Best Python code snippet using pyatom_python
MainScript.py
Source:MainScript.py  
1# Grader Comments:2# -5 Should put the main file outside the BusinessObjects module3# -2 for getting the stock number wrong4# -2 for getting the put number wrong5# -3 for insufficient comments6'''7Bernardo Bravo-Benitez, bb26998Chendi Ni, cn23679Sept.19th, 201410'''11#import the csv module12import csv13#import SecurityObjects module14from SecurityObjects import Bond, Option, Stock15#import datetime module to compare dates16from datetime import datetime17class PortfolioConcentration(object):18    19    #open a comma delimited file and return the output20    '''21    This method loads the csv data into a dictionary which has the structure: {'Bond':[a list of 'Bond' objects ], 22    'Stock':[a list of 'Stock' objects], 'Option':[a list of 'Option' objects]} 23    '''24    def GetObjectList(self):25        try:26            positionsFile = None27            # raw string28            fileName = r".\PortfolioAppraisal2.csv"29            if not csv.Sniffer().has_header(fileName):30                raise Exception("headers expected in position file. FileName: " + fileName)31            positionsFile = open(fileName, 'rt')32            dictReader = csv.DictReader(positionsFile)33            #dictReader is list of dictionaries where the keys are the column headers and the values represent one row of values34            dictTag = {}35            #iterate over 36            for dictRow in dictReader:37                securitytype = dictRow['SecurityTypeCode']38                NewObject={'Bond':Bond(dictRow["IssuerDesc"],dictRow["SecurityCode"],dictRow["SecurityDesc"],dictRow["HoldingDirection"],dictRow["CustodianCode"],dictRow["CurrencyCode"],dictRow["Quantity"],dictRow["PriceLocal"],dictRow["PriceBook"],dictRow["UnderlierPriceBook"],dictRow["MktValLocal"],dictRow["MktValBook"],dictRow["AvgCostLocal"],dictRow["AvgCostBook"],dictRow["CostLocal"],dictRow["CostBook"],dictRow["DtdPnlTotal"],dictRow["MtdPnlTotal"],dictRow["YtdPnlTotal"],dictRow["NetExposure"],dictRow["BbergCode"],dictRow["BloombergMarketSectorCode"],dictRow["Cusip"],dictRow["Sedol"],dictRow["Isin"],dictRow["AccrualStartDate"],dictRow["FrequencyCode"],dictRow["Coupon"],dictRow["IssuedDate"],dictRow["Maturity"],dictRow["Strike"],dictRow["ContractSize"],dictRow["ExcerciseType"],dictRow["PutCall"],dictRow["Expiration"],dictRow["ExchangeCode"],dictRow["SecurityTypeCode"],dictRow["SectorDesc"],dictRow["GeographyRegionDesc"],dictRow["GicsSectorDesc"]),'Stock':Stock(dictRow["IssuerDesc"],dictRow["SecurityCode"],dictRow["SecurityDesc"],dictRow["HoldingDirection"],dictRow["CustodianCode"],dictRow["CurrencyCode"],dictRow["Quantity"],dictRow["PriceLocal"],dictRow["PriceBook"],dictRow["UnderlierPriceBook"],dictRow["MktValLocal"],dictRow["MktValBook"],dictRow["AvgCostLocal"],dictRow["AvgCostBook"],dictRow["CostLocal"],dictRow["CostBook"],dictRow["DtdPnlTotal"],dictRow["MtdPnlTotal"],dictRow["YtdPnlTotal"],dictRow["NetExposure"],dictRow["BbergCode"],dictRow["BloombergMarketSectorCode"],dictRow["Cusip"],dictRow["Sedol"],dictRow["Isin"],dictRow["AccrualStartDate"],dictRow["FrequencyCode"],dictRow["Coupon"],dictRow["IssuedDate"],dictRow["Maturity"],dictRow["Strike"],dictRow["ContractSize"],dictRow["ExcerciseType"],dictRow["PutCall"],dictRow["Expiration"],dictRow["ExchangeCode"],dictRow["SecurityTypeCode"],dictRow["SectorDesc"],dictRow["GeographyRegionDesc"],dictRow["GicsSectorDesc"]),'Option':Option(dictRow["IssuerDesc"],dictRow["SecurityCode"],dictRow["SecurityDesc"],dictRow["HoldingDirection"],dictRow["CustodianCode"],dictRow["CurrencyCode"],dictRow["Quantity"],dictRow["PriceLocal"],dictRow["PriceBook"],dictRow["UnderlierPriceBook"],dictRow["MktValLocal"],dictRow["MktValBook"],dictRow["AvgCostLocal"],dictRow["AvgCostBook"],dictRow["CostLocal"],dictRow["CostBook"],dictRow["DtdPnlTotal"],dictRow["MtdPnlTotal"],dictRow["YtdPnlTotal"],dictRow["NetExposure"],dictRow["BbergCode"],dictRow["BloombergMarketSectorCode"],dictRow["Cusip"],dictRow["Sedol"],dictRow["Isin"],dictRow["AccrualStartDate"],dictRow["FrequencyCode"],dictRow["Coupon"],dictRow["IssuedDate"],dictRow["Maturity"],dictRow["Strike"],dictRow["ContractSize"],dictRow["ExcerciseType"],dictRow["PutCall"],dictRow["Expiration"],dictRow["ExchangeCode"],dictRow["SecurityTypeCode"],dictRow["SectorDesc"],dictRow["GeographyRegionDesc"],dictRow["GicsSectorDesc"])}[securitytype]39                #need to cast to float40                if(dictTag.has_key(securitytype)):41                    dictTag[securitytype].append(NewObject)42                else:43                    dictTag[securitytype] = [NewObject]44            return dictTag45        except Exception, e:46            print e47            raise e48        finally:49            #print 'Finalizer called'50            if positionsFile != None :51                positionsFile.close()52    53    def Count(self,ObjList,tag1,tag2):54        '''55        This method counts the number of distinct certain securities56        tag1: security type column header,57        tag2: security name column header58        example:59        for problem(a) one should put tag1 as 'Bond' and tag2 as 'SecurityDesc'60        '''61        try:62            keylist=[]63            for Obj in ObjList[tag1]:64                if not getattr(Obj,tag2) in keylist:65                    keylist.append(getattr(Obj,tag2))66            return len(keylist)67        except Exception,e:68            print e69    70    def TagCount(self,ObjList,tag1, tag2, tagvalue):71        '''72        This method counts the number of certain securities that has certain values73        tag1: security type column header,74        tag2: the column header of the target attribute75        tagvalue: the target value of the target attribute76        example:77        for problem(b) one should put tag1 as 'Option' and tag2 as 'PutCall' and tagvalue as 'C'78        '''79        try:80            count=081            for Obj in ObjList[tag1]:82                if getattr(Obj, tag2)==tagvalue:83                    count=count+184            return count85        except Exception,e:    86            print e87    def DistinctTagCount(self,ObjList,tag1, tag2, tagvalue,tag3):88        '''89        This method counts the number of certain distinct securities that has certain values(which does not count duplicated securities)90        tag1: security type column header,91        tag2: the column header of the target attribute92        tagvalue: the target value of the target attribute93        tag3: tag for distinction use94        example:95        for problem(d) one should put tag1 as 'Bond', tag2 as 'SectorDesc', tagvalue as 'Health Care' and tag3 as "SecurityDesc"96        '''97        try:98            count=099            keylist=[]100            for Obj in ObjList[tag1]:101                if getattr(Obj, tag2)==tagvalue:102                    if not getattr(Obj,tag3) in keylist:103                        count=count+1104                        keylist.append(getattr(Obj,tag3))105            return count106        except Exception,e:    107            print e108    109    def GetMax(self,ObjList,tag1,tag2,taginfo):110        '''111        This method finds the maximum of certain attribute of certain securities112        tag1: security type column header,113        tag2: the column header of the target attribute114        taginfo: the column header of the the name of the target attribute115        example:116        for problem(c) one should put tag1 as 'Bond' and tag2 as 'Maturity' and taginfo as 'SecurityDesc'117        '''118        try:119            #to compare 2 string-type dates we imported datetime method in datetime module that converts strings into date objects so that they can be compared120            if tag2=='Maturity':121                ansdict={}122                for Obj in ObjList[tag1]:123                    if getattr(Obj,tag2)=='NULL':124                        continue125                    if not bool(ansdict):126                        ansdict[tag2]=[getattr(Obj,tag2),getattr(Obj,taginfo)]127                    else:128                        if datetime.strptime(getattr(Obj,tag2),"%m/%d/%Y")>datetime.strptime(ansdict[tag2][0],"%m/%d/%Y"):129                            ansdict[tag2]=[getattr(Obj,tag2),getattr(Obj,taginfo)]130            else:131                ansdict={}132                for Obj in ObjList[tag1]:133                    if not bool(ansdict):134                        ansdict[tag2]=[getattr(Obj,tag2),getattr(Obj,taginfo)]135                    else:136                        if getattr(Obj,tag2)>ansdict['tag2'][0]:137                            ansdict[tag2]=[getattr(Obj,tag2),getattr(Obj,taginfo)]138            return ansdict139        except Exception,e:140                print e    141try:142    newtest=PortfolioConcentration()143    print('Problem(a):')144    print('Number of distinct bonds:'+str(newtest.Count(newtest.GetObjectList(), 'Bond','SecurityDesc')))145    print('Number of distinct stocks:'+str(newtest.Count(newtest.GetObjectList(), 'Stock','SecurityDesc')))146    print('Number of distinct options:'+str(newtest.Count(newtest.GetObjectList(), 'Option','SecurityDesc')))147    print('Problem(b):')148    print('Call Option Numbers:'+str(newtest.TagCount(newtest.GetObjectList(), 'Option','PutCall','C')))149    print('Put Option Numbers:'+str(newtest.TagCount(newtest.GetObjectList(), 'Option','PutCall','P')))150    print('Problem(c):')151    attrlist=newtest.GetMax(newtest.GetObjectList(), 'Bond', 'Maturity', 'SecurityDesc')['Maturity']152    print('Bond with the farthest maturity date and its maturity date:')153    print(attrlist[1]+', '+attrlist[0])154    print('Problem(d):')155    print('Number of securities in the portfolio belong to the Health Care sector:'+str(newtest.DistinctTagCount(newtest.GetObjectList(), 'Bond','SectorDesc','Health Care','SecurityDesc')+newtest.DistinctTagCount(newtest.GetObjectList(), 'Stock','SectorDesc','Health Care','SecurityDesc')+newtest.DistinctTagCount(newtest.GetObjectList(), 'Option','SectorDesc','Health Care','SecurityDesc')))    #print type(newtest.GetObjectList()['Bond'][0].Maturity)156    157except Exception, e:...testchecker.py
Source:testchecker.py  
1try:2    import rhinoscriptsyntax as rs3    import Rhino, scriptcontext4    import System.Drawing, System.Guid5    from System.Drawing import *6    from Rhino import *7    from Rhino.DocObjects import *8    from Rhino.DocObjects.Tables import *9    from Rhino.Geometry import *10    from Rhino.Input import *11    from Rhino.Commands import *12    from Rhino.UI.Dialogs import ShowColorDialog13    from scriptcontext import doc14except:15    pass16def get_num_layer():17    count = 018    objID = []19    while 1:20        count += 121        zero_str = '000000'22        objName = 'Layer: ' + zero_str[:-len(str(count))] + str(count) + ' Wall1'23        objID.append(rs.ObjectsByName(objName))24        if objID[-1] == []:25            # rs.HideObjects(objID[:])26            return count - 127_NUM_LAYER = get_num_layer()28def FindObjectsByName(name):29    settings = Rhino.DocObjects.ObjectEnumeratorSettings()30    settings.NameFilter = name31    ids = [rhobj.Id for rhobj in scriptcontext.doc.Objects.GetObjectList(settings)]32    if not ids:33        print "No objects with the name", name34        return Rhino.Commands.Result.Failure35    else:36        print "Found", len(ids), "objects"37    return Rhino.Commands.Result.Success38def GetPointDynamicDrawFuncHide(sender, args):39    obj_all = rs.VisibleObjects()40    rs.HideObjects(obj_all)41    cursPos = rs.GetCursorPos()42    viewSize = rs.ViewSize()43    stepSize = int(viewSize[1] / _NUM_LAYER)44    obj_Layer1 = 'Layer: 000001 Wall1'45    obj_Layer2 = 'Layer: 000002 Wall1'46    settings = Rhino.DocObjects.ObjectEnumeratorSettings()47    settings.HiddenObjects = True48    settings.NameFilter = obj_Layer149    ids_L1 = [rhobj.Id for rhobj in scriptcontext.doc.Objects.GetObjectList(settings)]50    settings.NameFilter = obj_Layer251    ids_L2 = [rhobj.Id for rhobj in scriptcontext.doc.Objects.GetObjectList(settings)]52    z_L1 = rs.BoundingBox(ids_L1[0])[0][2]53    z_L2 = rs.BoundingBox(ids_L2[0])[0][2]54    zVal = viewSize[1] - cursPos[3][1]55    z_level = int(zVal / stepSize)56    segmentList = ['Wall',57                   'DenseInfill',58                   'SparseInfill',59                   'Brim',60                   'Skirt',61                   'Support']62    zero_str = '000000'63    settings = ObjectEnumeratorSettings()64    settings.HiddenObjects = True65    for segment in segmentList:66        i = 067        while 1:68            i += 169            obj_LayerZ = str('Layer: ' + zero_str[:-len(str(z_level))] + str(z_level) + ' ' + segment + str(i))70            try:71                settings.NameFilter = obj_LayerZ72                ids_LZ = [rhobj.Id for rhobj in scriptcontext.doc.Objects.GetObjectList(settings)]73                if len(ids_LZ) == 0:74                    break75                # rs.SelectObject(ids_LZ)76                rs.ShowObject(ids_LZ)77            except:78                print 'not found'79    args.Display.DrawDot(args.CurrentPoint, 'Layer ' + str(z_level) + ' - Distance ' + str(z_L2 - z_L1) + ' mm')80    Rhino.Display.RhinoView.Redraw(scriptcontext.doc.Views.ActiveView)81    Rhino.RhinoApp.Wait()82def GetPointDynamicDrawFuncSelect(sender, args):83    # pt1 = Rhino.Geometry.Point3d(0,0,0)84    # pt2 = Rhino.Geometry.Point3d(10,10,0)85    # args.Display.DrawLine(pt1, args.CurrentPoint, System.Drawing.Color.Red, 2)86    # args.Display.DrawLine(pt2, args.CurrentPoint, System.Drawing.Color.Blue, 2)87    rs.UnselectAllObjects()88    cursPos = rs.GetCursorPos()89    viewSize = rs.ViewSize()90    stepSize = int(viewSize[1] / _NUM_LAYER)91    obj_Layer1 = 'Layer: 000001 Wall1'92    obj_Layer2 = 'Layer: 000002 Wall1'93    settings = Rhino.DocObjects.ObjectEnumeratorSettings()94    settings.NameFilter = obj_Layer195    ids_L1 = [rhobj.Id for rhobj in scriptcontext.doc.Objects.GetObjectList(settings)]96    settings.NameFilter = obj_Layer297    ids_L2 = [rhobj.Id for rhobj in scriptcontext.doc.Objects.GetObjectList(settings)]98    z_L1 = rs.BoundingBox(ids_L1[0])[0][2]99    z_L2 = rs.BoundingBox(ids_L2[0])[0][2]100    zVal = viewSize[1] - cursPos[3][1]101    z_level = int(zVal / stepSize)102    segmentList = ['Wall',103                   'DenseInfill',104                   'SparseInfill',105                   'Brim',106                   'Skirt',107                   'Support']108    zero_str = '000000'109    settings = ObjectEnumeratorSettings()110    for segment in segmentList:111        i = 0112        while 1:113            i += 1114            obj_LayerZ = str('Layer: ' + zero_str[:-len(str(z_level))] + str(z_level) + ' ' + segment + str(i))115            try:116                settings.NameFilter = obj_LayerZ117                ids_LZ = [rhobj.Id for rhobj in scriptcontext.doc.Objects.GetObjectList(settings)]118                if len(ids_LZ) == 0:119                    break120                rs.SelectObject(ids_LZ)121            except:122                print 'not found'123    args.Display.DrawDot(args.CurrentPoint, 'Layer ' + str(z_level) + ' - Distance ' + str(z_L2 - z_L1) + ' mm')124    Rhino.Display.RhinoView.Redraw(scriptcontext.doc.Views.ActiveView)125    Rhino.RhinoApp.Wait()126class testchecker():127    def __init__(self):128        pass129    def draw_line_select(self):130        # Create an instance of a GetPoint class and add a delegate for the DynamicDraw event131        gp = Rhino.Input.Custom.GetPoint()132        # gp = Rhino.Input.Custom.PickContext()133        gp.DynamicDraw += GetPointDynamicDrawFuncSelect134        gp.Get()135        obj_all = rs.HiddenObjects()136        rs.ShowObjects(obj_all)137        # print gp.Point()138    def draw_line_hide(self):139        obj_all = rs.VisibleObjects()140        rs.HideObjects(obj_all)141        # Create an instance of a GetPoint class and add a delegate for the DynamicDraw event142        gp = Rhino.Input.Custom.GetPoint()143        # gp = Rhino.Input.Custom.PickContext()144        gp.DynamicDraw += GetPointDynamicDrawFuncHide145        gp.Get()146        obj_all = rs.HiddenObjects()...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
