signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def purge_objects ( self , request ) : """Removes all objects in this table . This action first displays a confirmation page ; next , it deletes all objects and redirects back to the change list ."""
def truncate_table ( model ) : if settings . TRUNCATE_TABLE_SQL_STATEMENT : from django . db import connection sql = settings . TRUNCATE_TABLE_SQL_STATEMENT . format ( db_table = model . _meta . db_table ) cursor = connection . cursor ( ) cursor . execute ( sql ) else : m...
def query_phenomizer ( usr , pwd , * hpo_terms ) : """Query the phenomizer web tool Arguments : usr ( str ) : A username for phenomizer pwd ( str ) : A password for phenomizer hpo _ terms ( list ) : A list with hpo terms Returns : raw _ answer : The raw result from phenomizer"""
base_string = 'http://compbio.charite.de/phenomizer/phenomizer/PhenomizerServiceURI' questions = { 'mobilequery' : 'true' , 'terms' : ',' . join ( hpo_terms ) , 'username' : usr , 'password' : pwd } try : r = requests . get ( base_string , params = questions , timeout = 10 ) except requests . exceptions . Timeout :...
def mjpeg_url ( self , channelno = None , typeno = None ) : """Return MJPEG streaming url Params : channelno : integer , the video channel index which starts from 1, default 1 if not specified . typeno : the stream type , default 0 if not specified . It can be the following value : 0 - Main Stream 1 -...
if channelno is None : channelno = 0 if typeno is None : typeno = 1 cmd = "mjpg/video.cgi?channel={0}&subtype={1}" . format ( channelno , typeno ) return '{0}{1}' . format ( self . _base_url , cmd )
def is_variable ( tup ) : """Takes ( name , object ) tuple , returns True if it is a variable ."""
name , item = tup if callable ( item ) : # function or class return False if isinstance ( item , types . ModuleType ) : # imported module return False if name . startswith ( "_" ) : # private property return False return True
def backgr ( img , mask = None , mode = MODE_AUTO , thresh = 2 , splinepoints = 5 , scale = 1 , maxiter = 40 , convergence = .001 ) : '''Iterative spline - based background correction . mode - one of MODE _ AUTO , MODE _ DARK , MODE _ BRIGHT or MODE _ GRAY thresh - thresh is threshold to cut at , in units of si...
assert img . ndim == 2 , "Image must be 2-d" assert splinepoints >= 3 , "The minimum grid size is 3x3" assert maxiter >= 1 assert mode in [ MODE_AUTO , MODE_BRIGHT , MODE_DARK , MODE_GRAY ] , mode + " is not a valid background mode" orig_shape = np . array ( img . shape ) . copy ( ) input_mask = mask if mask is None : ...
def get_f_clvd ( self ) : """Returns the statistic f _ clvd : the signed ratio of the sizes of the intermediate and largest principal moments : : f _ clvd = - b _ axis _ eigenvalue / max ( | t _ axis _ eigenvalue | , | p _ axis _ eigenvalue | )"""
if not self . principal_axes : # Principal axes not yet defined for moment tensor - raises error raise ValueError ( 'Principal Axes not defined!' ) denominator = np . max ( np . array ( [ fabs ( self . principal_axes . t_axis [ 'eigenvalue' ] ) , fabs ( self . principal_axes . p_axis [ 'eigenvalue' ] ) ] ) ) self ....
def get_requirements ( * args ) : """Get requirements from pip requirement files ."""
requirements = set ( ) contents = get_contents ( * args ) for line in contents . splitlines ( ) : # Strip comments . line = re . sub ( r'^#.*|\s#.*' , '' , line ) # Ignore empty lines if line and not line . isspace ( ) : requirements . add ( re . sub ( r'\s+' , '' , line ) ) return sorted ( requirem...
def list_document_libraries ( self , limit = None , * , query = None , order_by = None , batch = None ) : """Returns a collection of document libraries for this site ( a collection of Drive instances ) : param int limit : max no . of items to get . Over 999 uses batch . : param query : applies a OData filter ...
return self . site_storage . get_drives ( limit = limit , query = query , order_by = order_by , batch = batch )
def _read ( self ) : """get two list , each list contains two elements : name and nd . array value"""
_ , data_img_name , label_img_name = self . f . readline ( ) . strip ( '\n' ) . split ( "\t" ) data = { } label = { } data [ self . data_name ] , label [ self . label_name ] = self . _read_img ( data_img_name , label_img_name ) return list ( data . items ( ) ) , list ( label . items ( ) )
def _closest_centroid ( self , x ) : """Returns the index of the closest centroid to the sample"""
closest_centroid = 0 distance = 10 ^ 9 for i in range ( self . n_clusters ) : current_distance = linalg . norm ( x - self . centroids [ i ] ) if current_distance < distance : closest_centroid = i distance = current_distance return closest_centroid
def encode ( val , base , minlen = 0 ) : """Given an integer value ( val ) and a numeric base ( base ) , encode it into the string of symbols with the given base . ( with minimum length minlen ) Returns the ( left - padded ) re - encoded val as a string ."""
base , minlen = int ( base ) , int ( minlen ) code_string = get_code_string ( base ) result = "" while val > 0 : result = code_string [ val % base ] + result val //= base return code_string [ 0 ] * max ( minlen - len ( result ) , 0 ) + result
def sign_statement ( self , statement , node_name , key_file , node_id , id_attr ) : """Sign an XML statement . The parameters actually used in this CryptoBackend implementation are : : param statement : XML as string : param node _ name : Name of the node to sign : param key _ file : xmlsec key _ spec st...
import xmlsec import lxml . etree xml = xmlsec . parse_xml ( statement ) signed = xmlsec . sign ( xml , key_file ) signed_str = lxml . etree . tostring ( signed , xml_declaration = False , encoding = "UTF-8" ) if not isinstance ( signed_str , six . string_types ) : signed_str = signed_str . decode ( "utf-8" ) retur...
def generate_random_string ( cls , length ) : """Generatesa a [ length ] characters alpha numeric secret"""
# avoid things that could be mistaken ex : ' I ' and ' 1' letters = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ" return "" . join ( [ random . choice ( letters ) for _ in range ( length ) ] )
def parse ( self , raw_sections = None , namespaces = True , strip_comments = True , strip_whitespaces = True , strip_quotation_markers = True , raise_parsing_errors = True ) : """Process the file content and extracts the sections / attributes as nested : class : ` collections . OrderedDict ` dictionaries or dict...
LOGGER . debug ( "> Reading sections from: '{0}'." . format ( self . path ) ) if not self . content : self . read ( ) attributes = { } if not self . __preserve_order else OrderedDict ( ) section = self . __defaults_section raw_sections = raw_sections or [ ] commentId = 0 for i , line in enumerate ( self . content )...
def get_connections ( self ) : """Returns a list of site pairs that are Voronoi Neighbors , along with their real - space distances ."""
con = [ ] maxconn = self . max_connectivity for ii in range ( 0 , maxconn . shape [ 0 ] ) : for jj in range ( 0 , maxconn . shape [ 1 ] ) : if maxconn [ ii ] [ jj ] != 0 : dist = self . s . get_distance ( ii , jj ) con . append ( [ ii , jj , dist ] ) return con
def marker_for_line ( self , line ) : """Returns the marker that is displayed at the specified line number if any . : param line : The marker line . : return : Marker of None : rtype : pyqode . core . Marker"""
block = self . editor . document ( ) . findBlockByNumber ( line ) try : return block . userData ( ) . messages except AttributeError : return [ ]
def psq2 ( d1 , d2 ) : """Compute the PSQ2 measure . Args : d1 ( np . ndarray ) : The first distribution . d2 ( np . ndarray ) : The second distribution ."""
d1 , d2 = flatten ( d1 ) , flatten ( d2 ) def f ( p ) : return sum ( ( p ** 2 ) * np . nan_to_num ( np . log ( p * len ( p ) ) ) ) return abs ( f ( d1 ) - f ( d2 ) )
def fake ( args ) : """% prog fake input . bed Make fake ` scaffolds . fasta ` . Use case for this is that sometimes I would receive just the csv / bed file and I ' d like to use path ( ) out of the box ."""
from math import ceil from random import choice from Bio import SeqIO from Bio . Seq import Seq from Bio . SeqRecord import SeqRecord p = OptionParser ( fake . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) inputbed , = args bed = Bed...
def remove_editor_tab ( self , editor ) : """Removes the * * Script _ Editor _ tabWidget * * Widget tab with given editor . : param editor : Editor . : type editor : Editor : return : Method success . : rtype : bool"""
LOGGER . debug ( "> Removing tab with Editor '{0}'." . format ( editor ) ) self . Script_Editor_tabWidget . removeTab ( self . get_editorTab ( editor ) ) return True
def make_skip_list ( cts ) : """Return hand - defined list of place names to skip and not attempt to geolocate . If users would like to exclude country names , this would be the function to do it with ."""
# maybe make these non - country searches but don ' t discard , at least for # some ( esp . bodies of water ) special_terms = [ "Europe" , "West" , "the West" , "South Pacific" , "Gulf of Mexico" , "Atlantic" , "the Black Sea" , "Black Sea" , "North America" , "Mideast" , "Middle East" , "the Middle East" , "Asia" , "t...
def evaluate ( self ) : """Run the engine on the expression This method performs alignment which is necessary no matter what engine is being used , thus its implementation is in the base class . Returns obj : object The result of the passed expression ."""
if not self . _is_aligned : self . result_type , self . aligned_axes = _align ( self . expr . terms ) # make sure no names in resolvers and locals / globals clash res = self . _evaluate ( ) return _reconstruct_object ( self . result_type , res , self . aligned_axes , self . expr . terms . return_type )
def decrypt ( self , message , ** kwargs ) : """Decrypt the contents of a string or file - like object ` ` message ` ` . : type message : file or str or : class : ` io . BytesIO ` : param message : A string or file - like object to decrypt . : param bool always _ trust : Instruct GnuPG to ignore trust checks ...
stream = _make_binary_stream ( message , self . _encoding ) result = self . decrypt_file ( stream , ** kwargs ) stream . close ( ) return result
def getBestAngle ( entities , current_yaw , current_health ) : '''Scan through 360 degrees , looking for the best direction in which to take the next step .'''
us = findUs ( entities ) scores = [ ] # Normalise current yaw : while current_yaw < 0 : current_yaw += 360 while current_yaw > 360 : current_yaw -= 360 # Look for best option for i in range ( agent_search_resolution ) : # Calculate cost of turning : ang = 2 * math . pi * ( old_div ( i , float ( agent_search...
def get ( self ) : """: return : response stats dict"""
stats = { } if self . start_date is not None : stats [ "start_date" ] = self . start_date if self . end_date is not None : stats [ "end_date" ] = self . end_date if self . aggregated_by is not None : stats [ "aggregated_by" ] = self . aggregated_by if self . sort_by_metric is not None : stats [ "sort_by...
def telnet_login ( self , pri_prompt_terminator = "#" , alt_prompt_terminator = ">" , username_pattern = r"Login Name:" , pwd_pattern = r"assword" , delay_factor = 1 , max_loops = 60 , ) : """Telnet login : can be username / password or just password ."""
super ( HPProcurveTelnet , self ) . telnet_login ( pri_prompt_terminator = pri_prompt_terminator , alt_prompt_terminator = alt_prompt_terminator , username_pattern = username_pattern , pwd_pattern = pwd_pattern , delay_factor = delay_factor , max_loops = max_loops , )
def check_file ( self , fs , info ) : # type : ( FS , Info ) - > bool """Check if a filename should be included . Override to exclude files from the walk . Arguments : fs ( FS ) : A filesystem instance . info ( Info ) : A resource info object . Returns : bool : ` True ` if the file should be included ."...
if self . exclude is not None and fs . match ( self . exclude , info . name ) : return False return fs . match ( self . filter , info . name )
def login ( self , username : str , password : str , course : int ) -> requests . Response : """登入課程"""
try : # 操作所需資訊 payload = { 'name' : username , 'passwd' : password , 'rdoCourse' : course } # 回傳嘗試登入的回應 return self . __session . post ( self . __url + '/Login' , data = payload , timeout = 0.5 , verify = False ) except requests . exceptions . Timeout : return None
def _compute_predicates ( table_op , predicates , data , scope , ** kwargs ) : """Compute the predicates for a table operation . Parameters table _ op : TableNode predicates : List [ ir . ColumnExpr ] data : pd . DataFrame scope : dict kwargs : dict Returns computed _ predicate : pd . Series [ bool ...
for predicate in predicates : # Map each root table of the predicate to the data so that we compute # predicates on the result instead of any left or right tables if the # Selection is on a Join . Project data to only inlude columns from # the root table . root_tables = predicate . op ( ) . root_tables ( ) # ha...
def discover_files ( base_path , sub_path = '' , ext = '' , trim_base_path = False ) : """Discovers all files with certain extension in given paths ."""
file_list = [ ] for root , dirs , files in walk ( path . join ( base_path , sub_path ) ) : if trim_base_path : root = path . relpath ( root , base_path ) file_list . extend ( [ path . join ( root , file_name ) for file_name in files if file_name . endswith ( ext ) ] ) return sorted ( file_list )
def magic_string ( string , filename = None ) : """Returns tuple of ( num _ of _ matches , array _ of _ matches ) arranged highest confidence match first If filename is provided it will be used in the computation . : param string : string representation to check : param filename : original filename : retu...
if not string : raise ValueError ( "Input was empty" ) head , foot = _string_details ( string ) ext = ext_from_filename ( filename ) if filename else None info = _identify_all ( head , foot , ext ) info . sort ( key = lambda x : x . confidence , reverse = True ) return info
def _get_preseq_params ( data , preseq_cmd , read_count ) : """Get parameters through resources . If " step " or " extrap " limit are not provided , then calculate optimal values based on read count ."""
defaults = { 'seg_len' : 100000 , # maximum segment length when merging paired end bam reads 'steps' : 300 , # number of points on the plot 'extrap_fraction' : 3 , # extrapolate up to X times read _ count 'extrap' : None , # extrapolate up to X reads 'step' : None , # step size ( number of reads between points on the p...
def report ( self , item_id , report_format = "json" ) : """Retrieves the specified report for the analyzed item , referenced by item _ id . Available formats include : json . : type item _ id : str : param item _ id : File ID number : type report _ format : str : param report _ format : Return format :...
if report_format == "html" : return "Report Unavailable" # grab an analysis id from the submission id . response = self . _request ( "/analysis/sample/{sample_id}" . format ( sample_id = item_id ) , headers = self . headers ) try : # the highest score is probably the most interesting . # vmray uses this internally ...
def fit_predict ( self , sequences , y = None ) : """Performs clustering on X and returns cluster labels . Parameters sequences : list of array - like , each of shape [ sequence _ length , n _ features ] A list of multivariate timeseries . Each sequence may have a different length , but they all must have t...
if hasattr ( super ( MultiSequenceClusterMixin , self ) , 'fit_predict' ) : check_iter_of_sequences ( sequences , allow_trajectory = self . _allow_trajectory ) labels = super ( MultiSequenceClusterMixin , self ) . fit_predict ( sequences ) else : self . fit ( sequences ) labels = self . predict ( sequen...
def deserialize ( serialized_material_description ) : # type : ( dynamodb _ types . BINARY _ ATTRIBUTE ) - > Dict [ Text , Text ] """Deserialize a serialized material description attribute into a material description dictionary . : param dict serialized _ material _ description : DynamoDB attribute value containi...
try : _raw_material_description = serialized_material_description [ Tag . BINARY . dynamodb_tag ] material_description_bytes = io . BytesIO ( _raw_material_description ) total_bytes = len ( _raw_material_description ) except ( TypeError , KeyError ) : message = "Invalid material description" _LOGGER...
def verse_lookup ( self , book_name , book_chapter , verse , cache_chapter = True ) : """Looks up a verse from online . recoveryversion . bible , then returns it ."""
verses_list = self . get_chapter ( book_name , str ( book_chapter ) , cache_chapter = cache_chapter ) return verses_list [ int ( verse ) - 1 ]
def MakeStatResponse ( self , tsk_file , tsk_attribute = None , append_name = None ) : """Given a TSK info object make a StatEntry . Note that tsk uses two things to uniquely identify a data stream - the inode object given in tsk _ file and the attribute object which may correspond to an ADS of this file for ...
precondition . AssertOptionalType ( append_name , Text ) info = tsk_file . info response = rdf_client_fs . StatEntry ( ) meta = info . meta if meta : response . st_ino = meta . addr for attribute in [ "mode" , "nlink" , "uid" , "gid" , "size" , "atime" , "mtime" , "ctime" , "crtime" ] : try : ...
def execute_go_cmd ( self , cmd , gopath = None , args = None , env = None , workunit_factory = None , workunit_name = None , workunit_labels = None , ** kwargs ) : """Runs a Go command that is optionally targeted to a Go workspace . If a ` workunit _ factory ` is supplied the command will run in a work unit cont...
go_cmd = self . create_go_cmd ( cmd , gopath = gopath , args = args ) if workunit_factory is None : return go_cmd . spawn ( ** kwargs ) . wait ( ) else : name = workunit_name or cmd labels = [ WorkUnitLabel . TOOL ] + ( workunit_labels or [ ] ) with workunit_factory ( name = name , labels = labels , cmd...
def custom_size ( self , minimum : int = 40 , maximum : int = 62 ) -> int : """Generate clothing size using custom format . : param minimum : Minimum value . : param maximum : Maximum value . : return : Clothing size ."""
return self . random . randint ( minimum , maximum )
def out_64 ( library , session , space , offset , data , extended = False ) : """Write in an 64 - bit value from the specified memory space and offset . Corresponds to viOut64 * functions of the VISA library . : param library : the visa library wrapped by ctypes . : param session : Unique logical identifier t...
if extended : return library . viOut64Ex ( session , space , offset , data ) else : return library . viOut64 ( session , space , offset , data )
def get_char ( self , offset = 0 ) : """Return the current character in the working string ."""
if not self . has_space ( offset = offset ) : return '' return self . string [ self . pos + offset ]
def get_candidate_votes ( self , candidate ) : """Get all votes attached to a CandidateElection for a Candidate in this election ."""
candidate_election = CandidateElection . objects . get ( candidate = candidate , election = self ) return candidate_election . votes . all ( )
def format_name ( self ) : """Formats the media file based on enhanced metadata . The actual name of the file and even the name of the directory structure where the file is to be stored ."""
self . formatted_filename = formatter . format_filename ( self . series_name , self . season_number , self . episode_numbers , self . episode_names , self . extension ) self . formatted_dirname = self . location if cfg . CONF . move_files_enabled : self . formatted_dirname = formatter . format_location ( self . ser...
def run_multiple_column_experiment ( ) : """Compare the ideal observer against a multi - column sensorimotor network ."""
# Create the objects featureRange = [ 5 , 10 , 20 , 30 ] pointRange = 1 objectRange = [ 100 ] numLocations = [ 10 ] numPoints = 10 numTrials = 10 columnRange = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] useLocation = 1 resultsDir = os . path . dirname ( os . path . realpath ( __file__ ) ) args = [ ] for c in reversed ( columnRa...
async def is_object_synced_to_cn ( self , client , pid ) : """Check if object with { pid } has successfully synced to the CN . CNRead . describe ( ) is used as it ' s a light - weight HTTP HEAD request . This assumes that the call is being made over a connection that has been authenticated and has read or bet...
try : await client . describe ( pid ) except d1_common . types . exceptions . DataONEException : return False return True
def find_all ( source , substring , start = None , end = None , overlap = False ) : """Return every location a substring can be found in a source string . source The source string to search . start Start offset to read from ( default : start ) end End offset to stop reading at ( default : end ) overla...
return [ x for x in find_all_iter ( source , substring , start , end , overlap ) ]
def get_work_item_template ( self , project , type , fields = None , as_of = None , expand = None ) : """GetWorkItemTemplate . [ Preview API ] Returns a single work item from a template . : param str project : Project ID or project name : param str type : The work item type name : param str fields : Comma -...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if type is not None : route_values [ 'type' ] = self . _serialize . url ( 'type' , type , 'str' ) query_parameters = { } if fields is not None : query_parameters [ 'fields' ] = se...
def load_nameserver_credentials ( self , working_directory , num_tries = 60 , interval = 1 ) : """loads the nameserver credentials in cases where master and workers share a filesystem Parameters working _ directory : str the working directory for the HPB run ( see master ) num _ tries : int number of atte...
fn = os . path . join ( working_directory , 'HPB_run_%s_pyro.pkl' % self . run_id ) for i in range ( num_tries ) : try : with open ( fn , 'rb' ) as fh : self . nameserver , self . nameserver_port = pickle . load ( fh ) return except FileNotFoundError : self . logger . warning...
def _mpl_marker2pgfp_marker ( data , mpl_marker , marker_face_color ) : """Translates a marker style of matplotlib to the corresponding style in PGFPlots ."""
# try default list try : pgfplots_marker = _MP_MARKER2PGF_MARKER [ mpl_marker ] except KeyError : pass else : if ( marker_face_color is not None ) and pgfplots_marker == "o" : pgfplots_marker = "*" data [ "tikz libs" ] . add ( "plotmarks" ) marker_options = None return ( data , pgfpl...
def changed ( self ) : """Tells if module configuration has been changed ( it needs to be saved )"""
# Not installed modules cannot issue a change to save if not self . installed : return False # Check if module status changed if self . _info . _changed : return True # Check model changes for model in self . models ( ) : if model . objects . changed ( ) . count ( ) or model . objects . deleted ( ) . count ...
def add_to_class ( self , cls , name ) : '''Overrides the base class to add a PhoheNumberDescriptor rather than the standard FieldDescriptor'''
self . model_class = cls setattr ( cls , name , PhoneNumberDescriptor ( self ) ) self . _bound = True
def index ( self ) : """Get the index of the day of the week . Returns IntegerValue The index of the day of the week . Ibis follows pandas conventions , where * * Monday = 0 and Sunday = 6 * * ."""
import ibis . expr . operations as ops return ops . DayOfWeekIndex ( self . op ( ) . arg ) . to_expr ( )
def properties ( self ) : """The properties property . Returns : ( hash ) . the property value . ( defaults to : { } )"""
if 'properties' in self . _values : return self . _values [ 'properties' ] self . _values [ 'properties' ] = copy . deepcopy ( self . _defaults [ 'properties' ] ) return self . _values [ 'properties' ]
def has_frames ( self , destination ) : """Whether specified queue has any frames . @ param destination : The queue name ( destinationination ) . @ type destination : C { str } @ return : Whether there are any frames in the specified queue . @ rtype : C { bool }"""
return ( destination in self . queue_metadata ) and bool ( self . queue_metadata [ destination ] [ 'frames' ] )
def slugify ( s ) : """Converts the given string to a URL slug ."""
s = strip_accents ( s . replace ( "'" , '' ) . lower ( ) ) return re . sub ( '[^a-z0-9]+' , ' ' , s ) . strip ( ) . replace ( ' ' , '-' )
def plot_single_configuration ( self , config_nr , sens_file ) : """plot sensitivity distribution with center of mass for a single configuration . The electrodes used are colored . Parameters config _ nr : int number of configuration sens _ file : string , file path filename to sensitvity file"""
indices = elem . load_column_file_to_elements_advanced ( sens_file , [ 2 , 3 ] , False , False ) elem . plt_opt . title = '' elem . plt_opt . reverse = True elem . plt_opt . cbmin = - 1 elem . plt_opt . cbmax = 1 elem . plt_opt . cblabel = r'fill' elem . plt_opt . xlabel = 'x (m)' elem . plt_opt . ylabel = 'z (m)' fig ...
def SaveDataToFD ( self , raw_data , fd ) : """Merge the raw data with the config file and store it ."""
fd . write ( yaml . Dump ( raw_data ) . encode ( "utf-8" ) )
def createCatalog ( config , roi = None , lon = None , lat = None ) : """Create a catalog object"""
import ugali . observation . catalog if roi is None : roi = createROI ( config , lon , lat ) catalog = ugali . observation . catalog . Catalog ( config , roi = roi ) return catalog
def add_magic_table_from_data ( self , dtype , data ) : """Add a MagIC table to the contribution from a data list Parameters dtype : str MagIC table type , i . e . ' specimens ' data : list of dicts data list with format [ { ' key1 ' : ' val1 ' , . . . } , { ' key1 ' : ' val2 ' , . . . } , . . . } ]"""
self . tables [ dtype ] = MagicDataFrame ( dtype = dtype , data = data ) if dtype == 'measurements' : self . tables [ 'measurements' ] . add_sequence ( ) return dtype , self . tables [ dtype ]
def save ( self , revision ) : """: param revision : : type revision : : class : ` revision . data . Revision `"""
if not isinstance ( revision , Revision ) : raise InvalidArgType ( ) self . state . update ( revision )
def build_spec ( user , repo , sha = None , prov = None , extraMetadata = [ ] ) : """Build grlc specification for the given github user / repo ."""
loader = grlc . utils . getLoader ( user , repo , sha = sha , prov = prov ) files = loader . fetchFiles ( ) raw_repo_uri = loader . getRawRepoUri ( ) # Fetch all . rq files items = [ ] allowed_ext = [ "rq" , "sparql" , "json" , "tpf" ] for c in files : glogger . debug ( '>>>>>>>>>>>>>>>>>>>>>>>>>c_name: {}' . forma...
def copy_dependency_images ( tile ) : """Copy all documentation from dependencies into build / output / doc folder"""
env = Environment ( tools = [ ] ) outputbase = os . path . join ( 'build' , 'output' ) depbase = os . path . join ( 'build' , 'deps' ) for dep in tile . dependencies : depdir = os . path . join ( depbase , dep [ 'unique_id' ] ) outputdir = os . path . join ( outputbase ) deptile = IOTile ( depdir ) for ...
def process_actions ( action_ids = None ) : """Process actions in the publishing schedule . Returns the number of actions processed ."""
actions_taken = 0 action_list = PublishAction . objects . prefetch_related ( 'content_object' , ) . filter ( scheduled_time__lte = timezone . now ( ) , ) if action_ids is not None : action_list = action_list . filter ( id__in = action_ids ) for action in action_list : action . process_action ( ) action . de...
def projects_from_cli ( args ) : """Take arguments through the CLI can create a list of specified projects ."""
description = ( 'Determine if a set of project dependencies will work with ' 'Python 3' ) parser = argparse . ArgumentParser ( description = description ) req_help = 'path(s) to a pip requirements file (e.g. requirements.txt)' parser . add_argument ( '--requirements' , '-r' , nargs = '+' , default = ( ) , help = req_he...
def _lti16 ( ins ) : '''Compares & pops top 2 operands out of the stack , and checks if the 1st operand < 2nd operand ( top of the stack ) . Pushes 0 if False , 1 if True . 16 bit signed version'''
output = _16bit_oper ( ins . quad [ 2 ] , ins . quad [ 3 ] ) output . append ( 'call __LTI16' ) output . append ( 'push af' ) REQUIRES . add ( 'lti16.asm' ) return output
def buff ( self , target , buff , ** kwargs ) : """Summon \a buff and apply it to \a target If keyword arguments are given , attempt to set the given values to the buff . Example : player . buff ( target , health = random . randint ( 1 , 5 ) ) NOTE : Any Card can buff any other Card . The controller of the ...
ret = self . controller . card ( buff , self ) ret . source = self ret . apply ( target ) for k , v in kwargs . items ( ) : setattr ( ret , k , v ) return ret
def add_columns ( self , data , column_names = None , inplace = False ) : """Returns an SFrame with multiple columns added . The number of elements in all columns must match the length of every other column of the SFrame . If inplace = = False ( default ) this operation does not modify the current SFrame , ...
datalist = data if isinstance ( data , SFrame ) : other = data datalist = [ other . select_column ( name ) for name in other . column_names ( ) ] column_names = other . column_names ( ) my_columns = set ( self . column_names ( ) ) for name in column_names : if name in my_columns : ...
def PC_varExplained ( Y , standardized = True ) : """Run PCA and calculate the cumulative fraction of variance Args : Y : phenotype values standardize : if True , phenotypes are standardized Returns : var : cumulative distribution of variance explained"""
# figuring out the number of latent factors if standardized : Y -= Y . mean ( 0 ) Y /= Y . std ( 0 ) covY = sp . cov ( Y ) S , U = linalg . eigh ( covY + 1e-6 * sp . eye ( covY . shape [ 0 ] ) ) S = S [ : : - 1 ] rv = np . array ( [ S [ 0 : i ] . sum ( ) for i in range ( 1 , S . shape [ 0 ] ) ] ) rv /= S . sum ...
def get_date_range_this_year ( now = None ) : """Return the starting and ending date of the current school year ."""
if now is None : now = datetime . datetime . now ( ) . date ( ) if now . month <= settings . YEAR_TURNOVER_MONTH : date_start = datetime . datetime ( now . year - 1 , 8 , 1 ) # TODO ; don ' t hardcode these values date_end = datetime . datetime ( now . year , 7 , 1 ) else : date_start = datetime . d...
def resolve ( uri , include_paths ) : """Banana banana"""
include_filename , line_ranges , symbol = __parse_include ( uri ) if include_filename is None : return None include_path = find_file ( include_filename , include_paths ) if include_path is None : return None return __get_content ( include_path . strip ( ) , line_ranges , symbol )
def char_repl ( x ) : """A little embarrassing : couldn ' t figure out how to avoid crashes when hardcore unicode occurs in description fields . . ."""
r = "" for c in x : if ord ( c ) > 255 : r += "?" else : r += c return r
def parse ( self , rule : str ) : """Parses policy to tree . Translate a policy written in the policy language into a tree of Check objects ."""
# Empty rule means always accept if not rule : return checks . TrueCheck ( ) for token , value in self . _parse_tokenize ( rule ) : self . _shift ( token , value ) try : return self . result except ValueError : LOG . exception ( 'Failed to understand rule %r' , rule ) # Fail closed return checks...
def sort ( self , key_or_list , direction = None ) : """Sorts this cursor ' s results . Pass a field name and a direction , either : data : ` ~ pymongo . ASCENDING ` or : data : ` ~ pymongo . DESCENDING ` : : for doc in collection . find ( ) . sort ( ' field ' , pymongo . ASCENDING ) : print ( doc ) To so...
self . __check_okay_to_chain ( ) keys = helpers . _index_list ( key_or_list , direction ) self . __ordering = helpers . _index_document ( keys ) return self
def includeme ( config ) : """Include pyramid _ multiauth into a pyramid configurator . This function provides a hook for pyramid to include the default settings for auth via pyramid _ multiauth . Activate it like so : config . include ( " pyramid _ multiauth " ) This will pull the list of registered authn ...
# Grab the pyramid - wide settings , to look for any auth config . settings = config . get_settings ( ) # Hook up a default AuthorizationPolicy . # Get the authorization policy from config if present . # Default ACLAuthorizationPolicy is usually what you want . authz_class = settings . get ( "multiauth.authorization_po...
def write_dna ( dna , path ) : '''Write DNA to a file ( genbank or fasta ) . : param dna : DNA sequence to write to file : type dna : coral . DNA : param path : file path to write . Has to be genbank or fasta file . : type path : str'''
# Check if path filetype is valid , remember for later ext = os . path . splitext ( path ) [ 1 ] if ext == '.gb' or ext == '.ape' : filetype = 'genbank' elif ext == '.fa' or ext == '.fasta' : filetype = 'fasta' else : raise ValueError ( 'Only genbank or fasta files are supported.' ) # Convert features to Bi...
def get_branding_ids ( self ) : """Gets the branding asset ` ` Ids ` ` . return : ( osid . id . IdList ) - a list of asset ` ` Ids ` ` * compliance : mandatory - - This method must be implemented . *"""
from . . id . objects import IdList if 'brandingIds' not in self . _my_map : return IdList ( [ ] ) id_list = [ ] for idstr in self . _my_map [ 'brandingIds' ] : id_list . append ( Id ( idstr ) ) return IdList ( id_list )
def all_props ( self ) : """Return a dictionary with the values of all children , and place holders for all of the section argumemts . It combines props and arg _ props"""
d = self . arg_props d . update ( self . props ) return d
def transform ( list , pattern , indices = [ 1 ] ) : """Matches all elements of ' list ' agains the ' pattern ' and returns a list of the elements indicated by indices of all successfull matches . If ' indices ' is omitted returns a list of first paranthethised groups of all successfull matches ."""
result = [ ] for e in list : m = re . match ( pattern , e ) if m : for i in indices : result . append ( m . group ( i ) ) return result
def training_config ( estimator , inputs = None , job_name = None , mini_batch_size = None ) : """Export Airflow training config from an estimator Args : estimator ( sagemaker . estimator . EstimatorBase ) : The estimator to export training config from . Can be a BYO estimator , Framework estimator or Amazo...
train_config = training_base_config ( estimator , inputs , job_name , mini_batch_size ) train_config [ 'TrainingJobName' ] = estimator . _current_job_name if estimator . tags is not None : train_config [ 'Tags' ] = estimator . tags return train_config
def _map_reduce ( self , map , reduce , out , session , read_pref , ** kwargs ) : """Internal mapReduce helper ."""
cmd = SON ( [ ( "mapReduce" , self . __name ) , ( "map" , map ) , ( "reduce" , reduce ) , ( "out" , out ) ] ) collation = validate_collation_or_none ( kwargs . pop ( 'collation' , None ) ) cmd . update ( kwargs ) inline = 'inline' in out if inline : user_fields = { 'results' : 1 } else : user_fields = None read...
def prepare_data_keys ( primary_master_key , master_keys , algorithm , encryption_context ) : """Prepares a DataKey to be used for encrypting message and list of EncryptedDataKey objects to be serialized into header . : param primary _ master _ key : Master key with which to generate the encryption data key :...
encrypted_data_keys = set ( ) encrypted_data_encryption_key = None data_encryption_key = primary_master_key . generate_data_key ( algorithm , encryption_context ) _LOGGER . debug ( "encryption data generated with master key: %s" , data_encryption_key . key_provider ) for master_key in master_keys : # Don ' t re - encry...
def get_goid2color_pval ( self ) : """Return a go2color dict containing GO colors determined by P - value ."""
go2color = { } self . set_goid2color_pval ( go2color ) color_dflt = self . alpha2col [ 1.000 ] for goid in self . go2res : if goid not in go2color : go2color [ goid ] = color_dflt return go2color
def update_docstrings ( ) : """update the docstring of each module using info in the modules / README . md file"""
modules_dict = parse_readme ( ) files = { } # update modules for mod in modules_dict : mod_file = os . path . join ( modules_directory ( ) , mod + ".py" ) with open ( mod_file ) as f : files [ mod ] = f . readlines ( ) for mod in files : replaced = False done = False lines = False out = ...
def read_template_source ( filename ) : """Read the source of a Django template , returning the Unicode text ."""
# Import this late to be sure we don ' t trigger settings machinery too # early . from django . conf import settings if not settings . configured : settings . configure ( ) with open ( filename , "rb" ) as f : text = f . read ( ) . decode ( settings . FILE_CHARSET ) return text
def is_email ( ) : """Validates that a fields value is a valid email address ."""
email = ( ur'(?!^\.)' # No dot at start ur'(?!.*\.@)' # No dot before at sign ur'(?!.*@\.)' # No dot after at sign ur'(?!.*\.$)' # No dot at the end ur'(?!.*\.\.)' # No double dots anywhere ur'^\S+' # Starts with one or more non - whitespace characters ur'@' # Contains an at sign ur'\S+$' # Ends with one or more non - ...
def get_subject_with_remote_validation ( jwt_bu64 , base_url ) : """Same as get _ subject _ with _ local _ validation ( ) except that the signing certificate is automatically downloaded from the CN . - Additional possible validations errors : - The certificate could not be retrieved from the root CN ."""
cert_obj = d1_common . cert . x509 . download_as_obj ( base_url ) return get_subject_with_local_validation ( jwt_bu64 , cert_obj )
def c_drop ( self , frequency ) : '''Capacitance of an electrode covered in liquid , normalized per unit area ( i . e . , units are F / mm ^ 2 ) .'''
try : return np . interp ( frequency , self . _c_drop [ 'frequency' ] , self . _c_drop [ 'capacitance' ] ) except : pass return self . _c_drop
def add_to_fileswitcher ( self , plugin , tabs , data , icon ) : """Add a plugin to the File Switcher ."""
if self . fileswitcher is None : from spyder . widgets . fileswitcher import FileSwitcher self . fileswitcher = FileSwitcher ( self , plugin , tabs , data , icon ) else : self . fileswitcher . add_plugin ( plugin , tabs , data , icon ) self . fileswitcher . sig_goto_file . connect ( plugin . get_current_tab...
def _to_meta_data ( pif_obj , dataset_hit , mdf_acl ) : """Convert the meta - data from the PIF into MDF"""
pif = pif_obj . as_dictionary ( ) dataset = dataset_hit . as_dictionary ( ) mdf = { } try : if pif . get ( "names" ) : mdf [ "title" ] = pif [ "names" ] [ 0 ] else : mdf [ "title" ] = "Citrine PIF " + str ( pif [ "uid" ] ) if pif . get ( "chemicalFormula" ) : mdf [ "composition" ] = ...
def _mouseMoveDrag ( moveOrDrag , x , y , xOffset , yOffset , duration , tween = linear , button = None ) : """Handles the actual move or drag event , since different platforms implement them differently . On Windows & Linux , a drag is a normal mouse move while a mouse button is held down . On OS X , a disti...
# The move and drag code is similar , but OS X requires a special drag event instead of just a move event when dragging . # See https : / / stackoverflow . com / a / 2696107/1893164 assert moveOrDrag in ( 'move' , 'drag' ) , "moveOrDrag must be in ('move', 'drag'), not %s" % ( moveOrDrag ) if sys . platform != 'darwin'...
def camel_case_from_underscores ( string ) : """Generate a CamelCase string from an underscore _ string"""
components = string . split ( '_' ) string = '' for component in components : if component in abbreviations : string += component else : string += component [ 0 ] . upper ( ) + component [ 1 : ] . lower ( ) return string
def get_evidence ( assay ) : """Given an activity , return an INDRA Evidence object . Parameters assay : dict an activity from the activities list returned by a query to the API Returns ev : : py : class : ` Evidence ` an : py : class : ` Evidence ` object containing the kinetics of the"""
kin = get_kinetics ( assay ) source_id = assay . get ( 'assay_chembl_id' ) if not kin : return None annotations = { 'kinetics' : kin } chembl_doc_id = str ( assay . get ( 'document_chembl_id' ) ) pmid = get_pmid ( chembl_doc_id ) ev = Evidence ( source_api = 'chembl' , pmid = pmid , source_id = source_id , annotati...
def append_faces ( vertices_seq , faces_seq ) : """Given a sequence of zero - indexed faces and vertices combine them into a single array of faces and a single array of vertices . Parameters vertices _ seq : ( n , ) sequence of ( m , d ) float Multiple arrays of verticesvertex arrays faces _ seq : ( n ,...
# the length of each vertex array vertices_len = np . array ( [ len ( i ) for i in vertices_seq ] ) # how much each group of faces needs to be offset face_offset = np . append ( 0 , np . cumsum ( vertices_len ) [ : - 1 ] ) new_faces = [ ] for offset , faces in zip ( face_offset , faces_seq ) : if len ( faces ) == 0...
def fetchJobStoreFiles ( jobStore , options ) : """Takes a list of file names as glob patterns , searches for these within a given directory , and attempts to take all of the files found and copy them into options . localFilePath . : param jobStore : A fileJobStore object . : param options . fetch : List of...
for jobStoreFile in options . fetch : jobStoreHits = recursiveGlob ( directoryname = options . jobStore , glob_pattern = jobStoreFile ) for jobStoreFileID in jobStoreHits : logger . debug ( "Copying job store file: %s to %s" , jobStoreFileID , options . localFilePath [ 0 ] ) jobStore . readFile ...
def rae ( label , pred ) : """computes the relative absolute error ( condensed using standard deviation formula )"""
numerator = np . mean ( np . abs ( label - pred ) , axis = None ) denominator = np . mean ( np . abs ( label - np . mean ( label , axis = None ) ) , axis = None ) return numerator / denominator
def paw_header ( filename , ppdesc ) : """Parse the PAW abinit header . Examples : Paw atomic data for element Ni - Generated by AtomPAW ( N . Holzwarth ) + AtomPAW2Abinit v3.0.5 28.000 18.000 20061204 : zatom , zion , pspdat 7 7 2 0 350 0 . : pspcod , pspxc , lmax , lloc , mmax , r2well paw3 1305 : pspfmt ...
supported_formats = [ "paw3" , "paw4" , "paw5" ] if ppdesc . format not in supported_formats : raise NotImplementedError ( "format %s not in %s" % ( ppdesc . format , supported_formats ) ) lines = _read_nlines ( filename , - 1 ) summary = lines [ 0 ] header = _dict_from_lines ( lines [ : 5 ] , [ 0 , 3 , 6 , 2 , 2 ]...
def transform_audio ( self , y ) : '''Compute HCQT magnitude . Parameters y : np . ndarray the audio buffer Returns data : dict data [ ' mag ' ] : np . ndarray , shape = ( n _ frames , n _ bins ) The CQT magnitude'''
data = super ( HCQTMag , self ) . transform_audio ( y ) data . pop ( 'phase' ) return data
def edit ( self , body ) : """Edit this comment . : param str body : ( required ) , new body of the comment , Markdown formatted : returns : bool"""
if body : json = self . _json ( self . _patch ( self . _api , data = dumps ( { 'body' : body } ) ) , 200 ) if json : self . _update_ ( json ) return True return False
def ExpireRules ( self ) : """Removes any rules with an expiration date in the past ."""
rules = self . Get ( self . Schema . RULES ) new_rules = self . Schema . RULES ( ) now = time . time ( ) * 1e6 expired_session_ids = set ( ) for rule in rules : if rule . expires > now : new_rules . Append ( rule ) else : for action in rule . actions : if action . hunt_id : ...
def _attributeLinesToDict ( attributeLines ) : """Converts a list of obo ' Term ' lines to a dictionary . : param attributeLines : a list of obo ' Term ' lines . Each line contains a key and a value part which are separated by a ' : ' . : return : a dictionary containing the attributes of an obo ' Term ' entr...
attributes = dict ( ) for line in attributeLines : attributeId , attributeValue = line . split ( ':' , 1 ) attributes [ attributeId . strip ( ) ] = attributeValue . strip ( ) return attributes
def global_request_interceptor ( self ) : # type : ( ) - > Callable """Decorator that can be used to add global request interceptors easily to the builder . The returned wrapper function can be applied as a decorator on any function that processes the input . The function should follow the signature of the ...
def wrapper ( process_func ) : if not callable ( process_func ) : raise SkillBuilderException ( "Global Request Interceptor process_func input parameter " "should be callable" ) class_attributes = { "process" : lambda self , handler_input : process_func ( handler_input ) } request_interceptor = type...