signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def delete_namespaced_lease ( self , name , namespace , ** kwargs ) : # noqa : E501 """delete _ namespaced _ lease # noqa : E501 delete a Lease # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . d...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . delete_namespaced_lease_with_http_info ( name , namespace , ** kwargs ) # noqa : E501 else : ( data ) = self . delete_namespaced_lease_with_http_info ( name , namespace , ** kwargs ) # noqa : E501 return data
def getWorkitems ( self , projectarea_id = None , projectarea_name = None , returned_properties = None , archived = False ) : """Get all : class : ` rtcclient . workitem . Workitem ` objects by project area id or name If both ` projectarea _ id ` and ` projectarea _ name ` are ` None ` , all the workitems in ...
workitems_list = list ( ) projectarea_ids = list ( ) if not isinstance ( projectarea_id , six . string_types ) or not projectarea_id : pa_ids = self . getProjectAreaIDs ( projectarea_name ) if pa_ids is None : self . log . warning ( "Stop getting workitems because of " "no ProjectAreas" ) return...
def stream_time ( self , significant_digits = 3 ) : """: param significant _ digits : int of the number of significant digits in the return : return : float of the time in seconds of how long the data took to stream"""
try : return round ( self . _timestamps [ 'last_stream' ] - self . _timestamps [ 'stream' ] , significant_digits ) except Exception as e : return None
def register_classes ( ) : """Register these classes with the ` LinkFactory `"""
Gtlink_select . register_class ( ) Gtlink_bin . register_class ( ) Gtlink_expcube2 . register_class ( ) Gtlink_scrmaps . register_class ( ) Gtlink_mktime . register_class ( ) Gtlink_ltcube . register_class ( ) Link_FermipyCoadd . register_class ( ) Link_FermipyGatherSrcmaps . register_class ( ) Link_FermipyVstack . reg...
def create ( self , from_ = None , ** kwargs ) : """Create and send a new outbound message . Returns : class : ` Message ` object contains next attributes : ' id ' , ' href ' , ' type ' , ' sessionId ' , ' bulkId ' , ' messageId ' , ' scheduledId ' . : Example : message = client . messages . create ( from _...
if "dummy" in kwargs and kwargs [ "dummy" ] : response , instance = self . request ( "POST" , self . uri , data = kwargs ) return instance if from_ : kwargs [ "from" ] = from_ return self . create_instance ( kwargs )
def cleanup ( config , searchstring , force = False ) : """Deletes a found branch locally and remotely ."""
repo = config . repo branches_ = list ( find ( repo , searchstring ) ) if not branches_ : error_out ( "No branches found" ) elif len ( branches_ ) > 1 : error_out ( "More than one branch found.{}" . format ( "\n\t" . join ( [ "" ] + [ x . name for x in branches_ ] ) ) ) assert len ( branches_ ) == 1 branch_name...
def obsgroup_generator ( self , sql , sql_args ) : """Generator for ObservationGroup : param sql : A SQL statement which must return rows describing observation groups : param sql _ args : Any variables required to populate the query provided in ' sql ' : return : A generator which produces Event instan...
self . con . execute ( sql , sql_args ) results = self . con . fetchall ( ) output = [ ] for result in results : obs_group = mp . ObservationGroup ( group_id = result [ 'publicId' ] , title = result [ 'title' ] , obs_time = result [ 'time' ] , set_time = result [ 'setAtTime' ] , semantic_type = result [ 'semanticTy...
def constrain_bounded ( self , lower , upper , warning = True , trigger_parent = True ) : """: param lower , upper : the limits to bound this parameter to : param warning : print a warning if re - constraining parameters . Constrain this parameter to lie within the given range ."""
self . constrain ( Logistic ( lower , upper ) , warning = warning , trigger_parent = trigger_parent )
def jpegtran ( ext_args ) : """Create argument list for jpegtran ."""
args = copy . copy ( _JPEGTRAN_ARGS ) if Settings . destroy_metadata : args += [ "-copy" , "none" ] else : args += [ "-copy" , "all" ] if Settings . jpegtran_prog : args += [ "-progressive" ] args += [ '-outfile' ] args += [ ext_args . new_filename , ext_args . old_filename ] extern . run_ext ( args ) retur...
def macronize_tags ( self , text ) : """Return macronized form along with POS tags . E . g . " Gallia est omnis divisa in partes tres , " - > [ ( ' gallia ' , ' n - s - - - fb - ' , ' galliā ' ) , ( ' est ' , ' v3spia - - - ' , ' est ' ) , ( ' omnis ' , ' a - s - - - mn - ' , ' omnis ' ) , ( ' divisa ' , ' t...
return [ self . _macronize_word ( word ) for word in self . _retrieve_tag ( text ) ]
def parse_query ( self , query ) : """Parse a query string and return an iterator which yields ( key , value )"""
writer = self . writer if writer is None : raise GaugedUseAfterFreeError Gauged . writer_parse_query ( writer , query ) position = 0 writer_contents = writer . contents size = writer_contents . buffer_size pointers = writer_contents . buffer while position < size : yield pointers [ position ] , pointers [ posit...
def _input_handler_decorator ( self , data ) : """Adds positional parameters to selected input _ handler ' s results ."""
input_handler = getattr ( self , self . __InputHandler ) input_parts = [ self . Parameters [ 'taxonomy_file' ] , input_handler ( data ) , self . Parameters [ 'training_set_id' ] , self . Parameters [ 'taxonomy_version' ] , self . Parameters [ 'modification_info' ] , self . ModelDir , ] return self . _commandline_join (...
def convert2fits ( sci_ivm ) : """Checks if a file is in WAIVER of GEIS format and converts it to MEF"""
removed_files = [ ] translated_names = [ ] newivmlist = [ ] for file in sci_ivm : # find out what the input is # if science file is not found on disk , add it to removed _ files for removal try : imgfits , imgtype = fileutil . isFits ( file [ 0 ] ) except IOError : print ( "Warning: File %s cou...
def flag ( self , context ) : """Flag data source"""
lrow , urow = MS . row_extents ( context ) flag = self . _manager . ordered_main_table . getcol ( MS . FLAG , startrow = lrow , nrow = urow - lrow ) return flag . reshape ( context . shape ) . astype ( context . dtype )
def regexpExec ( self , content ) : """Check if the regular expression generates the value"""
ret = libxml2mod . xmlRegexpExec ( self . _o , content ) return ret
def nsdiffs ( x , m , max_D = 2 , test = 'ocsb' , ** kwargs ) : """Estimate the seasonal differencing term , ` ` D ` ` . Perform a test of seasonality for different levels of ` ` D ` ` to estimate the number of seasonal differences required to make a given time series stationary . Will select the maximum valu...
if max_D <= 0 : raise ValueError ( 'max_D must be a positive integer' ) # get the test - this validates m internally testfunc = get_callable ( test , VALID_STESTS ) ( m , ** kwargs ) . estimate_seasonal_differencing_term x = column_or_1d ( check_array ( x , ensure_2d = False , force_all_finite = True , dtype = DTYP...
def _send_requests ( self , parts_results , requests ) : """Send the requests We ' ve determined the partition for each message group in the batch , or got errors for them ."""
# We use these dictionaries to be able to combine all the messages # destined to the same topic / partition into one request # the messages & deferreds , both by topic + partition reqsByTopicPart = defaultdict ( list ) payloadsByTopicPart = defaultdict ( list ) deferredsByTopicPart = defaultdict ( list ) # We now have ...
def list_ ( bank , cachedir = None ) : '''Lists entries stored in the specified bank . CLI Example : . . code - block : : bash salt - run cache . list cloud / active / ec2 / myec2 cachedir = / var / cache / salt /'''
if cachedir is None : cachedir = __opts__ [ 'cachedir' ] try : cache = salt . cache . Cache ( __opts__ , cachedir = cachedir ) except TypeError : cache = salt . cache . Cache ( __opts__ ) return cache . list ( bank )
def create ( self , product_type , attribute_set_id , sku , data ) : """Create Product and return ID : param product _ type : String type of product : param attribute _ set _ id : ID of attribute set : param sku : SKU of the product : param data : Dictionary of data : return : INT id of product created"""
return int ( self . call ( 'catalog_product.create' , [ product_type , attribute_set_id , sku , data ] ) )
def get_tool_class ( self , tool ) : """Gets the actual class which can then be instantiated with its parameters : param tool : The tool name or id : type tool : str | unicode | StreamId : rtype : Tool | MultiOutputTool : return : The tool class"""
if isinstance ( tool , string_types ) : tool_id = StreamId ( tool ) elif isinstance ( tool , StreamId ) : tool_id = tool else : raise TypeError ( tool ) tool_stream_view = None # Look in the main tool channel first if tool_id in self . tools : tool_stream_view = self . tools [ tool_id ] . window ( ( MIN...
def download_ts ( self , path , chunk , process_last_line = True ) : """This will look for a download ts link . It will then download that file and replace the link with the local file . : param process _ last _ line : : param path : str of the path to put the file : param chunk : str of the chunk file , ...
import glob ret_chunk = [ ] partial_chunk = '' lines = chunk . strip ( ) . split ( '\n' ) if not process_last_line : partial_chunk = lines . pop ( ) for line in lines : if line . startswith ( 'http:' ) : ts = '%s/%s.ts' % ( path , line . split ( '.ts?' ) [ 0 ] . split ( '/' ) [ - 1 ] ) relative_...
def get_sequence ( cls , entry ) : """get models . Sequence object from XML node entry : param entry : XML node entry : return : : class : ` pyuniprot . manager . models . Sequence ` object"""
seq_tag = entry . find ( "./sequence" ) seq = seq_tag . text seq_tag . clear ( ) return models . Sequence ( sequence = seq )
async def connect ( cls , endpoint = None , uuid = None , username = None , password = None , cacert = None , bakery_client = None , loop = None , max_frame_size = None , retries = 3 , retry_backoff = 10 , ) : """Connect to the websocket . If uuid is None , the connection will be to the controller . Otherwise it ...
self = cls ( ) if endpoint is None : raise ValueError ( 'no endpoint provided' ) self . uuid = uuid if bakery_client is None : bakery_client = httpbakery . Client ( ) self . bakery_client = bakery_client if username and '@' in username and not username . endswith ( '@local' ) : # We ' re trying to log in as an ...
def jdnDate ( jdn ) : """Converts Julian Day Number to Gregorian date ."""
a = jdn + 32044 b = ( 4 * a + 3 ) // 146097 c = a - ( 146097 * b ) // 4 d = ( 4 * c + 3 ) // 1461 e = c - ( 1461 * d ) // 4 m = ( 5 * e + 2 ) // 153 day = e + 1 - ( 153 * m + 2 ) // 5 month = m + 3 - 12 * ( m // 10 ) year = 100 * b + d - 4800 + m // 10 return [ year , month , day ]
def splitroot ( self , part , sep = sep ) : """Splits path string into drive , root and relative path Uses ' / artifactory / ' as a splitting point in URI . Everything before it , including ' / artifactory / ' itself is treated as drive . The next folder is treated as root , and everything else is taken for...
drv = '' root = '' base = get_global_base_url ( part ) if base and without_http_prefix ( part ) . startswith ( without_http_prefix ( base ) ) : mark = without_http_prefix ( base ) . rstrip ( sep ) + sep parts = part . split ( mark ) else : mark = sep + 'artifactory' + sep parts = part . split ( mark ) i...
def seconds ( num ) : """Pause for this many seconds"""
now = pytime . time ( ) end = now + num until ( end )
def returner ( ret ) : '''Send a message to Nagios with the data'''
_options = _get_options ( ret ) log . debug ( '_options %s' , _options ) _options [ 'hostname' ] = ret . get ( 'id' ) if 'url' not in _options or _options [ 'url' ] == '' : log . error ( 'nagios_nrdp.url not defined in salt config' ) return if 'token' not in _options or _options [ 'token' ] == '' : log . er...
def load ( filename , format = None , ** kwargs ) : '''load ( filename ) yields the data contained in the file referenced by the given filename in a neuropythy or neuropythy - friendly format . load ( filename , format ) specifies that the given format should be used ; this should be the name of the importer ...
from neuropythy . util import ObjectWithMetaData filename = os . path . expanduser ( filename ) if format is None : format = guess_import_format ( filename , ** kwargs ) if format is None : # try formats and see if one works ! for ( k , ( f , _ , _ ) ) in six . iteritems ( importers ) : try ...
def raw_imu_encode ( self , time_usec , xacc , yacc , zacc , xgyro , ygyro , zgyro , xmag , ymag , zmag ) : '''The RAW IMU readings for the usual 9DOF sensor setup . This message should always contain the true raw values without any scaling to allow data capture and system debugging . time _ usec : Timestamp ...
return MAVLink_raw_imu_message ( time_usec , xacc , yacc , zacc , xgyro , ygyro , zgyro , xmag , ymag , zmag )
async def _handle_container_timeout ( self , container_id , timeout ) : """Check timeout with docker stats : param container _ id : : param timeout : in seconds ( cpu time )"""
try : docker_stats = await self . _docker_interface . get_stats ( container_id ) source = AsyncIteratorWrapper ( docker_stats ) nano_timeout = timeout * ( 10 ** 9 ) async for upd in source : if upd is None : await self . _kill_it_with_fire ( container_id ) self . _logger . de...
def remove ( self , server_id ) : """remove server and data stuff Args : server _ id - server identity"""
server = self . _storage . pop ( server_id ) server . stop ( ) server . cleanup ( )
def calcVmin ( self , ** kwargs ) : """NAME : calcVmin PURPOSE : calculate the v ' pericenter ' INPUT : OUTPUT : vmin HISTORY : 2012-11-28 - Written - Bovy ( IAS )"""
if hasattr ( self , '_vmin' ) : # pragma : no cover return self . _vmin E , L = self . _E , self . _Lz if nu . fabs ( self . _pvx ) < 10. ** - 7. : # We are at vmin or vmax eps = 10. ** - 8. peps = _JzStaeckelIntegrandSquared ( self . _vx + eps , E , L , self . _I3V , self . _delta , self . _ux , self . _co...
def get_key ( self , section , key ) : """Gets key value from settings file . : param section : Current section to retrieve key from . : type section : unicode : param key : Current key to retrieve . : type key : unicode : return : Current key value . : rtype : object"""
LOGGER . debug ( "> Retrieving '{0}' in '{1}' section." . format ( key , section ) ) self . __settings . beginGroup ( section ) value = self . __settings . value ( key ) LOGGER . debug ( "> Key value: '{0}'." . format ( value ) ) self . __settings . endGroup ( ) return value
def ExpandGlobs ( path , opts = None ) : """Performs glob expansion on a given path . Path can contain regular glob elements ( such as ` * * ` , ` * ` , ` ? ` , ` [ a - z ] ` ) . For example , having files ` foo ` , ` bar ` , ` baz ` glob expansion of ` ba ? ` will yield ` bar ` and ` baz ` . Args : path ...
precondition . AssertType ( path , Text ) if not path : raise ValueError ( "Path is empty" ) if not _IsAbsolutePath ( path , opts ) : raise ValueError ( "Path '%s' is not absolute" % path ) if opts is not None and opts . pathtype == rdf_paths . PathSpec . PathType . REGISTRY : # Handle HKLM \ Foo and / HKLM / F...
def _estimate_AIC ( self , y , mu , weights = None ) : """estimate the Akaike Information Criterion Parameters y : array - like of shape ( n _ samples , ) output data vector mu : array - like of shape ( n _ samples , ) , expected value of the targets given the model and inputs weights : array - like sha...
estimated_scale = not ( self . distribution . _known_scale ) # if we estimate the scale , that adds 2 dof return - 2 * self . _loglikelihood ( y = y , mu = mu , weights = weights ) + 2 * self . statistics_ [ 'edof' ] + 2 * estimated_scale
def _set_lif_main_intf_type ( self , v , load = False ) : """Setter method for lif _ main _ intf _ type , mapped from YANG variable / bridge _ domain _ state / bridge _ domain _ list / outer _ vlan _ list / tagged _ ports _ list / lif _ main _ intf _ type ( nsm - dcm - lif - main - intf - type ) If this variable ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'nsm-dcm-lif-main-intf-type-pw' : { 'value' : 5 } , u'nsm-dcm-lif-main-intf-type-lag' : { 'value' : 2 } , u'nsm-dcm-lif-main-int...
def create_integer ( self , value : int ) -> Integer : """Creates a new : class : ` ConstantInteger ` , adding it to the pool and returning it . : param value : The value of the new integer ."""
self . append ( ( 3 , value ) ) return self . get ( self . raw_count - 1 )
def lag_plot ( data , lag = 1 , kind = "scatter" , ** kwds ) : """Lag plot for time series . Parameters data : pandas . Series the time series to plot lag : integer The lag of the scatter plot , default = 1 kind : string The kind of plot to use ( e . g . ' scatter ' , ' line ' ) * * kwds : Additio...
if lag != int ( lag ) or int ( lag ) <= 0 : raise ValueError ( "lag must be a positive integer" ) lag = int ( lag ) values = data . values y1 = "y(t)" y2 = "y(t + {0})" . format ( lag ) lags = pd . DataFrame ( { y1 : values [ : - lag ] . T . ravel ( ) , y2 : values [ lag : ] . T . ravel ( ) } ) if isinstance ( data...
def _gzip_open_handle ( handle ) : """" Hide Python 2 vs . 3 differences in gzip . GzipFile ( )"""
import gzip if sys . version_info [ 0 ] > 2 : import io handle = io . TextIOWrapper ( gzip . GzipFile ( fileobj = handle ) , encoding = "UTF-8" ) else : handle = gzip . GzipFile ( fileobj = handle ) return handle
def read_astropy_ascii ( self , ** kwargs ) : """Open as an ASCII table , returning a : class : ` astropy . table . Table ` object . Keyword arguments are passed to : func : ` astropy . io . ascii . open ` ; valid ones likely include : - ` ` names = < list > ` ` ( column names ) - ` ` format ` ` ( ' basic '...
from astropy . io import ascii return ascii . read ( text_type ( self ) , ** kwargs )
def solve_and_plot_series ( self , x0 , params , varied_data , varied_idx , solver = None , plot_kwargs = None , plot_residuals_kwargs = None , ** kwargs ) : """Solve and plot for a series of a varied parameter . Convenience method , see : meth : ` solve _ series ` , : meth : ` plot _ series ` & : meth : ` plot...
sol , nfo = self . solve_series ( x0 , params , varied_data , varied_idx , solver = solver , ** kwargs ) ax_sol = self . plot_series ( sol , varied_data , varied_idx , info = nfo , ** ( plot_kwargs or { } ) ) extra = dict ( ax_sol = ax_sol , info = nfo ) if plot_residuals_kwargs : extra [ 'ax_resid' ] = self . plot...
def get_coding_potential_cutoff ( ref_gtf , ref_fasta , data ) : """estimate the coding potential cutoff that best classifies coding / noncoding transcripts by splitting the reference annotation into a test and training set and determining the cutoff where the sensitivity and specificity meet"""
train_gtf , test_gtf = gtf . split_gtf ( ref_gtf , sample_size = 2000 ) coding_gtf = gtf . partition_gtf ( train_gtf , coding = True ) noncoding_gtf = gtf . partition_gtf ( train_gtf ) noncoding_fasta = gtf . gtf_to_fasta ( noncoding_gtf , ref_fasta ) cds_fasta = gtf . gtf_to_fasta ( coding_gtf , ref_fasta , cds = True...
def saver_for_file ( filename ) : """Returns a Saver that can load the specified file , based on the file extension . None if failed to determine . : param filename : the filename to get the saver for : type filename : str : return : the associated saver instance or None if none found : rtype : Saver"""
saver = javabridge . static_call ( "weka/core/converters/ConverterUtils" , "getSaverForFile" , "(Ljava/lang/String;)Lweka/core/converters/AbstractFileSaver;" , filename ) if saver is None : return None else : return Saver ( jobject = saver )
def chain ( tree , edition_number ) : """Args : tree ( dict ) : Tree history of all editions of a piece . edition _ number ( int ) : The edition number to check for . In the case of a piece ( master edition ) , an empty string ( ` ` ' ' ` ` ) or zero ( ` ` 0 ` ` ) can be passed . Returns : list : The ch...
# return the chain for an edition _ number sorted by the timestamp return sorted ( tree . get ( edition_number , [ ] ) , key = lambda d : d [ 'timestamp_utc' ] )
def wait_for_completion ( report , interval = 10 ) : """Wait for asynchronous jobs stil running in the given campaign . : param report : memory representation of a campaign report : type campaign : ReportNode : param interval : wait interval : type interval : int or float : return : list of asynchronous j...
for jobid in report . collect ( 'jobid' ) : try : if not Job . finished ( jobid ) : logging . info ( 'waiting for SLURM job %s' , jobid ) time . sleep ( interval ) while not Job . finished ( jobid ) : time . sleep ( interval ) yield Job . fromid ( ...
def jsonarrappend ( self , name , path = Path . rootPath ( ) , * args ) : """Appends the objects ` ` args ` ` to the array under the ` ` path ` in key ` ` name ` `"""
pieces = [ name , str_path ( path ) ] for o in args : pieces . append ( self . _encode ( o ) ) return self . execute_command ( 'JSON.ARRAPPEND' , * pieces )
def validatePopElement ( self , doc , elem , qname ) : """Pop the element end from the validation stack ."""
if doc is None : doc__o = None else : doc__o = doc . _o if elem is None : elem__o = None else : elem__o = elem . _o ret = libxml2mod . xmlValidatePopElement ( self . _o , doc__o , elem__o , qname ) return ret
def get_scaled_f_scores ( self , category , scaler_algo = DEFAULT_SCALER_ALGO , beta = DEFAULT_BETA ) : '''Computes scaled - fscores Parameters category : str category name to score scaler _ algo : str Function that scales an array to a range \ in [ 0 and 1 ] . Use ' percentile ' , ' normcdf ' . Default ....
assert beta > 0 cat_word_counts , not_cat_word_counts = self . _get_catetgory_and_non_category_word_counts ( category ) scores = self . _get_scaled_f_score_from_counts ( cat_word_counts , not_cat_word_counts , scaler_algo , beta ) return np . array ( scores )
def footprints_from_place ( place , footprint_type = 'building' , retain_invalid = False ) : """Get footprints within the boundaries of some place . The query must be geocodable and OSM must have polygon boundaries for the geocode result . If OSM does not have a polygon for this place , you can instead get it...
city = gdf_from_place ( place ) polygon = city [ 'geometry' ] . iloc [ 0 ] return create_footprints_gdf ( polygon , retain_invalid = retain_invalid , footprint_type = footprint_type )
def get_clouds ( wxdata : [ str ] ) -> ( [ str ] , list ) : # type : ignore """Returns the report list and removed list of split cloud layers"""
clouds = [ ] for i , item in reversed ( list ( enumerate ( wxdata ) ) ) : if item [ : 3 ] in CLOUD_LIST or item [ : 2 ] == 'VV' : cloud = wxdata . pop ( i ) clouds . append ( make_cloud ( cloud ) ) return wxdata , sorted ( clouds , key = lambda cloud : ( cloud . altitude , cloud . type ) )
def GetClosestPoint ( self , p ) : """Returns ( closest _ p , closest _ i ) , where closest _ p is the closest point to p on the piecewise linear curve represented by the polyline , and closest _ i is the index of the point on the polyline just before the polyline segment that contains closest _ p ."""
assert ( len ( self . _points ) > 0 ) closest_point = self . _points [ 0 ] closest_i = 0 for i in range ( 0 , len ( self . _points ) - 1 ) : ( a , b ) = ( self . _points [ i ] , self . _points [ i + 1 ] ) cur_closest_point = GetClosestPoint ( p , a , b ) if p . Angle ( cur_closest_point ) < p . Angle ( clos...
def dynamic_symbols_count ( self ) : """Return the dynamic symbols count attribute of the BFD file being processed ."""
if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . DYNAMIC_SYMCOUNT )
def normalizePointType ( value ) : """Normalizes point type . * * * value * * must be an string . * * * value * * must be one of the following : | move | | line | | offcurve | | curve | | qcurve | * Returned value will be an unencoded ` ` unicode ` ` string ."""
allowedTypes = [ 'move' , 'line' , 'offcurve' , 'curve' , 'qcurve' ] if not isinstance ( value , basestring ) : raise TypeError ( "Point type must be a string, not %s." % type ( value ) . __name__ ) if value not in allowedTypes : raise ValueError ( "Point type must be '%s'; not %r." % ( "', '" . join ( allowedT...
def form_valid ( self , form ) : """Processes a valid form submittal . : param form : the form instance . : rtype : django . http . HttpResponse ."""
# noinspection PyAttributeOutsideInit self . object = form . save ( ) meta = getattr ( self . object , '_meta' ) # Index the object . for backend in get_search_backends ( ) : backend . add ( object ) # noinspection PyUnresolvedReferences messages . success ( self . request , _ ( u'{0} "{1}" saved.' ) . format ( met...
def remove_my_api_key_from_groups ( self , body , ** kwargs ) : # noqa : E501 """Remove API key from groups . # noqa : E501 An endpoint for removing API key from groups . * * Example usage : * * ` curl - X DELETE https : / / api . us - east - 1 . mbedcloud . com / v3 / api - keys / me / groups - d ' [ 0162056a9a1...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . remove_my_api_key_from_groups_with_http_info ( body , ** kwargs ) # noqa : E501 else : ( data ) = self . remove_my_api_key_from_groups_with_http_info ( body , ** kwargs ) # noqa : E501 return data
def fdroid ( ) : '''Set up an F - Droid App Repo . More infos : * https : / / f - droid . org / wiki / page / Setup _ an _ FDroid _ App _ Repo * https : / / f - droid . org / wiki / page / Installing _ the _ Server _ and _ Repo _ Tools'''
hostname = re . sub ( r'^[^@]+@' , '' , env . host ) # without username if any sitename = query_input ( question = '\nEnter site-name of Your F-Droid web service' , default = flo ( 'fdroid.{hostname}' ) ) username = env . user fabfile_data_dir = FABFILE_DATA_DIR print ( magenta ( ' install fdroidserver' ) ) res = run (...
def product_url ( self , product ) : """Return a human - friendly URL for this product . : param product : str , eg . " ceph " : returns : str , URL"""
url = 'product/%s' % product return posixpath . join ( self . url , url )
def get_urls ( self ) : """Add the entries view to urls ."""
urls = super ( FormAdmin , self ) . get_urls ( ) extra_urls = [ re_path ( "^(?P<form_id>\d+)/entries/$" , self . admin_site . admin_view ( self . entries_view ) , name = "form_entries" ) , re_path ( "^(?P<form_id>\d+)/entries/show/$" , self . admin_site . admin_view ( self . entries_view ) , { "show" : True } , name = ...
def get_relation_cnt ( self ) : """Return a Counter containing all relations contained in the Annotation Extensions ."""
ctr = cx . Counter ( ) for ntgpad in self . associations : if ntgpad . Extension is not None : ctr += ntgpad . Extension . get_relations_cnt ( ) return ctr
def is_seq ( obj ) : """Returns True if object is not a string but is iterable"""
if not hasattr ( obj , '__iter__' ) : return False if isinstance ( obj , basestring ) : return False return True
def canChiNgay ( nn , tt , nnnn , duongLich = True , timeZone = 7 , thangNhuan = False ) : """Summary Args : nn ( int ) : ngày tt ( int ) : tháng nnnn ( int ) : năm duongLich ( bool , optional ) : True nếu là dương lịch , False âm lịch timeZone ( int , optional ) : Múi giờ thangNhuan ( b...
if duongLich is False : [ nn , tt , nnnn ] = L2S ( nn , tt , nnnn , thangNhuan , timeZone ) jd = jdFromDate ( nn , tt , nnnn ) # print jd canNgay = ( jd + 9 ) % 10 + 1 chiNgay = ( jd + 1 ) % 12 + 1 return [ canNgay , chiNgay ]
def get_predictor ( self , input_names , output_names , device = 0 ) : """This method will build the trainer ' s tower function under ` ` TowerContext ( is _ training = False ) ` ` , and returns a callable predictor with input placeholders & output tensors in this tower . This method handles the common case of ...
assert self . tower_func is not None , "Must set tower_func on the trainer to use get_predictor()!" tower_name = 'tower-pred-{}' . format ( device ) if device >= 0 else 'tower-pred-cpu' device_id = device device = '/gpu:{}' . format ( device_id ) if device_id >= 0 else '/cpu:0' try : tower = self . tower_func . tow...
def _warn_if_deprecated ( key ) : """Checks if ` key ` is a deprecated option and if so , prints a warning . Returns bool - True if ` key ` is deprecated , False otherwise ."""
d = _get_deprecated_option ( key ) if d : if d . msg : print ( d . msg ) warnings . warn ( d . msg , DeprecationWarning ) else : msg = "'%s' is deprecated" % key if d . removal_ver : msg += ' and will be removed in %s' % d . removal_ver if d . rkey : ...
def render ( self , view , context = None ) : """Render ` view ` with this block ' s runtime and the supplied ` context `"""
return self . runtime . render ( self , view , context )
def flash_set_parameters ( self , size ) : """Tell the ESP bootloader the parameters of the chip Corresponds to the " flashchip " data structure that the ROM has in RAM . ' size ' is in bytes . All other flash parameters are currently hardcoded ( on ESP8266 these are mostly ignored by ROM code , on ESP32 ...
fl_id = 0 total_size = size block_size = 64 * 1024 sector_size = 4 * 1024 page_size = 256 status_mask = 0xffff self . check_command ( "set SPI params" , ESP32ROM . ESP_SPI_SET_PARAMS , struct . pack ( '<IIIIII' , fl_id , total_size , block_size , sector_size , page_size , status_mask ) )
def canonify_slice ( s , n ) : """Convert a slice object into a canonical form to simplify treatment in histogram bin content and edge slicing ."""
if isinstance ( s , ( int , long ) ) : return canonify_slice ( slice ( s , s + 1 , None ) , n ) start = s . start % n if s . start is not None else 0 stop = s . stop % n if s . stop is not None else n step = s . step if s . step is not None else 1 return slice ( start , stop , step )
def rotation_coefs ( self ) : """get the rotation coefficents in radians Returns rotation _ coefs : list the rotation coefficients implied by Vario2d . bearing"""
return [ np . cos ( self . bearing_rads ) , np . sin ( self . bearing_rads ) , - 1.0 * np . sin ( self . bearing_rads ) , np . cos ( self . bearing_rads ) ]
def report_on_field ( layer ) : """Helper function to set on which field we are going to report . The return might be empty if we don ' t report on a field . : param layer : The vector layer . : type layer : QgsVectorLayer : return : The field index on which we should report . : rtype : int"""
source_fields = layer . keywords [ 'inasafe_fields' ] if source_fields . get ( size_field [ 'key' ] ) : field_size = source_fields [ size_field [ 'key' ] ] field_index = layer . fields ( ) . lookupField ( field_size ) else : field_index = None # Special case for a point layer and indivisible polygon , # we ...
def _commitData ( self , commit ) : """Get data from a commit object : param commit : commit object : type commit : git . objects . commit . Commit"""
return { "hexsha" : commit [ 'hash' ] , "adate" : time . mktime ( time . strptime ( commit [ 'date' ] [ : 19 ] , '%Y-%m-%dT%H:%M:%S' ) ) , "cdate" : time . mktime ( time . strptime ( commit [ 'date' ] [ : 19 ] , '%Y-%m-%dT%H:%M:%S' ) ) , "author" : commit [ 'author' ] [ 'raw' ] , "message" : commit [ 'message' ] }
def create_datapipeline ( self ) : """Creates data pipeline and adds definition"""
utils . banner ( "Creating Data Pipeline" ) dpobj = datapipeline . AWSDataPipeline ( app = self . app , env = self . env , region = self . region , prop_path = self . json_path ) dpobj . create_datapipeline ( ) dpobj . set_pipeline_definition ( ) if self . configs [ self . env ] . get ( 'datapipeline' ) . get ( 'activa...
def PWS_stack ( streams , weight = 2 , normalize = True ) : """Compute the phase weighted stack of a series of streams . . . note : : It is recommended to align the traces before stacking . : type streams : list : param streams : List of : class : ` obspy . core . stream . Stream ` to stack . : type weight ...
# First get the linear stack which we will weight by the phase stack Linstack = linstack ( streams ) # Compute the instantaneous phase instaphases = [ ] print ( "Computing instantaneous phase" ) for stream in streams : instaphase = stream . copy ( ) for tr in instaphase : analytic = hilbert ( tr . data ...
def uricompose ( scheme = None , authority = None , path = '' , query = None , fragment = None , userinfo = None , host = None , port = None , querysep = '&' , encoding = 'utf-8' ) : """Compose a URI reference string from its individual components ."""
# RFC 3986 3.1 : Scheme names consist of a sequence of characters # beginning with a letter and followed by any combination of # letters , digits , plus ( " + " ) , period ( " . " ) , or hyphen ( " - " ) . # Although schemes are case - insensitive , the canonical form is # lowercase and documents that specify schemes m...
def read ( self , timeout = READ_TIMEOUT , raw = False ) : '''Read data from the arm . Data is returned as a latin _ 1 encoded string , or raw bytes if ' raw ' is True .'''
time . sleep ( READ_SLEEP_TIME ) raw_out = self . ser . read ( self . ser . in_waiting ) out = raw_out . decode ( OUTPUT_ENCODING ) time_waiting = 0 while len ( out ) == 0 or ending_in ( out . strip ( OUTPUT_STRIP_CHARS ) , RESPONSE_END_WORDS ) is None : time . sleep ( READ_SLEEP_TIME ) time_waiting += READ_SLE...
def _get_service_instance ( host , username , password , protocol , port , mechanism , principal , domain ) : '''Internal method to authenticate with a vCenter server or ESX / ESXi host and return the service instance object .'''
log . trace ( 'Retrieving new service instance' ) token = None if mechanism == 'userpass' : if username is None : raise salt . exceptions . CommandExecutionError ( 'Login mechanism userpass was specified but the mandatory ' 'parameter \'username\' is missing' ) if password is None : raise salt ....
def read_cell ( self , x , y ) : """Reads the cell at position x + 1 and y + 1 ; return value : param x : line index : param y : coll index : return : { header : value }"""
if isinstance ( self . header [ y ] , tuple ) : header = self . header [ y ] [ 0 ] else : header = self . header [ y ] x += 1 y += 1 if self . strip : self . _sheet . cell ( x , y ) . value = self . _sheet . cell ( x , y ) . value . strip ( ) else : return { header : self . _sheet . cell ( x , y ) . val...
def info ( name ) : '''Return user information Args : name ( str ) : Username for which to display information Returns : dict : A dictionary containing user information - fullname - username - SID - passwd ( will always return None ) - comment ( same as description , left here for backwards compat...
if six . PY2 : name = _to_unicode ( name ) ret = { } items = { } try : items = win32net . NetUserGetInfo ( None , name , 4 ) except win32net . error : pass if items : groups = [ ] try : groups = win32net . NetUserGetLocalGroups ( None , name ) except win32net . error : pass r...
def enable_enhanced_monitoring ( stream_name , metrics , region = None , key = None , keyid = None , profile = None ) : '''Enable enhanced monitoring for the specified shard - level metrics on stream stream _ name CLI example : : salt myminion boto _ kinesis . enable _ enhanced _ monitoring my _ stream [ " metr...
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) r = _execute_with_retries ( conn , "enable_enhanced_monitoring" , StreamName = stream_name , ShardLevelMetrics = metrics ) if 'error' not in r : r [ 'result' ] = True return r
def determine_api_port ( public_port , singlenode_mode = False ) : '''Determine correct API server listening port based on existence of HTTPS reverse proxy and / or haproxy . public _ port : int : standard public port for given service singlenode _ mode : boolean : Shuffle ports when only a single unit is pre...
i = 0 if singlenode_mode : i += 1 elif len ( peer_units ( ) ) > 0 or is_clustered ( ) : i += 1 if https ( ) : i += 1 return public_port - ( i * 10 )
def collect_snmp ( self , device , host , port , community ) : """Collect Fusion IO Drive SNMP stats from device host and device are from the conf file . In the future device should be changed to be what IODRive device it being checked . i . e . fioa , fiob ."""
# Set timestamp timestamp = time . time ( ) for k , v in self . IODRIVE_STATS . items ( ) : # Get Metric Name and Value metricName = '.' . join ( [ k ] ) metricValue = int ( self . get ( v , host , port , community ) [ v ] ) # Get Metric Path metricPath = '.' . join ( [ 'servers' , host , device , metri...
def set_fixed_image ( self , image ) : """Set Fixed ANTsImage for metric"""
if not isinstance ( image , iio . ANTsImage ) : raise ValueError ( 'image must be ANTsImage type' ) if image . dimension != self . dimension : raise ValueError ( 'image dim (%i) does not match metric dim (%i)' % ( image . dimension , self . dimension ) ) self . _metric . setFixedImage ( image . pointer , False ...
def mini_histogram ( series , ** kwargs ) : """Plot a small ( mini ) histogram of the data . Parameters series : Series The data to plot . Returns str The resulting image encoded as a string ."""
imgdata = BytesIO ( ) plot = _plot_histogram ( series , figsize = ( 2 , 0.75 ) , ** kwargs ) plot . axes . get_yaxis ( ) . set_visible ( False ) if LooseVersion ( matplotlib . __version__ ) <= '1.5.9' : plot . set_axis_bgcolor ( "w" ) else : plot . set_facecolor ( "w" ) xticks = plot . xaxis . get_major_ticks (...
def requestConnection ( self , wanInterfaceId = 1 , timeout = 1 ) : """Request the connection to be established : param int wanInterfaceId : the id of the WAN interface : param float timeout : the timeout to wait for the action to be executed"""
namespace = Wan . getServiceType ( "requestConnection" ) + str ( wanInterfaceId ) uri = self . getControlURL ( namespace ) self . execute ( uri , namespace , "RequestConnection" , timeout = timeout )
def modulo11 ( base ) : """Calcula o dígito verificador ( DV ) para o argumento usando " Módulo 11 " . : param str base : String contendo os dígitos sobre os quais o DV será calculado , assumindo que o DV não está incluído no argumento . : return : O dígito verificador calculado . : rtype : int"""
pesos = '23456789' * ( ( len ( base ) // 8 ) + 1 ) acumulado = sum ( [ int ( a ) * int ( b ) for a , b in zip ( base [ : : - 1 ] , pesos ) ] ) digito = 11 - ( acumulado % 11 ) return 0 if digito >= 10 else digito
def content_type ( self , mime_type : Optional [ MimeType ] = None ) -> str : """Get a random HTTP content type . : return : Content type . : Example : Content - Type : application / json"""
fmt = self . __file . mime_type ( type_ = mime_type ) return 'Content-Type: {}' . format ( fmt )
def downloadFile ( self , filename , ispickle = False , athome = False ) : """Downloads a single file from Redunda . : param str filename : The name of the file you want to download : param bool ispickle : Optional variable which tells if the file to be downloaded is a pickle ; default is False . : returns : ...
print ( "Downloading file {} from Redunda." . format ( filename ) ) _ , tail = os . path . split ( filename ) url = "https://redunda.sobotics.org/bots/data/{}?key={}" . format ( tail , self . key ) requestToMake = request . Request ( url ) # Make the request . response = request . urlopen ( requestToMake ) if response ...
def sendall ( self , s ) : """Send data to the channel , without allowing partial results . Unlike ` send ` , this method continues to send data from the given string until either all data has been sent or an error occurs . Nothing is returned . : param str s : data to send . : raises socket . timeout : i...
while s : sent = self . send ( s ) s = s [ sent : ] return None
def squash ( change , is_ignored = False , options = None ) : """squashes the in - depth information of a change to a simplified ( and less memory - intensive ) form"""
if options : is_ignored = change . is_ignored ( options ) if isinstance ( change , Removal ) : result = SquashedRemoval ( change , is_ignored ) elif isinstance ( change , Addition ) : result = SquashedAddition ( change , is_ignored ) else : result = SquashedChange ( change , is_ignored ) return result
def clear ( self , domain = None , path = None , name = None ) : """Clear some cookies . Invoking this method without arguments will clear all cookies . If given a single argument , only cookies belonging to that domain will be removed . If given two arguments , cookies belonging to the specified path withi...
if name is not None : if ( domain is None ) or ( path is None ) : raise ValueError ( "domain and path must be given to remove a cookie by name" ) del self . _cookies [ domain ] [ path ] [ name ] elif path is not None : if domain is None : raise ValueError ( "domain must be given to remove co...
def _take_ownership ( self ) : """Make the Python instance take ownership of the GIBaseInfo . i . e . unref if the python instance gets gc ' ed ."""
if self : ptr = cast ( self . value , GIBaseInfo ) _UnrefFinalizer . track ( self , ptr ) self . __owns = True
def facets_boundary ( self ) : """Return the edges which represent the boundary of each facet Returns edges _ boundary : sequence of ( n , 2 ) int Indices of self . vertices"""
# make each row correspond to a single face edges = self . edges_sorted . reshape ( ( - 1 , 6 ) ) # get the edges for each facet edges_facet = [ edges [ i ] . reshape ( ( - 1 , 2 ) ) for i in self . facets ] edges_boundary = np . array ( [ i [ grouping . group_rows ( i , require_count = 1 ) ] for i in edges_facet ] ) r...
def fit ( self , X ) : """Fit the PyNNDescent transformer to build KNN graphs with neighbors given by the dataset X . Parameters X : array - like , shape ( n _ samples , n _ features ) Sample data Returns transformer : PyNNDescentTransformer The trained transformer"""
self . n_samples_fit = X . shape [ 0 ] if self . metric_kwds is None : metric_kwds = { } else : metric_kwds = self . metric_kwds self . pynndescent_ = NNDescent ( X , self . metric , metric_kwds , self . n_neighbors , self . n_trees , self . leaf_size , self . pruning_level , self . tree_init , self . random_st...
def from_files ( cls , ID , datafiles , parser = 'name' , position_mapper = None , readdata_kwargs = { } , readmeta_kwargs = { } , ID_kwargs = { } , ** kwargs ) : """Create an OrderedCollection of measurements from a set of data files . Parameters { _ bases _ ID } { _ bases _ data _ files } { _ bases _ file...
if position_mapper is None : if isinstance ( parser , six . string_types ) : position_mapper = parser else : msg = "When using a custom parser, you must specify the position_mapper keyword." raise ValueError ( msg ) d = _assign_IDS_to_datafiles ( datafiles , parser , cls . _measurement_c...
def parsePowerTable ( uhfbandcap ) : """Parse the transmit power table @ param uhfbandcap : Capability dictionary from self . capabilities [ ' RegulatoryCapabilities ' ] [ ' UHFBandCapabilities ' ] @ return : a list of [ 0 , dBm value , dBm value , . . . ] > > > LLRPClient . parsePowerTable ( { ' TransmitPo...
bandtbl = { k : v for k , v in uhfbandcap . items ( ) if k . startswith ( 'TransmitPowerLevelTableEntry' ) } tx_power_table = [ 0 ] * ( len ( bandtbl ) + 1 ) for k , v in bandtbl . items ( ) : idx = v [ 'Index' ] tx_power_table [ idx ] = int ( v [ 'TransmitPowerValue' ] ) / 100.0 return tx_power_table
def make_fc ( dim_in , hidden_dim , use_gn = False ) : '''Caffe2 implementation uses XavierFill , which in fact corresponds to kaiming _ uniform _ in PyTorch'''
if use_gn : fc = nn . Linear ( dim_in , hidden_dim , bias = False ) nn . init . kaiming_uniform_ ( fc . weight , a = 1 ) return nn . Sequential ( fc , group_norm ( hidden_dim ) ) fc = nn . Linear ( dim_in , hidden_dim ) nn . init . kaiming_uniform_ ( fc . weight , a = 1 ) nn . init . constant_ ( fc . bias ,...
async def async_get_event_log ( self , index : int ) -> Optional [ EventLogResponse ] : """Get an entry from the event log . : param index : Index for the event log entry to be obtained . : return : Response containing the event log entry , or None if not found ."""
response = await self . _protocol . async_execute ( GetEventLogCommand ( index ) ) if isinstance ( response , EventLogResponse ) : return response return None
def _show_final_paste_message ( self , tl_key , no_pasted_cells ) : """Show actually pasted number of cells"""
plural = "" if no_pasted_cells == 1 else _ ( "s" ) statustext = _ ( "{ncells} cell{plural} pasted at cell {topleft}" ) . format ( ncells = no_pasted_cells , plural = plural , topleft = tl_key ) post_command_event ( self . main_window , self . StatusBarMsg , text = statustext )
def xlsx_to_csv ( self , infile , worksheet = 0 , delimiter = "," ) : """Convert xlsx to easier format first , since we want to use the convenience of the CSV library"""
wb = load_workbook ( self . getInputFile ( ) ) sheet = wb . worksheets [ worksheet ] buffer = StringIO ( ) # extract all rows for n , row in enumerate ( sheet . rows ) : line = [ ] for cell in row : value = cell . value if type ( value ) in types . StringTypes : value = value . encod...
def put ( self , name , base ) : '''Add a Base ( or sub - class ) to the BaseRef by name . Args : name ( str ) : The name / iden of the Base base ( Base ) : The Base instance Returns : ( None )'''
async def fini ( ) : if self . base_by_name . get ( name ) is base : self . base_by_name . pop ( name , None ) # Remove myself from BaseRef when I fini base . onfini ( fini ) self . base_by_name [ name ] = base
def update ( self , pos ) : """Set new absolute progress position . Parameters : pos : new absolute progress"""
self . pos = pos self . now = time . time ( )
def compare_to_xrefs ( self , xg1 , xg2 ) : """Compares a base xref graph with another one"""
ont = self . merged_ontology for ( i , j , d ) in xg1 . edges ( data = True ) : ont_left = self . _id_to_ontology ( i ) ont_right = self . _id_to_ontology ( j ) unique_lr = True num_xrefs_left = 0 same_left = False if i in xg2 : for j2 in xg2 . neighbors ( i ) : ont_right2 = ...