signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _get_fixed_params ( im ) : """Parameters that the user has no influence on . Mostly chosen bases on the input images ."""
p = Parameters ( ) if not isinstance ( im , np . ndarray ) : return p # Dimension of the inputs p . FixedImageDimension = im . ndim p . MovingImageDimension = im . ndim # Always write result , so I can verify p . WriteResultImage = True # How to write the result tmp = DTYPE_NP2ITK [ im . dtype . name ] p . ResultIm...
def add ( self , docs , boost = None , fieldUpdates = None , commit = None , softCommit = False , commitWithin = None , waitFlush = None , waitSearcher = None , overwrite = None , handler = 'update' ) : """Adds or updates documents . Requires ` ` docs ` ` , which is a list of dictionaries . Each key is the fiel...
start_time = time . time ( ) self . log . debug ( "Starting to build add request..." ) message = ElementTree . Element ( 'add' ) if commitWithin : message . set ( 'commitWithin' , commitWithin ) for doc in docs : el = self . _build_doc ( doc , boost = boost , fieldUpdates = fieldUpdates ) message . append (...
def destroy ( self ) : '''Tear down the syndic minion'''
# We borrowed the local clients poller so give it back before # it ' s destroyed . Reset the local poller reference . super ( Syndic , self ) . destroy ( ) if hasattr ( self , 'local' ) : del self . local if hasattr ( self , 'forward_events' ) : self . forward_events . stop ( )
def get_text ( self ) : """Return extended progress bar text"""
done_units = to_reasonable_unit ( self . done , self . units ) current = round ( self . current / done_units [ 'multiplier' ] , 2 ) percent = int ( self . current * 100 / self . done ) return '{0:.2f} of {1:.2f} {2} ({3}%)' . format ( current , done_units [ 'val' ] , done_units [ 'label' ] , percent )
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'custom_language_model' ) and self . custom_language_model is not None : _dict [ 'custom_language_model' ] = self . custom_language_model if hasattr ( self , 'speaker_labels' ) and self . speaker_labels is not None : _dict [ 'speaker_labels' ] = self . speaker_labels return _dict
def get_scalar ( mesh , name , preference = 'cell' , info = False , err = False ) : """Searches both point and cell data for an array Parameters name : str The name of the array to get the range . preference : str , optional When scalars is specified , this is the perfered scalar type to search for in t...
parr = point_scalar ( mesh , name ) carr = cell_scalar ( mesh , name ) if isinstance ( preference , str ) : if preference in [ 'cell' , 'c' , 'cells' ] : preference = CELL_DATA_FIELD elif preference in [ 'point' , 'p' , 'points' ] : preference = POINT_DATA_FIELD else : raise RuntimeE...
def print_lines ( process : Popen ) -> None : """Let a subprocess : func : ` communicate ` , then write both its ` ` stdout ` ` and its ` ` stderr ` ` to our ` ` stdout ` ` ."""
out , err = process . communicate ( ) if out : for line in out . decode ( "utf-8" ) . splitlines ( ) : print ( line ) if err : for line in err . decode ( "utf-8" ) . splitlines ( ) : print ( line )
def read_parquet ( cls , path , engine , columns , ** kwargs ) : """Load a parquet object from the file path , returning a DataFrame . Ray DataFrame only supports pyarrow engine for now . Args : path : The filepath of the parquet file . We only support local files for now . engine : Ray only support pyarr...
from pyarrow . parquet import ParquetFile if cls . read_parquet_remote_task is None : return super ( RayIO , cls ) . read_parquet ( path , engine , columns , ** kwargs ) if not columns : pf = ParquetFile ( path ) columns = [ name for name in pf . metadata . schema . names if not PQ_INDEX_REGEX . match ( nam...
def quattodcm ( quat ) : """Convert quaternion to DCM This function will convert a quaternion to the equivalent rotation matrix , or direction cosine matrix . Parameters : quat - ( 4 , ) numpy array Array defining a quaterion where the quaternion is defined in terms of a vector and a scalar part . The v...
dcm = ( quat [ - 1 ] ** 2 - np . inner ( quat [ 0 : 3 ] , quat [ 0 : 3 ] ) ) * np . eye ( 3 , 3 ) + 2 * np . outer ( quat [ 0 : 3 ] , quat [ 0 : 3 ] ) + 2 * quat [ - 1 ] * hat_map ( quat [ 0 : 3 ] ) return dcm
def _planck_deriv ( self , lam , Teff ) : """Computes the derivative of the monochromatic blackbody intensity using the Planck function . @ lam : wavelength in m @ Teff : effective temperature in K Returns : the derivative of monochromatic blackbody intensity"""
expterm = np . exp ( self . h * self . c / lam / self . k / Teff ) return 2 * self . h * self . c * self . c / self . k / Teff / lam ** 7 * ( expterm - 1 ) ** - 2 * ( self . h * self . c * expterm - 5 * lam * self . k * Teff * ( expterm - 1 ) )
def check_time_event ( oqparam , occupancy_periods ) : """Check the ` time _ event ` parameter in the datastore , by comparing with the periods found in the exposure ."""
time_event = oqparam . time_event if time_event and time_event not in occupancy_periods : raise ValueError ( 'time_event is %s in %s, but the exposure contains %s' % ( time_event , oqparam . inputs [ 'job_ini' ] , ', ' . join ( occupancy_periods ) ) )
def predict ( self , X ) : """Apply transforms to the data , and predict with the final estimator Parameters X : iterable Data to predict on . Must fulfill input requirements of first step of the pipeline . Returns yp : array - like Predicted transformed target"""
Xt , _ , _ = self . _transform ( X ) return self . _final_estimator . predict ( Xt )
def asfreq ( obj , freq , method = None , how = None , normalize = False , fill_value = None ) : """Utility frequency conversion method for Series / DataFrame ."""
if isinstance ( obj . index , PeriodIndex ) : if method is not None : raise NotImplementedError ( "'method' argument is not supported" ) if how is None : how = 'E' new_obj = obj . copy ( ) new_obj . index = obj . index . asfreq ( freq , how = how ) elif len ( obj . index ) == 0 : new...
def query_metric_definition ( self , metric_type , metric_id ) : """Query definition of a single metric id . : param metric _ type : MetricType to be matched ( required ) : param metric _ id : Exact string matching metric id"""
return self . _get ( self . _get_metrics_single_url ( metric_type , metric_id ) )
def restart ( self ) : """Restart application with same args as it was started . Does * * not * * return"""
if self . verbose : print ( "Restarting {} {} ..." . format ( sys . executable , sys . argv ) ) os . execl ( sys . executable , * ( [ sys . executable ] + sys . argv ) )
def _apply_cen_to_throats ( self , p_cen , t_cen , t_norm , men_cen ) : r'''Take the pore center and throat center and work out which way the throat normal is pointing relative to the vector between centers . Offset the meniscus center along the throat vector in the correct direction'''
v = p_cen - t_cen sign = np . sign ( np . sum ( v * t_norm , axis = 1 ) ) c3 = np . vstack ( ( men_cen * sign , men_cen * sign , men_cen * sign ) ) . T coords = t_cen + c3 * t_norm return coords
def parse_options ( metadata ) : """Parse argument options ."""
parser = argparse . ArgumentParser ( description = '%(prog)s usage:' , prog = __prog__ ) setoption ( parser , metadata = metadata ) return parser
def urlsplit ( name ) : """Parse : param : ` name ` into ( netloc , port , ssl )"""
if not ( isinstance ( name , string_types ) ) : name = str ( name ) if not name . startswith ( ( 'http://' , 'https://' ) ) : name = 'http://' + name rv = urlparse ( name ) if rv . scheme == 'https' and rv . port is None : return rv . netloc , 443 , True return rv . netloc . rsplit ( ':' ) [ 0 ] , rv . port...
def _addDBParam ( self , name , value ) : """Adds a database parameter"""
if name [ - 4 : ] == '__OP' : return self . _setComparasionOperator ( name [ : - 4 ] , value ) if name [ - 3 : ] == '.op' : return self . _setComparasionOperator ( name [ : - 3 ] , value ) if name . find ( '__' ) != - 1 : import re name = name . replace ( '__' , '::' ) elif name . find ( '.' ) != - 1 : ...
def convert_dict_to_datetime ( obj_map ) : """converts dictionary representations of datetime back to datetime obj"""
converted_map = { } for key , value in obj_map . items ( ) : if isinstance ( value , dict ) and 'tzinfo' in value . keys ( ) : converted_map [ key ] = datetime . datetime ( ** value ) elif isinstance ( value , dict ) : converted_map [ key ] = convert_dict_to_datetime ( value ) elif isinstanc...
def wrap ( self , string , width ) : """Wrap lines according to width Place ' \n ' whenever necessary"""
if not string or width <= 0 : logging . error ( "invalid string: %s or width: %s" % ( string , width ) ) return False tmp = "" for line in string . splitlines ( ) : if len ( line ) <= width : tmp += line + "\n" continue cur = 0 length = len ( line ) while cur + width < length : ...
def initialize_path ( self , path_num = None ) : """inits producer for next path , i . e . sets current state to initial state"""
for p in self . producers : p . initialize_path ( path_num ) # self . state = copy ( self . initial _ state ) # self . state . path = path _ num self . random . seed ( hash ( self . seed ) + hash ( path_num ) )
def fsl2antstransform ( matrix , reference , moving ) : """Convert an FSL linear transform to an antsrTransform ANTsR function : ` fsl2antsrtransform ` Arguments matrix : ndarray / list 4x4 matrix of transform parameters reference : ANTsImage target image moving : ANTsImage moving image Returns ...
if reference . dimension != 3 : raise ValueError ( 'reference image must be 3 dimensions' ) if reference . pixeltype != 'float' : reference = reference . clone ( 'float' ) if moving . pixeltype != 'float' : moving = moving . clone ( 'float' ) libfn = utils . get_lib_fn ( 'fsl2antstransformF3' ) tx_ptr = lib...
def shell_out_ignore_exitcode ( cmd , stderr = STDOUT , cwd = None ) : """Same as shell _ out but doesn ' t raise if the cmd exits badly ."""
try : return shell_out ( cmd , stderr = stderr , cwd = cwd ) except CalledProcessError as c : return _clean_output ( c . output )
def compute_positions ( cls , screen_width , line ) : """Compute the relative position of the fields on a given line . Args : screen _ width ( int ) : the width of the screen line ( mpdlcd . display _ fields . Field list ) : the list of fields on the line Returns : ( ( int , mpdlcd . display _ fields . ...
# First index left = 1 # Last index right = screen_width + 1 # Current ' flexible ' field flexible = None # Compute the space to the left and to the right of the ( optional ) # flexible field . for field in line : if field . is_flexible ( ) : if flexible : raise FormatError ( 'There can be only ...
def birth ( self ) : '''Create the individual ( compute the spline curve )'''
splineReal = scipy . interpolate . splrep ( self . x , self . y . real ) self . y_int . real = scipy . interpolate . splev ( self . x_int , splineReal ) splineImag = scipy . interpolate . splrep ( self . x , self . y . imag ) self . y_int . imag = scipy . interpolate . splev ( self . x_int , splineImag )
def _code_contents ( code , docstring = None ) : """Return the signature contents of a code object . By providing direct access to the code object of the function , Python makes this extremely easy . Hooray ! Unfortunately , older versions of Python include line number indications in the compiled byte code ...
# contents = [ ] # The code contents depends on the number of local variables # but not their actual names . contents = bytearray ( "{}, {}" . format ( code . co_argcount , len ( code . co_varnames ) ) , 'utf-8' ) contents . extend ( b", " ) contents . extend ( bytearray ( str ( len ( code . co_cellvars ) ) , 'utf-8' )...
def add_dependency ( id = None , name = None , dependency_id = None , dependency_name = None ) : """Add an existing BuildConfiguration as a dependency to another BuildConfiguration ."""
data = add_dependency_raw ( id , name , dependency_id , dependency_name ) if data : return utils . format_json_list ( data )
def dof ( self ) : """Returns the DoF of the robot ( with grippers ) ."""
dof = self . mujoco_robot . dof if self . has_gripper : dof += self . gripper . dof return dof
def _parse_file_modify ( self , info ) : """Parse a filemodify command within a commit . : param info : a string in the format " mode dataref path " ( where dataref might be the hard - coded literal ' inline ' ) ."""
params = info . split ( b' ' , 2 ) path = self . _path ( params [ 2 ] ) mode = self . _mode ( params [ 0 ] ) if params [ 1 ] == b'inline' : dataref = None data = self . _get_data ( b'filemodify' ) else : dataref = params [ 1 ] data = None return commands . FileModifyCommand ( path , mode , dataref , dat...
def stop ( self ) : """Stop the sensor"""
# check that everything is running if not self . _running : logging . warning ( 'Kinect not running. Aborting stop' ) return False # stop subs self . _image_sub . unregister ( ) self . _depth_sub . unregister ( ) self . _camera_info_sub . unregister self . _running = False return True
def update_file_metadata ( self , uri , filename = None , description = None , mtime = None , privacy = None ) : """Update file metadata . uri - - MediaFire file URI Supplying the following keyword arguments would change the metadata on the server side : filename - - rename file description - - set file d...
resource = self . get_resource_by_uri ( uri ) if not isinstance ( resource , File ) : raise ValueError ( 'Expected File, got {}' . format ( type ( resource ) ) ) result = self . api . file_update ( resource [ 'quickkey' ] , filename = filename , description = description , mtime = mtime , privacy = privacy ) return...
def _water ( cls , T , P ) : """Get properties of pure water , Table4 pag 8"""
water = IAPWS95 ( P = P , T = T ) prop = { } prop [ "g" ] = water . h - T * water . s prop [ "gt" ] = - water . s prop [ "gp" ] = 1. / water . rho prop [ "gtt" ] = - water . cp / T prop [ "gtp" ] = water . betas * water . cp / T prop [ "gpp" ] = - 1e6 / ( water . rho * water . w ) ** 2 - water . betas ** 2 * 1e3 * wate...
def plot_lf_hf ( x , xlf , xhf , title = '' ) : '''Plot original signal , low - pass filtered , and high - pass filtered signals Args x : ndarray Signal data array xlf : ndarray Low - pass filtered signal xhf : ndarray High - pass filtered signal title : str Main title of plot'''
from . import plotutils fig , ( ax1 , ax2 , ax3 ) = plt . subplots ( 3 , 1 , sharex = True , sharey = True ) plt . title ( title ) # ax1 . title . set _ text ( ' All freqencies ' ) ax1 . plot ( range ( len ( x ) ) , x , color = _colors [ 0 ] , linewidth = _linewidth , label = 'original' ) ax1 . legend ( loc = 'upper ri...
def assertCategoricalLevelsEqual ( self , levels1 , levels2 , msg = None ) : '''Fail if ` ` levels1 ` ` and ` ` levels2 ` ` do not have the same domain . Parameters levels1 : iterable levels2 : iterable msg : str If not provided , the : mod : ` marbles . mixins ` or : mod : ` unittest ` standard messa...
if not isinstance ( levels1 , collections . Iterable ) : raise TypeError ( 'First argument is not iterable' ) if not isinstance ( levels2 , collections . Iterable ) : raise TypeError ( 'Second argument is not iterable' ) standardMsg = '%s levels != %s levels' % ( levels1 , levels2 ) if not all ( level in levels...
def progress ( self ) : """Returns the percentage , current and total number of jobs in the queue ."""
total = len ( self . all_jobs ) remaining = total - len ( self . active_jobs ) if total > 0 else 0 percent = int ( 100 * ( float ( remaining ) / total ) ) if total > 0 else 0 return percent
def cli ( env , sortby , columns , datacenter , username , storage_type ) : """List file storage ."""
file_manager = SoftLayer . FileStorageManager ( env . client ) file_volumes = file_manager . list_file_volumes ( datacenter = datacenter , username = username , storage_type = storage_type , mask = columns . mask ( ) ) table = formatting . Table ( columns . columns ) table . sortby = sortby for file_volume in file_volu...
def download ( self , file_path = None , verbose = None , silent = None , ignore_existing = None , checksum = None , destdir = None , retries = None , ignore_errors = None , fileobj = None , return_responses = None , no_change_timestamp = None , params = None ) : """Download the file into the current working direct...
verbose = False if verbose is None else verbose ignore_existing = False if ignore_existing is None else ignore_existing checksum = False if checksum is None else checksum retries = 2 if not retries else retries ignore_errors = False if not ignore_errors else ignore_errors return_responses = False if not return_response...
def run_RNAplfold ( input_fasta , tmpdir , W = 240 , L = 160 , U = 1 ) : """Arguments : W , Int : span - window length L , Int , maxiumm span U , Int , size of unpaired region"""
profiles = RNAplfold_PROFILES_EXECUTE for i , P in enumerate ( profiles ) : print ( "running {P}_RNAplfold... ({i}/{N})" . format ( P = P , i = i + 1 , N = len ( profiles ) ) ) command = "{bin}/{P}_RNAplfold" . format ( bin = RNAplfold_BIN_DIR , P = P ) file_out = "{tmp}/{P}_profile.fa" . format ( tmp = tmp...
def deriv2 ( self , p ) : """Second derivative of the Cauchy link function . Parameters p : array - like Probabilities Returns g ' ' ( p ) : array Value of the second derivative of Cauchy link function at ` p `"""
a = np . pi * ( p - 0.5 ) d2 = 2 * np . pi ** 2 * np . sin ( a ) / np . cos ( a ) ** 3 return d2
def get_object ( self , name , * argv , ** kwargs ) : """Get url object tuple for url : param name : url regexp from : type name : str : param argv : overrided args : param kwargs : overrided kwargs : return : url object : rtype : django . conf . urls . url"""
regexp = name options = self . opts ( regexp ) options . update ( kwargs ) args = options . pop ( 'view_args' , argv ) csrf_enable = self . get_backend_data ( regexp ) . get ( 'CSRF_ENABLE' , True ) if regexp in self . settings_urls : regexp = r'^{}' . format ( self . get_django_settings ( regexp ) [ 1 : ] ) view =...
def _set_action_profile_event_actions ( self , v , load = False ) : """Setter method for action _ profile _ event _ actions , mapped from YANG variable / cfm _ state / cfm _ y1731 / action _ profile / action _ profile _ event _ actions ( container ) If this variable is read - only ( config : false ) in the sour...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = action_profile_event_actions . action_profile_event_actions , is_container = 'container' , presence = False , yang_name = "action-profile-event-actions" , rest_name = "action-profile-event-actions" , parent = self , path_help...
def currentView ( cls , parent = None ) : """Returns the current view for the given class within a viewWidget . If no view widget is supplied , then a blank view is returned . : param viewWidget | < projexui . widgets . xviewwidget . XViewWidget > | | None : return < XView > | | None"""
if parent is None : parent = projexui . topWindow ( ) for inst in parent . findChildren ( cls ) : if inst . isCurrent ( ) : return inst return None
def call_api ( self , table , column , value , ** kwargs ) : """Exposed method to connect and query the EPA ' s API ."""
try : output_format = kwargs . pop ( 'output_format' ) except KeyError : output_format = self . output_format url_list = [ self . base_url , table , column , quote ( value ) , 'rows' ] rows_count = self . _number_of_rows ( ** kwargs ) url_list . append ( rows_count ) url_string = '/' . join ( url_list ) xml_dat...
def get_group_entitlement ( self , group_id ) : """GetGroupEntitlement . [ Preview API ] Get a group entitlement . : param str group _ id : ID of the group . : rtype : : class : ` < GroupEntitlement > < azure . devops . v5_0 . member _ entitlement _ management . models . GroupEntitlement > `"""
route_values = { } if group_id is not None : route_values [ 'groupId' ] = self . _serialize . url ( 'group_id' , group_id , 'str' ) response = self . _send ( http_method = 'GET' , location_id = '2280bffa-58a2-49da-822e-0764a1bb44f7' , version = '5.0-preview.1' , route_values = route_values ) return self . _deserial...
def split_pulls ( all_issues , project = "arokem/python-matlab-bridge" ) : """split a list of closed issues into non - PR Issues and Pull Requests"""
pulls = [ ] issues = [ ] for i in all_issues : if is_pull_request ( i ) : pull = get_pull_request ( project , i [ 'number' ] , auth = True ) pulls . append ( pull ) else : issues . append ( i ) return issues , pulls
def send_signal ( self , request , response , forum ) : """Sends the signal associated with the view ."""
self . view_signal . send ( sender = self , forum = forum , user = request . user , request = request , response = response , )
def _call ( self , x , out = None ) : """Evaluate all operators in ` ` x ` ` and broadcast ."""
wrapped_x = self . prod_op . domain . element ( [ x ] , cast = False ) return self . prod_op ( wrapped_x , out = out )
def odo_register ( ) : '''Enable conversion of . sdmx files with odo ( http : / / odo . readthedocs . org ) . Adds conversion from sdmx to PD . DataFrame to odo graph . Note that native discovery of sdmx files is not yet supported . odo will thus convert to PD . DataFrame and discover the data shape from th...
logger . info ( 'Registering with odo...' ) import odo from odo . utils import keywords import pandas as PD from toolz import keyfilter import toolz . curried . operator as op class PandaSDMX ( object ) : def __init__ ( self , uri ) : self . uri = uri @ odo . resource . register ( r'.*\.sdmx' ) def resource...
def _swap_curly ( string ) : """Swap single and double curly brackets"""
return ( string . replace ( '{{ ' , '{{' ) . replace ( '{{' , '\x00' ) . replace ( '{' , '{{' ) . replace ( '\x00' , '{' ) . replace ( ' }}' , '}}' ) . replace ( '}}' , '\x00' ) . replace ( '}' , '}}' ) . replace ( '\x00' , '}' ) )
def create_schema ( self , check_if_exists = False , sync_schema = True , verbosity = 1 ) : """Creates the schema ' schema _ name ' for this tenant . Optionally checks if the schema already exists before creating it . Returns true if the schema was created , false otherwise ."""
# safety check _check_schema_name ( self . schema_name ) cursor = connection . cursor ( ) if check_if_exists and schema_exists ( self . schema_name ) : return False # create the schema cursor . execute ( 'CREATE SCHEMA %s' % self . schema_name ) if sync_schema : call_command ( 'migrate_schemas' , schema_name = ...
def set_window_user_pointer ( window , pointer ) : """Sets the user pointer of the specified window . You may pass a normal python object into this function and it will be wrapped automatically . The object will be kept in existence until the pointer is set to something else or until the window is destroyed . ...
data = ( False , pointer ) if not isinstance ( pointer , ctypes . c_void_p ) : data = ( True , pointer ) # Create a void pointer for the python object pointer = ctypes . cast ( ctypes . pointer ( ctypes . py_object ( pointer ) ) , ctypes . c_void_p ) window_addr = ctypes . cast ( ctypes . pointer ( window )...
def send ( self , tid , session , feature = None ) : '''taobao . logistics . dummy . send 无需物流 ( 虚拟 ) 发货处理 用户调用该接口可实现无需物流 ( 虚拟 ) 发货 , 使用该接口发货 , 交易订单状态会直接变成卖家已发货'''
request = TOPRequest ( 'taobao.logistics.dummy.send' ) request [ 'tid' ] = tid if feature != None : request [ 'feature' ] = feature self . create ( self . execute ( request , session ) ) return self . shipping
def entries ( self ) : """Return the entries ( as a { date : entries } dict ) of all timesheets in the collection ."""
entries_list = self . _timesheets_callback ( 'entries' ) ( ) return reduce ( lambda x , y : x + y , entries_list )
def _choose_unit ( value , unit = None , asciimode = None ) : """Finds a good unit to print seconds in Args : value ( float ) : measured value in seconds unit ( str ) : if specified , overrides heuristic decision asciimode ( bool ) : if True , forces ascii for microseconds Returns : tuple [ ( str , floa...
from collections import OrderedDict micro = _trychar ( 'µs' , 'us' , asciimode ) units = OrderedDict ( [ ( 's' , ( 's' , 1e0 ) ) , ( 'ms' , ( 'ms' , 1e-3 ) ) , ( 'us' , ( micro , 1e-6 ) ) , ( 'ns' , ( 'ns' , 1e-9 ) ) , ] ) if unit is None : for suffix , mag in units . values ( ) : # pragma : nobranch if val...
def rank ( syllabifications ) : '''Rank syllabifications .'''
# def key ( s ) : # word = s [ 0] # w = wsp ( word ) # p = pk _ prom ( word ) # n = nuc ( word ) # t = w + p + n # print ( ' % s \ twsp : % s \ tpk : % s \ tnuc : % s \ ttotal : % s ' % ( word , w , p , n , t ) ) # return w + p + n # syllabifications . sort ( key = key ) syllabifications . sort ( key = lambda s : wsp (...
def list_symbols ( self , all_symbols = False , snapshot = None , regex = None , ** kwargs ) : """Return the symbols in this library . Parameters all _ symbols : ` bool ` If True returns all symbols under all snapshots , even if the symbol has been deleted in the current version ( i . e . it exists under a ...
query = { } if regex is not None : query [ 'symbol' ] = { '$regex' : regex } if kwargs : for k , v in six . iteritems ( kwargs ) : # TODO : this doesn ' t work as expected as it ignores the versions with metadata . deleted set # as a result it will return symbols with matching metadata which have been delet...
def account ( self , id ) : """Fetch account information by user ` id ` . Does not require authentication . Returns a ` user dict ` _ ."""
id = self . __unpack_id ( id ) url = '/api/v1/accounts/{0}' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
def findwalks ( CIJ ) : '''Walks are sequences of linked nodes , that may visit a single node more than once . This function finds the number of walks of a given length , between any two nodes . Parameters CIJ : NxN np . ndarray binary directed / undirected connection matrix Returns Wq : NxNxQ np . nd...
CIJ = binarize ( CIJ , copy = True ) n = len ( CIJ ) Wq = np . zeros ( ( n , n , n ) ) CIJpwr = CIJ . copy ( ) Wq [ : , : , 1 ] = CIJ for q in range ( n ) : CIJpwr = np . dot ( CIJpwr , CIJ ) Wq [ : , : , q ] = CIJpwr twalk = np . sum ( Wq ) # total number of walks wlq = np . sum ( np . sum ( Wq , axis = 0 ) , ...
def mapping_of ( cls ) : """Expects a mapping from some key to data for ` cls ` instances ."""
def mapper ( data ) : if not isinstance ( data , Mapping ) : raise TypeError ( "data must be a mapping, not %s" % type ( data ) . __name__ ) return { key : cls ( value ) for key , value in data . items ( ) } return mapper
def generate_file ( self , r , undistorted = False ) : """Generate file for IIIFRequest object r from this image . FIXME - Would be nicer to have the test for an undistorted image request based on the IIIFRequest object , and then know whether to apply canonicalization or not . Logically we might use ` w , ...
use_canonical = self . get_osd_config ( self . osd_version ) [ 'use_canonical' ] height = None if ( undistorted and use_canonical ) : height = r . size_wh [ 1 ] r . size_wh = [ r . size_wh [ 0 ] , None ] # [ sw , sh ] - > [ sw , ] path = r . url ( ) # Generate . . . if ( self . dryrun ) : self . logger ...
def cmd_migrate ( self , name = None , fake = False ) : """Run migrations ."""
from peewee_migrate . router import Router , LOGGER LOGGER . setLevel ( 'INFO' ) LOGGER . propagate = 0 router = Router ( self . database , migrate_dir = self . app . config [ 'PEEWEE_MIGRATE_DIR' ] , migrate_table = self . app . config [ 'PEEWEE_MIGRATE_TABLE' ] ) migrations = router . run ( name , fake = fake ) if mi...
def process_view ( self , request , view_func , view_args , view_kwargs ) : """Per - request mechanics for the current page object ."""
# Load the closest matching page by slug , and assign it to the # request object . If none found , skip all further processing . slug = path_to_slug ( request . path_info ) pages = Page . objects . with_ascendants_for_slug ( slug , for_user = request . user , include_login_required = True ) if pages : page = pages ...
def add_argparser ( self , root , parents ) : """Add arguments for this command ."""
parser = root . add_parser ( 'diff' , parents = parents ) parser . set_defaults ( func = self ) parser . add_argument ( '--secrets' , dest = 'secrets' , action = 'store' , help = 'Path to the authorization secrets file (client_secrets.json).' ) parser . add_argument ( '-d' , '--data' , dest = 'data_path' , action = 'st...
def frame_apply ( obj , func , axis = 0 , broadcast = None , raw = False , reduce = None , result_type = None , ignore_failures = False , args = None , kwds = None ) : """construct and return a row or column based frame apply object"""
axis = obj . _get_axis_number ( axis ) if axis == 0 : klass = FrameRowApply elif axis == 1 : klass = FrameColumnApply return klass ( obj , func , broadcast = broadcast , raw = raw , reduce = reduce , result_type = result_type , ignore_failures = ignore_failures , args = args , kwds = kwds )
def parse_peddy_csv ( self , f , pattern ) : """Parse csv output from peddy"""
parsed_data = dict ( ) headers = None s_name_idx = None for l in f [ 'f' ] . splitlines ( ) : s = l . split ( "," ) if headers is None : headers = s try : s_name_idx = [ headers . index ( "sample_id" ) ] except ValueError : try : s_name_idx = [ hea...
def _parse_file ( cls , value ) : """Represents value as a string , allowing including text from nearest files using ` file : ` directive . Directive is sandboxed and won ' t reach anything outside directory with setup . py . Examples : file : README . rst , CHANGELOG . md , src / file . txt : param str...
include_directive = 'file:' if not isinstance ( value , string_types ) : return value if not value . startswith ( include_directive ) : return value spec = value [ len ( include_directive ) : ] filepaths = ( os . path . abspath ( path . strip ( ) ) for path in spec . split ( ',' ) ) return '\n' . join ( cls . _...
def add_information_about_person ( self , session_info ) : """If there already are information from this source in the cache this function will overwrite that information"""
session_info = dict ( session_info ) name_id = session_info [ "name_id" ] issuer = session_info . pop ( "issuer" ) self . cache . set ( name_id , issuer , session_info , session_info [ "not_on_or_after" ] ) return name_id
def axis_to_data ( ax , width ) : """For a width in axis coordinates , return the corresponding in data coordinates . Parameters ax : matplotlib . axis Axis object from matplotlib . width : float Width in xaxis coordinates ."""
xlim = ax . get_xlim ( ) widthx = width * ( xlim [ 1 ] - xlim [ 0 ] ) ylim = ax . get_ylim ( ) widthy = width * ( ylim [ 1 ] - ylim [ 0 ] ) return 0.5 * ( widthx + widthy )
def main ( ) : # pragma : no cover """Main entry point ."""
try : # Exit on broken pipe . signal . signal ( signal . SIGPIPE , signal . SIG_DFL ) except AttributeError : # SIGPIPE is not available on Windows . pass try : return _main ( sys . argv , standard_out = sys . stdout , standard_error = sys . stderr ) except KeyboardInterrupt : return 2
def _nicetitle ( coord , value , maxchar , template ) : """Put coord , value in template and truncate at maxchar"""
prettyvalue = format_item ( value , quote_strings = False ) title = template . format ( coord = coord , value = prettyvalue ) if len ( title ) > maxchar : title = title [ : ( maxchar - 3 ) ] + '...' return title
def update_route53 ( self ) : """Update list of Route53 DNS Zones and their records for the account Returns : ` None `"""
self . log . debug ( 'Updating Route53 information for {}' . format ( self . account ) ) # region Update zones existing_zones = DNSZone . get_all ( self . account ) zones = self . __fetch_route53_zones ( ) for resource_id , data in zones . items ( ) : if resource_id in existing_zones : zone = DNSZone . get ...
def stop ( self ) -> None : """Stop monitoring the base unit ."""
self . _shutdown = True # Close connection if needed self . _protocol . close ( ) # Cancel any pending tasks self . cancel_pending_tasks ( )
def make_plot_waveform_plot ( workflow , params , out_dir , ifos , exclude = None , require = None , tags = None ) : """Add plot _ waveform jobs to the workflow ."""
tags = [ ] if tags is None else tags makedir ( out_dir ) name = 'single_template_plot' secs = requirestr ( workflow . cp . get_subsections ( name ) , require ) secs = excludestr ( secs , exclude ) files = FileList ( [ ] ) for tag in secs : node = PlotExecutable ( workflow . cp , 'plot_waveform' , ifos = ifos , out_...
def save_array ( store , arr , ** kwargs ) : """Convenience function to save a NumPy array to the local file system , following a similar API to the NumPy save ( ) function . Parameters store : MutableMapping or string Store or path to directory in file system or name of zip file . arr : ndarray NumPy a...
may_need_closing = isinstance ( store , str ) store = normalize_store_arg ( store , clobber = True ) try : _create_array ( arr , store = store , overwrite = True , ** kwargs ) finally : if may_need_closing and hasattr ( store , 'close' ) : # needed to ensure zip file records are written store . close ( ...
def _loop_thread_main ( self ) : """Main background thread running the event loop ."""
asyncio . set_event_loop ( self . loop ) self . _loop_check . inside_loop = True try : self . _logger . debug ( "Starting loop in background thread" ) self . loop . run_forever ( ) self . _logger . debug ( "Finished loop in background thread" ) except : # pylint : disable = bare - except ; This is a backgro...
def add ( self , item , header_flag = False , align = None ) : """Add a Cell to the row : param item : An element to add to the Cells can be list or Cell object . : type item : basestring , QString , list , Cell : param header _ flag : Flag indicating it the item is a header or not . : type header _ flag : ...
if self . _is_stringable ( item ) or self . _is_qstring ( item ) : self . cells . append ( Cell ( item , header = header_flag , align = align ) ) elif isinstance ( item , Cell ) : self . cells . append ( item ) elif isinstance ( item , Image ) : self . cells . append ( Cell ( item ) ) elif isinstance ( item...
def factor_for_trace ( ls : HilbertSpace , op : Operator ) -> Operator : r'''Given a : class : ` . LocalSpace ` ` ls ` to take the partial trace over and an operator ` op ` , factor the trace such that operators acting on disjoint degrees of freedom are pulled out of the trace . If the operator acts trivially...
if op . space == ls : if isinstance ( op , OperatorTimes ) : pull_out = [ o for o in op . operands if o . space is TrivialSpace ] rest = [ o for o in op . operands if o . space is not TrivialSpace ] if pull_out : return ( OperatorTimes . create ( * pull_out ) * OperatorTrace . cr...
def __hover ( self , ** kwargs ) : """This hovers the particle 1m above the bathymetry WHERE IT WOULD HAVE ENDED UP . This is WRONG and we need to compute the location that it actually hit the bathymetry and hover 1m above THAT ."""
end_point = kwargs . pop ( 'end_point' ) # The location argument here should be the point that intersected the bathymetry , # not the end _ point that is " through " the bathymetry . depth = self . get_depth ( location = end_point ) return Location4D ( latitude = end_point . latitude , longitude = end_point . longitude...
def add_workflow ( self , workflow ) : """Add a sub - workflow to this workflow This function adds a sub - workflow of Workflow class to this workflow . Parent child relationships are determined by data dependencies Parameters workflow : Workflow instance The sub - workflow to add to this one"""
workflow . in_workflow = self self . sub_workflows += [ workflow ] node = workflow . as_job self . _adag . addJob ( node ) node . file . PFN ( os . path . join ( os . getcwd ( ) , node . file . name ) , site = 'local' ) self . _adag . addFile ( node . file ) for inp in self . _external_workflow_inputs : workflow . ...
def layer_description_extractor ( layer , node_to_id ) : '''get layer description .'''
layer_input = layer . input layer_output = layer . output if layer_input is not None : if isinstance ( layer_input , Iterable ) : layer_input = list ( map ( lambda x : node_to_id [ x ] , layer_input ) ) else : layer_input = node_to_id [ layer_input ] if layer_output is not None : layer_outpu...
def MLP ( num_hidden_layers = 2 , hidden_size = 512 , activation_fn = layers . Relu , num_output_classes = 10 , mode = "train" ) : """Multi - layer feed - forward neural network with non - linear activations ."""
del mode cur_layers = [ layers . Flatten ( ) ] for _ in range ( num_hidden_layers ) : cur_layers += [ layers . Dense ( hidden_size ) , activation_fn ( ) ] cur_layers += [ layers . Dense ( num_output_classes ) , layers . LogSoftmax ( ) ] return layers . Serial ( * cur_layers )
def updateFgiAnnotationFromFi ( fgiContainer , fiContainer , largerBetter ) : """# TODO : docstring : param fgiContainer : : param fiContainer : : param largerBetter :"""
for fgi in listvalues ( fgiContainer . container ) : annotations = list ( ) for specfile , fiId in zip ( fgi . specfiles , fgi . featureIds ) : fi = fiContainer . getItem ( specfile , fiId ) if not fi . isAnnotated : continue annotations . append ( [ fi . score , fi . peptide...
def _get ( url : str , headers : dict ) -> dict : """Make a GET call ."""
response = requests . get ( url , headers = headers ) data = response . json ( ) if response . status_code != 200 : raise GoogleApiError ( { "status_code" : response . status_code , "error" : data . get ( "error" , "" ) } ) return data
def get_activities_for_objective ( self , objective_id = None ) : """Gets the activities for the given objective . In plenary mode , the returned list contains all of the activities mapped to the objective Id or an error results if an Id in the supplied list is not found or inaccessible . Otherwise , inacce...
if objective_id is None : raise NullArgument ( ) # Should also check if objective _ id exists ? url_path = construct_url ( 'activities' , bank_id = self . _catalog_idstr , obj_id = objective_id ) return objects . ActivityList ( self . _get_request ( url_path ) )
def format_field ( self , value , format_spec ) : """Override : meth : ` string . Formatter . format _ field ` to have our default format _ spec for : class : ` datetime . Datetime ` objects , and to let None yield an empty string rather than ` ` None ` ` ."""
if isinstance ( value , datetime ) and not format_spec : return super ( ) . format_field ( value , '%Y-%m-%d_%H-%M-%S' ) if value is None : return '' return super ( ) . format_field ( value , format_spec )
def post ( self ) : """POST item to Model post : requestBody : description : Model schema required : true content : application / json : schema : $ ref : ' # / components / schemas / { { self . _ _ class _ _ . _ _ name _ _ } } . post ' responses : 201: description : Item inserted content : ...
if not request . is_json : return self . response_400 ( message = "Request is not JSON" ) try : item = self . add_model_schema . load ( request . json ) except ValidationError as err : return self . response_422 ( message = err . messages ) # This validates custom Schema with custom validations if isinstanc...
def create_keyspace ( name , strategy_class , replication_factor , durable_writes = True , ** replication_values ) : """creates a keyspace : param name : name of keyspace to create : param strategy _ class : keyspace replication strategy class : param replication _ factor : keyspace replication factor : par...
cluster = get_cluster ( ) if name not in cluster . metadata . keyspaces : # try the 1.2 method replication_map = { 'class' : strategy_class , 'replication_factor' : replication_factor } replication_map . update ( replication_values ) if strategy_class . lower ( ) != 'simplestrategy' : # Although the Cassand...
def reload_input_rbridge_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) reload = ET . Element ( "reload" ) config = reload input = ET . SubElement ( reload , "input" ) rbridge_id = ET . SubElement ( input , "rbridge-id" ) rbridge_id . text = kwargs . pop ( 'rbridge_id' ) callback = kwargs . pop ( 'callback' , self . _callback ) return callback ( config )
def _get ( self , url , headers = { } ) : """Get a JSON API endpoint and return the parsed data . : param url : str , * relative * URL ( relative to pp - admin / api endpoint ) : param headers : dict ( optional ) : returns : deferred that when fired returns the parsed data from JSON or errbacks with Product...
# print ( ' getting % s ' % url ) headers = headers . copy ( ) headers [ 'Accept' ] = 'application/json' url = posixpath . join ( self . url , url ) try : response = yield treq . get ( url , headers = headers , timeout = 5 ) if response . code != 200 : err = '%s returned %s' % ( url , response . code ) ...
def fit_for_distance ( self ) : """` ` True ` ` if any of the properties are apparent magnitudes ."""
for prop in self . properties . keys ( ) : if prop in self . ic . bands : return True return False
def get_timestamp ( self , ** kwargs ) : """Retrieves the timestamp for a given set of data"""
timestamp = kwargs . get ( 'timestamp' ) if not timestamp : now = datetime . datetime . utcnow ( ) timestamp = now . strftime ( "%Y-%m-%dT%H:%M:%S" ) + ".%03d" % ( now . microsecond / 1000 ) + "Z" return timestamp
def _fit_spatial ( noise , noise_temporal , mask , template , spatial_sd , temporal_sd , noise_dict , fit_thresh , fit_delta , iterations , ) : """Fit the noise model to match the SNR of the data Parameters noise : multidimensional array , float Initial estimate of the noise noise _ temporal : multidimensio...
# Pull out information that is needed dim_tr = noise . shape base = template * noise_dict [ 'max_activity' ] base = base . reshape ( dim_tr [ 0 ] , dim_tr [ 1 ] , dim_tr [ 2 ] , 1 ) mean_signal = ( base [ mask > 0 ] ) . mean ( ) target_snr = noise_dict [ 'snr' ] # Iterate through different parameters to fit SNR and SFN...
def cluster ( data , inputs , verbose = False ) : """Clusters data Using the new offset model , this method uses a greedy algorithm to cluster the data . It starts with all the data points in separate clusters and tests whether combining them increases the overall log - likelihood ( LL ) . It then iterative...
N = len ( data ) # Define a set of N active cluster active = [ ] for p in range ( 0 , N ) : active . append ( [ p ] ) loglikes = np . zeros ( len ( active ) ) loglikes [ : ] = None pairloglikes = np . zeros ( [ len ( active ) , len ( active ) ] ) pairloglikes [ : ] = None pairoffset = np . zeros ( [ len ( active ) ...
def get_media_metadata ( self , item_id ) : """Get metadata for a media item . Args : item _ id ( str ) : The item for which metadata is required . Returns : ~ collections . OrderedDict : The item ' s metadata , or ` None ` See also : The Sonos ` getMediaMetadata API < http : / / musicpartners . sonos...
response = self . soap_client . call ( 'getMediaMetadata' , [ ( 'id' , item_id ) ] ) return response . get ( 'getMediaMetadataResult' , None )
def create_config_files ( directory ) : """Initialize directory ready for vpn walker : param directory : the path where you want this to happen : return :"""
# Some constant strings vpn_gate_url = "http://www.vpngate.net/api/iphone/" if not os . path . exists ( directory ) : os . makedirs ( directory ) # get csv into memory csv_str = "" logging . info ( "Downloading info from VPN Gate API..." ) r = requests . get ( vpn_gate_url ) for line in r . text . split ( '\n' ) : ...
def _lock ( self ) : """Lock the config DB ."""
if not self . locked : self . device . cu . lock ( ) self . locked = True
def post_process ( self , post_list , req , resp , params ) : """Post - process the extensions for the action . If any post - processing extension ( specified by ` post _ list ` , which should be generated by the pre _ process ( ) method ) yields a value which tests as True , the response being considered by ...
# Walk through the post - processing extensions for ext in post_list : if inspect . isgenerator ( ext ) : try : result = ext . send ( resp ) except StopIteration : # Expected , but not required result = None # If it returned a response , use that for subsequent ...
def orthogonal ( * args ) -> bool : """Determine if a set of arrays are orthogonal . Parameters args : array - likes or array shapes Returns bool Array orthogonality condition ."""
for i , arg in enumerate ( args ) : if hasattr ( arg , "shape" ) : args [ i ] = arg . shape for s in zip ( * args ) : if np . product ( s ) != max ( s ) : return False return True
def read ( self , size = - 1 ) : """Read bytes and update the progress bar ."""
buf = self . _fd . read ( size ) self . _progress_cb ( len ( buf ) ) return buf