signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def parse_result ( cls , result ) : """Parse a simple items result . May either be two item tuple containing items and a context dictionary ( see : relation convention ) or a list of items ."""
if isinstance ( result , tuple ) == 2 : items , context = result else : context = { } items = result return items , context
def normalize ( self , path ) : """Return the normalized path ( on the server ) of a given path . This can be used to quickly resolve symbolic links or determine what the server is considering to be the " current folder " ( by passing C { ' . ' } as C { path } ) . @ param path : path to be normalized @ ty...
path = self . _adjust_cwd ( path ) self . _log ( DEBUG , 'normalize(%r)' % path ) t , msg = self . _request ( CMD_REALPATH , path ) if t != CMD_NAME : raise SFTPError ( 'Expected name response' ) count = msg . get_int ( ) if count != 1 : raise SFTPError ( 'Realpath returned %d results' % count ) return _to_unic...
def set_left_colon ( self , show_colon ) : """Turn the left colon on with show color True , or off with show colon False . Only the large 1.2 " 7 - segment display has a left colon ."""
if show_colon : self . buffer [ 4 ] |= 0x04 self . buffer [ 4 ] |= 0x08 else : self . buffer [ 4 ] &= ( ~ 0x04 ) & 0xFF self . buffer [ 4 ] &= ( ~ 0x08 ) & 0xFF
def _get_bounds ( self , ib , dimension ) : """ib = = 0/1 means lower / upper bound , return a vector of length ` dimension `"""
sign_ = 2 * ib - 1 assert sign_ ** 2 == 1 if self . bounds is None or self . bounds [ ib ] is None : return array ( dimension * [ sign_ * np . Inf ] ) res = [ ] for i in xrange ( dimension ) : res . append ( self . bounds [ ib ] [ min ( [ i , len ( self . bounds [ ib ] ) - 1 ] ) ] ) if res [ - 1 ] is None :...
def save ( self , status = None ) : """Save object to persistent storage ."""
if self . model is None : raise WorkflowsMissingModel ( ) with db . session . begin_nested ( ) : self . model . modified = datetime . now ( ) if status is not None : self . model . status = status if self . model . extra_data is None : self . model . extra_data = dict ( ) flag_modifi...
def logon ( self , password = 'admin' ) : """Parameters password : str default ' admin ' Returns dict"""
r = self . _basic_post ( url = 'logon' , data = password ) return r . json ( )
def implicify_hydrogens ( self ) : """remove explicit hydrogens if possible : return : number of removed hydrogens"""
total = 0 for ml in ( self . __reagents , self . __reactants , self . __products ) : for m in ml : if hasattr ( m , 'implicify_hydrogens' ) : total += m . implicify_hydrogens ( ) if total : self . flush_cache ( ) return total
def authcode_get ( self , path , ** kwargs ) : """Perform an HTTP GET to okcupid . com using this profiles session where the authcode is automatically added as a query parameter ."""
kwargs . setdefault ( 'params' , { } ) [ 'authcode' ] = self . authcode return self . _session . okc_get ( path , ** kwargs )
def rename_keys ( record : Mapping , key_map : Mapping ) -> dict : """New record with same keys or renamed keys if key found in key _ map ."""
new_record = dict ( ) for k , v in record . items ( ) : key = key_map [ k ] if k in key_map else k new_record [ key ] = v return new_record
def attach ( self , handle , filters = None , resolution = None ) : """Attach to an existing SignalFlow computation ."""
params = self . _get_params ( filters = filters , resolution = resolution ) c = computation . Computation ( lambda since : self . _transport . attach ( handle , params ) ) self . _computations . add ( c ) return c
def acquisition_source ( self , key , value ) : """Populate the ` ` acquisition _ source ` ` key ."""
def _get_datetime ( value ) : d_value = force_single_element ( value . get ( 'd' , '' ) ) if d_value : try : date = PartialDate . loads ( d_value ) except ValueError : return d_value else : datetime_ = datetime ( year = date . year , month = date . mon...
def get_initial_RAM ( self ) : """init the Dragon RAM See : http : / / archive . worldofdragon . org / phpBB3 / viewtopic . php ? f = 5 & t = 4444"""
mem_FF = [ 0xff for _ in xrange ( 4 ) ] mem_00 = [ 0x00 for _ in xrange ( 4 ) ] mem = [ ] for _ in xrange ( self . RAM_SIZE // 8 ) : mem += mem_FF mem += mem_00 return mem
def epsilon ( data , correction = 'gg' ) : """Epsilon adjustement factor for repeated measures . Parameters data : pd . DataFrame DataFrame containing the repeated measurements . ` ` data ` ` must be in wide - format . To convert from wide to long format , use the : py : func : ` pandas . pivot _ table ` ...
# Covariance matrix S = data . cov ( ) n = data . shape [ 0 ] k = data . shape [ 1 ] # Lower bound if correction == 'lb' : if S . columns . nlevels == 1 : return 1 / ( k - 1 ) elif S . columns . nlevels == 2 : ka = S . columns . levels [ 0 ] . size kb = S . columns . levels [ 1 ] . size ...
def GetZipInfo ( self ) : """Retrieves the ZIP info object . Returns : zipfile . ZipInfo : a ZIP info object or None if not available . Raises : PathSpecError : if the path specification is incorrect ."""
if not self . _zip_info : location = getattr ( self . path_spec , 'location' , None ) if location is None : raise errors . PathSpecError ( 'Path specification missing location.' ) if not location . startswith ( self . _file_system . LOCATION_ROOT ) : raise errors . PathSpecError ( 'Invalid l...
def _add_hard_link_to_rec ( self , old_rec , boot_catalog_old , ** kwargs ) : # type : ( Any , bool , str ) - > int '''Add a hard link to the ISO . Hard links are alternate names for the same file contents that don ' t take up any additional space on the ISO . This API can be used to create hard links between t...
num_new = 0 iso_new_path = None joliet_new_path = None rr_name = b'' udf_new_path = None new_rec = None # type : Optional [ Union [ dr . DirectoryRecord , udfmod . UDFFileEntry ] ] for key in kwargs : if key == 'iso_new_path' and kwargs [ key ] is not None : num_new += 1 iso_new_path = utils . normp...
def primitive ( self , dictionary ) : """Item from Python primitive ."""
self . __dict__ = { k : v for k , v in dictionary . items ( ) if v }
def driver_send ( command , hostname = None , wait = 0.2 ) : '''Send a command ( or ` ` list ` ` of commands ) to AFNI at ` ` hostname ` ` ( defaults to local host ) Requires plugouts enabled ( open afni with ` ` - yesplugouts ` ` or set ` ` AFNI _ YESPLUGOUTS = YES ` ` in ` ` . afnirc ` ` ) If ` ` wait ` ` is ...
cmd = [ 'plugout_drive' ] if hostname : cmd += [ '-host' , hostname ] if isinstance ( command , basestring ) : command = [ command ] cmd += [ [ '-com' , x ] for x in command ] + [ '-quit' ] o = nl . run ( cmd , quiet = None , stderr = None ) if wait != None : time . sleep ( wait )
def _updateWidgets ( self ) : """Updates the combo and spin boxes given the new rti or axes . Emits the sigContentsChanged signal ."""
row = 0 model = self . tree . model ( ) # Create path label nodePath = '' if self . rti is None else self . rti . nodePath pathItem = QtGui . QStandardItem ( nodePath ) pathItem . setToolTip ( nodePath ) pathItem . setEditable ( False ) if self . rti is not None : pathItem . setIcon ( self . rti . decoration ) mode...
def _summarize_accessible_fields ( field_descriptions , width = 40 , section_title = 'Accessible fields' ) : """Create a summary string for the accessible fields in a model . Unlike ` _ toolkit _ repr _ print ` , this function does not look up the values of the fields , it just formats the names and description...
key_str = "{:<{}}: {}" items = [ ] items . append ( section_title ) items . append ( "-" * len ( section_title ) ) for field_name , field_desc in field_descriptions . items ( ) : items . append ( key_str . format ( field_name , width , field_desc ) ) return "\n" . join ( items )
def nucmer_hits_to_ref_and_qry_coords ( cls , nucmer_hits , contig = None ) : '''Same as nucmer _ hits _ to _ ref _ coords , except removes containing hits first , and returns ref and qry coords lists'''
if contig is None : ctg_coords = { key : [ ] for key in nucmer_hits . keys ( ) } else : ctg_coords = { contig : [ ] } ref_coords = { } for key in ctg_coords : hits = copy . copy ( nucmer_hits [ key ] ) hits . sort ( key = lambda x : len ( x . ref_coords ( ) ) ) if len ( hits ) > 1 : i = 0 ...
def orthologize ( ast , bo , species_id : str ) : """Recursively orthologize BEL Entities in BEL AST using API endpoint NOTE : - will take first ortholog returned in BEL . bio API result ( which may return more than one ortholog ) Args : ast ( BEL ) : BEL AST endpoint ( str ) : endpoint url with a placehold...
# if species _ id = = ' TAX : 9606 ' and str ( ast ) = = ' MGI : Sult2a1 ' : # import pdb ; pdb . set _ trace ( ) if not species_id : bo . validation_messages . append ( ( "WARNING" , "No species id was provided for orthologization" ) ) return ast if isinstance ( ast , NSArg ) : if ast . orthologs : # log ....
def output_format_lock ( self , packages , ** kwargs ) : """Text to lock file"""
self . _output_config [ 'type' ] = PLAIN text = '' tmp_packages = OrderedDict ( ) columns = self . _config . get_columns ( ) widths = { } for _pkg in packages . values ( ) : _pkg_name = _pkg . package_name _params = _pkg . get_params ( columns , merged = True , raw = False ) if _pkg_name not in tmp_packages...
async def _capability_negotiated ( self , capab ) : """Mark capability as negotiated , and end negotiation if we ' re done ."""
self . _capabilities_negotiating . discard ( capab ) if not self . _capabilities_requested and not self . _capabilities_negotiating : await self . rawmsg ( 'CAP' , 'END' )
def touidref ( src , dst , src_relation , src_portal_type , fieldname ) : """Convert an archetypes reference in src / src _ relation to a UIDReference in dst / fieldname ."""
field = dst . getField ( fieldname ) refs = src . getRefs ( relationship = src_relation ) if len ( refs ) == 1 : value = get_uid ( refs [ 0 ] ) elif len ( refs ) > 1 : value = filter ( lambda x : x , [ get_uid ( ref ) for ref in refs ] ) else : value = field . get ( src ) if not value : value = '' if no...
def find_dunder_version_in_file ( self , full_path ) : # type : ( str ) - > Dict [ str , str ] """Find _ _ version _ _ in a source file : param full _ path : : return :"""
versions = { } with self . file_opener . open_this ( full_path , "r" ) as infile : for line in infile : version , _ = dunder_version . find_in_line ( line ) if version : versions [ full_path ] = version version , _ = dunder_version . find_in_line ( line ) return versions
def Page ( QLExportable ) : '''For multi - page files , e . g . if pdf preview'''
def __init__ ( self , filename , page_id ) : self . id = page_id super ( Page , self ) . __init__ ( filename ) def export ( self , export_format = ExportFormat . PNG ) : pass
def download ( self ) : """Download SRA files . Returns : : obj : ` list ` of : obj : ` str ` : List of downloaded files ."""
self . downloaded_paths = list ( ) for path in self . paths_for_download : downloaded_path = list ( ) utils . mkdir_p ( os . path . abspath ( self . directory ) ) sra_run = path . split ( "/" ) [ - 1 ] logger . info ( "Analysing %s" % sra_run ) url = type ( self ) . FTP_ADDRESS_TPL . format ( range_...
def createTable ( self , tableName , path = None , source = None , schema = None , ** options ) : """Creates a table based on the dataset in a data source . It returns the DataFrame associated with the table . The data source is specified by the ` ` source ` ` and a set of ` ` options ` ` . If ` ` source ` ` ...
if path is not None : options [ "path" ] = path if source is None : source = self . _sparkSession . _wrapped . _conf . defaultDataSourceName ( ) if schema is None : df = self . _jcatalog . createTable ( tableName , source , options ) else : if not isinstance ( schema , StructType ) : raise TypeE...
def clear ( self , context = None ) : """Delete all data from the graph ."""
context = URIRef ( context ) . n3 ( ) if context is not None else '?g' query = """ DELETE { GRAPH %s { ?s ?p ?o } } WHERE { GRAPH %s { ?s ?p ?o } } """ % ( context , context ) self . parent . graph . update ( query )
def get_attribute ( self , attribute ) : """: param attribute : requested attributes . : return : attribute value . : raise TgnError : if invalid attribute ."""
value = self . api . getAttribute ( self . obj_ref ( ) , attribute ) # IXN returns ' : : ixNet : : OK ' for invalid attributes . We want error . if value == '::ixNet::OK' : raise TgnError ( self . ref + ' does not have attribute ' + attribute ) return str ( value )
def plotter ( path , show , goodFormat ) : '''makes some plots creates binned histograms of the results of each module ( ie count of results in ranges [ ( 0,40 ) , ( 40 , 50 ) , ( 50,60 ) , ( 60 , 70 ) , ( 70 , 80 ) , ( 80 , 90 ) , ( 90 , 100 ) ] ) Arguments : path { str } - - path to save plots to show {...
for module in goodFormat . items ( ) : # for each module bins = [ 0 , 40 , 50 , 60 , 70 , 80 , 90 , 100 ] # cut the data into bins out = pd . cut ( module [ 1 ] , bins = bins , include_lowest = True ) ax = out . value_counts ( ) . plot . bar ( rot = 0 , color = "b" , figsize = ( 10 , 6 ) , alpha = 0.5 ,...
def get_tensor_size ( self , tensor_name , partial_layout = None , mesh_dimension_to_size = None ) : """The size of a tensor in bytes . If partial _ layout is specified , then mesh _ dimension _ to _ size must also be . In this case , the size on a single device is returned . Args : tensor _ name : a string...
return ( self . get_tensor_dtype ( tensor_name ) . size * self . get_tensor_num_entries ( tensor_name , partial_layout , mesh_dimension_to_size ) )
def new_linsolver ( name , prop ) : """Creates a linear solver . Parameters name : string prop : string Returns solver : : class : ` LinSolver < optalg . lin _ solver . LinSolver > `"""
if name == 'mumps' : return LinSolverMUMPS ( prop ) elif name == 'superlu' : return LinSolverSUPERLU ( prop ) elif name == 'umfpack' : return LinSolverUMFPACK ( prop ) elif name == 'default' : try : return new_linsolver ( 'mumps' , prop ) except ImportError : return new_linsolver ( '...
def _setNodeData ( self , name , metadata , data , channel = None ) : """Returns a data point from data"""
nodeChannel = None if name in metadata : nodeChannelList = metadata [ name ] if len ( nodeChannelList ) > 1 : nodeChannel = channel if channel is not None else nodeChannelList [ 0 ] elif len ( nodeChannelList ) == 1 : nodeChannel = nodeChannelList [ 0 ] if nodeChannel is not None and nod...
def repr_failure ( self , excinfo ) : """called when self . runtest ( ) raises an exception ."""
exc = excinfo . value cc = self . colors if isinstance ( exc , NbCellError ) : msg_items = [ cc . FAIL + "Notebook cell execution failed" + cc . ENDC ] formatstring = ( cc . OKBLUE + "Cell %d: %s\n\n" + "Input:\n" + cc . ENDC + "%s\n" ) msg_items . append ( formatstring % ( exc . cell_num , str ( exc ) , ex...
def mouseGestureHandler ( self , info ) : """This is the callback for MouseClickContext . Passed to VideoWidget as a parameter"""
print ( self . pre , ": mouseGestureHandler: " ) # * * * single click events * * * if ( info . fsingle ) : print ( self . pre , ": mouseGestureHandler: single click" ) if ( info . button == QtCore . Qt . LeftButton ) : print ( self . pre , ": mouseGestureHandler: Left button clicked" ) elif ( info ....
def in_cmd ( argv ) : """Run a command in the given virtualenv ."""
if len ( argv ) == 1 : return workon_cmd ( argv ) parse_envname ( argv , lambda : sys . exit ( 'You must provide a valid virtualenv to target' ) ) return inve ( * argv )
def reconciliateNs ( self , tree ) : """This function checks that all the namespaces declared within the given tree are properly declared . This is needed for example after Copy or Cut and then paste operations . The subtree may still hold pointers to namespace declarations outside the subtree or invalid / ...
if tree is None : tree__o = None else : tree__o = tree . _o ret = libxml2mod . xmlReconciliateNs ( self . _o , tree__o ) return ret
def text_has_changed ( self , text ) : """Line edit ' s text has changed"""
text = to_text_string ( text ) if text : self . lineno = int ( text ) else : self . lineno = None
def closedopen ( lower_value , upper_value ) : """Helper function to construct an interval object with a closed lower and open upper . For example : > > > closedopen ( 100.2 , 800.9) [100.2 , 800.9)"""
return Interval ( Interval . CLOSED , lower_value , upper_value , Interval . OPEN )
def format_output ( old_maps , new_maps ) : """This function takes the returned dict from ` transform ` and converts it to the same datatype as the input . Parameters old _ maps : { FieldArray , dict } The mapping object to add new maps to . new _ maps : dict A dict with key as parameter name and value ...
# if input is FieldArray then return FieldArray if isinstance ( old_maps , record . FieldArray ) : keys = new_maps . keys ( ) values = [ new_maps [ key ] for key in keys ] for key , vals in zip ( keys , values ) : try : old_maps = old_maps . add_fields ( [ vals ] , [ key ] ) exce...
def resume ( localfile , jottafile , JFS ) : """Continue uploading a new file from local file ( already exists on JottaCloud"""
with open ( localfile ) as lf : _complete = jottafile . resume ( lf ) return _complete
def delete_user ( iam_client , user , mfa_serial = None , keep_user = False , terminated_groups = [ ] ) : """Delete IAM user : param iam _ client : : param user : : param mfa _ serial : : param keep _ user : : param terminated _ groups : : return :"""
errors = [ ] printInfo ( 'Deleting user %s...' % user ) # Delete access keys try : aws_keys = get_access_keys ( iam_client , user ) for aws_key in aws_keys : try : printInfo ( 'Deleting access key ID %s... ' % aws_key [ 'AccessKeyId' ] , False ) iam_client . delete_access_key ( A...
def systemInformationType16 ( ) : """SYSTEM INFORMATION TYPE 16 Section 9.1.43d"""
a = L2PseudoLength ( l2pLength = 0x01 ) b = TpPd ( pd = 0x6 ) c = MessageType ( mesType = 0x3d ) # 00111101 d = Si16RestOctets ( ) packet = a / b / c / d return packet
def op_gen ( mcode ) : """Generate a machine instruction using the op gen table ."""
gen = op_tbl [ mcode [ 0 ] ] ret = gen [ 0 ] # opcode nargs = len ( gen ) i = 1 while i < nargs : if i < len ( mcode ) : # or assume they are same len ret |= ( mcode [ i ] & gen [ i ] [ 0 ] ) << gen [ i ] [ 1 ] i += 1 return ret
def SetDayOfWeekHasService ( self , dow , has_service = True ) : """Set service as running ( or not ) on a day of the week . By default the service does not run on any days . Args : dow : 0 for Monday through 6 for Sunday has _ service : True if this service operates on dow , False if it does not . Return...
assert ( dow >= 0 and dow < 7 ) self . day_of_week [ dow ] = has_service
def main ( ) : """Run the core ."""
parser = ArgumentParser ( ) subs = parser . add_subparsers ( dest = 'cmd' ) setup_parser = subs . add_parser ( 'setup' ) setup_parser . add_argument ( '-e' , '--email' , dest = 'email' , required = True , help = 'Email of the Google user.' , type = str ) setup_parser . add_argument ( '-p' , '--password' , dest = 'pwd' ...
def should_trace ( self , sampling_req = None ) : """Return the matched sampling rule name if the sampler finds one and decide to sample . If no sampling rule matched , it falls back to the local sampler ' s ` ` should _ trace ` ` implementation . All optional arguments are extracted from incoming requests by...
if not global_sdk_config . sdk_enabled ( ) : return False if not self . _started : self . start ( ) # only front - end that actually uses the sampler spawns poller threads now = int ( time . time ( ) ) if sampling_req and not sampling_req . get ( 'service_type' , None ) : sampling_req [ 'service_type' ] = s...
def read_csv ( path , fieldnames = None , sniff = True , encoding = 'utf-8' , * args , ** kwargs ) : '''Read CSV rows as table from a file . By default , csv . reader ( ) will be used any output will be a list of lists . If fieldnames is provided , DictReader will be used and output will be list of OrderedDict ...
return list ( r for r in read_csv_iter ( path , fieldnames = fieldnames , sniff = sniff , encoding = encoding , * args , ** kwargs ) )
def calcTemperature ( self ) : """Calculates the temperature using which uses equations . MeanPlanetTemp , albedo assumption and potentially equations . starTemperature . issues - you cant get the albedo assumption without temp but you need it to calculate the temp ."""
try : return eq . MeanPlanetTemp ( self . albedo , self . star . T , self . star . R , self . a ) . T_p except ( ValueError , HierarchyError ) : # ie missing value ( . a ) returning nan return np . nan
def ingest_from_dataframe ( self , df , ingestion_properties ) : """Ingest from pandas DataFrame . : param pandas . DataFrame df : input dataframe to ingest . : param azure . kusto . ingest . IngestionProperties ingestion _ properties : Ingestion properties ."""
from pandas import DataFrame if not isinstance ( df , DataFrame ) : raise ValueError ( "Expected DataFrame instance, found {}" . format ( type ( df ) ) ) file_name = "df_{timestamp}_{pid}.csv.gz" . format ( timestamp = int ( time . time ( ) ) , pid = os . getpid ( ) ) temp_file_path = os . path . join ( tempfile . ...
def fit ( self , X ) : """Fit the scaler based on some data . Takes the columnwise mean and standard deviation of the entire input array . If the array has more than 2 dimensions , it is flattened . Parameters X : numpy array Returns scaled : numpy array A scaled version of said array ."""
if X . ndim > 2 : X = X . reshape ( ( np . prod ( X . shape [ : - 1 ] ) , X . shape [ - 1 ] ) ) self . mean = X . mean ( 0 ) self . std = X . std ( 0 ) self . is_fit = True return self
def clear ( self , clear_indices = False ) : 'Remove all items . index names are removed if ` ` clear _ indices = = True ` ` .'
super ( MIMapping , self ) . clear ( ) if clear_indices : self . indices . clear ( ) else : for index_d in self . indices [ 1 : ] : index_d . clear ( )
async def callproc ( self , procname , args = ( ) ) : """Execute stored procedure procname with args Compatibility warning : PEP - 249 specifies that any modified parameters must be returned . This is currently impossible as they are only available by storing them in a server variable and then retrieved by ...
conn = self . _get_db ( ) if self . _echo : logger . info ( "CALL %s" , procname ) logger . info ( "%r" , args ) for index , arg in enumerate ( args ) : q = "SET @_%s_%d=%s" % ( procname , index , conn . escape ( arg ) ) await self . _query ( q ) await self . nextset ( ) _args = ',' . join ( '@_%s_%...
def instance ( cls , * args , ** kwargs ) : """Singleton getter"""
if cls . _instance is None : cls . _instance = cls ( * args , ** kwargs ) loaded = cls . _instance . reload ( ) logging . getLogger ( 'luigi-interface' ) . info ( 'Loaded %r' , loaded ) return cls . _instance
def update_model ( self , sentences , update_labels_bool ) : '''takes a list of sentenes and updates an existing model . Vectors will be callable through self . model [ label ] update _ labels _ bool : boolean that says whether to train the model ( self . model . train _ words = True ) or simply to get vector...
n_sentences = self . _add_new_labels ( sentences ) # add new rows to self . model . syn0 n = self . model . syn0 . shape [ 0 ] self . model . syn0 = np . vstack ( ( self . model . syn0 , np . empty ( ( n_sentences , self . model . layer1_size ) , dtype = np . float32 ) ) ) for i in xrange ( n , n + n_sentences ) : ...
def word_tokenize ( text , tokenizer = None , include_punc = True , * args , ** kwargs ) : """Convenience function for tokenizing text into words . NOTE : NLTK ' s word tokenizer expects sentences as input , so the text will be tokenized to sentences before being tokenized to words . This function returns an ...
_tokenizer = tokenizer if tokenizer is not None else NLTKPunktTokenizer ( ) words = chain . from_iterable ( WordTokenizer ( tokenizer = _tokenizer ) . itokenize ( sentence , include_punc , * args , ** kwargs ) for sentence in sent_tokenize ( text , tokenizer = _tokenizer ) ) return words
def run ( self ) : """Perform the specified action"""
if self . args [ 'add' ] : self . action_add ( ) elif self . args [ 'rm' ] : self . action_rm ( ) elif self . args [ 'show' ] : self . action_show ( ) elif self . args [ 'rename' ] : self . action_rename ( ) else : self . action_run_command ( )
def keys ( self ) : """: returns : a list of usable keys : rtype : list"""
keys = list ( ) for attribute_name , type_instance in inspect . getmembers ( self ) : # ignore parameters with _ _ and if they are methods if attribute_name . startswith ( '__' ) or inspect . ismethod ( type_instance ) : continue keys . append ( attribute_name ) return keys
def add ( self , * args ) : """This function adds strings to the keyboard , while not exceeding row _ width . E . g . ReplyKeyboardMarkup # add ( " A " , " B " , " C " ) yields the json result { keyboard : [ [ " A " ] , [ " B " ] , [ " C " ] ] } when row _ width is set to 1. When row _ width is set to 2 , the...
i = 1 row = [ ] for button in args : if util . is_string ( button ) : row . append ( { 'text' : button } ) elif isinstance ( button , bytes ) : row . append ( { 'text' : button . decode ( 'utf-8' ) } ) else : row . append ( button . to_dic ( ) ) if i % self . row_width == 0 : ...
def set_itunes_closed_captioned ( self ) : """Parses isClosedCaptioned from itunes tags and sets value"""
try : self . itunes_closed_captioned = self . soup . find ( 'itunes:isclosedcaptioned' ) . string self . itunes_closed_captioned = self . itunes_closed_captioned . lower ( ) except AttributeError : self . itunes_closed_captioned = None
def _insert_dLbl_in_sequence ( self , idx ) : """Return a newly created ` c : dLbl ` element having ` c : idx ` child of * idx * and inserted in numeric sequence among the ` c : dLbl ` children of this element ."""
new_dLbl = self . _new_dLbl ( ) new_dLbl . idx . val = idx dLbl = None for dLbl in self . dLbl_lst : if dLbl . idx_val > idx : dLbl . addprevious ( new_dLbl ) return new_dLbl if dLbl is not None : dLbl . addnext ( new_dLbl ) else : self . insert ( 0 , new_dLbl ) return new_dLbl
def get_invoice_payments_per_page ( self , per_page = 1000 , page = 1 , params = None ) : """Get invoice payments 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"""
if not params : params = { } return self . _get_resource_per_page ( resource = INVOICE_PAYMENTS , per_page = per_page , page = page , params = params , )
def serializer_class ( self ) : """Get the class of the child serializer . Resolves string imports ."""
serializer_class = self . _serializer_class if not isinstance ( serializer_class , six . string_types ) : return serializer_class parts = serializer_class . split ( '.' ) module_path = '.' . join ( parts [ : - 1 ] ) if not module_path : if getattr ( self , 'parent' , None ) is None : raise Exception ( "...
def toPlanarPotential ( Pot ) : """NAME : toPlanarPotential PURPOSE : convert an Potential to a planarPotential in the mid - plane ( z = 0) INPUT : Pot - Potential instance or list of such instances ( existing planarPotential instances are just copied to the output ) OUTPUT : planarPotential instance ...
Pot = flatten ( Pot ) if isinstance ( Pot , list ) : out = [ ] for pot in Pot : if isinstance ( pot , planarPotential ) : out . append ( pot ) elif isinstance ( pot , Potential ) and pot . isNonAxi : out . append ( planarPotentialFromFullPotential ( pot ) ) elif i...
def makeFrequencyGraph ( allFreqs , title , substitution , pattern , color = 'blue' , createFigure = True , showFigure = True , readsAx = False ) : """For a title , make a graph showing the frequencies . @ param allFreqs : result from getCompleteFreqs @ param title : A C { str } , title of virus of which freque...
cPattern = [ 'ACA' , 'ACC' , 'ACG' , 'ACT' , 'CCA' , 'CCC' , 'CCG' , 'CCT' , 'GCA' , 'GCC' , 'GCG' , 'GCT' , 'TCA' , 'TCC' , 'TCG' , 'TCT' ] tPattern = [ 'ATA' , 'ATC' , 'ATG' , 'ATT' , 'CTA' , 'CTC' , 'CTG' , 'CTT' , 'GTA' , 'GTC' , 'GTG' , 'GTT' , 'TTA' , 'TTC' , 'TTG' , 'TTT' ] # choose the right pattern if pattern ...
def load_from_bytecode ( self , code : str , bin_runtime : bool = False , address : Optional [ str ] = None ) -> Tuple [ str , EVMContract ] : """Returns the address and the contract class for the given bytecode : param code : Bytecode : param bin _ runtime : Whether the code is runtime code or creation code ...
if address is None : address = util . get_indexed_address ( 0 ) if bin_runtime : self . contracts . append ( EVMContract ( code = code , name = "MAIN" , enable_online_lookup = self . enable_online_lookup , ) ) else : self . contracts . append ( EVMContract ( creation_code = code , name = "MAIN" , enable_onl...
def _translate_nd ( self , source : mx . nd . NDArray , source_length : int , restrict_lexicon : Optional [ lexicon . TopKLexicon ] , raw_constraints : List [ Optional [ constrained . RawConstraintList ] ] , raw_avoid_list : List [ Optional [ constrained . RawConstraintList ] ] , max_output_lengths : mx . nd . NDArray ...
return self . _get_best_from_beam ( * self . _beam_search ( source , source_length , restrict_lexicon , raw_constraints , raw_avoid_list , max_output_lengths ) )
def load_state ( self , fname : str ) : """Loads the state of the iterator from a file . : param fname : File name to load the information from ."""
# restore order self . data = self . data . permute ( self . inverse_data_permutations ) with open ( fname , "rb" ) as fp : self . batch_indices = pickle . load ( fp ) self . curr_batch_index = pickle . load ( fp ) inverse_data_permutations = np . load ( fp ) data_permutations = np . load ( fp ) # Right...
def set_option ( self , key , subkey , value ) : """Sets the value of an option . : param str key : First identifier of the option . : param str subkey : Second identifier of the option . : param value : New value for the option ( type varies ) . : raise : : NotRegisteredError : If ` ` key ` ` or ` ` subk...
key , subkey = _lower_keys ( key , subkey ) _entry_must_exist ( self . gc , key , subkey ) df = self . gc [ ( self . gc [ "k1" ] == key ) & ( self . gc [ "k2" ] == subkey ) ] if df [ "locked" ] . values [ 0 ] : raise ValueError ( "{0}.{1} option is locked" . format ( key , subkey ) ) ev . value_eval ( value , df [ ...
def rehearse ( self , docs , sgd = None , losses = None , config = None ) : """Make a " rehearsal " update to the models in the pipeline , to prevent forgetting . Rehearsal updates run an initial copy of the model over some data , and update the model so its current predictions are more like the initial ones ...
# TODO : document if len ( docs ) == 0 : return if sgd is None : if self . _optimizer is None : self . _optimizer = create_default_optimizer ( Model . ops ) sgd = self . _optimizer docs = list ( docs ) for i , doc in enumerate ( docs ) : if isinstance ( doc , basestring_ ) : docs [ i ] =...
def legacy_networking ( self , legacy_networking ) : """Sets either QEMU legacy networking commands are used . : param legacy _ networking : boolean"""
if legacy_networking : log . info ( 'QEMU VM "{name}" [{id}] has enabled legacy networking' . format ( name = self . _name , id = self . _id ) ) else : log . info ( 'QEMU VM "{name}" [{id}] has disabled legacy networking' . format ( name = self . _name , id = self . _id ) ) self . _legacy_networking = legacy_ne...
def search_template_create ( id , body , hosts = None , profile = None ) : '''. . versionadded : : 2017.7.0 Create search template by supplied definition id Template ID body Search template definition CLI example : : salt myminion elasticsearch . search _ template _ create mytemplate ' { " template " ...
es = _get_instance ( hosts , profile ) try : result = es . put_template ( id = id , body = body ) return result . get ( 'acknowledged' , False ) except elasticsearch . TransportError as e : raise CommandExecutionError ( "Cannot create search template {0}, server returned code {1} with message {2}" . format ...
def get_page_and_url ( session , url ) : """Download an HTML page using the requests session and return the final URL after following redirects ."""
reply = get_reply ( session , url ) return reply . text , reply . url
def systemInformationType7 ( ) : """SYSTEM INFORMATION TYPE 7 Section 9.1.41"""
a = L2PseudoLength ( l2pLength = 0x01 ) b = TpPd ( pd = 0x6 ) c = MessageType ( mesType = 0x37 ) # 000110111 d = Si7RestOctets ( ) packet = a / b / c / d return packet
def seek_in_frame ( self , pos , * args , ** kwargs ) : """Seeks relative to the total offset of the current contextual frames ."""
super ( ) . seek ( self . _total_offset + pos , * args , ** kwargs )
def init_config ( self , ** kw ) : """Get a configuration object for this type of YubiKey ."""
return YubiKeyConfigUSBHID ( ykver = self . version_num ( ) , capabilities = self . capabilities , ** kw )
def update_stale ( self ) : """Update stale active statuses"""
# Some events don ' t post an inactive XML , only active . # If we don ' t get an active update for 5 seconds we can # assume the event is no longer active and update accordingly . for etype , echannels in self . event_states . items ( ) : for eprop in echannels : if eprop [ 3 ] is not None : se...
def create_point ( self , x , y ) : """Create an ECDSA point on the SECP256k1 curve with the given coords . : param x : The x coordinate on the curve : type x : long : param y : The y coodinate on the curve : type y : long"""
if ( not isinstance ( x , six . integer_types ) or not isinstance ( y , six . integer_types ) ) : raise ValueError ( "The coordinates must be longs." ) return _ECDSA_Point ( SECP256k1 . curve , x , y )
def get_children ( self ) : """: returns : A queryset of all the node ' s children"""
if self . is_leaf ( ) : return get_result_class ( self . __class__ ) . objects . none ( ) return get_result_class ( self . __class__ ) . objects . filter ( depth = self . depth + 1 , path__range = self . _get_children_path_interval ( self . path ) ) . order_by ( 'path' )
def plot_multi ( data , cols = None , spacing = .06 , color_map = None , plot_kw = None , ** kwargs ) : """Plot data with multiple scaels together Args : data : DataFrame of data cols : columns to be plotted spacing : spacing between legends color _ map : customized colors in map plot _ kw : kwargs for ...
import matplotlib . pyplot as plt from pandas import plotting if cols is None : cols = data . columns if plot_kw is None : plot_kw = [ { } ] * len ( cols ) if len ( cols ) == 0 : return num_colors = len ( utils . flatten ( cols ) ) # Get default color style from pandas colors = getattr ( getattr ( plotting ...
def remove_field ( self , field ) : """Removes a field from this table : param field : This can be a string of a field name , a dict of { ' alias ' : field } , or a ` ` Field ` ` instance : type field : str or dict or : class : ` Field < querybuilder . fields . Field > `"""
new_field = FieldFactory ( field , ) new_field . set_table ( self ) new_field_identifier = new_field . get_identifier ( ) for field in self . fields : if field . get_identifier ( ) == new_field_identifier : self . fields . remove ( field ) return field return None
def _init_field ( self , setting , field_class , name , code = None ) : """Initialize a field whether it is built with a custom name for a specific translation language or not ."""
kwargs = { "label" : setting [ "label" ] + ":" , "required" : setting [ "type" ] in ( int , float ) , "initial" : getattr ( settings , name ) , "help_text" : self . format_help ( setting [ "description" ] ) , } if setting [ "choices" ] : field_class = forms . ChoiceField kwargs [ "choices" ] = setting [ "choice...
def _to_diagonally_dominant ( mat ) : """Make matrix unweighted diagonally dominant using the Laplacian ."""
mat += np . diag ( np . sum ( mat != 0 , axis = 1 ) + 0.01 ) return mat
def _make_register ( self ) -> BaseRegisterStore : """Make the register storage ."""
s = settings . REGISTER_STORE store_class = import_class ( s [ 'class' ] ) return store_class ( ** s [ 'params' ] )
def save_imglist ( self , fname = None , root = None , shuffle = False ) : """save imglist to disk Parameters : fname : str saved filename"""
def progress_bar ( count , total , suffix = '' ) : import sys bar_len = 24 filled_len = int ( round ( bar_len * count / float ( total ) ) ) percents = round ( 100.0 * count / float ( total ) , 1 ) bar = '=' * filled_len + '-' * ( bar_len - filled_len ) sys . stdout . write ( '[%s] %s%s ...%s\r' ...
def combined_message_class ( self ) : """A ProtoRPC message class with both request and parameters fields . Caches the result in a local private variable . Uses _ CopyField to create copies of the fields from the existing request and parameters classes since those fields are " owned " by the message classes ....
if self . __combined_message_class is not None : return self . __combined_message_class fields = { } # We don ' t need to preserve field . number since this combined class is only # used for the protorpc remote . method and is not needed for the API config . # The only place field . number matters is in parameterOr...
def exclude ( self , ** attrs ) : """Remove items from distribution that are named in keyword arguments For example , ' dist . exclude ( py _ modules = [ " x " ] ) ' would remove ' x ' from the distribution ' s ' py _ modules ' attribute . Excluding packages uses the ' exclude _ package ( ) ' method , so all ...
for k , v in attrs . items ( ) : exclude = getattr ( self , '_exclude_' + k , None ) if exclude : exclude ( v ) else : self . _exclude_misc ( k , v )
def list_of_dictionaries_to_mysql_inserts ( log , datalist , tableName ) : """Convert a python list of dictionaries to pretty csv output * * Key Arguments : * * - ` ` log ` ` - - logger - ` ` datalist ` ` - - a list of dictionaries - ` ` tableName ` ` - - the name of the table to create the insert statement...
log . debug ( 'starting the ``list_of_dictionaries_to_mysql_inserts`` function' ) if not len ( datalist ) : return "NO MATCH" inserts = [ ] for d in datalist : insertCommand = convert_dictionary_to_mysql_table ( log = log , dictionary = d , dbTableName = "testing_table" , uniqueKeyList = [ ] , dateModified = Fa...
def tempallow ( ip = None , ttl = None , port = None , direction = None , comment = '' ) : '''Add an rule to the temporary ip allow list . See : func : ` _ access _ rule ` . 1 - Add an IP : CLI Example : . . code - block : : bash salt ' * ' csf . tempallow 127.0.0.1 3600 port = 22 direction = ' in ' comme...
return _tmp_access_rule ( 'tempallow' , ip , ttl , port , direction , comment )
def evaluate ( self , num_eval_batches = None ) : """Run one round of evaluation , return loss and accuracy ."""
num_eval_batches = num_eval_batches or self . num_eval_batches with tf . Graph ( ) . as_default ( ) as graph : self . tensors = self . model . build_eval_graph ( self . eval_data_paths , self . batch_size ) self . summary = tf . summary . merge_all ( ) self . saver = tf . train . Saver ( ) self . summary_wr...
def match_function_id ( self , function_id , match ) : """Matches the function identified by the given ` ` Id ` ` . arg : function _ id ( osid . id . Id ) : the Id of the ` ` Function ` ` arg : match ( boolean ) : ` ` true ` ` if a positive match , ` ` false ` ` for a negative match raise : NullArgument - `...
self . _add_match ( 'functionId' , str ( function_id ) , bool ( match ) )
def chart_range ( self ) : """Calculates the chart range from start and end . Downloads larger datasets ( 5y and 2y ) when necessary , but defaults to 1y for performance reasons"""
delta = datetime . datetime . now ( ) . year - self . start . year if 2 <= delta <= 5 : return "5y" elif 1 <= delta <= 2 : return "2y" elif 0 <= delta < 1 : return "1y" else : raise ValueError ( "Invalid date specified. Must be within past 5 years." )
def flux_down ( self , fluxDownTop , emission = None ) : '''Compute upwelling radiative flux at interfaces between layers . Inputs : * fluxUpBottom : flux up from bottom * emission : emission from atmospheric levels ( N ) defaults to zero if not given Returns : * vector of upwelling radiative flux betwe...
if emission is None : emission = np . zeros_like ( self . absorptivity ) E = np . concatenate ( ( np . atleast_1d ( fluxDownTop ) , emission ) , axis = - 1 ) # dot product ( matrix multiplication ) along last axes return np . squeeze ( matrix_multiply ( self . Tdown , E [ ... , np . newaxis ] ) )
def copy_openapi_specs ( output_path , component ) : """Copy generated and validated openapi specs to reana - commons module ."""
if component == 'reana-server' : file = 'reana_server.json' elif component == 'reana-workflow-controller' : file = 'reana_workflow_controller.json' elif component == 'reana-job-controller' : file = 'reana_job_controller.json' if os . environ . get ( 'REANA_SRCDIR' ) : reana_srcdir = os . environ . get (...
def is_all_field_none ( self ) : """: rtype : bool"""
if self . _id_ is not None : return False if self . _created is not None : return False if self . _updated is not None : return False if self . _billing_account_id is not None : return False if self . _invoice_notification_preference is not None : return False return True
def remove_item ( self , * args , ** kwargs ) : """Pass through to provider methods ."""
try : self . _get_provider_session ( 'assessment_basic_authoring_session' ) . remove_item ( * args , ** kwargs ) except InvalidArgument : self . _get_sub_package_provider_session ( 'assessment_authoring' , 'assessment_part_item_design_session' ) . remove_item ( * args , ** kwargs )
def collect_changes ( self ) : """Collect file and feature changes Steps 1 . Collects the files that have changed in this pull request as compared to a comparison branch . 2 . Categorize these file changes into admissible or inadmissible file changes . Admissible file changes solely contribute python file...
file_diffs = self . _collect_file_diffs ( ) candidate_feature_diffs , valid_init_diffs , inadmissible_diffs = self . _categorize_file_diffs ( file_diffs ) new_feature_info = self . _collect_feature_info ( candidate_feature_diffs ) return CollectedChanges ( file_diffs , candidate_feature_diffs , valid_init_diffs , inadm...
def checklat ( lat , name = 'lat' ) : """Makes sure the latitude is inside [ - 90 , 90 ] , clipping close values ( tolerance 1e - 4 ) . Parameters lat : array _ like latitude name : str , optional parameter name to use in the exception message Returns lat : ndarray or float Same as input where val...
if np . all ( np . float64 ( lat ) >= - 90 ) and np . all ( np . float64 ( lat ) <= 90 ) : return lat if np . isscalar ( lat ) : if lat > 90 and np . isclose ( lat , 90 , rtol = 0 , atol = 1e-4 ) : lat = 90 return lat elif lat < - 90 and np . isclose ( lat , - 90 , rtol = 0 , atol = 1e-4 ) :...
def save ( self ) : """Save changes made to object to NIPAP . If the object represents a new VRF unknown to NIPAP ( attribute ` id ` is ` None ` ) this function maps to the function : py : func : ` nipap . backend . Nipap . add _ vrf ` in the backend , used to create a new VRF . Otherwise it maps to the fun...
xmlrpc = XMLRPCConnection ( ) data = { 'rt' : self . rt , 'name' : self . name , 'description' : self . description , 'tags' : [ ] , 'avps' : self . avps } for tag_name in self . tags : data [ 'tags' ] . append ( tag_name ) if self . id is None : # New object , create try : vrf = xmlrpc . connection . a...