signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def parse_table_data ( lines ) : """" Parse list of lines from SOFT file into DataFrame . Args : lines ( : obj : ` Iterable ` ) : Iterator over the lines . Returns : : obj : ` pandas . DataFrame ` : Table data ."""
# filter lines that do not start with symbols data = "\n" . join ( [ i . rstrip ( ) for i in lines if not i . startswith ( ( "^" , "!" , "#" ) ) and i . rstrip ( ) ] ) if data : return read_csv ( StringIO ( data ) , index_col = None , sep = "\t" ) else : return DataFrame ( )
def remove ( self , * args ) : '''cplan . remove ( . . . ) yields a new calculation plan identical to cplan except without any of the calculation steps listed in the arguments . An exception is raised if any keys are not found in the calc - plan .'''
return Plan ( reduce ( lambda m , k : m . remove ( k ) , args , self . nodes ) )
def do_some_work ( self , work_dict ) : """do _ some _ work : param work _ dict : dictionary for key / values"""
label = "do_some_work" log . info ( ( "task - {} - start " "work_dict={}" ) . format ( label , work_dict ) ) ret_data = { "job_results" : ( "some response key={}" ) . format ( str ( uuid . uuid4 ( ) ) ) } log . info ( ( "task - {} - result={} done" ) . format ( ret_data , label ) ) return ret_data
def create ( self ) : """Create a single instance of notebook ."""
# Point to chart repo . out = helm ( "repo" , "add" , "jupyterhub" , self . helm_repo ) out = helm ( "repo" , "update" ) # Get token to secure Jupyterhub secret_yaml = self . get_security_yaml ( ) # Get Jupyterhub . out = helm ( "upgrade" , "--install" , self . release , "jupyterhub/jupyterhub" , namespace = self . nam...
def run ( self , * , connector : Union [ EnvVar , Token , SlackClient , None ] = None , interval : float = 0.5 , retries : int = 16 , backoff : Callable [ [ int ] , float ] = None , until : Callable [ [ List [ dict ] ] , bool ] = None ) -> None : """Connect to the Slack API and run the event handler loop . Args :...
backoff = backoff or _truncated_exponential until = until or _forever self . _ensure_slack ( connector = connector , retries = retries , backoff = backoff ) assert self . _slack is not None while True : events = self . _slack . fetch_events ( ) if not until ( events ) : log . debug ( 'Exiting event loop...
def insert ( self , index , child , by_name_index = - 1 ) : """Add the child at the given index : type index : ` ` int ` ` : param index : child position : type child : : class : ` Element < hl7apy . core . Element > ` : param child : an instance of an : class : ` Element < hl7apy . core . Element > ` subcl...
if self . _can_add_child ( child ) : try : if by_name_index == - 1 : self . indexes [ child . name ] . append ( child ) else : self . indexes [ child . name ] . insert ( by_name_index , child ) except KeyError : self . indexes [ child . name ] = [ child ] self...
def GET_savedgetitemvalues ( self ) -> None : """Get the previously saved values of all | GetItem | objects ."""
dict_ = state . getitemvalues . get ( self . _id ) if dict_ is None : self . GET_getitemvalues ( ) else : for name , value in dict_ . items ( ) : self . _outputs [ name ] = value
def _get_handshake_headers ( self , upgrade ) : """Do an HTTP upgrade handshake with the server . Websockets upgrade from HTTP rather than TCP largely because it was assumed that servers which provide websockets will always be talking to a browser . Maybe a reasonable assumption once upon a time . . . The h...
headers = [ ] # https : / / tools . ietf . org / html / rfc6455 headers . append ( "GET {} HTTP/1.1" . format ( self . websocket_location ) ) headers . append ( "Host: {}:{}" . format ( self . host , self . port ) ) headers . append ( "Upgrade: websocket" ) headers . append ( "Connection: Upgrade" ) # Sec - WebSocket -...
def to_irc ( self ) -> int : """Convert to mIRC color Code : return : IRC color code"""
d = { ( self . BLACK , True ) : 14 , ( self . BLACK , False ) : 1 , ( self . RED , True ) : 4 , ( self . RED , False ) : 5 , ( self . GREEN , True ) : 9 , ( self . GREEN , False ) : 3 , ( self . YELLOW , True ) : 8 , ( self . YELLOW , False ) : 7 , ( self . BLUE , True ) : 12 , ( self . BLUE , False ) : 2 , ( self . MA...
def send ( self , request : Request ) -> None : """Dispatches a request . Expects one and one only target handler : param request : The request to dispatch : return : None , will throw a ConfigurationException if more than one handler factor is registered for the command"""
handler_factories = self . _registry . lookup ( request ) if len ( handler_factories ) != 1 : raise ConfigurationException ( "There is no handler registered for this request" ) handler = handler_factories [ 0 ] ( ) handler . handle ( request )
def get_tiny_position ( self , symbol , acc_id = 0 ) : """得到股票持仓"""
ret , data = self . _trade_ctx . position_list_query ( code = symbol , trd_env = self . _env_type , acc_id = acc_id ) if 0 != ret : return None for _ , row in data . iterrows ( ) : if row [ 'code' ] != symbol : continue pos = TinyPosition ( ) pos . symbol = symbol pos . position = row [ 'qty...
def OnRemoveCards ( self , removedcards ) : """Called when a card is removed . Removes the card from the tree ."""
self . mutex . acquire ( ) try : parentnode = self . root for cardtoremove in removedcards : ( childReader , cookie ) = self . GetFirstChild ( parentnode ) found = False while childReader . IsOk ( ) and not found : if self . GetItemText ( childReader ) == str ( cardtoremove ....
def publish ( self ) : '''Function to publish cmdvel .'''
# print ( self ) # self . using _ event . wait ( ) self . lock . acquire ( ) msg = cmdvel2PosTarget ( self . vel ) self . lock . release ( ) self . pub . publish ( msg )
def _run_funnel ( args ) : """Run funnel TES server with rabix bunny for CWL ."""
host = "localhost" port = "8088" main_file , json_file , project_name = _get_main_and_json ( args . directory ) work_dir = utils . safe_makedir ( os . path . join ( os . getcwd ( ) , "funnel_work" ) ) log_file = os . path . join ( work_dir , "%s-funnel.log" % project_name ) # Create bunny configuration directory with T...
def get_federation_token ( self , name , duration = None , policy = None ) : """: type name : str : param name : The name of the Federated user associated with the credentials . : type duration : int : param duration : The number of seconds the credentials should remain valid . : type policy : str : p...
params = { 'Name' : name } if duration : params [ 'DurationSeconds' ] = duration if policy : params [ 'Policy' ] = policy return self . get_object ( 'GetFederationToken' , params , FederationToken , verb = 'POST' )
def approve ( self , sha = None , ** kwargs ) : """Approve the merge request . Args : sha ( str ) : Head SHA of MR * * kwargs : Extra options to send to the server ( e . g . sudo ) Raises : GitlabAuthenticationError : If authentication is not correct GitlabMRApprovalError : If the approval failed"""
path = '%s/%s/approve' % ( self . manager . path , self . get_id ( ) ) data = { } if sha : data [ 'sha' ] = sha server_data = self . manager . gitlab . http_post ( path , post_data = data , ** kwargs ) self . _update_attrs ( server_data )
def get_list_subtask_positions_objs ( client , list_id ) : '''Gets all subtask positions objects for the tasks within a given list . This is a convenience method so you don ' t have to get all the list ' s tasks before getting subtasks , though I can ' t fathom how mass subtask reordering is useful . Returns : ...
params = { 'list_id' : int ( list_id ) } response = client . authenticated_request ( client . api . Endpoints . SUBTASK_POSITIONS , params = params ) return response . json ( )
def get ( self , identity ) : """Constructs a EntityContext : param identity : Unique identity of the Entity : returns : twilio . rest . authy . v1 . service . entity . EntityContext : rtype : twilio . rest . authy . v1 . service . entity . EntityContext"""
return EntityContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , identity = identity , )
def _parse_mtllibs ( self ) : """Load mtl files"""
for mtllib in self . meta . mtllibs : try : materials = self . material_parser_cls ( os . path . join ( self . path , mtllib ) , encoding = self . encoding , strict = self . strict ) . materials except IOError : raise IOError ( "Failed to load mtl file:" . format ( os . path . join ( self . path...
def region_option ( f ) : """Configures - - region option for CLI : param f : Callback Function to be passed to Click"""
def callback ( ctx , param , value ) : state = ctx . ensure_object ( Context ) state . region = value return value return click . option ( '--region' , expose_value = False , help = 'Set the AWS Region of the service (e.g. us-east-1).' , callback = callback ) ( f )
def make_date ( dt , date_parser = parse_date ) : """Coerce a datetime or string into datetime . date object Arguments : dt ( str or datetime . datetime or atetime . time or numpy . Timestamp ) : time or date to be coerced into a ` datetime . time ` object Returns : datetime . time : Time of day portion o...
if not dt : return datetime . date ( 1970 , 1 , 1 ) if isinstance ( dt , basestring ) : dt = date_parser ( dt ) try : dt = dt . timetuple ( ) [ : 3 ] except : dt = tuple ( dt ) [ : 3 ] return datetime . date ( * dt )
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'grammars' ) and self . grammars is not None : _dict [ 'grammars' ] = [ x . _to_dict ( ) for x in self . grammars ] return _dict
def close ( self ) : """Clean up files that were created ."""
if self . file : self . file . close ( ) self . file = None # If temp _ file is a folder , we do not remove it because we may # still need it after the unpickler is disposed if self . tmp_file and _os . path . isfile ( self . tmp_file ) : _os . remove ( self . tmp_file ) self . tmp_file = None
def sort_run ( run ) : """Sort function for runs within a release ."""
# Sort errors first , then by name . Also show errors that were manually # approved , so the paging sort order stays the same even after users # approve a diff on the run page . if run . status in models . Run . DIFF_NEEDED_STATES : return ( 0 , run . name ) return ( 1 , run . name )
def instance ( self , name = None , * args , ** kwargs ) : """Create a new instance using key ` ` name ` ` . : param name : the name of the class ( by default ) or the key name of the class used to find the class : param args : given to the ` ` _ _ init _ _ ` ` method : param kwargs : given to the ` ` _ _ i...
logger . info ( f'new instance of {name}' ) t0 = time ( ) name = self . default_name if name is None else name logger . debug ( f'creating instance of {name}' ) class_name , params = self . _class_name_params ( name ) cls = self . _find_class ( class_name ) params . update ( kwargs ) if self . _has_init_config ( cls ) ...
def _readfloatle ( self , length , start ) : """Read bits and interpret as a little - endian float ."""
startbyte , offset = divmod ( start + self . _offset , 8 ) if not offset : if length == 32 : f , = struct . unpack ( '<f' , bytes ( self . _datastore . getbyteslice ( startbyte , startbyte + 4 ) ) ) elif length == 64 : f , = struct . unpack ( '<d' , bytes ( self . _datastore . getbyteslice ( sta...
def calc_shape_statistics ( self , stat_names ) : """Calculate shape statistics using regionprops applied to the object mask . Args : stat _ names : List of statistics to be extracted from those calculated by regionprops . Returns : Dictionary of shape statistics"""
stats = { } try : all_props = [ regionprops ( m ) for m in self . masks ] except TypeError : print ( self . masks ) exit ( ) for stat in stat_names : stats [ stat ] = np . mean ( [ p [ 0 ] [ stat ] for p in all_props ] ) return stats
def validate ( config ) : '''Validate the beacon configuration'''
if not isinstance ( config , list ) : return False , ( 'Configuration for haproxy beacon must ' 'be a list.' ) else : _config = { } list ( map ( _config . update , config ) ) if 'backends' not in _config : return False , ( 'Configuration for haproxy beacon ' 'requires backends.' ) else : ...
def get_dir_relpath ( base , relpath ) : """Returns the absolute path to the ' relpath ' taken relative to the base directory . : arg base : the base directory to take the path relative to . : arg relpath : the path relative to ' base ' in terms of ' . ' and ' . . ' ."""
from os import path xbase = path . abspath ( path . expanduser ( base ) ) if not path . isdir ( xbase ) : return path . join ( xbase , relpath ) if relpath [ 0 : 2 ] == "./" : return path . join ( xbase , relpath [ 2 : : ] ) else : from os import chdir , getcwd cd = getcwd ( ) chdir ( xbase ) re...
def get_solution ( self , parameters = None ) : """stub"""
if not self . has_solution ( ) : raise IllegalState ( ) try : if not self . get_text ( 'python_script' ) : return self . get_text ( 'solution' ) . text if not parameters : parameters = self . get_parameters ( ) return self . _get_parameterized_text ( parameters ) except Exception : r...
def __copy_static ( self , template , output_path ) : """This method takes the files in css and js folders of the template and copy to final folders"""
self . path_static = os . path . join ( template , "static" , "css" ) for file in os . listdir ( self . path_static ) : print ( file ) shutil . copyfile ( os . path . join ( template , "static" , "css" , file ) , os . path . join ( output_path , "output" , self . name , "site" , "static" , "css" , file ) ) self...
def get_instance ( self , payload ) : """Build an instance of IpAddressInstance : param dict payload : Payload response from the API : returns : twilio . rest . api . v2010 . account . sip . ip _ access _ control _ list . ip _ address . IpAddressInstance : rtype : twilio . rest . api . v2010 . account . sip ....
return IpAddressInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , ip_access_control_list_sid = self . _solution [ 'ip_access_control_list_sid' ] , )
def name ( self ) : """Compute a name according to sub meta results names > > > gres = PlayMeta ( " operation " ) > > > res _ plus = BasicPlayMeta ( Composable ( name = " plus " ) ) > > > res _ moins = BasicPlayMeta ( Composable ( name = " moins " ) ) > > > gres . append ( res _ plus ) > > > gres . append...
return "%s:[%s]" % ( self . _name , ", " . join ( meta . name for meta in self . _metas ) )
def get_catalogs ( self ) : """Pass through to provider CatalogLookupSession . get _ catalogs"""
# Implemented from kitosid template for - # osid . resource . BinLookupSession . get _ bins _ template catalogs = self . _get_provider_session ( 'catalog_lookup_session' ) . get_catalogs ( ) cat_list = [ ] for cat in catalogs : cat_list . append ( Catalog ( self . _provider_manager , cat , self . _runtime , self . ...
def symlink_list ( saltenv = 'base' , backend = None ) : '''Return a list of symlinked files and dirs saltenv : base The salt fileserver environment to be listed backend Narrow fileserver backends to a subset of the enabled ones . If all passed backends start with a minus sign ( ` ` - ` ` ) , then these b...
fileserver = salt . fileserver . Fileserver ( __opts__ ) load = { 'saltenv' : saltenv , 'fsbackend' : backend } return fileserver . symlink_list ( load = load )
def where ( self , ** overrides ) : """Creates a new route , based on the current route , with the specified overrided values"""
route_data = self . route . copy ( ) route_data . update ( overrides ) return self . __class__ ( ** route_data )
def insert_fft_options ( optgroup ) : """Inserts the options that affect the behavior of this backend Parameters optgroup : fft _ option OptionParser argument group whose options are extended"""
optgroup . add_argument ( "--fftw-measure-level" , help = "Determines the measure level used in planning " "FFTW FFTs; allowed values are: " + str ( [ 0 , 1 , 2 , 3 ] ) , type = int , default = _default_measurelvl ) optgroup . add_argument ( "--fftw-threads-backend" , help = "Give 'openmp', 'pthreads' or 'unthreaded' t...
def sales_for_time_period ( from_date , to_date ) : """Get all sales for a given time period"""
sales = Order . objects . filter ( Q ( payment_date__lte = to_date ) & Q ( payment_date__gte = from_date ) ) . exclude ( status = Order . CANCELLED ) return sales
def translate ( self , instruction ) : """Return IR representation of an instruction ."""
try : trans_instrs = self . __translate ( instruction ) except NotImplementedError : unkn_instr = self . _builder . gen_unkn ( ) unkn_instr . address = instruction . address << 8 | ( 0x0 & 0xff ) trans_instrs = [ unkn_instr ] self . _log_not_supported_instruction ( instruction ) except Exception : ...
def split ( x , split_dim , num_or_size_splits , name = None ) : """Like tf . split . Args : x : a Tensor split _ dim : a Dimension in x . shape . dims num _ or _ size _ splits : either an integer dividing split _ dim . size or a list of integers adding up to split _ dim . size name : an optional string...
return SplitOperation ( x , split_dim , num_or_size_splits , name = name ) . outputs
def set_is_immediate ( self , value ) : """Setter for ' is _ immediate ' field . : param value - a new value of ' is _ immediate ' field . Must be a boolean type ."""
if value is None : self . __is_immediate = value elif not isinstance ( value , bool ) : raise TypeError ( "IsImediate must be set to a bool" ) else : self . __is_immediate = value
def custom_str ( self , sc_expr_str_fn ) : """Works like MenuNode . _ _ str _ _ ( ) , but allows a custom format to be used for all symbol / choice references . See expr _ str ( ) ."""
return self . _menu_comment_node_str ( sc_expr_str_fn ) if self . item in _MENU_COMMENT else self . _sym_choice_node_str ( sc_expr_str_fn )
def get_mail_addresses ( message , header_name ) : """Retrieve all email addresses from one message header ."""
headers = [ h for h in message . get_all ( header_name , [ ] ) ] addresses = email . utils . getaddresses ( headers ) for index , ( address_name , address_email ) in enumerate ( addresses ) : addresses [ index ] = { 'name' : decode_mail_header ( address_name ) , 'email' : address_email } logger . debug ( "{} Ma...
def sniff_csv_format ( csv_file , potential_sep = [ '\t' , ',' , ';' , '|' , '-' , '_' ] , max_test_lines = 10 , zip_file = None ) : """Tries to get the separator , nr of index cols and header rows in a csv file Parameters csv _ file : str Path to a csv file potential _ sep : list , optional List of poten...
def read_first_lines ( filehandle ) : lines = [ ] for i in range ( max_test_lines ) : line = ff . readline ( ) if line == '' : break try : line = line . decode ( 'utf-8' ) except AttributeError : pass lines . append ( line [ : - 1 ] ) ...
def set_log_level ( log_level ) : """Set logging level of this module . Using ` logbook < https : / / logbook . readthedocs . io / en / stable / > ` _ _ module for logging . : param int log _ level : One of the log level of ` logbook < https : / / logbook . readthedocs . io / en / stable / api / base . html...
if not LOGBOOK_INSTALLED : return # validate log level logbook . get_level_name ( log_level ) if log_level == logger . level : return if log_level == logbook . NOTSET : set_logger ( is_enable = False ) else : set_logger ( is_enable = True ) logger . level = log_level tabledata . set_log_level ( log_leve...
def _finish ( self , ispausing ) : """( internal ) executes when last output piper raises ` ` StopIteration ` ` ."""
if ispausing : self . log . debug ( '%s paused' % repr ( self ) ) else : self . _finished . set ( ) self . log . debug ( '%s finished' % repr ( self ) )
def _split_docstring ( self , docstring ) : """Separate a docstring into the synopsis ( first line ) and body ."""
lines = docstring . strip ( ) . splitlines ( ) synopsis = lines [ 0 ] . strip ( ) body = textwrap . dedent ( '\n' . join ( lines [ 2 : ] ) ) # Remove RST preformatted text markers . body = body . replace ( '\n::\n' , '' ) body = body . replace ( '::\n' , ':' ) return ( synopsis , body )
def name ( self ) : """The name of the node ( only used for facilitating its identification in the user interface ) ."""
try : return self . _name except AttributeError : if self . is_task : try : return self . pos_str except : return os . path . basename ( self . workdir ) else : return os . path . basename ( self . workdir )
def get_applicable_content_pattern_names ( self , path ) : """Return the content patterns applicable to a given path . Returns a tuple ( applicable _ content _ pattern _ names , content _ encoding ) . If path matches no path patterns , the returned content _ encoding will be None ( and applicable _ content _ ...
encodings = set ( ) applicable_content_pattern_names = set ( ) for path_pattern_name , content_pattern_names in self . _required_matches . items ( ) : m = self . _path_matchers [ path_pattern_name ] if m . matches ( path ) : encodings . add ( m . content_encoding ) applicable_content_pattern_nam...
def get_policy_for_vhost ( self , vhost , name ) : """Get a specific policy for a vhost . : param vhost : The virtual host the policy is for : type vhost : str : param name : The name of the policy : type name : str"""
return self . _api_get ( '/api/policies/{0}/{1}' . format ( urllib . parse . quote_plus ( vhost ) , urllib . parse . quote_plus ( name ) , ) )
def delete_user ( cls , username ) : """Delete user"""
ret = cls . exec_request ( 'user/{}' . format ( username ) , 'delete' ) logger . debug ( ret ) if cls . _response_ok ( ret ) : logger . info ( "Deleted SeAT user with username %s" % username ) return username return None
def _set_width_cb ( self ) : """This function is called when the user enters a value into the ' Width ' entry field . ( this is only possible when ' Screen size ' is unchecked ) We calculate the height or aspect , depending on whether ' Lock aspect ' is checked and update the shot generator viewer and UI ."...
wd , ht = self . get_wdht ( ) aspect = self . get_aspect ( ) if self . _lock_aspect and aspect is not None : ht = int ( round ( wd * 1.0 / aspect ) ) self . w . height . set_text ( str ( ht ) ) else : _as = self . calc_aspect_str ( wd , ht ) self . w . aspect . set_text ( _as ) self . shot_generator . c...
def format_additional_features_server_configurations ( result ) : '''Formats the AdditionalFeaturesServerConfigurations object removing arguments that are empty'''
from collections import OrderedDict # Only display parameters that have content order_dict = OrderedDict ( ) if result . is_rservices_enabled is not None : order_dict [ 'isRServicesEnabled' ] = result . is_rservices_enabled if result . backup_permissions_for_azure_backup_svc is not None : order_dict [ 'backupPe...
def spatial_slice_zeros ( x ) : """Experimental summary that shows how many planes are unused for a batch ."""
return tf . cast ( tf . reduce_all ( tf . less_equal ( x , 0.0 ) , [ 0 , 1 , 2 ] ) , tf . float32 )
def generate_parallel ( samples , run_parallel ) : """Provide parallel preparation of summary information for alignment and variant calling ."""
to_analyze , extras = _split_samples_by_qc ( samples ) qced = run_parallel ( "pipeline_summary" , to_analyze ) samples = _combine_qc_samples ( qced ) + extras qsign_info = run_parallel ( "qsignature_summary" , [ samples ] ) metadata_file = _merge_metadata ( [ samples ] ) summary_file = write_project_summary ( samples ,...
def deploy ( self , driver , location_id = config . DEFAULT_LOCATION_ID , size = config . DEFAULT_SIZE ) : """Use driver to deploy node , with optional ability to specify location id and size id . First , obtain location object from driver . Next , get the size . Then , get the image . Finally , deploy node ,...
logger . debug ( 'deploying node %s using driver %s' % ( self . name , driver ) ) args = { 'name' : self . name } if hasattr ( config , 'SSH_KEY_NAME' ) : args [ 'ex_keyname' ] = config . SSH_KEY_NAME if hasattr ( config , 'EX_USERDATA' ) : args [ 'ex_userdata' ] = config . EX_USERDATA args [ 'location' ] = dri...
def ativar_sat ( self , tipo_certificado , cnpj , codigo_uf ) : """Função ` ` AtivarSAT ` ` conforme ER SAT , item 6.1.1. Ativação do equipamento SAT . Dependendo do tipo do certificado , o procedimento de ativação é complementado enviando - se o certificado emitido pela ICP - Brasil ( : meth : ` comun...
return self . invocar__AtivarSAT ( self . gerar_numero_sessao ( ) , tipo_certificado , self . _codigo_ativacao , cnpj , codigo_uf )
def window ( seq , n = 2 ) : """Yield a sliding window over an iterable . Args : seq ( iter ) : The sequence . n ( int ) : The window width . Yields : tuple : The next window ."""
it = iter ( seq ) result = tuple ( islice ( it , n ) ) if len ( result ) == n : yield result for token in it : result = result [ 1 : ] + ( token , ) yield result
def nextprefix ( self ) : """Get the next available prefix . This means a prefix starting with ' ns ' with a number appended as ( ns0 , ns1 , . . ) that is not already defined on the wsdl document ."""
used = [ ns [ 0 ] for ns in self . prefixes ] used += [ ns [ 0 ] for ns in self . wsdl . root . nsprefixes . items ( ) ] for n in range ( 0 , 1024 ) : p = 'ns%d' % n if p not in used : return p raise Exception ( 'prefixes exhausted' )
def encode ( value , encoding = 'utf-8' , encoding_errors = 'strict' ) : """Return a bytestring representation of the value ."""
if isinstance ( value , bytes ) : return value if not isinstance ( value , basestring ) : value = str ( value ) if isinstance ( value , unicode ) : value = value . encode ( encoding , encoding_errors ) return value
def to_dict ( self , field = None , ** kwargs ) : """Convert the ParameterSet to a structured ( nested ) dictionary to allow traversing the structure from the bottom up : parameter str field : ( optional ) build the dictionary with keys at a given level / field . Can be any of the keys in : func : ` meta ` ...
if kwargs : return self . filter ( ** kwargs ) . to_dict ( field = field ) if field is not None : keys_for_this_field = set ( [ getattr ( p , field ) for p in self . to_list ( ) if getattr ( p , field ) is not None ] ) return { k : self . filter ( check_visible = False , ** { field : k } ) for k in keys_for...
def to_xml ( self ) : '''Returns a DOM representation of the payment . @ return : Element'''
for n , v in { "amount" : self . amount , "date" : self . date , "method" : self . method } . items ( ) : if is_empty_or_none ( v ) : raise PaymentError ( "'%s' attribute cannot be empty or " "None." % n ) doc = Document ( ) root = doc . createElement ( "payment" ) super ( Payment , self ) . to_xml ( root )...
def clear ( self ) : """Reset the config object to its initial state"""
with self . _lock : self . _config = { CacheConfig . Morlist : { 'last' : defaultdict ( float ) , 'intl' : { } } , CacheConfig . Metadata : { 'last' : defaultdict ( float ) , 'intl' : { } } , }
def interpolate ( series , delta_f ) : """Return a new PSD that has been interpolated to the desired delta _ f . Parameters series : FrequencySeries Frequency series to be interpolated . delta _ f : float The desired delta _ f of the output Returns interpolated series : FrequencySeries A new Frequen...
new_n = ( len ( series ) - 1 ) * series . delta_f / delta_f + 1 samples = numpy . arange ( 0 , numpy . rint ( new_n ) ) * delta_f interpolated_series = numpy . interp ( samples , series . sample_frequencies . numpy ( ) , series . numpy ( ) ) return FrequencySeries ( interpolated_series , epoch = series . epoch , delta_...
def write_to_file ( self , fn ) : '''Write the cube to a file in the Gaussian cube format .'''
with open ( fn , 'w' ) as f : f . write ( ' {}\n' . format ( self . molecule . title ) ) f . write ( ' {}\n' . format ( self . subtitle ) ) def write_grid_line ( n , v ) : f . write ( '%5i % 11.6f % 11.6f % 11.6f\n' % ( n , v [ 0 ] , v [ 1 ] , v [ 2 ] ) ) write_grid_line ( self . molecule . size...
def regex_matcher ( regex_pat ) : """generate token names ' cache : param regex _ pat : : return :"""
if isinstance ( regex_pat , str ) : regex_pat = re . compile ( regex_pat ) def f ( inp_str , pos ) : m = regex_pat . match ( inp_str , pos ) return m . group ( ) if m else None return f
def b_operator ( self , P ) : r"""The B operator , mapping P into . . math : : B ( P ) : = R - \ beta ^ 2 A ' PB ( Q + \ beta B ' PB ) ^ { - 1 } B ' PA + \ beta A ' PA and also returning . . math : : F : = ( Q + \ beta B ' PB ) ^ { - 1 } \ beta B ' PA Parameters P : array _ like ( float , ndim = 2) ...
A , B , Q , R , beta = self . A , self . B , self . Q , self . R , self . beta S1 = Q + beta * dot ( B . T , dot ( P , B ) ) S2 = beta * dot ( B . T , dot ( P , A ) ) S3 = beta * dot ( A . T , dot ( P , A ) ) F = solve ( S1 , S2 ) if not self . pure_forecasting else np . zeros ( ( self . k , self . n ) ) new_P = R - do...
def defaultSerialize ( obj , buf , lineLength ) : """Encode and fold obj and its children , write to buf or return a string ."""
outbuf = buf or six . StringIO ( ) if isinstance ( obj , Component ) : if obj . group is None : groupString = '' else : groupString = obj . group + '.' if obj . useBegin : foldOneLine ( outbuf , "{0}BEGIN:{1}" . format ( groupString , obj . name ) , lineLength ) for child in obj ...
def _set_metadata ( element , metadata , attr_map , transform = str ) : """Set metadata attributes on a given ` ` element ` ` . : param element : : class : ` xml . etree . ElementTree . Element ` instance : param metadata : Dictionary of metadata items containing attribute data for ` ` element ` ` . : par...
for kw , attr in attr_map . items ( ) : value = metadata . get ( kw ) if value is not None : element . set ( attr , transform ( value ) )
def wrap_warnings ( logger ) : """Have the function patch ` warnings . showwarning ` with the given logger . Arguments : logger ( ~ logging . logger ) : the logger to wrap warnings with when the decorated function is called . Returns : ` function ` : a decorator function ."""
def decorator ( func ) : @ functools . wraps ( func ) def new_func ( * args , ** kwargs ) : showwarning = warnings . showwarning warnings . showwarning = warn_logging ( logger ) try : return func ( * args , ** kwargs ) finally : warnings . showwarning = sh...
def get_products_size ( products ) : """Return the total file size in GB of all products in the OpenSearch response ."""
size_total = 0 for title , props in products . items ( ) : size_product = props [ "size" ] size_value = float ( size_product . split ( " " ) [ 0 ] ) size_unit = str ( size_product . split ( " " ) [ 1 ] ) if size_unit == "MB" : size_value /= 1024. if size_unit == "KB" : size_value /= ...
def add_translation_fields ( model , opts ) : """Monkey patches the original model class to provide additional fields for every language . Adds newly created translation fields to the given translation options ."""
model_empty_values = getattr ( opts , 'empty_values' , NONE ) for field_name in opts . local_fields . keys ( ) : field_empty_value = parse_field ( model_empty_values , field_name , NONE ) for l in mt_settings . AVAILABLE_LANGUAGES : # Create a dynamic translation field translation_field = create_transla...
def appendData ( self , bins , repnum = None ) : """Increases the values at bins ( indexes ) : param bins : bin center values to increment counts for , to increment a time bin more than once include multiple items in list with that bin center value : type bins : numpy . ndarray"""
# only if the last sample was above threshold , but last - 1 one wasn ' t bins [ bins >= len ( self . _counts ) ] = len ( self . _counts ) - 1 bin_totals = np . bincount ( bins ) self . _counts [ : len ( bin_totals ) ] += bin_totals self . histo . setOpts ( height = np . array ( self . _counts ) )
def frequency ( self ) : """0 means unknown"""
assert self . parsed_frames , "no frame parsed yet" f_index = self . _fixed_header_key [ 4 ] try : return _FREQS [ f_index ] except IndexError : return 0
def writeImageToFile ( self , filename , _format = "PNG" , deviceart = None , dropshadow = True , screenglare = True ) : '''Write the View image to the specified filename in the specified format . @ type filename : str @ param filename : Absolute path and optional filename receiving the image . If this points t...
filename = self . device . substituteDeviceTemplate ( filename ) if not os . path . isabs ( filename ) : raise ValueError ( "writeImageToFile expects an absolute path (filename='%s')" % filename ) if os . path . isdir ( filename ) : filename = os . path . join ( filename , self . serialno + '.' + _format . lowe...
def is_filter_at_key ( self , key ) : """return True if attribute is a sub filter"""
if key in self : attribute_status = getattr ( self , key ) if isinstance ( attribute_status , self . __class__ ) : return True return False
def getclienturl ( idclient , * args , ** kwargs ) : """Request Clients URL . If idclient is set , you ' ll get a response adequate for a MambuClient object . If not set , you ' ll get a response adequate for a MambuClients object . See mambuclient module and pydoc for further information . Currently implem...
getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "firstName=%s" % kwargs [ "firs...
def main ( ) : """NAME gaussian . py DESCRIPTION generates set of normally distribed data from specified distribution INPUT ( COMMAND LINE ENTRY ) OUTPUT SYNTAX gaussian . py [ command line options ] OPTIONS - h prints help message and quits - s specify standard deviation as next argument , defa...
N , mean , sigma = 100 , 0 , 1. outfile = "" if '-h' in sys . argv : print ( main . __doc__ ) sys . exit ( ) else : if '-s' in sys . argv : ind = sys . argv . index ( '-s' ) sigma = float ( sys . argv [ ind + 1 ] ) if '-n' in sys . argv : ind = sys . argv . index ( '-n' ) ...
def rotate_capture_handler_log ( self , name ) : '''Force a rotation of a handler ' s log file Args : name : The name of the handler who ' s log file should be rotated .'''
for sc_key , sc in self . _stream_capturers . iteritems ( ) : for h in sc [ 0 ] . capture_handlers : if h [ 'name' ] == name : sc [ 0 ] . _rotate_log ( h )
def fromfile ( cls , f , n = - 1 ) : """Read a bloom filter from file - object ` f ' serialized with ` ` BloomFilter . tofile ' ' . If ` n ' > 0 read only so many bytes ."""
headerlen = calcsize ( cls . FILE_FMT ) if 0 < n < headerlen : raise ValueError ( 'n too small!' ) filter = cls ( 1 ) # Bogus instantiation , we will ` _ setup ' . filter . _setup ( * unpack ( cls . FILE_FMT , f . read ( headerlen ) ) ) filter . bitarray = bitarray . bitarray ( endian = 'little' ) if n > 0 : ( ...
def set_display_sleep ( minutes ) : '''Set the amount of idle time until the display sleeps . Pass " Never " of " Off " to never sleep . : param minutes : Can be an integer between 1 and 180 or " Never " or " Off " : ptype : int , str : return : True if successful , False if not : rtype : bool CLI Examp...
value = _validate_sleep ( minutes ) cmd = 'systemsetup -setdisplaysleep {0}' . format ( value ) salt . utils . mac_utils . execute_return_success ( cmd ) return salt . utils . mac_utils . confirm_updated ( str ( value ) , get_display_sleep , )
def evals_get ( self , service_staff_id , start_date , end_date , session ) : '''taobao . wangwang . eservice . evals . get 获取评价详细 根据用户id查询用户对应的评价详细情况 , 主账号id可以查询店铺内子账号的评价 组管理员可以查询组内账号的评价 非管理员的子账号可以查自己的评价'''
request = TOPRequest ( 'taobao.wangwang.eservice.evals.get' ) request [ 'service_staff_id' ] = service_staff_id request [ 'start_date' ] = start_date request [ 'end_date' ] = end_date self . create ( self . execute ( request , session ) ) return self . staff_eval_details
def mapsplice ( job , job_vars ) : """Maps RNA - Seq reads to a reference genome . job _ vars : tuple Tuple of dictionaries : input _ args and ids"""
# Unpack variables input_args , ids = job_vars work_dir = job . fileStore . getLocalTempDir ( ) cores = input_args [ 'cpu_count' ] sudo = input_args [ 'sudo' ] single_end_reads = input_args [ 'single_end_reads' ] files_to_delete = [ 'R1.fastq' ] # I / O return_input_paths ( job , work_dir , ids , 'ebwt.zip' , 'chromoso...
def add_search_path ( * path_tokens ) : """Adds a new search path from where modules can be loaded . This function is provided for test applications to add locations to the search path , so any required functionality can be loaded . It helps keeping the step implementation modules simple by placing the bulk of ...
full_path = os . path . join ( * path_tokens ) if full_path not in sys . path : sys . path . insert ( 0 , os . path . abspath ( full_path ) )
def from_bam ( pysam_samfile , loci , normalized_contig_names = True ) : '''Create a PileupCollection for a set of loci from a BAM file . Parameters pysam _ samfile : ` pysam . Samfile ` instance , or filename string to a BAM file . The BAM file must be indexed . loci : list of Locus instances Loci to col...
loci = [ to_locus ( obj ) for obj in loci ] close_on_completion = False if typechecks . is_string ( pysam_samfile ) : pysam_samfile = Samfile ( pysam_samfile ) close_on_completion = True try : # Map from pyensembl normalized chromosome names used in Variant to # the names used in the BAM file . if normalize...
def do_rotation ( self , mirror , rot ) : """Null implementation of rotate and / or mirror ."""
if ( mirror ) : raise IIIFError ( code = 501 , parameter = "rotation" , text = "Null manipulator does not support mirroring." ) if ( rot != 0.0 ) : raise IIIFError ( code = 501 , parameter = "rotation" , text = "Null manipulator supports only rotation=(0|360)." )
def remove_child_objectives ( self , objective_id = None ) : """Removes all children from an objective . arg : objective _ id ( osid . id . Id ) : the Id of an objective raise : NotFound - objective _ id not found raise : NullArgument - objective _ id is null raise : OperationFailed - unable to complete req...
if objective_id is None : raise NullArgument ( ) ols = ObjectiveLookupSession ( self . _objective_bank_id , runtime = self . _runtime ) try : ols . get_objective ( objective_id ) except : raise # If no objective , get _ objectives will raise NotFound ids_arg = { 'ids' : [ ] } url_path = construct_url ( ...
def calc_glide_ratios ( dives , des , asc , glide_mask , depths , pitch_lf ) : '''Calculate summary information on glides during dive ascent / descents Args dives : ( n , 10) Numpy record array with summary information of dives in sensor data des : ndarray Boolean mask of descents over sensor data asc :...
import numpy import pandas # Create empty ` pandas . DataFrame ` for storing data , init with ` nan ` s cols = [ 'des_duration' , 'des_gl_duration' , 'des_gl_ratio' , 'des_mean_pitch' , 'des_rate' , 'asc_duration' , 'asc_gl_duration' , 'asc_gl_ratio' , 'asc_mean_pitch' , 'asc_rate' , ] gl_ratio = pandas . DataFrame ( i...
def get_phase ( self , nintp = None , rintp = None , delta_offset_x = 0 , delta_offset_y = 0 ) : """Interpolate from the border fields to new coordinates Parameters nintp : float or None Refractive index of the sphere rintp : float or None Radius of sphere [ m ] delta _ offset _ x : float Offset in x ...
if nintp is None : nintp = self . sphere_index if rintp is None : rintp = self . radius assert ( rintp == self . radius or nintp == self . sphere_index ) , "Only r or n can be changed at a time." assert rintp >= self . radius - self . dr assert rintp <= self . radius + self . dr assert nintp >= self . sphere_in...
def from_mime_type ( cls , mime_type ) : """Essentially a copy constructor . Type . from _ mime _ type ( plaintext ) is equivalent to : t = Type . new ( plaintext . content _ type . dup ) t . extensions = plaintext . extensions . dup t . system = plaintext . system . dup t . encoding = plaintext . encod...
mt = cls ( deepcopy ( mime_type . content_type ) ) mt . extensions = map ( deepcopy , mime_type . extensions ) mt . url = mime_type . url and map ( deepcopy , mime_type . url ) or None mt . system = deepcopy ( mime_type . system ) mt . encoding = deepcopy ( mime_type . encoding ) mt . docs = deepcopy ( mime_type . docs...
def get_clusters_interfaces ( clusters , extra_cond = lambda nic : True ) : """Returns for each cluster the available cluster interfaces Args : clusters ( str ) : list of the clusters extra _ cond ( lambda ) : extra predicate to filter network card retrieved from the API . E . g lambda nic : not nic [ ' mou...
interfaces = { } for cluster in clusters : nics = get_cluster_interfaces ( cluster , extra_cond = extra_cond ) interfaces . setdefault ( cluster , nics ) return interfaces
def get_auth_server_name ( host_override = None , port_override = None , protocol = 'https' ) : """Chooses the auth server name from the currently configured API server name . Raises DXError if the auth server name cannot be guessed and the overrides are not provided ( or improperly provided ) ."""
if host_override is not None or port_override is not None : if host_override is None or port_override is None : raise exceptions . DXError ( "Both host and port must be specified if either is specified" ) return protocol + '://' + host_override + ':' + str ( port_override ) elif APISERVER_HOST == 'stagi...
def get_exe_info ( dir_ , flag_protected = False ) : """Returns a list of ExeInfo objects , which represent Python scripts within dir _ Args : dir _ : string , path to directory flag _ protected : whether or not to include files starting with a ' _ ' Returns : list of ExeInfo objects The ExeInfo objects...
ret = [ ] # gets all scripts in script directory ff = glob . glob ( os . path . join ( dir_ , "*.py" ) ) # discards scripts whose file name starts with a " _ " ff = [ f for f in ff if flag_protected or not os . path . basename ( f ) . startswith ( "_" ) ] ff . sort ( ) for f in ff : _ , filename = os . path . split...
def recv ( self , timeout = None ) : """Overwrite standard recv for timeout calls to catch interrupt errors ."""
if timeout : try : testsock = self . _zmq . select ( [ self . socket ] , [ ] , [ ] , timeout ) [ 0 ] except zmq . ZMQError as e : if e . errno == errno . EINTR : testsock = None else : raise if not testsock : return rv = self . socket . recv ( self...
def set_xticks ( start , step , axes = "gca" ) : """This will generate a tick array and apply said array to the axis"""
if axes == "gca" : axes = _pylab . gca ( ) # first get one of the tick label locations yposition = axes . xaxis . get_ticklabels ( ) [ 0 ] . get_position ( ) [ 1 ] # get the bounds xmin , xmax = axes . get_xlim ( ) # get the starting tick nstart = int ( _pylab . floor ( ( xmin - start ) / step ) ) nstop = int ( _py...
def _from_dict ( cls , _dict ) : """Initialize a UtteranceAnalyses object from a json dictionary ."""
args = { } if 'utterances_tone' in _dict : args [ 'utterances_tone' ] = [ UtteranceAnalysis . _from_dict ( x ) for x in ( _dict . get ( 'utterances_tone' ) ) ] else : raise ValueError ( 'Required property \'utterances_tone\' not present in UtteranceAnalyses JSON' ) if 'warning' in _dict : args [ 'warning' ]...
def import_spydercustomize ( ) : """Import our customizations into the kernel ."""
here = osp . dirname ( __file__ ) parent = osp . dirname ( here ) customize_dir = osp . join ( parent , 'customize' ) # Remove current directory from sys . path to prevent kernel # crashes when people name Python files or modules with # the same name as standard library modules . # See spyder - ide / spyder # 8007 whil...
def _call ( self , x ) : """` ` self ( x ) ` ` ."""
with self . mutex : result = sheardec2D ( x , self . shearlet_system ) return np . moveaxis ( result , - 1 , 0 )
def transform_revision ( self , revision ) : """make config revision look like describe output ."""
config = self . manager . get_source ( 'config' ) return config . load_resource ( revision )
def get_user_credentials ( self ) : """Gets new credentials : return : User credentials created via OAuth"""
# create path to user credentials if needed if not os . path . exists ( os . path . dirname ( self . user_credentials ) ) : os . makedirs ( os . path . dirname ( self . user_credentials ) ) credentials = self . store . get ( ) # retrieve credentials needs_to_be_updated = not credentials or credentials . invalid if ...