signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
async def get_instances ( self , ** kwargs ) -> List [ ApiResource ] : """Returns a list of resource instances . : raises PvApiError when a hub problem occurs ."""
raw_resources = await self . get_resources ( ** kwargs ) _instances = [ self . _resource_factory ( _raw ) for _raw in self . _loop_raw ( raw_resources ) ] return _instances
def obj_deref ( ref ) : """Returns the object identified by ` ref `"""
from indico_livesync . models . queue import EntryType if ref [ 'type' ] == EntryType . category : return Category . get_one ( ref [ 'category_id' ] ) elif ref [ 'type' ] == EntryType . event : return Event . get_one ( ref [ 'event_id' ] ) elif ref [ 'type' ] == EntryType . session : return Session . get_on...
def setDraw ( self , p0 = ( 0 , 0 ) , angle = 0 , mode = 'plain' ) : """set element visualization drawing : param p0 : start drawing position , ( x , y ) : param angle : rotation angle [ deg ] of drawing central point , angle is rotating from x - axis to be ' + ' or ' - ' , ' + ' : anticlockwise , ' - ' : clock...
sconf = self . getConfig ( type = 'simu' ) self . _style [ 'w' ] = float ( sconf [ 'l' ] ) # element width _width = self . _style [ 'w' ] _height = self . _style [ 'h' ] _fc = self . _style [ 'fc' ] _ec = self . _style [ 'ec' ] _alpha = self . _style [ 'alpha' ] _kval = float ( sconf [ 'k1' ] ) _lw = self . _style [ 'l...
def get_interface_detail_output_interface_line_protocol_state ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_interface_detail = ET . Element ( "get_interface_detail" ) config = get_interface_detail output = ET . SubElement ( get_interface_detail , "output" ) interface = ET . SubElement ( output , "interface" ) interface_type_key = ET . SubElement ( interface , "interface-type" ) interfac...
def filter_table ( table , * column_filters ) : """Apply one or more column slice filters to a ` Table ` Multiple column filters can be given , and will be applied concurrently Parameters table : ` ~ astropy . table . Table ` the table to filter column _ filter : ` str ` , ` tuple ` a column slice fil...
keep = numpy . ones ( len ( table ) , dtype = bool ) for name , op_func , operand in parse_column_filters ( * column_filters ) : col = table [ name ] . view ( numpy . ndarray ) keep &= op_func ( col , operand ) return table [ keep ]
def colRowIsOnSciencePixel ( self , col , row , padding = DEFAULT_PADDING ) : """Is col row on a science pixel ? Ranges taken from Fig 25 or Instrument Handbook ( p50) Padding allows for the fact that distortion means the results from getColRowWithinChannel can be off by a bit . Setting padding > 0 means th...
if col < 12. - padding or col > 1111 + padding : return False if row < 20 - padding or row > 1043 + padding : return False return True
def create_entry_tag ( sender , instance , created , ** kwargs ) : """Creates EntryTag for Entry corresponding to specified ItemBase instance . : param sender : the sending ItemBase class . : param instance : the ItemBase instance ."""
from . . models import ( Entry , EntryTag ) entry = Entry . objects . get_for_model ( instance . content_object ) [ 0 ] tag = instance . tag if not EntryTag . objects . filter ( tag = tag , entry = entry ) . exists ( ) : EntryTag . objects . create ( tag = tag , entry = entry )
def from_dict ( cls , val ) : """Creates dict2 object from dict object Args : val ( : obj : ` dict ` ) : Value to create from Returns : Equivalent dict2 object ."""
if isinstance ( val , dict2 ) : return val elif isinstance ( val , dict ) : res = cls ( ) for k , v in val . items ( ) : res [ k ] = cls . from_dict ( v ) return res elif isinstance ( val , list ) : res = [ ] for item in val : res . append ( cls . from_dict ( item ) ) return ...
def queue_push ( self , key , value , create = False , ** kwargs ) : """Add an item to the end of a queue . : param key : The document ID of the queue : param value : The item to add to the queue : param create : Whether the queue should be created if it does not exist : param kwargs : Arguments to pass to ...
return self . list_prepend ( key , value , ** kwargs )
def RtlGetVersion ( os_version_info_struct ) : """Wraps the lowlevel RtlGetVersion routine . Args : os _ version _ info _ struct : instance of either a RTL _ OSVERSIONINFOW structure or a RTL _ OSVERSIONINFOEXW structure , ctypes . Structure - wrapped , with the dwOSVersionInfoSize field preset to ctype...
rc = ctypes . windll . Ntdll . RtlGetVersion ( ctypes . byref ( os_version_info_struct ) ) if rc != 0 : raise OSError ( "Getting Windows version failed." )
def get_secondary_strain_data ( self , strain_data = None ) : '''Calculate the following and add to data dictionary : 1 ) 2nd invarient of strain 2 ) Dilatation rate 3 ) e1h and e2h 4 ) err : param dict strain _ data : Strain data dictionary ( as described ) - will overwrite current data if input'''
if strain_data : self . data = strain_data if not isinstance ( self . data , dict ) : raise ValueError ( 'Strain data not input or incorrectly formatted' ) # Check to ensure essential attributes are in data dictionary for essential_key in DATA_VARIABLES : if essential_key not in self . data : print ...
def exposures_for_layer ( layer_geometry_key ) : """Get hazard categories form layer _ geometry _ key : param layer _ geometry _ key : The geometry key : type layer _ geometry _ key : str : returns : List of hazard : rtype : list"""
result = [ ] for exposure in exposure_all : if layer_geometry_key in exposure . get ( 'allowed_geometries' ) : result . append ( exposure ) return sorted ( result , key = lambda k : k [ 'key' ] )
def convertfields_old ( key_comm , obj , inblock = None ) : """convert the float and interger fields"""
convinidd = ConvInIDD ( ) typefunc = dict ( integer = convinidd . integer , real = convinidd . real ) types = [ ] for comm in key_comm : types . append ( comm . get ( 'type' , [ None ] ) [ 0 ] ) convs = [ typefunc . get ( typ , convinidd . no_type ) for typ in types ] try : inblock = list ( inblock ) except Typ...
def publishMap ( self , maps_info , fsInfo = None , itInfo = None ) : """Publishes a list of maps . Args : maps _ info ( list ) : A list of JSON configuration maps to publish . Returns : list : A list of results from : py : meth : ` arcrest . manageorg . _ content . UserItem . updateItem ` ."""
if self . securityhandler is None : print ( "Security handler required" ) return itemInfo = None itemId = None map_results = None replaceInfo = None replaceItem = None map_info = None admin = None try : admin = arcrest . manageorg . Administration ( securityHandler = self . _securityHandler ) map_result...
def get_accounts ( self , provider = 'aws' ) : """Get Accounts added to Spinnaker . Args : provider ( str ) : What provider to find accounts for . Returns : list : list of dicts of Spinnaker credentials matching _ provider _ . Raises : AssertionError : Failure getting accounts from Spinnaker ."""
url = '{gate}/credentials' . format ( gate = API_URL ) response = requests . get ( url , verify = GATE_CA_BUNDLE , cert = GATE_CLIENT_CERT ) assert response . ok , 'Failed to get accounts: {0}' . format ( response . text ) all_accounts = response . json ( ) self . log . debug ( 'Accounts in Spinnaker:\n%s' , all_accoun...
def ls ( path ) : """List files on HDFS . : param path : A string ( potentially with wildcards ) . : rtype : A list of strings representing HDFS paths . : raises : IOError : An error occurred listing the directory ( e . g . , not available ) ."""
rcode , stdout , stderr = _checked_hadoop_fs_command ( 'hadoop fs -ls %s' % path ) found_line = lambda x : re . search ( 'Found [0-9]+ items$' , x ) out = [ x . split ( ' ' ) [ - 1 ] for x in stdout . split ( '\n' ) if x and not found_line ( x ) ] return out
def _get_cert_url ( self ) : """Get the signing certificate URL . Only accept urls that match the domains set in the AWS _ SNS _ BOUNCE _ CERT _ TRUSTED _ DOMAINS setting . Sub - domains are allowed . i . e . if amazonaws . com is in the trusted domains then sns . us - east - 1 . amazonaws . com will match ...
cert_url = self . _data . get ( 'SigningCertURL' ) if cert_url : if cert_url . startswith ( 'https://' ) : url_obj = urlparse ( cert_url ) for trusted_domain in settings . BOUNCE_CERT_DOMAINS : parts = trusted_domain . split ( '.' ) if url_obj . netloc . split ( '.' ) [ - len...
def set_branch_ids ( self ) : """Performs generation and setting of ids of branches for all MV and underlying LV grids . See Also ding0 . core . network . grids . MVGridDing0 . set _ branch _ ids"""
for grid_district in self . mv_grid_districts ( ) : grid_district . mv_grid . set_branch_ids ( ) logger . info ( '=====> Branch IDs set' )
def code128 ( self , data , ** kwargs ) : """Renders given ` ` data ` ` as * * Code 128 * * barcode symbology . : param str codeset : Optional . Keyword argument for the subtype ( code set ) to render . Defaults to : attr : ` escpos . barcode . CODE128 _ A ` . . . warning : : You should draw up your data ac...
if not re . match ( r'^[\x20-\x7F]+$' , data ) : raise ValueError ( 'Invalid Code 128 symbology. Code 128 can encode ' 'any ASCII character ranging from 32 (20h) to 127 (7Fh); ' 'got {!r}' . format ( data ) ) codeset = kwargs . pop ( 'codeset' , barcode . CODE128_A ) barcode . validate_barcode_args ( ** kwargs ) re...
def json_schema ( self , ** add_keys ) : """Convert our compact schema representation to the standard , but more verbose , JSON Schema standard . Example JSON schema : http : / / json - schema . org / examples . html Core standard : http : / / json - schema . org / latest / json - schema - core . html : par...
self . _json_schema_keys = add_keys if self . _json_schema is None : self . _json_schema = self . _build_schema ( self . _schema ) return self . _json_schema
def file_root_name ( name ) : """Returns the root name of a file from a full file path . It will not raise an error if the result is empty , but an warning will be issued ."""
base = os . path . basename ( name ) root = os . path . splitext ( base ) [ 0 ] if not root : warning = 'file_root_name returned an empty root name from \"{0}\"' log . warning ( warning . format ( name ) ) return root
def _replace_with_new_dims ( # type : ignore self : T , variables : 'OrderedDict[Any, Variable]' = None , coord_names : set = None , attrs : 'Optional[OrderedDict]' = __default , indexes : 'Optional[OrderedDict[Any, pd.Index]]' = __default , inplace : bool = False , ) -> T : """Replace variables with recalculated d...
dims = dict ( calculate_dimensions ( variables ) ) return self . _replace ( variables , coord_names , dims , attrs , indexes , inplace = inplace )
def _augment ( graph , capacity , flow , source , target ) : """find a shortest augmenting path"""
n = len ( graph ) A = [ 0 ] * n # A [ v ] = min residual cap . on path source - > v augm_path = [ None ] * n # None = node was not visited yet Q = deque ( ) # BFS Q . append ( source ) augm_path [ source ] = source A [ source ] = float ( 'inf' ) while Q : u = Q . popleft ( ) for v in graph [ u ] : cuv =...
def _request ( self , method , url , params , headers , content , form_content ) : # type : ( str , str , Optional [ Dict [ str , str ] ] , Optional [ Dict [ str , str ] ] , Any , Optional [ Dict [ str , Any ] ] ) - > ClientRequest """Create ClientRequest object . : param str url : URL for the request . : param...
request = ClientRequest ( method , self . format_url ( url ) ) if params : request . format_parameters ( params ) if headers : request . headers . update ( headers ) # All requests should contain a Accept . # This should be done by Autorest , but wasn ' t in old Autorest # Force it for now , but might deprecate...
def p_expression_eq ( self , p ) : 'expression : expression EQ expression'
p [ 0 ] = Eq ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def _metric_names_for_training_job ( self ) : """Helper method to discover the metrics defined for a training job ."""
training_description = self . _sage_client . describe_training_job ( TrainingJobName = self . _training_job_name ) metric_definitions = training_description [ 'AlgorithmSpecification' ] [ 'MetricDefinitions' ] metric_names = [ md [ 'Name' ] for md in metric_definitions ] return metric_names
def download_content ( self , dir_path = '' , filename = None , force_download = False ) : """Download the content for this document to a file : type dir _ path : String : param dir _ path : the path to which to write the data : type filename : String : param filename : filename to write to ( if None , defa...
if filename is None : filename = self . get_filename ( ) path = os . path . join ( dir_path , filename ) data = self . client . get_document ( self . url ( ) , force_download ) with open ( path , 'wb' ) as f : f . write ( data ) return path
def addLengthMeters ( stream_network ) : """Adds length field in meters to network ( The added field name will be ' LENGTH _ M ' ) . . . note : : This may be needed for generating the kfac file depending on the units of your raster . See : : doc : ` gis _ tools ` . Parameters stream _ network : str Path...
network_shapefile = ogr . Open ( stream_network , 1 ) network_layer = network_shapefile . GetLayer ( ) network_layer_defn = network_layer . GetLayerDefn ( ) # make sure projection EPSG : 4326 network_layer_proj = network_layer . GetSpatialRef ( ) geographic_proj = osr . SpatialReference ( ) geographic_proj . ImportFrom...
def _pluck_provider_state ( raw_provider_state : Dict ) -> ProviderState : """> > > _ pluck _ provider _ state ( { ' name ' : ' there is an egg ' } ) ProviderState ( descriptor = ' there is an egg ' , params = None ) > > > _ pluck _ provider _ state ( { ' name ' : ' there is an egg called ' , ' params ' : { ' n...
return ProviderState ( descriptor = raw_provider_state [ 'name' ] , params = raw_provider_state . get ( 'params' ) )
def _create_cluster_connection ( self , node ) : """Create a connection to a Redis server . : param node : The node to connect to : type node : tredis . cluster . ClusterNode"""
LOGGER . debug ( 'Creating a cluster connection to %s:%s' , node . ip , node . port ) conn = _Connection ( node . ip , node . port , 0 , self . _read , self . _on_closed , self . io_loop , cluster_node = True , read_only = 'slave' in node . flags , slots = node . slots ) self . io_loop . add_future ( conn . connect ( )...
def related_to ( self ) : """returns a list of all parameters that are either constrained by or constrain this parameter"""
params = [ ] constraints = self . in_constraints if self . is_constraint is not None : constraints . append ( self . is_constraint ) for constraint in constraints : for var in constraint . _vars : param = var . get_parameter ( ) if param not in params and param . uniqueid != self . uniqueid : ...
def getele ( fele , up = None , verbose = False ) : """Reads t . 1 . ele , returns a list of elements . Example : > > > elements , regions = self . getele ( " t . 1 . ele " , MyBar ( " elements : " ) ) > > > elements [ ( 20 , 154 , 122 , 258 ) , ( 86 , 186 , 134 , 238 ) , ( 15 , 309 , 170 , 310 ) , ( 146, ...
f = file ( fele ) l = [ int ( x ) for x in f . readline ( ) . split ( ) ] ntetra , nnod , nattrib = l # we have either linear or quadratic tetrahedra : elem = None if nnod in [ 4 , 10 ] : elem = '3_4' linear = ( nnod == 4 ) if nnod in [ 3 , 7 ] : elem = '2_3' linear = ( nnod == 3 ) if elem is None or no...
def image ( self , tag , image , step = None ) : """Saves RGB image summary from onp . ndarray [ H , W ] , [ H , W , 1 ] , or [ H , W , 3 ] . Args : tag : str : label for this data image : ndarray : [ H , W ] , [ H , W , 1 ] , [ H , W , 3 ] save image in greyscale or colors / step : int : training step"""
image = onp . array ( image ) if step is None : step = self . _step else : self . _step = step if len ( onp . shape ( image ) ) == 2 : image = image [ : , : , onp . newaxis ] if onp . shape ( image ) [ - 1 ] == 1 : image = onp . repeat ( image , 3 , axis = - 1 ) image_strio = io . BytesIO ( ) plt . imsa...
def moving_statistic ( values , statistic , size , start = 0 , stop = None , step = None , ** kwargs ) : """Calculate a statistic in a moving window over ` values ` . Parameters values : array _ like The data to summarise . statistic : function The statistic to compute within each window . size : int ...
windows = index_windows ( values , size , start , stop , step ) # setup output out = np . array ( [ statistic ( values [ i : j ] , ** kwargs ) for i , j in windows ] ) return out
def WriteEventBody ( self , event ) : """Writes the body of an event object to the output . Args : event ( EventObject ) : event ."""
if not hasattr ( event , 'timestamp' ) : return row = self . _GetSanitizedEventValues ( event ) try : self . _cursor . execute ( self . _INSERT_QUERY , row ) except MySQLdb . Error as exception : logger . warning ( 'Unable to insert into database with error: {0!s}.' . format ( exception ) ) self . _count +=...
def read ( self , size ) : """Read wrapper . Parameters size : int Number of bytes to read ."""
try : return_val = self . handle . read ( size ) if return_val == '' : print ( ) print ( "Piksi disconnected" ) print ( ) raise IOError return return_val except OSError : print ( ) print ( "Piksi disconnected" ) print ( ) raise IOError
def _create_record_internal ( self , rtype , name , content , identifier = None ) : """Create a new DNS entry in the domain zone if it does not already exist . Args : rtype ( str ) : The DNS type ( e . g . A , TXT , MX , etc ) of the new entry . name ( str ) : The name of the new DNS entry , e . g the domain ...
name = self . _relative_name ( name ) if name is not None else name LOGGER . debug ( 'Creating record with name %s' , name ) if self . _is_duplicate_record ( rtype , name , content ) : return True data = self . _get_post_data_to_create_dns_entry ( rtype , name , content , identifier ) LOGGER . debug ( 'Create DNS d...
def regon_checksum ( digits ) : """Calculates and returns a control digit for given list of digits basing on REGON standard ."""
weights_for_check_digit = [ 8 , 9 , 2 , 3 , 4 , 5 , 6 , 7 ] check_digit = 0 for i in range ( 0 , 8 ) : check_digit += weights_for_check_digit [ i ] * digits [ i ] check_digit %= 11 if check_digit == 10 : check_digit = 0 return check_digit
def bootstrap ( ** kwargs ) : """Bootstrap an EC2 instance that has been booted into an AMI from http : / / www . daemonology . net / freebsd - on - ec2/ Note : deprecated , current AMI images are basically pre - bootstrapped , they just need to be configured ."""
# the user for the image is ` ec2 - user ` , there is no sudo , but we can su to root w / o password original_host = env . host_string env . host_string = 'ec2-user@%s' % env . instance . uid bootstrap_files = env . instance . config . get ( 'bootstrap-files' , 'bootstrap-files' ) put ( '%s/authorized_keys' % bootstrap...
def _build_lv_grid_dict ( network ) : """Creates dict of LV grids LV grid ids are used as keys , LV grid references as values . Parameters network : : class : ` ~ . grid . network . Network ` The eDisGo container object Returns : obj : ` dict ` Format : { : obj : ` int ` : : class : ` ~ . grid . grids...
lv_grid_dict = { } for lv_grid in network . mv_grid . lv_grids : lv_grid_dict [ lv_grid . id ] = lv_grid return lv_grid_dict
def _get_mpr_table ( self , connection , partition ) : """Returns name of the postgres table who stores mpr data . Args : connection : connection to postgres db who stores mpr data . partition ( orm . Partition ) : Returns : str : Raises : MissingTableError : if partition table not found in the db .""...
# TODO : This is the first candidate for optimization . Add field to partition # with table name and update it while table creation . # Optimized version . # return partition . mpr _ table or raise exception # Not optimized version . # first check either partition has materialized view . logger . debug ( 'Looking for m...
def update_ipsecpolicy ( self , ipsecpolicy , body = None ) : """Updates an IPsecPolicy ."""
return self . put ( self . ipsecpolicy_path % ( ipsecpolicy ) , body = body )
def create_pymol_selection_from_PDB_residue_ids ( residue_list ) : '''Elements of residue _ list should be strings extracted from PDB lines from position 21-26 inclusive ( zero - indexing ) i . e . the chain letter concatenated by the 5 - character ( including insertion code ) residue ID .'''
residues_by_chain = { } for residue_id in residue_list : chain_id = residue_id [ 0 ] pruned_residue_id = residue_id [ 1 : ] residues_by_chain [ chain_id ] = residues_by_chain . get ( chain_id , [ ] ) residues_by_chain [ chain_id ] . append ( pruned_residue_id ) str = [ ] for chain_id , residue_list in s...
def elapsed ( self , label = None , total = True ) : """Get elapsed time since timer start . Parameters label : string , optional ( default None ) Specify the label of the timer for which the elapsed time is required . If it is ` ` None ` ` , the default timer with label specified by the ` ` dfltlbl ` ` p...
# Get current time t = timer ( ) # Default label is self . dfltlbl if label is None : label = self . dfltlbl # Return 0.0 if default timer selected and it is not initialised if label not in self . t0 : return 0.0 # Raise exception if timer with specified label does not exist if label not in self . t...
def getProjectionMatrix ( self , eEye , fNearZ , fFarZ ) : """The projection matrix for the specified eye"""
fn = self . function_table . getProjectionMatrix result = fn ( eEye , fNearZ , fFarZ ) return result
def make_unicode ( string ) : """Python 2 and 3 compatibility function that converts a string to Unicode . In case of Unicode , the string is returned unchanged : param string : input string : return : Unicode string"""
if sys . version < '3' and isinstance ( string , str ) : return unicode ( string . decode ( 'utf-8' ) ) return string
def shap_values ( self , X ) : """Estimate the SHAP values for a set of samples . Parameters X : numpy . array or pandas . DataFrame A matrix of samples ( # samples x # features ) on which to explain the model ' s output . Returns For models with a single output this returns a matrix of SHAP values ( # ...
# convert dataframes if str ( type ( X ) ) . endswith ( "pandas.core.series.Series'>" ) : X = X . values elif str ( type ( X ) ) . endswith ( "'pandas.core.frame.DataFrame'>" ) : X = X . values # assert str ( type ( X ) ) . endswith ( " ' numpy . ndarray ' > " ) , " Unknown instance type : " + str ( type ( X ) ...
def _parse_tables ( cls , parsed_content ) : """Parses the information tables found in a world ' s information page . Parameters parsed _ content : : class : ` bs4 . BeautifulSoup ` A : class : ` BeautifulSoup ` object containing all the content . Returns : class : ` OrderedDict ` [ : class : ` str ` , : ...
tables = parsed_content . find_all ( 'div' , attrs = { 'class' : 'TableContainer' } ) output = OrderedDict ( ) for table in tables : title = table . find ( "div" , attrs = { 'class' : 'Text' } ) . text title = title . split ( "[" ) [ 0 ] . strip ( ) inner_table = table . find ( "div" , attrs = { 'class' : '...
def compute_quality_score ( self , quality ) : """Compute the score related to the quality of that dataset ."""
score = 0 UNIT = 2 if 'frequency' in quality : # TODO : should be related to frequency . if quality [ 'update_in' ] < 0 : score += UNIT else : score -= UNIT if 'tags_count' in quality : if quality [ 'tags_count' ] > 3 : score += UNIT if 'description_length' in quality : if qualit...
def mouse_up ( self , window , button ) : """Send a mouse release ( aka mouse up ) for a given button at the current mouse location . : param window : The window you want to send the event to or CURRENTWINDOW : param button : The mouse button . Generally , 1 is left , 2 is middle , 3 is right , 4 is whe...
_libxdo . xdo_mouse_up ( self . _xdo , ctypes . c_ulong ( window ) , ctypes . c_int ( button ) )
def listPhysicsGroups ( self , physics_group_name = "" ) : """Returns all physics groups if physics group names are not passed ."""
if not isinstance ( physics_group_name , basestring ) : dbsExceptionHandler ( 'dbsException-invalid-input' , 'physics group name given is not valid : %s' % physics_group_name ) else : try : physics_group_name = str ( physics_group_name ) except : dbsExceptionHandler ( 'dbsException-invalid-i...
def list_all_zones_by_id ( region = None , key = None , keyid = None , profile = None ) : '''List , by their IDs , all hosted zones in the bound account . region Region to connect to . key Secret key to be used . keyid Access key to be used . profile A dict with region , key and keyid , or a pillar ...
ret = describe_hosted_zones ( region = region , key = key , keyid = keyid , profile = profile ) return [ r [ 'Id' ] . replace ( '/hostedzone/' , '' ) for r in ret ]
def send_spyder_msg ( self , spyder_msg_type , content = None , data = None ) : """Publish custom messages to the Spyder frontend . Parameters spyder _ msg _ type : str The spyder message type content : dict The ( JSONable ) content of the message data : any Any object that is serializable by cloudpic...
import cloudpickle if content is None : content = { } content [ 'spyder_msg_type' ] = spyder_msg_type msg = self . session . send ( self . iopub_socket , 'spyder_msg' , content = content , buffers = [ cloudpickle . dumps ( data , protocol = PICKLE_PROTOCOL ) ] , parent = self . _parent_header , ) self . log . debug...
def generator ( self , Xgen , Xexc , Xgov , Vgen ) : """Generator model . Based on Generator . m from MatDyn by Stijn Cole , developed at Katholieke Universiteit Leuven . See U { http : / / www . esat . kuleuven . be / electa / teaching / matdyn / } for more information ."""
generators = self . dyn_generators omegas = 2 * pi * self . freq F = zeros ( Xgen . shape ) typ1 = [ g . _i for g in generators if g . model == CLASSICAL ] typ2 = [ g . _i for g in generators if g . model == FOURTH_ORDER ] # Generator type 1 : classical model omega = Xgen [ typ1 , 1 ] Pm0 = Xgov [ typ1 , 0 ] H = array ...
def get_surveys ( self , url = _SURVEYS_URL ) : """Function to get the surveys for the account"""
res = self . client . _get ( url = url , expected_status_code = 200 ) soup = BeautifulSoup ( res . text , _DEFAULT_BEAUTIFULSOUP_PARSER ) surveys_soup = soup . select ( _SURVEYS_SELECTOR ) survey_list = [ ] for survey_soup in surveys_soup : survey_name = _css_select ( survey_soup , _SURVEY_NAME_SELECTOR ) try :...
def catch_exceptions ( orig_func ) : """Catch uncaught exceptions and turn them into http errors"""
@ functools . wraps ( orig_func ) def catch_exceptions_wrapper ( self , * args , ** kwargs ) : try : return orig_func ( self , * args , ** kwargs ) except arvados . errors . ApiError as e : logging . exception ( "Failure" ) return { "msg" : e . _get_reason ( ) , "status_code" : e . resp ...
def _create_tag_table ( self ) : """Creates the table to store blog post tags . : return :"""
with self . _engine . begin ( ) as conn : tag_table_name = self . _table_name ( "tag" ) if not conn . dialect . has_table ( conn , tag_table_name ) : self . _tag_table = sqla . Table ( tag_table_name , self . _metadata , sqla . Column ( "id" , sqla . Integer , primary_key = True ) , sqla . Column ( "tex...
def findPatternsInFile ( codes , patternFinder ) : """Find patterns of exceptions in a file . @ param codes : code of the file to check @ param patternFinder : a visitor for pattern checking and save results"""
tree = ast . parse ( codes ) patternFinder . visit ( tree )
def read_pipe ( pipe_out ) : """Read data on a pipe Used to capture stdout data produced by libiperf : param pipe _ out : The os pipe _ out : rtype : unicode string"""
out = b'' while more_data ( pipe_out ) : out += os . read ( pipe_out , 1024 ) return out . decode ( 'utf-8' )
def check_request_parameters ( self , parameters : dict = dict ) : """Check parameters passed to avoid errors and help debug . : param dict response : search request parameters"""
# - - SEMANTIC QUERY - - - - - li_args = parameters . get ( "q" ) . split ( ) logging . debug ( li_args ) # Unicity li_filters = [ i . split ( ":" ) [ 0 ] for i in li_args ] filters_count = Counter ( li_filters ) li_filters_must_be_unique = ( "coordinate-system" , "format" , "owner" , "type" ) for i in filters_count : ...
def imm_transient ( imm ) : '''imm _ transient ( imm ) yields a duplicate of the given immutable imm that is transient .'''
if not is_imm ( imm ) : raise ValueError ( 'Non-immutable given to imm_transient' ) # make a duplicate immutable that is in the transient state dup = copy . copy ( imm ) if _imm_is_init ( imm ) : # this is an initial - state immutable . . . _imm_init_to_trans ( dup ) elif _imm_is_persist ( imm ) : # it ' s pers...
def calculate_overlap ( haystack , needle , allowpartial = True ) : """Calculate the overlap between two sequences . Yields ( overlap , placement ) tuples ( multiple because there may be multiple overlaps ! ) . The former is the part of the sequence that overlaps , and the latter is - 1 if the overlap is on the lef...
needle = tuple ( needle ) haystack = tuple ( haystack ) solutions = [ ] # equality check if needle == haystack : return [ ( needle , 2 ) ] if allowpartial : minl = 1 else : minl = len ( needle ) for l in range ( minl , min ( len ( needle ) , len ( haystack ) ) + 1 ) : # print " LEFT - DEBUG " , l , " : " , ...
def delete_cached ( task_id , broker = None ) : """Delete a task from the cache backend"""
if not broker : broker = get_broker ( ) return broker . cache . delete ( '{}:{}' . format ( broker . list_key , task_id ) )
async def handle_frame ( self , frame ) : """Handle incoming API frame , return True if this was the expected frame ."""
if not isinstance ( frame , FrameHouseStatusMonitorEnableConfirmation ) : return False self . success = True return True
def find_trigger_value ( psd_var , idx , start , sample_rate ) : """Find the PSD variation value at a particular time Parameters psd _ var : TimeSeries Time series of the varaibility in the PSD estimation idx : numpy . ndarray Time indices of the triggers start : float GPS start time sample _ rate :...
# Find gps time of the trigger time = start + idx / sample_rate # Find where in the psd variation time series the trigger belongs ind = numpy . digitize ( time , psd_var . sample_times ) ind -= 1 vals = psd_var [ ind ] return vals
def init_app ( self , app ) : """This callback can be used to initialize an application for the use with this prometheus reporter setup . This is usually used with a flask " app factory " configuration . Please see : http : / / flask . pocoo . org / docs / 1.0 / patterns / appfactories / Note , that you nee...
if self . path : self . register_endpoint ( self . path , app ) if self . _export_defaults : self . export_defaults ( self . buckets , self . group_by , self . _defaults_prefix , app )
def unique ( seq , key = None ) : """Create a unique list or tuple from a provided list or tuple and preserve the order . : param seq : The list or tuple to preserve unique items from . : type seq : list , tuple : param key : If key is provided it will be called during the comparison process . : type ke...
if key is None : key = lambda x : x preserved_type = type ( seq ) if preserved_type not in ( list , tuple ) : raise TypeError ( "unique argument 1 must be list or tuple, not {0}" . format ( preserved_type . __name__ ) ) seen = [ ] result = [ ] for item in seq : marker = key ( item ) if marker in seen : ...
def cmd ( send , msg , _ ) : """Generates a meaning for the specified acronym . Syntax : { command } < acronym >"""
if not msg : send ( "What acronym?" ) return words = get_list ( ) letters = [ c for c in msg . lower ( ) if c in string . ascii_lowercase ] output = " " . join ( [ choice ( words [ c ] ) for c in letters ] ) if output : send ( '%s: %s' % ( msg , output . title ( ) ) ) else : send ( "No acronym found for...
def patch_lazy ( import_path , rvalue = UNDEFINED , side_effect = UNDEFINED , ignore = UNDEFINED , callback = UNDEFINED , ctxt = UNDEFINED ) : """Patches lazy - loaded methods of classes . Patching at the class definition overrides the _ _ getattr _ _ method for the class with a new version that patches any callabl...
def patch_method ( unpatched_method ) : context = get_context ( unpatched_method ) getter , attribute = _get_target ( import_path ) klass = getter ( ) getattr_path = "." . join ( import_path . split ( '.' ) [ 0 : - 1 ] + [ '__getattr__' ] ) def wrapper ( wrapped_method , instance , attr ) : ...
def _process_merge_request_change ( self , payload , event , codebase = None ) : """Consumes the merge _ request JSON as a python object and turn it into a buildbot change . : arguments : payload Python Object that represents the JSON sent by GitLab Service Hook ."""
attrs = payload [ 'object_attributes' ] commit = attrs [ 'last_commit' ] when_timestamp = dateparse ( commit [ 'timestamp' ] ) # @ todo provide and document a way to choose between http and ssh url repo_url = attrs [ 'target' ] [ 'git_http_url' ] # project name from http headers is empty for me , so get it from object ...
def start_notebook_on_demand ( self , name , context ) : """Start notebook if not yet running with these settings . Return the updated settings with a port info . : return : ( context dict , created flag )"""
if self . is_running ( name ) : last_context = self . get_context ( name ) logger . info ( "Notebook context change detected for %s" , name ) if not self . is_same_context ( context , last_context ) : self . stop_notebook ( name ) # Make sure we don ' t get race condition over context . json...
def WriteUserNotification ( self , notification ) : """Writes a notification for a given user ."""
if notification . username not in self . users : raise db . UnknownGRRUserError ( notification . username ) cloned_notification = notification . Copy ( ) if not cloned_notification . timestamp : cloned_notification . timestamp = rdfvalue . RDFDatetime . Now ( ) self . notifications_by_username . setdefault ( cl...
def parse_valu ( text , off = 0 ) : '''Special syntax for the right side of equals in a macro'''
_ , off = nom ( text , off , whites ) if nextchar ( text , off , '(' ) : return parse_list ( text , off ) if isquote ( text , off ) : return parse_string ( text , off ) # since it ' s not quoted , we can assume we are bound by both # white space and storm syntax chars ( ) , = valu , off = meh ( text , off , val...
def _generate_service ( service_config ) : '''Generate a service from a service _ config dictionary Parameters service _ config : dict Configuration with keys service , args , and kwargs used to generate a new fs service object Returns service : object fs service object initialized with * args , *...
filesystems = [ ] for _ , modname , _ in pkgutil . iter_modules ( fs . __path__ ) : if modname . endswith ( 'fs' ) : filesystems . append ( modname ) service_mod_name = service_config [ 'service' ] . lower ( ) assert_msg = 'Filesystem "{}" not found in pyFilesystem {}' . format ( service_mod_name , fs . __v...
def expect_column_value_lengths_to_be_between ( self , column , min_value = None , max_value = None , mostly = None , result_format = None , include_config = False , catch_exceptions = None , meta = None ) : """Expect column entries to be strings with length between a minimum value and a maximum value ( inclusive )...
raise NotImplementedError
def get_input_list ( self ) : """Description : Get input list Returns an ordered list of all available input keys and names"""
inputs = [ ' ' ] * len ( self . command [ 'input' ] ) for key in self . command [ 'input' ] : inputs [ self . command [ 'input' ] [ key ] [ 'order' ] ] = { "key" : key , "name" : self . command [ 'input' ] [ key ] [ 'name' ] } return inputs
def _validate_func_args ( func , kwargs ) : """Validate decorator args when used to decorate a function ."""
args , varargs , varkw , defaults = inspect . getargspec ( func ) if set ( kwargs . keys ( ) ) != set ( args [ 1 : ] ) : # chop off self raise TypeError ( "decorator kwargs do not match %s()'s kwargs" % func . __name__ )
def get_version ( ) : """Returns shorter version ( digit parts only ) as string ."""
version = '.' . join ( ( str ( each ) for each in VERSION [ : 3 ] ) ) if len ( VERSION ) > 3 : version += VERSION [ 3 ] return version
def readInfo ( stream ) : """Read previously - written information about diffs ."""
try : for line in stream : ( toUUID , fromUUID , size ) = line . split ( ) try : size = int ( size ) except Exception : logger . warning ( "Bad size: %s" , size ) continue logger . debug ( "diff info: %s %s %d" , toUUID , fromUUID , size ) ...
def GetNeighbors ( ID , model = None , neighbors = None , mag_range = None , cdpp_range = None , aperture_name = None , cadence = 'lc' , ** kwargs ) : '''Return ` neighbors ` random bright stars on the same module as ` EPIC ` . : param int ID : The target ID number : param str model : The : py : obj : ` everest...
raise NotImplementedError ( 'This mission is not yet supported.' )
def hotmaps_permutation ( obs_stat , context_counts , context_to_mut , seq_context , gene_seq , window , num_permutations = 10000 , stop_criteria = 100 , max_batch = 25000 , null_save_path = None ) : """Performs null - permutations for position - based mutation statistics in a single gene . Parameters obs _ s...
# get contexts and somatic base mycontexts = context_counts . index . tolist ( ) somatic_base = [ base for one_context in mycontexts for base in context_to_mut [ one_context ] ] # calculate the # of batches for simulations max_batch = min ( num_permutations , max_batch ) num_batches = num_permutations // max_batch rema...
def subscribe_condition_fulfilled ( self , agreement_id , timeout , callback , args , timeout_callback = None , wait = False ) : """Subscribe to the condition fullfilled event . : param agreement _ id : id of the agreement , hex str : param timeout : : param callback : : param args : : param timeout _ cal...
logger . info ( f'Subscribing {self.FULFILLED_EVENT} event with agreement id {agreement_id}.' ) return self . subscribe_to_event ( self . FULFILLED_EVENT , timeout , { '_agreementId' : Web3Provider . get_web3 ( ) . toBytes ( hexstr = agreement_id ) } , callback = callback , timeout_callback = timeout_callback , args = ...
def genslices_ndim ( ndim , shape ) : """Generate all possible slice tuples for ' shape ' ."""
iterables = [ genslices ( shape [ n ] ) for n in range ( ndim ) ] yield from product ( * iterables )
def formatters ( * chained_formatters ) : """Chain formatter functions . : param chained _ formatters : : type chained _ formatters : : return : : rtype :"""
def formatters_chain ( input_string ) : # pylint : disable = missing - docstring for chained_formatter in chained_formatters : input_string = chained_formatter ( input_string ) return input_string return formatters_chain
def _repack_options ( options ) : '''Repack the options data'''
return dict ( [ ( six . text_type ( x ) , _normalize ( y ) ) for x , y in six . iteritems ( salt . utils . data . repack_dictlist ( options ) ) ] )
def setWorkingPlayAreaSize ( self , sizeX , sizeZ ) : """Sets the Play Area in the working copy ."""
fn = self . function_table . setWorkingPlayAreaSize fn ( sizeX , sizeZ )
def deploy ( self , id_networkv4 ) : """Deploy network in equipments and set column ' active = 1 ' in tables redeipv4 : param id _ networkv4 : ID for NetworkIPv4 : return : Equipments configuration output"""
data = dict ( ) uri = 'api/networkv4/%s/equipments/' % id_networkv4 return super ( ApiNetworkIPv4 , self ) . post ( uri , data = data )
def fit ( self , X ) : """Fit a t - SNE embedding for a given data set . Runs the standard t - SNE optimization , consisting of the early exaggeration phase and a normal optimization phase . Parameters X : np . ndarray The data matrix to be embedded . Returns TSNEEmbedding A fully optimized t - SNE ...
embedding = self . prepare_initial ( X ) try : # Early exaggeration with lower momentum to allow points to find more # easily move around and find their neighbors embedding . optimize ( n_iter = self . early_exaggeration_iter , exaggeration = self . early_exaggeration , momentum = self . initial_momentum , inplace ...
def get_length ( topics , yaml_info ) : '''Find the length ( # of rows ) in the created dataframe'''
total = 0 info = yaml_info [ 'topics' ] for topic in topics : for t in info : if t [ 'topic' ] == topic : total = total + t [ 'messages' ] break return total
def gen_dist ( network , techs = None , snapshot = 1 , n_cols = 3 , gen_size = 0.2 , filename = None ) : """Generation distribution Parameters network : PyPSA network container Holds topology of grid including results from powerflow analysis techs : dict type of technologies which shall be plotted snaps...
if techs is None : techs = network . generators . carrier . unique ( ) else : techs = techs n_graphs = len ( techs ) n_cols = n_cols if n_graphs % n_cols == 0 : n_rows = n_graphs // n_cols else : n_rows = n_graphs // n_cols + 1 fig , axes = plt . subplots ( nrows = n_rows , ncols = n_cols ) size = 4 fig...
def get_list_url ( cls , world , town , house_type : HouseType = HouseType . HOUSE ) : """Gets the URL to the house list on Tibia . com with the specified parameters . Parameters world : : class : ` str ` The name of the world . town : : class : ` str ` The name of the town . house _ type : : class : ` ...
house_type = "%ss" % house_type . value return HOUSE_LIST_URL % ( urllib . parse . quote ( world ) , urllib . parse . quote ( town ) , house_type )
def _invert ( self ) : """Invert coverage data from { test _ context : { file : line } } to { file : { test _ context : line } }"""
result = defaultdict ( dict ) for test_context , src_context in six . iteritems ( self . data ) : for src , lines in six . iteritems ( src_context ) : result [ src ] [ test_context ] = lines return result
def process_train_set ( hdf5_file , train_archive , patch_archive , n_train , wnid_map , shuffle_seed = None ) : """Process the ILSVRC2010 training set . Parameters hdf5 _ file : : class : ` h5py . File ` instance HDF5 file handle to which to write . Assumes ` features ` , ` targets ` and ` filenames ` alre...
producer = partial ( train_set_producer , train_archive = train_archive , patch_archive = patch_archive , wnid_map = wnid_map ) consumer = partial ( image_consumer , hdf5_file = hdf5_file , num_expected = n_train , shuffle_seed = shuffle_seed ) producer_consumer ( producer , consumer )
def SetClipboardData ( type , content ) : """Modeled after http : / / msdn . microsoft . com / en - us / library / ms649016%28VS . 85%29 . aspx # _ win32 _ Copying _ Information _ to _ the _ Clipboard"""
allocators = { clipboard . CF_TEXT : ctypes . create_string_buffer , clipboard . CF_UNICODETEXT : ctypes . create_unicode_buffer , clipboard . CF_HTML : ctypes . create_string_buffer , } if type not in allocators : raise NotImplementedError ( "Only text and HTML types are supported at this time" ) # allocate the me...
def Tracing_recordClockSyncMarker ( self , syncId ) : """Function path : Tracing . recordClockSyncMarker Domain : Tracing Method name : recordClockSyncMarker Parameters : Required arguments : ' syncId ' ( type : string ) - > The ID of this clock sync marker No return value . Description : Record a clo...
assert isinstance ( syncId , ( str , ) ) , "Argument 'syncId' must be of type '['str']'. Received type: '%s'" % type ( syncId ) subdom_funcs = self . synchronous_command ( 'Tracing.recordClockSyncMarker' , syncId = syncId ) return subdom_funcs
def get_slug ( self , language_code , lang_name ) : """Notes : - slug must be unique ! - slug is used to check if page already exists ! : return : ' slug ' string for cms . api . create _ page ( )"""
title = self . get_title ( language_code , lang_name ) assert title != "" title = str ( title ) # e . g . : evaluate a lazy translation slug = slugify ( title ) assert slug != "" , "Title %r results in empty slug!" % title return slug
def configure ( self , options , conf ) : """Get filetype option to specify additional filetypes to watch ."""
Plugin . configure ( self , options , conf ) if options . filetype : self . filetypes += options . filetype
def __add_tokens ( self , token_tier ) : """adds all tokens to the document graph . Exmaralda considers them to be annotations as well , that ' s why we could only extract the token node IDs from the timeline ( using ` ` _ _ add _ tokenization ( ) ` ` ) , but not the tokens themselves . Parameters token _...
for event in token_tier . iter ( 'event' ) : assert len ( self . gen_token_range ( event . attrib [ 'start' ] , event . attrib [ 'end' ] ) ) == 1 , "Events in the token tier must not span more than one token." token_id = event . attrib [ 'start' ] self . node [ token_id ] [ self . ns + ':token' ] = event . ...
def decode_datavalue ( self , datatype : str , datavalue : Mapping [ str , object ] ) -> object : """Decode the given ` ` datavalue ` ` using the configured : attr : ` datavalue _ decoder ` . . . versionadded : : 0.3.0"""
decode = cast ( Callable [ [ Client , str , Mapping [ str , object ] ] , object ] , self . datavalue_decoder ) return decode ( self , datatype , datavalue )
def get_rows ( runSetResults ) : """Create list of rows with all data . Each row consists of several RunResults ."""
rows = [ ] for task_results in zip ( * [ runset . results for runset in runSetResults ] ) : rows . append ( Row ( task_results ) ) return rows