signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_parent_gradebooks ( self , gradebook_id ) : """Gets the parents of the given gradebook . arg : gradebook _ id ( osid . id . Id ) : the ` ` Id ` ` of a gradebook return : ( osid . grading . GradebookList ) - the parents of the gradebook raise : NotFound - ` ` gradebook _ id ` ` is not found raise :...
# Implemented from template for # osid . resource . BinHierarchySession . get _ parent _ bins if self . _catalog_session is not None : return self . _catalog_session . get_parent_catalogs ( catalog_id = gradebook_id ) return GradebookLookupSession ( self . _proxy , self . _runtime ) . get_gradebooks_by_ids ( list (...
def instance_for_arguments ( self , arguments : { Prior : float } ) : """Create an instance of the associated class for a set of arguments Parameters arguments : { Prior : float } Dictionary mapping _ matrix priors to attribute analysis _ path and value pairs Returns An instance of the class"""
for prior , value in arguments . items ( ) : prior . assert_within_limits ( value ) model_arguments = { t . name : arguments [ t . prior ] for t in self . direct_prior_tuples } constant_arguments = { t . name : t . constant . value for t in self . direct_constant_tuples } for tuple_prior in self . tuple_prior_tuple...
def process_soundcloud ( vargs ) : """Main SoundCloud path ."""
artist_url = vargs [ 'artist_url' ] track_permalink = vargs [ 'track' ] keep_previews = vargs [ 'keep' ] folders = vargs [ 'folders' ] id3_extras = { } one_track = False likes = False client = get_client ( ) if 'soundcloud' not in artist_url . lower ( ) : if vargs [ 'group' ] : artist_url = 'https://soundcl...
def tabSeparatedSummary ( self , sortOn = None ) : """Summarize all the alignments for this title as multi - line string with TAB - separated values on each line . @ param sortOn : A C { str } attribute to sort titles on . One of ' length ' , ' maxScore ' , ' medianScore ' , ' readCount ' , or ' title ' . @...
# The order of the fields returned here is somewhat arbitrary . The # subject titles are last because they are so variable in length . # Putting them last makes it more likely that the initial columns in # printed output will be easier to read down . # Note that post - processing scripts will be relying on the field # ...
def fit ( self , X , y = None ) : """Fit a transformation from the pipeline : param X ( DataSet ) : the data to fit"""
for columns , transformer in self . mapping : if transformer is not None : transformer . fit ( self . _get_columns ( X , columns ) ) return self
def _geocode ( self , pq ) : """: arg PlaceQuery pq : PlaceQuery object to use for geocoding : returns : list of location Candidates"""
# : List of desired output fields # : See ` ESRI docs < https : / / developers . arcgis . com / rest / geocode / api - reference / geocoding - geocode - addresses . htm > _ ` for details outFields = ( 'Loc_name' , # ' Shape ' , 'Score' , 'Match_addr' , # based on address standards for the country # ' Address ' , # retu...
def js_reverse_inline ( context ) : """Outputs a string of javascript that can generate URLs via the use of the names given to those URLs ."""
if 'request' in context : default_urlresolver = get_resolver ( getattr ( context [ 'request' ] , 'urlconf' , None ) ) else : default_urlresolver = get_resolver ( None ) return mark_safe ( generate_js ( default_urlresolver ) )
def stripe_to_db ( self , data ) : """Convert the raw value to decimal representation ."""
val = data . get ( self . name ) # Note : 0 is a possible return value , which is ' falseish ' if val is not None : return val / decimal . Decimal ( "100" )
def u2open ( self , u2request ) : """Open a connection . @ param u2request : A urllib2 request . @ type u2request : urllib2 . Requet . @ return : The opened file - like urllib2 object . @ rtype : fp"""
tm = self . options . timeout url = build_opener ( HTTPSClientAuthHandler ( self . context ) ) if self . u2ver ( ) < 2.6 : socket . setdefaulttimeout ( tm ) return url . open ( u2request ) else : return url . open ( u2request , timeout = tm )
def save ( self , force = False , uuid = False , ** kwargs ) : """REPLACES the object in DB . This is forbidden with objects from find ( ) methods unless force = True is given ."""
if not self . _initialized_with_doc and not force : raise Exception ( "Cannot save a document not initialized from a Python dict. This might remove fields from the DB!" ) self . _initialized_with_doc = False if '_id' not in self : if uuid : self [ '_id' ] = str ( "%s-%s" % ( self . mongokat_collection ....
def write_keys ( self , records_in , clean = True ) : """Write the keywords to the header . parameters records : FITSHDR or list or dict Can be one of these : - FITSHDR object - list of dictionaries containing ' name ' , ' value ' and optionally a ' comment ' field ; the order is preserved . - a dicti...
if isinstance ( records_in , FITSHDR ) : hdr = records_in else : hdr = FITSHDR ( records_in ) if clean : is_table = hasattr ( self , '_table_type_str' ) # is _ table = isinstance ( self , TableHDU ) hdr . clean ( is_table = is_table ) for r in hdr . records ( ) : name = r [ 'name' ] . upper ( ) ...
def task ( func ) : """Decorator to run the decorated function as a Task"""
def task_wrapper ( * args , ** kwargs ) : return spawn ( func , * args , ** kwargs ) return task_wrapper
def add_to_stmts_rules ( stmts , rules ) : """Use by plugins to add extra rules to the existing rules for a statement ."""
def is_rule_less_than ( ra , rb ) : rka = ra [ 0 ] rkb = rb [ 0 ] if not util . is_prefixed ( rkb ) : # old rule is non - prefixed ; append new rule after return False if not util . is_prefixed ( rka ) : # old rule prefixed , but new rule is not , insert return True # both are prefix...
def moments_match_ep ( self , data_i , tau_i , v_i , Y_metadata_i = None ) : """Moments match of the marginal approximation in EP algorithm : param i : number of observation ( int ) : param tau _ i : precision of the cavity distribution ( float ) : param v _ i : mean / variance of the cavity distribution ( fl...
sigma2_hat = 1. / ( 1. / self . variance + tau_i ) mu_hat = sigma2_hat * ( data_i / self . variance + v_i ) sum_var = self . variance + 1. / tau_i Z_hat = 1. / np . sqrt ( 2. * np . pi * sum_var ) * np . exp ( - .5 * ( data_i - v_i / tau_i ) ** 2. / sum_var ) return Z_hat , mu_hat , sigma2_hat
def _build_dependent_model_list ( self , obj_schema ) : '''Helper function to build the list of models the given object schema is referencing .'''
dep_models_list = [ ] if obj_schema : obj_schema [ 'type' ] = obj_schema . get ( 'type' , 'object' ) if obj_schema [ 'type' ] == 'array' : dep_models_list . extend ( self . _build_dependent_model_list ( obj_schema . get ( 'items' , { } ) ) ) else : ref = obj_schema . get ( '$ref' ) if ref : ref_...
def pivot_table ( self , index , columns , values = 'value' , aggfunc = 'count' , fill_value = None , style = None ) : """Returns a pivot table Parameters index : str or list of strings rows for Pivot table columns : str or list of strings columns for Pivot table values : str , default ' value ' dataf...
index = [ index ] if isstr ( index ) else index columns = [ columns ] if isstr ( columns ) else columns df = self . data # allow ' aggfunc ' to be passed as string for easier user interface if isstr ( aggfunc ) : if aggfunc == 'count' : df = self . data . groupby ( index + columns , as_index = False ) . cou...
def constants_pyx ( ) : """generate CONST = ZMQ _ CONST and _ _ all _ _ for constants . pxi"""
all_lines = [ ] assign_lines = [ ] for name in all_names : if name == "NULL" : # avoid conflict with NULL in Cython assign_lines . append ( "globals()['NULL'] = ZMQ_NULL" ) else : assign_lines . append ( '{0} = ZMQ_{0}' . format ( name ) ) all_lines . append ( ' "{0}",' . format ( name ) ) ...
def _parse_broadcast ( self , msg ) : """Given a broacast message , returns the message that was broadcast ."""
# get message , remove surrounding quotes , and unescape return self . _unescape ( self . _get_type ( msg [ self . broadcast_prefix_len : ] ) )
def image_summary ( tag , image ) : """Outputs a ` Summary ` protocol buffer with image ( s ) . Parameters tag : str A name for the generated summary . Will also serve as a series name in TensorBoard . image : MXNet ` NDArray ` or ` numpy . ndarray ` Image data that is one of the following layout : ( H , ...
tag = _clean_tag ( tag ) image = _prepare_image ( image ) image = _make_image ( image ) return Summary ( value = [ Summary . Value ( tag = tag , image = image ) ] )
def abstracts ( self , key , value ) : """Populate the ` ` abstracts ` ` key ."""
result = [ ] source = force_single_element ( value . get ( '9' ) ) for a_value in force_list ( value . get ( 'a' ) ) : result . append ( { 'source' : source , 'value' : a_value , } ) return result
def get_artifact_info ( self ) : """Returns a tuple composed of a : class : ` pants . java . jar . JarDependency ` describing the jar for this target and a bool indicating if this target is exportable ."""
exported = bool ( self . provides ) org = self . provides . org if exported else 'internal' name = self . provides . name if exported else self . identifier # TODO ( John Sirois ) : This should return something less than a JarDependency encapsulating just # the org and name . Perhaps a JarFamily ? return JarDependency ...
def next ( self ) : """Returns the next ( object , nextPageToken ) pair ."""
if self . _currentObject is None : raise StopIteration ( ) nextPageToken = None if self . _nextObject is not None : start = self . _getStart ( self . _nextObject ) # If start > the search anchor , move the search anchor . Otherwise , # increment the distance from the anchor . if start > self . _sear...
def line_spacing ( self ) : """The spacing between baselines of successive lines in this paragraph . A float value indicates a number of lines . A | Length | value indicates a fixed spacing . Value is contained in ` . / a : lnSpc / a : spcPts / @ val ` or ` . / a : lnSpc / a : spcPct / @ val ` . Value is | No...
lnSpc = self . lnSpc if lnSpc is None : return None if lnSpc . spcPts is not None : return lnSpc . spcPts . val return lnSpc . spcPct . val
def compute_equiv_class ( atom ) : """( atom ) - > Computes a unique integer for an atom"""
try : equiv_class = atom . number + 1000 * ( atom . charge + 10 ) + 100000 * ( atom . hcount ) + 1000000 * ( atom . weight ) except TypeError : raise ValueError , "Can't compute number from atom.number %s atom.charge %s atom.hcount %s" " atom.weight %s" % ( atom . number , atom . charge , atom . hcount , atom ....
def walk ( textRoot , currentTag , level , prefix = None , postfix = None , unwrapUntilPara = False ) : '''. . note : : This method does not cover all possible input doxygen types ! This means that when an unsupported / unrecognized doxygen tag appears in the xml listing , the * * raw xml will appear on the f...
if not currentTag : return if prefix : currentTag . insert_before ( prefix ) if postfix : currentTag . insert_after ( postfix ) children = currentTag . findChildren ( recursive = False ) indent = " " * level if currentTag . name == "orderedlist" : idx = 1 for child in children : walk ( tex...
def start_tree ( self , tree , name ) : """Skip this fixer if " _ _ future _ _ . division " is already imported ."""
super ( FixDivisionSafe , self ) . start_tree ( tree , name ) self . skip = "division" in tree . future_features
def _slice_bam ( in_bam , region , tmp_dir , config ) : """Use sambamba to slice a bam region"""
name_file = os . path . splitext ( os . path . basename ( in_bam ) ) [ 0 ] out_file = os . path . join ( tmp_dir , os . path . join ( tmp_dir , name_file + _to_str ( region ) + ".bam" ) ) sambamba = config_utils . get_program ( "sambamba" , config ) region = _to_sambamba ( region ) with file_transaction ( out_file ) as...
def log_update ( self , service , to_update , status , count ) : """lets log everything at the end : param service : service object : param to _ update : boolean to check if we have to update : param status : is everything worked fine ? : param count : number of data to update : type service : service obj...
if to_update : if status : msg = "{} - {} new data" . format ( service , count ) update_result ( service . id , msg = "OK" , status = status ) logger . info ( msg ) else : msg = "{} AN ERROR OCCURS " . format ( service ) update_result ( service . id , msg = msg , status =...
def _weighted_formula ( form , weight_func ) : """Yield weight of each formula element ."""
for e , mf in form . items ( ) : if e == Atom . H : continue yield e , mf , weight_func ( e )
def _identify_eds_ing ( first , second ) : """Find nodes connecting adjacent edges . Args : first ( Edge ) : Edge object representing the first edge . second ( Edge ) : Edge object representing the second edge . Returns : tuple [ int , int , set [ int ] ] : The first two values represent left and right no...
A = set ( [ first . L , first . R ] ) A . update ( first . D ) B = set ( [ second . L , second . R ] ) B . update ( second . D ) depend_set = A & B left , right = sorted ( list ( A ^ B ) ) return left , right , depend_set
def get_file_descriptor ( self ) : """Returns the file descriptor used for passing to the select call when listening on the message queue ."""
return self . _subscription . connection and self . _subscription . connection . _sock . fileno ( )
def spmatrix ( self , reordered = True , symmetric = False ) : """Converts the : py : class : ` cspmatrix ` : math : ` A ` to a sparse matrix . A reordered matrix is returned if the optional argument ` reordered ` is ` True ` ( default ) , and otherwise the inverse permutation is applied . Only the default op...
n = self . symb . n snptr = self . symb . snptr snode = self . symb . snode relptr = self . symb . relptr snrowidx = self . symb . snrowidx sncolptr = self . symb . sncolptr blkptr = self . symb . blkptr blkval = self . blkval if self . is_factor : if symmetric : raise ValueError ( "'symmetric = True' not i...
def _write ( self , f ) : """Serialize an NDEF record to a file - like object ."""
log . debug ( "writing ndef record at offset {0}" . format ( f . tell ( ) ) ) record_type = self . type record_name = self . name record_data = self . data if record_type == '' : header_flags = 0 ; record_name = '' ; record_data = '' elif record_type . startswith ( "urn:nfc:wkt:" ) : header_flags = 1 ; ...
def fetch ( self , minutes = values . unset , start_date = values . unset , end_date = values . unset , task_channel = values . unset ) : """Fetch a WorkerStatisticsInstance : param unicode minutes : Filter cumulative statistics by up to ' x ' minutes in the past . : param datetime start _ date : Filter cumulat...
return self . _proxy . fetch ( minutes = minutes , start_date = start_date , end_date = end_date , task_channel = task_channel , )
def get_group_for_col ( self , table_name , col_name ) : """Check data model to find group name for a given column header Parameters table _ name : str col _ name : str Returns group _ name : str"""
df = self . dm [ table_name ] try : group_name = df . loc [ col_name , 'group' ] except KeyError : return '' return group_name
def _read_para_reg_failed ( self , code , cbit , clen , * , desc , length , version ) : """Read HIP REG _ FAILED parameter . Structure of HIP REG _ FAILED parameter [ RFC 8003 ] : 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 | Type | Length | | Lifetime | Reg Type # 1 | Reg Type...
_life = collections . namedtuple ( 'Lifetime' , ( 'min' , 'max' ) ) _mint = self . _read_unpack ( 1 ) _maxt = self . _read_unpack ( 1 ) _type = list ( ) for _ in range ( clen - 2 ) : _code = self . _read_unpack ( 1 ) _kind = _REG_FAILURE_TYPE . get ( _code ) if _kind is None : if 0 <= _code <= 200 :...
def get_pickup_time_estimates ( self , start_latitude , start_longitude , product_id = None , ) : """Get pickup time estimates for products at a given location . Parameters start _ latitude ( float ) The latitude component of a start location . start _ longitude ( float ) The longitude component of a star...
args = OrderedDict ( [ ( 'start_latitude' , start_latitude ) , ( 'start_longitude' , start_longitude ) , ( 'product_id' , product_id ) , ] ) return self . _api_call ( 'GET' , 'v1.2/estimates/time' , args = args )
def dragMoveEvent ( self , event ) : """Processes the drag drop event using the filter set by the setDragDropFilter : param event | < QDragEvent >"""
filt = self . dragDropFilter ( ) if ( filt and filt ( self , event ) ) : return super ( XTableWidget , self ) . dragMoveEvent ( event )
def convert_epoch_to_timestamp ( cls , timestamp , tsformat ) : """Converts the given float representing UNIX - epochs into an actual timestamp . : param float timestamp : Timestamp as UNIX - epochs . : param string tsformat : Format of the given timestamp . This is used to convert the timestamp from UNIX epo...
return time . strftime ( tsformat , time . gmtime ( timestamp ) )
def set_auth_request ( self , interface_id , address = None ) : """Set the authentication request field for the specified engine ."""
self . interface . set_auth_request ( interface_id , address ) self . _engine . update ( )
def get_crumbs ( self ) : """Get crumbs for navigation links . Returns : tuple : concatenated list of crumbs using these crumbs and the crumbs of the parent classes through ` ` _ _ mro _ _ ` ` ."""
crumbs = [ ] for cls in reversed ( type ( self ) . __mro__ [ 1 : ] ) : crumbs . extend ( getattr ( cls , 'crumbs' , ( ) ) ) crumbs . extend ( list ( self . crumbs ) ) return tuple ( crumbs )
def properties ( self , name = None , pk = None , category = Category . INSTANCE , ** kwargs ) : # type : ( Optional [ str ] , Optional [ str ] , Optional [ str ] , * * Any ) - > List [ Property ] """Retrieve properties . If additional ` keyword = value ` arguments are provided , these are added to the request pa...
request_params = { 'name' : name , 'id' : pk , 'category' : category } if kwargs : request_params . update ( ** kwargs ) response = self . _request ( 'GET' , self . _build_url ( 'properties' ) , params = request_params ) if response . status_code != requests . codes . ok : # pragma : no cover raise NotFoundErro...
def stop_event_loop ( self , event = None ) : """Stop an event loop . This is used to stop a blocking event loop so that interactive functions , such as ginput and waitforbuttonpress , can wait for events . Call signature : : stop _ event _ loop _ default ( self )"""
if hasattr ( self , '_event_loop' ) : if self . _event_loop . IsRunning ( ) : self . _event_loop . Exit ( ) del self . _event_loop
def on_headers ( self , response , exc = None ) : '''Websocket upgrade as ` ` on _ headers ` ` event .'''
if response . status_code == 101 : connection = response . connection request = response . request handler = request . websocket_handler if not handler : handler = WS ( ) parser = request . client . frame_parser ( kind = 1 ) consumer = partial ( WebSocketClient . create , response , hand...
def get_query ( self , q , request ) : """return a query set searching for the query string q either implement this method yourself or set the search _ field in the LookupChannel class definition"""
return Group . objects . filter ( Q ( name__icontains = q ) | Q ( description__icontains = q ) )
def generate_plates ( seed , world_name , output_dir , width , height , num_plates = 10 ) : """Eventually this method should be invoked when generation is called at asked to stop at step " plates " , it should not be a different operation : param seed : : param world _ name : : param output _ dir : : para...
elevation , plates = generate_plates_simulation ( seed , width , height , num_plates = num_plates ) world = World ( world_name , Size ( width , height ) , seed , GenerationParameters ( num_plates , - 1.0 , "plates" ) ) world . elevation = ( numpy . array ( elevation ) . reshape ( height , width ) , None ) world . plate...
def evaluate ( self , input_data , targets , return_cache = False , prediction = True ) : """Evaluate the loss function without computing gradients . * * Parameters : * * input _ data : GPUArray Data to evaluate targets : GPUArray Targets return _ cache : bool , optional Whether to return intermediary...
# Forward pass activations , hidden_cache = self . feed_forward ( input_data , return_cache = True , prediction = prediction ) loss = self . top_layer . train_error ( None , targets , average = False , cache = activations , prediction = prediction ) for hl in self . hidden_layers : if hl . l1_penalty_weight : ...
def augment_usage_errors ( ctx , param = None ) : """Context manager that attaches extra information to exceptions that fly ."""
try : yield except BadParameter as e : if e . ctx is None : e . ctx = ctx if param is not None and e . param is None : e . param = param raise except UsageError as e : if e . ctx is None : e . ctx = ctx raise
def windows_df ( self ) : """Get Windows ( W ) W - row , W - col and W - index of windows e . g . loaded with : meth : ` block _ windows ` as a dataframe . Returns : [ dataframe ] - - A dataframe with the window information and indices ( row , col , index ) ."""
import pandas as pd if self . windows is None : raise Exception ( "You need to call the block_windows or windows before." ) df_wins = [ ] for row , col , win in zip ( self . windows_row , self . windows_col , self . windows ) : df_wins . append ( pd . DataFrame ( { "row" : [ row ] , "col" : [ col ] , "Window" :...
def map_to_array ( pairs ) : """MAP THE ( tuid , line ) PAIRS TO A SINGLE ARRAY OF TUIDS : param pairs : : return :"""
if pairs : pairs = [ TuidMap ( * p ) for p in pairs ] max_line = max ( p . line for p in pairs ) tuids = [ None ] * max_line for p in pairs : if p . line : # line = = 0 IS A PLACEHOLDER FOR FILES THAT DO NOT EXIST tuids [ p . line - 1 ] = p . tuid return tuids else : return N...
def _build_model ( self ) : """Build the model ."""
# Set up LSTM modules self . lstms = nn . ModuleList ( [ RNN ( num_classes = 0 , num_tokens = self . word_dict . s , emb_size = self . settings [ "emb_dim" ] , lstm_hidden = self . settings [ "hidden_dim" ] , attention = self . settings [ "attention" ] , dropout = self . settings [ "dropout" ] , bidirectional = self . ...
def morpho ( self , m ) : """Renvoie la chaîne de rang m dans la liste des morphologies donnée par le fichier data / morphos . la : param m : Indice de morphologie : type m : int : return : Chaîne de rang m dans la liste des morphologies donnée par le fichier data / morphos . la : rtype : str"""
l = "fr" # TODO : Si ajout langue de traduction , il faudra convertir ce qui suit # if self . _ morphos . keys ( ) . contains ( _ cible . mid ( 0,2 ) ) ) l = _ cible . mid ( 0,2: # elif ( _ cible . size ( ) > 4 ) and ( _ morphos . keys ( ) . contains ( _ cible . mid ( 3,2 ) ) ) : # l = _ cible . mid ( 3,2) if m < 0 or ...
def Emulation_setVisibleSize ( self , width , height ) : """Function path : Emulation . setVisibleSize Domain : Emulation Method name : setVisibleSize WARNING : This function is marked ' Experimental ' ! Parameters : Required arguments : ' width ' ( type : integer ) - > Frame width ( DIP ) . ' height ...
assert isinstance ( width , ( int , ) ) , "Argument 'width' must be of type '['int']'. Received type: '%s'" % type ( width ) assert isinstance ( height , ( int , ) ) , "Argument 'height' must be of type '['int']'. Received type: '%s'" % type ( height ) subdom_funcs = self . synchronous_command ( 'Emulation.setVisibleSi...
def com_google_fonts_check_metadata_match_weight_postscript ( font_metadata ) : """METADATA . pb weight matches postScriptName ."""
WEIGHTS = { "Thin" : 100 , "ThinItalic" : 100 , "ExtraLight" : 200 , "ExtraLightItalic" : 200 , "Light" : 300 , "LightItalic" : 300 , "Regular" : 400 , "Italic" : 400 , "Medium" : 500 , "MediumItalic" : 500 , "SemiBold" : 600 , "SemiBoldItalic" : 600 , "Bold" : 700 , "BoldItalic" : 700 , "ExtraBold" : 800 , "ExtraBoldI...
def dipole ( self ) : """Calculates the dipole of the Slab in the direction of the surface normal . Note that the Slab must be oxidation state - decorated for this to work properly . Otherwise , the Slab will always have a dipole of 0."""
dipole = np . zeros ( 3 ) mid_pt = np . sum ( self . cart_coords , axis = 0 ) / len ( self ) normal = self . normal for site in self : charge = sum ( [ getattr ( sp , "oxi_state" , 0 ) * amt for sp , amt in site . species . items ( ) ] ) dipole += charge * np . dot ( site . coords - mid_pt , normal ) * normal r...
def findTargetNS ( self , node ) : """Return the defined target namespace uri for the given node ."""
attrget = self . getAttr attrkey = ( self . NS_XMLNS , 'xmlns' ) DOCUMENT_NODE = node . DOCUMENT_NODE ELEMENT_NODE = node . ELEMENT_NODE while 1 : if node . nodeType != ELEMENT_NODE : node = node . parentNode continue result = attrget ( node , 'targetNamespace' , default = None ) if result i...
def to_dict ( self ) : """Converts this embed object into a dict ."""
# add in the raw data into the dict result = { key [ 1 : ] : getattr ( self , key ) for key in self . __slots__ if key [ 0 ] == '_' and hasattr ( self , key ) } # deal with basic convenience wrappers try : colour = result . pop ( 'colour' ) except KeyError : pass else : if colour : result [ 'color' ...
def _remove_layer_and_reconnect ( self , layer ) : """Remove the layer , and reconnect each of its predecessor to each of its successor"""
successors = self . get_successors ( layer ) predecessors = self . get_predecessors ( layer ) # remove layer ' s edges for succ in successors : self . _remove_edge ( layer , succ ) for pred in predecessors : self . _remove_edge ( pred , layer ) # connect predecessors and successors for pred in predecessors : ...
def gen_ref_docs ( gen_index = False ) : # type : ( int , bool ) - > None """Generate reference documentation for the project . This will use * * sphinx - refdoc * * to generate the source . rst files for the reference documentation . Args : gen _ index ( bool ) : Set it to * * True * * if you want to gen...
try : from refdoc import generate_docs except ImportError as ex : msg = ( "You need to install sphinx-refdoc if you want to generate " "code reference docs." ) print ( msg , file = sys . stderr ) log . err ( "Exception: {}" . format ( ex ) ) sys . exit ( - 1 ) pretend = context . get ( 'pretend' , F...
def get_uses_implied_permission_list ( self ) : """Return all permissions implied by the target SDK or other permissions . : rtype : list of string"""
target_sdk_version = self . get_effective_target_sdk_version ( ) READ_CALL_LOG = 'android.permission.READ_CALL_LOG' READ_CONTACTS = 'android.permission.READ_CONTACTS' READ_EXTERNAL_STORAGE = 'android.permission.READ_EXTERNAL_STORAGE' READ_PHONE_STATE = 'android.permission.READ_PHONE_STATE' WRITE_CALL_LOG = 'android.per...
def kill_current_session ( ctx : Context_T ) -> None : """Force kill current session of the given context , despite whether it is running or not . : param ctx : message context"""
ctx_id = context_id ( ctx ) if ctx_id in _sessions : del _sessions [ ctx_id ]
def write_grid_tpl ( name , tpl_file , suffix , zn_array = None , shape = None , spatial_reference = None , longnames = False ) : """write a grid - based template file Parameters name : str the base parameter name tpl _ file : str the template file to write - include path zn _ array : numpy . ndarray ...
if shape is None and zn_array is None : raise Exception ( "must pass either zn_array or shape" ) elif shape is None : shape = zn_array . shape parnme , x , y = [ ] , [ ] , [ ] with open ( tpl_file , 'w' ) as f : f . write ( "ptf ~\n" ) for i in range ( shape [ 0 ] ) : for j in range ( shape [ 1 ...
def daemonize ( pid_file = None , cwd = None ) : """Detach a process from the controlling terminal and run it in the background as a daemon . Modified version of : code . activestate . com / recipes / 278731 - creating - a - daemon - the - python - way / author = " Chad J . Schroeder " copyright = " Copyr...
cwd = cwd or '/' try : pid = os . fork ( ) except OSError as e : raise Exception ( "%s [%d]" % ( e . strerror , e . errno ) ) if ( pid == 0 ) : # The first child . os . setsid ( ) try : pid = os . fork ( ) # Fork a second child . except OSError as e : raise Exception ( "%s [%...
def set_dict_value ( dictionary , keys , value ) : """Set a value in a ( nested ) dictionary by defining a list of keys . . . note : : Side - effects This function does not make a copy of dictionary , but directly edits it . Parameters dictionary : dict keys : List [ Any ] value : object Returns d...
orig = dictionary for key in keys [ : - 1 ] : dictionary = dictionary . setdefault ( key , { } ) dictionary [ keys [ - 1 ] ] = value return orig
def findGlyph ( self , glyphName ) : """Returns a ` ` list ` ` of the group or groups associated with * * glyphName * * . * * glyphName * * will be an : ref : ` type - string ` . If no group is found to contain * * glyphName * * an empty ` ` list ` ` will be returned . : : > > > font . groups . findGlyph ( ...
glyphName = normalizers . normalizeGlyphName ( glyphName ) groupNames = self . _findGlyph ( glyphName ) groupNames = [ self . keyNormalizer . __func__ ( groupName ) for groupName in groupNames ] return groupNames
def _get_current_migration_state ( self , loader , apps ) : """Extract the most recent migrations from the relevant apps . If no migrations have been performed , return ' zero ' as the most recent migration for the app . This should only be called from list _ migrations ( ) ."""
# Only care about applied migrations for the passed - in apps . apps = set ( apps ) relevant_applied = [ migration for migration in loader . applied_migrations if migration [ 0 ] in apps ] # Sort them by the most recent migration and convert to a dictionary , # leaving apps as keys and most recent migration as values ....
def get_hostfirmware ( self , callb = None ) : """Convenience method to request the device firmware info from the device This method will check whether the value has already been retrieved from the device , if so , it will simply return it . If no , it will request the information from the device and request ...
if self . host_firmware_version is None : mypartial = partial ( self . resp_set_hostfirmware ) if callb : mycallb = lambda x , y : ( mypartial ( y ) , callb ( x , y ) ) else : mycallb = lambda x , y : mypartial ( y ) response = self . req_with_resp ( GetHostFirmware , StateHostFirmware ,...
def clean ( cls , cpf ) : u"""Retorna apenas os dígitos do CPF . > > > CPF . clean ( ' 581.194.436-59 ' ) '58119443659'"""
if isinstance ( cpf , six . string_types ) : cpf = int ( re . sub ( '[^0-9]' , '' , cpf ) ) return '{0:011d}' . format ( cpf )
def generate_version_file ( self , schema_filename , binding_filename ) : """Given a DataONE schema , generates a file that contains version information about the schema ."""
version_filename = binding_filename + '_version.txt' version_path = os . path . join ( self . binding_dir , version_filename ) schema_path = os . path . join ( self . schema_dir , schema_filename ) try : tstamp , svnpath , svnrev , version = self . get_version_info_from_svn ( schema_path ) except TypeError : pa...
def get_objects ( self , queryset = None ) : """Return an iterator of Django model objects in Elasticsearch order , optionally using the given Django queryset . If no queryset is given , a default queryset ( Model . objects . all ) is used . : param queryset : Optional queryset to filter in . : return :"""
if not self : return if not queryset : queryset = self [ 0 ] . django_model . objects . all ( ) pks = [ res . pk for res in self if res . django_model == queryset . model ] object_map = dict ( ( text_type ( obj . pk ) , obj ) for obj in queryset . filter ( pk__in = pks ) ) result_map = dict ( ( res . pk , res )...
def get_timeseries ( self , child_agg_count = 0 , dataframe = False ) : """Get time series data for the specified fields and period of analysis : param child _ agg _ count : the child aggregation count to be used default = 0 : param dataframe : if dataframe = True , return a pandas . DataFrame object : retu...
res = self . fetch_aggregation_results ( ) ts = { "date" : [ ] , "value" : [ ] , "unixtime" : [ ] } if 'buckets' not in res [ 'aggregations' ] [ str ( self . parent_agg_counter - 1 ) ] : raise RuntimeError ( "Aggregation results have no buckets in time series results." ) for bucket in res [ 'aggregations' ] [ str (...
async def connect_to_endpoints ( self , * endpoints : ConnectionConfig ) -> None : """Connect to the given endpoints and await until all connections are established ."""
self . _throw_if_already_connected ( * endpoints ) await asyncio . gather ( * ( self . _await_connect_to_endpoint ( endpoint ) for endpoint in endpoints ) , loop = self . event_loop )
def download ( ctx ) : """Download blobs or files from Azure Storage"""
settings . add_cli_options ( ctx . cli_options , settings . TransferAction . Download ) ctx . initialize ( settings . TransferAction . Download ) specs = settings . create_download_specifications ( ctx . cli_options , ctx . config ) del ctx . cli_options for spec in specs : blobxfer . api . Downloader ( ctx . gener...
def _propagate_packages ( self ) : r"""Propogate packages . Make sure that all the packages included in the previous containers are part of the full list of packages ."""
super ( ) . _propagate_packages ( ) for item in ( self . preamble ) : if isinstance ( item , LatexObject ) : if isinstance ( item , Container ) : item . _propagate_packages ( ) for p in item . packages : self . packages . add ( p )
def is_local ( self , hadoop_conf = None , hadoop_home = None ) : """Is Hadoop configured to run in local mode ? By default , it is . [ pseudo - ] distributed mode must be explicitly configured ."""
conf = self . hadoop_params ( hadoop_conf , hadoop_home ) keys = ( 'mapreduce.framework.name' , 'mapreduce.jobtracker.address' , 'mapred.job.tracker' ) for k in keys : if conf . get ( k , 'local' ) . lower ( ) != 'local' : return False return True
def fastq_info ( path ) : """Found some info about how to ignore warnings in code blocks here : - http : / / stackoverflow . com / questions / 14463277 / how - to - disable - python - warnings"""
numBases = 0 numReads = 0 readLengths = Counter ( ) GCTot = 0 with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) handle = gzip . open ( path , "rt" ) for record in SeqIO . parse ( handle , "fastq" ) : numBases += len ( record ) numReads += 1 readLengths [ len (...
def stop ( ) : """Stop the server , invalidating any viewer URLs . This allows any previously - referenced data arrays to be garbage collected if there are no other references to them ."""
global global_server if global_server is not None : ioloop = global_server . ioloop def stop_ioloop ( ) : ioloop . stop ( ) ioloop . close ( ) global_server . ioloop . add_callback ( stop_ioloop ) global_server = None
def _packed_data ( self ) : '''Returns the bit - packed data extracted from the data file . This is not so useful to analyze . Use the complex _ data method instead .'''
header = self . header ( ) packed_data = np . frombuffer ( self . data , dtype = np . int8 ) . reshape ( ( header [ 'number_of_half_frames' ] , header [ 'half_frame_bytes' ] ) ) # create array of half frames packed_data = packed_data [ : : - 1 , constants . header_offset : ] # slice out header and flip half frame order...
def assimilate ( self , path ) : """Parses vasp runs . Then insert the result into the db . and return the task _ id or doc of the insertion . Returns : If in simulate _ mode , the entire doc is returned for debugging purposes . Else , only the task _ id of the inserted doc is returned ."""
try : d = self . get_task_doc ( path ) if self . mapi_key is not None and d [ "state" ] == "successful" : self . calculate_stability ( d ) tid = self . _insert_doc ( d ) return tid except Exception as ex : import traceback logger . error ( traceback . format_exc ( ) ) return False
def _run_program ( self , bin , fastafile , params = None ) : """Run XXmotif and predict motifs from a FASTA file . Parameters bin : str Command used to run the tool . fastafile : str Name of the FASTA input file . params : dict , optional Optional parameters . For some of the tools required parameter...
params = self . _parse_params ( params ) outfile = os . path . join ( self . tmpdir , os . path . basename ( fastafile . replace ( ".fa" , ".pwm" ) ) ) stdout = "" stderr = "" cmd = "%s %s %s --localization --batch %s %s" % ( bin , self . tmpdir , fastafile , params [ "background" ] , params [ "strand" ] , ) p = Popen ...
def uncomment ( comment ) : """Converts the comment node received to a non - commented element , in place , and will return the new node . This may fail , primarily due to special characters within the comment that the xml parser is unable to handle . If it fails , this method will log an error and return N...
parent = comment . parentNode h = html . parser . HTMLParser ( ) data = h . unescape ( comment . data ) try : node = minidom . parseString ( data ) . firstChild except xml . parsers . expat . ExpatError : # Could not parse ! log . error ( 'Could not uncomment node due to parsing error!' ) return None else :...
def easeOutElastic ( n , amplitude = 1 , period = 0.3 ) : """An elastic tween function that overshoots the destination and then " rubber bands " into the destination . Args : n ( float ) : The time progress , starting at 0.0 and ending at 1.0. Returns : ( float ) The line progress , starting at 0.0 and endi...
_checkRange ( n ) if amplitude < 1 : amplitude = 1 s = period / 4 else : s = period / ( 2 * math . pi ) * math . asin ( 1 / amplitude ) return amplitude * 2 ** ( - 10 * n ) * math . sin ( ( n - s ) * ( 2 * math . pi / period ) ) + 1
def package_install ( name , ** kwargs ) : '''Install a " package " on the ssh server'''
cmd = 'pkg_install ' + name if kwargs . get ( 'version' , False ) : cmd += ' ' + kwargs [ 'version' ] # Send the command to execute out , err = DETAILS [ 'server' ] . sendline ( cmd ) # " scrape " the output and return the right fields as a dict return parse ( out )
def page ( self , course , msg = "" , error = False ) : """Get all data and display the page"""
aggregations = OrderedDict ( ) taskids = list ( course . get_tasks ( ) . keys ( ) ) for aggregation in self . user_manager . get_course_aggregations ( course ) : aggregations [ aggregation [ '_id' ] ] = dict ( list ( aggregation . items ( ) ) + [ ( "tried" , 0 ) , ( "done" , 0 ) , ( "url" , self . submission_url_ge...
def classify ( self , url_path ) : """Classify an url"""
for dict_api_url in self . user_defined_rules : api_url = dict_api_url [ 'str' ] re_api_url = dict_api_url [ 're' ] if re_api_url . match ( url_path [ 1 : ] ) : return api_url return self . RE_SIMPLIFY_URL . sub ( r'(\\d+)/' , url_path )
def fit ( self , ** skip_gram_params ) : """Creates the embeddings using gensim ' s Word2Vec . : param skip _ gram _ params : Parameteres for gensim . models . Word2Vec - do not supply ' size ' it is taken from the Node2Vec ' dimensions ' parameter : type skip _ gram _ params : dict : return : A gensim word2v...
if 'workers' not in skip_gram_params : skip_gram_params [ 'workers' ] = self . workers if 'size' not in skip_gram_params : skip_gram_params [ 'size' ] = self . dimensions return gensim . models . Word2Vec ( self . walks , ** skip_gram_params )
import re def discard_lowercase ( input_string ) : """This function discards lowercase characters from a given string using regex . Examples : discard _ lowercase ( ' KDeoALOklOOHserfLoAJSIskdsf ' ) - > ' KDALOOOHLAJSI ' discard _ lowercase ( ' ProducTnamEstreAmIngMediAplAYer ' ) - > ' PTEAIMAAY ' discard _...
remove_lower_case = ( lambda text : re . sub ( '[a-z]' , '' , text ) ) return remove_lower_case ( input_string )
def _are_nearby_parallel_boxes ( self , b1 , b2 ) : "Are two boxes nearby , parallel , and similar in width ?"
if not self . _are_aligned_angles ( b1 . angle , b2 . angle ) : return False # Otherwise pick the smaller angle and see whether the two boxes are close according to the " up " direction wrt that angle angle = min ( b1 . angle , b2 . angle ) return abs ( np . dot ( b1 . center - b2 . center , [ - np . sin ( angle ) ...
def get_datatype ( object_type , propid , vendor_id = 0 ) : """Return the datatype for the property of an object ."""
if _debug : get_datatype . _debug ( "get_datatype %r %r vendor_id=%r" , object_type , propid , vendor_id ) # get the related class cls = get_object_class ( object_type , vendor_id ) if not cls : return None # get the property prop = cls . _properties . get ( propid ) if not prop : return None # return the d...
def create_tokenizer ( self , name , config = dict ( ) ) : """Create a pipeline component from a factory . name ( unicode ) : Factory name to look up in ` Language . factories ` . config ( dict ) : Configuration parameters to initialise component . RETURNS ( callable ) : Pipeline component ."""
if name not in self . factories : raise KeyError ( Errors . E002 . format ( name = name ) ) factory = self . factories [ name ] return factory ( self , ** config )
def set_object ( self , object , logmsg = None ) : # @ ReservedAssignment """Set the object we point to , possibly dereference our symbolic reference first . If the reference does not exist , it will be created : param object : a refspec , a SymbolicReference or an Object instance . SymbolicReferences will be...
if isinstance ( object , SymbolicReference ) : object = object . object # @ ReservedAssignment # END resolve references is_detached = True try : is_detached = self . is_detached except ValueError : pass # END handle non - existing ones if is_detached : return self . set_reference ( object , logmsg ) # s...
def define_mask_borders ( image2d , sought_value , nadditional = 0 ) : """Generate mask avoiding undesired values at the borders . Set to True image borders with values equal to ' sought _ value ' Parameters image2d : numpy array Initial 2D image . sought _ value : int , float , bool Pixel value that in...
# input image size naxis2 , naxis1 = image2d . shape # initialize mask mask2d = np . zeros ( ( naxis2 , naxis1 ) , dtype = bool ) # initialize list to store borders borders = [ ] for i in range ( naxis2 ) : # only spectra with values different from ' sought _ value ' jborder_min , jborder_max = find_pix_borders ( i...
def update_layers_esri_imageserver ( service ) : """Update layers for an ESRI REST ImageServer . Sample endpoint : https : / / gis . ngdc . noaa . gov / arcgis / rest / services / bag _ bathymetry / ImageServer / ? f = json"""
try : esri_service = ArcImageService ( service . url ) # set srs # both mapserver and imageserver exposes just one srs at the service level # not sure if other ones are supported , for now we just store this one obj = json . loads ( esri_service . _contents ) srs_code = obj [ 'spatialReference' ...
def get_project ( self , project_id , include_capabilities = None , include_history = None ) : """GetProject . Get project with the specified id or name , optionally including capabilities . : param str project _ id : : param bool include _ capabilities : Include capabilities ( such as source control ) in the...
route_values = { } if project_id is not None : route_values [ 'projectId' ] = self . _serialize . url ( 'project_id' , project_id , 'str' ) query_parameters = { } if include_capabilities is not None : query_parameters [ 'includeCapabilities' ] = self . _serialize . query ( 'include_capabilities' , include_capab...
def print_file ( self , file_format = 'ctfile' , f = sys . stdout ) : """Print representation of : class : ` ~ ctfile . ctfile . CTfile ` . : param str file _ format : Format to use : ` ` ctfile ` ` or ` ` json ` ` . : param f : Print to file or stdout . : type f : File - like : return : None . : rtype : ...
print ( self . writestr ( file_format = file_format ) , file = f )
def _find_unprocessed ( config ) : """Find any finished directories that have not been processed ."""
reported = _read_reported ( config [ "msg_db" ] ) for dname in _get_directories ( config ) : if os . path . isdir ( dname ) and dname not in reported : if _is_finished_dumping ( dname ) : yield dname
def merge ( self , across = False ) : """Merge the range cells into one region in the worksheet . : param bool across : Optional . Set True to merge cells in each row of the specified range as separate merged cells ."""
url = self . build_url ( self . _endpoints . get ( 'merge_range' ) ) return bool ( self . session . post ( url , data = { 'across' : across } ) )
def bling ( self , target , sender ) : "will print yo"
if target . startswith ( "#" ) : self . message ( target , "%s: yo" % sender ) else : self . message ( sender , "yo" )
def check_valid_package ( package , cyg_arch = 'x86_64' , mirrors = None ) : '''Check if the package is valid on the given mirrors . Args : package : The name of the package cyg _ arch : The cygwin architecture mirrors : any mirrors to check Returns ( bool ) : True if Valid , otherwise False CLI Example...
if mirrors is None : mirrors = [ { DEFAULT_MIRROR : DEFAULT_MIRROR_KEY } ] LOG . debug ( 'Checking Valid Mirrors: %s' , mirrors ) for mirror in mirrors : for mirror_url , key in mirror . items ( ) : if package in _get_all_packages ( mirror_url , cyg_arch ) : return True return False
def on_change ( self , callable_ ) : """Add a change observer to this entity ."""
self . model . add_observer ( callable_ , self . entity_type , 'change' , self . entity_id )