signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def list_items ( self , url , container = None , last_obj = None , spr = False ) : """Builds a long list of objects found in a container . NOTE : This could be millions of Objects . : param url : : param container : : param last _ obj : : param spr : " single page return " Limit the returned data to one p...
headers , container_uri = self . _return_base_data ( url = url , container = container ) if container : resp = self . _header_getter ( uri = container_uri , headers = headers ) if resp . status_code == 404 : LOG . info ( 'Container [ %s ] not found.' , container ) return [ resp ] return self . _...
def calc_strain_tf ( self , lin , lout ) : """Compute the strain transfer function from ` lout ` to ` location _ in ` . The strain transfer function from the acceleration at layer ` n ` ( outcrop ) to the mid - height of layer ` m ` ( within ) is defined as Parameters lin : : class : ` ~ site . Location `...
# FIXME : Correct discussion for using acceleration FAS # Strain ( angFreq , z = h _ m / 2) # accel _ n ( angFreq ) # i k * _ m [ A _ m exp ( i k * _ m h _ m / 2 ) - B _ m exp ( - i k * _ m h _ m / 2 ) ] # - angFreq ^ 2 ( 2 * A _ n ) assert lout . wave_field == WaveField . within ang_freqs = self . motion . angular_fre...
def get_title_metadata ( self ) : """Gets the metadata for an asset title . return : ( osid . Metadata ) - metadata for the title * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . resource . ResourceForm . get _ group _ metadata _ template metadata = dict ( self . _mdata [ 'title' ] ) metadata . update ( { 'existing_string_values' : self . _my_map [ 'title' ] } ) return Metadata ( ** metadata )
def fmt_routes ( bottle_app ) : """Return a pretty formatted string of the list of routes ."""
routes = [ ( r . method , r . rule ) for r in bottle_app . routes ] if not routes : return string = 'Routes:\n' string += fmt_pairs ( routes , sort_key = operator . itemgetter ( 1 ) ) return string
def fromML ( mat ) : """Convert a matrix from the new mllib - local representation . This does NOT copy the data ; it copies references . : param mat : a : py : class : ` pyspark . ml . linalg . Matrix ` : return : a : py : class : ` pyspark . mllib . linalg . Matrix ` . . versionadded : : 2.0.0"""
if isinstance ( mat , newlinalg . DenseMatrix ) : return DenseMatrix ( mat . numRows , mat . numCols , mat . values , mat . isTransposed ) elif isinstance ( mat , newlinalg . SparseMatrix ) : return SparseMatrix ( mat . numRows , mat . numCols , mat . colPtrs , mat . rowIndices , mat . values , mat . isTranspos...
def add_element_to_doc ( doc , tag , value ) : """Set text value of an etree . Element of tag , appending a new element with given tag if it doesn ' t exist ."""
element = doc . find ( ".//%s" % tag ) if element is None : element = etree . SubElement ( doc , tag ) element . text = value
def point_coll_value ( coll , xy , scale = 1 ) : """Extract the output value from a calculation at a point"""
output = getinfo ( coll . getRegion ( ee . Geometry . Point ( xy ) , scale = scale ) ) # Structure output to easily be converted to a Pandas dataframe # First key is band name , second key is the date string col_dict = { } info_dict = { } for i , k in enumerate ( output [ 0 ] [ 4 : ] ) : col_dict [ k ] = i + 4 ...
def populate_index ( version , circleci_build , appveyor_build , coveralls_build , travis_build ) : """Populates ` ` docs / index . rst ` ` with release - specific data . Args : version ( str ) : The current version . circleci _ build ( Union [ str , int ] ) : The CircleCI build ID corresponding to the rele...
with open ( RELEASE_INDEX_FILE , "r" ) as file_obj : template = file_obj . read ( ) contents = template . format ( version = version , circleci_build = circleci_build , appveyor_build = appveyor_build , coveralls_build = coveralls_build , travis_build = travis_build , ) with open ( INDEX_FILE , "w" ) as file_obj : ...
def visitValueTypeMacro ( self , ctx : jsgParser . ValueTypeMacroContext ) : """valueTypeMacro : ID EQUALS nonRefValueType ( BAR nonRefValueType ) * SEMI"""
self . _context . grammarelts [ as_token ( ctx ) ] = JSGValueType ( self . _context , ctx )
def flatten ( l , types = ( list , float ) ) : """Flat nested list of lists into a single list ."""
l = [ item if isinstance ( item , types ) else [ item ] for item in l ] return [ item for sublist in l for item in sublist ]
def delete ( self ) : """delete the jenkins job , if it exists"""
if self . jenkins_host . has_job ( self . name ) : LOGGER . info ( "deleting {0}..." . format ( self . name ) ) self . jenkins_host . delete_job ( self . name )
def run ( self , clean = True ) : """Create a temporary file and run it"""
template = self . template parameters = self . parameters # write to a temporary R script fw = must_open ( "tmp" , "w" ) path = fw . name fw . write ( template . safe_substitute ( ** parameters ) ) fw . close ( ) sh ( "Rscript %s" % path ) if clean : os . remove ( path ) # I have no idea why using ggsave , ther...
def register_death ( self ) : """Registers its own death ."""
self . log . info ( 'Registering death' ) with self . connection . pipeline ( ) as p : p . hset ( self . scheduler_key , 'death' , time . time ( ) ) p . expire ( self . scheduler_key , 60 ) p . execute ( )
def run_iter ( self , mine = False , jid = None ) : '''Execute and yield returns as they come in , do not print to the display mine The Single objects will use mine _ functions defined in the roster , pillar , or master config ( they will be checked in that order ) and will modify the argv with the argument...
fstr = '{0}.prep_jid' . format ( self . opts [ 'master_job_cache' ] ) jid = self . returners [ fstr ] ( passed_jid = jid or self . opts . get ( 'jid' , None ) ) # Save the invocation information argv = self . opts [ 'argv' ] if self . opts . get ( 'raw_shell' , False ) : fun = 'ssh._raw' args = argv else : ...
def ipglob ( self , * args ) : """Returns a random address from within the given ip global https : / / pythonhosted . org / netaddr / api . html # ip - glob - ranges IPGLOB : GLOB % { IPGLOB : * . * . * . * } - > ' '"""
call_args = list ( args ) return self . random . choice ( IPGlob ( call_args . pop ( 0 ) ) )
def compare_layers_from_nets ( caffe_net , arg_params , aux_params , exe , layer_name_to_record , top_to_layers , mean_diff_allowed , max_diff_allowed ) : """Compare layer by layer of a caffe network with mxnet network : param caffe _ net : loaded caffe network : param arg _ params : arguments : param aux _ p...
import re log_format = ' {0:<40} {1:<40} {2:<8} {3:>10} {4:>10} {5:<1}' compare_layers_from_nets . is_first_convolution = True def _compare_blob ( caf_blob , mx_blob , caf_name , mx_name , blob_type , note ) : diff = np . abs ( mx_blob - caf_blob ) diff_mean = diff . mean ( ) diff_max = diff . max ( )...
def subdispatch_to_all_initiatortransfer ( payment_state : InitiatorPaymentState , state_change : StateChange , channelidentifiers_to_channels : ChannelMap , pseudo_random_generator : random . Random , ) -> TransitionResult [ InitiatorPaymentState ] : events = list ( ) '''Copy and iterate over the list of keys ...
for secrethash in list ( payment_state . initiator_transfers . keys ( ) ) : initiator_state = payment_state . initiator_transfers [ secrethash ] sub_iteration = subdispatch_to_initiatortransfer ( payment_state = payment_state , initiator_state = initiator_state , state_change = state_change , channelidentifiers...
def open ( filename , connection = None ) : """Edits or Adds a filename ensuring the file is in perforce and editable : param filename : File to check out : type filename : str : param connection : Connection object to use : type connection : : py : class : ` Connection `"""
c = connection or connect ( ) res = c . ls ( filename ) if res and res [ 0 ] . revision : res [ 0 ] . edit ( ) else : c . add ( filename )
def sum_fields ( layer , output_field_key , input_fields ) : """Sum the value of input _ fields and put it as output _ field . : param layer : The vector layer . : type layer : QgsVectorLayer : param output _ field _ key : The output field definition key . : type output _ field _ key : basestring : param ...
field_definition = definition ( output_field_key ) output_field_name = field_definition [ 'field_name' ] # If the fields only has one element if len ( input_fields ) == 1 : # Name is different , copy it if input_fields [ 0 ] != output_field_name : to_rename = { input_fields [ 0 ] : output_field_name } ...
def split_semicolon ( line , maxsplit = None ) : r"""Split a line on semicolons characters but not on the escaped semicolons : param line : line to split : type line : str : param maxsplit : maximal number of split ( if None , no limit ) : type maxsplit : None | int : return : split line : rtype : list ...
# Split on ' ; ' character split_line = line . split ( ';' ) split_line_size = len ( split_line ) # if maxsplit is not specified , we set it to the number of part if maxsplit is None or maxsplit < 0 : maxsplit = split_line_size # Join parts to the next one , if ends with a ' \ ' # because we mustn ' t split if the ...
def wrap_guess_content_type ( func_ , * args , ** kwargs ) : """guesses the content type with libmagic if available : param func _ : : param args : : param kwargs : : return :"""
assert isinstance ( args [ 0 ] , dict ) if not args [ 0 ] . get ( CONTENTTYPE_FIELD , None ) : content = args [ 0 ] . get ( CONTENT_FIELD , b"" ) try : args [ 0 ] [ CONTENTTYPE_FIELD ] = magic . from_buffer ( content ) except magic . MagicException : # pragma : no cover args [ 0 ] [ CONTENTT...
def get_change ( self , change_id ) : """Get information about a proposed set of changes , as submitted by the change _ rrsets method . Returns a Python data structure with status information about the changes . : type change _ id : str : param change _ id : The unique identifier for the set of changes . ...
uri = '/%s/change/%s' % ( self . Version , change_id ) response = self . make_request ( 'GET' , uri ) body = response . read ( ) boto . log . debug ( body ) if response . status >= 300 : raise exception . DNSServerError ( response . status , response . reason , body ) e = boto . jsonresponse . Element ( ) h = boto ...
def download ( self , file_name , save_as = None ) : """Download the specified file from the server . Arguments : file _ name - - Name of file resource to save . save _ as - - Optional path name to write file to . If not specified , then file named by the last part of the resource path is downloaded to cu...
self . _check_session ( ) try : if save_as : save_as = os . path . normpath ( save_as ) save_dir = os . path . dirname ( save_as ) if save_dir : if not os . path . exists ( save_dir ) : os . makedirs ( save_dir ) elif not os . path . isdir ( save_dir )...
def create_shared_noise ( count ) : """Create a large array of noise to be shared by all workers ."""
seed = 123 noise = np . random . RandomState ( seed ) . randn ( count ) . astype ( np . float32 ) return noise
def deserialize ( self , data = None ) : """Invoke the deserializer If the payload is a collection ( more than 1 records ) then a list will be returned of normalized dict ' s . If the payload is a single item then the normalized dict will be returned ( not a list ) : return : list or dict"""
data = [ ] if self . req . content_type_params . get ( 'header' ) != 'present' : abort ( exceptions . InvalidRequestHeader ( ** { 'detail' : 'When using text/csv your Content-Type ' 'header MUST have a header=present parameter ' '& the payload MUST include a header of fields' , 'links' : 'tools.ietf.org/html/rfc418...
def zGetUpdate ( self ) : """Update the lens"""
status , ret = - 998 , None ret = self . _sendDDEcommand ( "GetUpdate" ) if ret != None : status = int ( ret ) # Note : Zemax returns - 1 if GetUpdate fails . return status
def GuinierPorod ( q , G , Rg , alpha ) : """Empirical Guinier - Porod scattering Inputs : ` ` q ` ` : independent variable ` ` G ` ` : factor of the Guinier - branch ` ` Rg ` ` : radius of gyration ` ` alpha ` ` : power - law exponent Formula : ` ` G * exp ( - q ^ 2 * Rg ^ 2/3 ) ` ` if ` ` q < q _ se...
return GuinierPorodMulti ( q , G , Rg , alpha )
def bottomup ( cls ) : """Get all bottomup ` Relationship ` instances . Example : > > > from pronto import Relationship > > > for r in Relationship . bottomup ( ) : . . . print ( r ) Relationship ( ' is _ a ' ) Relationship ( ' part _ of ' ) Relationship ( ' develops _ from ' )"""
return tuple ( unique_everseen ( r for r in cls . _instances . values ( ) if r . direction == 'bottomup' ) )
def OauthAuthorizeApplication ( self , oauth_duration = 'hour' ) : """Authorize an application using oauth . If this function returns True , the obtained oauth token can be retrieved using getResponse and will be in url - parameters format . TODO : allow the option to ask the user himself for permission , instead...
if self . __session_id__ == '' : self . __error__ = "not logged in" return False # automatically get authorization for the application parameters = { 'oauth_token' : self . __oauth_token__ . key , 'tok_expir' : self . __OauthGetTokExpir__ ( oauth_duration ) , 'action' : 'ALLOW' , 'session_id' : self . __session...
def linear_weights ( i , n ) : """A window function that falls off arithmetically . This is used to calculate a weighted moving average ( WMA ) that gives higher weight to changes near the point being analyzed , and smooth out changes at the opposite edge of the moving window . See bug 879903 for details ."""
if i >= n : return 0.0 return float ( n - i ) / float ( n )
def _Close ( self ) : """Closes the file - like object . If the file - like object was passed in the init function the compressed stream file - like object does not control the file - like object and should not actually close it ."""
if not self . _file_object_set_in_init : self . _file_object . close ( ) self . _file_object = None self . _compressed_data = b'' self . _uncompressed_data = b'' self . _decompressor = None
def ssn ( self ) : """Returns 11 character Polish national identity code ( Public Electronic Census System , Polish : Powszechny Elektroniczny System Ewidencji Ludności - PESEL ) . It has the form YYMMDDZZZXQ , where YYMMDD is the date of birth ( with century encoded in month field ) , ZZZ is the personal id...
birth_date = self . generator . date_time ( ) year_without_century = int ( birth_date . strftime ( '%y' ) ) month = calculate_month ( birth_date ) day = int ( birth_date . strftime ( '%d' ) ) pesel_digits = [ int ( year_without_century / 10 ) , year_without_century % 10 , int ( month / 10 ) , month % 10 , int ( day / 1...
def _call ( self , x , out = None ) : """Return the zero vector or assign it to ` ` out ` ` ."""
if self . domain == self . range : if out is None : out = 0 * x else : out . lincomb ( 0 , x ) else : result = self . range . zero ( ) if out is None : out = result else : out . assign ( result ) return out
def get_concrete_derived_from ( self , address ) : """Get the concrete target the specified target was ( directly or indirectly ) derived from . The returned target is guaranteed to not have been derived from any other target . : API : public"""
current_address = address next_address = self . _derived_from_by_derivative . get ( current_address , current_address ) while next_address != current_address : current_address = next_address next_address = self . _derived_from_by_derivative . get ( current_address , current_address ) return self . get_target ( ...
def error_handler ( f ) : """Return a json payload and appropriate status code on expection ."""
@ wraps ( f ) def inner ( * args , ** kwargs ) : try : return f ( * args , ** kwargs ) except ReceiverDoesNotExist : return jsonify ( status = 404 , description = 'Receiver does not exists.' ) , 404 except InvalidPayload as e : return jsonify ( status = 415 , description = 'Receiver ...
def treat_machine_dict ( machine ) : '''Make machine presentable for outside world . ! ! ! Modifies the input machine ! ! ! @ param machine : @ type machine : dict @ return : the modified input machine @ rtype : dict'''
machine . update ( { 'id' : machine . get ( 'id' , '' ) , 'image' : machine . get ( 'image' , '' ) , 'size' : '{0} MB' . format ( machine . get ( 'memorySize' , 0 ) ) , 'state' : machine_get_machinestate_str ( machine ) , 'private_ips' : [ ] , 'public_ips' : [ ] , } ) # Replaced keys if 'memorySize' in machine : de...
def parse ( cls , constraints_expression ) : """Parses a : ref : ` constraints _ expression < constraints - expressions > ` and returns a : class : ` Constraints ` object ."""
constraint_exprs = re . split ( r'\s*,\s*' , constraints_expression ) return Constraints ( merge ( Constraint . parse ( constraint_expr ) for constraint_expr in constraint_exprs ) )
def can_lookup_activities ( self ) : """Tests if this user can perform Activity lookups . A return of true does not guarantee successful authorization . A return of false indicates that it is known all methods in this session will result in a PermissionDenied . This is intended as a hint to an application t...
url_path = construct_url ( 'authorization' , bank_id = self . _catalog_idstr ) return self . _get_request ( url_path ) [ 'activityHints' ] [ 'canLookup' ]
def check ( self , strict = False ) : """Check if the metadata is compliant . If strict is True then raise if no Name or Version are provided"""
self . set_metadata_version ( ) # XXX should check the versions ( if the file was loaded ) missing , warnings = [ ] , [ ] for attr in ( 'Name' , 'Version' ) : # required by PEP 345 if attr not in self : missing . append ( attr ) if strict and missing != [ ] : msg = 'missing required metadata: %s' % ', '...
def _compute_example_flat_helper ( self , label ) : """From the " raw example , " resolves references to examples of other data types to compute the final example . Returns an Example object . The ` value ` attribute contains a JSON - serializable representation of the example ."""
assert label in self . _raw_examples , label example = self . _raw_examples [ label ] def deref_example_ref ( dt , val ) : dt , _ = unwrap_nullable ( dt ) if not dt . _has_example ( val . label ) : raise InvalidSpec ( "Reference to example for '%s' with label '%s' " "does not exist." % ( dt . name , val...
def create_token ( self , request , refresh_token = False , ** kwargs ) : """Create a BearerToken , by default without refresh token . : param request : OAuthlib request . : type request : oauthlib . common . Request : param refresh _ token :"""
if "save_token" in kwargs : warnings . warn ( "`save_token` has been deprecated, it was not called internally." "If you do, call `request_validator.save_token()` instead." , DeprecationWarning ) if callable ( self . expires_in ) : expires_in = self . expires_in ( request ) else : expires_in = self . expires...
def list_all_files ( i ) : """Input : { path - top level path ( file _ name ) - search for a specific file name ( pattern ) - return only files with this pattern ( path _ ext ) - path extension ( needed for recursion ) ( limit ) - limit number of files ( if directories with a large number of files ) ( n...
number = 0 if i . get ( 'number' , '' ) != '' : number = int ( i [ 'number' ] ) inames = i . get ( 'ignore_names' , [ ] ) fname = i . get ( 'file_name' , '' ) limit = - 1 if i . get ( 'limit' , '' ) != '' : limit = int ( i [ 'limit' ] ) a = { } iall = i . get ( 'all' , '' ) pe = '' if i . get ( 'path_ext' , '' ...
def get_default_net_device ( ) : """Find the device where the default route is ."""
with open ( '/proc/net/route' ) as fh : for line in fh : iface , dest , _ = line . split ( None , 2 ) if dest == '00000000' : return iface return None
def add_include ( self , name , included_scope , module ) : """Register an imported module into this scope . Raises ` ` ThriftCompilerError ` ` if the name has already been used ."""
# The compiler already ensures this . If we still get here with a # conflict , that ' s a bug . assert name not in self . included_scopes self . included_scopes [ name ] = included_scope self . add_surface ( name , module )
def get_default_config_help ( self ) : """Returns the help text for the configuration options for this handler"""
config = super ( StatsiteHandler , self ) . get_default_config_help ( ) config . update ( { 'host' : '' , 'tcpport' : '' , 'udpport' : '' , 'timeout' : '' , } ) return config
def _qt_export_vtkjs ( self , show = True ) : """Spawn an save file dialog to export a vtkjs file ."""
return FileDialog ( self . app_window , filefilter = [ 'VTK JS File(*.vtkjs)' ] , show = show , directory = os . getcwd ( ) , callback = self . export_vtkjs )
def remove ( self , context , request ) : """/ @ @ API / remove : Remove existing object Required parameters : - UID : UID for the object . runtime : Function running time . error : true or string ( message ) if error . false if no error . success : true or string ( message ) if success . false if no succ...
savepoint = transaction . savepoint ( ) uc = getToolByName ( context , 'uid_catalog' ) _uid = request . get ( 'UID' , '' ) if not _uid : raise BadRequest ( "No UID specified in request" ) ret = { "url" : router . url_for ( "remove" , force_external = True ) , "success" : True , "error" : False , } data = uc ( UID =...
def instance ( cls , public_keys_dir ) : '''Please avoid create multi instance'''
if public_keys_dir in cls . _authenticators : return cls . _authenticators [ public_keys_dir ] new_instance = cls ( public_keys_dir ) cls . _authenticators [ public_keys_dir ] = new_instance return new_instance
def start ( self ) : """Creates a SSL connection to the iDigi Server and sends a ConnectionRequest message ."""
self . log . info ( "Starting SSL Session for Monitor %s." % self . monitor_id ) if self . socket is not None : raise Exception ( "Socket already established for %s." % self ) try : # Create socket , wrap in SSL and connect . self . socket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) # Vali...
def edge_list ( self ) -> List [ Edge ] : """The ordered list of edges in the container ."""
return [ edge for edge in sorted ( self . _edges . values ( ) , key = attrgetter ( "key" ) ) ]
def _get_starting_paths ( self , curdir ) : """Get the starting location . For case sensitive paths , we have to " glob " for it first as Python doesn ' t like for its users to think about case . By scanning for it , we can get the actual casing and then compare ."""
results = [ curdir ] if not self . _is_parent ( curdir ) and not self . _is_this ( curdir ) : fullpath = os . path . abspath ( curdir ) basename = os . path . basename ( fullpath ) dirname = os . path . dirname ( fullpath ) if basename : matcher = self . _get_matcher ( basename ) results...
def aggregate_result ( self , return_code , output , service_description = '' , specific_servers = None ) : '''aggregate result'''
if specific_servers == None : specific_servers = self . servers else : specific_servers = set ( self . servers ) . intersection ( specific_servers ) for server in specific_servers : if not self . servers [ server ] [ 'send_errors_only' ] or return_code > 0 : self . servers [ server ] [ 'results' ] ....
def override_stage_config_setting ( self , key , val ) : """Forcefully override a setting set by zappa _ settings ( for the current stage only ) : param key : settings key : param val : value"""
self . _stage_config_overrides = getattr ( self , '_stage_config_overrides' , { } ) self . _stage_config_overrides . setdefault ( self . api_stage , { } ) [ key ] = val
def parseFullScan ( self , i , modifications = False ) : """parses scan info for giving a Spectrum Obj for plotting . takes significantly longer since it has to unzip / parse xml"""
scanObj = PeptideObject ( ) peptide = str ( i [ 1 ] ) pid = i [ 2 ] scanObj . acc = self . protein_map . get ( i [ 4 ] , i [ 4 ] ) if pid is None : return None if modifications : sql = 'select aam.ModificationName,pam.Position,aam.DeltaMass from peptidesaminoacidmodifications pam left join aminoacidmodification...
def get_note ( self , coords ) : """Get the note for the cell at the given coordinates . coords is a tuple of ( col , row )"""
col , row = coords note = self . raw_sheet . cell_note_map . get ( ( row , col ) ) return note . text if note else None
def set_ ( uri , value ) : '''Set a value in a db , using a uri in the form of ` ` sdb : / / < profile > / < key > ` ` . If the uri provided does not start with ` ` sdb : / / ` ` or the value is not successfully set , return ` ` False ` ` . CLI Example : . . code - block : : bash salt ' * ' sdb . set sdb ...
return salt . utils . sdb . sdb_set ( uri , value , __opts__ , __utils__ )
def html_for_cgi_argument ( argument , form ) : """Returns an HTML snippet for a CGI argument . Args : argument : A string representing an CGI argument name in a form . form : A CGI FieldStorage object . Returns : String HTML representing the CGI value and variable ."""
value = form [ argument ] . value if argument in form else None return KEY_VALUE_TEMPLATE . format ( argument , value )
def is_newer_than ( pth1 , pth2 ) : """Return true if either file pth1 or file pth2 don ' t exist , or if pth1 has been modified more recently than pth2"""
return not os . path . exists ( pth1 ) or not os . path . exists ( pth2 ) or os . stat ( pth1 ) . st_mtime > os . stat ( pth2 ) . st_mtime
def save ( self ) : """Creates / updates a row . This is a blind insert call . All validation and cleaning needs to happen prior to calling this ."""
if self . instance is None : raise CQLEngineException ( "DML Query intance attribute is None" ) assert type ( self . instance ) == self . model nulled_fields = set ( ) if self . instance . _has_counter or self . instance . _can_update ( ) : if self . instance . _has_counter : warn ( "'create' and 'save'...
def ensure_dtype ( core , dtype , dtype_ ) : """Ensure dtype is correct ."""
core = core . copy ( ) if dtype is None : dtype = dtype_ if dtype_ == dtype : return core , dtype for key , val in { int : chaospy . poly . typing . asint , float : chaospy . poly . typing . asfloat , np . float32 : chaospy . poly . typing . asfloat , np . float64 : chaospy . poly . typing . asfloat , } . items...
def xml_equal ( xml_file1 , xml_file2 ) : """Parse xml and convert to a canonical string representation so we don ' t have to worry about semantically meaningless differences"""
def canonical ( xml_file ) : # poor man ' s canonicalization , since we don ' t want to install # external packages just for unittesting s = et . tostring ( et . parse ( xml_file ) . getroot ( ) ) . decode ( "UTF-8" ) s = re . sub ( "[\n|\t]*" , "" , s ) s = re . sub ( "\s+" , " " , s ) s = "" . join ( ...
def pull ( i ) : """Input : { ( repo _ uoa ) - repo UOA , if needed module _ uoa - module UOA data _ uoa - data UOA ( filename ) - filename ( with path ) ( if empty , set archive to ' yes ' ) or ( cid [ 0 ] ) if empty , create an archive of the entry ( archive ) - if ' yes ' pull whole entry as zip ...
o = i . get ( 'out' , '' ) tj = False if o == 'json' or o == 'json_file' or i . get ( 'encode_file' , '' ) == 'yes' : tj = True st = i . get ( 'skip_tmp' , '' ) ruoa = i . get ( 'repo_uoa' , '' ) muoa = i . get ( 'module_uoa' , '' ) duoa = i . get ( 'data_uoa' , '' ) pat = i . get ( 'pattern' , '' ) pats = i . get ...
def cd ( self , remote ) : """Change working directory on server"""
try : self . conn . cwd ( remote ) except Exception : return False else : return self . pwd ( )
def p_next1 ( p ) : """label _ next : LABEL NEXT ID | NEXT ID"""
if p [ 1 ] == 'NEXT' : p1 = make_nop ( ) p3 = p [ 2 ] else : p1 = make_label ( p [ 1 ] , p . lineno ( 1 ) ) p3 = p [ 3 ] if p3 != gl . LOOPS [ - 1 ] [ 1 ] : api . errmsg . syntax_error_wrong_for_var ( p . lineno ( 2 ) , gl . LOOPS [ - 1 ] [ 1 ] , p3 ) p [ 0 ] = make_nop ( ) return p [ 0 ] = ...
def on_message ( self , _ , basic_deliver , properties , body ) : """Invoked by pika when a message is delivered from RabbitMQ . The channel is passed for your convenience . The basic _ deliver object that is passed in carries the exchange , routing key , delivery tag and a redelivered flag for the message . ...
logger . debug ( 'Received message # %s from %s: %s' , basic_deliver . delivery_tag , properties . app_id , body ) try : decoded = json . loads ( body . decode ( '-utf-8' ) ) except ValueError : logger . warning ( 'Discarding message containing invalid json: %s' , body ) else : self . _handler ( decoded ) s...
def change_directory ( self , path , * args , ** kwargs ) : """: meth : ` . WNetworkClientProto . change _ directory ` method implementation"""
client = self . dav_client ( ) previous_path = self . session_path ( ) try : if client . is_dir ( self . session_path ( path ) ) is False : raise ValueError ( 'Unable to change current working directory to non-directory entry' ) except Exception : self . session_path ( previous_path ) raise
def TerminalSize ( ) : """Returns terminal length and width as a tuple ."""
try : with open ( os . ctermid ( ) , 'r' ) as tty_instance : length_width = struct . unpack ( 'hh' , fcntl . ioctl ( tty_instance . fileno ( ) , termios . TIOCGWINSZ , '1234' ) ) except ( IOError , OSError ) : try : length_width = ( int ( os . environ [ 'LINES' ] ) , int ( os . environ [ 'COLUMN...
def parseOutPorts ( outports ) : """Parse the outports string Valid formats : 8899 / tcp - 8899 / tcp , 22 / tcp - 22 / tcp 8899 / tcp - 8899,22 / tcp - 22 8899-8899,22-22 8899 / tcp , 22 / udp 8899,22 1:10 / tcp , 9:22 / udp 1:10,9:22 Returns a list of outport objects"""
res = [ ] ports = outports . split ( ',' ) for port in ports : if port . find ( '-' ) != - 1 and port . find ( ':' ) != - 1 : raise RADLParseException ( 'Port range (:) and port mapping (-) cannot be combined.' ) if port . find ( ':' ) != - 1 : parts = port . split ( ':' ) range_init = p...
def debug_interactive_inspect_node ( self ) : """Call after segmentation to see selected node neighborhood . User have to select one node by click . : return :"""
if ( np . sum ( np . abs ( np . asarray ( self . msinds . shape ) - np . asarray ( self . segmentation . shape ) ) ) == 0 ) : segmentation = self . segmentation else : segmentation = self . temp_msgc_resized_segmentation logger . info ( "Click to select one voxel of interest" ) import sed3 ed = sed3 . sed3 ( se...
def get_mysql_vars ( mysql : str , host : str , port : int , user : str ) -> Dict [ str , str ] : """Asks MySQL for its variables and status . Args : mysql : ` ` mysql ` ` executable filename host : host name port : TCP / IP port number user : username Returns : dictionary of MySQL variables / values"...
cmdargs = [ mysql , "-h" , host , "-P" , str ( port ) , "-e" , "SHOW VARIABLES; SHOW STATUS" , "-u" , user , "-p" # prompt for password ] log . info ( "Connecting to MySQL with user: {}" , user ) log . debug ( cmdargs ) process = subprocess . Popen ( cmdargs , stdout = subprocess . PIPE ) out , err = process . communic...
def list_balancer_members ( balancer_id , profile , ** libcloud_kwargs ) : '''List the members of a load balancer : param balancer _ id : id of a load balancer you want to fetch : type balancer _ id : ` ` str ` ` : param profile : The profile key : type profile : ` ` str ` ` : param libcloud _ kwargs : Ex...
conn = _get_driver ( profile = profile ) balancer = conn . get_balancer ( balancer_id ) libcloud_kwargs = salt . utils . args . clean_kwargs ( ** libcloud_kwargs ) members = conn . balancer_list_members ( balancer = balancer , ** libcloud_kwargs ) return [ _simple_member ( member ) for member in members ]
def _patch_chromosomal_features ( cytobands , one_chrom_match , two_chrom_match ) : """Highlight positions for each chromosome segment / feature . Parameters cytobands : pandas . DataFrame cytoband table from UCSC one _ chrom _ match : list of dicts segments to highlight on the chromosomes representing on...
chromosomes = cytobands [ "chrom" ] . unique ( ) df = pd . DataFrame ( ) for chromosome in chromosomes : chromosome_length = np . max ( cytobands [ cytobands [ "chrom" ] == chromosome ] [ "end" ] . values ) # get all markers for this chromosome one_chrom_match_markers = [ marker for marker in one_chrom_matc...
def list_dir ( self , iso_path , joliet = False ) : # type : ( str , bool ) - > Generator '''( deprecated ) Generate a list of all of the file / directory objects in the specified location on the ISO . It is recommended to use the ' list _ children ' API instead . Parameters : iso _ path - The path on the I...
if not self . _initialized : raise pycdlibexception . PyCdlibInvalidInput ( 'This object is not yet initialized; call either open() or new() to create an ISO' ) if joliet : rec = self . _get_entry ( None , None , self . _normalize_joliet_path ( iso_path ) ) else : normpath = utils . normpath ( iso_path ) ...
def _startServices ( jobGraphsWithServicesToStart , jobGraphsWithServicesThatHaveStarted , serviceJobsToStart , terminate , jobStore ) : """Thread used to schedule services ."""
servicesThatAreStarting = set ( ) servicesRemainingToStartForJob = { } serviceToJobGraph = { } while True : with throttle ( 1.0 ) : if terminate . is_set ( ) : logger . debug ( 'Received signal to quit starting services.' ) break try : jobGraph = jobGraphsWithServ...
def from_file ( cls , source , distance_weights = None , merge_same_words = False , group_marker_opening = '<<' , group_marker_closing = '>>' ) : """Read a string from a file and derive a ` ` Graph ` ` from it . This is a convenience function for opening a file and passing its contents to ` ` Graph . from _ str...
source_string = open ( source , 'r' ) . read ( ) return cls . from_string ( source_string , distance_weights , merge_same_words , group_marker_opening = group_marker_opening , group_marker_closing = group_marker_closing )
def list_public_containers ( self ) : """Returns a list of the names of all CDN - enabled containers ."""
resp , resp_body = self . api . cdn_request ( "" , "GET" ) return [ cont [ "name" ] for cont in resp_body ]
def edit_service ( self , id_ , ** kwargs ) : """Edits a service by ID . All fields available at creation can be updated as well . If you want to update hourly rates retroactively , set the argument ` update _ hourly _ rate _ on _ time _ entries ` to True ."""
data = self . _wrap_dict ( "service" , kwargs ) return self . patch ( "/services/{}.json" . format ( id_ ) , data = data )
def connect_to_images ( region = None , public = True ) : """Creates a client for working with Images ."""
return _create_client ( ep_name = "image" , region = region , public = public )
def contraction_round ( Di1 , Di2 , rc , method = 'Rennels' ) : r'''Returns loss coefficient for any any round edged pipe contraction . This calculation has three methods available . The ' Miller ' [ 2 ] _ method is a bivariate spline digitization of a graph ; the ' Idelchik ' [ 3 ] _ method is an interpolati...
beta = Di2 / Di1 if method is None : method = 'Rennels' if method == 'Rennels' : lbd = 1.0 + 0.622 * ( 1.0 - 0.30 * ( rc / Di2 ) ** 0.5 - 0.70 * rc / Di2 ) ** 4 * ( 1.0 - 0.215 * beta ** 2 - 0.785 * beta ** 5 ) return 0.0696 * ( 1.0 - 0.569 * rc / Di2 ) * ( 1.0 - ( rc / Di2 ) ** 0.5 * beta ) * ( 1.0 - beta ...
def resume_runs ( dirnames , t_output_every , t_upto , parallel = False ) : """Resume many models , and run . Parameters dirnames : list [ str ] List of output directory paths from which to resume . output _ every : int see : class : ` Runner ` . t _ upto : float Run each model until the time is equal...
run_model_partial = partial ( run_model , t_output_every , force_resume = True , t_upto = t_upto ) run_func ( run_model_partial , dirnames , parallel )
def get_authors ( repo_path , from_commit ) : """Given a repo and optionally a base revision to start from , will return the list of authors ."""
repo = dulwich . repo . Repo ( repo_path ) refs = get_refs ( repo ) start_including = False authors = set ( ) if from_commit is None : start_including = True for commit_sha , children in reversed ( get_children_per_first_parent ( repo_path ) . items ( ) ) : commit = get_repo_object ( repo , commit_sha ) if ...
def sign ( self , method , params ) : """Calculate signature with the SIG _ METHOD ( HMAC - SHA1) Returns a base64 encoeded string of the hex signature : param method : the http verb : param params : the params needs calculate"""
query_str = utils . percent_encode ( params . items ( ) , True ) str_to_sign = "{0}&%2F&{1}" . format ( method , utils . percent_quote ( query_str ) ) sig = hmac . new ( utils . to_bytes ( self . _secret_key + "&" ) , utils . to_bytes ( str_to_sign ) , hashlib . sha1 ) return base64 . b64encode ( sig . digest ( ) )
def get_api_url ( self ) : """gets a canonical path to the api detail url of the video on the hub : return : the path to the api detail of the video : rtype : str"""
url = getattr ( settings , 'VIDEOHUB_API_URL' , None ) # Support alternate setting ( used by most client projects ) if not url : url = getattr ( settings , 'VIDEOHUB_API_BASE_URL' , None ) if url : url = url . rstrip ( '/' ) + '/videos/{}' if not url : url = self . DEFAULT_VIDEOHUB_API_URL return ur...
def update_anomalous_score ( self ) : """Update anomalous score . New anomalous score is a weighted average of differences between current summary and reviews . The weights come from credibilities . Therefore , the new anomalous score of reviewer : math : ` p ` is as . . math : : { \\ rm anomalous } ( r )...
products = self . _graph . retrieve_products ( self ) diffs = [ p . summary . difference ( self . _graph . retrieve_review ( self , p ) ) for p in products ] old = self . anomalous_score try : self . anomalous_score = np . average ( diffs , weights = list ( map ( self . _credibility , products ) ) ) except ZeroDivi...
def as_ul ( self , current_linkable = False , class_current = "active_link" , before_1 = "" , after_1 = "" , before_all = "" , after_all = "" ) : """It returns menu as ul"""
return self . __do_menu ( "as_ul" , current_linkable , class_current , before_1 = before_1 , after_1 = after_1 , before_all = before_all , after_all = after_all )
def get_stp_mst_detail_output_msti_port_oper_root_guard ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_stp_mst_detail = ET . Element ( "get_stp_mst_detail" ) config = get_stp_mst_detail output = ET . SubElement ( get_stp_mst_detail , "output" ) msti = ET . SubElement ( output , "msti" ) instance_id_key = ET . SubElement ( msti , "instance-id" ) instance_id_key . text = kwargs . pop...
async def async_get_forecast ( self ) -> List [ SmhiForecast ] : """Returns a list of forecasts . The first in list are the current one"""
json_data = await self . _api . async_get_forecast_api ( self . _longitude , self . _latitude ) return _get_forecast ( json_data )
def _udf_cell ( args , js ) : """Implements the bigquery _ udf cell magic for ipython notebooks . The supported syntax is : % % bigquery udf - - module < var > < js function > Args : args : the optional arguments following ' % % bigquery udf ' . js : the UDF declaration ( inputs and outputs ) and implem...
variable_name = args [ 'module' ] if not variable_name : raise Exception ( 'Declaration must be of the form %%bigquery udf --module <variable name>' ) # Parse out the input and output specification spec_pattern = r'\{\{([^}]+)\}\}' spec_part_pattern = r'[a-z_][a-z0-9_]*' specs = re . findall ( spec_pattern , js ) i...
def set_score ( self , member , score , pipe = None ) : """Set the score of * member * to * score * ."""
pipe = self . redis if pipe is None else pipe pipe . zadd ( self . key , { self . _pickle ( member ) : float ( score ) } )
def get_static ( self , _ , file_name = None ) : """Get static content for UI ."""
content_type = { 'ss' : 'text/css' , 'js' : 'application/javascript' , } . get ( file_name [ - 2 : ] ) if not content_type : raise HttpError ( HTTPStatus . NOT_FOUND , 42 ) return HttpResponse ( self . load_static ( file_name ) , headers = { 'Content-Type' : content_type , 'Content-Encoding' : 'gzip' , 'Cache-Contr...
def set_instructions ( self , instructions ) : """Set the instructions : param instructions : the list of instructions : type instructions : a list of : class : ` Instruction `"""
if self . code == None : return [ ] return self . code . get_bc ( ) . set_instructions ( instructions )
def __get_all_ids ( self ) : '''Returns all ids'''
if self . __all_ids is None : parent_id = parsers . get_parent_id ( self . __chebi_id ) self . __all_ids = parsers . get_all_ids ( self . __chebi_id if math . isnan ( parent_id ) else parent_id ) if self . __all_ids is None : self . __all_ids = [ ] return self . __all_ids
def remove ( self , option ) : """Removes the first ` option ` from the Combo . Returns ` True ` if an item was removed . : param string option : The option to remove from the Combo ."""
if option in self . _options : if len ( self . _options ) == 1 : # this is the last option in the list so clear it self . clear ( ) else : self . _options . remove ( option ) self . _refresh_options ( ) # have we just removed the selected option ? # if so set it to the fi...
def eta_from_seebeck ( seeb , Lambda ) : """It takes a value of seebeck and adjusts the analytic seebeck until it ' s equal Returns : eta where the two seebeck coefficients are equal ( reduced chemical potential )"""
from scipy . optimize import fsolve out = fsolve ( lambda x : ( seebeck_spb ( x , Lambda ) - abs ( seeb ) ) ** 2 , 1. , full_output = True ) return out [ 0 ] [ 0 ]
def _synthesize ( self ) : """Assigns all placeholder labels to actual values and implicitly declares the ` ` ro ` ` register for backwards compatibility . Changed in 1.9 : Either all qubits must be defined or all undefined . If qubits are undefined , this method will not help you . You must explicitly call `...
self . _synthesized_instructions = instantiate_labels ( self . _instructions ) self . _synthesized_instructions = implicitly_declare_ro ( self . _synthesized_instructions ) return self
def get_release_environment ( self , project , release_id , environment_id ) : """GetReleaseEnvironment . [ Preview API ] Get a release environment . : param str project : Project ID or project name : param int release _ id : Id of the release . : param int environment _ id : Id of the release environment ....
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if release_id is not None : route_values [ 'releaseId' ] = self . _serialize . url ( 'release_id' , release_id , 'int' ) if environment_id is not None : route_values [ 'environmen...
def seek_file_end ( file ) : '''Seek to the end of the file .'''
try : file . seek ( 0 , 2 ) except ValueError : # gzip files don ' t support seek from end while True : data = file . read ( 4096 ) if not data : break
def receive_device_value ( self , raw_value : int ) : """Set a new value , called from within the joystick implementation class when parsing the event queue . : param raw _ value : the raw value from the joystick hardware : internal :"""
new_value = self . _input_to_raw_value ( raw_value ) self . __value = new_value if new_value > self . max : self . max = new_value elif new_value < self . min : self . min = new_value
def log_every_n ( n , level , message , * args ) : # pylint : disable = invalid - name """Logs a message every n calls . See _ log _ every _ n _ to _ logger ."""
return _log_every_n_to_logger ( n , None , level , message , * args )
def ns ( ns ) : """Class decorator that sets default tags namespace to use with its instances ."""
def setup_ns ( cls ) : setattr ( cls , ENTITY_DEFAULT_NS_ATTR , ns ) return cls return setup_ns