content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# @dependency 001-main/002-createrepository.py SHA1 = "66f25ae79dcc5e200b136388771b5924a1b5ae56" with repository.workcopy() as work: REMOTE_URL = instance.repository_url("alice") work.run(["checkout", "-b", "008-branch", SHA1]) work.run(["rebase", "--force-rebase", "HEAD~5"]) work.run(["push", REMOTE_URL, "008-branch"]) sha1 = work.run(["rev-parse", "HEAD"]).strip() try: instance.unittest("api.branch", ["basic"], args=["--sha1=" + sha1, "--name=008-branch"]) finally: work.run(["push", REMOTE_URL, ":008-branch"])
sha1 = '66f25ae79dcc5e200b136388771b5924a1b5ae56' with repository.workcopy() as work: remote_url = instance.repository_url('alice') work.run(['checkout', '-b', '008-branch', SHA1]) work.run(['rebase', '--force-rebase', 'HEAD~5']) work.run(['push', REMOTE_URL, '008-branch']) sha1 = work.run(['rev-parse', 'HEAD']).strip() try: instance.unittest('api.branch', ['basic'], args=['--sha1=' + sha1, '--name=008-branch']) finally: work.run(['push', REMOTE_URL, ':008-branch'])
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: h5part.py # # Programmer: Gunther Weber # Date: January, 2009 # # Modifications: # Mark C. Miller, Wed Jan 21 09:36:13 PST 2009 # Took Gunther's original code and integrated it with test suite. # # ---------------------------------------------------------------------------- RequiredDatabasePlugin("H5Part") TurnOffAllAnnotations() OpenDatabase(data_path("h5part_test_data/sample.h5part"), 0) AddPlot("Pseudocolor", "GaussianField", 1, 0) DrawPlots() Test("h5part_01") ChangeActivePlotsVar("LinearField") View3DAtts = GetView3D() View3DAtts.viewNormal = (1.000000, 0.000000, 0.0000000) View3DAtts.focus = (31.5, 31.5, 31.5) View3DAtts.viewUp = (0.000000, 1.000000, 0.0000000) View3DAtts.viewAngle = 30 View3DAtts.parallelScale = 54.5596 View3DAtts.nearPlane = -109.119 View3DAtts.farPlane = 109.119 View3DAtts.imagePan = (0, 0) View3DAtts.imageZoom = 1 View3DAtts.perspective = 1 View3DAtts.eyeAngle = 2 View3DAtts.centerOfRotationSet = 0 View3DAtts.centerOfRotation = (31.5, 31.5, 31.5) SetView3D(View3DAtts) Test("h5part_02") DeleteActivePlots() AddPlot("Pseudocolor", "px", 1, 0) PseudocolorAtts = PseudocolorAttributes() PseudocolorAtts.pointType = PseudocolorAtts.Sphere PseudocolorAtts.pointSize = 1.5 SetPlotOptions(PseudocolorAtts) DrawPlots() Test("h5part_03") AddPlot("Pseudocolor", "LinearField", 1, 0) AddOperator("Slice", 0) SliceAtts = SliceAttributes() SliceAtts.originType = SliceAtts.Intercept SliceAtts.originIntercept = 30 SliceAtts.axisType = SliceAtts.XAxis SliceAtts.project2d = 0 SliceAtts.meshName = "particles" SetOperatorOptions(SliceAtts) DrawPlots() Test("h5part_04") Exit()
required_database_plugin('H5Part') turn_off_all_annotations() open_database(data_path('h5part_test_data/sample.h5part'), 0) add_plot('Pseudocolor', 'GaussianField', 1, 0) draw_plots() test('h5part_01') change_active_plots_var('LinearField') view3_d_atts = get_view3_d() View3DAtts.viewNormal = (1.0, 0.0, 0.0) View3DAtts.focus = (31.5, 31.5, 31.5) View3DAtts.viewUp = (0.0, 1.0, 0.0) View3DAtts.viewAngle = 30 View3DAtts.parallelScale = 54.5596 View3DAtts.nearPlane = -109.119 View3DAtts.farPlane = 109.119 View3DAtts.imagePan = (0, 0) View3DAtts.imageZoom = 1 View3DAtts.perspective = 1 View3DAtts.eyeAngle = 2 View3DAtts.centerOfRotationSet = 0 View3DAtts.centerOfRotation = (31.5, 31.5, 31.5) set_view3_d(View3DAtts) test('h5part_02') delete_active_plots() add_plot('Pseudocolor', 'px', 1, 0) pseudocolor_atts = pseudocolor_attributes() PseudocolorAtts.pointType = PseudocolorAtts.Sphere PseudocolorAtts.pointSize = 1.5 set_plot_options(PseudocolorAtts) draw_plots() test('h5part_03') add_plot('Pseudocolor', 'LinearField', 1, 0) add_operator('Slice', 0) slice_atts = slice_attributes() SliceAtts.originType = SliceAtts.Intercept SliceAtts.originIntercept = 30 SliceAtts.axisType = SliceAtts.XAxis SliceAtts.project2d = 0 SliceAtts.meshName = 'particles' set_operator_options(SliceAtts) draw_plots() test('h5part_04') exit()
def artist(): return "The Hardkiss" def genre(): return "Pop" def year(): return 2014 def restrictedContent(): return False def forGeneralAudiences(): return True
def artist(): return 'The Hardkiss' def genre(): return 'Pop' def year(): return 2014 def restricted_content(): return False def for_general_audiences(): return True
class TestErrors: """Errors""" pass
class Testerrors: """Errors""" pass
# -*- mode: python; -*- # Return the pathname of the calling package. # (This is used to recover the directory name to pass to cc -I<dir>, when # choosing from among alternative header files for different platforms.) def pkg_path_name(): return "./" + Label(REPOSITORY_NAME + "//" + PACKAGE_NAME + ":nsync").workspace_root + "/" + PACKAGE_NAME
def pkg_path_name(): return './' + label(REPOSITORY_NAME + '//' + PACKAGE_NAME + ':nsync').workspace_root + '/' + PACKAGE_NAME
# Play = 'play' # Pass = 'pass' Draw = 'draw' Discard = 'discard' TutorDeck = 'tutor_deck' TutorDiscard = 'tutor_discard' Create = 'create' Shuffle = 'shuffle' Mill = 'mill' Top = 'top' # Resolve = 'resolve' # Win = 'win' # Lose = 'lose' # Tie = 'tie' # # Build = 'build' # Inspire = 'inspire' # Nourish = 'nourish' # # Meow = 'meow' # Yell = 'yell' # BoneSnap = 'bone_snap' # Bird = 'bird' # Drown = 'drown' # Fire = 'fire' # Reset = 'reset' # Crowd = 'crowd' # Sarcophagus = 'sarcophagus'
draw = 'draw' discard = 'discard' tutor_deck = 'tutor_deck' tutor_discard = 'tutor_discard' create = 'create' shuffle = 'shuffle' mill = 'mill' top = 'top'
# -*- coding:utf8 -*- """ common settings FUTURE: read setting from a json file """ """ path configuration """ ICON_PATH = '../icons/' CACHE_PATH = '../cache/' DATA_PATH = '../data/' """ mode configuration """ DEBUG = True # 1 for debug PRODUCTION = False # 0 for Production Environment LOGFILE = CACHE_PATH + 'error.log' MODE = DEBUG """ theme configuration """ QSS_PATH = 'themes/default.qss' """ web_assets configuration """ HTML_PATH = 'web_assets/' PUBLIC_PATH = 'web_assets/public/' """ icon name """ PLAYLIST_FAVORITE = ICON_PATH + 'playlist_favorite.png' PLAYLIST_MINE = ICON_PATH + 'Format-Bullets-01-16.png' PLAYLIST_NORMAL = ICON_PATH + 'playlist_mine.png' WINDOW_ICON = ICON_PATH + 'FeelUOwn.png'
""" common settings FUTURE: read setting from a json file """ '\npath configuration\n' icon_path = '../icons/' cache_path = '../cache/' data_path = '../data/' '\nmode configuration\n' debug = True production = False logfile = CACHE_PATH + 'error.log' mode = DEBUG '\ntheme configuration\n' qss_path = 'themes/default.qss' '\nweb_assets configuration\n' html_path = 'web_assets/' public_path = 'web_assets/public/' '\nicon name\n' playlist_favorite = ICON_PATH + 'playlist_favorite.png' playlist_mine = ICON_PATH + 'Format-Bullets-01-16.png' playlist_normal = ICON_PATH + 'playlist_mine.png' window_icon = ICON_PATH + 'FeelUOwn.png'
#!/usr/bin/env python # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # # FreeType high-level python API - Copyright 2011-2012 Nicolas P. Rougier # Distributed under the terms of the new BSD license. # # ----------------------------------------------------------------------------- """ An enumeration used to specify character sets supported by charmaps. Used in the FT_Select_Charmap API function. FT_ENCODING_NONE The encoding value 0 is reserved. FT_ENCODING_UNICODE Corresponds to the Unicode character set. This value covers all versions of the Unicode repertoire, including ASCII and Latin-1. Most fonts include a Unicode charmap, but not all of them. For example, if you want to access Unicode value U+1F028 (and the font contains it), use value 0x1F028 as the input value for FT_Get_Char_Index. FT_ENCODING_MS_SYMBOL Corresponds to the Microsoft Symbol encoding, used to encode mathematical symbols in the 32..255 character code range. For more information, see 'http://www.ceviz.net/symbol.htm'. FT_ENCODING_SJIS Corresponds to Japanese SJIS encoding. More info at at 'http://langsupport.japanreference.com/encoding.shtml'. See note on multi-byte encodings below. FT_ENCODING_GB2312 Corresponds to an encoding system for Simplified Chinese as used used in mainland China. FT_ENCODING_BIG5 Corresponds to an encoding system for Traditional Chinese as used in Taiwan and Hong Kong. FT_ENCODING_WANSUNG Corresponds to the Korean encoding system known as Wansung. For more information see 'http://www.microsoft.com/typography/unicode/949.txt'. FT_ENCODING_JOHAB The Korean standard character set (KS C 5601-1992), which corresponds to MS Windows code page 1361. This character set includes all possible Hangeul character combinations. FT_ENCODING_ADOBE_LATIN_1 Corresponds to a Latin-1 encoding as defined in a Type 1 PostScript font. It is limited to 256 character codes. FT_ENCODING_ADOBE_STANDARD Corresponds to the Adobe Standard encoding, as found in Type 1, CFF, and OpenType/CFF fonts. It is limited to 256 character codes. FT_ENCODING_ADOBE_EXPERT Corresponds to the Adobe Expert encoding, as found in Type 1, CFF, and OpenType/CFF fonts. It is limited to 256 character codes. FT_ENCODING_ADOBE_CUSTOM Corresponds to a custom encoding, as found in Type 1, CFF, and OpenType/CFF fonts. It is limited to 256 character codes. FT_ENCODING_APPLE_ROMAN Corresponds to the 8-bit Apple roman encoding. Many TrueType and OpenType fonts contain a charmap for this encoding, since older versions of Mac OS are able to use it. FT_ENCODING_OLD_LATIN_2 This value is deprecated and was never used nor reported by FreeType. Don't use or test for it. """ def _FT_ENC_TAG(a, b, c, d): return (ord(a) << 24 | ord(b) << 16 | ord(c) << 8 | ord(d)) FT_ENCODINGS = {'FT_ENCODING_NONE': _FT_ENC_TAG('\0', '\0', '\0', '\0'), 'FT_ENCODING_MS_SYMBOL': _FT_ENC_TAG('s', 'y', 'm', 'b'), 'FT_ENCODING_UNICODE': _FT_ENC_TAG('u', 'n', 'i', 'c'), 'FT_ENCODING_SJIS': _FT_ENC_TAG('s', 'j', 'i', 's'), 'FT_ENCODING_GB2312': _FT_ENC_TAG('g', 'b', ' ', ' '), 'FT_ENCODING_BIG5': _FT_ENC_TAG('b', 'i', 'g', '5'), 'FT_ENCODING_WANSUNG': _FT_ENC_TAG('w', 'a', 'n', 's'), 'FT_ENCODING_JOHAB': _FT_ENC_TAG('j', 'o', 'h', 'a'), 'FT_ENCODING_ADOBE_STANDARD': _FT_ENC_TAG('A', 'D', 'O', 'B'), 'FT_ENCODING_ADOBE_EXPERT': _FT_ENC_TAG('A', 'D', 'B', 'E'), 'FT_ENCODING_ADOBE_CUSTOM': _FT_ENC_TAG('A', 'D', 'B', 'C'), 'FT_ENCODING_ADOBE_LATIN1': _FT_ENC_TAG('l', 'a', 't', '1'), 'FT_ENCODING_OLD_LATIN2': _FT_ENC_TAG('l', 'a', 't', '2'), 'FT_ENCODING_APPLE_ROMAN': _FT_ENC_TAG('a', 'r', 'm', 'n')} globals().update(FT_ENCODINGS)
""" An enumeration used to specify character sets supported by charmaps. Used in the FT_Select_Charmap API function. FT_ENCODING_NONE The encoding value 0 is reserved. FT_ENCODING_UNICODE Corresponds to the Unicode character set. This value covers all versions of the Unicode repertoire, including ASCII and Latin-1. Most fonts include a Unicode charmap, but not all of them. For example, if you want to access Unicode value U+1F028 (and the font contains it), use value 0x1F028 as the input value for FT_Get_Char_Index. FT_ENCODING_MS_SYMBOL Corresponds to the Microsoft Symbol encoding, used to encode mathematical symbols in the 32..255 character code range. For more information, see 'http://www.ceviz.net/symbol.htm'. FT_ENCODING_SJIS Corresponds to Japanese SJIS encoding. More info at at 'http://langsupport.japanreference.com/encoding.shtml'. See note on multi-byte encodings below. FT_ENCODING_GB2312 Corresponds to an encoding system for Simplified Chinese as used used in mainland China. FT_ENCODING_BIG5 Corresponds to an encoding system for Traditional Chinese as used in Taiwan and Hong Kong. FT_ENCODING_WANSUNG Corresponds to the Korean encoding system known as Wansung. For more information see 'http://www.microsoft.com/typography/unicode/949.txt'. FT_ENCODING_JOHAB The Korean standard character set (KS C 5601-1992), which corresponds to MS Windows code page 1361. This character set includes all possible Hangeul character combinations. FT_ENCODING_ADOBE_LATIN_1 Corresponds to a Latin-1 encoding as defined in a Type 1 PostScript font. It is limited to 256 character codes. FT_ENCODING_ADOBE_STANDARD Corresponds to the Adobe Standard encoding, as found in Type 1, CFF, and OpenType/CFF fonts. It is limited to 256 character codes. FT_ENCODING_ADOBE_EXPERT Corresponds to the Adobe Expert encoding, as found in Type 1, CFF, and OpenType/CFF fonts. It is limited to 256 character codes. FT_ENCODING_ADOBE_CUSTOM Corresponds to a custom encoding, as found in Type 1, CFF, and OpenType/CFF fonts. It is limited to 256 character codes. FT_ENCODING_APPLE_ROMAN Corresponds to the 8-bit Apple roman encoding. Many TrueType and OpenType fonts contain a charmap for this encoding, since older versions of Mac OS are able to use it. FT_ENCODING_OLD_LATIN_2 This value is deprecated and was never used nor reported by FreeType. Don't use or test for it. """ def _ft_enc_tag(a, b, c, d): return ord(a) << 24 | ord(b) << 16 | ord(c) << 8 | ord(d) ft_encodings = {'FT_ENCODING_NONE': _ft_enc_tag('\x00', '\x00', '\x00', '\x00'), 'FT_ENCODING_MS_SYMBOL': _ft_enc_tag('s', 'y', 'm', 'b'), 'FT_ENCODING_UNICODE': _ft_enc_tag('u', 'n', 'i', 'c'), 'FT_ENCODING_SJIS': _ft_enc_tag('s', 'j', 'i', 's'), 'FT_ENCODING_GB2312': _ft_enc_tag('g', 'b', ' ', ' '), 'FT_ENCODING_BIG5': _ft_enc_tag('b', 'i', 'g', '5'), 'FT_ENCODING_WANSUNG': _ft_enc_tag('w', 'a', 'n', 's'), 'FT_ENCODING_JOHAB': _ft_enc_tag('j', 'o', 'h', 'a'), 'FT_ENCODING_ADOBE_STANDARD': _ft_enc_tag('A', 'D', 'O', 'B'), 'FT_ENCODING_ADOBE_EXPERT': _ft_enc_tag('A', 'D', 'B', 'E'), 'FT_ENCODING_ADOBE_CUSTOM': _ft_enc_tag('A', 'D', 'B', 'C'), 'FT_ENCODING_ADOBE_LATIN1': _ft_enc_tag('l', 'a', 't', '1'), 'FT_ENCODING_OLD_LATIN2': _ft_enc_tag('l', 'a', 't', '2'), 'FT_ENCODING_APPLE_ROMAN': _ft_enc_tag('a', 'r', 'm', 'n')} globals().update(FT_ENCODINGS)
def Fibonacci_Tail(n, acc0= 0, acc1= 1): # Base-Case(s): F(0) = 0, F(1) = 1 if(n == 0): return acc0 if(n == 1): return acc1 # Recursion return Fibonacci_Tail(n-1, acc1, acc1+acc0) n = 0 while(n <= 10): get = Fibonacci_Tail(n) print(f"Fibonacci({n}) = {get}") n = n+1
def fibonacci__tail(n, acc0=0, acc1=1): if n == 0: return acc0 if n == 1: return acc1 return fibonacci__tail(n - 1, acc1, acc1 + acc0) n = 0 while n <= 10: get = fibonacci__tail(n) print(f'Fibonacci({n}) = {get}') n = n + 1
# # PySNMP MIB module Juniper-Notification-Log-CONF (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-Notification-Log-CONF # Produced by pysmi-0.3.4 at Mon Apr 29 19:52:48 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint") juniAgents, = mibBuilder.importSymbols("Juniper-Agents", "juniAgents") AgentCapabilities, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "ModuleCompliance", "NotificationGroup") Integer32, ModuleIdentity, Counter32, IpAddress, TimeTicks, iso, MibIdentifier, Counter64, Gauge32, Unsigned32, Bits, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "ModuleIdentity", "Counter32", "IpAddress", "TimeTicks", "iso", "MibIdentifier", "Counter64", "Gauge32", "Unsigned32", "Bits", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") juniNotificationLogAgent = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 56)) juniNotificationLogAgent.setRevisions(('2002-09-06 16:54', '2002-03-25 18:22',)) if mibBuilder.loadTexts: juniNotificationLogAgent.setLastUpdated('200209061654Z') if mibBuilder.loadTexts: juniNotificationLogAgent.setOrganization('Juniper Networks, Inc.') juniNotificationLogAgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 56, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniNotificationLogAgentV1 = juniNotificationLogAgentV1.setProductRelease('Version 1 of the Notification Log component of the JUNOSe SNMP agent.\n This version of the Notification Log component is supported in JUNOSe\n 4.1 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniNotificationLogAgentV1 = juniNotificationLogAgentV1.setStatus('current') mibBuilder.exportSymbols("Juniper-Notification-Log-CONF", PYSNMP_MODULE_ID=juniNotificationLogAgent, juniNotificationLogAgent=juniNotificationLogAgent, juniNotificationLogAgentV1=juniNotificationLogAgentV1)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, constraints_union, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint') (juni_agents,) = mibBuilder.importSymbols('Juniper-Agents', 'juniAgents') (agent_capabilities, module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'AgentCapabilities', 'ModuleCompliance', 'NotificationGroup') (integer32, module_identity, counter32, ip_address, time_ticks, iso, mib_identifier, counter64, gauge32, unsigned32, bits, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'ModuleIdentity', 'Counter32', 'IpAddress', 'TimeTicks', 'iso', 'MibIdentifier', 'Counter64', 'Gauge32', 'Unsigned32', 'Bits', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') juni_notification_log_agent = module_identity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 56)) juniNotificationLogAgent.setRevisions(('2002-09-06 16:54', '2002-03-25 18:22')) if mibBuilder.loadTexts: juniNotificationLogAgent.setLastUpdated('200209061654Z') if mibBuilder.loadTexts: juniNotificationLogAgent.setOrganization('Juniper Networks, Inc.') juni_notification_log_agent_v1 = agent_capabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 56, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juni_notification_log_agent_v1 = juniNotificationLogAgentV1.setProductRelease('Version 1 of the Notification Log component of the JUNOSe SNMP agent.\n This version of the Notification Log component is supported in JUNOSe\n 4.1 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juni_notification_log_agent_v1 = juniNotificationLogAgentV1.setStatus('current') mibBuilder.exportSymbols('Juniper-Notification-Log-CONF', PYSNMP_MODULE_ID=juniNotificationLogAgent, juniNotificationLogAgent=juniNotificationLogAgent, juniNotificationLogAgentV1=juniNotificationLogAgentV1)
# pylint: skip-file #- @A defines/binding ClassA #- @object ref vname("module.object", _, _, "pytd:__builtin__", _) #- ClassA.node/kind class class A(object): pass #- @B defines/binding ClassB #- @A ref ClassA #- ClassB.node/kind class class B(A): pass #- @Foo defines/binding ClassFoo #- @A ref ClassA #- @B ref ClassB #- ClassFoo.node/kind class class Foo(A, B): pass
class A(object): pass class B(A): pass class Foo(A, B): pass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 20 08:50:32 2019 @author: Giles """ ''' Question 1 Ask the user for two numbers between 1 and 100. Then count from the lower number to the higher number. Print the results to the screen. ''' ''' Question 2 Ask the user to input a string and then print it out to the screen in reverse order (use a for loop). ''' ''' Question 3 Ask the user for a number between 1 and 12 and then display a times table for that number. ''' ''' Question 4 Can you amend the solution to question 3 so that it just prints out all times tables between 1 and 12? (no need to ask user for input) ''' ''' Question 5 Ask the user to input a sequence of numbers. Then calculate the mean and print the result ''' ''' Question 6 Write code that will calculate 15 factorial. (factorial is product of positive ints up to a given number. e.g 5 factorial is 5x4x3x2x1) ''' ''' Question 7 Write code to calculate Fibonacci numbers. Create list containing first 20 Fibonacci numbers, (Fib numbers made by sum of preceeding two. Series starts 0 1 1 2 3 5 8 13 ....) ''' ''' Question 8 The previous question was the first to contain comments. Go back through the other questions in this file and add comments to the solutions. ''' ''' Question 9 ***** * **** * * * Can you draw this using python? (comment the solution code) ''' ''' Question 10 Write some code that will determine all odd and even numbers between 1 and 100. Put the odds in a list named odd and the evens in a list named even. '''
""" Created on Sun Oct 20 08:50:32 2019 @author: Giles """ '\nQuestion 1\nAsk the user for two numbers between 1 and 100. Then count from the\nlower number to the higher number. Print the results to the screen.\n' '\nQuestion 2\nAsk the user to input a string and then print it out to the screen in\nreverse order (use a for loop).\n' '\nQuestion 3\nAsk the user for a number between 1 and 12 and then display a times\ntable for that number.\n' '\nQuestion 4\nCan you amend the solution to question 3 so that it just prints out all\ntimes tables between 1 and 12? (no need to ask user for input)\n' '\nQuestion 5\nAsk the user to input a sequence of numbers. Then calculate the mean\nand print the result\n' '\nQuestion 6\nWrite code that will calculate 15 factorial. (factorial is product of\npositive ints up to a given number. e.g 5 factorial is 5x4x3x2x1)\n' '\nQuestion 7\nWrite code to calculate Fibonacci numbers. Create list containing\nfirst 20 Fibonacci numbers, (Fib numbers made by sum of preceeding\ntwo. Series starts 0 1 1 2 3 5 8 13 ....)\n' '\nQuestion 8\nThe previous question was the first to contain comments. Go back\nthrough the other questions in this file and add comments to the\nsolutions.\n' '\nQuestion 9\n\n *****\n *\n ****\n *\n *\n *\nCan you draw this using python? (comment the solution code)\n' '\nQuestion 10\nWrite some code that will determine all odd and even numbers\nbetween 1 and 100. Put the odds in a list named odd and the evens\nin a list named even.\n'
## A note on unneecssary complexity # We have gone through a few different standards on naming Julia's build artifacts. # The latest, as of this writing, is the `sf/consistent_distnames` branch on github, # and simplifies things relative to earlier versions. However, this buildbot needs # to be able to build/upload Julia versions of all reasonably recent versions. # `sf/consistent_distnames` should be merged before the 0.6 release, which means # that once the release _after_ 0.6 is out in the wild and 0.5 is put to rest, # we can safely remove anything that talks about non-`sf/consistent_distnames` # compatibility/workarounds. # Helper function to generate the necessary julia invocation to get metadata # about this build such as major/minor versions @util.renderer def make_julia_version_command(props_obj): command = [ "usr/bin/julia", "-e", "println(\"$(VERSION.major).$(VERSION.minor).$(VERSION.patch)\\n$(Base.GIT_VERSION_INFO.commit[1:10])\")" ] if is_windows(props_obj): command[0] += '.exe' return command # Parse out the full julia version generated by make_julia_version_command's command def parse_julia_version(return_code, stdout, stderr): lines = stdout.split('\n') return { "majmin": lines[0][:lines[0].rfind('.')], "version": lines[0].strip(), "shortcommit": lines[1].strip(), } def parse_git_log(return_code, stdout, stderr): lines = stdout.split('\n') return { "commitmessage": lines[0], "commitname": lines[1], "commitemail": lines[2], "authorname": lines[3], "authoremail": lines[4], } def gen_local_filename(props_obj): props = props_obj_to_dict(props_obj) # Get the output of the `make print-JULIA_BINARYDIST_FILENAME` step artifact = "{artifact_filename}".format(**props).strip() # First, see if we got a JULIA_BINARYDIST_FILENAME output if artifact[:26] == "JULIA_BINARYDIST_FILENAME=" and len(artifact) > 26: return artifact[26:] + ".{os_pkg_ext}".format(**props) else: # If not, use non-sf/consistent_distnames naming if is_mac(props_obj): return "contrib/mac/app/Julia-{version}-{shortcommit}.{os_pkg_ext}".format(**props) elif is_windows(props_obj): return "julia-{version}-{tar_arch}.{os_pkg_ext}".format(**props) elif is_freebsd(props_obj): return "julia-{shortcommit}-FreeBSD-{tar_arch}.{os_pkg_ext}".format(**props) else: # We made bad decisions in the past if props['tar_arch'] == "armv7l": return "julia-{shortcommit}-Linux-arm.{os_pkg_ext}".format(**props) return "julia-{shortcommit}-Linux-{tar_arch}.{os_pkg_ext}".format(**props) def gen_upload_filename(props_obj): props = props_obj_to_dict(props_obj) # We don't like "winnt" at the end of files, we use just "win" instead. props["os_name_file"] = props["os_name"] if props["os_name_file"] == "winnt": props["os_name_file"] = "win" return "julia-{shortcommit}-{os_name_file}{bits}.{os_pkg_ext}".format(**props) def gen_upload_path(props_obj, namespace=None): up_arch = props_obj.getProperty("up_arch") majmin = props_obj.getProperty("majmin") upload_filename = props_obj.getProperty("upload_filename") os = get_os_name(props_obj) if namespace is None: return "julialangnightlies/bin/%s/%s/%s/%s"%(os, up_arch, majmin, upload_filename) else: return "julialangnightlies/%s/bin/%s/%s/%s/%s"%(namespace, os, up_arch, majmin, upload_filename) def gen_latest_upload_path(props_obj, namespace=None): up_arch = props_obj.getProperty("up_arch") upload_filename = props_obj.getProperty("upload_filename") if upload_filename[:6] == "julia-": split_name = upload_filename.split("-") upload_filename = "julia-latest-%s"%(split_name[2]) os = get_os_name(props_obj) if namespace is None: return "julialangnightlies/bin/%s/%s/%s"%(os, up_arch, upload_filename) else: return "julialangnightlies/%s/bin/%s/%s/%s"%(namespace, os, up_arch, upload_filename) def gen_download_url(props_obj, namespace=None): base = 'https://s3.amazonaws.com' return '%s/%s'%(base, gen_upload_path(props_obj, namespace=namespace)) def gen_latest_download_url(props_obj): base = 'https://s3.amazonaws.com' return '%s/%s'%(base, gen_latest_upload_path(props_obj)) # This is a weird buildbot hack where we really want to parse the output of our # make command, but we also need access to our properties, which we can't get # from within an `extract_fn`. So we save the output from a previous # SetPropertyFromCommand invocation, then invoke a new command through this # @util.renderer nonsense. This function is supposed to return a new command # to be executed, but it has full access to all our properties, so we do all our # artifact filename parsing/munging here, then return ["true"] as the step # to be executed. @util.renderer def munge_artifact_filename(props_obj): # Generate our local and upload filenames local_filename = gen_local_filename(props_obj) upload_filename = gen_upload_filename(props_obj) props_obj.setProperty("local_filename", local_filename, "munge_artifact_filename") props_obj.setProperty("upload_filename", upload_filename, "munge_artifact_filename") return ["true"] @util.renderer def render_upload_command(props_obj): upload_path = gen_upload_path(props_obj, namespace="pretesting") upload_filename = props_obj.getProperty("upload_filename") return ["/bin/sh", "-c", "aws s3 cp --acl public-read /tmp/julia_package/%s s3://%s"%(upload_filename, upload_path)] @util.renderer def render_promotion_command(props_obj): src_path = gen_upload_path(props_obj, namespace="pretesting") dst_path = gen_upload_path(props_obj) return ["/bin/sh", "-c", "aws s3 cp --acl public-read s3://%s s3://%s"%(src_path, dst_path)] @util.renderer def render_latest_promotion_command(props_obj): src_path = gen_upload_path(props_obj, namespace="pretesting") dst_path = gen_latest_upload_path(props_obj) return ["/bin/sh", "-c", "aws s3 cp --acl public-read s3://%s s3://%s"%(src_path, dst_path)] @util.renderer def render_cleanup_pretesting_command(props_obj): del_path = gen_upload_path(props_obj, namespace="pretesting") return ["/bin/sh", "-c", "aws s3 rm s3://%s"%(del_path)] @util.renderer def render_download_url(props_obj): return gen_download_url(props_obj) @util.renderer def render_pretesting_download_url(props_obj): return gen_download_url(props_obj, namespace="pretesting") @util.renderer def render_make_app(props_obj): props = props_obj_to_dict(props_obj) new_way = "make {flags} app".format(**props) old_way = "make {flags} -C contrib/mac/app && mv contrib/mac/app/*.dmg {local_filename}".format(**props) # We emit a shell command that attempts to run `make app` (which is the nice # `sf/consistent_distnames` shortcut), and if that fails, it runs the steps # manually, which boil down to `make -C contrib/mac/app` and moving the # result to the top-level, where we can find it. We can remove this once # 0.6 is no longer being built. return [ "/bin/sh", "-c", "~/unlock_keychain.sh && (%s || (%s))"%(new_way, old_way) ] def build_download_julia_cmd(props_obj): download_url = props_obj.getProperty("download_url") # Build commands to download/install julia if is_mac(props_obj): # Download the .dmg cmd = "curl -L '%s' -o julia-installer.dmg && "%(download_url) # Mount it cmd += "hdiutil mount julia-installer.dmg && " # copy its `julia` folder contents here. cmd += "cp -Ra /Volumes/Julia-*/Julia-*.app/Contents/Resources/julia/* . && " # Unmount any and all Julia disk images cmd += "for j in /Volumes/Julia-*; do hdiutil unmount \"$j\"; done && " # Delete the .dmg cmd += "rm -f julia-installer.dmg" elif is_windows(props_obj): # Download the .exe cmd = "curl -L '%s' -o julia-installer.exe && "%(download_url) # Make it executable cmd += "chmod +x julia-installer.exe && " # Extract it into the current directory cmd += "./julia-installer.exe /S /D=$(cygpath -w $(pwd)) && " # Remove the .exe cmd += "rm -f julia-installer.exe" else: # Oh linux. Your simplicity always gets me cmd = "curl -L '%s' | tar --strip-components=1 -zxf -"%(download_url) return ["/bin/sh", "-c", cmd] @util.renderer def download_julia(props_obj, namespace=None): # If we already have an "url", use that, otherwise try to generate it: if not props_obj.hasProperty('download_url'): # Calculate upload_filename, add to properties, then get download url upload_filename = gen_upload_filename(props_obj) props_obj.setProperty("upload_filename", upload_filename, "download_julia") download_url = gen_download_url(props_obj) props_obj.setProperty("download_url", download_url, "download_julia") return build_download_julia_cmd(props_obj) def download_latest_julia(props_obj): # Fake `gen_upload_filename()` into giving us something like # `julia-latest-linux64.tar.gz` instead of a true shortcommit props_obj.setProperty("shortcommit", "latest", "download_latest_julia") upload_filename = gen_upload_filename(props_obj) props_obj.setProperty("upload_filename", upload_filename, "download_latest_julia") download_url = gen_latest_download_url(props_obj) props_obj.setProperty("download_url", download_url, "download_latest_julia") return build_download_julia_cmd(props_obj) @util.renderer def render_tester_name(props_obj): props = props_obj_to_dict(props_obj) return "Julia %s Testing"%(props['buildername'].replace('package_', ''))
@util.renderer def make_julia_version_command(props_obj): command = ['usr/bin/julia', '-e', 'println("$(VERSION.major).$(VERSION.minor).$(VERSION.patch)\\n$(Base.GIT_VERSION_INFO.commit[1:10])")'] if is_windows(props_obj): command[0] += '.exe' return command def parse_julia_version(return_code, stdout, stderr): lines = stdout.split('\n') return {'majmin': lines[0][:lines[0].rfind('.')], 'version': lines[0].strip(), 'shortcommit': lines[1].strip()} def parse_git_log(return_code, stdout, stderr): lines = stdout.split('\n') return {'commitmessage': lines[0], 'commitname': lines[1], 'commitemail': lines[2], 'authorname': lines[3], 'authoremail': lines[4]} def gen_local_filename(props_obj): props = props_obj_to_dict(props_obj) artifact = '{artifact_filename}'.format(**props).strip() if artifact[:26] == 'JULIA_BINARYDIST_FILENAME=' and len(artifact) > 26: return artifact[26:] + '.{os_pkg_ext}'.format(**props) elif is_mac(props_obj): return 'contrib/mac/app/Julia-{version}-{shortcommit}.{os_pkg_ext}'.format(**props) elif is_windows(props_obj): return 'julia-{version}-{tar_arch}.{os_pkg_ext}'.format(**props) elif is_freebsd(props_obj): return 'julia-{shortcommit}-FreeBSD-{tar_arch}.{os_pkg_ext}'.format(**props) else: if props['tar_arch'] == 'armv7l': return 'julia-{shortcommit}-Linux-arm.{os_pkg_ext}'.format(**props) return 'julia-{shortcommit}-Linux-{tar_arch}.{os_pkg_ext}'.format(**props) def gen_upload_filename(props_obj): props = props_obj_to_dict(props_obj) props['os_name_file'] = props['os_name'] if props['os_name_file'] == 'winnt': props['os_name_file'] = 'win' return 'julia-{shortcommit}-{os_name_file}{bits}.{os_pkg_ext}'.format(**props) def gen_upload_path(props_obj, namespace=None): up_arch = props_obj.getProperty('up_arch') majmin = props_obj.getProperty('majmin') upload_filename = props_obj.getProperty('upload_filename') os = get_os_name(props_obj) if namespace is None: return 'julialangnightlies/bin/%s/%s/%s/%s' % (os, up_arch, majmin, upload_filename) else: return 'julialangnightlies/%s/bin/%s/%s/%s/%s' % (namespace, os, up_arch, majmin, upload_filename) def gen_latest_upload_path(props_obj, namespace=None): up_arch = props_obj.getProperty('up_arch') upload_filename = props_obj.getProperty('upload_filename') if upload_filename[:6] == 'julia-': split_name = upload_filename.split('-') upload_filename = 'julia-latest-%s' % split_name[2] os = get_os_name(props_obj) if namespace is None: return 'julialangnightlies/bin/%s/%s/%s' % (os, up_arch, upload_filename) else: return 'julialangnightlies/%s/bin/%s/%s/%s' % (namespace, os, up_arch, upload_filename) def gen_download_url(props_obj, namespace=None): base = 'https://s3.amazonaws.com' return '%s/%s' % (base, gen_upload_path(props_obj, namespace=namespace)) def gen_latest_download_url(props_obj): base = 'https://s3.amazonaws.com' return '%s/%s' % (base, gen_latest_upload_path(props_obj)) @util.renderer def munge_artifact_filename(props_obj): local_filename = gen_local_filename(props_obj) upload_filename = gen_upload_filename(props_obj) props_obj.setProperty('local_filename', local_filename, 'munge_artifact_filename') props_obj.setProperty('upload_filename', upload_filename, 'munge_artifact_filename') return ['true'] @util.renderer def render_upload_command(props_obj): upload_path = gen_upload_path(props_obj, namespace='pretesting') upload_filename = props_obj.getProperty('upload_filename') return ['/bin/sh', '-c', 'aws s3 cp --acl public-read /tmp/julia_package/%s s3://%s' % (upload_filename, upload_path)] @util.renderer def render_promotion_command(props_obj): src_path = gen_upload_path(props_obj, namespace='pretesting') dst_path = gen_upload_path(props_obj) return ['/bin/sh', '-c', 'aws s3 cp --acl public-read s3://%s s3://%s' % (src_path, dst_path)] @util.renderer def render_latest_promotion_command(props_obj): src_path = gen_upload_path(props_obj, namespace='pretesting') dst_path = gen_latest_upload_path(props_obj) return ['/bin/sh', '-c', 'aws s3 cp --acl public-read s3://%s s3://%s' % (src_path, dst_path)] @util.renderer def render_cleanup_pretesting_command(props_obj): del_path = gen_upload_path(props_obj, namespace='pretesting') return ['/bin/sh', '-c', 'aws s3 rm s3://%s' % del_path] @util.renderer def render_download_url(props_obj): return gen_download_url(props_obj) @util.renderer def render_pretesting_download_url(props_obj): return gen_download_url(props_obj, namespace='pretesting') @util.renderer def render_make_app(props_obj): props = props_obj_to_dict(props_obj) new_way = 'make {flags} app'.format(**props) old_way = 'make {flags} -C contrib/mac/app && mv contrib/mac/app/*.dmg {local_filename}'.format(**props) return ['/bin/sh', '-c', '~/unlock_keychain.sh && (%s || (%s))' % (new_way, old_way)] def build_download_julia_cmd(props_obj): download_url = props_obj.getProperty('download_url') if is_mac(props_obj): cmd = "curl -L '%s' -o julia-installer.dmg && " % download_url cmd += 'hdiutil mount julia-installer.dmg && ' cmd += 'cp -Ra /Volumes/Julia-*/Julia-*.app/Contents/Resources/julia/* . && ' cmd += 'for j in /Volumes/Julia-*; do hdiutil unmount "$j"; done && ' cmd += 'rm -f julia-installer.dmg' elif is_windows(props_obj): cmd = "curl -L '%s' -o julia-installer.exe && " % download_url cmd += 'chmod +x julia-installer.exe && ' cmd += './julia-installer.exe /S /D=$(cygpath -w $(pwd)) && ' cmd += 'rm -f julia-installer.exe' else: cmd = "curl -L '%s' | tar --strip-components=1 -zxf -" % download_url return ['/bin/sh', '-c', cmd] @util.renderer def download_julia(props_obj, namespace=None): if not props_obj.hasProperty('download_url'): upload_filename = gen_upload_filename(props_obj) props_obj.setProperty('upload_filename', upload_filename, 'download_julia') download_url = gen_download_url(props_obj) props_obj.setProperty('download_url', download_url, 'download_julia') return build_download_julia_cmd(props_obj) def download_latest_julia(props_obj): props_obj.setProperty('shortcommit', 'latest', 'download_latest_julia') upload_filename = gen_upload_filename(props_obj) props_obj.setProperty('upload_filename', upload_filename, 'download_latest_julia') download_url = gen_latest_download_url(props_obj) props_obj.setProperty('download_url', download_url, 'download_latest_julia') return build_download_julia_cmd(props_obj) @util.renderer def render_tester_name(props_obj): props = props_obj_to_dict(props_obj) return 'Julia %s Testing' % props['buildername'].replace('package_', '')
""" Creating new user after checking all the input. the user will be added into the remote data source and input the login details into the login window """ def makeUser(self,name,pw,pw2,email): """Checking input is valid and not already exist in the current database before creating new user instance Args: name (string): username taken from user input, need to be more than 2 characters and less than 20 characters pw (string): password taken from user input, need to be more than 8 character and less than 20 characters pw2 (string): confirm password, need to be identical with password input email (string): email from user, need to have @ and valid email name """ self.destroy() pass
""" Creating new user after checking all the input. the user will be added into the remote data source and input the login details into the login window """ def make_user(self, name, pw, pw2, email): """Checking input is valid and not already exist in the current database before creating new user instance Args: name (string): username taken from user input, need to be more than 2 characters and less than 20 characters pw (string): password taken from user input, need to be more than 8 character and less than 20 characters pw2 (string): confirm password, need to be identical with password input email (string): email from user, need to have @ and valid email name """ self.destroy() pass
# -*- coding: utf-8 -*- """ 958. Check Completeness of a Binary Tree Given a binary tree, determine if it is a complete binary tree. Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Note: The tree will have between 1 and 100 nodes. """ # 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 isCompleteTree(self, root): node_list = [root] pre_lvl_full = True while node_list: next_node_list = [] first_node = node_list[0] if first_node is None: for node in node_list[1:]: if node is not None: return False else: next_node_list.append(first_node.left) next_node_list.append(first_node.right) if not pre_lvl_full: return False pre_lvl_full = True for ind, node in enumerate(node_list[1:], start=1): if node is not None: if node_list[ind - 1] is None: return False else: next_node_list.append(node.left) next_node_list.append(node.right) else: pre_lvl_full = False node_list = next_node_list return True
""" 958. Check Completeness of a Binary Tree Given a binary tree, determine if it is a complete binary tree. Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Note: The tree will have between 1 and 100 nodes. """ class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def is_complete_tree(self, root): node_list = [root] pre_lvl_full = True while node_list: next_node_list = [] first_node = node_list[0] if first_node is None: for node in node_list[1:]: if node is not None: return False else: next_node_list.append(first_node.left) next_node_list.append(first_node.right) if not pre_lvl_full: return False pre_lvl_full = True for (ind, node) in enumerate(node_list[1:], start=1): if node is not None: if node_list[ind - 1] is None: return False else: next_node_list.append(node.left) next_node_list.append(node.right) else: pre_lvl_full = False node_list = next_node_list return True
class Scope: """ Class to define the Scope object to be used during compilation of the whole program. """ def __init__(self, line_number, instructions): """ Constructor for the Scope object. :param line_number: The line the function is defined at :param instructions: The program to be compiled """ self._type = None self.__line_number = line_number self._instructions = instructions self.__length = len(self._instructions) - 2 # -2 To remove opening and closing line def get_type(self): """ Getter for the type of the scope. :return: The type of the scope as a TokenType """ return self._type def get_line_number(self): """ Getter for the line number the loop is declared at. :return: The line number the scope is declared at as an integer """ return self.__line_number def get_instructions(self): """ Getter for the list of instructions the scope performs. :return: The list of instructions as a 2D list """ return self._instructions def get_length(self): """ Getter for the length of the scope. :return: The length of the function as an integer """ return self.__length if __name__ == '__main__': print('Please save your instructions and run run.py') input('Press enter to close window . . . ')
class Scope: """ Class to define the Scope object to be used during compilation of the whole program. """ def __init__(self, line_number, instructions): """ Constructor for the Scope object. :param line_number: The line the function is defined at :param instructions: The program to be compiled """ self._type = None self.__line_number = line_number self._instructions = instructions self.__length = len(self._instructions) - 2 def get_type(self): """ Getter for the type of the scope. :return: The type of the scope as a TokenType """ return self._type def get_line_number(self): """ Getter for the line number the loop is declared at. :return: The line number the scope is declared at as an integer """ return self.__line_number def get_instructions(self): """ Getter for the list of instructions the scope performs. :return: The list of instructions as a 2D list """ return self._instructions def get_length(self): """ Getter for the length of the scope. :return: The length of the function as an integer """ return self.__length if __name__ == '__main__': print('Please save your instructions and run run.py') input('Press enter to close window . . . ')
try: num = float(input("Enter a number : ")) def real_nums(x): if x > 0: return "The number is POSITIVE" elif x == 0: return "The number is ZERO" elif x < 0: return "The number is NEGATIVE" else: return "Enter a valid number!" def even_or_odd(x): if x%2 == 0: if x == 0: return "Zero cannot be either positive or negative." else: return "The number is EVEN." elif x%2 != 0: return "The number is ODD." else: return "Enter a valid number!" x,y = real_nums(num), even_or_odd(num) print(x,y,sep=' & ') except: print("Enter a valid number!")
try: num = float(input('Enter a number : ')) def real_nums(x): if x > 0: return 'The number is POSITIVE' elif x == 0: return 'The number is ZERO' elif x < 0: return 'The number is NEGATIVE' else: return 'Enter a valid number!' def even_or_odd(x): if x % 2 == 0: if x == 0: return 'Zero cannot be either positive or negative.' else: return 'The number is EVEN.' elif x % 2 != 0: return 'The number is ODD.' else: return 'Enter a valid number!' (x, y) = (real_nums(num), even_or_odd(num)) print(x, y, sep=' & ') except: print('Enter a valid number!')
""" month picker simple case implementation in python """ class Case(object): """ class to return a month """ def what_month(self, num): """ returns the month Arguments: num {int} -- month Returns: string -- month """ method_name = "month_{}".format(num) method = getattr(self, method_name, lambda: "Invalid Input") return method() @staticmethod def month_1(): ''' jan ''' return "January" @staticmethod def month_2(): ''' feb ''' return "February" @staticmethod def month_3(): ''' mar ''' return "March" @staticmethod def month_4(): ''' apr ''' return "April" @staticmethod def month_5(): ''' may ''' return "May" @staticmethod def month_6(): ''' jun ''' return "June" @staticmethod def month_7(): ''' jul ''' return "July" @staticmethod def month_8(): ''' aug ''' return "August" @staticmethod def month_9(): ''' sep ''' return "Setember" @staticmethod def month_10(): ''' oct ''' return "October" @staticmethod def month_11(): ''' nov ''' return "November" @staticmethod def month_12(): ''' dec ''' return "December" if __name__ == "__main__": MY_MONTH = Case() print(MY_MONTH.what_month(input("Please Enter the Month Number: ")))
""" month picker simple case implementation in python """ class Case(object): """ class to return a month """ def what_month(self, num): """ returns the month Arguments: num {int} -- month Returns: string -- month """ method_name = 'month_{}'.format(num) method = getattr(self, method_name, lambda : 'Invalid Input') return method() @staticmethod def month_1(): """ jan """ return 'January' @staticmethod def month_2(): """ feb """ return 'February' @staticmethod def month_3(): """ mar """ return 'March' @staticmethod def month_4(): """ apr """ return 'April' @staticmethod def month_5(): """ may """ return 'May' @staticmethod def month_6(): """ jun """ return 'June' @staticmethod def month_7(): """ jul """ return 'July' @staticmethod def month_8(): """ aug """ return 'August' @staticmethod def month_9(): """ sep """ return 'Setember' @staticmethod def month_10(): """ oct """ return 'October' @staticmethod def month_11(): """ nov """ return 'November' @staticmethod def month_12(): """ dec """ return 'December' if __name__ == '__main__': my_month = case() print(MY_MONTH.what_month(input('Please Enter the Month Number: ')))
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class BoolStr(object): """A custom boolean/string hybrid type for resource.props. Translates a given value to the desired type. """ def __init__(self, given): """A boolean parser. Interprets the given value as a boolean, ignoring whitespace and case. A TypeError is raised when interpreted as neither True nor False. """ expr = str(given).lower() if 'true' == expr: self.parsed = True elif 'false' == expr: self.parsed = False else: msg = 'Invalid as boolean: %s' % given raise ValueError(msg) def __bool__(self): return self.parsed __nonzero__ = __bool__ def __str__(self): return str(self.parsed)
class Boolstr(object): """A custom boolean/string hybrid type for resource.props. Translates a given value to the desired type. """ def __init__(self, given): """A boolean parser. Interprets the given value as a boolean, ignoring whitespace and case. A TypeError is raised when interpreted as neither True nor False. """ expr = str(given).lower() if 'true' == expr: self.parsed = True elif 'false' == expr: self.parsed = False else: msg = 'Invalid as boolean: %s' % given raise value_error(msg) def __bool__(self): return self.parsed __nonzero__ = __bool__ def __str__(self): return str(self.parsed)
""" Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. You may return any answer array that satisfies this condition. Example: Input: [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Note: 1. 2 <= A.length <= 20000 2. A.length % 2 == 0 3. 0 <= A[i] <= 1000 """ #Difficulty: Easy #61 / 61 test cases passed. #Runtime: 212 ms #Memory Usage: 16.4 MB #Runtime: 212 ms, faster than 92.97% of Python3 online submissions for Sort Array By Parity II. #Memory Usage: 16.4 MB, less than 39.20% of Python3 online submissions for Sort Array By Parity II. class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: even = 0 odd = 1 l = len(A) B = [None] * l for i in range(l): if A[i] % 2: B[odd] = A[i] odd += 2 else: B[even] = A[i] even += 2 return B
""" Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. You may return any answer array that satisfies this condition. Example: Input: [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Note: 1. 2 <= A.length <= 20000 2. A.length % 2 == 0 3. 0 <= A[i] <= 1000 """ class Solution: def sort_array_by_parity_ii(self, A: List[int]) -> List[int]: even = 0 odd = 1 l = len(A) b = [None] * l for i in range(l): if A[i] % 2: B[odd] = A[i] odd += 2 else: B[even] = A[i] even += 2 return B
#Finding number of hansu which is under n def number_of_hansu(n): out = 0 digit_difference = 0 for i in range(1, n + 1): #Number under 100 is always hansu if i < 100: out += 1 else: #First digit difference digit_difference = digits(i)[1] - digits(i)[0] for j in range(len(digits(i)) - 1): #If digits are different if digits(i)[j + 1] - digits(i)[j] != digit_difference: break #If the number is hansu if j == len(digits(i)) - 2: out += 1 #Returning value return out #Finding digits of n def digits(n): digit = [] while n > 0: digit += [n % 10] n = n // 10 digit.reverse() return digit #Input part N = int(input()) answer = 0 #Applying algorithm answer = number_of_hansu(N) #Output part print(answer)
def number_of_hansu(n): out = 0 digit_difference = 0 for i in range(1, n + 1): if i < 100: out += 1 else: digit_difference = digits(i)[1] - digits(i)[0] for j in range(len(digits(i)) - 1): if digits(i)[j + 1] - digits(i)[j] != digit_difference: break if j == len(digits(i)) - 2: out += 1 return out def digits(n): digit = [] while n > 0: digit += [n % 10] n = n // 10 digit.reverse() return digit n = int(input()) answer = 0 answer = number_of_hansu(N) print(answer)
criteria = [ { 'name': 'Price', 'inc': "Two thousand dollars is a lot of Ramen.", 'just': "A high price tag will be a deal breaker no matter what." }, { 'name': 'User Rating', 'inc': "User ratings indicate reliability and general satisfaction of previous customers.", 'just': "This is the only way to determine quality without testing each laptop." }, { 'name': 'Weight', 'inc': "The last thing you want is to carry a dumbbell around campus.", 'just': "The cold, hard truth is you will spend more time carrying your laptop than using it." }, { 'name': 'Screen Size', 'inc': "You can Facebook and program at the same time!", 'just': "Being able to see multiple objects makes you far more effective." }, { 'name': 'Power', 'inc': "Some of your programs are computationally intensive with high memory usage.", 'just': "It is nice, but for the most part it doesn't make a difference in your life." }, { 'name': 'Storage', 'inc': "In some programs you will produce lots of data and waiting for it to save is boring. ", 'just': "Load and save time is relatively insignificant." }, { 'name': 'Battery Life', 'inc': "A laptop is useless if you can't use it on the go. But there are plenty of outlets on campus.", 'just': "The only time an outlet might not be available is during a lecture." } ] ranking = [ { 'name' : "HP Envy 15t Quad Edition", 'rank': 71.6 }, { 'name' : "Dell Inspiron i15RV-1435BLK", 'rank': 69.6 }, { 'name' : "Toshiba Satellite C55-A5245", 'rank': 69.1 }, { 'name' : "Lenovo IdeaPad U430", 'rank': 64.7 }, { 'name' : "MacBook Air 13\"", 'rank': 63.5 }, { 'name' : "MacBook Pro 13\" with Retina Display", 'rank': 62.9 }, { 'name' : "ASUS ROG 6750JM-DS71", 'rank': 57.7 } ] algorithm = [ { 'name': 'Price', 'weight': 30, 'formula': "img/price_formula.gif", 'assumption': "$2000 is likely the most a student will be willing to pay for a laptop." }, { 'name': 'User Rating', 'weight': 25, 'formula': "img/user_rating_formula.gif", 'assumption': "User Ratings are from 1 to 5." }, { 'name': 'Weight', 'weight': 20, 'formula': "img/weight_formula.gif", 'assumption': "10 pounds is the most a laptop should weigh to be reasonable for a student." }, { 'name': 'Screen Size', 'weight': 10, 'formula': "img/screen_size_formula.gif", 'assumption': "The largest reasonable laptop screen size is 17 inches." }, { 'name': 'Power', 'weight':7, 'formula': "img/power_formula.gif", 'assumption': "Quad core, 3 GHz, and 8Gb of RAM are reasonable limits for a student." }, { 'name': 'Storage', 'weight': 5, 'formula': "img/storage_formula.gif", 'assumption': "An SSD is roughly equivalent to a 10,000 rpm optical disk and 512 Gb is a reasonable upper bound on hard drive space." }, { 'name': 'Battery Life', 'weight': 3, 'formula': "img/battery_life_formula.gif", 'assumption': "15 hours is the largest reasonable battery life of a laptop." } ] breakdown = { 'row_headings': ["Price", "User Rating", "Weight", "Screen Size", "Power", "Storage", "Battery Life"], 'col_headings': ["HP Envy 15t Quad", "Dell Inspiron i15RV", "Toshiba Satellite C55", "Lenovo IdeaPad U430", "MacBook Air 13\"", "MacBook Pro 13\"", "ASUS ROG 6750JM"], 'rows': [ [19.5, 20.5, 8.8, 9.2, 5.6, 6.2, 1.9], [24.3, 20.0, 10.1, 9.2, 1.5, 3.8, 0.8], [23.7, 20.5, 9.2, 9.2, 1.9, 3.8, 0.8], [19.5, 19.0, 11.6, 8.2, 1.5, 3.8, 1.1], [15.8, 20.5, 14.1, 6.5, 1.2, 3.1, 2.4], [ 9.0, 23.5, 13.1, 7.8, 4.0, 3.8, 1.8], [10.5, 21.5, 0.2, 10.2, 8.4, 6.2, 0.7] ] } proscons = [ { 'name':'HP Envy 15t Quad Edition', 'url': 'http://ssl-product-images.www8-hp.com/digmedialib/prodimg/lowres/c03698047.png', 'pro': '15.6 inch screen\nSolid power\nFour Beats audio speakers ', 'con': 'Heavy\nNo SSD' }, { 'name':'Dell Inspiron i15RV-1435BLK', 'url': 'http://ecx.images-amazon.com/images/I/71qmqgZmp7L._SL1500_.jpg', 'pro': 'Inexpensive\n15.6 Inch Screen', 'con': 'Poor battery life\nNot very powerful\nNo SSD' }, { 'name':'Toshiba Satellite C55-A5245', 'url': 'https://www.laptopninja.org/wp-content/uploads/2014/03/Toshiba-Satellite-C55-A5245.jpg', 'pro': 'Inexpensive\n15.6 Inch Screen', 'con': 'Fairly heavy\nPoor battery life\nNo SSD' }, { 'name':'Lenovo IdeaPad U430', 'url': 'http://media.engadget.com/img/products/488/ah7w/ah7w-800.jpg', 'pro': 'Powerful\nTouch screen', 'con': 'No SSD' }, { 'name':'MacBook Air 13"', 'url': 'http://images.apple.com/macbook-air/images/techspecs_headline_13inch.jpg', 'pro': 'Weight\nSuper thin\nHas SSD', 'con': 'Expensive\nScreen Size' }, { 'name':'MacBook Pro 13" with Retina Display', 'url': 'http://cdn0.sbnation.com/products/large/7406/retina13.jpg?1382468345', 'pro': 'Retina display\nPowerful\nThin & light\nHas SSD', 'con': 'Expensive\nSmall Screen' }, { 'name':'ASUS ROG 6750JM-DS71', 'url': 'http://ecx.images-amazon.com/images/I/41eUTqGvDpL._SL160_SL150_.jpg', 'pro': 'Very powerful\n1 TB hard drive\nGaming', 'con': 'Extremely heavy\nVery poor battery life\nNo SSD' } ] specs = [ # Price Rating Weight ScreenSize Power RAM Hard Drive BL ["$702", 4.1, "5.6 lbs", "15.6\"", "4 cores 2.4 clock with 8Gb of RAM", "5400 rpm 1100 Gb", "9.5 hrs"], ["$379", 4.0, "4.9 lbs", "15.6\"", "2 cores 1.8 clock with 4Gb of RAM", "5400 rpm 500 Gb", "4 hrs"], ["$419", 4.1, "5.4 lbs", "15.6\"", "2 cores 2.3 clock with 4Gb of RAM", "5400 rpm 500 Gb", "4 hrs"], ["$699", 3.8, "4.2 lbs", "14.0\"", "2 cores 1.8 clock with 4Gb of RAM", "5400 rpm 500 Gb", "5.5 hrs"], ["$949", 4.1, "2.9 lbs", "11.0\"", "2 cores 1.4 clock with 4Gb of RAM", "10000 rpm 128 Gb", "12 hrs"], ["$1399", 4.7, "3.4 lbs", "13.3\"", "2 cores 2.4 clock with 8Gb of RAM", "10000 rpm 256 Gb", "9 hrs"], ["$1299", 4.3, "9.9 lbs", "17.3\"", "4 cores 2.4 clock with 12Gb of RAM", "5400 rpm 1000 Gb", "3.5 hrs"] ]
criteria = [{'name': 'Price', 'inc': 'Two thousand dollars is a lot of Ramen.', 'just': 'A high price tag will be a deal breaker no matter what.'}, {'name': 'User Rating', 'inc': 'User ratings indicate reliability and general satisfaction of previous customers.', 'just': 'This is the only way to determine quality without testing each laptop.'}, {'name': 'Weight', 'inc': 'The last thing you want is to carry a dumbbell around campus.', 'just': 'The cold, hard truth is you will spend more time carrying your laptop than using it.'}, {'name': 'Screen Size', 'inc': 'You can Facebook and program at the same time!', 'just': 'Being able to see multiple objects makes you far more effective.'}, {'name': 'Power', 'inc': 'Some of your programs are computationally intensive with high memory usage.', 'just': "It is nice, but for the most part it doesn't make a difference in your life."}, {'name': 'Storage', 'inc': 'In some programs you will produce lots of data and waiting for it to save is boring. ', 'just': 'Load and save time is relatively insignificant.'}, {'name': 'Battery Life', 'inc': "A laptop is useless if you can't use it on the go. But there are plenty of outlets on campus.", 'just': 'The only time an outlet might not be available is during a lecture.'}] ranking = [{'name': 'HP Envy 15t Quad Edition', 'rank': 71.6}, {'name': 'Dell Inspiron i15RV-1435BLK', 'rank': 69.6}, {'name': 'Toshiba Satellite C55-A5245', 'rank': 69.1}, {'name': 'Lenovo IdeaPad U430', 'rank': 64.7}, {'name': 'MacBook Air 13"', 'rank': 63.5}, {'name': 'MacBook Pro 13" with Retina Display', 'rank': 62.9}, {'name': 'ASUS ROG 6750JM-DS71', 'rank': 57.7}] algorithm = [{'name': 'Price', 'weight': 30, 'formula': 'img/price_formula.gif', 'assumption': '$2000 is likely the most a student will be willing to pay for a laptop.'}, {'name': 'User Rating', 'weight': 25, 'formula': 'img/user_rating_formula.gif', 'assumption': 'User Ratings are from 1 to 5.'}, {'name': 'Weight', 'weight': 20, 'formula': 'img/weight_formula.gif', 'assumption': '10 pounds is the most a laptop should weigh to be reasonable for a student.'}, {'name': 'Screen Size', 'weight': 10, 'formula': 'img/screen_size_formula.gif', 'assumption': 'The largest reasonable laptop screen size is 17 inches.'}, {'name': 'Power', 'weight': 7, 'formula': 'img/power_formula.gif', 'assumption': 'Quad core, 3 GHz, and 8Gb of RAM are reasonable limits for a student.'}, {'name': 'Storage', 'weight': 5, 'formula': 'img/storage_formula.gif', 'assumption': 'An SSD is roughly equivalent to a 10,000 rpm optical disk and 512 Gb is a reasonable upper bound on hard drive space.'}, {'name': 'Battery Life', 'weight': 3, 'formula': 'img/battery_life_formula.gif', 'assumption': '15 hours is the largest reasonable battery life of a laptop.'}] breakdown = {'row_headings': ['Price', 'User Rating', 'Weight', 'Screen Size', 'Power', 'Storage', 'Battery Life'], 'col_headings': ['HP Envy 15t Quad', 'Dell Inspiron i15RV', 'Toshiba Satellite C55', 'Lenovo IdeaPad U430', 'MacBook Air 13"', 'MacBook Pro 13"', 'ASUS ROG 6750JM'], 'rows': [[19.5, 20.5, 8.8, 9.2, 5.6, 6.2, 1.9], [24.3, 20.0, 10.1, 9.2, 1.5, 3.8, 0.8], [23.7, 20.5, 9.2, 9.2, 1.9, 3.8, 0.8], [19.5, 19.0, 11.6, 8.2, 1.5, 3.8, 1.1], [15.8, 20.5, 14.1, 6.5, 1.2, 3.1, 2.4], [9.0, 23.5, 13.1, 7.8, 4.0, 3.8, 1.8], [10.5, 21.5, 0.2, 10.2, 8.4, 6.2, 0.7]]} proscons = [{'name': 'HP Envy 15t Quad Edition', 'url': 'http://ssl-product-images.www8-hp.com/digmedialib/prodimg/lowres/c03698047.png', 'pro': '15.6 inch screen\nSolid power\nFour Beats audio speakers ', 'con': 'Heavy\nNo SSD'}, {'name': 'Dell Inspiron i15RV-1435BLK', 'url': 'http://ecx.images-amazon.com/images/I/71qmqgZmp7L._SL1500_.jpg', 'pro': 'Inexpensive\n15.6 Inch Screen', 'con': 'Poor battery life\nNot very powerful\nNo SSD'}, {'name': 'Toshiba Satellite C55-A5245', 'url': 'https://www.laptopninja.org/wp-content/uploads/2014/03/Toshiba-Satellite-C55-A5245.jpg', 'pro': 'Inexpensive\n15.6 Inch Screen', 'con': 'Fairly heavy\nPoor battery life\nNo SSD'}, {'name': 'Lenovo IdeaPad U430', 'url': 'http://media.engadget.com/img/products/488/ah7w/ah7w-800.jpg', 'pro': 'Powerful\nTouch screen', 'con': 'No SSD'}, {'name': 'MacBook Air 13"', 'url': 'http://images.apple.com/macbook-air/images/techspecs_headline_13inch.jpg', 'pro': 'Weight\nSuper thin\nHas SSD', 'con': 'Expensive\nScreen Size'}, {'name': 'MacBook Pro 13" with Retina Display', 'url': 'http://cdn0.sbnation.com/products/large/7406/retina13.jpg?1382468345', 'pro': 'Retina display\nPowerful\nThin & light\nHas SSD', 'con': 'Expensive\nSmall Screen'}, {'name': 'ASUS ROG 6750JM-DS71', 'url': 'http://ecx.images-amazon.com/images/I/41eUTqGvDpL._SL160_SL150_.jpg', 'pro': 'Very powerful\n1 TB hard drive\nGaming', 'con': 'Extremely heavy\nVery poor battery life\nNo SSD'}] specs = [['$702', 4.1, '5.6 lbs', '15.6"', '4 cores 2.4 clock with 8Gb of RAM', '5400 rpm 1100 Gb', '9.5 hrs'], ['$379', 4.0, '4.9 lbs', '15.6"', '2 cores 1.8 clock with 4Gb of RAM', '5400 rpm 500 Gb', '4 hrs'], ['$419', 4.1, '5.4 lbs', '15.6"', '2 cores 2.3 clock with 4Gb of RAM', '5400 rpm 500 Gb', '4 hrs'], ['$699', 3.8, '4.2 lbs', '14.0"', '2 cores 1.8 clock with 4Gb of RAM', '5400 rpm 500 Gb', '5.5 hrs'], ['$949', 4.1, '2.9 lbs', '11.0"', '2 cores 1.4 clock with 4Gb of RAM', '10000 rpm 128 Gb', '12 hrs'], ['$1399', 4.7, '3.4 lbs', '13.3"', '2 cores 2.4 clock with 8Gb of RAM', '10000 rpm 256 Gb', '9 hrs'], ['$1299', 4.3, '9.9 lbs', '17.3"', '4 cores 2.4 clock with 12Gb of RAM', '5400 rpm 1000 Gb', '3.5 hrs']]
""" __init__.py Created by: Martin Sicho On: 4/27/20, 10:49 AM """
""" __init__.py Created by: Martin Sicho On: 4/27/20, 10:49 AM """
# # PySNMP MIB module A3COM-HUAWEI-DNS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-DNS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 16:49:29 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) # h3cCommon, = mibBuilder.importSymbols("A3COM-HUAWEI-OID-MIB", "h3cCommon") Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint") InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") TimeTicks, Integer32, Gauge32, IpAddress, Counter32, Bits, Unsigned32, ModuleIdentity, iso, MibIdentifier, ObjectIdentity, NotificationType, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Integer32", "Gauge32", "IpAddress", "Counter32", "Bits", "Unsigned32", "ModuleIdentity", "iso", "MibIdentifier", "ObjectIdentity", "NotificationType", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TextualConvention") h3cDns = ModuleIdentity((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97)) h3cDns.setRevisions(('2009-02-12 00:00',)) if mibBuilder.loadTexts: h3cDns.setLastUpdated('200902120000Z') if mibBuilder.loadTexts: h3cDns.setOrganization('Hangzhou H3C Tech. Co., Ltd.') h3cDnsObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1)) h3cDnsStaticSrvIpTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 1), ) if mibBuilder.loadTexts: h3cDnsStaticSrvIpTable.setStatus('current') h3cDnsStaticSrvIpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 1, 1), ).setIndexNames((0, "A3COM-HUAWEI-DNS-MIB", "h3cDnsStaticSrvIpType"), (0, "A3COM-HUAWEI-DNS-MIB", "h3cDnsStaticSrvIpAddr")) if mibBuilder.loadTexts: h3cDnsStaticSrvIpEntry.setStatus('current') h3cDnsStaticSrvIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 1, 1, 1), InetAddressType()) if mibBuilder.loadTexts: h3cDnsStaticSrvIpType.setStatus('current') h3cDnsStaticSrvIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 1, 1, 2), InetAddress().subtype(subtypeSpec=ValueSizeConstraint(1, 64))) if mibBuilder.loadTexts: h3cDnsStaticSrvIpAddr.setStatus('current') h3cDnsStaticSrvIpPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: h3cDnsStaticSrvIpPriority.setStatus('current') h3cDnsStaticSrvIpRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 1, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: h3cDnsStaticSrvIpRowStatus.setStatus('current') h3cDnsDynamicSrvIpTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 2), ) if mibBuilder.loadTexts: h3cDnsDynamicSrvIpTable.setStatus('current') h3cDnsDynamicSrvIpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 2, 1), ).setIndexNames((0, "A3COM-HUAWEI-DNS-MIB", "h3cDnsDynamicSrvIpType"), (0, "A3COM-HUAWEI-DNS-MIB", "h3cDnsDynamicSrvIpAddr")) if mibBuilder.loadTexts: h3cDnsDynamicSrvIpEntry.setStatus('current') h3cDnsDynamicSrvIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 2, 1, 1), InetAddressType()) if mibBuilder.loadTexts: h3cDnsDynamicSrvIpType.setStatus('current') h3cDnsDynamicSrvIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 2, 1, 2), InetAddress().subtype(subtypeSpec=ValueSizeConstraint(1, 64))) if mibBuilder.loadTexts: h3cDnsDynamicSrvIpAddr.setStatus('current') h3cDnsDynamicSrvIpPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: h3cDnsDynamicSrvIpPriority.setStatus('current') h3cDnsMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 2)) h3cDnsMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 2, 1)) h3cDnsMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 2, 1, 1)).setObjects(("A3COM-HUAWEI-DNS-MIB", "h3cDnsStaticSrvIpGroup"), ("A3COM-HUAWEI-DNS-MIB", "h3cDnsDynamicSrvIpGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3cDnsMIBCompliance = h3cDnsMIBCompliance.setStatus('current') h3cDnsMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 2, 2)) h3cDnsStaticSrvIpGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 2, 2, 1)).setObjects(("A3COM-HUAWEI-DNS-MIB", "h3cDnsStaticSrvIpPriority"), ("A3COM-HUAWEI-DNS-MIB", "h3cDnsStaticSrvIpRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3cDnsStaticSrvIpGroup = h3cDnsStaticSrvIpGroup.setStatus('current') h3cDnsDynamicSrvIpGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 2, 2, 2)).setObjects(("A3COM-HUAWEI-DNS-MIB", "h3cDnsDynamicSrvIpPriority")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3cDnsDynamicSrvIpGroup = h3cDnsDynamicSrvIpGroup.setStatus('current') mibBuilder.exportSymbols("A3COM-HUAWEI-DNS-MIB", h3cDnsStaticSrvIpPriority=h3cDnsStaticSrvIpPriority, h3cDnsStaticSrvIpAddr=h3cDnsStaticSrvIpAddr, h3cDnsDynamicSrvIpPriority=h3cDnsDynamicSrvIpPriority, h3cDnsDynamicSrvIpGroup=h3cDnsDynamicSrvIpGroup, h3cDns=h3cDns, h3cDnsDynamicSrvIpType=h3cDnsDynamicSrvIpType, h3cDnsStaticSrvIpType=h3cDnsStaticSrvIpType, h3cDnsStaticSrvIpEntry=h3cDnsStaticSrvIpEntry, h3cDnsDynamicSrvIpEntry=h3cDnsDynamicSrvIpEntry, h3cDnsMIBConformance=h3cDnsMIBConformance, h3cDnsStaticSrvIpRowStatus=h3cDnsStaticSrvIpRowStatus, h3cDnsDynamicSrvIpTable=h3cDnsDynamicSrvIpTable, h3cDnsMIBCompliance=h3cDnsMIBCompliance, h3cDnsObjects=h3cDnsObjects, PYSNMP_MODULE_ID=h3cDns, h3cDnsStaticSrvIpTable=h3cDnsStaticSrvIpTable, h3cDnsStaticSrvIpGroup=h3cDnsStaticSrvIpGroup, h3cDnsMIBGroups=h3cDnsMIBGroups, h3cDnsDynamicSrvIpAddr=h3cDnsDynamicSrvIpAddr, h3cDnsMIBCompliances=h3cDnsMIBCompliances)
(h3c_common,) = mibBuilder.importSymbols('A3COM-HUAWEI-OID-MIB', 'h3cCommon') (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constraint, constraints_intersection, single_value_constraint, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueSizeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueRangeConstraint') (inet_address_type, inet_address) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddressType', 'InetAddress') (notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup') (time_ticks, integer32, gauge32, ip_address, counter32, bits, unsigned32, module_identity, iso, mib_identifier, object_identity, notification_type, counter64, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks', 'Integer32', 'Gauge32', 'IpAddress', 'Counter32', 'Bits', 'Unsigned32', 'ModuleIdentity', 'iso', 'MibIdentifier', 'ObjectIdentity', 'NotificationType', 'Counter64', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn') (row_status, display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'DisplayString', 'TextualConvention') h3c_dns = module_identity((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97)) h3cDns.setRevisions(('2009-02-12 00:00',)) if mibBuilder.loadTexts: h3cDns.setLastUpdated('200902120000Z') if mibBuilder.loadTexts: h3cDns.setOrganization('Hangzhou H3C Tech. Co., Ltd.') h3c_dns_objects = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1)) h3c_dns_static_srv_ip_table = mib_table((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 1)) if mibBuilder.loadTexts: h3cDnsStaticSrvIpTable.setStatus('current') h3c_dns_static_srv_ip_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 1, 1)).setIndexNames((0, 'A3COM-HUAWEI-DNS-MIB', 'h3cDnsStaticSrvIpType'), (0, 'A3COM-HUAWEI-DNS-MIB', 'h3cDnsStaticSrvIpAddr')) if mibBuilder.loadTexts: h3cDnsStaticSrvIpEntry.setStatus('current') h3c_dns_static_srv_ip_type = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 1, 1, 1), inet_address_type()) if mibBuilder.loadTexts: h3cDnsStaticSrvIpType.setStatus('current') h3c_dns_static_srv_ip_addr = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 1, 1, 2), inet_address().subtype(subtypeSpec=value_size_constraint(1, 64))) if mibBuilder.loadTexts: h3cDnsStaticSrvIpAddr.setStatus('current') h3c_dns_static_srv_ip_priority = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 1, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly') if mibBuilder.loadTexts: h3cDnsStaticSrvIpPriority.setStatus('current') h3c_dns_static_srv_ip_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 1, 1, 4), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: h3cDnsStaticSrvIpRowStatus.setStatus('current') h3c_dns_dynamic_srv_ip_table = mib_table((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 2)) if mibBuilder.loadTexts: h3cDnsDynamicSrvIpTable.setStatus('current') h3c_dns_dynamic_srv_ip_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 2, 1)).setIndexNames((0, 'A3COM-HUAWEI-DNS-MIB', 'h3cDnsDynamicSrvIpType'), (0, 'A3COM-HUAWEI-DNS-MIB', 'h3cDnsDynamicSrvIpAddr')) if mibBuilder.loadTexts: h3cDnsDynamicSrvIpEntry.setStatus('current') h3c_dns_dynamic_srv_ip_type = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 2, 1, 1), inet_address_type()) if mibBuilder.loadTexts: h3cDnsDynamicSrvIpType.setStatus('current') h3c_dns_dynamic_srv_ip_addr = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 2, 1, 2), inet_address().subtype(subtypeSpec=value_size_constraint(1, 64))) if mibBuilder.loadTexts: h3cDnsDynamicSrvIpAddr.setStatus('current') h3c_dns_dynamic_srv_ip_priority = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 1, 2, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly') if mibBuilder.loadTexts: h3cDnsDynamicSrvIpPriority.setStatus('current') h3c_dns_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 2)) h3c_dns_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 2, 1)) h3c_dns_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 2, 1, 1)).setObjects(('A3COM-HUAWEI-DNS-MIB', 'h3cDnsStaticSrvIpGroup'), ('A3COM-HUAWEI-DNS-MIB', 'h3cDnsDynamicSrvIpGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3c_dns_mib_compliance = h3cDnsMIBCompliance.setStatus('current') h3c_dns_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 2, 2)) h3c_dns_static_srv_ip_group = object_group((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 2, 2, 1)).setObjects(('A3COM-HUAWEI-DNS-MIB', 'h3cDnsStaticSrvIpPriority'), ('A3COM-HUAWEI-DNS-MIB', 'h3cDnsStaticSrvIpRowStatus')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3c_dns_static_srv_ip_group = h3cDnsStaticSrvIpGroup.setStatus('current') h3c_dns_dynamic_srv_ip_group = object_group((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 97, 2, 2, 2)).setObjects(('A3COM-HUAWEI-DNS-MIB', 'h3cDnsDynamicSrvIpPriority')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3c_dns_dynamic_srv_ip_group = h3cDnsDynamicSrvIpGroup.setStatus('current') mibBuilder.exportSymbols('A3COM-HUAWEI-DNS-MIB', h3cDnsStaticSrvIpPriority=h3cDnsStaticSrvIpPriority, h3cDnsStaticSrvIpAddr=h3cDnsStaticSrvIpAddr, h3cDnsDynamicSrvIpPriority=h3cDnsDynamicSrvIpPriority, h3cDnsDynamicSrvIpGroup=h3cDnsDynamicSrvIpGroup, h3cDns=h3cDns, h3cDnsDynamicSrvIpType=h3cDnsDynamicSrvIpType, h3cDnsStaticSrvIpType=h3cDnsStaticSrvIpType, h3cDnsStaticSrvIpEntry=h3cDnsStaticSrvIpEntry, h3cDnsDynamicSrvIpEntry=h3cDnsDynamicSrvIpEntry, h3cDnsMIBConformance=h3cDnsMIBConformance, h3cDnsStaticSrvIpRowStatus=h3cDnsStaticSrvIpRowStatus, h3cDnsDynamicSrvIpTable=h3cDnsDynamicSrvIpTable, h3cDnsMIBCompliance=h3cDnsMIBCompliance, h3cDnsObjects=h3cDnsObjects, PYSNMP_MODULE_ID=h3cDns, h3cDnsStaticSrvIpTable=h3cDnsStaticSrvIpTable, h3cDnsStaticSrvIpGroup=h3cDnsStaticSrvIpGroup, h3cDnsMIBGroups=h3cDnsMIBGroups, h3cDnsDynamicSrvIpAddr=h3cDnsDynamicSrvIpAddr, h3cDnsMIBCompliances=h3cDnsMIBCompliances)
DEBUG = False PORT = 8080 PROPAGATE_EXCEPTIONS = True SQLALCHEMY_ECHO = False SQLALCHEMY_DATABASE_URI = "" SQLALCHEMY_POOL_SIZE = 15
debug = False port = 8080 propagate_exceptions = True sqlalchemy_echo = False sqlalchemy_database_uri = '' sqlalchemy_pool_size = 15
class Workpiece: def __init__(self, id): self.id = id # self.status = "awaiting production" self.status = "awaiting next step" self.actual_quality = None self.source = None self.sink = None self.location = "wc_0" # Starting point. Location refers to workcell id. self.step_idx = None self.pos = None self.count_down = 0
class Workpiece: def __init__(self, id): self.id = id self.status = 'awaiting next step' self.actual_quality = None self.source = None self.sink = None self.location = 'wc_0' self.step_idx = None self.pos = None self.count_down = 0
def add_filters_to_legend(): pass def extend_data_from_recs(): pass def find_errors(): '''find errors such as restricted works, etc. where data needs to be entered manually''' pass
def add_filters_to_legend(): pass def extend_data_from_recs(): pass def find_errors(): """find errors such as restricted works, etc. where data needs to be entered manually""" pass
QWERTY_KEYMAP = bytearray.fromhex('000000000000000000000000760f00d4ffffffc7000000782c1e3420212224342627252e362d3738271e1f202122232425263333362e37381f0405060708090a0b0c0d0e0f101112131415161718191a1b1c1d2f3130232d350405060708090a0b0c0d0e0f101112131415161718191a1b1c1d2f313035') print(QWERTY_KEYMAP) print(type(QWERTY_KEYMAP))
qwerty_keymap = bytearray.fromhex('000000000000000000000000760f00d4ffffffc7000000782c1e3420212224342627252e362d3738271e1f202122232425263333362e37381f0405060708090a0b0c0d0e0f101112131415161718191a1b1c1d2f3130232d350405060708090a0b0c0d0e0f101112131415161718191a1b1c1d2f313035') print(QWERTY_KEYMAP) print(type(QWERTY_KEYMAP))
# MIT License # # Copyright (c) [2018] [Victor Manuel Cajes Gonzalez - vcajes@gmail.com] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # possibles values for the BancardAPI environment class member ENVIRONMENT_SANDBOX = "sandbox" ENVIRONMENT_PRODUCTION = "production" # Currencies that Bancard allows for charging BANCARD_ALLOWED_CURRENCIES = ["PYG"] BANCARD_BASE_URL_SANDBOX = "https://vpos.infonet.com.py:8888" BANCARD_BASE_URL_PRODUCTION = "https://vpos.infonet.com.py" # Keys for the SANDBOX_URLS / PRODUCTION_URLS dictionaries ROLLBACK_KEY = "rollback" CHARGE_TOKEN_GENERATOR_KEY = "single_buy" PAYMENT_WEB_URL_KEY = "payment" CONFIRMATIONS_KEY = "confirmations" # Bancard WebService development (sandbox) environment endpoints BANCARD_SANDBOX_URLS = { ROLLBACK_KEY: "%s/vpos/api/0.3/single_buy/rollback" % BANCARD_BASE_URL_SANDBOX, CHARGE_TOKEN_GENERATOR_KEY: "%s/vpos/api/0.3/single_buy" % BANCARD_BASE_URL_SANDBOX, PAYMENT_WEB_URL_KEY: "%s/payment/single_buy?process_id=" % BANCARD_BASE_URL_SANDBOX, CONFIRMATIONS_KEY: "%s/vpos/api/0.3/single_buy/confirmations" % BANCARD_BASE_URL_SANDBOX, } # Bancard WebService production environment endpoints BANCARD_PRODUCTION_URLS = { ROLLBACK_KEY: "%s/vpos/api/0.3/single_buy/rollback" % BANCARD_BASE_URL_PRODUCTION, CHARGE_TOKEN_GENERATOR_KEY: "%s/vpos/api/0.3/single_buy" % BANCARD_BASE_URL_PRODUCTION, PAYMENT_WEB_URL_KEY: "%s/payment/single_buy?process_id=" % BANCARD_BASE_URL_PRODUCTION, CONFIRMATIONS_KEY: "%s/vpos/api/0.3/single_buy/confirmations" % BANCARD_BASE_URL_PRODUCTION, } # All the Bancard WebService endpoints for sandbox/production BANCARD_URLS = { ENVIRONMENT_SANDBOX: BANCARD_SANDBOX_URLS, ENVIRONMENT_PRODUCTION: BANCARD_PRODUCTION_URLS }
environment_sandbox = 'sandbox' environment_production = 'production' bancard_allowed_currencies = ['PYG'] bancard_base_url_sandbox = 'https://vpos.infonet.com.py:8888' bancard_base_url_production = 'https://vpos.infonet.com.py' rollback_key = 'rollback' charge_token_generator_key = 'single_buy' payment_web_url_key = 'payment' confirmations_key = 'confirmations' bancard_sandbox_urls = {ROLLBACK_KEY: '%s/vpos/api/0.3/single_buy/rollback' % BANCARD_BASE_URL_SANDBOX, CHARGE_TOKEN_GENERATOR_KEY: '%s/vpos/api/0.3/single_buy' % BANCARD_BASE_URL_SANDBOX, PAYMENT_WEB_URL_KEY: '%s/payment/single_buy?process_id=' % BANCARD_BASE_URL_SANDBOX, CONFIRMATIONS_KEY: '%s/vpos/api/0.3/single_buy/confirmations' % BANCARD_BASE_URL_SANDBOX} bancard_production_urls = {ROLLBACK_KEY: '%s/vpos/api/0.3/single_buy/rollback' % BANCARD_BASE_URL_PRODUCTION, CHARGE_TOKEN_GENERATOR_KEY: '%s/vpos/api/0.3/single_buy' % BANCARD_BASE_URL_PRODUCTION, PAYMENT_WEB_URL_KEY: '%s/payment/single_buy?process_id=' % BANCARD_BASE_URL_PRODUCTION, CONFIRMATIONS_KEY: '%s/vpos/api/0.3/single_buy/confirmations' % BANCARD_BASE_URL_PRODUCTION} bancard_urls = {ENVIRONMENT_SANDBOX: BANCARD_SANDBOX_URLS, ENVIRONMENT_PRODUCTION: BANCARD_PRODUCTION_URLS}
class APIError(Exception): """Base exception for errors raised by high-level websocket API.""" class MessageHandlerError(APIError): """Decoding or parsing a message failed.""" class RemoteMessageHandlerError(MessageHandlerError): """Raised for errors directly caused by messages from the client.""" class InternalMessageHandlerError(MessageHandlerError): """Raised for errors directly caused by messages from internal sources."""
class Apierror(Exception): """Base exception for errors raised by high-level websocket API.""" class Messagehandlererror(APIError): """Decoding or parsing a message failed.""" class Remotemessagehandlererror(MessageHandlerError): """Raised for errors directly caused by messages from the client.""" class Internalmessagehandlererror(MessageHandlerError): """Raised for errors directly caused by messages from internal sources."""
def printadj(table,g): print(" ",end="") print(" ".join(table)) for i in table: strout = "" print(i,end=" : ") for j in table: l = g.get(i,None) if not l : strout+="0, " elif j in l: strout+="1, " else: strout+="0, " print(strout[:-2]) table = [] inp = input("Enter : ").split(",") g = dict() for i in inp: if g.get(i.split()[0],-1) == -1: g[i.split()[0]] = i.split()[1] else: g[i.split()[0]] += i.split()[1] if i.split()[0] not in table: table.append(i.split()[0]) if i.split()[1] not in table: table.append(i.split()[1]) table.sort() printadj(table,g)
def printadj(table, g): print(' ', end='') print(' '.join(table)) for i in table: strout = '' print(i, end=' : ') for j in table: l = g.get(i, None) if not l: strout += '0, ' elif j in l: strout += '1, ' else: strout += '0, ' print(strout[:-2]) table = [] inp = input('Enter : ').split(',') g = dict() for i in inp: if g.get(i.split()[0], -1) == -1: g[i.split()[0]] = i.split()[1] else: g[i.split()[0]] += i.split()[1] if i.split()[0] not in table: table.append(i.split()[0]) if i.split()[1] not in table: table.append(i.split()[1]) table.sort() printadj(table, g)
""" Created on May 4 - 2019 ---Based on the 2-stage stochastic program structure ---Assumption: RHS is random ---read stoc file (.tim) ---save the distributoin of the random variables and return the ---random variables @author: Siavash Tabrizian - stabrizian@smu.edu """ class readtim: def __init__(self, name): self.name = name + ".tim" self.stage = list() self.stagenum = 0 ## Read the stoc file def readfile(self): with open(self.name, "r") as f: data = f.readlines() #go through the time file count = 0 for line in data: words = line.split() #print words if len(words) > 2: tmp = list() tmp.append(words[0]) tmp.append(words[1]) self.stage.append(tmp) count += 1 self.stagenum = count if count > 2: print ("ERROR: more than two stages")
""" Created on May 4 - 2019 ---Based on the 2-stage stochastic program structure ---Assumption: RHS is random ---read stoc file (.tim) ---save the distributoin of the random variables and return the ---random variables @author: Siavash Tabrizian - stabrizian@smu.edu """ class Readtim: def __init__(self, name): self.name = name + '.tim' self.stage = list() self.stagenum = 0 def readfile(self): with open(self.name, 'r') as f: data = f.readlines() count = 0 for line in data: words = line.split() if len(words) > 2: tmp = list() tmp.append(words[0]) tmp.append(words[1]) self.stage.append(tmp) count += 1 self.stagenum = count if count > 2: print('ERROR: more than two stages')
class Solution: def twoSum(self, nums, target): for n in nums: print("n = {}".format(n)) indexN = nums.index(n) print("indexN = {}".format(indexN)) for p in nums[1:]: print("p = {}".format(p)) indexP = nums.index(p) print("indexP = {}".format(indexP)) if indexP == 0: continue else: if n + p == target: num1 = nums.index(n) num2 = nums.index(p) return [num1,num2] twoSum(0,[3, 3], 6)
class Solution: def two_sum(self, nums, target): for n in nums: print('n = {}'.format(n)) index_n = nums.index(n) print('indexN = {}'.format(indexN)) for p in nums[1:]: print('p = {}'.format(p)) index_p = nums.index(p) print('indexP = {}'.format(indexP)) if indexP == 0: continue elif n + p == target: num1 = nums.index(n) num2 = nums.index(p) return [num1, num2] two_sum(0, [3, 3], 6)
''' Binary Seach works on only sorted collection. Time : O(log n) Space : O(1) ''' def binarySearch(arr, target): left = 0 right = len(arr)-1 while(left <= right): mid = (left + right) // 2 if(arr[mid] == target): return mid #if target is greater than mid then set left to min+1 elif(arr[mid]< target): left = mid+1 else: right = mid - 1 return -1 if __name__ == "__main__": arr = [10,11,12,13,14,15] target = 15 result = binarySearch(arr, target) #5 if result != -1: print("Result is present at index %d"% result) else: print("Element is not present in the list.")
""" Binary Seach works on only sorted collection. Time : O(log n) Space : O(1) """ def binary_search(arr, target): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 if __name__ == '__main__': arr = [10, 11, 12, 13, 14, 15] target = 15 result = binary_search(arr, target) if result != -1: print('Result is present at index %d' % result) else: print('Element is not present in the list.')
""" 1436. Destination City You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city. Example 1: Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] Output: "Sao Paulo" Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo". Example 2: Input: paths = [["B","C"],["D","B"],["C","A"]] Output: "A" Explanation: All possible trips are: "D" -> "B" -> "C" -> "A". "B" -> "C" -> "A". "C" -> "A". "A". Clearly the destination city is "A". Example 3: Input: paths = [["A","Z"]] Output: "Z" Constraints: 1 <= paths.length <= 100 paths[i].length == 2 1 <= cityAi.length, cityBi.length <= 10 cityAi != cityBi All strings consist of lowercase and uppercase English letters and the space character. """ class Solution: def destCity(self, paths: List[List[str]]): start, end = set(), set() for pth in paths: start.add(pth[0]) end.add(pth[1]) for des in end: if des not in start: return des
""" 1436. Destination City You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city. Example 1: Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] Output: "Sao Paulo" Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo". Example 2: Input: paths = [["B","C"],["D","B"],["C","A"]] Output: "A" Explanation: All possible trips are: "D" -> "B" -> "C" -> "A". "B" -> "C" -> "A". "C" -> "A". "A". Clearly the destination city is "A". Example 3: Input: paths = [["A","Z"]] Output: "Z" Constraints: 1 <= paths.length <= 100 paths[i].length == 2 1 <= cityAi.length, cityBi.length <= 10 cityAi != cityBi All strings consist of lowercase and uppercase English letters and the space character. """ class Solution: def dest_city(self, paths: List[List[str]]): (start, end) = (set(), set()) for pth in paths: start.add(pth[0]) end.add(pth[1]) for des in end: if des not in start: return des
t=int(input()) for qwerty in range(t): #n,a,b,c=input().split() #n,a,b,c=int(n),int(a),int(b),int(c) #n=int(input()) arr1=list(map(int,input().split())) arr2=list(map(int,input().split())) n1,n2=len(arr1),len(arr2) arr3=[] i=0 j=0 k=0 while(i<n1 and j <n2): if(arr1[i]<arr2[j]): arr3.append(arr1[i]) i+=1 else: arr3.append(arr2[j]) j+=1 if(j!=n1): for k in range(j,n2): arr3.append(arr2[k]) elif(i!=n2): for k in range(i,n1): arr3.append(arr1[k]) print(arr3)
t = int(input()) for qwerty in range(t): arr1 = list(map(int, input().split())) arr2 = list(map(int, input().split())) (n1, n2) = (len(arr1), len(arr2)) arr3 = [] i = 0 j = 0 k = 0 while i < n1 and j < n2: if arr1[i] < arr2[j]: arr3.append(arr1[i]) i += 1 else: arr3.append(arr2[j]) j += 1 if j != n1: for k in range(j, n2): arr3.append(arr2[k]) elif i != n2: for k in range(i, n1): arr3.append(arr1[k]) print(arr3)
expected_output ={ "vrf": { "tn-L2-PBR:vrf-L2-PBR": { "address_family": { "ipv4": { "routes": { "192.168.1.0/24": { "route": "192.168.1.0/24", "active": True, "ubest": 1, "mbest": 0, "attached": True, "direct": True, "pervasive": True, "metric": 0, "route_preference": 1, "tag": 4294967294, "next_hop": { "next_hop_list": { 1: { "index": 1, "next_hop": "10.11.200.98", "source_protocol": "static", "best_ucast_nexthop": True, "updated": "02w00d", "next_hop_vrf": "overlay-1", "metric": 0, "route_preference": 1, } } }, "source_protocol": "static", }, "192.168.1.1/32": { "route": "192.168.1.1/32", "active": True, "ubest": 1, "mbest": 0, "attached": True, "pervasive": True, "metric": 0, "route_preference": 0, "next_hop": { "next_hop_list": { 1: { "index": 1, "next_hop": "192.168.1.1", "source_protocol": "local", "source_protocol_status": "local", "best_ucast_nexthop": True, "updated": "02w00d", "outgoing_interface": "Vlan60", "metric": 0, "route_preference": 0, } } }, "source_protocol": "local", "source_protocol_status": "local", }, "192.168.100.0/24": { "route": "192.168.100.0/24", "active": True, "ubest": 1, "mbest": 0, "attached": True, "direct": True, "pervasive": True, "metric": 0, "route_preference": 1, "tag": 4294967294, "next_hop": { "next_hop_list": { 1: { "index": 1, "next_hop": "10.11.200.98", "source_protocol": "static", "best_ucast_nexthop": True, "updated": "02w00d", "next_hop_vrf": "overlay-1", "metric": 0, "route_preference": 1, } } }, "source_protocol": "static", }, "192.168.100.1/32": { "route": "192.168.100.1/32", "active": True, "ubest": 1, "mbest": 0, "attached": True, "pervasive": True, "metric": 0, "route_preference": 0, "next_hop": { "next_hop_list": { 1: { "index": 1, "next_hop": "192.168.100.1", "source_protocol": "local", "source_protocol_status": "local", "best_ucast_nexthop": True, "updated": "02w00d", "outgoing_interface": "Vlan14", "metric": 0, "route_preference": 0, } } }, "source_protocol": "local", "source_protocol_status": "local", }, "192.168.254.0/24": { "route": "192.168.254.0/24", "active": True, "ubest": 1, "mbest": 0, "attached": True, "direct": True, "pervasive": True, "metric": 0, "route_preference": 1, "tag": 4294967294, "next_hop": { "next_hop_list": { 1: { "index": 1, "next_hop": "10.11.200.98", "source_protocol": "static", "best_ucast_nexthop": True, "updated": "02w00d", "next_hop_vrf": "overlay-1", "metric": 0, "route_preference": 1, } } }, "source_protocol": "static", }, "192.168.254.1/32": { "route": "192.168.254.1/32", "active": True, "ubest": 1, "mbest": 0, "attached": True, "pervasive": True, "metric": 0, "route_preference": 0, "next_hop": { "next_hop_list": { 1: { "index": 1, "next_hop": "192.168.254.1", "source_protocol": "local", "source_protocol_status": "local", "best_ucast_nexthop": True, "updated": "02w00d", "outgoing_interface": "Vlan39", "metric": 0, "route_preference": 0, } } }, "source_protocol": "local", "source_protocol_status": "local", }, } } } } } }
expected_output = {'vrf': {'tn-L2-PBR:vrf-L2-PBR': {'address_family': {'ipv4': {'routes': {'192.168.1.0/24': {'route': '192.168.1.0/24', 'active': True, 'ubest': 1, 'mbest': 0, 'attached': True, 'direct': True, 'pervasive': True, 'metric': 0, 'route_preference': 1, 'tag': 4294967294, 'next_hop': {'next_hop_list': {1: {'index': 1, 'next_hop': '10.11.200.98', 'source_protocol': 'static', 'best_ucast_nexthop': True, 'updated': '02w00d', 'next_hop_vrf': 'overlay-1', 'metric': 0, 'route_preference': 1}}}, 'source_protocol': 'static'}, '192.168.1.1/32': {'route': '192.168.1.1/32', 'active': True, 'ubest': 1, 'mbest': 0, 'attached': True, 'pervasive': True, 'metric': 0, 'route_preference': 0, 'next_hop': {'next_hop_list': {1: {'index': 1, 'next_hop': '192.168.1.1', 'source_protocol': 'local', 'source_protocol_status': 'local', 'best_ucast_nexthop': True, 'updated': '02w00d', 'outgoing_interface': 'Vlan60', 'metric': 0, 'route_preference': 0}}}, 'source_protocol': 'local', 'source_protocol_status': 'local'}, '192.168.100.0/24': {'route': '192.168.100.0/24', 'active': True, 'ubest': 1, 'mbest': 0, 'attached': True, 'direct': True, 'pervasive': True, 'metric': 0, 'route_preference': 1, 'tag': 4294967294, 'next_hop': {'next_hop_list': {1: {'index': 1, 'next_hop': '10.11.200.98', 'source_protocol': 'static', 'best_ucast_nexthop': True, 'updated': '02w00d', 'next_hop_vrf': 'overlay-1', 'metric': 0, 'route_preference': 1}}}, 'source_protocol': 'static'}, '192.168.100.1/32': {'route': '192.168.100.1/32', 'active': True, 'ubest': 1, 'mbest': 0, 'attached': True, 'pervasive': True, 'metric': 0, 'route_preference': 0, 'next_hop': {'next_hop_list': {1: {'index': 1, 'next_hop': '192.168.100.1', 'source_protocol': 'local', 'source_protocol_status': 'local', 'best_ucast_nexthop': True, 'updated': '02w00d', 'outgoing_interface': 'Vlan14', 'metric': 0, 'route_preference': 0}}}, 'source_protocol': 'local', 'source_protocol_status': 'local'}, '192.168.254.0/24': {'route': '192.168.254.0/24', 'active': True, 'ubest': 1, 'mbest': 0, 'attached': True, 'direct': True, 'pervasive': True, 'metric': 0, 'route_preference': 1, 'tag': 4294967294, 'next_hop': {'next_hop_list': {1: {'index': 1, 'next_hop': '10.11.200.98', 'source_protocol': 'static', 'best_ucast_nexthop': True, 'updated': '02w00d', 'next_hop_vrf': 'overlay-1', 'metric': 0, 'route_preference': 1}}}, 'source_protocol': 'static'}, '192.168.254.1/32': {'route': '192.168.254.1/32', 'active': True, 'ubest': 1, 'mbest': 0, 'attached': True, 'pervasive': True, 'metric': 0, 'route_preference': 0, 'next_hop': {'next_hop_list': {1: {'index': 1, 'next_hop': '192.168.254.1', 'source_protocol': 'local', 'source_protocol_status': 'local', 'best_ucast_nexthop': True, 'updated': '02w00d', 'outgoing_interface': 'Vlan39', 'metric': 0, 'route_preference': 0}}}, 'source_protocol': 'local', 'source_protocol_status': 'local'}}}}}}}
# Week 1 Exercise 1 # Orla Higgins, 2018-02-20 # A program that displays Fibonacci numbers. def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i # Test the function with the following value. x = 16 ans = fib(x) print("Fibonacci number", x, "is", ans) # Comments on Discussions Board for Topic 1: # My name is Orla, so the first and last letter of my name (O + A = 15 + 1) give the number 16. The 16th Fibonacci number is 987. # Week 2 Exercise 2 # Orla Higgins, 2018-02-26 # A program that displays Fibonacci numbers using people's names. name = "Higgins" first = name[0] last = name[-1] firstno = ord(first) lastno = ord(last) x = firstno + lastno ans = fib(x) print("My surname is", name) print("The first letter", first, "is number", firstno) print("The last letter", last, "is number", lastno) print("Fibonacci number", x, "is", ans) # Comments on Discussions Board for Topic 2: # My surname is Higgins # The first letter H is number 72 # The last letter s is number 115 # Fibonacci number 187 is 538522340430300790495419781092981030533 # ord() is a built-in function of Python. Given a string representing one Unicode character, the function will return an integer representing the Unicode code point of that character in decimal form.
def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: (i, j) = (j, i + j) n = n - 1 return i x = 16 ans = fib(x) print('Fibonacci number', x, 'is', ans) name = 'Higgins' first = name[0] last = name[-1] firstno = ord(first) lastno = ord(last) x = firstno + lastno ans = fib(x) print('My surname is', name) print('The first letter', first, 'is number', firstno) print('The last letter', last, 'is number', lastno) print('Fibonacci number', x, 'is', ans)
''' Fixed XOR Write a function that takes two equal-length buffers and produces their XOR combination. If your function works properly, then when you feed it the string: 1c0111001f010100061a024b53535009181c ... after hex decoding, and when XOR'd against: 686974207468652062756c6c277320657965 ... should produce: 746865206b696420646f6e277420706c6179 ''' buf1 = '1c0111001f010100061a024b53535009181c' buf2 = '686974207468652062756c6c277320657965' def bufferXOR(buffer1,buffer2,printflag=False): ''' takes two equal-length buffers and produces their XOR combination :param buffer1: either hex string or bytes :param buffer2: either hex string or bytes :param printflag: :return: XOR result in bytearray ''' # verify if length is the same try: byte1 = buffer1 byte2 = buffer2 if isinstance(buffer1,str): byte1= bytes.fromhex(buffer1) if isinstance(buffer2,str): byte2 = bytes.fromhex(buffer2) if len(byte1)!=len(byte2): print('Input error, len1 {} and len2 {} do not match'.format(len(byte1),len(byte2))) return '' XOR_bytes = bytearray(byte1) for i,b in enumerate(byte2): XOR_bytes[i]^=b # XOR_message = XOR_bytes.decode() if printflag: print('Buffer1 is: {}'.format(buffer1)) print('Buffer2 is: {}'.format(buffer2)) print('Hex is: {}'.format(XOR_bytes.hex())) # print('XOR buffer is: {}'.format(XOR_message)) return XOR_bytes except ValueError: print('Error hex conversion, verify validity of input') return bytearray(b'') if __name__=='__main__': bufferXOR(buf1,buf2,True)
""" Fixed XOR Write a function that takes two equal-length buffers and produces their XOR combination. If your function works properly, then when you feed it the string: 1c0111001f010100061a024b53535009181c ... after hex decoding, and when XOR'd against: 686974207468652062756c6c277320657965 ... should produce: 746865206b696420646f6e277420706c6179 """ buf1 = '1c0111001f010100061a024b53535009181c' buf2 = '686974207468652062756c6c277320657965' def buffer_xor(buffer1, buffer2, printflag=False): """ takes two equal-length buffers and produces their XOR combination :param buffer1: either hex string or bytes :param buffer2: either hex string or bytes :param printflag: :return: XOR result in bytearray """ try: byte1 = buffer1 byte2 = buffer2 if isinstance(buffer1, str): byte1 = bytes.fromhex(buffer1) if isinstance(buffer2, str): byte2 = bytes.fromhex(buffer2) if len(byte1) != len(byte2): print('Input error, len1 {} and len2 {} do not match'.format(len(byte1), len(byte2))) return '' xor_bytes = bytearray(byte1) for (i, b) in enumerate(byte2): XOR_bytes[i] ^= b if printflag: print('Buffer1 is: {}'.format(buffer1)) print('Buffer2 is: {}'.format(buffer2)) print('Hex is: {}'.format(XOR_bytes.hex())) return XOR_bytes except ValueError: print('Error hex conversion, verify validity of input') return bytearray(b'') if __name__ == '__main__': buffer_xor(buf1, buf2, True)
CAPACITY = 100 class Heap: def __init__(self): self.heap_size = 0 self.heap = [0]*CAPACITY def insert(self, item): if self.heap_size == CAPACITY: return self.heap[self.heap_size] = item self.heap_size = self.heap_size + 1 self.fix_up(self.heap_size-1) def fix_up(self, index): parent_index = (index-1)//2 if index > 0 and self.heap[index] > self.heap[parent_index]: self.heap[index], self.heap[parent_index] = self.heap[parent_index], self.heap[index] self.fix_up(parent_index) def get_max(self): return self.heap[0] def poll(self): max_item = self.get_max() self.heap[0], self.heap[self.heap_size - 1] = self.heap[self.heap_size - 1], self.heap[0] self.heap_size = self.heap_size - 1 self.fix_down(0) return max_item def fix_down(self, index): index_left = 2 * index + 1 index_right = 2 * index + 2 largest_index = index if index_left < self.heap_size and self.heap[index_left] > self.heap[index]: largest_index = index_left if index_right < self.heap_size and self.heap[index_right] > self.heap[largest_index]: largest_index = index_right if index != largest_index: self.heap[index], self.heap[largest_index] = self.heap[largest_index], self.heap[index] self.fix_down(largest_index) def heap_sort(self): for _ in range(self.heap_size): max_item = self.poll() print(max_item, end=" ") heap = Heap() heap.insert(13) heap.insert(-2) heap.insert(0) heap.insert(8) heap.insert(1) heap.insert(-5) heap.insert(93) heap.insert(94) heap.insert(95) heap.insert(96) heap.insert(97) heap.insert(-50) heap.insert(-97) heap.heap_sort()
capacity = 100 class Heap: def __init__(self): self.heap_size = 0 self.heap = [0] * CAPACITY def insert(self, item): if self.heap_size == CAPACITY: return self.heap[self.heap_size] = item self.heap_size = self.heap_size + 1 self.fix_up(self.heap_size - 1) def fix_up(self, index): parent_index = (index - 1) // 2 if index > 0 and self.heap[index] > self.heap[parent_index]: (self.heap[index], self.heap[parent_index]) = (self.heap[parent_index], self.heap[index]) self.fix_up(parent_index) def get_max(self): return self.heap[0] def poll(self): max_item = self.get_max() (self.heap[0], self.heap[self.heap_size - 1]) = (self.heap[self.heap_size - 1], self.heap[0]) self.heap_size = self.heap_size - 1 self.fix_down(0) return max_item def fix_down(self, index): index_left = 2 * index + 1 index_right = 2 * index + 2 largest_index = index if index_left < self.heap_size and self.heap[index_left] > self.heap[index]: largest_index = index_left if index_right < self.heap_size and self.heap[index_right] > self.heap[largest_index]: largest_index = index_right if index != largest_index: (self.heap[index], self.heap[largest_index]) = (self.heap[largest_index], self.heap[index]) self.fix_down(largest_index) def heap_sort(self): for _ in range(self.heap_size): max_item = self.poll() print(max_item, end=' ') heap = heap() heap.insert(13) heap.insert(-2) heap.insert(0) heap.insert(8) heap.insert(1) heap.insert(-5) heap.insert(93) heap.insert(94) heap.insert(95) heap.insert(96) heap.insert(97) heap.insert(-50) heap.insert(-97) heap.heap_sort()
"""Class that stores the position information""" class FlPosition: """Stores the position information""" def __init__(self, position_data, column_labels, timestamps, conversion): self.position_data = position_data self.column_labels = column_labels self.timestamps = timestamps self.conversion = conversion
"""Class that stores the position information""" class Flposition: """Stores the position information""" def __init__(self, position_data, column_labels, timestamps, conversion): self.position_data = position_data self.column_labels = column_labels self.timestamps = timestamps self.conversion = conversion
def HI(): print("=======================================") print("= = = =") print("= = =") print("= ====== = =") print("= = = = =") print("= = = = =") print("=======================================") HI()
def hi(): print('=======================================') print('= = = =') print('= = =') print('= ====== = =') print('= = = = =') print('= = = = =') print('=======================================') hi()
def makeminutes(time): h, m = time.split(':') return int(h)*60+int(m) def check_buses(n, m, lines): cntbuses = [0]*(n+1) busbalance = [0]*(n+1) events = [] overnight = 0 for line in lines: cdep, deptime, carr, arrtime = line.split() cdep = int(cdep) carr = int(carr) deptime = makeminutes(deptime) arrtime = makeminutes(arrtime) if arrtime < deptime: overnight += 1 busbalance[cdep] -= 1 busbalance[carr] += 1 events.append((deptime, 1, cdep)) events.append((arrtime, -1, carr)) disbalance = False for i in range(n+1): if busbalance[i] != 0: disbalance = True if disbalance: return '-1' events.sort() for event in events: if event[1] == -1: cntbuses[event[2]] += 1 else: if cntbuses[event[2]] > 0: cntbuses[event[2]] -= 1 ans = 0 for i in range(n+1): ans += cntbuses[i] return str(ans+overnight) with open('input.txt') as file: lines = file.readlines() n, m = map(int, lines[0].split()) with open('output.txt', 'w') as file: file.write(check_buses(n, m, lines[1:]))
def makeminutes(time): (h, m) = time.split(':') return int(h) * 60 + int(m) def check_buses(n, m, lines): cntbuses = [0] * (n + 1) busbalance = [0] * (n + 1) events = [] overnight = 0 for line in lines: (cdep, deptime, carr, arrtime) = line.split() cdep = int(cdep) carr = int(carr) deptime = makeminutes(deptime) arrtime = makeminutes(arrtime) if arrtime < deptime: overnight += 1 busbalance[cdep] -= 1 busbalance[carr] += 1 events.append((deptime, 1, cdep)) events.append((arrtime, -1, carr)) disbalance = False for i in range(n + 1): if busbalance[i] != 0: disbalance = True if disbalance: return '-1' events.sort() for event in events: if event[1] == -1: cntbuses[event[2]] += 1 elif cntbuses[event[2]] > 0: cntbuses[event[2]] -= 1 ans = 0 for i in range(n + 1): ans += cntbuses[i] return str(ans + overnight) with open('input.txt') as file: lines = file.readlines() (n, m) = map(int, lines[0].split()) with open('output.txt', 'w') as file: file.write(check_buses(n, m, lines[1:]))
#!/usr/bin/env python class DataProcessingException(Exception): pass
class Dataprocessingexception(Exception): pass
class Solution: def distinctSubseqII(self, S): res, end = 0, collections.Counter() for c in S: res, end[c] = res * 2 + 1 - end[c], res + 1 return res % (10**9 + 7)
class Solution: def distinct_subseq_ii(self, S): (res, end) = (0, collections.Counter()) for c in S: (res, end[c]) = (res * 2 + 1 - end[c], res + 1) return res % (10 ** 9 + 7)
inter_,gremio_ = input().split() inter = int(inter_) gremio = int(gremio_) a = 0 contador = 1 v_inter = 0 v_gremio = 0 empate = 0 if inter > gremio: v_inter += 1 elif inter == gremio: empate += 1 else: v_gremio += 1 while a == 0: print("Novo grenal (1-sim 2-nao)") cond = int(input()) if cond == 2: a = 1 else: inter_ = 0 gremio_ = 0 inter = 0 gremio = 0 inter_, gremio_ = input().split() inter = int(inter_) gremio = int(gremio_) contador += 1 if inter > gremio: v_inter += 1 elif inter == gremio: empate += 1 else: v_gremio += 1 print("%i grenais"%contador) print("Inter:%i"%v_inter) print("Gremio:%i"%v_gremio) print("Empates:%i"%empate) if inter > gremio: print("Inter venceu mais") else: print("Gremio venceu mais")
(inter_, gremio_) = input().split() inter = int(inter_) gremio = int(gremio_) a = 0 contador = 1 v_inter = 0 v_gremio = 0 empate = 0 if inter > gremio: v_inter += 1 elif inter == gremio: empate += 1 else: v_gremio += 1 while a == 0: print('Novo grenal (1-sim 2-nao)') cond = int(input()) if cond == 2: a = 1 else: inter_ = 0 gremio_ = 0 inter = 0 gremio = 0 (inter_, gremio_) = input().split() inter = int(inter_) gremio = int(gremio_) contador += 1 if inter > gremio: v_inter += 1 elif inter == gremio: empate += 1 else: v_gremio += 1 print('%i grenais' % contador) print('Inter:%i' % v_inter) print('Gremio:%i' % v_gremio) print('Empates:%i' % empate) if inter > gremio: print('Inter venceu mais') else: print('Gremio venceu mais')
valor1 = float(input("Digite o primeiro valor: ")) dobro = valor1 *2 triplo = valor1 *3 raiz = valor1 **0.5 print("O dobro {} o triplo {} e a raiz quadrada {}".format(dobro,triplo,raiz))
valor1 = float(input('Digite o primeiro valor: ')) dobro = valor1 * 2 triplo = valor1 * 3 raiz = valor1 ** 0.5 print('O dobro {} o triplo {} e a raiz quadrada {}'.format(dobro, triplo, raiz))
#!/usr/bin/env python #----------------------------------------------------------------------- # tag.py # Author: Olivia Zhang, Zoe Barnswell, Lyra Katzman #----------------------------------------------------------------------- #----------------------------------------------------------------------- class Tag: # def __init__(self, tagID): self.tagID = tagID self.numArticles = 0
class Tag: def __init__(self, tagID): self.tagID = tagID self.numArticles = 0
TARGET_URL = '/{tail:.*}' EXCLUDED_HEADERS = { # 'Accept-CH', # 'Accept-CH-Lifetime', # 'Cache-Control', # 'Content-Encoding', # 'Content-Security-Policy', # 'Content-Type', # 'Date', # 'Expires', # 'Last-Modified', # 'P3P', # 'Set-Cookie', 'Transfer-Encoding', 'X-Target-Url', 'Content-Length', # 'Host', # 'X-Content-Type-Options', # 'X-Frame-Options' }
target_url = '/{tail:.*}' excluded_headers = {'Transfer-Encoding', 'X-Target-Url', 'Content-Length'}
# author: alex o def counting_sort_int(array, base, col): # initialise count array count_array = [0]*base # get the digit in position column and add them into "buckets" for elem in array: digit = elem // 10 ** (col) count_array[digit % base] += 1 # initialise position array position = [0]*base position[0] = 1 for i in range(1, base): position[i] = position[i - 1] + count_array[i - 1] # initialise output array output = [0]*len(array) # put back elements from initial array into output array for elem in array: output[position[elem // 10 ** (col) % base] - 1] = elem position[elem // 10 ** (col) % base] += 1 return output def radix_sort(arr): # O(MN), M = number of digits, N = counting sort # gets the maximum length of digits m = max(arr) for i in range(len(str(m))): arr = counting_sort_int(arr, 10, i) yield arr return arr
def counting_sort_int(array, base, col): count_array = [0] * base for elem in array: digit = elem // 10 ** col count_array[digit % base] += 1 position = [0] * base position[0] = 1 for i in range(1, base): position[i] = position[i - 1] + count_array[i - 1] output = [0] * len(array) for elem in array: output[position[elem // 10 ** col % base] - 1] = elem position[elem // 10 ** col % base] += 1 return output def radix_sort(arr): m = max(arr) for i in range(len(str(m))): arr = counting_sort_int(arr, 10, i) yield arr return arr
""" 121 / 121 test cases passed. Runtime: 32 ms Memory Usage: 14.9 MB """ class Solution: def countHillValley(self, nums: List[int]) -> int: stk = [nums[0], nums[1]] ans = 0 for num in nums[2:]: if num == stk[-1]: continue if stk[-2] < stk[-1] and stk[-1] > num: ans += 1 elif stk[-2] > stk[-1] and stk[-1] < num: ans += 1 stk.append(num) return ans
""" 121 / 121 test cases passed. Runtime: 32 ms Memory Usage: 14.9 MB """ class Solution: def count_hill_valley(self, nums: List[int]) -> int: stk = [nums[0], nums[1]] ans = 0 for num in nums[2:]: if num == stk[-1]: continue if stk[-2] < stk[-1] and stk[-1] > num: ans += 1 elif stk[-2] > stk[-1] and stk[-1] < num: ans += 1 stk.append(num) return ans
a = [] b = [] c = a a.append(1) b.append(2) c.append(3) print(f'{a=}, {b=}, {c=}') #print(a is c)
a = [] b = [] c = a a.append(1) b.append(2) c.append(3) print(f'a={a!r}, b={b!r}, c={c!r}')
class Element: mass = 0.0 def __init__(self, params): self.mass = params["mass"] def molar_mass_kilograms(self): return self.mass / 1000 hydrogen = Element({"mass": 1.00794})
class Element: mass = 0.0 def __init__(self, params): self.mass = params['mass'] def molar_mass_kilograms(self): return self.mass / 1000 hydrogen = element({'mass': 1.00794})
# Here I will attempt to count the occurences of a kmer in a patter def count_kmer(kmer, pattern): num_matches = 0 for num, _ in enumerate(kmer): window = kmer[num: (num+len(pattern))] if window == pattern: num_matches = num_matches + 1 return num_matches count_kmer("ACAACTATGCATACTATCGGGAACTATCCT", "ACTAT") #3 #problem set kmer_to_match = "GGAGGATTCTCCTGAAAAGGATTCAAGCGAGGATTCAAGATATCGCCGTACAGTAGGATTCTAACAGGATTCAGGATTCCTAGACCAAAAGGATTCGACTAGGATTCAGGATTCAGCAAGGATTCAGGATTCAGGATTCTTAGGATTCTGCAGGATTCAGGATTCGAGGATTCTGAGGATTCGCAAGCTCTAGGATTCAGGATTCTTAGGATTCAGGATTCAGAGGATTCAGGATTCAGGATTCGTATGAAAGGATTCCGGAGGATTCCGGGTAGGATTCAGGATTCAAGGATTCAAGGATTCAGGATTCAGGATTCCGAGGATTCAGGATTCGGAGGATTCTTAGGATTCCCAGGATTCACGGGCAGACCTAGGATTCAGGATTCGAAAGGATTCTTGAGGATTCAGGATTCAAAGGATTCCGAGGATTCTAGGATTCGAAGTACCGAGGATTCCCCAGGATTCATGTAGGATTCAGGATTCTAGGATTCGTACGAGGATTCAGGATTCCGTTCTAGGATTCCTTAGGATTCCAGGATTCAGGATTCGGAGGATTCAGAAGGATTCCAGGATTCCTCACAAAATAGGATTCGAGGATTCTAGAGGATTCGCAGGATTCTAAGGATTCATTGTCCAGGATTCTTAAGGATTCAGGATTCAGGATTCAGCCTAGGATTCAGGATTCGGAGGATTCATTCAGGATTCGATCGTGACAGAGGATTCACCAGGATTCTCAGGATTCTAGGATTCAGGATTCGAGGATTCTAGGATTCAAGGATTCAGGATTCGTTATTCACTGGGCAGGATTCAAGGATTCATAGGATTCAGACGCAGGATTCAGGATTCAGGATTCCAGGATTCTGTGAGGATTCATCGAAGGATTCATCCAATAGGATTCCTTTGAGGATTCTAGGATTCGGGCGACTTTAGCAGGATTCGGCCGAAGGATTCAGGATTCATGTTGGTCGCAGGATTCCGCATTTAGTATAGGATTCAGGATTCAGGATTCCGCAAGTTCTGAGGATTCGAGGATTCAGGATTC" pattern = "AGGATTCAG" count_kmer(kmer_to_match, pattern) #OK now I want to find the most frequent Kmer in the dataset def list_of_all_kmer_in_string(input_string, kmer_length): all_kmer = [] for num in range(0, len(input_string) - kmer_length): window = input_string[num: (num+kmer_length)] all_kmer.append(window) kmers_unique = list(set(all_kmer)) #this gives you unique kmers return kmers_unique test_new = list_of_all_kmer_in_string(kmer_to_match, 5) high_match = 0 for kmer in test_new: num_matches = count_kmer(kmer_to_match, kmer) if num_matches > high_match: freq_kmer = kmer high_match = num_matches # note that this is not efficient O^2 # instead it is better to use a frequency table. # so each KMER gets its own dictionary entry text = "GGAGGATTCTCCTGAAAAGGATTCAAGCGAGGATTCAAGATATCGCCGTACAGTAGGATTCTAACAGGATTCAGGATTCCTAGACCAAAAGGATTCGACTAGGATTCAGGATTCAGCAAGGATTCAGGATTCAGGATTCTTAGGATTCTGCAGGATTCAGGATTCGAGGATTCTGAGGATTCGCAAGCTCTAGGATTCAGGATTCTTAGGATTCAGGATTCAGAGGATTCAGGATTCAGGATTCGTATGAAAGGATTCCGGAGGATTCCGGGTAGGATTCAGGATTCAAGGATTCAAGGATTCAGGATTCAGGATTCCGAGGATTCAGGATTCGGAGGATTCTTAGGATTCCCAGGATTCACGGGCAGACCTAGGATTCAGGATTCGAAAGGATTCTTGAGGATTCAGGATTCAAAGGATTCCGAGGATTCTAGGATTCGAAGTACCGAGGATTCCCCAGGATTCATGTAGGATTCAGGATTCTAGGATTCGTACGAGGATTCAGGATTCCGTTCTAGGATTCCTTAGGATTCCAGGATTCAGGATTCGGAGGATTCAGAAGGATTCCAGGATTCCTCACAAAATAGGATTCGAGGATTCTAGAGGATTCGCAGGATTCTAAGGATTCATTGTCCAGGATTCTTAAGGATTCAGGATTCAGGATTCAGCCTAGGATTCAGGATTCGGAGGATTCATTCAGGATTCGATCGTGACAGAGGATTCACCAGGATTCTCAGGATTCTAGGATTCAGGATTCGAGGATTCTAGGATTCAAGGATTCAGGATTCGTTATTCACTGGGCAGGATTCAAGGATTCATAGGATTCAGACGCAGGATTCAGGATTCAGGATTCCAGGATTCTGTGAGGATTCATCGAAGGATTCATCCAATAGGATTCCTTTGAGGATTCTAGGATTCGGGCGACTTTAGCAGGATTCGGCCGAAGGATTCAGGATTCATGTTGGTCGCAGGATTCCGCATTTAGTATAGGATTCAGGATTCAGGATTCCGCAAGTTCTGAGGATTCGAGGATTCAGGATTC" def frequency_table(text, kmer_len): freq_map = {} nt = len(text) nk = kmer_len for i in range(0, nt-nk): pattern = text[i : i+nk] if not freq_map.get(pattern): freq_map[pattern] = 1 else: freq_map[pattern] = freq_map[pattern] + 1 return freq_map freq_map = frequency_table(text, 5) max(freq_map, key=freq_map.get) # this is the easy way to get the highest freq one test_pattern = "TATGCTAGGTCCAAGTCCAATATATGCTAGCTCTACGTCCAATATATGCTAGTCCAATAGTCTTCTTCCAATAGTCCAAGGTCTTCTCTCTACGGTCTTCTTATGCTAGCTCTACGCTCTACGTATGCTAGTCCAATACTCTACGTATGCTAGGTCCAAGGTCTTCTTATGCTAGGTCTTCTCTCTACGCTCTACGTATGCTAGTATGCTAGCTCTACGGTCCAAGCTCTACGTCCAATACTCTACGTATGCTAGGTCCAAGGTCTTCTGTCTTCTTCCAATATCCAATAGTCCAAGTATGCTAGGTCCAAGGTCTTCTGTCTTCTGTCCAAGGTCCAAGGTCCAAGCTCTACGGTCTTCTTATGCTAGCTCTACGTATGCTAGGTCCAAGTCCAATATCCAATATATGCTAGTCCAATATCCAATAGTCTTCTGTCTTCTCTCTACGCTCTACGGTCCAAGGTCCAAGTCCAATATATGCTAGGTCCAAGGTCTTCTTATGCTAGGTCTTCTTCCAATAGTCTTCTGTCCAAGTCCAATAGTCCAAGGTCTTCTGTCTTCTTATGCTAGTATGCTAGGTCTTCTTCCAATATCCAATATCCAATATCCAATAGTCCAAGCTCTACGTCCAATATATGCTAGTATGCTAGCTCTACGGTCCAAGTATGCTAGCTCTACGTCCAATAGTCTTCTTCCAATATATGCTAGCTCTACGGTCCAAGCTCTACGTCCAATAGTCTTCTTATGCTAGCTCTACGGTCCAAGGTCCAAGTATGCTAGGTCTTCTGTCCAAGTCCAATACTCTACGTATGCTAGGTCTTCTTATGCTAGGTCTTCTGTCTTCTCTCTACGGTCTTCTCTCTACGGTCTTCTCTCTACG" test_pattern_1 = "CTTCCCAAAGACTTCTCTGATGTAGCAAAGACTTCTCTCGCTTTGCCGGTCTCGAGGATGTAGCAAAGACTTCTCTAGACTTCTCTAGACTTCTCTCTTCCCAACTTCCCAAGTCTCGAGGATGTAGCAAGATGTAGCAACGCTTTGCCGCTTCCCAAGTCTCGAGAGACTTCTCTGTCTCGAGCTTCCCAACGCTTTGCCGGTCTCGAGGTCTCGAGCTTCCCAAGTCTCGAGCTTCCCAACGCTTTGCCGCTTCCCAAGTCTCGAGCTTCCCAACTTCCCAAGTCTCGAGGTCTCGAGCTTCCCAAAGACTTCTCTGTCTCGAGCTTCCCAAAGACTTCTCTCTTCCCAACGCTTTGCCGCTTCCCAACGCTTTGCCGGATGTAGCAAAGACTTCTCTCGCTTTGCCGCGCTTTGCCGGATGTAGCAAAGACTTCTCTAGACTTCTCTCTTCCCAACGCTTTGCCGAGACTTCTCTCTTCCCAAGATGTAGCAACGCTTTGCCGGTCTCGAGCGCTTTGCCGGATGTAGCAAGTCTCGAGCTTCCCAAGATGTAGCAAGTCTCGAGCGCTTTGCCGGATGTAGCAAAGACTTCTCTCTTCCCAAGTCTCGAGCTTCCCAAAGACTTCTCTAGACTTCTCTGTCTCGAGGATGTAGCAAGTCTCGAGCTTCCCAAAGACTTCTCTAGACTTCTCTAGACTTCTCTCTTCCCAACTTCCCAAGTCTCGAGGTCTCGAGGTCTCGAGGTCTCGAGGTCTCGAGGATGTAGCAACTTCCCAACTTCCCAAAGACTTCTCTAGACTTCTCTGATGTAGCAACTTCCCAACGCTTTGCCGGTCTCGAGAGACTTCTCTGATGTAGCAACTTCCCAAGATGTAGCAAGTCTCGAGGTCTCGAGCGCTTTGCCGGATGTAGCAAAGACTTCTCTAGACTTCTCTGATGTAGCAAGTCTCGAGGATGTAGCAAAGACTTCTCT" test_length = 11 freq_map = frequency_table(test_pattern_1, test_length) max_value = max(freq_map.values()) [k for k,v in freq_map.items() if v == max_value]
def count_kmer(kmer, pattern): num_matches = 0 for (num, _) in enumerate(kmer): window = kmer[num:num + len(pattern)] if window == pattern: num_matches = num_matches + 1 return num_matches count_kmer('ACAACTATGCATACTATCGGGAACTATCCT', 'ACTAT') kmer_to_match = 'GGAGGATTCTCCTGAAAAGGATTCAAGCGAGGATTCAAGATATCGCCGTACAGTAGGATTCTAACAGGATTCAGGATTCCTAGACCAAAAGGATTCGACTAGGATTCAGGATTCAGCAAGGATTCAGGATTCAGGATTCTTAGGATTCTGCAGGATTCAGGATTCGAGGATTCTGAGGATTCGCAAGCTCTAGGATTCAGGATTCTTAGGATTCAGGATTCAGAGGATTCAGGATTCAGGATTCGTATGAAAGGATTCCGGAGGATTCCGGGTAGGATTCAGGATTCAAGGATTCAAGGATTCAGGATTCAGGATTCCGAGGATTCAGGATTCGGAGGATTCTTAGGATTCCCAGGATTCACGGGCAGACCTAGGATTCAGGATTCGAAAGGATTCTTGAGGATTCAGGATTCAAAGGATTCCGAGGATTCTAGGATTCGAAGTACCGAGGATTCCCCAGGATTCATGTAGGATTCAGGATTCTAGGATTCGTACGAGGATTCAGGATTCCGTTCTAGGATTCCTTAGGATTCCAGGATTCAGGATTCGGAGGATTCAGAAGGATTCCAGGATTCCTCACAAAATAGGATTCGAGGATTCTAGAGGATTCGCAGGATTCTAAGGATTCATTGTCCAGGATTCTTAAGGATTCAGGATTCAGGATTCAGCCTAGGATTCAGGATTCGGAGGATTCATTCAGGATTCGATCGTGACAGAGGATTCACCAGGATTCTCAGGATTCTAGGATTCAGGATTCGAGGATTCTAGGATTCAAGGATTCAGGATTCGTTATTCACTGGGCAGGATTCAAGGATTCATAGGATTCAGACGCAGGATTCAGGATTCAGGATTCCAGGATTCTGTGAGGATTCATCGAAGGATTCATCCAATAGGATTCCTTTGAGGATTCTAGGATTCGGGCGACTTTAGCAGGATTCGGCCGAAGGATTCAGGATTCATGTTGGTCGCAGGATTCCGCATTTAGTATAGGATTCAGGATTCAGGATTCCGCAAGTTCTGAGGATTCGAGGATTCAGGATTC' pattern = 'AGGATTCAG' count_kmer(kmer_to_match, pattern) def list_of_all_kmer_in_string(input_string, kmer_length): all_kmer = [] for num in range(0, len(input_string) - kmer_length): window = input_string[num:num + kmer_length] all_kmer.append(window) kmers_unique = list(set(all_kmer)) return kmers_unique test_new = list_of_all_kmer_in_string(kmer_to_match, 5) high_match = 0 for kmer in test_new: num_matches = count_kmer(kmer_to_match, kmer) if num_matches > high_match: freq_kmer = kmer high_match = num_matches text = 'GGAGGATTCTCCTGAAAAGGATTCAAGCGAGGATTCAAGATATCGCCGTACAGTAGGATTCTAACAGGATTCAGGATTCCTAGACCAAAAGGATTCGACTAGGATTCAGGATTCAGCAAGGATTCAGGATTCAGGATTCTTAGGATTCTGCAGGATTCAGGATTCGAGGATTCTGAGGATTCGCAAGCTCTAGGATTCAGGATTCTTAGGATTCAGGATTCAGAGGATTCAGGATTCAGGATTCGTATGAAAGGATTCCGGAGGATTCCGGGTAGGATTCAGGATTCAAGGATTCAAGGATTCAGGATTCAGGATTCCGAGGATTCAGGATTCGGAGGATTCTTAGGATTCCCAGGATTCACGGGCAGACCTAGGATTCAGGATTCGAAAGGATTCTTGAGGATTCAGGATTCAAAGGATTCCGAGGATTCTAGGATTCGAAGTACCGAGGATTCCCCAGGATTCATGTAGGATTCAGGATTCTAGGATTCGTACGAGGATTCAGGATTCCGTTCTAGGATTCCTTAGGATTCCAGGATTCAGGATTCGGAGGATTCAGAAGGATTCCAGGATTCCTCACAAAATAGGATTCGAGGATTCTAGAGGATTCGCAGGATTCTAAGGATTCATTGTCCAGGATTCTTAAGGATTCAGGATTCAGGATTCAGCCTAGGATTCAGGATTCGGAGGATTCATTCAGGATTCGATCGTGACAGAGGATTCACCAGGATTCTCAGGATTCTAGGATTCAGGATTCGAGGATTCTAGGATTCAAGGATTCAGGATTCGTTATTCACTGGGCAGGATTCAAGGATTCATAGGATTCAGACGCAGGATTCAGGATTCAGGATTCCAGGATTCTGTGAGGATTCATCGAAGGATTCATCCAATAGGATTCCTTTGAGGATTCTAGGATTCGGGCGACTTTAGCAGGATTCGGCCGAAGGATTCAGGATTCATGTTGGTCGCAGGATTCCGCATTTAGTATAGGATTCAGGATTCAGGATTCCGCAAGTTCTGAGGATTCGAGGATTCAGGATTC' def frequency_table(text, kmer_len): freq_map = {} nt = len(text) nk = kmer_len for i in range(0, nt - nk): pattern = text[i:i + nk] if not freq_map.get(pattern): freq_map[pattern] = 1 else: freq_map[pattern] = freq_map[pattern] + 1 return freq_map freq_map = frequency_table(text, 5) max(freq_map, key=freq_map.get) test_pattern = 'TATGCTAGGTCCAAGTCCAATATATGCTAGCTCTACGTCCAATATATGCTAGTCCAATAGTCTTCTTCCAATAGTCCAAGGTCTTCTCTCTACGGTCTTCTTATGCTAGCTCTACGCTCTACGTATGCTAGTCCAATACTCTACGTATGCTAGGTCCAAGGTCTTCTTATGCTAGGTCTTCTCTCTACGCTCTACGTATGCTAGTATGCTAGCTCTACGGTCCAAGCTCTACGTCCAATACTCTACGTATGCTAGGTCCAAGGTCTTCTGTCTTCTTCCAATATCCAATAGTCCAAGTATGCTAGGTCCAAGGTCTTCTGTCTTCTGTCCAAGGTCCAAGGTCCAAGCTCTACGGTCTTCTTATGCTAGCTCTACGTATGCTAGGTCCAAGTCCAATATCCAATATATGCTAGTCCAATATCCAATAGTCTTCTGTCTTCTCTCTACGCTCTACGGTCCAAGGTCCAAGTCCAATATATGCTAGGTCCAAGGTCTTCTTATGCTAGGTCTTCTTCCAATAGTCTTCTGTCCAAGTCCAATAGTCCAAGGTCTTCTGTCTTCTTATGCTAGTATGCTAGGTCTTCTTCCAATATCCAATATCCAATATCCAATAGTCCAAGCTCTACGTCCAATATATGCTAGTATGCTAGCTCTACGGTCCAAGTATGCTAGCTCTACGTCCAATAGTCTTCTTCCAATATATGCTAGCTCTACGGTCCAAGCTCTACGTCCAATAGTCTTCTTATGCTAGCTCTACGGTCCAAGGTCCAAGTATGCTAGGTCTTCTGTCCAAGTCCAATACTCTACGTATGCTAGGTCTTCTTATGCTAGGTCTTCTGTCTTCTCTCTACGGTCTTCTCTCTACGGTCTTCTCTCTACG' test_pattern_1 = 'CTTCCCAAAGACTTCTCTGATGTAGCAAAGACTTCTCTCGCTTTGCCGGTCTCGAGGATGTAGCAAAGACTTCTCTAGACTTCTCTAGACTTCTCTCTTCCCAACTTCCCAAGTCTCGAGGATGTAGCAAGATGTAGCAACGCTTTGCCGCTTCCCAAGTCTCGAGAGACTTCTCTGTCTCGAGCTTCCCAACGCTTTGCCGGTCTCGAGGTCTCGAGCTTCCCAAGTCTCGAGCTTCCCAACGCTTTGCCGCTTCCCAAGTCTCGAGCTTCCCAACTTCCCAAGTCTCGAGGTCTCGAGCTTCCCAAAGACTTCTCTGTCTCGAGCTTCCCAAAGACTTCTCTCTTCCCAACGCTTTGCCGCTTCCCAACGCTTTGCCGGATGTAGCAAAGACTTCTCTCGCTTTGCCGCGCTTTGCCGGATGTAGCAAAGACTTCTCTAGACTTCTCTCTTCCCAACGCTTTGCCGAGACTTCTCTCTTCCCAAGATGTAGCAACGCTTTGCCGGTCTCGAGCGCTTTGCCGGATGTAGCAAGTCTCGAGCTTCCCAAGATGTAGCAAGTCTCGAGCGCTTTGCCGGATGTAGCAAAGACTTCTCTCTTCCCAAGTCTCGAGCTTCCCAAAGACTTCTCTAGACTTCTCTGTCTCGAGGATGTAGCAAGTCTCGAGCTTCCCAAAGACTTCTCTAGACTTCTCTAGACTTCTCTCTTCCCAACTTCCCAAGTCTCGAGGTCTCGAGGTCTCGAGGTCTCGAGGTCTCGAGGATGTAGCAACTTCCCAACTTCCCAAAGACTTCTCTAGACTTCTCTGATGTAGCAACTTCCCAACGCTTTGCCGGTCTCGAGAGACTTCTCTGATGTAGCAACTTCCCAAGATGTAGCAAGTCTCGAGGTCTCGAGCGCTTTGCCGGATGTAGCAAAGACTTCTCTAGACTTCTCTGATGTAGCAAGTCTCGAGGATGTAGCAAAGACTTCTCT' test_length = 11 freq_map = frequency_table(test_pattern_1, test_length) max_value = max(freq_map.values()) [k for (k, v) in freq_map.items() if v == max_value]
""" Problem Description: Cody was once understanding numbers, their squares and perfect squares from his teacher. A perfect square is a number that can be expressed as square of an integer. To check how much Cody understood the concept his teacher kept a test. He has to find the nearest perfect square of the given number N. Input: The first line of input consists of a single integer T denoting the number of test cases. The first line of each test case consists of single integer N. Output: For each test case print the nearest perfect square. Constraints: 1<=T<=100. 1<=N<=10^4. Sample Input: 2 1602 2 Sample Output: 40 1 """ t = int(input()) for i in range(t): n = int(input()) l = [] boo = True i = 1 while boo: i += 1 if i ** 2 <= n: l.append(i) else: l.append(i) boo = False if n == 2 or n == 1: print(1) elif l[-2] == n: print(n) else: if len(l) >= 3: print(l[-1]) if l[-1] ** 2 - n <= n - l[-2] ** 2 else print(l[-2])
""" Problem Description: Cody was once understanding numbers, their squares and perfect squares from his teacher. A perfect square is a number that can be expressed as square of an integer. To check how much Cody understood the concept his teacher kept a test. He has to find the nearest perfect square of the given number N. Input: The first line of input consists of a single integer T denoting the number of test cases. The first line of each test case consists of single integer N. Output: For each test case print the nearest perfect square. Constraints: 1<=T<=100. 1<=N<=10^4. Sample Input: 2 1602 2 Sample Output: 40 1 """ t = int(input()) for i in range(t): n = int(input()) l = [] boo = True i = 1 while boo: i += 1 if i ** 2 <= n: l.append(i) else: l.append(i) boo = False if n == 2 or n == 1: print(1) elif l[-2] == n: print(n) elif len(l) >= 3: print(l[-1]) if l[-1] ** 2 - n <= n - l[-2] ** 2 else print(l[-2])
#!/usr/bin/python # -*- coding:utf-8 -*- #Filename: range.py for i in [0, 1, 2, 3, 4, 5]: print (i ** 2) # >>> 0 # 1 # 4 # 9 # 16 # 25 for i in range(6): print (i ** 2)
for i in [0, 1, 2, 3, 4, 5]: print(i ** 2) for i in range(6): print(i ** 2)
if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) f = arr[0] p = -100000 for i in arr: if i>f: p=f f=i; elif i<f and i>p: p=i print(p)
if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) f = arr[0] p = -100000 for i in arr: if i > f: p = f f = i elif i < f and i > p: p = i print(p)
load( "//scala:scala_cross_version.bzl", _default_maven_server_urls = "default_maven_server_urls", ) load("//third_party/repositories:repositories.bzl", "repositories") def junit_repositories( maven_servers = _default_maven_server_urls(), fetch_sources = True): repositories( for_artifact_ids = [ "io_bazel_rules_scala_junit_junit", "io_bazel_rules_scala_org_hamcrest_hamcrest_core", ], fetch_sources = fetch_sources, maven_servers = maven_servers, ) native.bind( name = "io_bazel_rules_scala/dependency/junit/junit", actual = "@io_bazel_rules_scala_junit_junit//jar", ) native.bind( name = "io_bazel_rules_scala/dependency/hamcrest/hamcrest_core", actual = "@io_bazel_rules_scala_org_hamcrest_hamcrest_core//jar", )
load('//scala:scala_cross_version.bzl', _default_maven_server_urls='default_maven_server_urls') load('//third_party/repositories:repositories.bzl', 'repositories') def junit_repositories(maven_servers=_default_maven_server_urls(), fetch_sources=True): repositories(for_artifact_ids=['io_bazel_rules_scala_junit_junit', 'io_bazel_rules_scala_org_hamcrest_hamcrest_core'], fetch_sources=fetch_sources, maven_servers=maven_servers) native.bind(name='io_bazel_rules_scala/dependency/junit/junit', actual='@io_bazel_rules_scala_junit_junit//jar') native.bind(name='io_bazel_rules_scala/dependency/hamcrest/hamcrest_core', actual='@io_bazel_rules_scala_org_hamcrest_hamcrest_core//jar')
"""Provide a decorator to register event handlers.""" def socketio_handler(event, namespace=None): """Register a socketio handler via decorator.""" def wrapper(func): """Decorate a ws event handler.""" # pylint: disable=protected-access func._ws_event = event func._ws_namespace = namespace return func return wrapper def partial_coro(func, *args, **keywords): """Return a partial coroutine.""" # https://docs.python.org/3/library/functools.html#functools.partial async def wrapper(*fargs, **fkeywords): """Wrap the coroutine function.""" newkeywords = keywords.copy() newkeywords.update(fkeywords) return await func(*args, *fargs, **newkeywords) wrapper.func = func wrapper.args = args wrapper.keywords = keywords return wrapper
"""Provide a decorator to register event handlers.""" def socketio_handler(event, namespace=None): """Register a socketio handler via decorator.""" def wrapper(func): """Decorate a ws event handler.""" func._ws_event = event func._ws_namespace = namespace return func return wrapper def partial_coro(func, *args, **keywords): """Return a partial coroutine.""" async def wrapper(*fargs, **fkeywords): """Wrap the coroutine function.""" newkeywords = keywords.copy() newkeywords.update(fkeywords) return await func(*args, *fargs, **newkeywords) wrapper.func = func wrapper.args = args wrapper.keywords = keywords return wrapper
class DynamicalSystem: def __init__(self, a1, b1, c1, alpha1, beta1, a2, b2, c2, alpha2, beta2): self.a1 = a1 self.b1 = b1 self.c1 = c1 self.alpha1 = alpha1 self.beta1 = beta1 self.a2 = a2 self.b2 = b2 self.c2 = c2 self.alpha2 = alpha2 self.beta2 = beta2 def eval(self, point, t): [x, y] = point x2 = x*x xy = x*y y2 = y*y dxdt = self.a1*x2 + self.b1*xy + self.c1*y2 + self.alpha1*x + self.beta1*y dydt = self.a2*x2 + self.b2*xy + self.c2*y2 + self.alpha2*x + self.beta2*y return [dxdt, dydt]
class Dynamicalsystem: def __init__(self, a1, b1, c1, alpha1, beta1, a2, b2, c2, alpha2, beta2): self.a1 = a1 self.b1 = b1 self.c1 = c1 self.alpha1 = alpha1 self.beta1 = beta1 self.a2 = a2 self.b2 = b2 self.c2 = c2 self.alpha2 = alpha2 self.beta2 = beta2 def eval(self, point, t): [x, y] = point x2 = x * x xy = x * y y2 = y * y dxdt = self.a1 * x2 + self.b1 * xy + self.c1 * y2 + self.alpha1 * x + self.beta1 * y dydt = self.a2 * x2 + self.b2 * xy + self.c2 * y2 + self.alpha2 * x + self.beta2 * y return [dxdt, dydt]
class Group(object): def __init__(self, _name): self.name = _name self.groups = [] self.users = [] def add_group(self, group): self.groups.append(group) def add_user(self, user): self.users.append(user) def get_groups(self): return self.groups def get_users(self): return self.users def get_name(self): return self.name def __repr__(self): return f"Group(name: {self.name},\n\tusers: {self.users},\n\tgroups:{self.groups})" """Checks if the user is in the group. If found, returns Ture, else, calls subgroups recursively.""" def is_user_in_group(user, group): if user in group.get_users(): return True for subgroup in group.get_groups(): #print("checking group-- ", subgroup.get_name()) return is_user_in_group(user, subgroup) return False """ verify the data """ def run_test_data(): parent = Group("parent") child = Group("child") sub_child = Group("subchild") sub_child_user = "sub_child_user" sub_child.add_user(sub_child_user) child.add_group(sub_child) parent.add_group(child) print("\nCheck if user in group - {}".format(is_user_in_group(sub_child_user, parent))) print("\nCheck if user in group - {}".format(is_user_in_group('youngqueenz',parent))) #Returns false cos sub_child_use doesn't exist print("\nCheck if user in group - {}".format(is_user_in_group('',parent))) #Returns false cos input is null print("\nParent Group:") print(parent) run_test_data()
class Group(object): def __init__(self, _name): self.name = _name self.groups = [] self.users = [] def add_group(self, group): self.groups.append(group) def add_user(self, user): self.users.append(user) def get_groups(self): return self.groups def get_users(self): return self.users def get_name(self): return self.name def __repr__(self): return f'Group(name: {self.name},\n\tusers: {self.users},\n\tgroups:{self.groups})' 'Checks if the user is in the group. If found, returns Ture, else, calls subgroups recursively.' def is_user_in_group(user, group): if user in group.get_users(): return True for subgroup in group.get_groups(): return is_user_in_group(user, subgroup) return False '\n verify the data\n' def run_test_data(): parent = group('parent') child = group('child') sub_child = group('subchild') sub_child_user = 'sub_child_user' sub_child.add_user(sub_child_user) child.add_group(sub_child) parent.add_group(child) print('\nCheck if user in group - {}'.format(is_user_in_group(sub_child_user, parent))) print('\nCheck if user in group - {}'.format(is_user_in_group('youngqueenz', parent))) print('\nCheck if user in group - {}'.format(is_user_in_group('', parent))) print('\nParent Group:') print(parent) run_test_data()
#WAP to read two numbers from the keyboard and display the larger one on the screen. num1 = input("enter the number one") num2 = input("enter the number two") if(num1>num2): largest = num1 print("number is ", largest) else: largest = num2 print("number is ",largest)
num1 = input('enter the number one') num2 = input('enter the number two') if num1 > num2: largest = num1 print('number is ', largest) else: largest = num2 print('number is ', largest)
__all__ = [ "bgl_preprocessor", "open_source_logs", ]
__all__ = ['bgl_preprocessor', 'open_source_logs']
def minesweeper(matrix): row = len(matrix) col = len(matrix[0]) def neighbouring_squares(i, j): return sum( matrix[x][y] for x in range(i - 1, i + 2) if 0 <= x < row for y in range(j - 1, j + 2) if 0 <= y < col if i != x or j != y ) return [[neighbouring_squares(i, j) for j in range(col)] for i in range(row)]
def minesweeper(matrix): row = len(matrix) col = len(matrix[0]) def neighbouring_squares(i, j): return sum((matrix[x][y] for x in range(i - 1, i + 2) if 0 <= x < row for y in range(j - 1, j + 2) if 0 <= y < col if i != x or j != y)) return [[neighbouring_squares(i, j) for j in range(col)] for i in range(row)]
ASSEMBLY_HUMAN = "Homo_sapiens.GRCh38.104" ASSEMBLY_MOUSE = "Mus_musculus.GRCm39.104" CELLTYPES = ["adventitial cell", "endothelial cell", "acinar cell", "pancreatic PP cell", "type B pancreatic cell"] CL_VERSION = "v2021-08-10"
assembly_human = 'Homo_sapiens.GRCh38.104' assembly_mouse = 'Mus_musculus.GRCm39.104' celltypes = ['adventitial cell', 'endothelial cell', 'acinar cell', 'pancreatic PP cell', 'type B pancreatic cell'] cl_version = 'v2021-08-10'
'''https://leetcode.com/problems/design-add-and-search-words-data-structure/ 211. Design Add and Search Words Data Structure Medium 3595 150 Add to List Share Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: WordDictionary() Initializes the object. void addWord(word) Adds word to the data structure, it can be matched later. bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter. Example: Input ["WordDictionary","addWord","addWord","addWord","search","search","search","search"] [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] Output [null,null,null,null,false,true,true,true] Explanation WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord("bad"); wordDictionary.addWord("dad"); wordDictionary.addWord("mad"); wordDictionary.search("pad"); // return False wordDictionary.search("bad"); // return True wordDictionary.search(".ad"); // return True wordDictionary.search("b.."); // return True Constraints: 1 <= word.length <= 500 word in addWord consists lower-case English letters. word in search consist of '.' or lower-case English letters. At most 50000 calls will be made to addWord and search.''' class TrieNode(): def __init__(self): self.children = collections.defaultdict(TrieNode) self.isWord = False class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def addWord(self, word: str) -> None: """ Adds a word into the data structure. """ node = self.root for w in word: node = node.children[w] node.isWord = True def search(self, word: str) -> bool: """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. """ node = self.root self.res = False self.dfs(node, word) return self.res def dfs(self, node, word): if not word: if node.isWord: self.res = True return if word[0] == ".": for n in node.children.values(): self.dfs(n, word[1:]) else: node = node.children.get(word[0]) if not node: return self.dfs(node, word[1:]) # Your WordDictionary object will be instantiated and called as such: # obj = WordDictionary() # obj.addWord(word) # param_2 = obj.search(word)
"""https://leetcode.com/problems/design-add-and-search-words-data-structure/ 211. Design Add and Search Words Data Structure Medium 3595 150 Add to List Share Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: WordDictionary() Initializes the object. void addWord(word) Adds word to the data structure, it can be matched later. bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter. Example: Input ["WordDictionary","addWord","addWord","addWord","search","search","search","search"] [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] Output [null,null,null,null,false,true,true,true] Explanation WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord("bad"); wordDictionary.addWord("dad"); wordDictionary.addWord("mad"); wordDictionary.search("pad"); // return False wordDictionary.search("bad"); // return True wordDictionary.search(".ad"); // return True wordDictionary.search("b.."); // return True Constraints: 1 <= word.length <= 500 word in addWord consists lower-case English letters. word in search consist of '.' or lower-case English letters. At most 50000 calls will be made to addWord and search.""" class Trienode: def __init__(self): self.children = collections.defaultdict(TrieNode) self.isWord = False class Worddictionary: def __init__(self): """ Initialize your data structure here. """ self.root = trie_node() def add_word(self, word: str) -> None: """ Adds a word into the data structure. """ node = self.root for w in word: node = node.children[w] node.isWord = True def search(self, word: str) -> bool: """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. """ node = self.root self.res = False self.dfs(node, word) return self.res def dfs(self, node, word): if not word: if node.isWord: self.res = True return if word[0] == '.': for n in node.children.values(): self.dfs(n, word[1:]) else: node = node.children.get(word[0]) if not node: return self.dfs(node, word[1:])
"""Module that defines varios enums.""" class Enum: __names = {} @classmethod def name(cls, state): if not cls.__names: cls.__names = { value: key for key, value in cls.__dict__.items() if isinstance(value, int) } return cls.__names[state] class VivintDeviceAttributes(Enum): """Devine generic vivint device attributes for humans.""" DeviceType = 't' Id = '_id' Name = 'n' class AlarmPanelAttributes(VivintDeviceAttributes): """Define alarm panel's attributes for humans.""" Devices = 'd' PanelId = 'panid' PartitionId = 'parid' State = 's' class ArmedStates(Enum): """Define all possible alarm states.""" Disarmed = 0 ArmingAwayInExitDelay = 1 ArmingStayInExitDelay = 2 ArmedStay = 3 ArmedAway = 4 ArmedStayInEntryDelay = 5 ArmedAwayInEntryDelay = 6 Alarm = 7 AlarmFire = 8 Disabled = 11 WalkTest = 12 class CameraAttributes(VivintDeviceAttributes): """Define camera's attributes for humans.""" CameraIPAddress = 'caip' CameraPrivacy = 'cpri' CameraThumbnailDate = 'ctd' CaptureClipOnMotion = 'ccom' Online = 'ol' WirelessSignalStrenght = 'wiss' class DoorLockAttributes(VivintDeviceAttributes): """Define door lock's attributes for humans.""" BatteryLevel = 'bl' Id = '_id' LowBattery = 'lb' OperationCount = 'opc' OperationFaultCode = 'opfc' NodeOnline = 'nonl' State = 's' class DeviceTypes(Enum): """Vivint's supported device types.""" Camera = 'camera_device' DoorLock = 'door_lock_device' LightModule = 'multilevel_switch_device' Thermostat = 'thermostat_device' TouchPanel = 'primary_touch_link_device' WirelessSensor = 'wireless_sensor' class WirelessSensorAttributes(VivintDeviceAttributes): """Wireless Sensor's attributes for humans.""" BatteryLevel = 'bl' EquipmentCode = 'ec' IdBypassed = 'b' LowBattery = 'lb' SerialNumber = 'ser32' State = 's' class AuthUserAttributes(Enum): """AuthUser attributes.""" IdToken = 'id_token' IsReadOnly = 'is_read_only' KeepSignedIn = 'keep_signed_in' RelayServer = 'rs' Users = 'u' class UsersAttributes(Enum): DocumentSequence = 'DocumentSequence' Email = 'e' Ghome = 'ghome' GroupIds = 'grpid' Id = '_id' MessageBroadcastChannel = 'mbc' Name = 'n' PingId = 'pngid' RestrictedSystem = 'rsystem' SmarthomeSystem = 'smarthomesystem' Settings = 'stg' System = 'system' Timestamp = 'ts' class PubNumMessageAttributes(Enum): Data = 'da' Devices = 'd' Operation = 'op' PanelId = 'panid' PartitionId = 'parid' Type = 't'
"""Module that defines varios enums.""" class Enum: __names = {} @classmethod def name(cls, state): if not cls.__names: cls.__names = {value: key for (key, value) in cls.__dict__.items() if isinstance(value, int)} return cls.__names[state] class Vivintdeviceattributes(Enum): """Devine generic vivint device attributes for humans.""" device_type = 't' id = '_id' name = 'n' class Alarmpanelattributes(VivintDeviceAttributes): """Define alarm panel's attributes for humans.""" devices = 'd' panel_id = 'panid' partition_id = 'parid' state = 's' class Armedstates(Enum): """Define all possible alarm states.""" disarmed = 0 arming_away_in_exit_delay = 1 arming_stay_in_exit_delay = 2 armed_stay = 3 armed_away = 4 armed_stay_in_entry_delay = 5 armed_away_in_entry_delay = 6 alarm = 7 alarm_fire = 8 disabled = 11 walk_test = 12 class Cameraattributes(VivintDeviceAttributes): """Define camera's attributes for humans.""" camera_ip_address = 'caip' camera_privacy = 'cpri' camera_thumbnail_date = 'ctd' capture_clip_on_motion = 'ccom' online = 'ol' wireless_signal_strenght = 'wiss' class Doorlockattributes(VivintDeviceAttributes): """Define door lock's attributes for humans.""" battery_level = 'bl' id = '_id' low_battery = 'lb' operation_count = 'opc' operation_fault_code = 'opfc' node_online = 'nonl' state = 's' class Devicetypes(Enum): """Vivint's supported device types.""" camera = 'camera_device' door_lock = 'door_lock_device' light_module = 'multilevel_switch_device' thermostat = 'thermostat_device' touch_panel = 'primary_touch_link_device' wireless_sensor = 'wireless_sensor' class Wirelesssensorattributes(VivintDeviceAttributes): """Wireless Sensor's attributes for humans.""" battery_level = 'bl' equipment_code = 'ec' id_bypassed = 'b' low_battery = 'lb' serial_number = 'ser32' state = 's' class Authuserattributes(Enum): """AuthUser attributes.""" id_token = 'id_token' is_read_only = 'is_read_only' keep_signed_in = 'keep_signed_in' relay_server = 'rs' users = 'u' class Usersattributes(Enum): document_sequence = 'DocumentSequence' email = 'e' ghome = 'ghome' group_ids = 'grpid' id = '_id' message_broadcast_channel = 'mbc' name = 'n' ping_id = 'pngid' restricted_system = 'rsystem' smarthome_system = 'smarthomesystem' settings = 'stg' system = 'system' timestamp = 'ts' class Pubnummessageattributes(Enum): data = 'da' devices = 'd' operation = 'op' panel_id = 'panid' partition_id = 'parid' type = 't'
test = { 'name': 'Question 1', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> read_line('3') 3 >>> read_line('-123') -123 >>> read_line('1.25') 1.25 >>> read_line('true') True >>> read_line('(a)') Pair('a', nil) >>> read_line(')') SyntaxError """, 'hidden': False, 'locked': False }, { 'code': r""" >>> read_line(" (quote x) ") Pair('quote', Pair('x', nil)) >>> read_line(" 'x ") Pair('quote', Pair('x', nil)) >>> read_line(" (a b) ") Pair('a', Pair('b', nil)) >>> read_line(" '(a b) ") Pair('quote', Pair(Pair('a', Pair('b', nil)), nil)) >>> read_line(" '((a)) ") Pair('quote', Pair(Pair(Pair('a', nil), nil), nil)) """, 'hidden': False, 'locked': False }, { 'code': r""" >>> read_line("(a (b 'c))") Pair('a', Pair(Pair('b', Pair(Pair('quote', Pair('c', nil)), nil)), nil)) >>> read_line("(a (b '(c d)))") Pair('a', Pair(Pair('b', Pair(Pair('quote', Pair(Pair('c', Pair('d', nil)), nil)), nil)), nil)) >>> read_line("')") SyntaxError """, 'hidden': False, 'locked': False } ], 'scored': True, 'setup': r""" >>> from scheme_reader import * """, 'teardown': '', 'type': 'doctest' } ] }
test = {'name': 'Question 1', 'points': 1, 'suites': [{'cases': [{'code': "\n >>> read_line('3')\n 3\n >>> read_line('-123')\n -123\n >>> read_line('1.25')\n 1.25\n >>> read_line('true')\n True\n >>> read_line('(a)')\n Pair('a', nil)\n >>> read_line(')')\n SyntaxError\n ", 'hidden': False, 'locked': False}, {'code': '\n >>> read_line(" (quote x) ")\n Pair(\'quote\', Pair(\'x\', nil))\n >>> read_line(" \'x ")\n Pair(\'quote\', Pair(\'x\', nil))\n >>> read_line(" (a b) ")\n Pair(\'a\', Pair(\'b\', nil))\n >>> read_line(" \'(a b) ")\n Pair(\'quote\', Pair(Pair(\'a\', Pair(\'b\', nil)), nil))\n >>> read_line(" \'((a)) ")\n Pair(\'quote\', Pair(Pair(Pair(\'a\', nil), nil), nil))\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> read_line("(a (b \'c))")\n Pair(\'a\', Pair(Pair(\'b\', Pair(Pair(\'quote\', Pair(\'c\', nil)), nil)), nil))\n >>> read_line("(a (b \'(c d)))")\n Pair(\'a\', Pair(Pair(\'b\', Pair(Pair(\'quote\', Pair(Pair(\'c\', Pair(\'d\', nil)), nil)), nil)), nil))\n >>> read_line("\')")\n SyntaxError\n ', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '\n >>> from scheme_reader import *\n ', 'teardown': '', 'type': 'doctest'}]}
CONFIG_DIR = '__config__' DATA_ROOT_DIR = '__data__' RESULTS_ROOT_DIR = '__results__' TB_DIR = '__runs__' WEIGHTS_DIR = '__weights__' NOISE_ROOT_DIR = "__noise__"
config_dir = '__config__' data_root_dir = '__data__' results_root_dir = '__results__' tb_dir = '__runs__' weights_dir = '__weights__' noise_root_dir = '__noise__'
# Map source standard name to command code # Note that the source names may be aliased in the device # The names that come back from the device in a feedback # message are the aliases ROTEL_RSP1570_SOURCES = { " CD": "SOURCE_CD", "TUNER": "SOURCE_TUNER", "TAPE": "SOURCE_TAPE", "VIDEO 1": "SOURCE_VIDEO_1", "VIDEO 2": "SOURCE_VIDEO_2", "VIDEO 3": "SOURCE_VIDEO_3", "VIDEO 4": "SOURCE_VIDEO_4", "VIDEO 5": "SOURCE_VIDEO_5", "MULTI": "SOURCE_MULTI_INPUT", }
rotel_rsp1570_sources = {' CD': 'SOURCE_CD', 'TUNER': 'SOURCE_TUNER', 'TAPE': 'SOURCE_TAPE', 'VIDEO 1': 'SOURCE_VIDEO_1', 'VIDEO 2': 'SOURCE_VIDEO_2', 'VIDEO 3': 'SOURCE_VIDEO_3', 'VIDEO 4': 'SOURCE_VIDEO_4', 'VIDEO 5': 'SOURCE_VIDEO_5', 'MULTI': 'SOURCE_MULTI_INPUT'}
class Test(object): """ @cvar some: some variable @type some: C{str} """ some = 'hello' def __init__(self): self.some1 = 10 def q(self, another): """ @param another: another variable @type another: C{str} """ pass
class Test(object): """ @cvar some: some variable @type some: C{str} """ some = 'hello' def __init__(self): self.some1 = 10 def q(self, another): """ @param another: another variable @type another: C{str} """ pass
""" Implementation of Bubble Sort """ def bubble_sort(arr): for i in range(len(arr)): for j in range(len(arr) - i - 1): if j < arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] print(arr) return arr test_arr_1 = [14, 78, 2587, 3, 687, 21] test_arr_2 = [85, 14, 36, 6 , 18, 55] bubble_sort(test_arr_1)
""" Implementation of Bubble Sort """ def bubble_sort(arr): for i in range(len(arr)): for j in range(len(arr) - i - 1): if j < arr[j + 1]: (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]) print(arr) return arr test_arr_1 = [14, 78, 2587, 3, 687, 21] test_arr_2 = [85, 14, 36, 6, 18, 55] bubble_sort(test_arr_1)
#!/usr/bin/env python3 # Print out all the codons for the sequence below in reading frame 1 # Use a 'for' loop dna = 'ATAGCGAATATCTCTCATGAGAGGGAA' ''' #for 1 frame for i in range(0, len(dna), 3): #range(start letter, lenth of seq, print 3 @ a time) codon = (dna[i:i+3]) print(codon) #f1 for i in range(1, len(dna)-2, 3): codon = (dna[i:i+3]) print(codon) ''' #for all frames step = 3 for f in range(46): #for number of ranges print('frame', f) for i in range(f, len(dna) -step +1, step): #generic: len(dna) -k +2 codon = dna[i:i+step] #define codon in case of loop print(codon) #for kmers. you can change k to any number to fit any window size k = 4 for i in range(0, len(dna) -k+1): kmer = dna [i:i+4] print(kmer) """ frame 0 ATA GCG AAT ATC TCT CAT GAG AGG GAA frame 1 TAG CGA ATA TCT CTC ATG AGA GGG """
dna = 'ATAGCGAATATCTCTCATGAGAGGGAA' '\n#for 1 frame\nfor i in range(0, len(dna), 3): #range(start letter, lenth of seq, print 3 @ a time)\n codon = (dna[i:i+3])\n print(codon)\n\n#f1\nfor i in range(1, len(dna)-2, 3):\n codon = (dna[i:i+3])\n print(codon)\n' step = 3 for f in range(46): print('frame', f) for i in range(f, len(dna) - step + 1, step): codon = dna[i:i + step] print(codon) k = 4 for i in range(0, len(dna) - k + 1): kmer = dna[i:i + 4] print(kmer) '\nframe 0\nATA\nGCG\nAAT\nATC\nTCT\nCAT\nGAG\nAGG\nGAA\n\nframe 1\nTAG\nCGA\nATA\nTCT\nCTC\nATG\nAGA\nGGG\n'
""" Leetcode 12 - Interger to Roman https://leetcode.com/problems/integer-to-roman/ 1. Time: O(1) Memory: O(1) """ class Solution1: """ 1. MINE | Straight-Forward """ def int_to_roman(self, num): if num is None or num == 0: return '' int_roman_pairs = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')] res = '' for value, roman in int_roman_pairs: if num >= value: res += num // value * roman num -= num // value * value elif num == 0: return res return res if __name__ == '__main__': num = 300 res = Solution1().int_to_roman(num) print(res)
""" Leetcode 12 - Interger to Roman https://leetcode.com/problems/integer-to-roman/ 1. Time: O(1) Memory: O(1) """ class Solution1: """ 1. MINE | Straight-Forward """ def int_to_roman(self, num): if num is None or num == 0: return '' int_roman_pairs = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')] res = '' for (value, roman) in int_roman_pairs: if num >= value: res += num // value * roman num -= num // value * value elif num == 0: return res return res if __name__ == '__main__': num = 300 res = solution1().int_to_roman(num) print(res)
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'chromium', 'depot_tools/bot_update', 'depot_tools/gclient', 'file', 'gsutil', 'recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/python', 'recipe_engine/raw_io', 'recipe_engine/step', ] def linux_builder_steps(api): build_properties = api.properties.legacy() # checkout DrMemory step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "drmemory" soln.url = "https://github.com/DynamoRIO/drmemory.git" soln.custom_deps = {"drmemory/dynamorio": "https://github.com/DynamoRIO/dynamorio.git", "tools/buildbot": "https://github.com/DynamoRIO/buildbot.git"} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # get buildnumber step; no longer needed # Package DrMemory step api.step("Package Dr. Memory", ["ctest", "-VV", "-S", str(api.path["checkout"].join("package.cmake")) + ",build=0x" + build_properties["got_revision"][:7] + ";drmem_only"]) # find package file step; no longer necessary # upload drmemory build step api.gsutil.upload("DrMemory-Linux-*" + build_properties["got_revision"][ :7] + ".tar.gz", "chromium-drmemory-builds", "builds/") def linux_lucid_x64_drm_steps(api): build_properties = api.properties.legacy() # checkout DrMemory step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "drmemory" soln.url = "https://github.com/DynamoRIO/drmemory.git" soln.custom_deps = {"drmemory/dynamorio": "https://github.com/DynamoRIO/dynamorio.git", "tools/buildbot": "https://github.com/DynamoRIO/buildbot.git"} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # Dr. Memory ctest step api.step( "Dr. Memory ctest", ["ctest", "--timeout", "60", "-VV", "-S", str(api.path["checkout"].join("tests", "runsuite.cmake")) + ",drmemory_only;long;build=0x" + build_properties["got_revision"][:7] ]) # Prepare to pack test results step; null converted # Pack test results step api.step("Pack test results", ['7z', 'a', '-xr!*.pdb', "testlogs_r" + build_properties["got_revision"] + "_b" + str(build_properties["buildnumber"]) + ".7z", 'build_drmemory-dbg-32/logs', 'build_drmemory-dbg-32/Testing/Temporary', 'build_drmemory-rel-32/logs', 'build_drmemory-rel-32/Testing/Temporary', 'build_drmemory-dbg-64/logs', 'build_drmemory-dbg-64/Testing/Temporary', 'build_drmemory-rel-64/logs', 'build_drmemory-rel-64/Testing/Temporary', 'xml:results']) # upload drmemory test logs step api.gsutil.upload("testlogs_r" + build_properties["got_revision"] + "_b" + str(api.properties[ "buildnumber"]) + ".7z", "chromium-drmemory-builds", "testlogs/from_%s" % api.properties["buildername"]) def win_vista_x64_drm_steps(api): build_properties = api.properties.legacy() # checkout DrMemory step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "drmemory" soln.url = "https://github.com/DynamoRIO/drmemory.git" soln.custom_deps = {"drmemory/dynamorio": "https://github.com/DynamoRIO/dynamorio.git", "tools/buildbot": "https://github.com/DynamoRIO/buildbot.git"} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # clear tools directory step; null converted # update tools step; null converted # unpack tools step; generic ShellCommand converted api.step("unpack tools", [api.path["slave_build"].join('tools', 'buildbot', 'bot_tools', 'unpack.bat')], env={}, cwd=api.path[ "slave_build"].join('tools', 'buildbot', 'bot_tools')) # windows Dr. Memory ctest step api.step("Dr. Memory ctest", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'ctest', '--timeout', '60', '-VV', '-S', str(api.path["checkout"].join("tests", "runsuite.cmake")) + ",drmemory_only;long;build=" + str(build_properties["buildnumber"])]) # Checkout TSan tests step api.step("Checkout TSan tests", ['svn', 'checkout', '--force', 'http://data-race-test.googlecode.com/svn/trunk/', api.path["slave_build"].join("tsan")]) # Build TSan tests step api.step("Build TSan Tests", ['E:\\b\\build\\scripts\\slave\\drmemory\\build_env.bat', 'make', '-C', api.path["slave_build"].join("tsan", "unittest")], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools"), "CYGWIN": "nodosfilewarning"}) # Dr. Memory TSan test step api.step( "dbg full TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "dbg light TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "-light", "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "rel full TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "rel light TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "-light", "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "dbg full nosyms TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Prepare to pack test results step; null converted # Pack test results step api.step("Pack test results", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"),'7z', 'a', '-xr!*.pdb', "testlogs_r" + build_properties["got_revision"] + "_b" + str(build_properties["buildnumber"]) + ".7z", 'build_drmemory-dbg-32/logs', 'build_drmemory-dbg-32/Testing/Temporary', 'build_drmemory-rel-32/logs', 'build_drmemory-rel-32/Testing/Temporary', 'build_drmemory-dbg-64/logs', 'build_drmemory-dbg-64/Testing/Temporary', 'build_drmemory-rel-64/logs', 'build_drmemory-rel-64/Testing/Temporary', 'xmlresults'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # upload drmemory test logs step api.gsutil.upload("testlogs_r" + build_properties["got_revision"] + "_b" + str(api.properties[ "buildnumber"]) + ".7z", "chromium-drmemory-builds", "testlogs/from_%s" % api.properties["buildername"]) def mac_mavericks_x64_DR_steps(api): build_properties = api.properties.legacy() # checkout DynamiRIO step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "dynamorio" soln.url = "https://github.com/DynamoRIO/dynamorio.git" api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # pre-commit suite step api.step("pre-commit suite", ['ctest', '--timeout', '120', '-VV', '-S', api.path[ "checkout"].join("suite", "runsuite.cmake")], cwd=api.path["slave_build"], ok_ret="all") def linux_cr_builder_steps(api): build_properties = api.properties.legacy() # update scripts step; implicitly run by recipe engine. # bot_update step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "src" soln.url = "https://chromium.googlesource.com/chromium/src.git" soln.custom_deps = {'src/third_party/WebKit/LayoutTests': None} soln.custom_vars = {'webkit_trunk': 'http://src.chromium.org/blink/trunk', 'googlecode_url': 'http://%s.googlecode.com/svn', 'nacl_trunk': 'http://src.chromium.org/native_client/trunk', 'sourceforge_url': 'https://svn.code.sf.net/p/%(repo)s/code', 'llvm_url': 'http://llvm.org/svn/llvm-project'} src_cfg.got_revision_mapping.update( {'src': 'got_revision', 'src/third_party/WebKit': 'got_webkit_revision', 'src/tools/swarming_client': 'got_swarming_client_revision', 'src/v8': 'got_v8_revision'}) api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # gclient revert step; made unnecessary by bot_update # gclient update step; made unnecessary by bot_update # gclient runhooks wrapper step env = {'CHROMIUM_GYP_SYNTAX_CHECK': '1', 'GYP_GENERATORS': 'ninja', 'DEPOT_TOOLS_UPDATE': '0', 'GYP_DEFINES': 'build_for_tool=drmemory component=shared_library', 'LANDMINES_VERBOSE': '1'} api.python("gclient runhooks wrapper", api.path["build"].join("scripts", "slave", "runhooks_wrapper.py"), env=env) # cleanup_temp step api.chromium.cleanup_temp() # compile.py step args = ['--target', 'Release', '--build-tool=ninja', '--compiler=goma', 'content_shell', 'base_unittests', 'browser_tests', 'crypto_unittests', 'ipc_tests', 'media_unittests', 'net_unittests', 'printing_unittests', 'remoting_unittests', 'sql_unittests', 'unit_tests', 'url_unittests'] if 'clobber' in api.properties: args.append("--clobber") api.python("compile", api.path["build"].join("scripts", "slave", "compile.py"), args=args) def mac_builder_DR_steps(api): build_properties = api.properties.legacy() # checkout DynamiRIO step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "dynamorio" soln.url = "https://github.com/DynamoRIO/dynamorio.git" api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # get buildnumber step; no longer needed # Package DynamoRIO step api.step("Package DynamoRIO", ["ctest", "-VV", "-S", str(api.path["checkout"].join("make", "package.cmake")) + ",build=0x" + build_properties["revision"][:7]]) # find package file step; no longer necessary # upload dynamorio package api.gsutil.upload("DynamoRIO-MacOS-*" + build_properties["got_revision"][ :7] + ".tar.gz", "chromium-dynamorio", "builds/") def win_xp_drm_steps(api): build_properties = api.properties.legacy() # checkout DrMemory step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "drmemory" soln.url = "https://github.com/DynamoRIO/drmemory.git" soln.custom_deps = {"drmemory/dynamorio": "https://github.com/DynamoRIO/dynamorio.git", "tools/buildbot": "https://github.com/DynamoRIO/buildbot.git"} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # clear tools directory step; null converted # update tools step; null converted # unpack tools step; generic ShellCommand converted api.step("unpack tools", [api.path["slave_build"].join('tools', 'buildbot', 'bot_tools', 'unpack.bat')], env={}, cwd=api.path[ "slave_build"].join('tools', 'buildbot', 'bot_tools')) # windows Dr. Memory ctest step api.step("Dr. Memory ctest", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'ctest', '--timeout', '60', '-VV', '-S', str(api.path["checkout"].join("tests", "runsuite.cmake")) + ",drmemory_only;long;build=" + str(build_properties["buildnumber"])]) # Checkout TSan tests step api.step("Checkout TSan tests", ['svn', 'checkout', '--force', 'http://data-race-test.googlecode.com/svn/trunk/', api.path["slave_build"].join("tsan")]) # Build TSan tests step api.step("Build TSan Tests", ['E:\\b\\build\\scripts\\slave\\drmemory\\build_env.bat', 'make', '-C', api.path["slave_build"].join("tsan", "unittest")], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools"), "CYGWIN": "nodosfilewarning"}) # Dr. Memory TSan test step api.step( "dbg full TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "dbg light TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "-light", "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "rel full TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "rel light TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "-light", "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "dbg full nosyms TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Prepare to pack test results step; null converted # Pack test results step api.step("Pack test results", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), '7z', 'a', '-xr!*.pdb', "testlogs_r" + build_properties["got_revision"] + "_b" + str(build_properties["buildnumber"]) + ".7z", 'build_drmemory-dbg-32/logs', 'build_drmemory-dbg-32/Testing/Temporary', 'build_drmemory-rel-32/logs', 'build_drmemory-rel-32/Testing/Temporary', 'build_drmemory-dbg-64/logs', 'build_drmemory-dbg-64/Testing/Temporary', 'build_drmemory-rel-64/logs', 'build_drmemory-rel-64/Testing/Temporary', 'xmlresults'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # upload drmemory test logs step api.gsutil.upload("testlogs_r" + build_properties["got_revision"] + "_b" + str(api.properties[ "buildnumber"]) + ".7z", "chromium-drmemory-builds", "testlogs/from_%s" % api.properties["buildername"]) def mac_mavericks_x64_drm_steps(api): build_properties = api.properties.legacy() # checkout DrMemory step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "drmemory" soln.url = "https://github.com/DynamoRIO/drmemory.git" soln.custom_deps = {"drmemory/dynamorio": "https://github.com/DynamoRIO/dynamorio.git", "tools/buildbot": "https://github.com/DynamoRIO/buildbot.git"} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # Dr. Memory ctest step api.step( "Dr. Memory ctest", ["ctest", "--timeout", "60", "-VV", "-S", str(api.path["checkout"].join("tests", "runsuite.cmake")) + ",drmemory_only;long;build=0x" + build_properties["got_revision"][:7] ]) # Prepare to pack test results step; null converted # Pack test results step api.step("Pack test results", ['7z', 'a', '-xr!*.pdb', "testlogs_r" + build_properties["got_revision"] + "_b" + str(build_properties["buildnumber"]) + ".7z", 'build_drmemory-dbg-32/logs', 'build_drmemory-dbg-32/Testing/Temporary', 'build_drmemory-rel-32/logs', 'build_drmemory-rel-32/Testing/Temporary', 'xml:results']) # upload drmemory test logs step api.gsutil.upload("testlogs_r" + build_properties["got_revision"] + "_b" + str(api.properties[ "buildnumber"]) + ".7z", "chromium-drmemory-builds", "testlogs/from_%s" % api.properties["buildername"]) def linux_cr_steps(api): build_properties = api.properties.legacy() # checkout DynamiRIO step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "dynamorio" soln.url = "https://github.com/DynamoRIO/dynamorio.git" api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # Make the build directory step api.file.makedirs("makedirs", api.path["slave_build"].join("dynamorio")) api.file.makedirs("makedirs", api.path["slave_build"].join("dynamorio", "build")) # Configure release DynamoRIO step; generic ShellCommand converted api.step("Configure release DynamoRIO", [ 'cmake', '..', '-DDEBUG=OFF' ], env={}, cwd=api.path["slave_build"].join('dynamorio', 'build')) # Compile release DynamoRIO step; generic ShellCommand converted api.step("Compile release DynamoRIO", [ 'make', '-j5' ], env={}, cwd=api.path["slave_build"].join('dynamorio', 'build')) # don't follow python step; generic ShellCommand converted api.step("don't follow python", ['bin64/drconfig', '-reg', 'python', '-norun', '-v'], env={}, cwd=api.path["slave_build"].join('dynamorio', 'build')) # drmemory test step api.step("content_shell", ['xvfb-run', '-a', api.path["checkout"].join("build", "bin64", "drrun"), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/content_shell', '--run-layout-test', 'file:///home/chrome-bot/bb.html'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path["checkout"]) # drmemory test step api.step("base_unittests", ['xvfb-run', '-a', api.path["checkout"].join("build", "bin64", "drrun"), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/base_unittests', '--gtest_filter=-TraceEventTestFixture.TraceContinuousSampling'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path["checkout"]) # drmemory test step api.step("browser_tests", ['xvfb-run', '-a', api.path["checkout"].join("build", "bin64", "drrun"), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/browser_tests', '--gtest_filter=AutofillTest.BasicFormFill'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path["checkout"]) # drmemory test step api.step("crypto_unittests", ['xvfb-run', '-a', api.path["checkout"].join("build", "bin64", "drrun"), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/crypto_unittests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path["checkout"]) # drmemory test step api.step("ipc_tests", ['xvfb-run', '-a', api.path["checkout"].join("build", "bin64", "drrun"), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/ipc_tests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path["checkout"]) # drmemory test step api.step("media_unittests", ['xvfb-run', '-a', api.path["checkout"].join("build", "bin64", "drrun"), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/media_unittests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path["checkout"]) # drmemory test step api.step("net_unittests", ['xvfb-run', '-a', api.path["checkout"].join("build", "bin64", "drrun"), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/net_unittests', '--gtest_filter=-CertDatabaseNSSTest.ImportCACertHierarchy*'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path["checkout"]) # drmemory test step api.step( "printing_unittests", ['xvfb-run', '-a', api.path["checkout"].join("build", "bin64", "drrun"), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/printing_unittests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path["checkout"]) # drmemory test step api.step( "remoting_unittests", ['xvfb-run', '-a', api.path["checkout"].join("build", "bin64", "drrun"), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/remoting_unittests', '--gtest_filter=' '-VideoFrameCapturerTest.Capture:DesktopProcessTest.DeathTest' ], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path["checkout"]) # drmemory test step api.step("sql_unittests", ['xvfb-run', '-a', api.path["checkout"].join("build", "bin64", "drrun"), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/sql_unittests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path["checkout"]) # drmemory test step api.step("unit_tests", ['xvfb-run', '-a', api.path["checkout"].join("build", "bin64", "drrun"), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/unit_tests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path["checkout"]) # drmemory test step api.step("url_unittests", ['xvfb-run', '-a', api.path["checkout"].join("build", "bin64", "drrun"), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/url_unittests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path["checkout"]) def win8_cr_builder_steps(api): build_properties = api.properties.legacy() # svnkill step; not necessary in recipes # update scripts step; implicitly run by recipe engine. # taskkill step api.python("taskkill", api.path["build"].join("scripts", "slave", "kill_processes.py")) # bot_update step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "src" soln.url = "https://chromium.googlesource.com/chromium/src.git" soln.custom_deps = {'src/third_party/WebKit/LayoutTests': None} soln.custom_vars = {'webkit_trunk': 'http://src.chromium.org/blink/trunk', 'googlecode_url': 'http://%s.googlecode.com/svn', 'nacl_trunk': 'http://src.chromium.org/native_client/trunk', 'sourceforge_url': 'https://svn.code.sf.net/p/%(repo)s/code', 'llvm_url': 'http://llvm.org/svn/llvm-project'} src_cfg.got_revision_mapping.update( {'src': 'got_revision', 'src/third_party/WebKit': 'got_webkit_revision', 'src/tools/swarming_client': 'got_swarming_client_revision', 'src/v8': 'got_v8_revision'}) api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # gclient revert step; made unnecessary by bot_update # gclient update step; made unnecessary by bot_update # gclient runhooks wrapper step env = {'CHROMIUM_GYP_SYNTAX_CHECK': '1', 'LANDMINES_VERBOSE': '1', 'DEPOT_TOOLS_UPDATE': '0', 'GYP_DEFINES': 'build_for_tool=drmemory component=shared_library'} api.python("gclient runhooks wrapper", api.path["build"].join("scripts", "slave", "runhooks_wrapper.py"), env=env) # cleanup_temp step api.chromium.cleanup_temp() # compile.py step args = ['--solution', 'all.sln', '--project', 'chromium_builder_dbg_drmemory_win', '--target', 'Debug'] if 'clobber' in api.properties: args.append("--clobber") api.step("compile", ["python_slave", api.path["build"].join( "scripts", "slave", "compile.py")] + args) def win8_cr_steps(api): build_properties = api.properties.legacy() # Download build step api.gsutil.download("chromium-drmemory-builds", "drmemory-windows-latest-sfx.exe", "drm-sfx.exe", cwd=api.path["slave_build"]) # Unpack the build step; generic ShellCommand converted api.step("Unpack the build", [ 'drm-sfx', '-ounpacked', '-y' ], env={}, cwd=api.path["slave_build"]) # Dr. Memory get revision step step_result = api.step("Get the revision number", [ 'unpacked\\bin\\drmemory', '-version' ], stdout=api.raw_io.output()) build_properties["got_revision"] = step_result.stdout.split()[3].\ split(".")[2] # Chromium 'url' tests step; generic ShellCommand converted api.step( "Chromium 'url' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'url', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'printing' tests step; generic ShellCommand converted api.step( "Chromium 'printing' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'printing', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'media' tests step; generic ShellCommand converted api.step( "Chromium 'media' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'media', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'sql' tests step; generic ShellCommand converted api.step( "Chromium 'sql' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'sql', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'crypto_unittests' tests step; generic ShellCommand converted api.step( "Chromium 'crypto_unittests' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'crypto_unittests', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'remoting' tests step; generic ShellCommand converted api.step( "Chromium 'remoting' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'remoting', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'ipc_tests' tests step; generic ShellCommand converted api.step( "Chromium 'ipc_tests' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'ipc_tests', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'base_unittests' tests step; generic ShellCommand converted api.step( "Chromium 'base_unittests' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'base_unittests', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'net' tests step; generic ShellCommand converted api.step( "Chromium 'net' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'net', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'unit' tests step; generic ShellCommand converted api.step( "Chromium 'unit' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'unit', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) def win7_cr_steps(api): build_properties = api.properties.legacy() # Download build step api.gsutil.download("chromium-drmemory-builds", "drmemory-windows-latest-sfx.exe", "drm-sfx.exe", cwd=api.path["slave_build"]) # Unpack the build step; generic ShellCommand converted api.step("Unpack the build", [ 'drm-sfx', '-ounpacked', '-y' ], env={}, cwd=api.path["slave_build"]) # Dr. Memory get revision step step_result = api.step("Get the revision number", [ 'unpacked\\bin\\drmemory', '-version' ], stdout=api.raw_io.output()) build_properties["got_revision"] = step_result.stdout.split()[3].\ split(".")[2] # Chromium 'url' tests step; generic ShellCommand converted api.step( "Chromium 'url' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'url', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'printing' tests step; generic ShellCommand converted api.step( "Chromium 'printing' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'printing', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'media' tests step; generic ShellCommand converted api.step( "Chromium 'media' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'media', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'sql' tests step; generic ShellCommand converted api.step( "Chromium 'sql' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'sql', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'crypto_unittests' tests step; generic ShellCommand converted api.step( "Chromium 'crypto_unittests' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'crypto_unittests', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'remoting' tests step; generic ShellCommand converted api.step( "Chromium 'remoting' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'remoting', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'ipc_tests' tests step; generic ShellCommand converted api.step( "Chromium 'ipc_tests' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'ipc_tests', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'base_unittests' tests step; generic ShellCommand converted api.step( "Chromium 'base_unittests' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'base_unittests', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'net' tests step; generic ShellCommand converted api.step( "Chromium 'net' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'net', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) # Chromium 'unit' tests step; generic ShellCommand converted api.step( "Chromium 'unit' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'unit', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path["slave_build"]) def win_8_x64_drm_steps(api): build_properties = api.properties.legacy() # checkout DrMemory step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "drmemory" soln.url = "https://github.com/DynamoRIO/drmemory.git" soln.custom_deps = {"drmemory/dynamorio": "https://github.com/DynamoRIO/dynamorio.git", "tools/buildbot": "https://github.com/DynamoRIO/buildbot.git"} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # clear tools directory step; null converted # update tools step; null converted # unpack tools step; generic ShellCommand converted api.step("unpack tools", [api.path["slave_build"].join('tools', 'buildbot', 'bot_tools', 'unpack.bat')], env={}, cwd=api.path[ "slave_build"].join('tools', 'buildbot', 'bot_tools')) # windows Dr. Memory ctest step api.step("Dr. Memory ctest", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'ctest', '--timeout', '60', '-VV', '-S', str(api.path["checkout"].join("tests", "runsuite.cmake")) + ",drmemory_only;long;build=" + str(build_properties["buildnumber"])]) # Checkout TSan tests step api.step("Checkout TSan tests", ['svn', 'checkout', '--force', 'http://data-race-test.googlecode.com/svn/trunk/', api.path["slave_build"].join("tsan")]) # Build TSan tests step api.step("Build TSan Tests", ['E:\\b\\build\\scripts\\slave\\drmemory\\build_env.bat', 'make', '-C', api.path["slave_build"].join("tsan", "unittest")], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools"), "CYGWIN": "nodosfilewarning"}) # Dr. Memory TSan test step api.step( "dbg full TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "dbg light TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "-light", "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "rel full TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "rel light TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "-light", "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "dbg full nosyms TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Prepare to pack test results step; null converted # Pack test results step api.step("Pack test results", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), '7z', 'a', '-xr!*.pdb', "testlogs_r" + build_properties["got_revision"] + "_b" + str(build_properties["buildnumber"]) + ".7z", 'build_drmemory-dbg-32/logs', 'build_drmemory-dbg-32/Testing/Temporary', 'build_drmemory-rel-32/logs', 'build_drmemory-rel-32/Testing/Temporary', 'build_drmemory-dbg-64/logs', 'build_drmemory-dbg-64/Testing/Temporary', 'build_drmemory-rel-64/logs', 'build_drmemory-rel-64/Testing/Temporary', 'xmlresults'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # upload drmemory test logs step api.gsutil.upload("testlogs_r" + build_properties["got_revision"] + "_b" + str(api.properties[ "buildnumber"]) + ".7z", "chromium-drmemory-builds", "testlogs/from_%s" % api.properties["buildername"]) def win7_cr_builder_steps(api): build_properties = api.properties.legacy() # svnkill step; not necessary in recipes # update scripts step; implicitly run by recipe engine. # taskkill step api.python("taskkill", api.path["build"].join("scripts", "slave", "kill_processes.py")) # bot_update step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "src" soln.url = "https://chromium.googlesource.com/chromium/src.git" soln.custom_deps = {'src/third_party/WebKit/LayoutTests': None} soln.custom_vars = {'webkit_trunk': 'http://src.chromium.org/blink/trunk', 'googlecode_url': 'http://%s.googlecode.com/svn', 'nacl_trunk': 'http://src.chromium.org/native_client/trunk', 'sourceforge_url': 'https://svn.code.sf.net/p/%(repo)s/code', 'llvm_url': 'http://llvm.org/svn/llvm-project'} src_cfg.got_revision_mapping.update( {'src': 'got_revision', 'src/third_party/WebKit': 'got_webkit_revision', 'src/tools/swarming_client': 'got_swarming_client_revision', 'src/v8': 'got_v8_revision'}) api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # gclient revert step; made unnecessary by bot_update # gclient update step; made unnecessary by bot_update # gclient runhooks wrapper step env = {'CHROMIUM_GYP_SYNTAX_CHECK': '1', 'LANDMINES_VERBOSE': '1', 'DEPOT_TOOLS_UPDATE': '0', 'GYP_DEFINES': 'build_for_tool=drmemory component=shared_library'} api.python("gclient runhooks wrapper", api.path["build"].join("scripts", "slave", "runhooks_wrapper.py"), env=env) # cleanup_temp step api.chromium.cleanup_temp() # compile.py step args = ['--solution', 'all.sln', '--project', 'chromium_builder_dbg_drmemory_win', '--target', 'Debug'] if 'clobber' in api.properties: args.append("--clobber") api.step("compile", ["python_slave", api.path["build"].join( "scripts", "slave", "compile.py")] + args) def win_7_x64_drm_steps(api): build_properties = api.properties.legacy() # checkout DrMemory step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "drmemory" soln.url = "https://github.com/DynamoRIO/drmemory.git" soln.custom_deps = {"drmemory/dynamorio": "https://github.com/DynamoRIO/dynamorio.git", "tools/buildbot": "https://github.com/DynamoRIO/buildbot.git"} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # clear tools directory step; null converted # update tools step; null converted # unpack tools step; generic ShellCommand converted api.step("unpack tools", [api.path["slave_build"].join('tools', 'buildbot', 'bot_tools', 'unpack.bat')], env={}, cwd=api.path[ "slave_build"].join('tools', 'buildbot', 'bot_tools')) # windows Dr. Memory ctest step api.step("Dr. Memory ctest", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'ctest', '--timeout', '60', '-VV', '-S', str(api.path["checkout"].join("tests", "runsuite.cmake")) + ",drmemory_only;long;build=" + str(build_properties["buildnumber"])]) # Checkout TSan tests step api.step("Checkout TSan tests", ['svn', 'checkout', '--force', 'http://data-race-test.googlecode.com/svn/trunk/', api.path["slave_build"].join("tsan")]) # Build TSan tests step api.step("Build TSan Tests", ['E:\\b\\build\\scripts\\slave\\drmemory\\build_env.bat', 'make', '-C', api.path["slave_build"].join("tsan", "unittest")], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools"), "CYGWIN": "nodosfilewarning"}) # Dr. Memory TSan test step api.step( "dbg full TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "dbg light TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "-light", "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "rel full TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "rel light TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "-light", "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Dr. Memory TSan test step api.step( "dbg full nosyms TSan tests", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path["checkout"].join( "tests", "app_suite", "default-suppressions.txt"), "--", api.path["slave_build"].join("tsan", 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=' '-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # Prepare to pack test results step; null converted # Pack test results step api.step("Pack test results", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), '7z', 'a', '-xr!*.pdb', "testlogs_r" + build_properties["got_revision"] + "_b" + str(build_properties["buildnumber"]) + ".7z", 'build_drmemory-dbg-32/logs', 'build_drmemory-dbg-32/Testing/Temporary', 'build_drmemory-rel-32/logs', 'build_drmemory-rel-32/Testing/Temporary', 'build_drmemory-dbg-64/logs', 'build_drmemory-dbg-64/Testing/Temporary', 'build_drmemory-rel-64/logs', 'build_drmemory-rel-64/Testing/Temporary', 'xmlresults'], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # upload drmemory test logs step api.gsutil.upload("testlogs_r" + build_properties["got_revision"] + "_b" + str(api.properties[ "buildnumber"]) + ".7z", "chromium-drmemory-builds", "testlogs/from_%s" % api.properties["buildername"]) def mac_builder_steps(api): build_properties = api.properties.legacy() # checkout DrMemory step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "drmemory" soln.url = "https://github.com/DynamoRIO/drmemory.git" soln.custom_deps = {"drmemory/dynamorio": "https://github.com/DynamoRIO/dynamorio.git", "tools/buildbot": "https://github.com/DynamoRIO/buildbot.git"} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # get buildnumber step; no longer needed # Package DrMemory step api.step("Package Dr. Memory", ["ctest", "-VV", "-S", str(api.path["checkout"].join("package.cmake")) + ",build=0x" + build_properties["got_revision"][:7] + ";drmem_only"]) # find package file step; no longer necessary # upload drmemory build step api.gsutil.upload("DrMemory-MacOS-*" + build_properties["got_revision"][ :7] + ".tar.gz", "chromium-drmemory-builds", "builds/") def win_builder_steps(api): build_properties = api.properties.legacy() # checkout DrMemory step src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = "drmemory" soln.url = "https://github.com/DynamoRIO/drmemory.git" soln.custom_deps = {"drmemory/dynamorio": "https://github.com/DynamoRIO/dynamorio.git", "tools/buildbot": "https://github.com/DynamoRIO/buildbot.git"} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get("properties", {})) # clear tools directory step; null converted # update tools step; null converted # unpack tools step; generic ShellCommand converted api.step("unpack tools", [api.path["slave_build"].join('tools', 'buildbot', 'bot_tools', 'unpack.bat')], env={}, cwd=api.path[ "slave_build"].join('tools', 'buildbot', 'bot_tools')) # get buildnumber step; no longer needed # Package dynamorio step api.step("Package Dr. Memory", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), 'ctest', '-VV', '-S', str(api.path["checkout"].join("package.cmake")) + ",build=0x" + build_properties["got_revision"][:7] + ";drmem_only"], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}, cwd=api.path["slave_build"]) # Find package basename step step_result = api.step("Find package basename", ["dir", "/B", "DrMemory-Windows-*0x" + build_properties[ "got_revision"][:7] + ".zip"], stdout=api.raw_io.output(), cwd=api.path["slave_build"]) basename = step_result.stdout[:-4] # Delete prior sfx archive step api.step("Delete prior sfx archive", [ "del", basename + "-sfx.exe" ], cwd=api.path["slave_build"]) # Create sfx archive step api.step("create sfx archive", [api.path["build"].join("scripts", "slave", "drmemory", "build_env.bat"), "7z", "a", "-sfx", basename + "-sfx.exe", "build_drmemory-debug-32\\_CPack_Packages\\Windows\\ZIP\\" + basename + "\\*"], cwd=api.path["slave_build"], env={"BOTTOOLS": api.path["slave_build"].join("tools", "buildbot", "bot_tools")}) # upload latest build step api.step("copy locally", ["copy", basename + "-sfx.exe", "drmemory-windows-latest-sfx.exe"], cwd=api.path["slave_build"]) api.gsutil.upload("drmemory-windows-latest-sfx.exe", "chromium-drmemory-builds", "", cwd=api.path["slave_build"]) # upload drmemory build step api.gsutil.upload("DrMemory-Windows-*" + build_properties["got_revision"][ :7] + ".zip", "chromium-drmemory-builds", "builds/") dispatch_directory = { 'linux-builder': linux_builder_steps, 'linux-lucid_x64-drm': linux_lucid_x64_drm_steps, 'win-vista_x64-drm': win_vista_x64_drm_steps, 'mac-mavericks_x64-DR': mac_mavericks_x64_DR_steps, 'linux-cr-builder': linux_cr_builder_steps, 'mac-builder-DR': mac_builder_DR_steps, 'win-xp-drm': win_xp_drm_steps, 'mac-mavericks_x64-drm': mac_mavericks_x64_drm_steps, 'linux-cr': linux_cr_steps, 'win8-cr-builder': win8_cr_builder_steps, 'win8-cr': win8_cr_steps, 'win7-cr': win7_cr_steps, 'win-8_x64-drm': win_8_x64_drm_steps, 'win7-cr-builder': win7_cr_builder_steps, 'win-7_x64-drm': win_7_x64_drm_steps, 'mac-builder': mac_builder_steps, 'win-builder': win_builder_steps, } def RunSteps(api): if api.properties["buildername"] not in dispatch_directory: raise api.step.StepFailure("Builder unsupported by recipe.") else: dispatch_directory[api.properties["buildername"]](api) def GenTests(api): yield (api.test('linux_builder') + api.properties(mastername='client.drmemory') + api.properties(buildername='linux-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('linux_lucid_x64_drm') + api.properties(mastername='client.drmemory') + api.properties(buildername='linux-lucid_x64-drm') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('win_vista_x64_drm') + api.properties(mastername='client.drmemory') + api.properties(buildername='win-vista_x64-drm') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('mac_mavericks_x64_DR') + api.properties(mastername='client.drmemory') + api.properties(buildername='mac-mavericks_x64-DR') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('linux_cr_builder') + api.properties(mastername='client.drmemory') + api.properties(buildername='linux-cr-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('linux_cr_builder_clobber') + api.properties(mastername='client.drmemory') + api.properties(buildername='linux-cr-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') + api.properties(clobber='') ) yield (api.test('mac_builder_DR') + api.properties(mastername='client.drmemory') + api.properties(buildername='mac-builder-DR') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('win_xp_drm') + api.properties(mastername='client.drmemory') + api.properties(buildername='win-xp-drm') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('mac_mavericks_x64_drm') + api.properties(mastername='client.drmemory') + api.properties(buildername='mac-mavericks_x64-drm') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('linux_cr') + api.properties(mastername='client.drmemory') + api.properties(buildername='linux-cr') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('win8_cr_builder') + api.properties(mastername='client.drmemory') + api.properties(buildername='win8-cr-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('win8_cr_builder_clobber') + api.properties(mastername='client.drmemory') + api.properties(buildername='win8-cr-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') + api.properties(clobber='') ) yield (api.test('win8_cr') + api.properties(mastername='client.drmemory') + api.properties(buildername='win8-cr') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') + api.step_data("Get the revision number", stdout=api.raw_io.output("Dr. Memory version 1.9.16845" " -- build 178560794")) ) yield (api.test('win7_cr') + api.properties(mastername='client.drmemory') + api.properties(buildername='win7-cr') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') + api.step_data("Get the revision number", stdout=api.raw_io.output("Dr. Memory version 1.9.16845" " -- build 178560794")) ) yield (api.test('win_8_x64_drm') + api.properties(mastername='client.drmemory') + api.properties(buildername='win-8_x64-drm') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('win7_cr_builder') + api.properties(mastername='client.drmemory') + api.properties(buildername='win7-cr-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('win7_cr_builder_clobber') + api.properties(mastername='client.drmemory') + api.properties(buildername='win7-cr-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') + api.properties(clobber='') ) yield (api.test('win_7_x64_drm') + api.properties(mastername='client.drmemory') + api.properties(buildername='win-7_x64-drm') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('mac_builder') + api.properties(mastername='client.drmemory') + api.properties(buildername='mac-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') ) yield (api.test('win_builder') + api.properties(mastername='client.drmemory') + api.properties(buildername='win-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') + api.step_data("Find package basename", stdout=api.raw_io.output("DrMemory-Windows-1.2.3-0x1234567.zip") )) yield (api.test('builder_not_in_dispatch_directory') + api.properties(mastername='client.drmemory') + api.properties(buildername='nonexistent_builder') + api.properties(slavename='TestSlave') )
deps = ['chromium', 'depot_tools/bot_update', 'depot_tools/gclient', 'file', 'gsutil', 'recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/python', 'recipe_engine/raw_io', 'recipe_engine/step'] def linux_builder_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'drmemory' soln.url = 'https://github.com/DynamoRIO/drmemory.git' soln.custom_deps = {'drmemory/dynamorio': 'https://github.com/DynamoRIO/dynamorio.git', 'tools/buildbot': 'https://github.com/DynamoRIO/buildbot.git'} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) api.step('Package Dr. Memory', ['ctest', '-VV', '-S', str(api.path['checkout'].join('package.cmake')) + ',build=0x' + build_properties['got_revision'][:7] + ';drmem_only']) api.gsutil.upload('DrMemory-Linux-*' + build_properties['got_revision'][:7] + '.tar.gz', 'chromium-drmemory-builds', 'builds/') def linux_lucid_x64_drm_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'drmemory' soln.url = 'https://github.com/DynamoRIO/drmemory.git' soln.custom_deps = {'drmemory/dynamorio': 'https://github.com/DynamoRIO/dynamorio.git', 'tools/buildbot': 'https://github.com/DynamoRIO/buildbot.git'} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) api.step('Dr. Memory ctest', ['ctest', '--timeout', '60', '-VV', '-S', str(api.path['checkout'].join('tests', 'runsuite.cmake')) + ',drmemory_only;long;build=0x' + build_properties['got_revision'][:7]]) api.step('Pack test results', ['7z', 'a', '-xr!*.pdb', 'testlogs_r' + build_properties['got_revision'] + '_b' + str(build_properties['buildnumber']) + '.7z', 'build_drmemory-dbg-32/logs', 'build_drmemory-dbg-32/Testing/Temporary', 'build_drmemory-rel-32/logs', 'build_drmemory-rel-32/Testing/Temporary', 'build_drmemory-dbg-64/logs', 'build_drmemory-dbg-64/Testing/Temporary', 'build_drmemory-rel-64/logs', 'build_drmemory-rel-64/Testing/Temporary', 'xml:results']) api.gsutil.upload('testlogs_r' + build_properties['got_revision'] + '_b' + str(api.properties['buildnumber']) + '.7z', 'chromium-drmemory-builds', 'testlogs/from_%s' % api.properties['buildername']) def win_vista_x64_drm_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'drmemory' soln.url = 'https://github.com/DynamoRIO/drmemory.git' soln.custom_deps = {'drmemory/dynamorio': 'https://github.com/DynamoRIO/dynamorio.git', 'tools/buildbot': 'https://github.com/DynamoRIO/buildbot.git'} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) api.step('unpack tools', [api.path['slave_build'].join('tools', 'buildbot', 'bot_tools', 'unpack.bat')], env={}, cwd=api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')) api.step('Dr. Memory ctest', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'ctest', '--timeout', '60', '-VV', '-S', str(api.path['checkout'].join('tests', 'runsuite.cmake')) + ',drmemory_only;long;build=' + str(build_properties['buildnumber'])]) api.step('Checkout TSan tests', ['svn', 'checkout', '--force', 'http://data-race-test.googlecode.com/svn/trunk/', api.path['slave_build'].join('tsan')]) api.step('Build TSan Tests', ['E:\\b\\build\\scripts\\slave\\drmemory\\build_env.bat', 'make', '-C', api.path['slave_build'].join('tsan', 'unittest')], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools'), 'CYGWIN': 'nodosfilewarning'}) api.step('dbg full TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('dbg light TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '-light', '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('rel full TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('rel light TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '-light', '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('dbg full nosyms TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('Pack test results', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), '7z', 'a', '-xr!*.pdb', 'testlogs_r' + build_properties['got_revision'] + '_b' + str(build_properties['buildnumber']) + '.7z', 'build_drmemory-dbg-32/logs', 'build_drmemory-dbg-32/Testing/Temporary', 'build_drmemory-rel-32/logs', 'build_drmemory-rel-32/Testing/Temporary', 'build_drmemory-dbg-64/logs', 'build_drmemory-dbg-64/Testing/Temporary', 'build_drmemory-rel-64/logs', 'build_drmemory-rel-64/Testing/Temporary', 'xmlresults'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.gsutil.upload('testlogs_r' + build_properties['got_revision'] + '_b' + str(api.properties['buildnumber']) + '.7z', 'chromium-drmemory-builds', 'testlogs/from_%s' % api.properties['buildername']) def mac_mavericks_x64_dr_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'dynamorio' soln.url = 'https://github.com/DynamoRIO/dynamorio.git' api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) api.step('pre-commit suite', ['ctest', '--timeout', '120', '-VV', '-S', api.path['checkout'].join('suite', 'runsuite.cmake')], cwd=api.path['slave_build'], ok_ret='all') def linux_cr_builder_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'src' soln.url = 'https://chromium.googlesource.com/chromium/src.git' soln.custom_deps = {'src/third_party/WebKit/LayoutTests': None} soln.custom_vars = {'webkit_trunk': 'http://src.chromium.org/blink/trunk', 'googlecode_url': 'http://%s.googlecode.com/svn', 'nacl_trunk': 'http://src.chromium.org/native_client/trunk', 'sourceforge_url': 'https://svn.code.sf.net/p/%(repo)s/code', 'llvm_url': 'http://llvm.org/svn/llvm-project'} src_cfg.got_revision_mapping.update({'src': 'got_revision', 'src/third_party/WebKit': 'got_webkit_revision', 'src/tools/swarming_client': 'got_swarming_client_revision', 'src/v8': 'got_v8_revision'}) api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) env = {'CHROMIUM_GYP_SYNTAX_CHECK': '1', 'GYP_GENERATORS': 'ninja', 'DEPOT_TOOLS_UPDATE': '0', 'GYP_DEFINES': 'build_for_tool=drmemory component=shared_library', 'LANDMINES_VERBOSE': '1'} api.python('gclient runhooks wrapper', api.path['build'].join('scripts', 'slave', 'runhooks_wrapper.py'), env=env) api.chromium.cleanup_temp() args = ['--target', 'Release', '--build-tool=ninja', '--compiler=goma', 'content_shell', 'base_unittests', 'browser_tests', 'crypto_unittests', 'ipc_tests', 'media_unittests', 'net_unittests', 'printing_unittests', 'remoting_unittests', 'sql_unittests', 'unit_tests', 'url_unittests'] if 'clobber' in api.properties: args.append('--clobber') api.python('compile', api.path['build'].join('scripts', 'slave', 'compile.py'), args=args) def mac_builder_dr_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'dynamorio' soln.url = 'https://github.com/DynamoRIO/dynamorio.git' api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) api.step('Package DynamoRIO', ['ctest', '-VV', '-S', str(api.path['checkout'].join('make', 'package.cmake')) + ',build=0x' + build_properties['revision'][:7]]) api.gsutil.upload('DynamoRIO-MacOS-*' + build_properties['got_revision'][:7] + '.tar.gz', 'chromium-dynamorio', 'builds/') def win_xp_drm_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'drmemory' soln.url = 'https://github.com/DynamoRIO/drmemory.git' soln.custom_deps = {'drmemory/dynamorio': 'https://github.com/DynamoRIO/dynamorio.git', 'tools/buildbot': 'https://github.com/DynamoRIO/buildbot.git'} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) api.step('unpack tools', [api.path['slave_build'].join('tools', 'buildbot', 'bot_tools', 'unpack.bat')], env={}, cwd=api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')) api.step('Dr. Memory ctest', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'ctest', '--timeout', '60', '-VV', '-S', str(api.path['checkout'].join('tests', 'runsuite.cmake')) + ',drmemory_only;long;build=' + str(build_properties['buildnumber'])]) api.step('Checkout TSan tests', ['svn', 'checkout', '--force', 'http://data-race-test.googlecode.com/svn/trunk/', api.path['slave_build'].join('tsan')]) api.step('Build TSan Tests', ['E:\\b\\build\\scripts\\slave\\drmemory\\build_env.bat', 'make', '-C', api.path['slave_build'].join('tsan', 'unittest')], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools'), 'CYGWIN': 'nodosfilewarning'}) api.step('dbg full TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('dbg light TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '-light', '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('rel full TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('rel light TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '-light', '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('dbg full nosyms TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('Pack test results', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), '7z', 'a', '-xr!*.pdb', 'testlogs_r' + build_properties['got_revision'] + '_b' + str(build_properties['buildnumber']) + '.7z', 'build_drmemory-dbg-32/logs', 'build_drmemory-dbg-32/Testing/Temporary', 'build_drmemory-rel-32/logs', 'build_drmemory-rel-32/Testing/Temporary', 'build_drmemory-dbg-64/logs', 'build_drmemory-dbg-64/Testing/Temporary', 'build_drmemory-rel-64/logs', 'build_drmemory-rel-64/Testing/Temporary', 'xmlresults'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.gsutil.upload('testlogs_r' + build_properties['got_revision'] + '_b' + str(api.properties['buildnumber']) + '.7z', 'chromium-drmemory-builds', 'testlogs/from_%s' % api.properties['buildername']) def mac_mavericks_x64_drm_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'drmemory' soln.url = 'https://github.com/DynamoRIO/drmemory.git' soln.custom_deps = {'drmemory/dynamorio': 'https://github.com/DynamoRIO/dynamorio.git', 'tools/buildbot': 'https://github.com/DynamoRIO/buildbot.git'} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) api.step('Dr. Memory ctest', ['ctest', '--timeout', '60', '-VV', '-S', str(api.path['checkout'].join('tests', 'runsuite.cmake')) + ',drmemory_only;long;build=0x' + build_properties['got_revision'][:7]]) api.step('Pack test results', ['7z', 'a', '-xr!*.pdb', 'testlogs_r' + build_properties['got_revision'] + '_b' + str(build_properties['buildnumber']) + '.7z', 'build_drmemory-dbg-32/logs', 'build_drmemory-dbg-32/Testing/Temporary', 'build_drmemory-rel-32/logs', 'build_drmemory-rel-32/Testing/Temporary', 'xml:results']) api.gsutil.upload('testlogs_r' + build_properties['got_revision'] + '_b' + str(api.properties['buildnumber']) + '.7z', 'chromium-drmemory-builds', 'testlogs/from_%s' % api.properties['buildername']) def linux_cr_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'dynamorio' soln.url = 'https://github.com/DynamoRIO/dynamorio.git' api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) api.file.makedirs('makedirs', api.path['slave_build'].join('dynamorio')) api.file.makedirs('makedirs', api.path['slave_build'].join('dynamorio', 'build')) api.step('Configure release DynamoRIO', ['cmake', '..', '-DDEBUG=OFF'], env={}, cwd=api.path['slave_build'].join('dynamorio', 'build')) api.step('Compile release DynamoRIO', ['make', '-j5'], env={}, cwd=api.path['slave_build'].join('dynamorio', 'build')) api.step("don't follow python", ['bin64/drconfig', '-reg', 'python', '-norun', '-v'], env={}, cwd=api.path['slave_build'].join('dynamorio', 'build')) api.step('content_shell', ['xvfb-run', '-a', api.path['checkout'].join('build', 'bin64', 'drrun'), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/content_shell', '--run-layout-test', 'file:///home/chrome-bot/bb.html'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path['checkout']) api.step('base_unittests', ['xvfb-run', '-a', api.path['checkout'].join('build', 'bin64', 'drrun'), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/base_unittests', '--gtest_filter=-TraceEventTestFixture.TraceContinuousSampling'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path['checkout']) api.step('browser_tests', ['xvfb-run', '-a', api.path['checkout'].join('build', 'bin64', 'drrun'), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/browser_tests', '--gtest_filter=AutofillTest.BasicFormFill'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path['checkout']) api.step('crypto_unittests', ['xvfb-run', '-a', api.path['checkout'].join('build', 'bin64', 'drrun'), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/crypto_unittests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path['checkout']) api.step('ipc_tests', ['xvfb-run', '-a', api.path['checkout'].join('build', 'bin64', 'drrun'), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/ipc_tests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path['checkout']) api.step('media_unittests', ['xvfb-run', '-a', api.path['checkout'].join('build', 'bin64', 'drrun'), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/media_unittests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path['checkout']) api.step('net_unittests', ['xvfb-run', '-a', api.path['checkout'].join('build', 'bin64', 'drrun'), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/net_unittests', '--gtest_filter=-CertDatabaseNSSTest.ImportCACertHierarchy*'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path['checkout']) api.step('printing_unittests', ['xvfb-run', '-a', api.path['checkout'].join('build', 'bin64', 'drrun'), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/printing_unittests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path['checkout']) api.step('remoting_unittests', ['xvfb-run', '-a', api.path['checkout'].join('build', 'bin64', 'drrun'), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/remoting_unittests', '--gtest_filter=-VideoFrameCapturerTest.Capture:DesktopProcessTest.DeathTest'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path['checkout']) api.step('sql_unittests', ['xvfb-run', '-a', api.path['checkout'].join('build', 'bin64', 'drrun'), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/sql_unittests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path['checkout']) api.step('unit_tests', ['xvfb-run', '-a', api.path['checkout'].join('build', 'bin64', 'drrun'), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/unit_tests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path['checkout']) api.step('url_unittests', ['xvfb-run', '-a', api.path['checkout'].join('build', 'bin64', 'drrun'), '-stderr_mask', '12', '--', '../../linux-cr-builder/build/src/out/Release/url_unittests'], env={'CHROME_DEVEL_SANDBOX': '/opt/chromium/chrome_sandbox'}, cwd=api.path['checkout']) def win8_cr_builder_steps(api): build_properties = api.properties.legacy() api.python('taskkill', api.path['build'].join('scripts', 'slave', 'kill_processes.py')) src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'src' soln.url = 'https://chromium.googlesource.com/chromium/src.git' soln.custom_deps = {'src/third_party/WebKit/LayoutTests': None} soln.custom_vars = {'webkit_trunk': 'http://src.chromium.org/blink/trunk', 'googlecode_url': 'http://%s.googlecode.com/svn', 'nacl_trunk': 'http://src.chromium.org/native_client/trunk', 'sourceforge_url': 'https://svn.code.sf.net/p/%(repo)s/code', 'llvm_url': 'http://llvm.org/svn/llvm-project'} src_cfg.got_revision_mapping.update({'src': 'got_revision', 'src/third_party/WebKit': 'got_webkit_revision', 'src/tools/swarming_client': 'got_swarming_client_revision', 'src/v8': 'got_v8_revision'}) api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) env = {'CHROMIUM_GYP_SYNTAX_CHECK': '1', 'LANDMINES_VERBOSE': '1', 'DEPOT_TOOLS_UPDATE': '0', 'GYP_DEFINES': 'build_for_tool=drmemory component=shared_library'} api.python('gclient runhooks wrapper', api.path['build'].join('scripts', 'slave', 'runhooks_wrapper.py'), env=env) api.chromium.cleanup_temp() args = ['--solution', 'all.sln', '--project', 'chromium_builder_dbg_drmemory_win', '--target', 'Debug'] if 'clobber' in api.properties: args.append('--clobber') api.step('compile', ['python_slave', api.path['build'].join('scripts', 'slave', 'compile.py')] + args) def win8_cr_steps(api): build_properties = api.properties.legacy() api.gsutil.download('chromium-drmemory-builds', 'drmemory-windows-latest-sfx.exe', 'drm-sfx.exe', cwd=api.path['slave_build']) api.step('Unpack the build', ['drm-sfx', '-ounpacked', '-y'], env={}, cwd=api.path['slave_build']) step_result = api.step('Get the revision number', ['unpacked\\bin\\drmemory', '-version'], stdout=api.raw_io.output()) build_properties['got_revision'] = step_result.stdout.split()[3].split('.')[2] api.step("Chromium 'url' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'url', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'printing' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'printing', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'media' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'media', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'sql' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'sql', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'crypto_unittests' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'crypto_unittests', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'remoting' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'remoting', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'ipc_tests' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'ipc_tests', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'base_unittests' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'base_unittests', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'net' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'net', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'unit' tests", ['..\\..\\win8-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'unit', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) def win7_cr_steps(api): build_properties = api.properties.legacy() api.gsutil.download('chromium-drmemory-builds', 'drmemory-windows-latest-sfx.exe', 'drm-sfx.exe', cwd=api.path['slave_build']) api.step('Unpack the build', ['drm-sfx', '-ounpacked', '-y'], env={}, cwd=api.path['slave_build']) step_result = api.step('Get the revision number', ['unpacked\\bin\\drmemory', '-version'], stdout=api.raw_io.output()) build_properties['got_revision'] = step_result.stdout.split()[3].split('.')[2] api.step("Chromium 'url' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'url', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'printing' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'printing', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'media' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'media', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'sql' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'sql', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'crypto_unittests' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'crypto_unittests', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'remoting' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'remoting', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'ipc_tests' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'ipc_tests', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'base_unittests' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'base_unittests', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'net' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'net', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) api.step("Chromium 'unit' tests", ['..\\..\\win7-cr-builder\\build\\src\\tools\\valgrind\\chrome_tests.bat', '-t', 'unit', '--tool', 'drmemory_light', '--keep_logs'], env={'DRMEMORY_COMMAND': 'unpacked/bin/drmemory.exe'}, cwd=api.path['slave_build']) def win_8_x64_drm_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'drmemory' soln.url = 'https://github.com/DynamoRIO/drmemory.git' soln.custom_deps = {'drmemory/dynamorio': 'https://github.com/DynamoRIO/dynamorio.git', 'tools/buildbot': 'https://github.com/DynamoRIO/buildbot.git'} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) api.step('unpack tools', [api.path['slave_build'].join('tools', 'buildbot', 'bot_tools', 'unpack.bat')], env={}, cwd=api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')) api.step('Dr. Memory ctest', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'ctest', '--timeout', '60', '-VV', '-S', str(api.path['checkout'].join('tests', 'runsuite.cmake')) + ',drmemory_only;long;build=' + str(build_properties['buildnumber'])]) api.step('Checkout TSan tests', ['svn', 'checkout', '--force', 'http://data-race-test.googlecode.com/svn/trunk/', api.path['slave_build'].join('tsan')]) api.step('Build TSan Tests', ['E:\\b\\build\\scripts\\slave\\drmemory\\build_env.bat', 'make', '-C', api.path['slave_build'].join('tsan', 'unittest')], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools'), 'CYGWIN': 'nodosfilewarning'}) api.step('dbg full TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('dbg light TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '-light', '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('rel full TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('rel light TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '-light', '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('dbg full nosyms TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('Pack test results', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), '7z', 'a', '-xr!*.pdb', 'testlogs_r' + build_properties['got_revision'] + '_b' + str(build_properties['buildnumber']) + '.7z', 'build_drmemory-dbg-32/logs', 'build_drmemory-dbg-32/Testing/Temporary', 'build_drmemory-rel-32/logs', 'build_drmemory-rel-32/Testing/Temporary', 'build_drmemory-dbg-64/logs', 'build_drmemory-dbg-64/Testing/Temporary', 'build_drmemory-rel-64/logs', 'build_drmemory-rel-64/Testing/Temporary', 'xmlresults'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.gsutil.upload('testlogs_r' + build_properties['got_revision'] + '_b' + str(api.properties['buildnumber']) + '.7z', 'chromium-drmemory-builds', 'testlogs/from_%s' % api.properties['buildername']) def win7_cr_builder_steps(api): build_properties = api.properties.legacy() api.python('taskkill', api.path['build'].join('scripts', 'slave', 'kill_processes.py')) src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'src' soln.url = 'https://chromium.googlesource.com/chromium/src.git' soln.custom_deps = {'src/third_party/WebKit/LayoutTests': None} soln.custom_vars = {'webkit_trunk': 'http://src.chromium.org/blink/trunk', 'googlecode_url': 'http://%s.googlecode.com/svn', 'nacl_trunk': 'http://src.chromium.org/native_client/trunk', 'sourceforge_url': 'https://svn.code.sf.net/p/%(repo)s/code', 'llvm_url': 'http://llvm.org/svn/llvm-project'} src_cfg.got_revision_mapping.update({'src': 'got_revision', 'src/third_party/WebKit': 'got_webkit_revision', 'src/tools/swarming_client': 'got_swarming_client_revision', 'src/v8': 'got_v8_revision'}) api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) env = {'CHROMIUM_GYP_SYNTAX_CHECK': '1', 'LANDMINES_VERBOSE': '1', 'DEPOT_TOOLS_UPDATE': '0', 'GYP_DEFINES': 'build_for_tool=drmemory component=shared_library'} api.python('gclient runhooks wrapper', api.path['build'].join('scripts', 'slave', 'runhooks_wrapper.py'), env=env) api.chromium.cleanup_temp() args = ['--solution', 'all.sln', '--project', 'chromium_builder_dbg_drmemory_win', '--target', 'Debug'] if 'clobber' in api.properties: args.append('--clobber') api.step('compile', ['python_slave', api.path['build'].join('scripts', 'slave', 'compile.py')] + args) def win_7_x64_drm_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'drmemory' soln.url = 'https://github.com/DynamoRIO/drmemory.git' soln.custom_deps = {'drmemory/dynamorio': 'https://github.com/DynamoRIO/dynamorio.git', 'tools/buildbot': 'https://github.com/DynamoRIO/buildbot.git'} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) api.step('unpack tools', [api.path['slave_build'].join('tools', 'buildbot', 'bot_tools', 'unpack.bat')], env={}, cwd=api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')) api.step('Dr. Memory ctest', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'ctest', '--timeout', '60', '-VV', '-S', str(api.path['checkout'].join('tests', 'runsuite.cmake')) + ',drmemory_only;long;build=' + str(build_properties['buildnumber'])]) api.step('Checkout TSan tests', ['svn', 'checkout', '--force', 'http://data-race-test.googlecode.com/svn/trunk/', api.path['slave_build'].join('tsan')]) api.step('Build TSan Tests', ['E:\\b\\build\\scripts\\slave\\drmemory\\build_env.bat', 'make', '-C', api.path['slave_build'].join('tsan', 'unittest')], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools'), 'CYGWIN': 'nodosfilewarning'}) api.step('dbg full TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('dbg light TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '-light', '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('rel full TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('rel light TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-rel-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '-light', '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('dbg full nosyms TSan tests', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'build_drmemory-dbg-32\\bin\\drmemory', '-dr_ops', '-msgbox_mask 0 -stderr_mask 15', '-results_to_stderr', '-batch', '-suppress', api.path['checkout'].join('tests', 'app_suite', 'default-suppressions.txt'), '--', api.path['slave_build'].join('tsan', 'unittest', 'bin', 'racecheck_unittest-windows-x86-O0.exe'), '--gtest_filter=-PositiveTests.FreeVsRead:NegativeTests.WaitForMultiple*', '-147'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('Pack test results', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), '7z', 'a', '-xr!*.pdb', 'testlogs_r' + build_properties['got_revision'] + '_b' + str(build_properties['buildnumber']) + '.7z', 'build_drmemory-dbg-32/logs', 'build_drmemory-dbg-32/Testing/Temporary', 'build_drmemory-rel-32/logs', 'build_drmemory-rel-32/Testing/Temporary', 'build_drmemory-dbg-64/logs', 'build_drmemory-dbg-64/Testing/Temporary', 'build_drmemory-rel-64/logs', 'build_drmemory-rel-64/Testing/Temporary', 'xmlresults'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.gsutil.upload('testlogs_r' + build_properties['got_revision'] + '_b' + str(api.properties['buildnumber']) + '.7z', 'chromium-drmemory-builds', 'testlogs/from_%s' % api.properties['buildername']) def mac_builder_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'drmemory' soln.url = 'https://github.com/DynamoRIO/drmemory.git' soln.custom_deps = {'drmemory/dynamorio': 'https://github.com/DynamoRIO/dynamorio.git', 'tools/buildbot': 'https://github.com/DynamoRIO/buildbot.git'} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) api.step('Package Dr. Memory', ['ctest', '-VV', '-S', str(api.path['checkout'].join('package.cmake')) + ',build=0x' + build_properties['got_revision'][:7] + ';drmem_only']) api.gsutil.upload('DrMemory-MacOS-*' + build_properties['got_revision'][:7] + '.tar.gz', 'chromium-drmemory-builds', 'builds/') def win_builder_steps(api): build_properties = api.properties.legacy() src_cfg = api.gclient.make_config(GIT_MODE=True) soln = src_cfg.solutions.add() soln.name = 'drmemory' soln.url = 'https://github.com/DynamoRIO/drmemory.git' soln.custom_deps = {'drmemory/dynamorio': 'https://github.com/DynamoRIO/dynamorio.git', 'tools/buildbot': 'https://github.com/DynamoRIO/buildbot.git'} api.gclient.c = src_cfg result = api.bot_update.ensure_checkout(force=True) build_properties.update(result.json.output.get('properties', {})) api.step('unpack tools', [api.path['slave_build'].join('tools', 'buildbot', 'bot_tools', 'unpack.bat')], env={}, cwd=api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')) api.step('Package Dr. Memory', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), 'ctest', '-VV', '-S', str(api.path['checkout'].join('package.cmake')) + ',build=0x' + build_properties['got_revision'][:7] + ';drmem_only'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}, cwd=api.path['slave_build']) step_result = api.step('Find package basename', ['dir', '/B', 'DrMemory-Windows-*0x' + build_properties['got_revision'][:7] + '.zip'], stdout=api.raw_io.output(), cwd=api.path['slave_build']) basename = step_result.stdout[:-4] api.step('Delete prior sfx archive', ['del', basename + '-sfx.exe'], cwd=api.path['slave_build']) api.step('create sfx archive', [api.path['build'].join('scripts', 'slave', 'drmemory', 'build_env.bat'), '7z', 'a', '-sfx', basename + '-sfx.exe', 'build_drmemory-debug-32\\_CPack_Packages\\Windows\\ZIP\\' + basename + '\\*'], cwd=api.path['slave_build'], env={'BOTTOOLS': api.path['slave_build'].join('tools', 'buildbot', 'bot_tools')}) api.step('copy locally', ['copy', basename + '-sfx.exe', 'drmemory-windows-latest-sfx.exe'], cwd=api.path['slave_build']) api.gsutil.upload('drmemory-windows-latest-sfx.exe', 'chromium-drmemory-builds', '', cwd=api.path['slave_build']) api.gsutil.upload('DrMemory-Windows-*' + build_properties['got_revision'][:7] + '.zip', 'chromium-drmemory-builds', 'builds/') dispatch_directory = {'linux-builder': linux_builder_steps, 'linux-lucid_x64-drm': linux_lucid_x64_drm_steps, 'win-vista_x64-drm': win_vista_x64_drm_steps, 'mac-mavericks_x64-DR': mac_mavericks_x64_DR_steps, 'linux-cr-builder': linux_cr_builder_steps, 'mac-builder-DR': mac_builder_DR_steps, 'win-xp-drm': win_xp_drm_steps, 'mac-mavericks_x64-drm': mac_mavericks_x64_drm_steps, 'linux-cr': linux_cr_steps, 'win8-cr-builder': win8_cr_builder_steps, 'win8-cr': win8_cr_steps, 'win7-cr': win7_cr_steps, 'win-8_x64-drm': win_8_x64_drm_steps, 'win7-cr-builder': win7_cr_builder_steps, 'win-7_x64-drm': win_7_x64_drm_steps, 'mac-builder': mac_builder_steps, 'win-builder': win_builder_steps} def run_steps(api): if api.properties['buildername'] not in dispatch_directory: raise api.step.StepFailure('Builder unsupported by recipe.') else: dispatch_directory[api.properties['buildername']](api) def gen_tests(api): yield (api.test('linux_builder') + api.properties(mastername='client.drmemory') + api.properties(buildername='linux-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('linux_lucid_x64_drm') + api.properties(mastername='client.drmemory') + api.properties(buildername='linux-lucid_x64-drm') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('win_vista_x64_drm') + api.properties(mastername='client.drmemory') + api.properties(buildername='win-vista_x64-drm') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('mac_mavericks_x64_DR') + api.properties(mastername='client.drmemory') + api.properties(buildername='mac-mavericks_x64-DR') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('linux_cr_builder') + api.properties(mastername='client.drmemory') + api.properties(buildername='linux-cr-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('linux_cr_builder_clobber') + api.properties(mastername='client.drmemory') + api.properties(buildername='linux-cr-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') + api.properties(clobber='')) yield (api.test('mac_builder_DR') + api.properties(mastername='client.drmemory') + api.properties(buildername='mac-builder-DR') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('win_xp_drm') + api.properties(mastername='client.drmemory') + api.properties(buildername='win-xp-drm') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('mac_mavericks_x64_drm') + api.properties(mastername='client.drmemory') + api.properties(buildername='mac-mavericks_x64-drm') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('linux_cr') + api.properties(mastername='client.drmemory') + api.properties(buildername='linux-cr') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('win8_cr_builder') + api.properties(mastername='client.drmemory') + api.properties(buildername='win8-cr-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('win8_cr_builder_clobber') + api.properties(mastername='client.drmemory') + api.properties(buildername='win8-cr-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') + api.properties(clobber='')) yield (api.test('win8_cr') + api.properties(mastername='client.drmemory') + api.properties(buildername='win8-cr') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') + api.step_data('Get the revision number', stdout=api.raw_io.output('Dr. Memory version 1.9.16845 -- build 178560794'))) yield (api.test('win7_cr') + api.properties(mastername='client.drmemory') + api.properties(buildername='win7-cr') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') + api.step_data('Get the revision number', stdout=api.raw_io.output('Dr. Memory version 1.9.16845 -- build 178560794'))) yield (api.test('win_8_x64_drm') + api.properties(mastername='client.drmemory') + api.properties(buildername='win-8_x64-drm') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('win7_cr_builder') + api.properties(mastername='client.drmemory') + api.properties(buildername='win7-cr-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('win7_cr_builder_clobber') + api.properties(mastername='client.drmemory') + api.properties(buildername='win7-cr-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') + api.properties(clobber='')) yield (api.test('win_7_x64_drm') + api.properties(mastername='client.drmemory') + api.properties(buildername='win-7_x64-drm') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('mac_builder') + api.properties(mastername='client.drmemory') + api.properties(buildername='mac-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave')) yield (api.test('win_builder') + api.properties(mastername='client.drmemory') + api.properties(buildername='win-builder') + api.properties(revision='123456789abcdef') + api.properties(got_revision='123456789abcdef') + api.properties(buildnumber=42) + api.properties(slavename='TestSlave') + api.step_data('Find package basename', stdout=api.raw_io.output('DrMemory-Windows-1.2.3-0x1234567.zip'))) yield (api.test('builder_not_in_dispatch_directory') + api.properties(mastername='client.drmemory') + api.properties(buildername='nonexistent_builder') + api.properties(slavename='TestSlave'))
#!/usr/bin/env python # Use generators to avoid crashed in memory when needed to interate on large set of data # Generators can be built with the syntax of list comprehensions but inside () names = ['Tim', 'Mark', 'Donna', 'Albert', 'Sara'] gen_a = (len(n) for n in names) print(next(gen_a)) print(next(gen_a)) # You define a generator function, using the yield keyword to return a value def my_generator(): names = ['Gianluca', 'Lisa', 'Sofia', 'Giulia'] for i in names: yield i # You define a generator iterator as an instance of the function gen = my_generator() # You call next to generate the next value print(next(gen)) print(next(gen)) # Being the generator an iterator you can use it in a for loop as well # notes that we keep generating from where we left for val in gen: print(val) # Remember: generators are used to generate the next value, # they allow you to iterate over values without having to load them # in memory. That's a key difference from a function where you # only get a chance to return all results all at the same time. # For example: # 1. when you read a file the built in mechanism is a generator # 2. the xrange uses a generator # yield: what it does is save the "state" of a generator function
names = ['Tim', 'Mark', 'Donna', 'Albert', 'Sara'] gen_a = (len(n) for n in names) print(next(gen_a)) print(next(gen_a)) def my_generator(): names = ['Gianluca', 'Lisa', 'Sofia', 'Giulia'] for i in names: yield i gen = my_generator() print(next(gen)) print(next(gen)) for val in gen: print(val)
def largest_product(a_list): if len(a_list) == 0: return False column = 0 row = 0 big = a_list[0][0] * a_list[0][1] while column < len(a_list) - 1: if a_list[column][row] * a_list[column][row + 1] > big: big = a_list[column][row] * a_list[column][row + 1] if a_list[column][row] * a_list[column + 1][row] > big: big = a_list[column][row] * a_list[column + 1][row] if a_list[column][row] * a_list[column + 1][row + 1] > big: big = a_list[column][row] * a_list[column + 1][row + 1] if a_list[column + 1][row] * a_list[column + 1][row + 1]: big = a_list[column + 1][row] * a_list[column + 1][row + 1] if a_list[column][row + 1] * a_list[column + 1][row + 1]: a_list[column][row + 1] * a_list[column + 1][row + 1] column += 1 return big
def largest_product(a_list): if len(a_list) == 0: return False column = 0 row = 0 big = a_list[0][0] * a_list[0][1] while column < len(a_list) - 1: if a_list[column][row] * a_list[column][row + 1] > big: big = a_list[column][row] * a_list[column][row + 1] if a_list[column][row] * a_list[column + 1][row] > big: big = a_list[column][row] * a_list[column + 1][row] if a_list[column][row] * a_list[column + 1][row + 1] > big: big = a_list[column][row] * a_list[column + 1][row + 1] if a_list[column + 1][row] * a_list[column + 1][row + 1]: big = a_list[column + 1][row] * a_list[column + 1][row + 1] if a_list[column][row + 1] * a_list[column + 1][row + 1]: a_list[column][row + 1] * a_list[column + 1][row + 1] column += 1 return big
### Dielectric class class Dielectric: ## Intialization function with all properties def __init__(self, pos_x, pos_y, width, height, eps_r): self.pos_x = pos_x self.pos_y = pos_y self.width = width self.height = height self.eps_r = eps_r ## String representation functions def __str__(self): return "x: {}, y: {}, w: {}, h: {}, eps_r: {}".format( self.pos_x, self.pos_y, self.width, self.height, self.eps_r ) def __repr__(self): return self.__str__()
class Dielectric: def __init__(self, pos_x, pos_y, width, height, eps_r): self.pos_x = pos_x self.pos_y = pos_y self.width = width self.height = height self.eps_r = eps_r def __str__(self): return 'x: {}, y: {}, w: {}, h: {}, eps_r: {}'.format(self.pos_x, self.pos_y, self.width, self.height, self.eps_r) def __repr__(self): return self.__str__()
def ceaser(message): ciphered = "" for c in message: if c.isalpha(): if c.isupper(): upper = True else: upper = False c = c.upper() place = ord(c) if place+13 > 90: place = (place+13 - 90) + 64 else: place = place + 13 if upper: ciphered += chr(place) else: ciphered += chr(place).lower() else: ciphered += c return ciphered
def ceaser(message): ciphered = '' for c in message: if c.isalpha(): if c.isupper(): upper = True else: upper = False c = c.upper() place = ord(c) if place + 13 > 90: place = place + 13 - 90 + 64 else: place = place + 13 if upper: ciphered += chr(place) else: ciphered += chr(place).lower() else: ciphered += c return ciphered
# # PySNMP MIB module CONV-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CONV-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:11:06 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection") Alias, cxConv = mibBuilder.importSymbols("CXProduct-SMI", "Alias", "cxConv") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") ObjectIdentity, iso, Bits, TimeTicks, Counter32, Counter64, Gauge32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Unsigned32, NotificationType, ModuleIdentity, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "iso", "Bits", "TimeTicks", "Counter32", "Counter64", "Gauge32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Unsigned32", "NotificationType", "ModuleIdentity", "Integer32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") cxConvTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1), ) if mibBuilder.loadTexts: cxConvTable.setStatus('mandatory') cxConvEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1), ).setIndexNames((0, "CONV-MIB", "cxConvPort")) if mibBuilder.loadTexts: cxConvEntry.setStatus('mandatory') cxConvPort = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: cxConvPort.setStatus('mandatory') cxConvPortAlias = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 2), Alias()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxConvPortAlias.setStatus('mandatory') cxConvRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("invalid", 1), ("valid", 2))).clone('valid')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxConvRowStatus.setStatus('mandatory') cxConvIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cxConvIfIndex.setStatus('mandatory') cxConvState = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("on", 1), ("off", 2))).clone('on')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxConvState.setStatus('mandatory') cxConvCompression = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxConvCompression.setStatus('mandatory') cxConvCompCompatibility = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("compatibleMemotec", 1), ("compatibleACC", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxConvCompCompatibility.setStatus('mandatory') cxFwkCircuitTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2), ) if mibBuilder.loadTexts: cxFwkCircuitTable.setStatus('mandatory') cxFwkCircuitEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1), ).setIndexNames((0, "CONV-MIB", "cxFwkCircuitPort")) if mibBuilder.loadTexts: cxFwkCircuitEntry.setStatus('mandatory') cxFwkCircuitPort = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cxFwkCircuitPort.setStatus('mandatory') cxFwkCircuitState = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(256, 1, 2, 3, 4))).clone(namedValues=NamedValues(("idle", 256), ("opened", 1), ("closed", 2), ("opening", 3), ("openFailed", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: cxFwkCircuitState.setStatus('mandatory') cxFwkCircuitRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("invalid", 1), ("valid", 2))).clone('valid')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxFwkCircuitRowStatus.setStatus('mandatory') cxFwkServiceType = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 256))).clone(namedValues=NamedValues(("frameRelay", 1), ("notSpecified", 256)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxFwkServiceType.setStatus('mandatory') cxFwkServiceProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("cls", 1), ("pvc", 2), ("svc", 3), ("char", 4)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxFwkServiceProtocol.setStatus('mandatory') cxFwkServiceName = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(16, 16)).setFixedLength(16)).setMaxAccess("readonly") if mibBuilder.loadTexts: cxFwkServiceName.setStatus('mandatory') cxFwkDestAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(20, 20)).setFixedLength(20)).setMaxAccess("readonly") if mibBuilder.loadTexts: cxFwkDestAddress.setStatus('mandatory') cxFwkDestAlias = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 8), Alias()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxFwkDestAlias.setStatus('mandatory') cxFwkServiceCircuitMdu = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 8192)).clone(1600)).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxFwkServiceCircuitMdu.setStatus('mandatory') cxFwkServiceCost = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1000000))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxFwkServiceCost.setStatus('mandatory') cxFwkServiceCardId = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: cxFwkServiceCardId.setStatus('mandatory') cxFwkServiceSapId = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cxFwkServiceSapId.setStatus('mandatory') cxFwkServiceRouteRef = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxFwkServiceRouteRef.setStatus('mandatory') cxFwkStatsInternalErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 15), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cxFwkStatsInternalErrors.setStatus('mandatory') cxFwkStatsRegistrationErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 16), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cxFwkStatsRegistrationErrors.setStatus('mandatory') cxFwkStatsQueryErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 17), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cxFwkStatsQueryErrors.setStatus('mandatory') cxFwkStatsOpenErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 18), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cxFwkStatsOpenErrors.setStatus('mandatory') cxFwkStatsResets = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 19), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cxFwkStatsResets.setStatus('mandatory') mibBuilder.exportSymbols("CONV-MIB", cxConvState=cxConvState, cxConvRowStatus=cxConvRowStatus, cxConvPortAlias=cxConvPortAlias, cxFwkServiceCardId=cxFwkServiceCardId, cxFwkStatsOpenErrors=cxFwkStatsOpenErrors, cxFwkDestAlias=cxFwkDestAlias, cxConvCompCompatibility=cxConvCompCompatibility, cxFwkStatsQueryErrors=cxFwkStatsQueryErrors, cxFwkServiceName=cxFwkServiceName, cxFwkServiceProtocol=cxFwkServiceProtocol, cxFwkDestAddress=cxFwkDestAddress, cxConvEntry=cxConvEntry, cxConvIfIndex=cxConvIfIndex, cxFwkServiceCircuitMdu=cxFwkServiceCircuitMdu, cxFwkServiceCost=cxFwkServiceCost, cxFwkCircuitPort=cxFwkCircuitPort, cxFwkStatsInternalErrors=cxFwkStatsInternalErrors, cxFwkServiceSapId=cxFwkServiceSapId, cxFwkCircuitTable=cxFwkCircuitTable, cxFwkStatsRegistrationErrors=cxFwkStatsRegistrationErrors, cxConvPort=cxConvPort, cxFwkCircuitEntry=cxFwkCircuitEntry, cxFwkCircuitState=cxFwkCircuitState, cxFwkCircuitRowStatus=cxFwkCircuitRowStatus, cxFwkServiceType=cxFwkServiceType, cxFwkStatsResets=cxFwkStatsResets, cxFwkServiceRouteRef=cxFwkServiceRouteRef, cxConvTable=cxConvTable, cxConvCompression=cxConvCompression)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection') (alias, cx_conv) = mibBuilder.importSymbols('CXProduct-SMI', 'Alias', 'cxConv') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (object_identity, iso, bits, time_ticks, counter32, counter64, gauge32, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, unsigned32, notification_type, module_identity, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'ObjectIdentity', 'iso', 'Bits', 'TimeTicks', 'Counter32', 'Counter64', 'Gauge32', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'Unsigned32', 'NotificationType', 'ModuleIdentity', 'Integer32') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') cx_conv_table = mib_table((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1)) if mibBuilder.loadTexts: cxConvTable.setStatus('mandatory') cx_conv_entry = mib_table_row((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1)).setIndexNames((0, 'CONV-MIB', 'cxConvPort')) if mibBuilder.loadTexts: cxConvEntry.setStatus('mandatory') cx_conv_port = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535))).setMaxAccess('readonly') if mibBuilder.loadTexts: cxConvPort.setStatus('mandatory') cx_conv_port_alias = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 2), alias()).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxConvPortAlias.setStatus('mandatory') cx_conv_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('invalid', 1), ('valid', 2))).clone('valid')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxConvRowStatus.setStatus('mandatory') cx_conv_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cxConvIfIndex.setStatus('mandatory') cx_conv_state = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('on', 1), ('off', 2))).clone('on')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxConvState.setStatus('mandatory') cx_conv_compression = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 6), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxConvCompression.setStatus('mandatory') cx_conv_comp_compatibility = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('compatibleMemotec', 1), ('compatibleACC', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxConvCompCompatibility.setStatus('mandatory') cx_fwk_circuit_table = mib_table((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2)) if mibBuilder.loadTexts: cxFwkCircuitTable.setStatus('mandatory') cx_fwk_circuit_entry = mib_table_row((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1)).setIndexNames((0, 'CONV-MIB', 'cxFwkCircuitPort')) if mibBuilder.loadTexts: cxFwkCircuitEntry.setStatus('mandatory') cx_fwk_circuit_port = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cxFwkCircuitPort.setStatus('mandatory') cx_fwk_circuit_state = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(256, 1, 2, 3, 4))).clone(namedValues=named_values(('idle', 256), ('opened', 1), ('closed', 2), ('opening', 3), ('openFailed', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: cxFwkCircuitState.setStatus('mandatory') cx_fwk_circuit_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('invalid', 1), ('valid', 2))).clone('valid')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxFwkCircuitRowStatus.setStatus('mandatory') cx_fwk_service_type = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 256))).clone(namedValues=named_values(('frameRelay', 1), ('notSpecified', 256)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxFwkServiceType.setStatus('mandatory') cx_fwk_service_protocol = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('cls', 1), ('pvc', 2), ('svc', 3), ('char', 4)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxFwkServiceProtocol.setStatus('mandatory') cx_fwk_service_name = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 6), octet_string().subtype(subtypeSpec=value_size_constraint(16, 16)).setFixedLength(16)).setMaxAccess('readonly') if mibBuilder.loadTexts: cxFwkServiceName.setStatus('mandatory') cx_fwk_dest_address = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 7), octet_string().subtype(subtypeSpec=value_size_constraint(20, 20)).setFixedLength(20)).setMaxAccess('readonly') if mibBuilder.loadTexts: cxFwkDestAddress.setStatus('mandatory') cx_fwk_dest_alias = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 8), alias()).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxFwkDestAlias.setStatus('mandatory') cx_fwk_service_circuit_mdu = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 9), integer32().subtype(subtypeSpec=value_range_constraint(0, 8192)).clone(1600)).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxFwkServiceCircuitMdu.setStatus('mandatory') cx_fwk_service_cost = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(0, 1000000))).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxFwkServiceCost.setStatus('mandatory') cx_fwk_service_card_id = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 11), integer32().subtype(subtypeSpec=value_range_constraint(1, 16))).setMaxAccess('readonly') if mibBuilder.loadTexts: cxFwkServiceCardId.setStatus('mandatory') cx_fwk_service_sap_id = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 12), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cxFwkServiceSapId.setStatus('mandatory') cx_fwk_service_route_ref = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 13), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxFwkServiceRouteRef.setStatus('mandatory') cx_fwk_stats_internal_errors = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 15), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cxFwkStatsInternalErrors.setStatus('mandatory') cx_fwk_stats_registration_errors = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 16), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cxFwkStatsRegistrationErrors.setStatus('mandatory') cx_fwk_stats_query_errors = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 17), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cxFwkStatsQueryErrors.setStatus('mandatory') cx_fwk_stats_open_errors = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 18), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cxFwkStatsOpenErrors.setStatus('mandatory') cx_fwk_stats_resets = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 8, 2, 1, 19), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cxFwkStatsResets.setStatus('mandatory') mibBuilder.exportSymbols('CONV-MIB', cxConvState=cxConvState, cxConvRowStatus=cxConvRowStatus, cxConvPortAlias=cxConvPortAlias, cxFwkServiceCardId=cxFwkServiceCardId, cxFwkStatsOpenErrors=cxFwkStatsOpenErrors, cxFwkDestAlias=cxFwkDestAlias, cxConvCompCompatibility=cxConvCompCompatibility, cxFwkStatsQueryErrors=cxFwkStatsQueryErrors, cxFwkServiceName=cxFwkServiceName, cxFwkServiceProtocol=cxFwkServiceProtocol, cxFwkDestAddress=cxFwkDestAddress, cxConvEntry=cxConvEntry, cxConvIfIndex=cxConvIfIndex, cxFwkServiceCircuitMdu=cxFwkServiceCircuitMdu, cxFwkServiceCost=cxFwkServiceCost, cxFwkCircuitPort=cxFwkCircuitPort, cxFwkStatsInternalErrors=cxFwkStatsInternalErrors, cxFwkServiceSapId=cxFwkServiceSapId, cxFwkCircuitTable=cxFwkCircuitTable, cxFwkStatsRegistrationErrors=cxFwkStatsRegistrationErrors, cxConvPort=cxConvPort, cxFwkCircuitEntry=cxFwkCircuitEntry, cxFwkCircuitState=cxFwkCircuitState, cxFwkCircuitRowStatus=cxFwkCircuitRowStatus, cxFwkServiceType=cxFwkServiceType, cxFwkStatsResets=cxFwkStatsResets, cxFwkServiceRouteRef=cxFwkServiceRouteRef, cxConvTable=cxConvTable, cxConvCompression=cxConvCompression)
# 268. Missing Number # Runtime: 132 ms, faster than 76.58% of Python3 online submissions for Missing Number. # Memory Usage: 15.5 MB, less than 51.40% of Python3 online submissions for Missing Number. class Solution: # Gauss' Formula def missingNumber(self, nums: list[int]) -> int: expected_sum = len(nums) * (len(nums) + 1) // 2 return expected_sum - sum(nums)
class Solution: def missing_number(self, nums: list[int]) -> int: expected_sum = len(nums) * (len(nums) + 1) // 2 return expected_sum - sum(nums)
def redis_key(project_slug, key, *namespaces): """ Generates project dependent Redis key >>> redis_key('a', 'b') 'a:b' >>> redis_key('a', 'b', 'c', 'd') 'a:c:d:b' >>> redis_key('a', 1, 'c', None) 'a:c:1' """ l = [project_slug] if namespaces: l.extend(namespaces) l.append(key) return ':'.join(str(i)for i in l if i) class RedisMixin: project_slug = None @classmethod def redis_key(cls, key, namespace): return redis_key(cls.project_slug, key, namespace) @classmethod async def redis(cls, request, key, *, value=None, sadd=None, expire=None, default=None, namespace=None, smembers=False, srem=None, delete=False, connection=None): key = cls.redis_key(key, namespace) async def _redis(cache): if value: await cache.set(key, value) elif delete: await cache.delete(key) elif sadd: if isinstance(sadd, (list, tuple)): await cache.sadd(key, *sadd) else: await cache.sadd(key, sadd) elif smembers: v = await cache.smembers(key) return v or default elif srem: return await cache.srem(key, srem) elif not expire: return (await cache.get(key)) or default if expire: await cache.expire(key, int(expire)) if connection is not None: return await _redis(connection) else: async with request.app.redis.get() as connection: return await _redis(connection)
def redis_key(project_slug, key, *namespaces): """ Generates project dependent Redis key >>> redis_key('a', 'b') 'a:b' >>> redis_key('a', 'b', 'c', 'd') 'a:c:d:b' >>> redis_key('a', 1, 'c', None) 'a:c:1' """ l = [project_slug] if namespaces: l.extend(namespaces) l.append(key) return ':'.join((str(i) for i in l if i)) class Redismixin: project_slug = None @classmethod def redis_key(cls, key, namespace): return redis_key(cls.project_slug, key, namespace) @classmethod async def redis(cls, request, key, *, value=None, sadd=None, expire=None, default=None, namespace=None, smembers=False, srem=None, delete=False, connection=None): key = cls.redis_key(key, namespace) async def _redis(cache): if value: await cache.set(key, value) elif delete: await cache.delete(key) elif sadd: if isinstance(sadd, (list, tuple)): await cache.sadd(key, *sadd) else: await cache.sadd(key, sadd) elif smembers: v = await cache.smembers(key) return v or default elif srem: return await cache.srem(key, srem) elif not expire: return await cache.get(key) or default if expire: await cache.expire(key, int(expire)) if connection is not None: return await _redis(connection) else: async with request.app.redis.get() as connection: return await _redis(connection)
# coding=utf-8 # Author: Jianghan LI # Question: 094.Binary_Tree_Inorder_Traversal # Date: 2017-07-03 13:26 - 13:37, 0 wrong try # Complexity: O(N) # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): # Recursive solution is trivial def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right) if root else [] # iteratively def inorderTraversal(self, root): stack = [] ret = [] cur = root while 1: while cur: stack.append(cur) cur = cur.left if not stack: break cur = stack.pop() ret.append(cur.val) cur = cur.right return ret # a little better, change condition def inorderTraversal(self, root): stack, ret, cur = [], [], root while cur or stack: while cur: stack.append(cur) cur = cur.left cur = stack.pop() ret.append(cur.val) cur = cur.right return ret # stack replaces recursion stack # cur replaces recursion input # ret repalces ruduced return value
class Solution(object): def inorder_traversal(self, root): """ :type root: TreeNode :rtype: List[int] """ return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right) if root else [] def inorder_traversal(self, root): stack = [] ret = [] cur = root while 1: while cur: stack.append(cur) cur = cur.left if not stack: break cur = stack.pop() ret.append(cur.val) cur = cur.right return ret def inorder_traversal(self, root): (stack, ret, cur) = ([], [], root) while cur or stack: while cur: stack.append(cur) cur = cur.left cur = stack.pop() ret.append(cur.val) cur = cur.right return ret
# -*- coding: utf-8 -*- def pizza(): print("Pizzaaaaaaa") def nuggets(): print("Course de poussins!") def quiche(): print("Qui?") def croques(): print("Ma machine est partie...") def courgettes(): print("Non, pas de courgettes :'(") def choix_repas_moche(num_choix=4): """ Choix d'un repas en utilisant les if/else """ if num_choix == 1: pizza() if num_choix == 2: nuggets() if num_choix == 3: quiche() if num_choix == 4: courgettes() def choix_repas(num_choix=4): """ Choix d'un repas en utilisant les dictionnaires """ choix = {1: pizza, 2: nuggets, 3: quiche, 4: courgettes} return choix.get(num_choix, 4)() if __name__ == '__main__': choix_repas(1) choix_repas(2) choix_repas(3) choix_repas(4) choix_repas()
def pizza(): print('Pizzaaaaaaa') def nuggets(): print('Course de poussins!') def quiche(): print('Qui?') def croques(): print('Ma machine est partie...') def courgettes(): print("Non, pas de courgettes :'(") def choix_repas_moche(num_choix=4): """ Choix d'un repas en utilisant les if/else """ if num_choix == 1: pizza() if num_choix == 2: nuggets() if num_choix == 3: quiche() if num_choix == 4: courgettes() def choix_repas(num_choix=4): """ Choix d'un repas en utilisant les dictionnaires """ choix = {1: pizza, 2: nuggets, 3: quiche, 4: courgettes} return choix.get(num_choix, 4)() if __name__ == '__main__': choix_repas(1) choix_repas(2) choix_repas(3) choix_repas(4) choix_repas()
class Solution: def removeOuterParentheses(self, S: str) -> str: res = "" level = 0 start = 0 for i, c in enumerate(S): if c == "(": level += 1 if c == ")": level -= 1 if level == 0: res += S[start + 1 : i] start = i + 1 return res
class Solution: def remove_outer_parentheses(self, S: str) -> str: res = '' level = 0 start = 0 for (i, c) in enumerate(S): if c == '(': level += 1 if c == ')': level -= 1 if level == 0: res += S[start + 1:i] start = i + 1 return res
class Linked_List: class __Node: def __init__(self, val): # declare and initialize the private attributes # for objects of the Node class. # TODO replace pass with your implementation self.val=val self.prev=None self.next=None def __init__(self): # declare and initialize the private attributes # for objects of the sentineled Linked_List class # TODO replace pass with your implementation self.__header = self.__Node(None) self.__trailer = self.__Node(None) self.__header.next = self.__trailer # trailer is after header self.__trailer.prev = self.__header # header is before trailer self.__size = 0 def __len__(self): # return the number of value-containing nodes in # this list. # TODO replace pass with your implementation ##??????SHOULD THIS WALK THROUGH return self.__size def append_element(self, val): # increase the size of the list by one, and add a # node containing val at the new tail position. this # is the only way to add items at the tail position. # TODO replace pass with your implementation new_node = Linked_List.__Node(val) self.__trailer.prev.next = new_node new_node.next=self.__trailer new_node.prev=self.__trailer.prev self.__trailer.prev = new_node self.__size = self.__size + 1 def insert_element_at(self, val, index): # assuming the head position (not the header node) # is indexed 0, add a node containing val at the # specified index. If the index is not a valid # position within the list, raise an IndexError # exception. This method cannot be used to add an # item at the tail position. # TODO replace pass with your implementation if index >= self.__size: raise IndexError if index < 0: raise IndexError new_node = Linked_List.__Node(val) current = self.__header for i in range(0, index): current = current.next new_node.next = current.next new_node.prev = current current.next = new_node new_node.next.prev = new_node self.__size = self.__size + 1 def remove_element_at(self, index): # assuming the head position (not the header node) # is indexed 0, remove and return the value stored # in the node at the specified index. If the index # is invalid, raise an IndexError exception. # TODO replace pass with your implementation if index >= self.__size: raise IndexError if index < 0: raise IndexError if self.__size == 0: raise IndexError current = self.__header for i in range(0, index): current = current.next valremoved=current.next.val current.next=current.next.next current.next.prev=current self.__size = self.__size - 1 return valremoved def get_element_at(self, index): # assuming the head position (not the header node) # is indexed 0, return the value stored in the node # at the specified index, but do not unlink it from # the list. If the specified index is invalid, raise # an IndexError exception. # TODO replace pass with your implementation if index >= self.__size: raise IndexError if index < 0: raise IndexError if self.__size == 0: raise IndexError current = self.__header for i in range(0, index): current = current.next return current.next.val #####CHECK CORRECT SYNTAX FOR THIS def rotate_left(self): # rotate the list left one position. Conceptual indices # should all decrease by one, except for the head, which # should become the tail. For example, if the list is # [ 5, 7, 9, -4 ], this method should alter it to # [ 7, 9, -4, 5 ]. This method should modify the list in # place and must not return a value. # TODO replace pass with your implementation. if self.__size==0: raise IndexError self.__trailer.prev.next = self.__header.next self.__header.next = self.__header.next.next self.__header.next.prev=self.__header self.__trailer.prev.next.prev=self.__trailer.prev self.__trailer.prev.next.next=self.__trailer self.__trailer.prev=self.__trailer.prev.next def __str__(self): # return a string representation of the list's # contents. An empty list should appear as [ ]. # A list with one element should appear as [ 5 ]. # A list with two elements should appear as [ 5, 7 ]. # You may assume that the values stored inside of the # node objects implement the __str__() method, so you # call str(val_object) on them to get their string # representations. # TODO replace pass with your implementation current = self.__header.next stringlist = list() stringlist.append("[") if self.__size==0: stringlist.append(" ") else: while(current != self.__trailer): element = str(current.val) stringlist.append(" " + element) if current.next != self.__trailer: stringlist.append(",") else: stringlist.append(" ") current = current.next stringlist.append("]") stringlist = "".join(stringlist) return stringlist def __iter__(self): # initialize a new attribute for walking through your list # TODO insert your initialization code before the return # statement. do not modify the return statement. self.__iter_index = 0 self.__current = self.__header return self def __next__(self): # using the attribute that you initialized in __iter__(), # fetch the next value and return it. If there are no more # values to fetch, raise a StopIteration exception. # TODO replace pass with your implementation if self.__iter_index == self.__size: raise StopIteration self.__current = self.__current.next self.__iter_index = self.__iter_index + 1 return self.__current.val if __name__ == '__main__': # Your test code should go here. Be sure to look at cases # when the list is empty, when it has one element, and when # it has several elements. Do the indexed methods raise exceptions # when given invalid indices? Do they position items # correctly when given valid indices? Does the string # representation of your list conform to the specified format? # Does removing an element function correctly regardless of that # element's location? Does a for loop iterate through your list # from head to tail? Your writeup should explain why you chose the # test cases. Leave all test cases in your code when submitting. # TODO replace pass with your tests list1 = Linked_List() list1.append_element(5) list1.append_element(6) list1.append_element(3) list1.append_element(-7) print("Original List:") print(list1.__str__()) print("Original Length:") print(list1.__len__()) ##Testing Insert-SHOULD WORK print("Testing Insert With Valid Index") try: list1.insert_element_at(-2, 0) except IndexError: print("Invalid index!!") print("New List:") print(list1.__str__()) print("New Length:") print(list1.__len__()) ##Testing Insert-SHOULD GIVE ERROR print("Testing Insert With Invalid Index") try: list1.insert_element_at(9,7) except IndexError: print("Invalid index!!") print(list1.__str__()) ##Testing Insert-SHOULD GIVE ERROR print("Testing Insert With Invalid Index") try: list1.insert_element_at(9,-1) except IndexError: print("Invalid index!!") print(list1.__str__()) ##Testing Remove-SHOULD WORK print("Testing Remove With Valid Index") try: list1.remove_element_at(2) except: print("Invalid index!!") print("New List:") print(list1.__str__()) print("New Length:") print(list1.__len__()) ##Testing Remove-SHOULD GIVE ERROR print("Testing Remove With Invalid Index") try: list1.remove_element_at(-1) except: print("Invalid index!!") print(list1.__str__()) ##Testing Remove-SHOULD GIVE ERROR print("Testing Remove With Invalid Index") try: list1.remove_element_at(10) except: print("Invalid index!!") print(list1.__str__()) ##Testing Get element at-SHOULD WORK print("Testing Get Element With Valid Index") try: list1.get_element_at(1) except: print("Invalid index!!") print(list1.get_element_at(1)) ##Testing Get element at-SHOULD GIVE ERROR print("Testing Get Element With Invalid Index") try: list1.get_element_at(-1) except: print("Invalid index!!") ##Testing Get element at-SHOULD GIVE ERROR print("Testing Get Element With Invalid Index") try: list1.get_element_at(19) except: print("Invalid index!!") print("Rotate Left Output") list1.rotate_left() print(list1.__str__()) print("Size:") print(list1.__len__()) print("Iterator:") for val in list1: print(val) ##empty list list2 = Linked_List() print("Original List:") print(list2.__str__()) print("Original Length:") print(list2.__len__()) ##testing insert-should give error print("Testing Insert With Invalid Index") try: list2.insert_element_at(9,0) except IndexError: print("Invalid index!!") print(list2.__str__()) ##testing remove-SHOULD GIVE ERROR print("Testing Remove With Invalid Index") try: list2.remove_element_at(1) except: print("Invalid index!!") print(list2.__str__()) ##Testing Get element at-SHOULD GIVE ERROR print("Testing Get Element With Invalid Index") try: list2.get_element_at(0) except: print("Invalid index!!") print(list2.__str__()) print("Trying an incorrect use of rotate left:") try: list2.rotate_left() except IndexError: print("Rotate left doesn't work on an empty list!") list2.append_element(2) list2.append_element(6) list2.append_element(8) print("New List:") print(list2.__str__()) print("New Length:") print(list2.__len__())
class Linked_List: class __Node: def __init__(self, val): self.val = val self.prev = None self.next = None def __init__(self): self.__header = self.__Node(None) self.__trailer = self.__Node(None) self.__header.next = self.__trailer self.__trailer.prev = self.__header self.__size = 0 def __len__(self): return self.__size def append_element(self, val): new_node = Linked_List.__Node(val) self.__trailer.prev.next = new_node new_node.next = self.__trailer new_node.prev = self.__trailer.prev self.__trailer.prev = new_node self.__size = self.__size + 1 def insert_element_at(self, val, index): if index >= self.__size: raise IndexError if index < 0: raise IndexError new_node = Linked_List.__Node(val) current = self.__header for i in range(0, index): current = current.next new_node.next = current.next new_node.prev = current current.next = new_node new_node.next.prev = new_node self.__size = self.__size + 1 def remove_element_at(self, index): if index >= self.__size: raise IndexError if index < 0: raise IndexError if self.__size == 0: raise IndexError current = self.__header for i in range(0, index): current = current.next valremoved = current.next.val current.next = current.next.next current.next.prev = current self.__size = self.__size - 1 return valremoved def get_element_at(self, index): if index >= self.__size: raise IndexError if index < 0: raise IndexError if self.__size == 0: raise IndexError current = self.__header for i in range(0, index): current = current.next return current.next.val def rotate_left(self): if self.__size == 0: raise IndexError self.__trailer.prev.next = self.__header.next self.__header.next = self.__header.next.next self.__header.next.prev = self.__header self.__trailer.prev.next.prev = self.__trailer.prev self.__trailer.prev.next.next = self.__trailer self.__trailer.prev = self.__trailer.prev.next def __str__(self): current = self.__header.next stringlist = list() stringlist.append('[') if self.__size == 0: stringlist.append(' ') else: while current != self.__trailer: element = str(current.val) stringlist.append(' ' + element) if current.next != self.__trailer: stringlist.append(',') else: stringlist.append(' ') current = current.next stringlist.append(']') stringlist = ''.join(stringlist) return stringlist def __iter__(self): self.__iter_index = 0 self.__current = self.__header return self def __next__(self): if self.__iter_index == self.__size: raise StopIteration self.__current = self.__current.next self.__iter_index = self.__iter_index + 1 return self.__current.val if __name__ == '__main__': list1 = linked__list() list1.append_element(5) list1.append_element(6) list1.append_element(3) list1.append_element(-7) print('Original List:') print(list1.__str__()) print('Original Length:') print(list1.__len__()) print('Testing Insert With Valid Index') try: list1.insert_element_at(-2, 0) except IndexError: print('Invalid index!!') print('New List:') print(list1.__str__()) print('New Length:') print(list1.__len__()) print('Testing Insert With Invalid Index') try: list1.insert_element_at(9, 7) except IndexError: print('Invalid index!!') print(list1.__str__()) print('Testing Insert With Invalid Index') try: list1.insert_element_at(9, -1) except IndexError: print('Invalid index!!') print(list1.__str__()) print('Testing Remove With Valid Index') try: list1.remove_element_at(2) except: print('Invalid index!!') print('New List:') print(list1.__str__()) print('New Length:') print(list1.__len__()) print('Testing Remove With Invalid Index') try: list1.remove_element_at(-1) except: print('Invalid index!!') print(list1.__str__()) print('Testing Remove With Invalid Index') try: list1.remove_element_at(10) except: print('Invalid index!!') print(list1.__str__()) print('Testing Get Element With Valid Index') try: list1.get_element_at(1) except: print('Invalid index!!') print(list1.get_element_at(1)) print('Testing Get Element With Invalid Index') try: list1.get_element_at(-1) except: print('Invalid index!!') print('Testing Get Element With Invalid Index') try: list1.get_element_at(19) except: print('Invalid index!!') print('Rotate Left Output') list1.rotate_left() print(list1.__str__()) print('Size:') print(list1.__len__()) print('Iterator:') for val in list1: print(val) list2 = linked__list() print('Original List:') print(list2.__str__()) print('Original Length:') print(list2.__len__()) print('Testing Insert With Invalid Index') try: list2.insert_element_at(9, 0) except IndexError: print('Invalid index!!') print(list2.__str__()) print('Testing Remove With Invalid Index') try: list2.remove_element_at(1) except: print('Invalid index!!') print(list2.__str__()) print('Testing Get Element With Invalid Index') try: list2.get_element_at(0) except: print('Invalid index!!') print(list2.__str__()) print('Trying an incorrect use of rotate left:') try: list2.rotate_left() except IndexError: print("Rotate left doesn't work on an empty list!") list2.append_element(2) list2.append_element(6) list2.append_element(8) print('New List:') print(list2.__str__()) print('New Length:') print(list2.__len__())
which_one = int(input("What Months (1-12)?")) months = ['January' , 'February' , 'March' , 'April' , 'May' , 'June' , 'July' , 'August' , 'September' , 'October', 'November' , 'December'] if 1 <= which_one <= 12: print("Months " , months[which_one - 1])
which_one = int(input('What Months (1-12)?')) months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] if 1 <= which_one <= 12: print('Months ', months[which_one - 1])
""" Shows the mathematical timestable """ for i in range(1, 13): for j in range(1, 13): print("{0} times {1} is {2}".format(j, i, i * j)) print("--------------------------------")
""" Shows the mathematical timestable """ for i in range(1, 13): for j in range(1, 13): print('{0} times {1} is {2}'.format(j, i, i * j)) print('--------------------------------')
# Example 1 def setup(): # Set to the same size as the source image # https://unsplash.com/photos/mGy1Jjr2e6M size(900, 600) # Load and display and position the image image(loadImage("file.jpg"), 0, 0)
def setup(): size(900, 600) image(load_image('file.jpg'), 0, 0)
MOUSE_BTN_LEFT = b"\x90" MOUSE_BTN_RIGHT = b"\x91" MOUSE_BTN_MIDDLE = b"\x92" KEY_LEFT_CTRL = b"\xe0" KEY_LEFT_SHIFT = b"\xe1" KEY_LEFT_ALT = b"\xe2" KEY_LEFT_GUI = b"\xe3" KEY_RIGHT_CTRL = b"\xe4" KEY_RIGHT_SHIFT = b"\xe5" KEY_RIGHT_ALT = b"\xe6" KEY_RIGHT_GUI = b"\xe8" KEY_A = b"\x04" KEY_B = b"\x05" KEY_C = b"\x06" KEY_D = b"\x07" KEY_E = b"\x08" KEY_F = b"\x09" KEY_G = b"\x0A" KEY_H = b"\x0B" KEY_I = b"\x0C" KEY_J = b"\x0D" KEY_K = b"\x0E" KEY_L = b"\x0F" KEY_M = b"\x10" KEY_N = b"\x11" KEY_O = b"\x12" KEY_P = b"\x13" KEY_Q = b"\x14" KEY_R = b"\x15" KEY_S = b"\x16" KEY_T = b"\x17" KEY_U = b"\x18" KEY_V = b"\x19" KEY_W = b"\x1A" KEY_X = b"\x1B" KEY_Y = b"\x1C" KEY_Z = b"\x1D" KEY_1 = b"\x1E" KEY_2 = b"\x1F" KEY_3 = b"\x20" KEY_4 = b"\x21" KEY_5 = b"\x22" KEY_6 = b"\x23" KEY_7 = b"\x24" KEY_8 = b"\x25" KEY_9 = b"\x26" KEY_0 = b"\x27" KEY_RETURN = b"\x28" KEY_ENTER = b"\x28" KEY_ESC = b"\x29" KEY_ESCAPE = b"\x29" KEY_BCKSPC = b"\x2A" KEY_BACKSPACE = b"\x2A" KEY_TAB = b"\x2B" KEY_SPACE = b"\x2C" KEY_MINUS = b"\x2D" KEY_DASH = b"\x2D" KEY_EQUALS = b"\x2E" KEY_EQUAL = b"\x2E" KEY_LBRACKET = b"\x2F" KEY_RBRACKET = b"\x30" KEY_BACKSLASH = b"\x31" KEY_HASH = b"\x32" KEY_NUMBER = b"\x32" KEY_SEMICOLON = b"\x33" KEY_QUOTE = b"\x34" KEY_BACKQUOTE = b"\x35" KEY_TILDE = b"\x35" KEY_COMMA = b"\x36" KEY_PERIOD = b"\x37" KEY_STOP = b"\x37" KEY_SLASH = b"\x38" KEY_CAPS_LOCK = b"\x39" KEY_CAPSLOCK = b"\x39" KEY_F1 = b"\x3A" KEY_F2 = b"\x3B" KEY_F3 = b"\x3C" KEY_F4 = b"\x3D" KEY_F5 = b"\x3E" KEY_F6 = b"\x3F" KEY_F7 = b"\x40" KEY_F8 = b"\x41" KEY_F9 = b"\x42" KEY_F10 = b"\x43" KEY_F11 = b"\x44" KEY_F12 = b"\x45" KEY_PRINT = b"\x46" KEY_SCROLL_LOCK = b"\x47" KEY_SCROLLLOCK = b"\x47" KEY_PAUSE = b"\x48" KEY_INSERT = b"\x49" KEY_HOME = b"\x4A" KEY_PAGEUP = b"\x4B" KEY_PGUP = b"\x4B" KEY_DEL = b"\x4C" KEY_DELETE = b"\x4C" KEY_END = b"\x4D" KEY_PAGEDOWN = b"\x4E" KEY_PGDOWN = b"\x4E" KEY_RIGHT = b"\x4F" KEY_LEFT = b"\x50" KEY_DOWN = b"\x51" KEY_UP = b"\x52" KEY_NUM_LOCK = b"\x53" KEY_NUMLOCK = b"\x53" KEY_KP_DIVIDE = b"\x54" KEY_KP_MULTIPLY = b"\x55" KEY_KP_MINUS = b"\x56" KEY_KP_PLUS = b"\x57" KEY_KP_ENTER = b"\x58" KEY_KP_RETURN = b"\x58" KEY_KP_1 = b"\x59" KEY_KP_2 = b"\x5A" KEY_KP_3 = b"\x5B" KEY_KP_4 = b"\x5C" KEY_KP_5 = b"\x5D" KEY_KP_6 = b"\x5E" KEY_KP_7 = b"\x5F" KEY_KP_8 = b"\x60" KEY_KP_9 = b"\x61" KEY_KP_0 = b"\x62" KEY_KP_PERIOD = b"\x63" KEY_KP_STOP = b"\x63" KEY_APPLICATION = b"\x65" KEY_POWER = b"\x66" KEY_KP_EQUALS = b"\x67" KEY_KP_EQUAL = b"\x67" KEY_F13 = b"\x68" KEY_F14 = b"\x69" KEY_F15 = b"\x6A" KEY_F16 = b"\x6B" KEY_F17 = b"\x6C" KEY_F18 = b"\x6D" KEY_F19 = b"\x6E" KEY_F20 = b"\x6F" KEY_F21 = b"\x70" KEY_F22 = b"\x71" KEY_F23 = b"\x72" KEY_F24 = b"\x73" KEY_EXECUTE = b"\x74" KEY_HELP = b"\x75" KEY_MENU = b"\x76" KEY_SELECT = b"\x77" KEY_CANCEL = b"\x78" KEY_REDO = b"\x79" KEY_UNDO = b"\x7A" KEY_CUT = b"\x7B" KEY_COPY = b"\x7C" KEY_PASTE = b"\x7D" KEY_FIND = b"\x7E" KEY_MUTE = b"\x7F" KEY_VOLUME_UP = b"\x80" KEY_VOLUME_DOWN = b"\x81"
mouse_btn_left = b'\x90' mouse_btn_right = b'\x91' mouse_btn_middle = b'\x92' key_left_ctrl = b'\xe0' key_left_shift = b'\xe1' key_left_alt = b'\xe2' key_left_gui = b'\xe3' key_right_ctrl = b'\xe4' key_right_shift = b'\xe5' key_right_alt = b'\xe6' key_right_gui = b'\xe8' key_a = b'\x04' key_b = b'\x05' key_c = b'\x06' key_d = b'\x07' key_e = b'\x08' key_f = b'\t' key_g = b'\n' key_h = b'\x0b' key_i = b'\x0c' key_j = b'\r' key_k = b'\x0e' key_l = b'\x0f' key_m = b'\x10' key_n = b'\x11' key_o = b'\x12' key_p = b'\x13' key_q = b'\x14' key_r = b'\x15' key_s = b'\x16' key_t = b'\x17' key_u = b'\x18' key_v = b'\x19' key_w = b'\x1a' key_x = b'\x1b' key_y = b'\x1c' key_z = b'\x1d' key_1 = b'\x1e' key_2 = b'\x1f' key_3 = b' ' key_4 = b'!' key_5 = b'"' key_6 = b'#' key_7 = b'$' key_8 = b'%' key_9 = b'&' key_0 = b"'" key_return = b'(' key_enter = b'(' key_esc = b')' key_escape = b')' key_bckspc = b'*' key_backspace = b'*' key_tab = b'+' key_space = b',' key_minus = b'-' key_dash = b'-' key_equals = b'.' key_equal = b'.' key_lbracket = b'/' key_rbracket = b'0' key_backslash = b'1' key_hash = b'2' key_number = b'2' key_semicolon = b'3' key_quote = b'4' key_backquote = b'5' key_tilde = b'5' key_comma = b'6' key_period = b'7' key_stop = b'7' key_slash = b'8' key_caps_lock = b'9' key_capslock = b'9' key_f1 = b':' key_f2 = b';' key_f3 = b'<' key_f4 = b'=' key_f5 = b'>' key_f6 = b'?' key_f7 = b'@' key_f8 = b'A' key_f9 = b'B' key_f10 = b'C' key_f11 = b'D' key_f12 = b'E' key_print = b'F' key_scroll_lock = b'G' key_scrolllock = b'G' key_pause = b'H' key_insert = b'I' key_home = b'J' key_pageup = b'K' key_pgup = b'K' key_del = b'L' key_delete = b'L' key_end = b'M' key_pagedown = b'N' key_pgdown = b'N' key_right = b'O' key_left = b'P' key_down = b'Q' key_up = b'R' key_num_lock = b'S' key_numlock = b'S' key_kp_divide = b'T' key_kp_multiply = b'U' key_kp_minus = b'V' key_kp_plus = b'W' key_kp_enter = b'X' key_kp_return = b'X' key_kp_1 = b'Y' key_kp_2 = b'Z' key_kp_3 = b'[' key_kp_4 = b'\\' key_kp_5 = b']' key_kp_6 = b'^' key_kp_7 = b'_' key_kp_8 = b'`' key_kp_9 = b'a' key_kp_0 = b'b' key_kp_period = b'c' key_kp_stop = b'c' key_application = b'e' key_power = b'f' key_kp_equals = b'g' key_kp_equal = b'g' key_f13 = b'h' key_f14 = b'i' key_f15 = b'j' key_f16 = b'k' key_f17 = b'l' key_f18 = b'm' key_f19 = b'n' key_f20 = b'o' key_f21 = b'p' key_f22 = b'q' key_f23 = b'r' key_f24 = b's' key_execute = b't' key_help = b'u' key_menu = b'v' key_select = b'w' key_cancel = b'x' key_redo = b'y' key_undo = b'z' key_cut = b'{' key_copy = b'|' key_paste = b'}' key_find = b'~' key_mute = b'\x7f' key_volume_up = b'\x80' key_volume_down = b'\x81'
""" pymake ------------------------------- - Eugenio Marinetto - nenetto@gmail.com ------------------------------- Created 08-08-2019 """ # __all__ variable # Fill it in with the packages you want to export in "from project_name import *" __all__ = []
""" pymake ------------------------------- - Eugenio Marinetto - nenetto@gmail.com ------------------------------- Created 08-08-2019 """ __all__ = []
x = 6 y = 7 # # Simple if # if x == y: # print(f'{x} is equal to {y}') # else: # print(f'{x} is not equal to {y}') # # Elif # if x > y: # print(f'{x} is bigger to {y}') # elif x == y: # print(f'{x} is equal to {y}') # else: # print(f'{x} is not equal to {y}') # Nested if # if x > 2: # if x <= 10: # print(f'{x} is less than 2 and greater than 10') # and logical operators # if x > 2 and x <= 10: # print(f'{x} is less than 2 and greater than 10') # or logical operators # if x > 2 or x <= 10: # print(f'{x} is less than 2 or greater than 10') # not logical operators # if not(x == y): # print(f'{x} is not equal to {y}') # Creating Simple List numbers = [1, 2, 3, 4, 5] # in # if x in numbers: # print(x in numbers) # not in # if x not in numbers: # print(x in numbers) # Identity Operators if x is y: print(x is y) if x is not y: print(x is y) if x is not y: print(x is not y)
x = 6 y = 7 numbers = [1, 2, 3, 4, 5] if x is y: print(x is y) if x is not y: print(x is y) if x is not y: print(x is not y)
# https://leetcode.com/problems/max-consecutive-ones class Solution: def findMaxConsecutiveOnes(self, nums): is_consec = False cnt, ans = 0, 0 for i in range(len(nums)): if (nums[i] == 1) and is_consec: cnt += 1 ans = max(ans, cnt) elif (nums[i] == 1) and (not is_consec): is_consec = True cnt = 1 ans = max(ans, cnt) else: is_consec = False return ans
class Solution: def find_max_consecutive_ones(self, nums): is_consec = False (cnt, ans) = (0, 0) for i in range(len(nums)): if nums[i] == 1 and is_consec: cnt += 1 ans = max(ans, cnt) elif nums[i] == 1 and (not is_consec): is_consec = True cnt = 1 ans = max(ans, cnt) else: is_consec = False return ans
""" 2015 Advent of Code, Day 1 """ with open("input", "r+") as file: puzzle_input = file.read() FLOOR = 0 POSITION = 0 BASEMENT = False for (index, character) in enumerate(puzzle_input): if character == "(": FLOOR += 1 if character == ")": FLOOR -= 1 if not BASEMENT and FLOOR < 0: BASEMENT = True POSITION = index + 1 print(FLOOR, POSITION)
""" 2015 Advent of Code, Day 1 """ with open('input', 'r+') as file: puzzle_input = file.read() floor = 0 position = 0 basement = False for (index, character) in enumerate(puzzle_input): if character == '(': floor += 1 if character == ')': floor -= 1 if not BASEMENT and FLOOR < 0: basement = True position = index + 1 print(FLOOR, POSITION)
a = 1 b = 2 print('a = ' + str(a) + ',' + 'b = ' + str(b)) temp = a a = b b = temp print('a = ' + str(a) + ',' + 'b = ' + str(b))
a = 1 b = 2 print('a = ' + str(a) + ',' + 'b = ' + str(b)) temp = a a = b b = temp print('a = ' + str(a) + ',' + 'b = ' + str(b))
THRESHOLD = 4 HEADER = '<?xml version="1.0" encoding="utf-8"?>\n\t<output>\n' FOOTER = '\t</output>\n' valMap = { '<': '', '>': '', '&': '', '\"': '' } keyMap = { '~': '', '`': '', '!': '', '@': '', '$': '', '%': '', '^': '', '&': '', '*': '', '(': '', ')': '', '+': '', '=': '', '{': '', '}': '', '[': '', ']': '', '\'': '', '|': '', '\"': '', ';': '', '?': '', '<': '', '>': '', '/': '', ',': '', ' ': '', '#': '_', u'\u2103': u'\u5ea6' }
threshold = 4 header = '<?xml version="1.0" encoding="utf-8"?>\n\t<output>\n' footer = '\t</output>\n' val_map = {'<': '', '>': '', '&': '', '"': ''} key_map = {'~': '', '`': '', '!': '', '@': '', '$': '', '%': '', '^': '', '&': '', '*': '', '(': '', ')': '', '+': '', '=': '', '{': '', '}': '', '[': '', ']': '', "'": '', '|': '', '"': '', ';': '', '?': '', '<': '', '>': '', '/': '', ',': '', ' ': '', '#': '_', u'℃': u'度'}
class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """
class Solution(object): def product_except_self(self, nums): """ :type nums: List[int] :rtype: List[int] """
# Whitelist of generated features in dev STATUS for quicker execution TSFRESH_FEATURE_WHITELIST = [ 'agg_autocorrelation', 'autocorrelation', 'mean', 'mean_change', 'median', 'standard_deviation', 'variance', 'minimum', ] # Size of the time-windows used for generating single time-series TSFRESH_TIME_WINDOWS = 14
tsfresh_feature_whitelist = ['agg_autocorrelation', 'autocorrelation', 'mean', 'mean_change', 'median', 'standard_deviation', 'variance', 'minimum'] tsfresh_time_windows = 14
# # solver_porting.py # # Description: # Hard code the solution values from the paper # Sin-Chung Chang, # "The Method of Space-Time Conservation Element # and Solution Element - A New Approach for Solving the Navier-Stokes # and Euler Equations", # Journal of Computational Physics, Volume 119, # Issue 2, July 1995, Pages 295-324. # # These values are caculated my python program ported from the # demo example written in fortran in the paper above. # # These two functions generated from the same python program # but one with high precision. # def get_specific_solution_for_unit_test(): solution_porting = [ (-0.505000, 1.000000, 0.000000, 1.000000), (-0.495000, 1.000000, 0.000000, 1.000000), (-0.485000, 1.000000, 0.000000, 1.000000), (-0.475000, 1.000000, 0.000000, 1.000000), (-0.465000, 1.000000, 0.000000, 1.000000), (-0.455000, 1.000000, 0.000000, 1.000000), (-0.445000, 1.000000, 0.000000, 1.000000), (-0.435000, 1.000000, 0.000000, 1.000000), (-0.425000, 1.000000, 0.000000, 1.000000), (-0.415000, 1.000000, 0.000000, 1.000000), (-0.405000, 1.000000, 0.000000, 1.000000), (-0.395000, 1.000000, 0.000000, 1.000000), (-0.385000, 1.000000, 0.000000, 1.000000), (-0.375000, 1.000000, 0.000000, 1.000000), (-0.365000, 1.000000, 0.000000, 1.000000), (-0.355000, 1.000000, 0.000000, 1.000000), (-0.345000, 1.000000, 0.000000, 1.000000), (-0.335000, 1.000000, 0.000000, 1.000000), (-0.325000, 1.000000, 0.000000, 1.000000), (-0.315000, 1.000000, 0.000001, 0.999990), (-0.305000, 0.999996, 0.000004, 0.999990), (-0.295000, 0.999976, 0.000028, 0.999960), (-0.285000, 0.999871, 0.000153, 0.999810), (-0.275000, 0.999414, 0.000694, 0.999170), (-0.265000, 0.997818, 0.002584, 0.996940), (-0.255000, 0.993421, 0.007803, 0.990800), (-0.245000, 0.983967, 0.019086, 0.977630), (-0.235000, 0.967934, 0.038418, 0.955410), (-0.225000, 0.945706, 0.065654, 0.924830), (-0.215000, 0.919136, 0.098909, 0.888630), (-0.205000, 0.890232, 0.135996, 0.849670), (-0.195000, 0.860418, 0.175310, 0.809950), (-0.185000, 0.830502, 0.215915, 0.770550), (-0.175000, 0.800906, 0.257311, 0.732020), (-0.165000, 0.771847, 0.299228, 0.694620), (-0.155000, 0.743447, 0.341510, 0.658480), (-0.145000, 0.715776, 0.384050, 0.623660), (-0.135000, 0.688881, 0.426769, 0.590190), (-0.125000, 0.662794, 0.469599, 0.558070), (-0.115000, 0.637537, 0.512474, 0.527300), (-0.105000, 0.613125, 0.555333, 0.497870), (-0.095000, 0.589570, 0.598112, 0.469770), (-0.085000, 0.566880, 0.640745, 0.442980), (-0.075000, 0.545061, 0.683162, 0.417490), (-0.065000, 0.524125, 0.725267, 0.393290), (-0.055000, 0.504121, 0.766883, 0.370400), (-0.045000, 0.485219, 0.807533, 0.349020), (-0.035000, 0.467990, 0.845786, 0.329740), (-0.025000, 0.453912, 0.877936, 0.314190), (-0.015000, 0.445312, 0.897992, 0.304800), (-0.005000, 0.442658, 0.904249, 0.301940), ( 0.005000, 0.442772, 0.904002, 0.302070), ( 0.015000, 0.444581, 0.899744, 0.304060), ( 0.025000, 0.446652, 0.894841, 0.306330), ( 0.035000, 0.447224, 0.893443, 0.306970), ( 0.045000, 0.447163, 0.893599, 0.306900), ( 0.055000, 0.446890, 0.894281, 0.306590), ( 0.065000, 0.446835, 0.894505, 0.306480), ( 0.075000, 0.446873, 0.894351, 0.306550), ( 0.085000, 0.446797, 0.894104, 0.306670), ( 0.095000, 0.446632, 0.893997, 0.306740), ( 0.105000, 0.446665, 0.893903, 0.306780), ( 0.115000, 0.447449, 0.893828, 0.306790), ( 0.125000, 0.448803, 0.893843, 0.306710), ( 0.135000, 0.449307, 0.893970, 0.306610), ( 0.145000, 0.446953, 0.894360, 0.306550), ( 0.155000, 0.424999, 0.896761, 0.306480), ( 0.165000, 0.376460, 0.902293, 0.306370), ( 0.175000, 0.323083, 0.908606, 0.306320), ( 0.185000, 0.283863, 0.913549, 0.306240), ( 0.195000, 0.263120, 0.916182, 0.306270), ( 0.205000, 0.255465, 0.916996, 0.306250), ( 0.215000, 0.253829, 0.917267, 0.306240), ( 0.225000, 0.253852, 0.917300, 0.306280), ( 0.235000, 0.254354, 0.917099, 0.306320), ( 0.245000, 0.254848, 0.917298, 0.306330), ( 0.255000, 0.255146, 0.917121, 0.306240), ( 0.265000, 0.255278, 0.916872, 0.306210), ( 0.275000, 0.255309, 0.917358, 0.306380), ( 0.285000, 0.255084, 0.917145, 0.306250), ( 0.295000, 0.255001, 0.916996, 0.306300), ( 0.305000, 0.255013, 0.917194, 0.306380), ( 0.315000, 0.254891, 0.917686, 0.306140), ( 0.325000, 0.254764, 0.917755, 0.306050), ( 0.335000, 0.254647, 0.917552, 0.306570), ( 0.345000, 0.257049, 0.921870, 0.308520), ( 0.355000, 0.246171, 0.878439, 0.292370), ( 0.365000, 0.133610, 0.075640, 0.110350), ( 0.375000, 0.125018, 0.000152, 0.100020), ( 0.385000, 0.125000, 0.000000, 0.100000), ( 0.395000, 0.125000, 0.000000, 0.100000), ( 0.405000, 0.125000, 0.000000, 0.100000), ( 0.415000, 0.125000, 0.000000, 0.100000), ( 0.425000, 0.125000, 0.000000, 0.100000), ( 0.435000, 0.125000, 0.000000, 0.100000), ( 0.445000, 0.125000, 0.000000, 0.100000), ( 0.455000, 0.125000, 0.000000, 0.100000), ( 0.465000, 0.125000, 0.000000, 0.100000), ( 0.475000, 0.125000, 0.000000, 0.100000), ( 0.485000, 0.125000, 0.000000, 0.100000), ( 0.495000, 0.125000, 0.000000, 0.100000), ( 0.505000, 0.125000, 0.000000, 0.100000) ] return solution_porting def get_specific_solution_for_unit_test_high_precision(): solution_porting = [ (-0.505, 1.0, 0.0, 1.0), (-0.495, 1.0, 1.1102230246251565e-16, 0.99999999999999978), (-0.48499999999999999, 1.0, 1.1102230246251565e-16, 0.99999999999999978), (-0.47499999999999998, 1.0, 1.1102230246251565e-16, 0.99999999999999978), (-0.46499999999999997, 1.0, 1.1102230246251565e-16, 0.99999999999999978), (-0.45499999999999996, 1.0, 1.1102230246251565e-16, 0.99999999999999978), (-0.44499999999999995, 1.0, 1.1102230246251565e-16, 0.99999999999999978), (-0.43499999999999994, 1.0, 1.1102230246251565e-16, 0.99999999999999978), (-0.42499999999999993, 1.0, 1.1102230246251565e-16, 0.99999999999999978), (-0.41499999999999992, 1.0, 1.1102230246251565e-16, 0.99999999999999978), (-0.40499999999999992, 1.0, 1.1102230246251565e-16, 0.99999999999999978), (-0.39499999999999991, 0.99999999999999978, 2.7755575615628918e-16, 0.99999999999999944), (-0.3849999999999999, 0.99999999999999467, 6.4670491184415716e-15, 0.99999999999999234), (-0.37499999999999989, 0.99999999999988776, 1.3308798507695558e-13, 0.99999999999984257), (-0.36499999999999988, 0.99999999999795142, 2.4237278850641443e-12, 0.99999999999713185), (-0.35499999999999987, 0.99999999996762634, 3.8304831530130371e-11, 0.99999999995467714), (-0.34499999999999986, 0.9999999995562131, 5.2509580040759933e-10, 0.99999999937869855), (-0.33499999999999985, 0.99999999472607115, 6.2401971419523565e-09, 0.99999999261649919), (-0.32499999999999984, 0.99999994577382079, 6.4161282047119177e-08, 0.99999992408334937), (-0.31499999999999984, 0.99999951928196795, 5.6879332200680462e-07, 0.99999932699485283), (-0.30499999999999983, 0.99999634481101307, 4.3248824814959905e-06, 0.99999488274087778), (-0.29499999999999982, 0.99997633737099978, 2.79981985962474e-05, 0.99996687254024597), (-0.28499999999999981, 0.99987088139365798, 0.00015278136209548727, 0.99981924026677849), (-0.2749999999999998, 0.99941378043705476, 0.00069375744886315566, 0.99917941692171297), (-0.26499999999999979, 0.99781788235911262, 0.0025838519965398011, 0.99694667070431586), (-0.25499999999999978, 0.99342121495457225, 0.0078025845316690946, 0.99080377644372952), (-0.24499999999999977, 0.98396664008085244, 0.019085577438586857, 0.97763274444798665), (-0.23499999999999976, 0.96793363368888941, 0.038418196061865424, 0.95541204434804472), (-0.22499999999999976, 0.94570644798043035, 0.065654265643744547, 0.92483779493022644), (-0.21499999999999975, 0.91913571997302768, 0.098909427615020667, 0.88863525073537986), (-0.20499999999999974, 0.89023221601523495, 0.13599566576005953, 0.84967793214624232), (-0.19499999999999973, 0.86041780219813813, 0.17531012301721785, 0.80995068909265133), (-0.18499999999999972, 0.8305020195811702, 0.21591521730211277, 0.77055070706890127), (-0.17499999999999971, 0.8009056282617506, 0.25731095878337934, 0.7320223185641187), (-0.1649999999999997, 0.77184714843620994, 0.29922837596343643, 0.69462654528961598), (-0.15499999999999969, 0.74344677036077855, 0.34150984863445688, 0.6584888001930933), (-0.14499999999999968, 0.71577615716384058, 0.3840502790961422, 0.62366900266734182), (-0.13499999999999968, 0.68888144418494501, 0.42676943038587994, 0.59019377200083745), (-0.12499999999999968, 0.6627941455413211, 0.46959860870295073, 0.55807162556304857), (-0.11499999999999969, 0.63753660526589484, 0.51247390933368231, 0.52730052843980701), (-0.10499999999999969, 0.61312484769809938, 0.55533265985338043, 0.49787180099864842), (-0.094999999999999696, 0.58957011850181684, 0.59811153812036699, 0.4697721936664796), (-0.084999999999999701, 0.56688001778671482, 0.64074509894323095, 0.44298533199781343), (-0.074999999999999706, 0.54506080995274542, 0.68316169419725314, 0.41749444939192293), (-0.064999999999999711, 0.52412533713855136, 0.72526708274475149, 0.39329151342581087), (-0.054999999999999709, 0.50412059320145031, 0.7668829674339982, 0.3704086642557895), (-0.044999999999999707, 0.48521942621212033, 0.8075325790323119, 0.34902157047542365), (-0.034999999999999705, 0.46798952801415838, 0.84578618076008127, 0.32974685351833127), (-0.024999999999999703, 0.4539124843363786, 0.87793571859933139, 0.3141914269987745), (-0.014999999999999703, 0.4453117097494409, 0.8979921479041113, 0.3048070144768753), (-0.0049999999999997026, 0.44265849796839962, 0.90424912589460049, 0.30194110396148455), (0.0050000000000002976, 0.44277152604102954, 0.90400167161754941, 0.30207396109955731), (0.015000000000000298, 0.44458074109625789, 0.89974424674017883, 0.30406154478259872), (0.0250000000000003, 0.44665186574379889, 0.89484127842442829, 0.30633620659817651), (0.035000000000000302, 0.44722415984760716, 0.89344336715923944, 0.3069767246505235), (0.045000000000000304, 0.44716266478033079, 0.89359856206472299, 0.30690395534340742), (0.055000000000000306, 0.44689000763788234, 0.89428145391403135, 0.30659011440665951), (0.065000000000000308, 0.44683455389593113, 0.89450478975743941, 0.30648208370927321), (0.075000000000000303, 0.44687343951557484, 0.89435080463668515, 0.30655575368395022), (0.085000000000000298, 0.44679662179222007, 0.89410446777149932, 0.30667701988019136), (0.095000000000000293, 0.44663194699514586, 0.89399670954746402, 0.3067426275793218), (0.10500000000000029, 0.44666498067017296, 0.8939032368159131, 0.30678067827130739), (0.11500000000000028, 0.44744939615633389, 0.8938283386254392, 0.30679034686021484), (0.12500000000000028, 0.44880262918560282, 0.89384265926379181, 0.30671165608649037), (0.13500000000000029, 0.44930671664614646, 0.8939701751341157, 0.30661316478296419), (0.1450000000000003, 0.44695294693653559, 0.89436014525089413, 0.30655123374810866), (0.1550000000000003, 0.42499884313690589, 0.8967607749926938, 0.30648056991207406), (0.16500000000000031, 0.37646019200020114, 0.90229316109419666, 0.3063749421769546), (0.17500000000000032, 0.32308346953859418, 0.9086059712367901, 0.30632068302060489), (0.18500000000000033, 0.28386306263008648, 0.91354863178497869, 0.30624468303654856), (0.19500000000000034, 0.26312012485796243, 0.91618236506234674, 0.30627926864421728), (0.20500000000000035, 0.25546475796037754, 0.91699628286383128, 0.30625564741653527), (0.21500000000000036, 0.25382887050832692, 0.91726748768940347, 0.30624466686916185), (0.22500000000000037, 0.25385244118957323, 0.91730025383922331, 0.30628818557740017), (0.23500000000000038, 0.25435421897952837, 0.91709938305572969, 0.30632175500661168), (0.24500000000000038, 0.25484785803655347, 0.91729763126993402, 0.30633152306973305), (0.25500000000000039, 0.25514629256535842, 0.91712073191552634, 0.30624259391310038), (0.2650000000000004, 0.25527804138560317, 0.91687215887997642, 0.30621371074195036), (0.27500000000000041, 0.2553086860042269, 0.9173579272884218, 0.306381349096989), (0.28500000000000042, 0.25508421322101449, 0.91714513017949251, 0.30625145391872971), (0.29500000000000043, 0.25500112971314676, 0.91699589381745272, 0.30630793033357473), (0.30500000000000044, 0.25501325412451314, 0.91719423148529511, 0.30637974594764761), (0.31500000000000045, 0.2548911547607271, 0.91768611502897424, 0.30614465035840854), (0.32500000000000046, 0.2547644714837658, 0.91775514645688094, 0.30605138955358835), (0.33500000000000046, 0.2546465556459554, 0.91755181317584589, 0.30657038190930797), (0.34500000000000047, 0.25704850786977601, 0.92186989259160956, 0.3085287750393364), (0.35500000000000048, 0.24617054290848731, 0.8784393859773485, 0.29236958085661585), (0.36500000000000049, 0.13360953118193081, 0.07564047374232051, 0.11035282175804639), (0.3750000000000005, 0.12501790423176928, 0.00015158938150652916, 0.10002005518613435), (0.38500000000000051, 0.12500002915548108, 2.4684206810964962e-07, 0.1000000326541411), (0.39500000000000052, 0.12500000004718731, 3.9950684412222107e-10, 0.10000000005284979), (0.40500000000000053, 0.12500000000007638, 6.4678817857060536e-13, 0.10000000000008555), (0.41500000000000054, 0.12500000000000014, 1.0269562977782686e-15, 0.10000000000000016), (0.42500000000000054, 0.125, 8.3266726846886741e-17, 0.10000000000000002), (0.43500000000000055, 0.125, 8.3266726846886741e-17, 0.10000000000000002), (0.44500000000000056, 0.125, 8.3266726846886741e-17, 0.10000000000000002), (0.45500000000000057, 0.125, 8.3266726846886741e-17, 0.10000000000000002), (0.46500000000000058, 0.125, 8.3266726846886741e-17, 0.10000000000000002), (0.47500000000000059, 0.125, 8.3266726846886741e-17, 0.10000000000000002), (0.4850000000000006, 0.125, 8.3266726846886741e-17, 0.10000000000000002), (0.49500000000000061, 0.125, 8.3266726846886741e-17, 0.10000000000000002), (0.50500000000000056, 0.125, 0.0, 0.10000000000000001)] return solution_porting
def get_specific_solution_for_unit_test(): solution_porting = [(-0.505, 1.0, 0.0, 1.0), (-0.495, 1.0, 0.0, 1.0), (-0.485, 1.0, 0.0, 1.0), (-0.475, 1.0, 0.0, 1.0), (-0.465, 1.0, 0.0, 1.0), (-0.455, 1.0, 0.0, 1.0), (-0.445, 1.0, 0.0, 1.0), (-0.435, 1.0, 0.0, 1.0), (-0.425, 1.0, 0.0, 1.0), (-0.415, 1.0, 0.0, 1.0), (-0.405, 1.0, 0.0, 1.0), (-0.395, 1.0, 0.0, 1.0), (-0.385, 1.0, 0.0, 1.0), (-0.375, 1.0, 0.0, 1.0), (-0.365, 1.0, 0.0, 1.0), (-0.355, 1.0, 0.0, 1.0), (-0.345, 1.0, 0.0, 1.0), (-0.335, 1.0, 0.0, 1.0), (-0.325, 1.0, 0.0, 1.0), (-0.315, 1.0, 1e-06, 0.99999), (-0.305, 0.999996, 4e-06, 0.99999), (-0.295, 0.999976, 2.8e-05, 0.99996), (-0.285, 0.999871, 0.000153, 0.99981), (-0.275, 0.999414, 0.000694, 0.99917), (-0.265, 0.997818, 0.002584, 0.99694), (-0.255, 0.993421, 0.007803, 0.9908), (-0.245, 0.983967, 0.019086, 0.97763), (-0.235, 0.967934, 0.038418, 0.95541), (-0.225, 0.945706, 0.065654, 0.92483), (-0.215, 0.919136, 0.098909, 0.88863), (-0.205, 0.890232, 0.135996, 0.84967), (-0.195, 0.860418, 0.17531, 0.80995), (-0.185, 0.830502, 0.215915, 0.77055), (-0.175, 0.800906, 0.257311, 0.73202), (-0.165, 0.771847, 0.299228, 0.69462), (-0.155, 0.743447, 0.34151, 0.65848), (-0.145, 0.715776, 0.38405, 0.62366), (-0.135, 0.688881, 0.426769, 0.59019), (-0.125, 0.662794, 0.469599, 0.55807), (-0.115, 0.637537, 0.512474, 0.5273), (-0.105, 0.613125, 0.555333, 0.49787), (-0.095, 0.58957, 0.598112, 0.46977), (-0.085, 0.56688, 0.640745, 0.44298), (-0.075, 0.545061, 0.683162, 0.41749), (-0.065, 0.524125, 0.725267, 0.39329), (-0.055, 0.504121, 0.766883, 0.3704), (-0.045, 0.485219, 0.807533, 0.34902), (-0.035, 0.46799, 0.845786, 0.32974), (-0.025, 0.453912, 0.877936, 0.31419), (-0.015, 0.445312, 0.897992, 0.3048), (-0.005, 0.442658, 0.904249, 0.30194), (0.005, 0.442772, 0.904002, 0.30207), (0.015, 0.444581, 0.899744, 0.30406), (0.025, 0.446652, 0.894841, 0.30633), (0.035, 0.447224, 0.893443, 0.30697), (0.045, 0.447163, 0.893599, 0.3069), (0.055, 0.44689, 0.894281, 0.30659), (0.065, 0.446835, 0.894505, 0.30648), (0.075, 0.446873, 0.894351, 0.30655), (0.085, 0.446797, 0.894104, 0.30667), (0.095, 0.446632, 0.893997, 0.30674), (0.105, 0.446665, 0.893903, 0.30678), (0.115, 0.447449, 0.893828, 0.30679), (0.125, 0.448803, 0.893843, 0.30671), (0.135, 0.449307, 0.89397, 0.30661), (0.145, 0.446953, 0.89436, 0.30655), (0.155, 0.424999, 0.896761, 0.30648), (0.165, 0.37646, 0.902293, 0.30637), (0.175, 0.323083, 0.908606, 0.30632), (0.185, 0.283863, 0.913549, 0.30624), (0.195, 0.26312, 0.916182, 0.30627), (0.205, 0.255465, 0.916996, 0.30625), (0.215, 0.253829, 0.917267, 0.30624), (0.225, 0.253852, 0.9173, 0.30628), (0.235, 0.254354, 0.917099, 0.30632), (0.245, 0.254848, 0.917298, 0.30633), (0.255, 0.255146, 0.917121, 0.30624), (0.265, 0.255278, 0.916872, 0.30621), (0.275, 0.255309, 0.917358, 0.30638), (0.285, 0.255084, 0.917145, 0.30625), (0.295, 0.255001, 0.916996, 0.3063), (0.305, 0.255013, 0.917194, 0.30638), (0.315, 0.254891, 0.917686, 0.30614), (0.325, 0.254764, 0.917755, 0.30605), (0.335, 0.254647, 0.917552, 0.30657), (0.345, 0.257049, 0.92187, 0.30852), (0.355, 0.246171, 0.878439, 0.29237), (0.365, 0.13361, 0.07564, 0.11035), (0.375, 0.125018, 0.000152, 0.10002), (0.385, 0.125, 0.0, 0.1), (0.395, 0.125, 0.0, 0.1), (0.405, 0.125, 0.0, 0.1), (0.415, 0.125, 0.0, 0.1), (0.425, 0.125, 0.0, 0.1), (0.435, 0.125, 0.0, 0.1), (0.445, 0.125, 0.0, 0.1), (0.455, 0.125, 0.0, 0.1), (0.465, 0.125, 0.0, 0.1), (0.475, 0.125, 0.0, 0.1), (0.485, 0.125, 0.0, 0.1), (0.495, 0.125, 0.0, 0.1), (0.505, 0.125, 0.0, 0.1)] return solution_porting def get_specific_solution_for_unit_test_high_precision(): solution_porting = [(-0.505, 1.0, 0.0, 1.0), (-0.495, 1.0, 1.1102230246251565e-16, 0.9999999999999998), (-0.485, 1.0, 1.1102230246251565e-16, 0.9999999999999998), (-0.475, 1.0, 1.1102230246251565e-16, 0.9999999999999998), (-0.46499999999999997, 1.0, 1.1102230246251565e-16, 0.9999999999999998), (-0.45499999999999996, 1.0, 1.1102230246251565e-16, 0.9999999999999998), (-0.44499999999999995, 1.0, 1.1102230246251565e-16, 0.9999999999999998), (-0.43499999999999994, 1.0, 1.1102230246251565e-16, 0.9999999999999998), (-0.42499999999999993, 1.0, 1.1102230246251565e-16, 0.9999999999999998), (-0.4149999999999999, 1.0, 1.1102230246251565e-16, 0.9999999999999998), (-0.4049999999999999, 1.0, 1.1102230246251565e-16, 0.9999999999999998), (-0.3949999999999999, 0.9999999999999998, 2.775557561562892e-16, 0.9999999999999994), (-0.3849999999999999, 0.9999999999999947, 6.4670491184415716e-15, 0.9999999999999923), (-0.3749999999999999, 0.9999999999998878, 1.3308798507695558e-13, 0.9999999999998426), (-0.3649999999999999, 0.9999999999979514, 2.4237278850641443e-12, 0.9999999999971318), (-0.35499999999999987, 0.9999999999676263, 3.830483153013037e-11, 0.9999999999546771), (-0.34499999999999986, 0.9999999995562131, 5.250958004075993e-10, 0.9999999993786985), (-0.33499999999999985, 0.9999999947260712, 6.2401971419523565e-09, 0.9999999926164992), (-0.32499999999999984, 0.9999999457738208, 6.416128204711918e-08, 0.9999999240833494), (-0.31499999999999984, 0.999999519281968, 5.687933220068046e-07, 0.9999993269948528), (-0.3049999999999998, 0.9999963448110131, 4.3248824814959905e-06, 0.9999948827408778), (-0.2949999999999998, 0.9999763373709998, 2.79981985962474e-05, 0.999966872540246), (-0.2849999999999998, 0.999870881393658, 0.00015278136209548727, 0.9998192402667785), (-0.2749999999999998, 0.9994137804370548, 0.0006937574488631557, 0.999179416921713), (-0.2649999999999998, 0.9978178823591126, 0.002583851996539801, 0.9969466707043159), (-0.2549999999999998, 0.9934212149545723, 0.007802584531669095, 0.9908037764437295), (-0.24499999999999977, 0.9839666400808524, 0.019085577438586857, 0.9776327444479866), (-0.23499999999999976, 0.9679336336888894, 0.038418196061865424, 0.9554120443480447), (-0.22499999999999976, 0.9457064479804304, 0.06565426564374455, 0.9248377949302264), (-0.21499999999999975, 0.9191357199730277, 0.09890942761502067, 0.8886352507353799), (-0.20499999999999974, 0.890232216015235, 0.13599566576005953, 0.8496779321462423), (-0.19499999999999973, 0.8604178021981381, 0.17531012301721785, 0.8099506890926513), (-0.18499999999999972, 0.8305020195811702, 0.21591521730211277, 0.7705507070689013), (-0.1749999999999997, 0.8009056282617506, 0.25731095878337934, 0.7320223185641187), (-0.1649999999999997, 0.7718471484362099, 0.29922837596343643, 0.694626545289616), (-0.1549999999999997, 0.7434467703607786, 0.3415098486344569, 0.6584888001930933), (-0.14499999999999968, 0.7157761571638406, 0.3840502790961422, 0.6236690026673418), (-0.13499999999999968, 0.688881444184945, 0.42676943038587994, 0.5901937720008374), (-0.12499999999999968, 0.6627941455413211, 0.4695986087029507, 0.5580716255630486), (-0.11499999999999969, 0.6375366052658948, 0.5124739093336823, 0.527300528439807), (-0.10499999999999969, 0.6131248476980994, 0.5553326598533804, 0.4978718009986484), (-0.0949999999999997, 0.5895701185018168, 0.598111538120367, 0.4697721936664796), (-0.0849999999999997, 0.5668800177867148, 0.640745098943231, 0.4429853319978134), (-0.0749999999999997, 0.5450608099527454, 0.6831616941972531, 0.41749444939192293), (-0.06499999999999971, 0.5241253371385514, 0.7252670827447515, 0.39329151342581087), (-0.05499999999999971, 0.5041205932014503, 0.7668829674339982, 0.3704086642557895), (-0.04499999999999971, 0.48521942621212033, 0.8075325790323119, 0.34902157047542365), (-0.034999999999999705, 0.4679895280141584, 0.8457861807600813, 0.3297468535183313), (-0.024999999999999703, 0.4539124843363786, 0.8779357185993314, 0.3141914269987745), (-0.014999999999999703, 0.4453117097494409, 0.8979921479041113, 0.3048070144768753), (-0.004999999999999703, 0.4426584979683996, 0.9042491258946005, 0.30194110396148455), (0.005000000000000298, 0.44277152604102954, 0.9040016716175494, 0.3020739610995573), (0.015000000000000298, 0.4445807410962579, 0.8997442467401788, 0.3040615447825987), (0.0250000000000003, 0.4466518657437989, 0.8948412784244283, 0.3063362065981765), (0.0350000000000003, 0.44722415984760716, 0.8934433671592394, 0.3069767246505235), (0.045000000000000304, 0.4471626647803308, 0.893598562064723, 0.3069039553434074), (0.055000000000000306, 0.44689000763788234, 0.8942814539140314, 0.3065901144066595), (0.06500000000000031, 0.44683455389593113, 0.8945047897574394, 0.3064820837092732), (0.0750000000000003, 0.44687343951557484, 0.8943508046366851, 0.3065557536839502), (0.0850000000000003, 0.44679662179222007, 0.8941044677714993, 0.30667701988019136), (0.09500000000000029, 0.44663194699514586, 0.893996709547464, 0.3067426275793218), (0.10500000000000029, 0.44666498067017296, 0.8939032368159131, 0.3067806782713074), (0.11500000000000028, 0.4474493961563339, 0.8938283386254392, 0.30679034686021484), (0.12500000000000028, 0.4488026291856028, 0.8938426592637918, 0.30671165608649037), (0.1350000000000003, 0.44930671664614646, 0.8939701751341157, 0.3066131647829642), (0.1450000000000003, 0.4469529469365356, 0.8943601452508941, 0.30655123374810866), (0.1550000000000003, 0.4249988431369059, 0.8967607749926938, 0.30648056991207406), (0.1650000000000003, 0.37646019200020114, 0.9022931610941967, 0.3063749421769546), (0.17500000000000032, 0.3230834695385942, 0.9086059712367901, 0.3063206830206049), (0.18500000000000033, 0.2838630626300865, 0.9135486317849787, 0.30624468303654856), (0.19500000000000034, 0.26312012485796243, 0.9161823650623467, 0.3062792686442173), (0.20500000000000035, 0.25546475796037754, 0.9169962828638313, 0.30625564741653527), (0.21500000000000036, 0.2538288705083269, 0.9172674876894035, 0.30624466686916185), (0.22500000000000037, 0.25385244118957323, 0.9173002538392233, 0.3062881855774002), (0.23500000000000038, 0.25435421897952837, 0.9170993830557297, 0.3063217550066117), (0.24500000000000038, 0.25484785803655347, 0.917297631269934, 0.30633152306973305), (0.2550000000000004, 0.2551462925653584, 0.9171207319155263, 0.3062425939131004), (0.2650000000000004, 0.25527804138560317, 0.9168721588799764, 0.30621371074195036), (0.2750000000000004, 0.2553086860042269, 0.9173579272884218, 0.306381349096989), (0.2850000000000004, 0.2550842132210145, 0.9171451301794925, 0.3062514539187297), (0.29500000000000043, 0.25500112971314676, 0.9169958938174527, 0.30630793033357473), (0.30500000000000044, 0.25501325412451314, 0.9171942314852951, 0.3063797459476476), (0.31500000000000045, 0.2548911547607271, 0.9176861150289742, 0.30614465035840854), (0.32500000000000046, 0.2547644714837658, 0.9177551464568809, 0.30605138955358835), (0.33500000000000046, 0.2546465556459554, 0.9175518131758459, 0.30657038190930797), (0.3450000000000005, 0.257048507869776, 0.9218698925916096, 0.3085287750393364), (0.3550000000000005, 0.2461705429084873, 0.8784393859773485, 0.29236958085661585), (0.3650000000000005, 0.1336095311819308, 0.07564047374232051, 0.1103528217580464), (0.3750000000000005, 0.12501790423176928, 0.00015158938150652916, 0.10002005518613435), (0.3850000000000005, 0.12500002915548108, 2.468420681096496e-07, 0.1000000326541411), (0.3950000000000005, 0.1250000000471873, 3.9950684412222107e-10, 0.10000000005284979), (0.4050000000000005, 0.12500000000007638, 6.467881785706054e-13, 0.10000000000008555), (0.41500000000000054, 0.12500000000000014, 1.0269562977782686e-15, 0.10000000000000016), (0.42500000000000054, 0.125, 8.326672684688674e-17, 0.10000000000000002), (0.43500000000000055, 0.125, 8.326672684688674e-17, 0.10000000000000002), (0.44500000000000056, 0.125, 8.326672684688674e-17, 0.10000000000000002), (0.45500000000000057, 0.125, 8.326672684688674e-17, 0.10000000000000002), (0.4650000000000006, 0.125, 8.326672684688674e-17, 0.10000000000000002), (0.4750000000000006, 0.125, 8.326672684688674e-17, 0.10000000000000002), (0.4850000000000006, 0.125, 8.326672684688674e-17, 0.10000000000000002), (0.4950000000000006, 0.125, 8.326672684688674e-17, 0.10000000000000002), (0.5050000000000006, 0.125, 0.0, 0.1)] return solution_porting
# __version__.py # autogenerated by poetry-hooks 0.1.0 __version__ = "0.1.0a0" __title__ = "pytorch-caldera" __authors__ = ["Justin Vrana <justin.vrana@gmail.com>"] __repository__ = "" __homepage__ = "http://www.github.com/jvrana/caldera" __description__ = "" __maintainers__ = "" __readme__ = "" __license__ = ""
__version__ = '0.1.0a0' __title__ = 'pytorch-caldera' __authors__ = ['Justin Vrana <justin.vrana@gmail.com>'] __repository__ = '' __homepage__ = 'http://www.github.com/jvrana/caldera' __description__ = '' __maintainers__ = '' __readme__ = '' __license__ = ''