signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def add_font ( self , family , style = '' , fname = '' , uni = False ) : "Add a TrueType or Type1 font"
family = family . lower ( ) if ( fname == '' ) : fname = family . replace ( ' ' , '' ) + style . lower ( ) + '.pkl' if ( family == 'arial' ) : family = 'helvetica' style = style . upper ( ) if ( style == 'IB' ) : style = 'BI' fontkey = family + style if fontkey in self . fonts : # Font already added ! r...
def parse_boolargs ( self , args ) : """Returns an array populated by given values , with the indices of those values dependent on given boolen tests on self . The given ` args ` should be a list of tuples , with the first element the return value and the second argument a string that evaluates to either Tr...
if not isinstance ( args , list ) : args = [ args ] # format the arguments return_vals = [ ] bool_args = [ ] for arg in args : if not isinstance ( arg , tuple ) : return_val = arg bool_arg = None elif len ( arg ) == 1 : return_val = arg [ 0 ] bool_arg = None elif len ( ar...
def zoomset_cb ( self , setting , value , channel ) : """This callback is called when the main window is zoomed ."""
if not self . gui_up : return info = channel . extdata . _info_info if info is None : return # scale _ x , scale _ y = fitsimage . get _ scale _ xy ( ) scale_x , scale_y = value # Set text showing zoom factor ( 1X , 2X , etc . ) if scale_x == scale_y : text = self . fv . scale2text ( scale_x ) else : te...
def get_default_target_names ( estimator , num_targets = None ) : """Return a vector of target names : " y " if there is only one target , and " y0 " , " y1 " , . . . if there are multiple targets ."""
if num_targets is None : if len ( estimator . coef_ . shape ) <= 1 : num_targets = 1 else : num_targets , _ = estimator . coef_ . shape if num_targets == 1 : target_names = [ 'y' ] else : target_names = [ 'y%d' % i for i in range ( num_targets ) ] return np . array ( target_names )
def ports ( self ) -> dict : """Create a smaller dictionary containing all ports ."""
return { param : self [ param ] . raw for param in self if param . startswith ( IOPORT ) }
def repl ( # noqa : C901 old_ctx , prompt_kwargs = None , allow_system_commands = True , allow_internal_commands = True , ) : """Start an interactive shell . All subcommands are available in it . : param old _ ctx : The current Click context . : param prompt _ kwargs : Parameters passed to : py : func : ` pro...
# parent should be available , but we ' re not going to bother if not group_ctx = old_ctx . parent or old_ctx group = group_ctx . command isatty = sys . stdin . isatty ( ) # Delete the REPL command from those available , as we don ' t want to allow # nesting REPLs ( note : pass ` None ` to ` pop ` as we don ' t want to...
def resolve_node ( self , node = None , resolved = None , seen = None ) : """Resolve a single node or all when node is omitted ."""
if seen is None : seen = [ ] if resolved is None : resolved = [ ] if node is None : dependencies = sorted ( self . _nodes . keys ( ) ) else : dependencies = self . _nodes [ node ] seen . append ( node ) for dependency in dependencies : if dependency in resolved : continue if dependen...
async def set_did_endpoint ( self , remote_did : str , did_endpoint : str ) -> EndpointInfo : """Set endpoint as metadata for pairwise remote DID in wallet . Pick up ( transport ) verification key from pairwise relation and return with endpoint in EndpointInfo . Raise BadIdentifier on bad DID . Raise WalletStat...
LOGGER . debug ( 'BaseAnchor.set_did_endpoint >>> remote_did: %s, did_endpoint: %s' , remote_did , did_endpoint ) if not ok_did ( remote_did ) : LOGGER . debug ( 'BaseAnchor.set_did_endpoint <!< Bad DID %s' , remote_did ) raise BadIdentifier ( 'Bad DID {}' . format ( remote_did ) ) pairwise_info = ( await self ...
def until ( self , method , message = '' ) : """Calls the method provided with the driver as an argument until the return value does not evaluate to ` ` False ` ` . : param method : callable ( WebDriver ) : param message : optional message for : exc : ` TimeoutException ` : returns : the result of the last ca...
screen = None stacktrace = None end_time = time . time ( ) + self . _timeout while True : try : value = method ( self . _driver ) if value : return value except self . _ignored_exceptions as exc : screen = getattr ( exc , 'screen' , None ) stacktrace = getattr ( exc ,...
def ensure_unicode_args ( function ) : '''Decodes all arguments passed to the wrapped function'''
@ wraps ( function ) def wrapped ( * args , ** kwargs ) : if six . PY2 : return function ( * salt . utils . data . decode_list ( args ) , ** salt . utils . data . decode_dict ( kwargs ) ) else : return function ( * args , ** kwargs ) return wrapped
def can_proceed ( bound_method , check_conditions = True ) : """Returns True if model in state allows to call bound _ method Set ` ` check _ conditions ` ` argument to ` ` False ` ` to skip checking conditions ."""
if not hasattr ( bound_method , '_django_fsm' ) : im_func = getattr ( bound_method , 'im_func' , getattr ( bound_method , '__func__' ) ) raise TypeError ( '%s method is not transition' % im_func . __name__ ) meta = bound_method . _django_fsm im_self = getattr ( bound_method , 'im_self' , getattr ( bound_method ...
def matching_files ( self ) : """Find files . Returns : list : the list of matching files ."""
matching = [ ] matcher = self . file_path_regex pieces = self . file_path_regex . pattern . split ( sep ) partial_matchers = list ( map ( re . compile , ( sep . join ( pieces [ : i + 1 ] ) for i in range ( len ( pieces ) ) ) ) ) for root , dirs , files in walk ( self . top_dir , topdown = True ) : for i in reversed...
def _command_template ( self , switches , objectInput = None ) : """Template for Tika app commands Args : switches ( list ) : list of switches to Tika app Jar objectInput ( object ) : file object / standard input to analyze Return : Standard output data ( unicode Python 2 , str Python 3)"""
command = [ "java" , "-jar" , self . file_jar , "-eUTF-8" ] if self . memory_allocation : command . append ( "-Xmx{}" . format ( self . memory_allocation ) ) command . extend ( switches ) if not objectInput : objectInput = subprocess . PIPE log . debug ( "Subprocess command: {}" . format ( ", " . join ( command...
def get_corrected_commands ( command ) : """Returns generator with sorted and unique corrected commands . : type command : thefuck . types . Command : rtype : Iterable [ thefuck . types . CorrectedCommand ]"""
corrected_commands = ( corrected for rule in get_rules ( ) if rule . is_match ( command ) for corrected in rule . get_corrected_commands ( command ) ) return organize_commands ( corrected_commands )
def cp ( args ) : """% prog cp " s3 : / / hli - mv - data - science / htang / str / * . csv " . Copy files to folder . Accepts list of s3 addresses as input ."""
p = OptionParser ( cp . __doc__ ) p . add_option ( "--force" , default = False , action = "store_true" , help = "Force overwrite if exists" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) store , folder = args force = opts . force cpus = opts . c...
def process_dataset ( dataset , models , ** kargs ) : """Convert ` ` dataset ` ` to processed data using ` ` models ` ` . : class : ` gvar . dataset . Dataset ` ( or similar dictionary ) object ` ` dataset ` ` is processed by each model in list ` ` models ` ` , and the results collected into a new dictionary ...
dset = collections . OrderedDict ( ) for m in MultiFitter . flatten_models ( models ) : dset [ m . datatag ] = ( m . builddataset ( dataset ) if m . ncg <= 1 else MultiFitter . coarse_grain ( m . builddataset ( dataset ) , ncg = m . ncg ) ) return gvar . dataset . avg_data ( dset , ** kargs )
def model_fields ( model , allow_pk = False , only = None , exclude = None , field_args = None , converter = None ) : """Generate a dictionary of fields for a given Peewee model . See ` model _ form ` docstring for description of parameters ."""
converter = converter or ModelConverter ( ) field_args = field_args or { } model_fields = list ( model . _meta . sorted_fields ) if not allow_pk : model_fields . pop ( 0 ) if only : model_fields = [ x for x in model_fields if x . name in only ] elif exclude : model_fields = [ x for x in model_fields if x . ...
def latex ( self ) : """Gives a latex representation of the assessment ."""
output = self . latex_preamble output += self . _repr_latex_ ( ) output += self . latex_post return output
def _init ( self ) : """Turn the records into actual usable keys ."""
self . _entry_points = { } for entry_point in self . raw_entry_points : if entry_point . dist . project_name != self . reserved . get ( entry_point . name , entry_point . dist . project_name ) : logger . error ( "registry '%s' for '%s' is reserved for package '%s'" , entry_point . name , self . registry_nam...
def SHA1_file ( filepath , extra = b'' ) : """Returns hex digest of SHA1 hash of file at filepath : param str filepath : File to hash : param bytes extra : Extra content added to raw read of file before taking hash : return : hex digest of hash : rtype : str"""
h = hashlib . sha1 ( ) with io . open ( filepath , 'rb' ) as f : for chunk in iter ( lambda : f . read ( h . block_size ) , b'' ) : h . update ( chunk ) h . update ( extra ) return h . hexdigest ( )
def add_templatetype ( templatetype , ** kwargs ) : """Add a template type with typeattrs ."""
type_i = _update_templatetype ( templatetype ) db . DBSession . flush ( ) return type_i
def to_url ( self ) : """special function for handling ' multi ' , refer to Swagger 2.0 , Parameter Object , collectionFormat"""
if self . __collection_format == 'multi' : return [ str ( s ) for s in self ] else : return [ str ( self ) ]
def add_passthru ( self , prefix ) : """Register a URL prefix to passthru any non - matching mock requests to . For example , to allow any request to ' https : / / example . com ' , but require mocks for the remainder , you would add the prefix as so : > > > responses . add _ passthru ( ' https : / / example ...
if _has_unicode ( prefix ) : prefix = _clean_unicode ( prefix ) self . passthru_prefixes += ( prefix , )
def followers ( self ) : """获取话题关注者 : return : 话题关注者 , 返回生成器 : rtype : Author . Iterable"""
from . author import Author , ANONYMOUS self . _make_soup ( ) gotten_data_num = 20 data = { '_xsrf' : self . xsrf , 'start' : '' , 'offset' : 0 } while gotten_data_num == 20 : res = self . _session . post ( Topic_Get_More_Follower_Url . format ( self . id ) , data = data ) j = res . json ( ) [ 'msg' ] gotte...
def tokenizer ( self ) : """A property to link into IntentEngine ' s tokenizer . Warning : this is only for backwards compatiblility and should not be used if you intend on using domains . Return : the domains tokenizer from its IntentEngine"""
domain = 0 if domain not in self . domains : self . register_domain ( domain = domain ) return self . domains [ domain ] . tokenizer
def _parse_bbox_list ( bbox_list ) : """Helper method for parsing a list of bounding boxes"""
if isinstance ( bbox_list , BBoxCollection ) : return bbox_list . bbox_list , bbox_list . crs if not isinstance ( bbox_list , list ) or not bbox_list : raise ValueError ( 'Expected non-empty list of BBox objects' ) for bbox in bbox_list : if not isinstance ( bbox , BBox ) : raise ValueError ( 'Eleme...
def repmct ( instr , marker , value , repcase , lenout = None ) : """Replace a marker with the text representation of a cardinal number . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / repmc _ c . html : param instr : Input string . : type instr : str : param marker : Mark...
if lenout is None : lenout = ctypes . c_int ( len ( instr ) + len ( marker ) + 15 ) instr = stypes . stringToCharP ( instr ) marker = stypes . stringToCharP ( marker ) value = ctypes . c_int ( value ) repcase = ctypes . c_char ( repcase . encode ( encoding = 'UTF-8' ) ) out = stypes . stringToCharP ( lenout ) libsp...
def showAddColumnDialog ( self , triggered ) : """Display the dialog to add a column to the model . This method is also a slot . Args : triggered ( bool ) : If the corresponding button was activated , the dialog will be created and shown ."""
if triggered : dialog = AddAttributesDialog ( self ) dialog . accepted . connect ( self . addColumn ) dialog . rejected . connect ( self . uncheckButton ) dialog . show ( )
def FromTrimmedData ( data , index ) : """Deserialize into a Header object from the provided data . Args : data ( bytes ) : index : UNUSED Returns : Header :"""
header = Header ( ) ms = StreamManager . GetStream ( data ) reader = BinaryReader ( ms ) header . DeserializeUnsigned ( reader ) reader . ReadByte ( ) witness = Witness ( ) witness . Deserialize ( reader ) header . Script = witness StreamManager . ReleaseStream ( ms ) return header
def dispatch ( self , pid , method , * args ) : """Call a method on another process by its pid . The method on the other process does not need to be installed with ` ` Process . install ` ` . The call is serialized with all other calls on the context ' s event loop . The pid must be bound to this context . ...
self . _assert_started ( ) self . _assert_local_pid ( pid ) function = self . _get_dispatch_method ( pid , method ) self . __loop . add_callback ( function , * args )
def dicom_to_nifti ( dicom_input , output_file = None ) : """This is the main dicom to nifti conversion fuction for ge images . As input ge images are required . It will then determine the type of images and do the correct conversion Examples : See unit test : param output _ file : the filepath to the output ...
assert common . is_ge ( dicom_input ) logger . info ( 'Reading and sorting dicom files' ) grouped_dicoms = _get_grouped_dicoms ( dicom_input ) if _is_4d ( grouped_dicoms ) : logger . info ( 'Found sequence type: 4D' ) return _4d_to_nifti ( grouped_dicoms , output_file ) logger . info ( 'Assuming anatomical data...
def lotus_root_geometry ( ) : """Tomographic geometry for the lotus root dataset . Notes See the article ` Tomographic X - ray data of a lotus root filled with attenuating objects ` _ for further information . See Also lotus _ root _ geometry References . . _ Tomographic X - ray data of a lotus root f...
# To get the same rotation as in the reference article a_offset = np . pi / 2 apart = uniform_partition ( a_offset , a_offset + 2 * np . pi * 366. / 360. , 366 ) # TODO : Find exact value , determined experimentally d_offset = 0.35 dpart = uniform_partition ( d_offset - 60 , d_offset + 60 , 2240 ) geometry = FanBeamGeo...
def get_user_ride_history ( self , start_time , end_time , limit = None ) : """Get activity about the user ' s lifetime activity with Lyft . Parameters start _ time ( datetime ) Restrict to rides starting after this point in time . The earliest supported date is 2015-01-01T00:00:00Z end _ time ( datetime ...
args = { 'start_time' : start_time , 'end_time' : end_time , 'limit' : limit , } return self . _api_call ( 'GET' , 'v1/rides' , args = args )
def check_nodes_count ( baremetal_client , stack , parameters , defaults ) : """Check if there are enough available nodes for creating / scaling stack"""
count = 0 if stack : for param in defaults : try : current = int ( stack . parameters [ param ] ) except KeyError : raise ValueError ( "Parameter '%s' was not found in existing stack" % param ) count += parameters . get ( param , current ) else : for param , defau...
def init_app ( self , app , entry_point_group = None , register_blueprint = True , register_config_blueprint = None ) : """Flask application initialization . : param app : The Flask application . : param entry _ point _ group : The group entry point to load extensions . ( Default : ` ` invenio _ jsonschemas ....
self . init_config ( app ) if not entry_point_group : entry_point_group = self . kwargs [ 'entry_point_group' ] if 'entry_point_group' in self . kwargs else 'invenio_jsonschemas.schemas' state = InvenioJSONSchemasState ( app ) # Load the json - schemas from extension points . if entry_point_group : for base_ent...
def GetArtifactKnowledgeBase ( client_obj , allow_uninitialized = False ) : """This generates an artifact knowledge base from a GRR client . Args : client _ obj : A GRRClient object which is opened for reading . allow _ uninitialized : If True we accept an uninitialized knowledge _ base . Returns : A Know...
client_schema = client_obj . Schema kb = client_obj . Get ( client_schema . KNOWLEDGE_BASE ) if not allow_uninitialized : if not kb : raise artifact_utils . KnowledgeBaseUninitializedError ( "KnowledgeBase empty for %s." % client_obj . urn ) if not kb . os : raise artifact_utils . KnowledgeBaseA...
def parse_rake ( strike , dip , rake ) : """Parses strings of strike , dip , and rake and returns a strike , dip , and rake measurement following the right - hand - rule , with the " end " of the strike that the rake is measured from indicated by the sign of the rake ( positive rakes correspond to the strike ...
strike , dip = parse_strike_dip ( strike , dip ) rake , direction = split_trailing_letters ( rake ) if direction is not None : if opposite_end ( strike , direction ) : rake = - rake if rake < 0 : rake += 180 elif rake > 180 : rake -= 180 return strike , dip , rake
def _mask ( self , tensor , length , padding_value = 0 ) : """Set padding elements of a batch of sequences to a constant . Useful for setting padding elements to zero before summing along the time dimension , or for preventing infinite results in padding elements . Args : tensor : Tensor of sequences . le...
with tf . name_scope ( 'mask' ) : range_ = tf . range ( tensor . shape [ 1 ] . value ) mask = range_ [ None , : ] < length [ : , None ] if tensor . shape . ndims > 2 : for _ in range ( tensor . shape . ndims - 2 ) : mask = mask [ ... , None ] mask = tf . tile ( mask , [ 1 , 1 ] +...
def MI_createInstance ( self , env , instance ) : # pylint : disable = invalid - name """Create a CIM instance , and return its instance name Implements the WBEM operation CreateInstance in terms of the set _ instance method . A derived class will not normally override this method ."""
logger = env . get_logger ( ) logger . log_debug ( 'CIMProvider MI_createInstance called...' ) rval = None ch = env . get_cimom_handle ( ) cimClass = ch . GetClass ( instance . classname , instance . path . namespace , LocalOnly = False , IncludeQualifiers = True ) # CIMOM has already filled in default property values ...
def score_intersect ( self , term1 , term2 , ** kwargs ) : """Compute the geometric area of the overlap between the kernel density estimates of two terms . Args : term1 ( str ) term2 ( str ) Returns : float"""
t1_kde = self . kde ( term1 , ** kwargs ) t2_kde = self . kde ( term2 , ** kwargs ) # Integrate the overlap . overlap = np . minimum ( t1_kde , t2_kde ) return np . trapz ( overlap )
def getRowByIndex ( self , index ) : """Get row by numeric index . Args : index : Zero - based index of the row to get . Returns : The corresponding row ."""
assert isinstance ( index , int ) return Row ( self . _impl . getRowByIndex ( index ) )
def get_templates_per_page ( self , per_page = 1000 , page = 1 , params = None ) : """Get templates per page : param per _ page : How many objects per page . Default : 1000 : param page : Which page . Default : 1 : param params : Search parameters . Default : { } : return : list"""
return self . _get_resource_per_page ( resource = TEMPLATES , per_page = per_page , page = page , params = params )
def tx_extract ( payload , senders , inputs , outputs , block_id , vtxindex , txid ) : """Extract and return a dict of fields from the underlying blockchain transaction data that are useful to this operation . Required ( + parse ) : sender : the script _ pubkey ( as a hex string ) of the principal that sent t...
sender_script = None sender_address = None sender_pubkey_hex = None recipient = None recipient_address = None burn_address = None op_fee = None op = NAME_REGISTRATION opcode = 'NAME_REGISTRATION' try : # first 2 outputs matter ( op _ return , owner addr ) assert check_tx_output_types ( outputs [ : 2 ] , block_id ) ...
def _get_anchor ( repo , id_prefix ) : """Get an anchor by ID , or a prefix of its id ."""
result = None for anchor_id , anchor in repo . items ( ) : if anchor_id . startswith ( id_prefix ) : if result is not None : raise ExitError ( ExitCode . DATA_ERR , 'Ambiguous ID specification' ) result = ( anchor_id , anchor ) if result is None : raise ExitError ( ExitCode . DATA_ER...
def _stream_search ( self , query ) : """Helper method for iterating over Solr search results ."""
for doc in self . solr . search ( query , rows = 100000000 ) : if self . unique_key != "_id" : doc [ "_id" ] = doc . pop ( self . unique_key ) yield doc
def extra ( self , ** kw ) : """Return a new S instance with extra args combined with existing set ."""
new = self . _clone ( ) actions = [ 'values_list' , 'values_dict' , 'order_by' , 'query' , 'filter' , 'facet' ] for key , vals in kw . items ( ) : assert key in actions if hasattr ( vals , 'items' ) : new . steps . append ( ( key , vals . items ( ) ) ) else : new . steps . append ( ( key , v...
def disconnect ( self , frame ) : """Handles the DISCONNECT command : Unbinds the connection . Clients are supposed to send this command , but in practice it should not be relied upon ."""
self . engine . log . debug ( "Disconnect" ) self . engine . unbind ( )
def getbit ( self , key , offset ) : """Returns the bit value at offset in the string value stored at key . : raises TypeError : if offset is not int : raises ValueError : if offset is less than 0"""
if not isinstance ( offset , int ) : raise TypeError ( "offset argument must be int" ) if offset < 0 : raise ValueError ( "offset must be greater equal 0" ) return self . execute ( b'GETBIT' , key , offset )
def command_canonize ( string , vargs ) : """Print the canonical representation of the given string . It will replace non - canonical compound characters with their canonical synonym . : param str string : the string to act upon : param dict vargs : the command line arguments"""
try : ipa_string = IPAString ( unicode_string = string , ignore = vargs [ "ignore" ] , single_char_parsing = vargs [ "single_char_parsing" ] ) print ( vargs [ "separator" ] . join ( [ ( u"%s" % c ) for c in ipa_string ] ) ) except ValueError as exc : print_error ( str ( exc ) )
def tab_complete ( self ) : """If there is a single option available one tab completes the option ."""
opts = self . _complete_options ( ) if len ( opts ) == 1 : self . set_current_text ( opts [ 0 ] + os . sep ) self . hide_completer ( )
def get_credentials ( * , scopes ) : """Gets valid user credentials from storage . If nothing has been stored , or if the stored credentials are invalid , the OAuth2 flow is completed to obtain the new credentials . Returns : Credentials , the obtained credential ."""
credential_dir = os . path . join ( HOME_DIR , ".cache" , __package__ , "credentials" ) if not os . path . exists ( credential_dir ) : os . makedirs ( credential_dir ) credential_path = os . path . join ( credential_dir , "googleapis.json" ) store = Storage ( credential_path ) credentials = store . get ( ) # see ht...
def normalize_select ( query ) : """If the query contains the : select operator , we enforce : sys properties . The SDK requires sys . type to function properly , but as other of our SDKs require more parts of the : sys properties , we decided that every SDK should include the complete : sys block to provide ...
if 'select' not in query : return if isinstance ( query [ 'select' ] , str_type ( ) ) : query [ 'select' ] = [ s . strip ( ) for s in query [ 'select' ] . split ( ',' ) ] query [ 'select' ] = [ s for s in query [ 'select' ] if not s . startswith ( 'sys.' ) ] if 'sys' not in query [ 'select' ] : query [ 'sel...
def attribute_is_visible ( self , permission ) : """Checks privacy options to see if an attribute is visible to public"""
try : parent = getattr ( self , "parent_{}" . format ( permission ) ) student = getattr ( self , "self_{}" . format ( permission ) ) return ( parent and student ) or ( self . is_http_request_sender ( ) or self . _current_user_override ( ) ) except Exception : logger . error ( "Could not retrieve permiss...
def _generateForTokenSecurity ( self , username , password , referer = None , tokenUrl = None , expiration = None , proxy_url = None , proxy_port = None ) : """generates a token for a feature service"""
if referer is None : referer = self . _referer_url if tokenUrl is None : tokenUrl = self . _token_url query_dict = { 'username' : self . _username , 'password' : self . _password , 'expiration' : str ( _defaultTokenExpiration ) , 'referer' : referer , 'f' : 'json' } if expiration is not None : query_dict [ ...
def dihedral ( array_of_xyzs ) : """Calculates dihedral angle between four coordinate points . Used for dihedral constraints ."""
p1 = array_of_xyzs [ 0 ] p2 = array_of_xyzs [ 1 ] p3 = array_of_xyzs [ 2 ] p4 = array_of_xyzs [ 3 ] vector1 = - 1.0 * ( p2 - p1 ) vector2 = p3 - p2 vector3 = p4 - p3 # Normalize vector so as not to influence magnitude of vector # rejections vector2 /= np . linalg . norm ( vector2 ) # Vector rejections : # v = projectio...
def __save_output ( self ) : """Saves the output into a native OOo document format ."""
out = zipfile . ZipFile ( self . outputfilename , 'w' ) for info_zip in self . infile . infolist ( ) : if info_zip . filename in self . templated_files : # Template file - we have edited these . # get a temp file streamout = open ( get_secure_filename ( ) , "w+b" ) fname , output_stream = self ....
def Reduce ( self ) : """Reduce the token stack into an AST ."""
# Check for sanity if self . state != 'INITIAL' and self . state != 'BINARY' : self . Error ( 'Premature end of expression' ) length = len ( self . stack ) while length > 1 : # Precedence order self . _CombineParenthesis ( ) self . _CombineBinaryExpressions ( 'and' ) self . _CombineBinaryExpressions ( '...
def point_normals ( self ) : """Point normals"""
mesh = self . compute_normals ( cell_normals = False , inplace = False ) return mesh . point_arrays [ 'Normals' ]
def get_comments ( self ) : """Returns the comments for the job , querying the server if necessary ."""
# Lazily load info if self . info is None : self . get_info ( ) if 'comments' in self . info : return [ structure [ 'text' ] for structure in self . info [ 'comments' ] [ 'comments' ] ] else : return [ ]
def AnalyzeClient ( self , client ) : """Finds the client _ id and keywords for a client . Args : client : A Client object record to find keywords for . Returns : A list of keywords related to client ."""
# Start with a universal keyword , used to find all clients . # TODO ( user ) : Remove the universal keyword once we have a better way # to do this , i . e . , once we have a storage library which can list all # clients directly . keywords = set ( [ "." ] ) def TryAppend ( prefix , keyword ) : precondition . Assert...
def on_get ( self , req , resp ) : """Send a GET request to get the list of all of the filter containers"""
resp . content_type = falcon . MEDIA_TEXT resp . status = falcon . HTTP_200 # connect to docker try : containers = docker . from_env ( ) except Exception as e : # pragma : no cover resp . body = "(False, 'unable to connect to docker because: " + str ( e ) + "')" return # search for all docker containers and...
def make_hdu ( self , data , ** kwargs ) : """Builds and returns a FITs HDU with input data data : The data begin stored Keyword arguments extname : The HDU extension name colbase : The prefix for column names"""
shape = data . shape extname = kwargs . get ( 'extname' , self . conv . extname ) if shape [ - 1 ] != self . _npix : raise Exception ( "Size of data array does not match number of pixels" ) cols = [ ] if self . _ipix is not None : cols . append ( fits . Column ( self . conv . idxstring , "J" , array = self . _i...
def calculate_width_widget_int ( width , border = False , margin = None , margin_left = None , margin_right = None ) : """Calculate actual widget content width based on given margins and paddings ."""
if margin_left is None : margin_left = margin if margin_right is None : margin_right = margin if margin_left is not None : width -= int ( margin_left ) if margin_right is not None : width -= int ( margin_right ) if border : width -= 2 return width if width > 0 else None
def strip ( self , data , strip_newlines = False ) : """Strips out any tags from the input text , using the same tokenization as the formatter ."""
text = [ ] for token_type , tag_name , tag_opts , token_text in self . tokenize ( data ) : if token_type == self . TOKEN_DATA : text . append ( token_text ) elif token_type == self . TOKEN_NEWLINE and not strip_newlines : text . append ( token_text ) return '' . join ( text )
def _parse_raster_info ( self , prop = RASTER_INFO ) : """Collapses multiple dimensions into a single raster _ info complex struct"""
raster_info = { } . fromkeys ( _iso_definitions [ prop ] , u'' ) # Ensure conversion of lists to newlines is in place raster_info [ 'dimensions' ] = get_default_for_complex_sub ( prop = prop , subprop = 'dimensions' , value = parse_property ( self . _xml_tree , None , self . _data_map , '_ri_num_dims' ) , xpath = self ...
def load_cfg ( self , src_dir ) : """Load defaults from configuration file : - from the source / directory / . dirsync file ( prioritary ) - and / or a % HOME % / . dirsync user config file"""
# last files override previous ones cfg_files = [ os . path . expanduser ( USER_CFG_FILE ) , os . path . abspath ( os . path . join ( src_dir , '.dirsync' ) ) ] cfg = ConfigParser ( ) cfg . read ( cfg_files ) if not cfg . has_section ( 'defaults' ) : return defaults = { } for name , val in cfg . items ( 'defaults' ...
def serialize ( self ) : """Convert this recorded RPC into a string ."""
return "{},{: <26},{:2d},{:#06x},{:#04x},{:5.0f},{: <40},{: <40},{}" . format ( self . connection , self . start_stamp . isoformat ( ) , self . address , self . rpc_id , self . status , self . runtime * 1000 , self . call , self . response , self . error )
def create_package ( name , data , package_cls = None ) : """Create a package given package data . Args : name ( str ) : Package name . data ( dict ) : Package data . Must conform to ` package _ maker . package _ schema ` . Returns : ` Package ` object ."""
from rez . package_maker__ import PackageMaker maker = PackageMaker ( name , data , package_cls = package_cls ) return maker . get_package ( )
def free_param_bounds ( self ) : """Combined free hyperparameter bounds for the kernel , noise kernel and ( if present ) mean function ."""
fpb = CombinedBounds ( self . k . free_param_bounds , self . noise_k . free_param_bounds ) if self . mu is not None : fpb = CombinedBounds ( fpb , self . mu . free_param_bounds ) return fpb
def _init_az_api ( self ) : """Initialise client objects for talking to Azure API . This is in a separate function so to be called by ` ` _ _ init _ _ ` ` and ` ` _ _ setstate _ _ ` ` ."""
with self . __lock : if self . _resource_client is None : log . debug ( "Making Azure `ServicePrincipalcredentials` object" " with tenant=%r, client_id=%r, secret=%r ..." , self . tenant_id , self . client_id , ( '<redacted>' if self . secret else None ) ) credentials = ServicePrincipalCredentials (...
def partitionBy ( * cols ) : """Creates a : class : ` WindowSpec ` with the partitioning defined ."""
sc = SparkContext . _active_spark_context jspec = sc . _jvm . org . apache . spark . sql . expressions . Window . partitionBy ( _to_java_cols ( cols ) ) return WindowSpec ( jspec )
def read_header ( self ) : """Read the header of a MPQ archive ."""
def read_mpq_header ( offset = None ) : if offset : self . file . seek ( offset ) data = self . file . read ( 32 ) header = MPQFileHeader . _make ( struct . unpack ( MPQFileHeader . struct_format , data ) ) header = header . _asdict ( ) if header [ 'format_version' ] == 1 : data = se...
def parse_geo_box ( geo_box_str ) : """parses [ - 90 , - 180 TO 90,180 ] to a shapely . geometry . box : param geo _ box _ str : : return :"""
from_point_str , to_point_str = parse_solr_geo_range_as_pair ( geo_box_str ) from_point = parse_lat_lon ( from_point_str ) to_point = parse_lat_lon ( to_point_str ) rectangle = box ( from_point [ 0 ] , from_point [ 1 ] , to_point [ 0 ] , to_point [ 1 ] ) return rectangle
def plot ( self , ax = None , ** kwargs ) : """Plot the histogram with matplotlib , returns ` matplotlib ` figure ."""
ax , fig , plt = get_ax_fig_plt ( ax ) yy = [ len ( v ) for v in self . values ] ax . plot ( self . binvals , yy , ** kwargs ) return fig
def parse_config_files ( self , filenames = None , ignore_option_errors = False ) : """Parses configuration files from various levels and loads configuration ."""
self . _parse_config_files ( filenames = filenames ) parse_configuration ( self , self . command_options , ignore_option_errors = ignore_option_errors ) self . _finalize_requires ( )
def hmset ( key , ** fieldsvals ) : '''Sets multiple hash fields to multiple values . . . versionadded : : 2017.7.0 CLI Example : . . code - block : : bash salt ' * ' redis . hmset foo _ hash bar _ field1 = bar _ value1 bar _ field2 = bar _ value2'''
host = fieldsvals . pop ( 'host' , None ) port = fieldsvals . pop ( 'port' , None ) database = fieldsvals . pop ( 'db' , None ) password = fieldsvals . pop ( 'password' , None ) server = _connect ( host , port , database , password ) return server . hmset ( key , salt . utils . args . clean_kwargs ( ** fieldsvals ) )
def set_locked_variable ( self , key , access_key , value ) : """Set an already locked global variable : param key : the key of the global variable to be set : param access _ key : the access key to the already locked global variable : param value : the new value of the global variable"""
return self . set_variable ( key , value , per_reference = False , access_key = access_key )
def print_error ( self , wrapper ) : """A crude way of output the errors for now . This needs to be cleaned up into something better ."""
level = 0 parent = wrapper . parent while parent : print_test_msg ( parent . name , level , TestStatus . FAIL , self . use_color ) level += 1 parent = parent . parent print_test_msg ( wrapper . name , level , TestStatus . FAIL , self . use_color ) print_test_args ( wrapper . execute_kwargs , level , TestSta...
def merge_templates ( self , replacements , separator ) : """Duplicate template . Creates a copy of the template , does a merge , and separates them by a new paragraph , a new break or a new section break . separator must be : - page _ break : Page Break . - column _ break : Column Break . ONLY HAVE EFFECT IF...
# TYPE PARAM CONTROL AND SPLIT valid_separators = { 'page_break' , 'column_break' , 'textWrapping_break' , 'continuous_section' , 'evenPage_section' , 'nextColumn_section' , 'nextPage_section' , 'oddPage_section' } if not separator in valid_separators : raise ValueError ( "Invalid separator argument" ) type , sepCl...
def output_deployment_status ( awsclient , deployment_id , iterations = 100 ) : """Wait until an deployment is in an steady state and output information . : param deployment _ id : : param iterations : : return : exit _ code"""
counter = 0 steady_states = [ 'Succeeded' , 'Failed' , 'Stopped' ] client_codedeploy = awsclient . get_client ( 'codedeploy' ) while counter <= iterations : response = client_codedeploy . get_deployment ( deploymentId = deployment_id ) status = response [ 'deploymentInfo' ] [ 'status' ] if status not in ste...
def p_arguments ( p ) : """arguments : argumentlist | argumentlist test | argumentlist ' ( ' testlist ' ) '"""
p [ 0 ] = { 'args' : p [ 1 ] , } if len ( p ) > 2 : if p [ 2 ] == '(' : p [ 0 ] [ 'tests' ] = p [ 3 ] else : p [ 0 ] [ 'tests' ] = [ p [ 2 ] ]
def calc_intsize ( self ) : """Calculates the size of an integration ( cross + auto ) in bytes"""
# assume first cross blob starts after headxml and second is one int of bytes later for k in self . binarychunks . iterkeys ( ) : if int ( k . split ( '/' ) [ 3 ] ) == 1 and 'cross' in k . split ( '/' ) [ - 1 ] : headsize = self . binarychunks [ k ] break for k in self . binarychunks . iterkeys ( ) ...
def right ( self ) : """Right coordinate ."""
if self . _has_real ( ) : return self . _data . real_right return self . _data . right
def _init_map ( self , record_types = None , ** kwargs ) : """Initialize form map"""
osid_objects . OsidObjectForm . _init_map ( self , record_types = record_types ) self . _my_map [ 'assessmentOfferedId' ] = str ( kwargs [ 'assessment_offered_id' ] ) self . _my_map [ 'takerId' ] = self . _taker_default self . _my_map [ 'assignedBankIds' ] = [ str ( kwargs [ 'bank_id' ] ) ] self . _my_map [ 'actualStar...
def config_wdl ( args ) : """Retrieve the WDL for a method config in a workspace , send stdout"""
r = fapi . get_workspace_config ( args . project , args . workspace , args . namespace , args . config ) fapi . _check_response_code ( r , 200 ) method = r . json ( ) [ "methodRepoMethod" ] args . namespace = method [ "methodNamespace" ] args . method = method [ "methodName" ] args . snapshot_id = method [ "methodVersi...
def load_xml_db ( self ) : """Load the Lutron database from the server ."""
import urllib . request xmlfile = urllib . request . urlopen ( 'http://' + self . _host + '/DbXmlInfo.xml' ) xml_db = xmlfile . read ( ) xmlfile . close ( ) _LOGGER . info ( "Loaded xml db" ) parser = LutronXmlDbParser ( lutron = self , xml_db_str = xml_db ) assert ( parser . parse ( ) ) # throw our own exception self ...
def _to_tuple ( bbox ) : """Converts the input bbox representation ( see the constructor docstring for a list of valid representations ) into a flat tuple : param bbox : A bbox in one of 7 forms listed in the class description . : return : A flat tuple of size : raises : TypeError"""
if isinstance ( bbox , ( list , tuple ) ) : return BBox . _tuple_from_list_or_tuple ( bbox ) if isinstance ( bbox , str ) : return BBox . _tuple_from_str ( bbox ) if isinstance ( bbox , dict ) : return BBox . _tuple_from_dict ( bbox ) if isinstance ( bbox , BBox ) : return BBox . _tuple_from_bbox ( bbox...
def parse_config_file ( config_file_path ) : """Parse a configuration file . Currently only supports . json , . py and properties separated by ' = ' : param config _ file _ path : : return : a dict of the configuration properties"""
extension = os . path . splitext ( config_file_path ) [ 1 ] if extension == '.pyc' : raise ValueError ( "Skipping .pyc file as config" ) if extension == '.json' : with open ( config_file_path ) as config_file : try : mapping = json . load ( config_file ) except ValueError as e : ...
def check_file ( filename , ** kwargs ) : """Perform static analysis on the given file . . . seealso : : - : data : ` . SUPPORTED _ FILES ` - : func : ` . check _ pep8 ` - : func : ` . check _ pydocstyle ` - and : func : ` . check _ license ` : param filename : path of file to check . : type filename ...
excludes = kwargs . get ( "excludes" , [ ] ) errors = [ ] if is_file_excluded ( filename , excludes ) : return None if filename . endswith ( ".py" ) : if kwargs . get ( "pep8" , True ) : errors += check_pep8 ( filename , ** kwargs ) if kwargs . get ( "pydocstyle" , True ) : errors += check_p...
def _buffered_generation_process ( source_gen , buffer_ , sentinal ) : """helper for buffered _ generator"""
for data in source_gen : buffer_ . put ( data , block = True ) # sentinel : signal the end of the iterator buffer_ . put ( sentinal ) # unfortunately this does not suffice as a signal : if buffer _ . get ( ) was # called and subsequently the buffer _ is closed , it will block forever . buffer_ . close ( )
def is_datetimelike_v_object ( a , b ) : """Check if we are comparing a datetime - like object to an object instance . Parameters a : array - like , scalar The first object to check . b : array - like , scalar The second object to check . Returns boolean Whether we return a comparing a datetime - li...
if not hasattr ( a , 'dtype' ) : a = np . asarray ( a ) if not hasattr ( b , 'dtype' ) : b = np . asarray ( b ) is_datetimelike = needs_i8_conversion return ( ( is_datetimelike ( a ) and is_object_dtype ( b ) ) or ( is_datetimelike ( b ) and is_object_dtype ( a ) ) )
def mailto ( to , cc = None , bcc = None , subject = None , body = None ) : """Generate and run mailto . : type to : string : param to : The recipient email address . : type cc : string : param cc : The recipient to copy to . : type bcc : string : param bcc : The recipient to blind copy to . : type su...
mailurl = 'mailto:' + str ( to ) if cc is None and bcc is None and subject is None and body is None : return str ( mailurl ) mailurl += '?' if cc is not None : mailurl += 'cc=' + str ( cc ) added = True added = False if bcc is not None : if added is True : mailurl += '&' mailurl += 'bcc=' + ...
def subkey_public_pair_chain_code_pair ( generator , public_pair , chain_code_bytes , i ) : """Yield info for a child node for this node . generator : the ecdsa generator public _ pair : base public pair chain _ code : base chain code the index for this node . Returns a pair ( new _ public _ pair , ...
INFINITY = generator . infinity ( ) ORDER = generator . order ( ) i_as_bytes = struct . pack ( ">l" , i ) sec = public_pair_to_sec ( public_pair , compressed = True ) data = sec + i_as_bytes I64 = hmac . HMAC ( key = chain_code_bytes , msg = data , digestmod = hashlib . sha512 ) . digest ( ) I_left_as_exponent = from_b...
def get_simple_dirs ( self , simple_dir : Path ) -> List [ Path ] : """Return a list of simple index directories that should be searched for package indexes when compiling the main index page ."""
if self . hash_index : # We are using index page directory hashing , so the directory # format is / simple / f / foo / . We want to return a list of dirs # like " simple / f " . subdirs = [ simple_dir / x for x in simple_dir . iterdir ( ) if x . is_dir ( ) ] else : # This is the traditional layout of / simple / foo...
def decode_file_iter ( file_obj , codec_options = DEFAULT_CODEC_OPTIONS ) : """Decode bson data from a file to multiple documents as a generator . Works similarly to the decode _ all function , but reads from the file object in chunks and parses bson in chunks , yielding one document at a time . : Parameters ...
while True : # Read size of next object . size_data = file_obj . read ( 4 ) if len ( size_data ) == 0 : break # Finished with file normaly . elif len ( size_data ) != 4 : raise InvalidBSON ( "cut off in middle of objsize" ) obj_size = _UNPACK_INT ( size_data ) [ 0 ] - 4 eleme...
def get_sentences ( corpus ) : '''Parameters corpus , ParsedCorpus Returns iter : [ sentence1word1 , . . . ] , [ sentence2word1 , . . . ]'''
assert isinstance ( corpus , ParsedCorpus ) return itertools . chain ( * [ [ [ corpus . _term_idx_store . getidxstrict ( t . lower_ ) for t in sent if not t . is_punct ] for sent in doc . sents ] for doc in corpus . get_parsed_docs ( ) ] )
def interp_values ( mass_arr , age_arr , feh_arr , icol , grid , mass_col , ages , fehs , grid_Ns ) : """mass _ arr , age _ arr , feh _ arr are all arrays at which values are desired icol is the column index of desired value grid is nfeh x nage x max ( nmass ) x ncols array mass _ col is the column index of m...
N = len ( mass_arr ) results = np . zeros ( N ) Nage = len ( ages ) Nfeh = len ( fehs ) for i in range ( N ) : mass = mass_arr [ i ] age = age_arr [ i ] feh = feh_arr [ i ] ifeh = searchsorted ( fehs , Nfeh , feh ) iage = searchsorted ( ages , Nage , age ) pts = np . zeros ( ( 8 , 3 ) ) vals...
def get_is_value ( tag ) : """Getters for data that also work with implicit transfersyntax : param tag : the tag to read"""
# data is int formatted as string so convert te string first and cast to int if tag . VR == 'OB' or tag . VR == 'UN' : value = int ( tag . value . decode ( "ascii" ) . replace ( " " , "" ) ) return value return int ( tag . value )
def bold ( * content , sep = ' ' ) : """Make bold text ( Markdown ) : param content : : param sep : : return :"""
return _md ( _join ( * content , sep = sep ) , symbols = MD_SYMBOLS [ 0 ] )
def lscmp ( a , b ) : """Compares two strings in a cryptographically safe way : Runtime is not affected by length of common prefix , so this is helpful against timing attacks . from vital . security import lscmp lscmp ( " ringo " , " starr " ) # - > False lscmp ( " ringo " , " ringo " ) # - > True"""
l = len return not sum ( 0 if x == y else 1 for x , y in zip ( a , b ) ) and l ( a ) == l ( b )