idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
240,000 | def _decode_sensor_data ( properties ) : b64_input = "" for s in properties . get ( 'payload' ) : b64_input += s decoded = base64 . b64decode ( b64_input ) data = zlib . decompress ( decoded ) points = [ ] i = 0 while i < len ( data ) : points . append ( { 'timestamp' : int ( 1e3 * ArloBaseStation . _parse_statistic ( ... | Decode decompress and parse the data from the history API |
240,001 | def _parse_statistic ( data , scale ) : i = 0 for byte in bytearray ( data ) : i = ( i << 8 ) + byte if i == 32768 : return None if scale == 0 : return i return float ( i ) / ( scale * 10 ) | Parse binary statistics returned from the history API |
240,002 | def play_track ( self , track_id = DEFAULT_TRACK_ID , position = 0 ) : self . publish ( action = 'playTrack' , resource = 'audioPlayback/player' , publish_response = False , properties = { 'trackId' : track_id , 'position' : position } ) | Plays a track at the given position . |
240,003 | def set_shuffle_on ( self ) : self . publish ( action = 'set' , resource = 'audioPlayback/config' , publish_response = False , properties = { 'config' : { 'shuffleActive' : True } } ) | Sets playback to shuffle . |
240,004 | def set_shuffle_off ( self ) : self . publish ( action = 'set' , resource = 'audioPlayback/config' , publish_response = False , properties = { 'config' : { 'shuffleActive' : False } } ) | Sets playback to sequential . |
240,005 | def set_night_light_on ( self ) : self . publish ( action = 'set' , resource = 'cameras/{}' . format ( self . device_id ) , publish_response = False , properties = { 'nightLight' : { 'enabled' : True } } ) | Turns on the night light . |
240,006 | def set_night_light_off ( self ) : self . publish ( action = 'set' , resource = 'cameras/{}' . format ( self . device_id ) , publish_response = False , properties = { 'nightLight' : { 'enabled' : False } } ) | Turns off the night light . |
240,007 | def mode ( self , mode ) : modes = self . available_modes if ( not modes ) or ( mode not in modes ) : return self . publish ( action = 'set' , resource = 'modes' if mode != 'schedule' else 'schedule' , mode = mode , publish_response = True ) self . update ( ) | Set Arlo camera mode . |
240,008 | def unindent ( self , lines ) : indent = min ( len ( self . re . match ( r'^ *' , line ) . group ( ) ) for line in lines ) return [ line [ indent : ] . rstrip ( ) for line in lines ] | Removes any indentation that is common to all of the given lines . |
240,009 | def get_call_exprs ( self , line ) : line = line . lstrip ( ) try : tree = self . ast . parse ( line ) except SyntaxError : return None for node in self . ast . walk ( tree ) : if isinstance ( node , self . ast . Call ) : offsets = [ ] for arg in node . args : if isinstance ( arg , self . ast . Attribute ) and ( ( 3 , ... | Gets the argument expressions from the source of a function call . |
240,010 | def show ( self , func_name , values , labels = None ) : s = self . Stanza ( self . indent ) if func_name == '<module>' and self . in_console : func_name = '<console>' s . add ( [ func_name + ': ' ] ) reprs = map ( self . safe_repr , values ) if labels : sep = '' for label , repr in zip ( labels , reprs ) : s . add ( [... | Prints out nice representations of the given values . |
240,011 | def trace ( self , func ) : def wrapper ( * args , ** kwargs ) : s = self . Stanza ( self . indent ) s . add ( [ self . GREEN , func . __name__ , self . NORMAL , '(' ] ) s . indent += 4 sep = '' for arg in args : s . add ( [ self . CYAN , self . safe_repr ( arg ) , self . NORMAL ] , sep ) sep = ', ' for name , value in... | Decorator to print out a function s arguments and return value . |
240,012 | def d ( self , depth = 1 ) : info = self . inspect . getframeinfo ( self . sys . _getframe ( 1 ) ) s = self . Stanza ( self . indent ) s . add ( [ info . function + ': ' ] ) s . add ( [ self . MAGENTA , 'Interactive console opened' , self . NORMAL ] ) self . writer . write ( s . chunks ) frame = self . sys . _getframe ... | Launches an interactive console at the point where it s called . |
240,013 | def swagger ( self ) : if not self . __swagger : return None common_path = os . path . commonprefix ( list ( self . __swagger . paths ) ) common_path = common_path [ : - 1 ] if common_path [ - 1 ] == '/' else common_path if len ( common_path ) > 0 : p = six . moves . urllib . parse . urlparse ( common_path ) self . __s... | some preparation before returning Swagger object |
240,014 | def scope_compose ( scope , name , sep = private . SCOPE_SEPARATOR ) : if name == None : new_scope = scope else : new_scope = scope if scope else name if scope and name : new_scope = scope + sep + name return new_scope | compose a new scope |
240,015 | def nv_tuple_list_replace ( l , v ) : _found = False for i , x in enumerate ( l ) : if x [ 0 ] == v [ 0 ] : l [ i ] = v _found = True if not _found : l . append ( v ) | replace a tuple in a tuple list |
240,016 | def url_dirname ( url ) : p = six . moves . urllib . parse . urlparse ( url ) for e in [ private . FILE_EXT_JSON , private . FILE_EXT_YAML ] : if p . path . endswith ( e ) : return six . moves . urllib . parse . urlunparse ( p [ : 2 ] + ( os . path . dirname ( p . path ) , ) + p [ 3 : ] ) return url | Return the folder containing the . json file |
240,017 | def url_join ( url , path ) : p = six . moves . urllib . parse . urlparse ( url ) t = None if p . path and p . path [ - 1 ] == '/' : if path and path [ 0 ] == '/' : path = path [ 1 : ] t = '' . join ( [ p . path , path ] ) else : t = ( '' if path and path [ 0 ] == '/' else '/' ) . join ( [ p . path , path ] ) return si... | url version of os . path . join |
240,018 | def derelativise_url ( url ) : parsed = six . moves . urllib . parse . urlparse ( url ) newpath = [ ] for chunk in parsed . path [ 1 : ] . split ( '/' ) : if chunk == '.' : continue elif chunk == '..' : newpath = newpath [ : - 1 ] continue elif _fullmatch ( r'\.{3,}' , chunk ) is not None : newpath = newpath [ : - 1 ] ... | Normalizes URLs gets rid of .. and . |
240,019 | def get_swagger_version ( obj ) : if isinstance ( obj , dict ) : if 'swaggerVersion' in obj : return obj [ 'swaggerVersion' ] elif 'swagger' in obj : return obj [ 'swagger' ] return None else : return obj . swaggerVersion if hasattr ( obj , 'swaggerVersion' ) else obj . swagger | get swagger version from loaded json |
240,020 | def walk ( start , ofn , cyc = None ) : ctx , stk = { } , [ start ] cyc = [ ] if cyc == None else cyc while len ( stk ) : top = stk [ - 1 ] if top not in ctx : ctx . update ( { top : list ( ofn ( top ) ) } ) if len ( ctx [ top ] ) : n = ctx [ top ] [ 0 ] if n in stk : nc = stk [ stk . index ( n ) : ] ni = nc . index ( ... | Non recursive DFS to detect cycles |
240,021 | def _validate_param ( self , path , obj , _ ) : errs = [ ] if obj . allowMultiple : if not obj . paramType in ( 'path' , 'query' , 'header' ) : errs . append ( 'allowMultiple should be applied on path, header, or query parameters' ) if obj . type == 'array' : errs . append ( 'array Type with allowMultiple is not suppor... | validate option combination of Parameter object |
240,022 | def _validate_items ( self , path , obj , _ ) : errs = [ ] if obj . type == 'void' : errs . append ( 'void is only allowed in Operation object.' ) return path , obj . __class__ . __name__ , errs | validate option combination of Property object |
240,023 | def _validate_auth ( self , path , obj , _ ) : errs = [ ] if obj . type == 'apiKey' : if not obj . passAs : errs . append ( 'need "passAs" for apiKey' ) if not obj . keyname : errs . append ( 'need "keyname" for apiKey' ) elif obj . type == 'oauth2' : if not obj . grantTypes : errs . append ( 'need "grantTypes" for oau... | validate that apiKey and oauth2 requirements |
240,024 | def _validate_granttype ( self , path , obj , _ ) : errs = [ ] if not obj . implicit and not obj . authorization_code : errs . append ( 'Either implicit or authorization_code should be defined.' ) return path , obj . __class__ . __name__ , errs | make sure either implicit or authorization_code is defined |
240,025 | def _validate_auths ( self , path , obj , app ) : errs = [ ] for k , v in six . iteritems ( obj . authorizations or { } ) : if k not in app . raw . authorizations : errs . append ( 'auth {0} not found in resource list' . format ( k ) ) if app . raw . authorizations [ k ] . type in ( 'basicAuth' , 'apiKey' ) and v != [ ... | make sure that apiKey and basicAuth are empty list in Operation object . |
240,026 | def default_tree_traversal ( root , leaves ) : objs = [ ( '#' , root ) ] while len ( objs ) > 0 : path , obj = objs . pop ( ) if obj . __class__ not in leaves : objs . extend ( map ( lambda i : ( path + '/' + i [ 0 ] , ) + ( i [ 1 ] , ) , six . iteritems ( obj . _children_ ) ) ) yield path , obj | default tree traversal |
240,027 | def render_all ( self , op , exclude = [ ] , opt = None ) : opt = self . default ( ) if opt == None else opt if not isinstance ( op , Operation ) : raise ValueError ( 'Not a Operation: {0}' . format ( op ) ) if not isinstance ( opt , dict ) : raise ValueError ( 'Not a dict: {0}' . format ( opt ) ) template = opt [ 'par... | render a set of parameter for an Operation |
240,028 | def _prepare_forms ( self ) : content_type = 'application/x-www-form-urlencoded' if self . __op . consumes and content_type not in self . __op . consumes : raise errs . SchemaError ( 'content type {0} does not present in {1}' . format ( content_type , self . __op . consumes ) ) return content_type , six . moves . urlli... | private function to prepare content for paramType = form |
240,029 | def _prepare_body ( self ) : content_type = self . __consume if not content_type : content_type = self . __op . consumes [ 0 ] if self . __op . consumes else 'application/json' if self . __op . consumes and content_type not in self . __op . consumes : raise errs . SchemaError ( 'content type {0} does not present in {1}... | private function to prepare content for paramType = body |
240,030 | def _prepare_files ( self , encoding ) : content_type = 'multipart/form-data' if self . __op . consumes and content_type not in self . __op . consumes : raise errs . SchemaError ( 'content type {0} does not present in {1}' . format ( content_type , self . __op . consumes ) ) boundary = uuid4 ( ) . hex content_type += '... | private function to prepare content for paramType = form with File |
240,031 | def prepare ( self , scheme = 'http' , handle_files = True , encoding = 'utf-8' ) : if isinstance ( scheme , list ) : if self . __scheme is None : scheme = scheme . pop ( ) else : if self . __scheme in scheme : scheme = self . __scheme else : raise Exception ( 'preferred scheme:{} is not supported by the client or spec... | make this request ready for Clients |
240,032 | def apply_with ( self , status = None , raw = None , header = None ) : if status != None : self . __status = status r = ( final ( self . __op . responses . get ( str ( self . __status ) , None ) ) or final ( self . __op . responses . get ( 'default' , None ) ) ) if header != None : if isinstance ( header , ( collection... | update header status code raw datum ... etc |
240,033 | def parse ( self , obj = None ) : if obj == None : return if not isinstance ( obj , dict ) : raise ValueError ( 'invalid obj passed: ' + str ( type ( obj ) ) ) def _apply ( x , kk , ct , v ) : if key not in self . _obj : self . _obj [ kk ] = { } if ct == None else [ ] with x ( self . _obj , kk ) as ctx : ctx . parse ( ... | major part do parsing . |
240,034 | def _assign_parent ( self , ctx ) : def _assign ( cls , _ , obj ) : if obj == None : return if cls . is_produced ( obj ) : if isinstance ( obj , BaseObj ) : obj . _parent__ = self else : raise ValueError ( 'Object is not instance of {0} but {1}' . format ( cls . __swagger_ref_object__ . __name__ , obj . __class__ . __n... | parent assignment internal usage only |
240,035 | def get_private_name ( self , f ) : f = self . __swagger_rename__ [ f ] if f in self . __swagger_rename__ . keys ( ) else f return '_' + self . __class__ . __name__ + '__' + f | get private protected name of an attribute |
240,036 | def update_field ( self , f , obj ) : n = self . get_private_name ( f ) if not hasattr ( self , n ) : raise AttributeError ( '{0} is not in {1}' . format ( n , self . __class__ . __name__ ) ) setattr ( self , n , obj ) self . __origin_keys . add ( f ) | update a field |
240,037 | def resolve ( self , ts ) : if isinstance ( ts , six . string_types ) : ts = [ ts ] obj = self while len ( ts ) > 0 : t = ts . pop ( 0 ) if issubclass ( obj . __class__ , BaseObj ) : obj = getattr ( obj , t ) elif isinstance ( obj , list ) : obj = obj [ int ( t ) ] elif isinstance ( obj , dict ) : obj = obj [ t ] retur... | resolve a list of tokens to an child object |
240,038 | def compare ( self , other , base = None ) : if self . __class__ != other . __class__ : return False , '' names = self . _field_names_ def cmp_func ( name , s , o ) : if isinstance ( s , six . string_types ) and isinstance ( o , six . string_types ) : return s == o , name if s . __class__ != o . __class__ : return Fals... | comparison will return the first difference |
240,039 | def _field_names_ ( self ) : ret = [ ] for n in six . iterkeys ( self . __swagger_fields__ ) : new_n = self . __swagger_rename__ . get ( n , None ) ret . append ( new_n ) if new_n else ret . append ( n ) return ret | get list of field names defined in Swagger spec |
240,040 | def _children_ ( self ) : ret = { } names = self . _field_names_ def down ( name , obj ) : if isinstance ( obj , BaseObj ) : if not isinstance ( obj , weakref . ProxyTypes ) : ret [ name ] = obj elif isinstance ( obj , list ) : for i , v in zip ( range ( len ( obj ) ) , obj ) : down ( jp_compose ( str ( i ) , name ) , ... | get children objects |
240,041 | def load ( kls , url , getter = None , parser = None , url_load_hook = None , sep = consts . private . SCOPE_SEPARATOR , prim = None , mime_codec = None , resolver = None ) : logger . info ( 'load with [{0}]' . format ( url ) ) url = utils . normalize_url ( url ) app = kls ( url , url_load_hook = url_load_hook , sep = ... | load json as a raw App |
240,042 | def prepare ( self , strict = True ) : self . __root = self . prepare_obj ( self . raw , self . __url ) self . validate ( strict = strict ) if hasattr ( self . __root , 'schemes' ) and self . __root . schemes : if len ( self . __root . schemes ) > 0 : self . __schemes = self . __root . schemes else : self . __schemes =... | preparation for loaded json |
240,043 | def create ( kls , url , strict = True ) : app = kls . load ( url ) app . prepare ( strict = strict ) return app | factory of App |
240,044 | def resolve ( self , jref , parser = None ) : logger . info ( 'resolving: [{0}]' . format ( jref ) ) if jref == None or len ( jref ) == 0 : raise ValueError ( 'Empty Path is not allowed' ) obj = None url , jp = utils . jr_split ( jref ) o = self . __objs . get ( url , None ) if o : if isinstance ( o , BaseObj ) : obj =... | JSON reference resolver |
240,045 | def prepare_schemes ( self , req ) : ret = sorted ( self . __schemes__ & set ( req . schemes ) , reverse = True ) if len ( ret ) == 0 : raise ValueError ( 'No schemes available: {0}' . format ( req . schemes ) ) return ret | make sure this client support schemes required by current request |
240,046 | def compose_headers ( self , req , headers = None , opt = None , as_dict = False ) : if headers is None : return list ( req . header . items ( ) ) if not as_dict else req . header opt = opt or { } join_headers = opt . pop ( BaseClient . join_headers , None ) if as_dict and not join_headers : headers = dict ( headers ) ... | a utility to compose headers from pyswagger . io . Request and customized headers |
240,047 | def request ( self , req_and_resp , opt = None , headers = None ) : req , resp = req_and_resp logger . info ( 'request.url: {0}' . format ( req . url ) ) logger . info ( 'request.header: {0}' . format ( req . header ) ) logger . info ( 'request.query: {0}' . format ( req . query ) ) logger . info ( 'request.file: {0}' ... | preprocess before performing a request usually some patching . authorization also applied here . |
240,048 | def to_url ( self ) : if self . __collection_format == 'multi' : return [ str ( s ) for s in self ] else : return [ str ( self ) ] | special function for handling multi refer to Swagger 2 . 0 Parameter Object collectionFormat |
240,049 | def apply_with ( self , obj , val , ctx ) : for k , v in six . iteritems ( val ) : if k in obj . properties : pobj = obj . properties . get ( k ) if pobj . readOnly == True and ctx [ 'read' ] == False : raise Exception ( 'read-only property is set in write context.' ) self [ k ] = ctx [ 'factory' ] . produce ( pobj , v... | recursively apply Schema object |
240,050 | def _op ( self , _ , obj , app ) : if obj . responses == None : return tmp = { } for k , v in six . iteritems ( obj . responses ) : if isinstance ( k , six . integer_types ) : tmp [ str ( k ) ] = v else : tmp [ k ] = v obj . update_field ( 'responses' , tmp ) | convert status code in Responses from int to string |
240,051 | def produce ( self , obj , val , ctx = None ) : val = obj . default if val == None else val if val == None : return None obj = deref ( obj ) ctx = { } if ctx == None else ctx if 'name' not in ctx and hasattr ( obj , 'name' ) : ctx [ 'name' ] = obj . name if 'guard' not in ctx : ctx [ 'guard' ] = CycleGuard ( ) if 'addp... | factory function to create primitives |
240,052 | def _check_elementary_axis_name ( name : str ) -> bool : if len ( name ) == 0 : return False if not 'a' <= name [ 0 ] <= 'z' : return False for letter in name : if ( not letter . isdigit ( ) ) and not ( 'a' <= letter <= 'z' ) : return False return True | Valid elementary axes contain only lower latin letters and digits and start with a letter . |
240,053 | def open ( self ) : self . _window = Window ( caption = self . caption , height = self . height , width = self . width , vsync = False , resizable = True , ) | Open the window . |
240,054 | def show ( self , frame ) : if len ( frame . shape ) != 3 : raise ValueError ( 'frame should have shape with only 3 dimensions' ) if not self . is_open : self . open ( ) self . _window . clear ( ) self . _window . switch_to ( ) self . _window . dispatch_events ( ) image = ImageData ( frame . shape [ 1 ] , frame . shape... | Show an array of pixels on the window . |
240,055 | def display_arr ( screen , arr , video_size , transpose ) : if transpose : pyg_img = pygame . surfarray . make_surface ( arr . swapaxes ( 0 , 1 ) ) else : pyg_img = arr pyg_img = pygame . transform . scale ( pyg_img , video_size ) screen . blit ( pyg_img , ( 0 , 0 ) ) | Display an image to the pygame screen . |
240,056 | def play ( env , transpose = True , fps = 30 , nop_ = 0 ) : assert isinstance ( env . observation_space , gym . spaces . box . Box ) obs_s = env . observation_space is_bw = len ( obs_s . shape ) == 2 is_rgb = len ( obs_s . shape ) == 3 and obs_s . shape [ 2 ] in [ 1 , 3 ] assert is_bw or is_rgb if hasattr ( env , 'get_... | Play the game using the keyboard as a human . |
240,057 | def play_human ( env ) : try : play ( env , fps = env . metadata [ 'video.frames_per_second' ] ) except KeyboardInterrupt : pass env . close ( ) | Play the environment using keyboard as a human . |
240,058 | def get_action_meanings ( self ) : actions = sorted ( self . _action_meanings . keys ( ) ) return [ self . _action_meanings [ action ] for action in actions ] | Return a list of actions meanings . |
240,059 | def prg_rom ( self ) : try : return self . raw_data [ self . prg_rom_start : self . prg_rom_stop ] except IndexError : raise ValueError ( 'failed to read PRG-ROM on ROM.' ) | Return the PRG ROM of the ROM file . |
240,060 | def chr_rom ( self ) : try : return self . raw_data [ self . chr_rom_start : self . chr_rom_stop ] except IndexError : raise ValueError ( 'failed to read CHR-ROM on ROM.' ) | Return the CHR ROM of the ROM file . |
240,061 | def _screen_buffer ( self ) : address = _LIB . Screen ( self . _env ) buffer_ = ctypes . cast ( address , ctypes . POINTER ( SCREEN_TENSOR ) ) . contents screen = np . frombuffer ( buffer_ , dtype = 'uint8' ) screen = screen . reshape ( SCREEN_SHAPE_32_BIT ) if sys . byteorder == 'little' : screen = screen [ : , : , : ... | Setup the screen buffer from the C ++ code . |
240,062 | def _ram_buffer ( self ) : address = _LIB . Memory ( self . _env ) buffer_ = ctypes . cast ( address , ctypes . POINTER ( RAM_VECTOR ) ) . contents return np . frombuffer ( buffer_ , dtype = 'uint8' ) | Setup the RAM buffer from the C ++ code . |
240,063 | def _controller_buffer ( self , port ) : address = _LIB . Controller ( self . _env , port ) buffer_ = ctypes . cast ( address , ctypes . POINTER ( CONTROLLER_VECTOR ) ) . contents return np . frombuffer ( buffer_ , dtype = 'uint8' ) | Find the pointer to a controller and setup a NumPy buffer . |
240,064 | def _frame_advance ( self , action ) : self . controllers [ 0 ] [ : ] = action _LIB . Step ( self . _env ) | Advance a frame in the emulator with an action . |
240,065 | def reset ( self ) : self . _will_reset ( ) if self . _has_backup : self . _restore ( ) else : _LIB . Reset ( self . _env ) self . _did_reset ( ) self . done = False return self . screen | Reset the state of the environment and returns an initial observation . |
240,066 | def step ( self , action ) : if self . done : raise ValueError ( 'cannot step in a done environment! call `reset`' ) self . controllers [ 0 ] [ : ] = action _LIB . Step ( self . _env ) reward = self . _get_reward ( ) self . done = self . _get_done ( ) info = self . _get_info ( ) self . _did_step ( self . done ) if rewa... | Run one frame of the NES and return the relevant observation data . |
240,067 | def close ( self ) : if self . _env is None : raise ValueError ( 'env has already been closed.' ) _LIB . Close ( self . _env ) self . _env = None if self . viewer is not None : self . viewer . close ( ) | Close the environment . |
240,068 | def render ( self , mode = 'human' ) : if mode == 'human' : if self . viewer is None : from . _image_viewer import ImageViewer if self . spec is None : caption = self . _rom_path . split ( '/' ) [ - 1 ] else : caption = self . spec . id self . viewer = ImageViewer ( caption = caption , height = SCREEN_HEIGHT , width = ... | Render the environment . |
240,069 | def _get_args ( ) : parser = argparse . ArgumentParser ( description = __doc__ ) parser . add_argument ( '--rom' , '-r' , type = str , help = 'The path to the ROM to play.' , required = True , ) parser . add_argument ( '--mode' , '-m' , type = str , default = 'human' , choices = [ 'human' , 'random' ] , help = 'The exe... | Parse arguments from the command line and return them . |
240,070 | def main ( ) : args = _get_args ( ) env = NESEnv ( args . rom ) if args . mode == 'human' : play_human ( env ) else : play_random ( env , args . steps ) | The main entry point for the command line interface . |
240,071 | def play_random ( env , steps ) : try : done = True progress = tqdm ( range ( steps ) ) for _ in progress : if done : _ = env . reset ( ) action = env . action_space . sample ( ) _ , reward , done , info = env . step ( action ) progress . set_postfix ( reward = reward , info = info ) env . render ( ) except KeyboardInt... | Play the environment making uniformly random decisions . |
240,072 | def markowitz_portfolio ( cov_mat , exp_rets , target_ret , allow_short = False , market_neutral = False ) : if not isinstance ( cov_mat , pd . DataFrame ) : raise ValueError ( "Covariance matrix is not a DataFrame" ) if not isinstance ( exp_rets , pd . Series ) : raise ValueError ( "Expected returns is not a Series" )... | Computes a Markowitz portfolio . |
240,073 | def min_var_portfolio ( cov_mat , allow_short = False ) : if not isinstance ( cov_mat , pd . DataFrame ) : raise ValueError ( "Covariance matrix is not a DataFrame" ) n = len ( cov_mat ) P = opt . matrix ( cov_mat . values ) q = opt . matrix ( 0.0 , ( n , 1 ) ) if not allow_short : G = opt . matrix ( - np . identity ( ... | Computes the minimum variance portfolio . |
240,074 | def print_portfolio_info ( returns , avg_rets , weights ) : ret = ( weights * avg_rets ) . sum ( ) std = ( weights * returns ) . sum ( 1 ) . std ( ) sharpe = ret / std print ( "Optimal weights:\n{}\n" . format ( weights ) ) print ( "Expected return: {}" . format ( ret ) ) print ( "Expected variance: {}" . format ( st... | Print information on expected portfolio performance . |
240,075 | def main ( self ) : for m in self . methods : if m . name in [ 'Main' , 'main' ] : return m if len ( self . methods ) : return self . methods [ 0 ] return None | Return the default method in this module . |
240,076 | def orderered_methods ( self ) : oms = [ ] self . methods . reverse ( ) if self . main : oms = [ self . main ] for m in self . methods : if m == self . main : continue oms . append ( m ) return oms | An ordered list of methods |
240,077 | def write_methods ( self ) : b_array = bytearray ( ) for key , vm_token in self . all_vm_tokens . items ( ) : b_array . append ( vm_token . out_op ) if vm_token . data is not None and vm_token . vm_op != VMOp . NOP : b_array = b_array + vm_token . data return b_array | Write all methods in the current module to a byte string . |
240,078 | def link_methods ( self ) : from . . compiler import Compiler for method in self . methods : method . prepare ( ) self . all_vm_tokens = OrderedDict ( ) address = 0 for method in self . orderered_methods : if not method . is_interop : method . address = address for key , vmtoken in method . vm_tokens . items ( ) : self... | Perform linkage of addresses between methods . |
240,079 | def export_debug ( self , output_path ) : file_hash = hashlib . md5 ( open ( output_path , 'rb' ) . read ( ) ) . hexdigest ( ) avm_name = os . path . splitext ( os . path . basename ( output_path ) ) [ 0 ] json_data = self . generate_debug_json ( avm_name , file_hash ) mapfilename = output_path . replace ( '.avm' , '.d... | this method is used to generate a debug map for NEO debugger |
240,080 | def load_and_save ( path , output_path = None , use_nep8 = True ) : compiler = Compiler . load ( os . path . abspath ( path ) , use_nep8 = use_nep8 ) data = compiler . write ( ) if output_path is None : fullpath = os . path . realpath ( path ) path , filename = os . path . split ( fullpath ) newfilename = filename . re... | Call load_and_save to load a Python file to be compiled to the . avm format and save the result . By default the resultant . avm file is saved along side the source file . |
240,081 | def load ( path , use_nep8 = True ) : Compiler . __instance = None compiler = Compiler . instance ( ) compiler . nep8 = use_nep8 compiler . entry_module = Module ( path ) return compiler | Call load to load a Python file to be compiled but not to write to . avm |
240,082 | def add_record_references ( self , app_id , record_id , field_id , target_record_ids ) : self . _swimlane . request ( 'post' , 'app/{0}/record/{1}/add-references' . format ( app_id , record_id ) , json = { 'fieldId' : field_id , 'targetRecordIds' : target_record_ids } ) | Bulk operation to directly add record references without making any additional requests |
240,083 | def add_comment ( self , app_id , record_id , field_id , message ) : self . _swimlane . request ( 'post' , 'app/{0}/record/{1}/{2}/comment' . format ( app_id , record_id , field_id ) , json = { 'message' : message , 'createdDate' : pendulum . now ( ) . to_rfc3339_string ( ) } ) | Directly add a comment to a record without retrieving the app or record first |
240,084 | def _evaluate ( self ) : retrieved_records = SortedDict ( ) for record_id , record in six . iteritems ( self . _elements ) : if record is self . _field . _unset : try : record = self . target_app . records . get ( id = record_id ) except SwimlaneHTTP400Error : logger . debug ( "Received 400 response retrieving record '... | Scan for orphaned records and retrieve any records that have not already been grabbed |
240,085 | def add ( self , record ) : self . _field . validate_value ( record ) self . _elements [ record . id ] = record self . _sync_field ( ) | Add a reference to the provided record |
240,086 | def remove ( self , record ) : self . _field . validate_value ( record ) del self . _elements [ record . id ] self . _sync_field ( ) | Remove a reference to the provided record |
240,087 | def target_app ( self ) : if self . __target_app is None : self . __target_app = self . _swimlane . apps . get ( id = self . __target_app_id ) return self . __target_app | Defer target app retrieval until requested |
240,088 | def validate_value ( self , value ) : if value not in ( None , self . _unset ) : super ( ReferenceField , self ) . validate_value ( value ) if value . app != self . target_app : raise ValidationError ( self . record , "Reference field '{}' has target app '{}', cannot reference record '{}' from app '{}'" . format ( self... | Validate provided record is a part of the appropriate target app for the field |
240,089 | def set_swimlane ( self , value ) : if not self . multiselect : if value and not isinstance ( value , list ) : value = [ value ] value = value or [ ] records = SortedDict ( ) for record_id in value : records [ record_id ] = self . _unset return super ( ReferenceField , self ) . set_swimlane ( records ) | Store record ids in separate location for later use but ignore initial value |
240,090 | def set_python ( self , value ) : if not self . multiselect : if value and not isinstance ( value , list ) : value = [ value ] value = value or [ ] records = SortedDict ( ) for record in value : self . validate_value ( record ) records [ record . id ] = record return_value = self . _set ( records ) self . record . _raw... | Expect list of record instances convert to a SortedDict for internal representation |
240,091 | def get_swimlane ( self ) : value = super ( ReferenceField , self ) . get_swimlane ( ) if value : ids = list ( value . keys ( ) ) if self . multiselect : return ids return ids [ 0 ] return None | Return list of record ids |
240,092 | def get_python ( self ) : cursor = super ( ReferenceField , self ) . get_python ( ) if self . multiselect : return cursor else : try : return cursor [ 0 ] except IndexError : return None | Return cursor if multi - select direct value if single - select |
240,093 | def get ( self , key , value ) : if key == 'id' : response = self . _swimlane . request ( 'get' , 'app/{}' . format ( value ) ) if response . status_code == 204 : raise ValueError ( 'No app with id "{}"' . format ( value ) ) return App ( self . _swimlane , response . json ( ) ) else : for app in self . list ( ) : if va... | Get single app by one of id or name |
240,094 | def list ( self ) : response = self . _swimlane . request ( 'get' , 'app' ) return [ App ( self . _swimlane , item ) for item in response . json ( ) ] | Retrieve list of all apps |
240,095 | def users ( self ) : if self . __users is None : self . __users = GroupUsersCursor ( swimlane = self . _swimlane , user_ids = self . __user_ids ) return self . __users | Returns a GroupUsersCursor with list of User instances for this Group |
240,096 | def _evaluate ( self ) : if self . _elements : for element in self . _elements : yield element else : for user_id in self . __user_ids : element = self . _swimlane . users . get ( id = user_id ) self . _elements . append ( element ) yield element | Lazily retrieve and build User instances from returned data |
240,097 | def _user_raw_from_login_content ( login_content ) : matching_keys = [ 'displayName' , 'lastLogin' , 'active' , 'name' , 'isMe' , 'lastPasswordChangedDate' , 'passwordResetRequired' , 'groups' , 'roles' , 'email' , 'isAdmin' , 'createdDate' , 'modifiedDate' , 'createdByUser' , 'modifiedByUser' , 'userName' , 'id' , 'di... | Returns a User instance with appropriate raw data parsed from login response content |
240,098 | def __verify_server_version ( self ) : if compare_versions ( '.' . join ( [ _lib_major_version , _lib_minor_version ] ) , self . product_version ) > 0 : logger . warning ( 'Client version {} connecting to server with newer minor release {}.' . format ( _lib_full_version , self . product_version ) ) if compare_versions ... | Verify connected to supported server product version |
240,099 | def settings ( self ) : if not self . __settings : self . __settings = self . request ( 'get' , 'settings' ) . json ( ) return self . __settings | Retrieve and cache settings from server |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.