signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def parse_conditional_derived_variable ( self , node ) : """Parses < ConditionalDerivedVariable > @ param node : Node containing the < ConditionalDerivedVariable > element @ type node : xml . etree . Element @ raise ParseError : Raised when no name or value is specified for the conditional derived variable ."...
if 'name' in node . lattrib : name = node . lattrib [ 'name' ] elif 'exposure' in node . lattrib : name = node . lattrib [ 'exposure' ] else : self . raise_error ( '<ConditionalDerivedVariable> must specify a name' ) if 'exposure' in node . lattrib : exposure = node . lattrib [ 'exposure' ] else : e...
async def addreaction ( self , ctx , * , reactor = "" ) : """Interactively adds a custom reaction"""
if not reactor : await self . bot . say ( "What should I react to?" ) response = await self . bot . wait_for_message ( author = ctx . message . author ) reactor = response . content data = self . config . get ( ctx . message . server . id , { } ) keyword = data . get ( reactor , { } ) if keyword : await...
def weighted_round_robin ( iterable ) : '''Takes an iterable of tuples of < item > , < weight > and cycles around them , returning heavier ( integer ) weighted items more frequently .'''
cyclable_list = [ ] assigned_weight = 0 still_to_process = [ ( item , weight ) for item , weight in sorted ( iterable , key = lambda tup : tup [ 1 ] , reverse = True ) ] while still_to_process : for i , ( item , weight ) in enumerate ( still_to_process ) : if weight > assigned_weight : cyclable_...
def _decode_messages ( self , messages ) : '''Take the zmq messages , decrypt / decode them into a payload : param list messages : A list of messages to be decoded'''
messages_len = len ( messages ) # if it was one message , then its old style if messages_len == 1 : payload = self . serial . loads ( messages [ 0 ] ) # 2 includes a header which says who should do it elif messages_len == 2 : if ( self . opts . get ( '__role' ) != 'syndic' and messages [ 0 ] not in ( 'broadcast...
def _call_variants ( example_dir , region_bed , data , out_file ) : """Call variants from prepared pileup examples , creating tensorflow record file ."""
tf_out_file = "%s-tfrecord.gz" % utils . splitext_plus ( out_file ) [ 0 ] if not utils . file_exists ( tf_out_file ) : with file_transaction ( data , tf_out_file ) as tx_out_file : model = "wes" if strelka2 . coverage_interval_from_bed ( region_bed ) == "targeted" else "wgs" cmd = [ "dv_call_variant...
def load ( cls , filename , project = None ) : r"""Loads data onto the given network from an appropriately formatted ' mat ' file ( i . e . MatLAB output ) . Parameters filename : string ( optional ) The name of the file containing the data to import . The formatting of this file is outlined below . pro...
filename = cls . _parse_filename ( filename = filename , ext = 'mat' ) data = spio . loadmat ( filename ) # Reinsert the ' . ' separator into the array names for item in list ( data . keys ( ) ) : if item in [ '__header__' , '__version__' , '__globals__' ] : data . pop ( item ) continue elif '_p...
def error_log ( self , msg = '' , level = 20 , traceback = False ) : """Write error message to log . Args : msg ( str ) : error message level ( int ) : logging level traceback ( bool ) : add traceback to output or not"""
# Override this in subclasses as desired sys . stderr . write ( msg + '\n' ) sys . stderr . flush ( ) if traceback : tblines = traceback_ . format_exc ( ) sys . stderr . write ( tblines ) sys . stderr . flush ( )
def handle ( self ) : """Handles a request ignoring dropped connections ."""
rv = None try : rv = BaseHTTPRequestHandler . handle ( self ) except ( _ConnectionError , socket . timeout ) as e : self . connection_dropped ( e ) except Exception as e : if self . server . ssl_context is None or not is_ssl_error ( e ) : raise if self . server . shutdown_signal : self . initiat...
def expand_includes ( text , path = '.' ) : """Recursively expands includes in given text ."""
def read_and_expand ( match ) : filename = match . group ( 'filename' ) filename = join ( path , filename ) text = read ( filename ) return expand_includes ( text , path = join ( path , dirname ( filename ) ) ) return re . sub ( r'^\.\. include:: (?P<filename>.*)$' , read_and_expand , text , flags = re ...
def is_pdf ( document ) : """Check if a document is a PDF file and return True if is is ."""
if not executable_exists ( 'pdftotext' ) : current_app . logger . warning ( "GNU file was not found on the system. " "Switching to a weak file extension test." ) if document . lower ( ) . endswith ( ".pdf" ) : return True return False # Tested with file version > = 4.10 . First test is secure and wo...
def get_crl ( self , expires = 86400 , encoding = None , algorithm = None , password = None , scope = None , ** kwargs ) : """Generate a Certificate Revocation List ( CRL ) . The ` ` full _ name ` ` and ` ` relative _ name ` ` parameters describe how to retrieve the CRL and are used in the ` Issuing Distributio...
if scope is not None and scope not in [ 'ca' , 'user' , 'attribute' ] : raise ValueError ( 'Scope must be either None, "ca", "user" or "attribute"' ) encoding = parse_encoding ( encoding ) now = now_builder = timezone . now ( ) algorithm = parse_hash_algorithm ( algorithm ) if timezone . is_aware ( now_builder ) : ...
def returnOneIndex ( self , last = False ) : '''Return the first origin index ( integer ) of the current list . That index refers to it ' s placement in the original list of dictionaries . This is very useful when one wants to reference the original entry by index . Example of use : > > > test = [ . . ....
if len ( self . table ) == 0 : return None else : if last : return self . index_track . pop ( ) else : return self . index_track [ 0 ]
def rpm ( state , host , source , present = True ) : '''Add / remove ` ` . rpm ` ` file packages . + source : filename or URL of the ` ` . rpm ` ` package + present : whether ore not the package should exist on the system URL sources with ` ` present = False ` ` : If the ` ` . rpm ` ` file isn ' t downloade...
# If source is a url if urlparse ( source ) . scheme : # Generate a temp filename ( with . rpm extension to please yum ) temp_filename = '{0}.rpm' . format ( state . get_temp_filename ( source ) ) # Ensure it ' s downloaded yield files . download ( state , host , source , temp_filename ) # Override the ...
def _linear_seaborn_ ( self , label = None , style = None , opts = None ) : """Returns a Seaborn linear regression plot"""
xticks , yticks = self . _get_ticks ( opts ) try : fig = sns . lmplot ( self . x , self . y , data = self . df ) fig = self . _set_with_height ( fig , opts ) return fig except Exception as e : self . err ( e , self . linear_ , "Can not draw linear regression chart" )
def delete_objective ( self , objective_id ) : """Deletes the ` ` Objective ` ` identified by the given ` ` Id ` ` . arg : objective _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Objective ` ` to delete raise : NotFound - an ` ` Objective ` ` was not found identified by the given ` ` Id ` ` raise : ...
# Implemented from template for # osid . learning . ObjectiveAdminSession . delete _ objective _ template if not isinstance ( objective_id , ABCId ) : raise errors . InvalidArgument ( 'the argument is not a valid OSID Id' ) collection = JSONClientValidated ( 'learning' , collection = 'Activity' , runtime = self . _...
def get_new_term_doc_mat ( self , doc_domains ) : '''Combines documents together that are in the same domain Parameters doc _ domains : array - like Returns scipy . sparse . csr _ matrix'''
assert len ( doc_domains ) == self . term_doc_matrix . get_num_docs ( ) doc_domain_set = set ( doc_domains ) num_terms = self . term_doc_matrix . get_num_terms ( ) num_domains = len ( doc_domain_set ) domain_mat = lil_matrix ( ( num_domains , num_terms ) , dtype = int ) X = self . term_doc_matrix . get_term_doc_mat ( )...
def _cleanup ( self ) : '''Cleanup all the local data .'''
self . _declare_cb = None self . _bind_cb = None self . _unbind_cb = None self . _delete_cb = None self . _purge_cb = None super ( QueueClass , self ) . _cleanup ( )
def max ( self , axis = None , skipna = True , * args , ** kwargs ) : """Return the maximum value of the Index or maximum along an axis . See Also numpy . ndarray . max Series . max : Return the maximum value in a Series ."""
nv . validate_max ( args , kwargs ) nv . validate_minmax_axis ( axis ) if not len ( self ) : return self . _na_value i8 = self . asi8 try : # quick check if len ( i8 ) and self . is_monotonic : if i8 [ - 1 ] != iNaT : return self . _box_func ( i8 [ - 1 ] ) if self . hasnans : if ...
def read_input ( self , filename , has_header = True ) : """filename is any filename , or something on which open ( ) can be called for example : csv _ input = CSVInput ( ) csv _ input . read _ input ( " csvfile . csv " )"""
stream = open ( filename ) reader = csv . reader ( stream ) csv_data = [ ] for ( i , row ) in enumerate ( reader ) : if i == 0 : if not has_header : csv_data . append ( [ str ( i ) for i in xrange ( 0 , len ( row ) ) ] ) csv_data . append ( row ) self . data = csv_data
def constant ( self , val , ty ) : """Creates a constant as a VexValue : param val : The value , as an integer : param ty : The type of the resulting VexValue : return : a VexValue"""
if isinstance ( val , VexValue ) and not isinstance ( val , IRExpr ) : raise Exception ( 'Constant cannot be made from VexValue or IRExpr' ) rdt = self . irsb_c . mkconst ( val , ty ) return VexValue ( self . irsb_c , rdt )
def bind ( self , study , ** kwargs ) : # @ UnusedVariable """Returns a copy of the Spec bound to the given study Parameters study : Study A study to bind the fileset spec to ( should happen in the study _ _ init _ _ )"""
if self . _study is not None : # Avoid rebinding specs in sub - studies that have already # been bound to MultiStudy bound = self else : bound = copy ( self ) bound . _study = study if not hasattr ( study , self . pipeline_getter ) : raise ArcanaError ( "{} does not have a method named '{}' requ...
def runner ( ) : '''Return all inline documentation for runner modules CLI Example : . . code - block : : bash salt - run doc . runner'''
client = salt . runner . RunnerClient ( __opts__ ) ret = client . get_docs ( ) return ret
def serialize_op ( cls , opcode , opdata , opfields , verbose = True ) : """Given an opcode ( byte ) , associated data ( dict ) , and the operation fields to serialize ( opfields ) , convert it into its canonical serialized form ( i . e . in order to generate a consensus hash . opdata is allowed to have ext...
fields = opfields . get ( opcode , None ) if fields is None : log . error ( "BUG: unrecongnized opcode '%s'" % opcode ) return None all_values = [ ] debug_all_values = [ ] missing = [ ] for field in fields : if not opdata . has_key ( field ) : missing . append ( field ) field_value = opdata . ge...
def to_bytes ( s ) : """Convert string ` s ` to an integer number of bytes . Suffixes like ' KB ' , ' MB ' , ' GB ' ( up to ' YB ' ) , with or without the trailing ' B ' , are allowed and properly accounted for . Case is ignored in suffixes . Examples : : > > > to _ bytes ( ' 12 ' ) 12 > > > to _ byte...
last = - 1 unit = s [ last ] . lower ( ) if unit . isdigit ( ) : # ` s ` is a integral number return int ( s ) if unit == 'b' : # ignore the the ' b ' or ' B ' suffix last -= 1 unit = s [ last ] . lower ( ) if unit == 'i' : k = 1024 last -= 1 unit = s [ last ] . lower ( ) else : k = 1000 # c...
def handle_block ( mediator_state : MediatorTransferState , state_change : Block , channelidentifiers_to_channels : ChannelMap , pseudo_random_generator : random . Random , ) -> TransitionResult [ MediatorTransferState ] : """After Raiden learns about a new block this function must be called to handle expiration ...
expired_locks_events = events_to_remove_expired_locks ( mediator_state , channelidentifiers_to_channels , state_change . block_number , pseudo_random_generator , ) secret_reveal_events = events_for_onchain_secretreveal_if_dangerzone ( channelmap = channelidentifiers_to_channels , secrethash = mediator_state . secrethas...
def ordered_load ( self , stream , Loader = yaml . Loader , object_pairs_hook = OrderedDict ) : """Allows you to use ` pyyaml ` to load as OrderedDict . Taken from https : / / stackoverflow . com / a / 21912744/1927102"""
class OrderedLoader ( Loader ) : pass def construct_mapping ( loader , node ) : loader . flatten_mapping ( node ) return object_pairs_hook ( loader . construct_pairs ( node ) ) OrderedLoader . add_constructor ( yaml . resolver . BaseResolver . DEFAULT_MAPPING_TAG , construct_mapping ) try : try : ...
def create_alarm ( panel_json , abode , area = '1' ) : """Create a new alarm device from a panel response ."""
panel_json [ 'name' ] = CONST . ALARM_NAME panel_json [ 'id' ] = CONST . ALARM_DEVICE_ID + area panel_json [ 'type' ] = CONST . ALARM_TYPE panel_json [ 'type_tag' ] = CONST . DEVICE_ALARM panel_json [ 'generic_type' ] = CONST . TYPE_ALARM return AbodeAlarm ( panel_json , abode , area )
def matchesOneOf ( cntxt : Context , T : RDFGraph , expr : ShExJ . OneOf , _ : DebugContext ) -> bool : """expr is a OneOf and there is some shape expression se2 in shapeExprs such that a matches ( T , se2 , m ) ."""
return any ( matches ( cntxt , T , e ) for e in expr . expressions )
def serviceManifest ( self , fileType = "json" ) : """The service manifest resource documents the data and other resources that define the service origins and power the service . This resource will tell you underlying databases and their location along with other supplementary files that make up the service ....
url = self . _url + "/iteminfo/manifest/manifest.%s" % fileType params = { } f = self . _get ( url = url , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port , out_folder = tempfile . gettempdir ( ) , file_name = os . path . basename ( url )...
def removeRef ( self , doc ) : """Remove the given attribute from the Ref table maintained internally ."""
if doc is None : doc__o = None else : doc__o = doc . _o ret = libxml2mod . xmlRemoveRef ( doc__o , self . _o ) return ret
def delete_value ( hive , key , vname = None , use_32bit_registry = False ) : '''Delete a registry value entry or the default value for a key . Args : hive ( str ) : The name of the hive . Can be one of the following - HKEY _ LOCAL _ MACHINE or HKLM - HKEY _ CURRENT _ USER or HKCU - HKEY _ USER or HKU ...
local_hive = _to_unicode ( hive ) local_key = _to_unicode ( key ) local_vname = _to_unicode ( vname ) registry = Registry ( ) try : hkey = registry . hkeys [ local_hive ] except KeyError : raise CommandExecutionError ( 'Invalid Hive: {0}' . format ( local_hive ) ) access_mask = registry . registry_32 [ use_32bi...
def get_patient_vcf ( job , patient_dict ) : """Convenience function to get the vcf from the patient dict : param dict patient _ dict : dict of patient info : return : The vcf : rtype : toil . fileStore . FileID"""
temp = job . fileStore . readGlobalFile ( patient_dict [ 'mutation_vcf' ] , os . path . join ( os . getcwd ( ) , 'temp.gz' ) ) if is_gzipfile ( temp ) : outfile = job . fileStore . writeGlobalFile ( gunzip ( temp ) ) job . fileStore . deleteGlobalFile ( patient_dict [ 'mutation_vcf' ] ) else : outfile = pat...
def describe_features ( self , traj ) : """Return a list of dictionaries describing the dihderal features . Parameters traj : mdtraj . Trajectory The trajectory to describe Returns feature _ descs : list of dict Dictionary describing each feature with the following information about the atoms particip...
feature_descs = [ ] for dihed_type in self . types : # TODO : Don ' t recompute dihedrals , just get the indices func = getattr ( md , 'compute_%s' % dihed_type ) # ainds is a list of four - tuples of atoms participating # in each dihedral aind_tuples , _ = func ( traj ) top = traj . topology bi...
def clean_out_dir ( directory ) : """Delete all the files and subdirectories in a directory ."""
if not isinstance ( directory , path ) : directory = path ( directory ) for file_path in directory . files ( ) : file_path . remove ( ) for dir_path in directory . dirs ( ) : dir_path . rmtree ( )
def _l_cv_weight ( self , donor_catchment ) : """Return L - CV weighting for a donor catchment . Methodology source : Science Report SC050050 , eqn . 6.18 and 6.22a"""
try : dist = donor_catchment . similarity_dist except AttributeError : dist = self . _similarity_distance ( self . catchment , donor_catchment ) b = 0.0047 * sqrt ( dist ) + 0.0023 / 2 c = 0.02609 / ( donor_catchment . record_length - 1 ) return 1 / ( b + c )
def _seconds_or_timedelta ( duration ) : """Returns ` datetime . timedelta ` object for the passed duration . Keyword Arguments : duration - - ` datetime . timedelta ` object or seconds in ` int ` format ."""
if isinstance ( duration , int ) : dt_timedelta = timedelta ( seconds = duration ) elif isinstance ( duration , timedelta ) : dt_timedelta = duration else : raise TypeError ( 'Expects argument as `datetime.timedelta` object ' 'or seconds in `int` format' ) return dt_timedelta
def train ( cls , data , iterations = 100 , step = 1.0 , miniBatchFraction = 1.0 , initialWeights = None , regParam = 0.0 , regType = None , intercept = False , validateData = True , convergenceTol = 0.001 ) : """Train a linear regression model using Stochastic Gradient Descent ( SGD ) . This solves the least squ...
warnings . warn ( "Deprecated in 2.0.0. Use ml.regression.LinearRegression." , DeprecationWarning ) def train ( rdd , i ) : return callMLlibFunc ( "trainLinearRegressionModelWithSGD" , rdd , int ( iterations ) , float ( step ) , float ( miniBatchFraction ) , i , float ( regParam ) , regType , bool ( intercept ) , b...
def watch_crc ( params , ctxt , scope , stream , coord ) : """WatchCrc32 - Watch the total crc32 of the params . Example : The code below uses the ` ` WatchCrc32 ` ` update function to update the ` ` crc ` ` field to the crc of the ` ` length ` ` and ` ` data ` ` fields : : char length ; char data [ lengt...
if len ( params ) <= 1 : raise errors . InvalidArguments ( coord , "{} args" . format ( len ( params ) ) , "at least two arguments" ) to_update = params [ 0 ] total_data = utils . binary ( "" ) for param in params [ 1 : ] : total_data += param . _pfp__build ( ) to_update . _pfp__set_value ( binascii . crc32 ( t...
def gf_poly_div ( dividend , divisor ) : '''Fast polynomial division by using Extended Synthetic Division and optimized for GF ( 2 ^ p ) computations ( doesn ' t work with standard polynomials outside of this galois field ) .'''
# CAUTION : this function expects polynomials to follow the opposite convention at decoding : the terms must go from the biggest to lowest degree ( while most other functions here expect a list from lowest to biggest degree ) . eg : 1 + 2x + 5x ^ 2 = [ 5 , 2 , 1 ] , NOT [ 1 , 2 , 5] msg_out = bytearray ( dividend ) # C...
def with_vtk ( plot = True ) : """Tests VTK interface and mesh repair of Stanford Bunny Mesh"""
mesh = vtki . PolyData ( bunny_scan ) meshfix = pymeshfix . MeshFix ( mesh ) if plot : print ( 'Plotting input mesh' ) meshfix . plot ( ) meshfix . repair ( ) if plot : print ( 'Plotting repaired mesh' ) meshfix . plot ( ) return meshfix . mesh
def get_qword_from_data ( self , data , offset ) : """Convert eight bytes of data to a word ( little endian ) ' offset ' is assumed to index into a word array . So setting it to N will return a dword out of the data starting at offset N * 8. Returns None if the data can ' t be turned into a quad word ."""
if ( offset + 1 ) * 8 > len ( data ) : return None return struct . unpack ( '<Q' , data [ offset * 8 : ( offset + 1 ) * 8 ] ) [ 0 ]
def _PrintEventLabelsCounter ( self , event_labels_counter , session_identifier = None ) : """Prints the event labels counter . Args : event _ labels _ counter ( collections . Counter ) : number of event tags per label . session _ identifier ( Optional [ str ] ) : session identifier ."""
if not event_labels_counter : return title = 'Event tags generated per label' if session_identifier : title = '{0:s}: {1:s}' . format ( title , session_identifier ) table_view = views . ViewsFactory . GetTableView ( self . _views_format_type , column_names = [ 'Label' , 'Number of event tags' ] , title = title ...
def highlight_canvas ( self , highlight ) : """Set a colored frame around the FigureCanvas if highlight is True ."""
colorname = self . canvas . palette ( ) . highlight ( ) . color ( ) . name ( ) if highlight : self . canvas . setStyleSheet ( "FigureCanvas{border: 1px solid %s;}" % colorname ) else : self . canvas . setStyleSheet ( "FigureCanvas{}" )
def project_delete_event ( self , proj_info ) : """Process project delete event ."""
LOG . debug ( "Processing project_delete_event..." ) proj_id = proj_info . get ( 'resource_info' ) proj_name = self . get_project_name ( proj_id ) if proj_name : try : self . dcnm_client . delete_project ( proj_name , self . cfg . dcnm . default_partition_name ) except dexc . DfaClientRequestFailed : # ...
def _find_parent ( self , path_elements ) : """Recurse up the tree of FileSetStates until we find a parent , i . e . one whose path _ elements member is the start of the path _ element argument"""
if not self . path_elements : # Automatically terminate on root return self elif self . path_elements == path_elements [ 0 : len ( self . path_elements ) ] : return self else : return self . parent . _find_parent ( path_elements )
def backward ( self , loss ) : """backward propagation with loss"""
with mx . autograd . record ( ) : if isinstance ( loss , ( tuple , list ) ) : ls = [ l * self . _scaler . loss_scale for l in loss ] else : ls = loss * self . _scaler . loss_scale mx . autograd . backward ( ls )
def _setter ( self , attr , value , bottom , top , to_step ) : """Set a value . : param attr : Attribute to set . : param value : Value to use . : param bottom : Get to bottom value . : param top : Get to top value . : param to _ step : Get to intermediary value ."""
if value < 0 or value > 1 : raise ValueError ( "out of range" ) if value == 0.0 : bottom ( ) elif value == 1.0 : top ( ) else : to_step ( value ) setattr ( self , attr , value )
def parse_cgn_postag ( rawtag , raisefeatureexceptions = False ) : global subsets , constraints """decodes PoS features like " N ( soort , ev , basis , onz , stan ) " into a PosAnnotation data structure based on CGN tag overview compiled by Matje van de Camp"""
begin = rawtag . find ( '(' ) if rawtag [ - 1 ] == ')' and begin > 0 : tag = folia . PosAnnotation ( None , cls = rawtag , set = 'http://ilk.uvt.nl/folia/sets/cgn' ) head = rawtag [ 0 : begin ] tag . append ( folia . Feature , subset = 'head' , cls = head ) rawfeatures = rawtag [ begin + 1 : - 1 ] . spl...
def init_config ( cls ) : """Initialize Gandi CLI configuration . Create global configuration directory with API credentials"""
try : # first load current conf and only overwrite needed params # we don ' t want to reset everything config_file = os . path . expanduser ( cls . home_config ) config = cls . load ( config_file , 'global' ) cls . _del ( 'global' , 'api.env' ) hidden_apikey = '%s...' % cls . get ( 'api.key' , '' ) [ : ...
def all ( ctx , fetcher_num , processor_num , result_worker_num , run_in ) : """Run all the components in subprocess or thread"""
ctx . obj [ 'debug' ] = False g = ctx . obj # FIXME : py34 cannot run components with threads if run_in == 'subprocess' and os . name != 'nt' : run_in = utils . run_in_subprocess else : run_in = utils . run_in_thread threads = [ ] try : # phantomjs if not g . get ( 'phantomjs_proxy' ) : phantomjs_co...
def switch_format ( self , gsr ) : """Convert the Wharton GSR format into the studyspaces API format ."""
if "error" in gsr : return gsr categories = { "cid" : 1 , "name" : "Huntsman Hall" , "rooms" : [ ] } for time in gsr [ "times" ] : for entry in time : entry [ "name" ] = entry [ "room_number" ] del entry [ "room_number" ] start_time_str = entry [ "start_time" ] end_time = datetim...
def commit_msg_hook ( argv ) : """Hook : for checking commit message ( prevent commit ) ."""
with open ( argv [ 1 ] , "r" , "utf-8" ) as fh : message = "\n" . join ( filter ( lambda x : not x . startswith ( "#" ) , fh . readlines ( ) ) ) options = { "allow_empty" : True } if not _check_message ( message , options ) : click . echo ( "Aborting commit due to commit message errors (override with " "'git co...
def get_addon_name ( addonxml ) : '''Parses an addon name from the given addon . xml filename .'''
xml = parse ( addonxml ) addon_node = xml . getElementsByTagName ( 'addon' ) [ 0 ] return addon_node . getAttribute ( 'name' )
def newComic ( self , comic ) : """Start new comic list in HTML ."""
if self . lastUrl is not None : self . html . write ( u'</li>\n' ) if self . lastComic is not None : self . html . write ( u'</ul>\n' ) self . html . write ( u'<li>%s</li>\n' % comic . name ) self . html . write ( u'<ul>\n' )
def new_points ( factory : IterationPointFactory , solution , weights : List [ List [ float ] ] = None ) -> List [ Tuple [ np . ndarray , List [ float ] ] ] : """Generate approximate set of points Generate set of Pareto optimal solutions projecting from the Pareto optimal solution using weights to determine the...
from desdeo . preference . direct import DirectSpecification points = [ ] nof = factory . optimization_method . optimization_problem . problem . nof_objectives ( ) if not weights : weights = random_weights ( nof , 50 * nof ) for pref in map ( lambda w : DirectSpecification ( factory . optimization_method , np . arr...
def parse_template ( template_str ) : """Parse the SAM template . : param template _ str : A packaged YAML or json CloudFormation template : type template _ str : str : return : Dictionary with keys defined in the template : rtype : dict"""
try : # PyYAML doesn ' t support json as well as it should , so if the input # is actually just json it is better to parse it with the standard # json parser . return json . loads ( template_str , object_pairs_hook = OrderedDict ) except ValueError : yaml . SafeLoader . add_constructor ( yaml . resolver . BaseR...
def make_close_message ( code = 1000 , message = b'' ) : """Close the websocket , sending the specified code and message ."""
return _make_frame ( struct . pack ( '!H%ds' % len ( message ) , code , message ) , opcode = OPCODE_CLOSE )
def main ( ) : """The main function . These are the steps performed for the data clean up : 1 . Prints the version number . 2 . Reads the configuration file ( : py : func : ` read _ config _ file ` ) . 3 . Creates a new directory with ` ` data _ clean _ up ` ` as prefix and the date and time as suffix . ...
# Getting and checking the options args = parse_args ( ) check_args ( args ) # The directory name dirname = "data_clean_up." dirname += datetime . datetime . today ( ) . strftime ( "%Y-%m-%d_%H.%M.%S" ) while os . path . isdir ( dirname ) : time . sleep ( 1 ) dirname = "data_clean_up." dirname += datetime ....
def display ( self , * arg ) : """For simple Demo 測試用顯示樣式 。"""
print self . stock_name , self . stock_no print '%s %s %s(%+.2f%%)' % ( self . data_date [ - 1 ] , self . raw_data [ - 1 ] , self . stock_range [ - 1 ] , self . range_per ) for i in arg : print ' - MA%02s %.2f %s(%s)' % ( i , self . MA ( i ) , self . MAC ( i ) , self . MA_serial ( i ) [ 0 ] ) print ' - Volume: %s ...
def get_country ( _ , data ) : """http : / / git . kernel . org / cgit / linux / kernel / git / jberg / iw . git / tree / scan . c ? id = v3.17 # n267. Positional arguments : data - - bytearray data to read . Returns : Dict ."""
answers = { 'Environment' : country_env_str ( chr ( data [ 2 ] ) ) } data = data [ 3 : ] while len ( data ) >= 3 : triplet = ieee80211_country_ie_triplet ( data ) if triplet . ext . reg_extension_id >= IEEE80211_COUNTRY_EXTENSION_ID : answers [ 'Extension ID' ] = triplet . ext . reg_extension_id ...
def get_list ( client , list_id ) : '''Gets the given list'''
endpoint = '/' . join ( [ client . api . Endpoints . LISTS , str ( list_id ) ] ) response = client . authenticated_request ( endpoint ) return response . json ( )
def _name ( self ) : """Define object name ."""
return "{0} {1} {2}" . format ( self . _camera . name , pretty_timestamp ( self . created_at ) , self . _attrs . get ( 'mediaDuration' ) )
def md_report ( self , file_path ) : """Generate and save MD report"""
self . logger . debug ( 'Generating MD report' ) report = self . zap . core . mdreport ( ) self . _write_report ( report , file_path )
def ufo2glyphs ( options ) : """Convert one designspace file or one or more UFOs to a Glyphs . app source file ."""
import fontTools . designspaceLib import defcon sources = options . designspace_file_or_UFOs designspace_file = None if ( len ( sources ) == 1 and sources [ 0 ] . endswith ( ".designspace" ) and os . path . isfile ( sources [ 0 ] ) ) : designspace_file = sources [ 0 ] designspace = fontTools . designspaceLib . ...
def get_available_devices ( self ) : """Gets available devices using mbedls and self . available _ edbg _ ports . : return : List of connected devices as dictionaries ."""
connected_devices = self . mbeds . list_mbeds ( ) if self . mbeds else [ ] # Check non mbedOS supported devices . # Just for backward compatible reason - is obsolete . . edbg_ports = self . available_edbg_ports ( ) for port in edbg_ports : connected_devices . append ( { "platform_name" : "SAM4E" , "serial_port" : p...
def docx_docx_gen_text ( doc : DOCX_DOCUMENT_TYPE , config : TextProcessingConfig ) -> Iterator [ str ] : # only called if docx loaded """Iterate through a DOCX file and yield text . Args : doc : DOCX document to process config : : class : ` TextProcessingConfig ` control object Yields : pieces of text ( ...
if in_order : for thing in docx_docx_iter_block_items ( doc ) : if isinstance ( thing , docx . text . paragraph . Paragraph ) : yield docx_process_simple_text ( thing . text , config . width ) elif isinstance ( thing , docx . table . Table ) : yield docx_process_table ( thing...
def detectRamPorts ( stm : IfContainer , current_en : RtlSignalBase ) : """Detect RAM ports in If statement : param stm : statement to detect the ram ports in : param current _ en : curent en / clk signal"""
if stm . ifFalse or stm . elIfs : return for _stm in stm . ifTrue : if isinstance ( _stm , IfContainer ) : yield from detectRamPorts ( _stm , _stm . cond & current_en ) elif isinstance ( _stm , Assignment ) : if isinstance ( _stm . dst . _dtype , HArray ) : assert len ( _stm . in...
def _enforce_instance ( model_or_class ) : """It ' s a common mistake to not initialize a schematics class . We should handle that by just calling the default constructor ."""
if isinstance ( model_or_class , type ) and issubclass ( model_or_class , BaseType ) : return model_or_class ( ) return model_or_class
def prepare_mosaic ( self , image , fov_deg , name = None ) : """Prepare a new ( blank ) mosaic image based on the pointing of the parameter image"""
header = image . get_header ( ) ra_deg , dec_deg = header [ 'CRVAL1' ] , header [ 'CRVAL2' ] data_np = image . get_data ( ) # dtype = data _ np . dtype dtype = None self . bg_ref = iqcalc . get_median ( data_np ) # TODO : handle skew ( differing rotation for each axis ) ? skew_limit = self . settings . get ( 'skew_limi...
def destroy_server ( server_id ) : '''Given a UUID id of a div removed or replaced in the Jupyter notebook , destroy the corresponding server sessions and stop it .'''
server = curstate ( ) . uuid_to_server . get ( server_id , None ) if server is None : log . debug ( "No server instance found for uuid: %r" % server_id ) return try : for session in server . get_sessions ( ) : session . destroy ( ) server . stop ( ) del curstate ( ) . uuid_to_server [ server...
def get_header ( uri ) : """Pull a FITS header from observation at the given URI @ param uri : The URI of the image in VOSpace ."""
if uri not in astheaders : astheaders [ uri ] = get_hdu ( uri , cutout = "[1:1,1:1]" ) [ 0 ] . header return astheaders [ uri ]
def to_ip ( self , values , from_unit ) : """Return values in IP and the units to which the values have been converted ."""
if from_unit in self . ip_units : return values , from_unit elif from_unit == 'tonne' : return self . to_unit ( values , 'ton' , from_unit ) , 'ton' else : return self . to_unit ( values , 'lb' , from_unit ) , 'lb'
def shift ( self , amount ) : """shifts position"""
if self . left is not None : self . left += amount if self . left is not None : self . right += amount
def com_google_fonts_check_fontdata_namecheck ( ttFont , familyname ) : """Familyname must be unique according to namecheck . fontdata . com"""
FB_ISSUE_TRACKER = "https://github.com/googlefonts/fontbakery/issues" import requests url = f"http://namecheck.fontdata.com/?q={familyname}" try : response = requests . get ( url , timeout = 10 ) data = response . content . decode ( "utf-8" ) if "fonts by that exact name" in data : yield INFO , ( "T...
def handle_CR ( self , value ) : """Parses cited references ."""
citation = self . entry_class ( ) value = strip_tags ( value ) # First - author name and publication date . ptn = '([\w\s\W]+),\s([0-9]{4}),\s([\w\s]+)' ny_match = re . match ( ptn , value , flags = re . U ) nj_match = re . match ( '([\w\s\W]+),\s([\w\s]+)' , value , flags = re . U ) if ny_match is not None : name_...
def do_refresh ( self , args ) : """Refresh the view of the log group"""
print "stackResource: {}" . format ( self . stackResource ) self . roleDetails = AwsConnectionFactory . getIamClient ( ) . get_role ( RoleName = self . stackResource . physical_resource_id ) print "== role details ==" pprint ( self . roleDetails ) self . rolePolicies = self . loadRolePolicies ( ) print "== attached pol...
def parse_xml_report ( cls , conf , path ) : """Parse the ivy xml report corresponding to the name passed to ivy . : API : public : param string conf : the ivy conf name ( e . g . " default " ) : param string path : The path to the ivy report file . : returns : The info in the xml report . : rtype : : cla...
if not os . path . exists ( path ) : raise cls . IvyResolveReportError ( 'Missing expected ivy output file {}' . format ( path ) ) logger . debug ( "Parsing ivy report {}" . format ( path ) ) ret = IvyInfo ( conf ) etree = ET . parse ( path ) doc = etree . getroot ( ) for module in doc . findall ( 'dependencies/mod...
def _replace_bm ( self ) : """Replace ` ` _ block _ matcher ` ` with current values ."""
self . _block_matcher = cv2 . StereoSGBM ( minDisparity = self . _min_disparity , numDisparities = self . _num_disp , SADWindowSize = self . _sad_window_size , uniquenessRatio = self . _uniqueness , speckleWindowSize = self . _speckle_window_size , speckleRange = self . _speckle_range , disp12MaxDiff = self . _max_disp...
def from_bytes ( cls , bitstream ) : '''Parse the given packet and update properties accordingly'''
packet = cls ( ) # Convert to ConstBitStream ( if not already provided ) if not isinstance ( bitstream , ConstBitStream ) : if isinstance ( bitstream , Bits ) : bitstream = ConstBitStream ( auto = bitstream ) else : bitstream = ConstBitStream ( bytes = bitstream ) # Read the type type_nr = bitst...
def calcMz ( self , specfiles = None , guessCharge = True , obsMzKey = 'obsMz' ) : """Calculate the exact mass for ` ` Sii ` ` elements from the ` ` Sii . peptide ` ` sequence . : param specfiles : the name of an ms - run file or a list of names . If None all specfiles are selected . : param guessCharge : b...
# TODO : important to test function , since changes were made _calcMass = maspy . peptidemethods . calcPeptideMass _calcMzFromMass = maspy . peptidemethods . calcMzFromMass _massProton = maspy . constants . atomicMassProton _guessCharge = lambda mass , mz : round ( mass / ( mz - _massProton ) , 0 ) if specfiles is None...
def read_electrostatic_potential ( self ) : """Parses the eletrostatic potential for the last ionic step"""
pattern = { "ngf" : r"\s+dimension x,y,z NGXF=\s+([\.\-\d]+)\sNGYF=\s+([\.\-\d]+)\sNGZF=\s+([\.\-\d]+)" } self . read_pattern ( pattern , postprocess = int ) self . ngf = self . data . get ( "ngf" , [ [ ] ] ) [ 0 ] pattern = { "radii" : r"the test charge radii are((?:\s+[\.\-\d]+)+)" } self . read_pattern ( pattern , r...
def is_ignored ( resource ) : '''Check of the resource ' s URL is part of LINKCHECKING _ IGNORE _ DOMAINS'''
ignored_domains = current_app . config [ 'LINKCHECKING_IGNORE_DOMAINS' ] url = resource . url if url : parsed_url = urlparse ( url ) return parsed_url . netloc in ignored_domains return True
def delmod_cli ( argv , alter_logger = True ) : """Command - line access to ` ` delmod ` ` functionality . The ` ` delmod ` ` task deletes " on - the - fly " model information from a Measurement Set . It is so easy to implement that a standalone function is essentially unnecessary . Just write : : from pwki...
check_usage ( delmod_doc , argv , usageifnoargs = True ) if alter_logger : util . logger ( ) cb = util . tools . calibrater ( ) for mspath in argv [ 1 : ] : cb . open ( b ( mspath ) , addcorr = False , addmodel = False ) cb . delmod ( otf = True , scr = False ) cb . close ( )
def show ( context , id ) : """show ( context , id ) Show a Feeder . > > > dcictl feeder - show [ OPTIONS ] : param string id : ID of the feeder to show [ required ]"""
result = feeder . get ( context , id = id ) utils . format_output ( result , context . format )
def _validate_object_can_be_tagged_with_redactor ( self , annotated_object ) : """Validates that the object type can be annotated and object does not have conflicting annotations ."""
data_type = annotated_object . data_type name = annotated_object . name loc = annotated_object . _ast_node . lineno , annotated_object . _ast_node . path curr_data_type = data_type while isinstance ( curr_data_type , Alias ) or isinstance ( curr_data_type , Nullable ) : # aliases have redactors assocaited with the type...
def add_directory_digests_for_jars ( self , targets_and_jars ) : """For each target , get DirectoryDigests for its jars and return them zipped with the jars . : param targets _ and _ jars : List of tuples of the form ( Target , [ pants . java . jar . jar _ dependency _ utils . ResolveJar ] ) : return : list [ t...
targets_and_jars = list ( targets_and_jars ) if not targets_and_jars or not self . get_options ( ) . capture_snapshots : return targets_and_jars jar_paths = [ ] for target , jars_to_snapshot in targets_and_jars : for jar in jars_to_snapshot : jar_paths . append ( fast_relpath ( jar . pants_path , get_bu...
def _read_opt_calipso ( self , code , * , desc ) : """Read HOPOPT CALIPSO option . Structure of HOPOPT CALIPSO option [ RFC 5570 ] : | Next Header | Hdr Ext Len | Option Type | Option Length | | CALIPSO Domain of Interpretation | | Cmpt Length | Sens Level | Checksum ( CRC - 16 ) | | Compartment Bitmap ( ...
_type = self . _read_opt_type ( code ) _size = self . _read_unpack ( 1 ) if _size < 8 and _size % 8 != 0 : raise ProtocolError ( f'{self.alias}: [Optno {code}] invalid format' ) _cmpt = self . _read_unpack ( 4 ) _clen = self . _read_unpack ( 1 ) if _clen % 2 != 0 : raise ProtocolError ( f'{self.alias}: [Optno {...
def insert_line ( self , line ) : """Insert a new line"""
if self . current_block is not None : self . current_block . append ( line ) else : self . header . append ( line )
def fit ( self ) : r"""Loop over distributions and find best parameter to fit the data for each When a distribution is fitted onto the data , we populate a set of dataframes : - : attr : ` df _ errors ` : sum of the square errors between the data and the fitted distribution i . e . , : math : ` \ sum _ i \ ...
for distribution in self . distributions : try : # need a subprocess to check time it takes . If too long , skip it dist = eval ( "scipy.stats." + distribution ) # TODO here , dist . fit may take a while or just hang forever # with some distributions . So , I thought to use signal module ...
def _get_object_parser ( self , json ) : """Parses a json document into a pandas object ."""
typ = self . typ dtype = self . dtype kwargs = { "orient" : self . orient , "dtype" : self . dtype , "convert_axes" : self . convert_axes , "convert_dates" : self . convert_dates , "keep_default_dates" : self . keep_default_dates , "numpy" : self . numpy , "precise_float" : self . precise_float , "date_unit" : self . d...
def advance ( self , myDateTime ) : """Advances to the next value and returns an appropriate value for the given time . : param myDateTime : ( datetime ) when to fetch the value for : return : ( float | int ) value for given time"""
if self . getTime ( ) == myDateTime : out = self . next ( ) # Sometimes , the stream has no value for this field and returns None , in # this case we ' ll use the last value as well . if out is None : out = self . last ( ) else : out = self . last ( ) # If there ' s no more data , we must fe...
def receive ( self , sequence , args ) : """Receive one packet If the sequence number is one we ' ve already seen before , it is dropped . If it is not the next expected sequence number , it is put into the _ out _ of _ order queue to be processed once the holes in sequence number are filled in . Args : ...
# If we are told to ignore sequence numbers , just pass the packet on if not self . _reorder : self . _callback ( * args ) return # If this packet is in the past , drop it if self . _next_expected is not None and sequence < self . _next_expected : print ( "Dropping out of order packet, seq=%d" % sequence ) ...
def downsampled_mesh ( self , step ) : """Returns a downsampled copy of this mesh . Args : step : the step size for the sampling Returns : a new , downsampled Mesh object . Raises : ValueError if this Mesh has faces ."""
from lace . mesh import Mesh if self . f is not None : raise ValueError ( 'Function `downsampled_mesh` does not support faces.' ) low = Mesh ( ) if self . v is not None : low . v = self . v [ : : step ] if self . vc is not None : low . vc = self . vc [ : : step ] return low
def edit ( self , physicalPath , cleanupMode , maxFileAge , description ) : """The server directory ' s edit operation allows you to change the path and clean up properties of the directory . This operation updates the GIS service configurations ( and points them to the new path ) that are using this director...
url = self . _url + "/edit" params = { "f" : "json" , "physicalPath" : physicalPath , "cleanupMode" : cleanupMode , "maxFileAge" : maxFileAge , "description" : description } return self . _post ( url = url , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = s...
def versions ( self ) : """Announce Versions of CLI and Server Args : None Returns : The running versions of both the CLI and the Workbench Server"""
print '%s<<< Workbench CLI Version %s >>>%s' % ( color . LightBlue , self . version , color . Normal ) print self . workbench . help ( 'version' )
def commit ( self ) : """Commit dirty records to the server . This method is automatically called when the ` auto _ commit ` option is set to ` True ` ( default ) . It can be useful to set the former option to ` False ` to get better performance by reducing the number of RPC requests generated . With ` auto...
# Iterate on a new set , as we remove record during iteration from the # original one for record in set ( self . dirty ) : values = { } for field in record . _values_to_write : if record . id in record . _values_to_write [ field ] : value = record . _values_to_write [ field ] . pop ( record ...
def cropped ( self , T0 , T1 ) : """returns a cropped copy of the path ."""
assert 0 <= T0 <= 1 and 0 <= T1 <= 1 assert T0 != T1 assert not ( T0 == 1 and T1 == 0 ) if T0 == 1 and 0 < T1 < 1 and self . isclosed ( ) : return self . cropped ( 0 , T1 ) if T1 == 1 : seg1 = self [ - 1 ] t_seg1 = 1 i1 = len ( self ) - 1 else : seg1_idx , t_seg1 = self . T2t ( T1 ) seg1 = self ...
def _uninstall ( cls ) : """uninstall the hook if installed"""
if cls . _hook : sys . meta_path . remove ( cls . _hook ) cls . _hook = None
def set_window_geometry ( geometry ) : """Set window geometry . Parameters geometry : tuple ( 4 integers ) or None x , y , dx , dy values employed to set the Qt backend geometry ."""
if geometry is not None : x_geom , y_geom , dx_geom , dy_geom = geometry mngr = plt . get_current_fig_manager ( ) if 'window' in dir ( mngr ) : try : mngr . window . setGeometry ( x_geom , y_geom , dx_geom , dy_geom ) except AttributeError : pass else : ...
async def restart ( request : web . Request ) -> web . Response : """Restart the robot . Blocks while the restart lock is held ."""
async with request . app [ RESTART_LOCK_NAME ] : asyncio . get_event_loop ( ) . call_later ( 1 , _do_restart ) return web . json_response ( { 'message' : 'Restarting in 1s' } , status = 200 )