signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def getResourceFileList ( self , pid ) :
"""Get a listing of files within a resource .
: param pid : The HydroShare ID of the resource whose resource files are to be listed .
: raises : HydroShareArgumentException if any parameters are invalid .
: raises : HydroShareNotAuthorized if user is not authorized to ... | url = "{url_base}/resource/{pid}/files/" . format ( url_base = self . url_base , pid = pid )
return resultsListGenerator ( self , url ) |
def parse_datetime ( s ) : # source : http : / / stackoverflow . com / questions / 2211362 / how - to - parse - xsddatetime - format
"""Returns ( datetime , tz offset in minutes ) or ( None , None ) .""" | m = re . match ( r""" ^
(?P<year>-?[0-9]{4}) - (?P<month>[0-9]{2}) - (?P<day>[0-9]{2})
T (?P<hour>[0-9]{2}) : (?P<minute>[0-9]{2}) : (?P<second>[0-9]{2})
(?P<microsecond>\.[0-9]{1,6})?
(?P<tz>
Z | (?P<tz_hr>[-+][0-9]{2}) : (?P<tz_min>[0-9]{2})
)?
$ """ , s , re . ... |
def copy ( self ) :
"""Create a copy of this ChemicalEntity""" | inst = super ( type ( self ) , type ( self ) ) . empty ( ** self . dimensions )
# Need to copy all attributes , fields , relations
inst . __attributes__ = { k : v . copy ( ) for k , v in self . __attributes__ . items ( ) }
inst . __fields__ = { k : v . copy ( ) for k , v in self . __fields__ . items ( ) }
inst . __rela... |
def signature_validate ( signature , error = None ) :
"is signature a valid sequence of zero or more complete types ." | error , my_error = _get_error ( error )
result = dbus . dbus_signature_validate ( signature . encode ( ) , error . _dbobj ) != 0
my_error . raise_if_set ( )
return result |
def bothify ( self , text = '## ??' , letters = string . ascii_letters ) :
"""Replaces all placeholders with random numbers and letters .
: param text : string to be parsed
: returns : string with all numerical and letter placeholders filled in""" | return self . lexify ( self . numerify ( text ) , letters = letters ) |
def order ( self , order ) :
'''Adds an Order to this query .
Args :
see : py : class : ` Order < datastore . query . Order > ` constructor
Returns self for JS - like method chaining : :
query . order ( ' + age ' ) . order ( ' - home ' )''' | order = order if isinstance ( order , Order ) else Order ( order )
# ensure order gets attr values the same way the rest of the query does .
order . object_getattr = self . object_getattr
self . orders . append ( order )
return self |
def list_services ( profile = None , api_key = None ) :
'''List services belonging to this account
CLI Example :
salt myminion pagerduty . list _ services my - pagerduty - account''' | return salt . utils . pagerduty . list_items ( 'services' , 'name' , __salt__ [ 'config.option' ] ( profile ) , api_key , opts = __opts__ ) |
def _maybe_coerce_values ( self , values ) :
"""Unbox to an extension array .
This will unbox an ExtensionArray stored in an Index or Series .
ExtensionArrays pass through . No dtype coercion is done .
Parameters
values : Index , Series , ExtensionArray
Returns
ExtensionArray""" | if isinstance ( values , ( ABCIndexClass , ABCSeries ) ) :
values = values . _values
return values |
def user_get ( alias = None , userids = None , ** kwargs ) :
'''Retrieve users according to the given parameters .
. . versionadded : : 2016.3.0
: param alias : user alias
: param userids : return only users with the given IDs
: param _ connection _ user : Optional - zabbix user ( can also be set in opts or... | conn_args = _login ( ** kwargs )
ret = { }
try :
if conn_args :
method = 'user.get'
params = { "output" : "extend" , "filter" : { } }
if not userids and not alias :
return { 'result' : False , 'comment' : 'Please submit alias or userids parameter to retrieve users.' }
if ... |
def set_extra_selections ( self , key , extra_selections ) :
"""Set extra selections for a key .
Also assign draw orders to leave current _ cell and current _ line
in the backgrund ( and avoid them to cover other decorations )
NOTE : This will remove previous decorations added to the same key .
Args :
key... | # use draw orders to highlight current _ cell and current _ line first
draw_order = DRAW_ORDERS . get ( key )
if draw_order is None :
draw_order = DRAW_ORDERS . get ( 'on_top' )
for selection in extra_selections :
selection . draw_order = draw_order
self . clear_extra_selections ( key )
self . extra_selections_... |
def get_discord_leaderboard ( self , guild ) :
"""Expects : ` int ` - Discord Guild ID
Returns : ` trainerdex . DiscordLeaderboard `""" | r = requests . get ( api_url + 'leaderboard/discord/' + str ( guild ) + '/' , headers = self . headers )
print ( request_status ( r ) )
r . raise_for_status ( )
return DiscordLeaderboard ( r . json ( ) ) |
def is_running ( self ) :
"""Property method that returns a bool specifying if the process is
currently running . This will return true if the state is active , idle
or initializing .
: rtype : bool""" | return self . _state in [ self . STATE_ACTIVE , self . STATE_IDLE , self . STATE_INITIALIZING ] |
def OnDeleteRows ( self , event ) :
"""Deletes rows from all tables of the grid""" | bbox = self . grid . selection . get_bbox ( )
if bbox is None or bbox [ 1 ] [ 0 ] is None : # Insert rows at cursor
del_point = self . grid . actions . cursor [ 0 ]
no_rows = 1
else : # Insert at lower edge of bounding box
del_point = bbox [ 0 ] [ 0 ]
no_rows = self . _get_no_rowscols ( bbox ) [ 0 ]
wit... |
def acquire_proxy ( self , host , port , use_ssl = False , host_key = None , tunnel = True ) :
'''Check out a connection .
This function is the same as acquire but with extra arguments
concerning proxies .
Coroutine .''' | if self . _host_filter and not self . _host_filter . test ( host ) :
connection = yield from super ( ) . acquire ( host , port , use_ssl , host_key )
return connection
host_key = host_key or ( host , port , use_ssl )
proxy_host , proxy_port = self . _proxy_address
connection = yield from super ( ) . acquire ( p... |
def multi ( self ) :
"""Start a transactional block of the pipeline after WATCH commands
are issued . End the transactional block with ` execute ` .""" | if self . explicit_transaction :
raise RedisError ( "Cannot issue nested calls to MULTI" )
if self . commands :
raise RedisError ( "Commands without an initial WATCH have already been issued" )
self . explicit_transaction = True |
def _find_combo_data ( widget , value ) :
"""Returns the index in a combo box where itemData = = value
Raises a ValueError if data is not found""" | # Here we check that the result is True , because some classes may overload
# = = and return other kinds of objects whether true or false .
for idx in range ( widget . count ( ) ) :
if widget . itemData ( idx ) is value or ( widget . itemData ( idx ) == value ) is True :
return idx
else :
raise ValueErr... |
def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , replaceParamFile ) :
"""Precipitation Read from File Method""" | # Set file extension property
self . fileExtension = extension
# Dictionary of keywords / cards and parse function names
KEYWORDS = ( 'EVENT' , )
# Parse file into chunks associated with keywords / cards
with open ( path , 'r' ) as f :
chunks = pt . chunk ( KEYWORDS , f )
# Parse chunks associated with each key
for... |
def get_remaining_time ( program ) :
'''Get the remaining time in seconds of a program that is currently on .''' | now = datetime . datetime . now ( )
program_start = program . get ( 'start_time' )
program_end = program . get ( 'end_time' )
if not program_start or not program_end :
_LOGGER . error ( 'Could not determine program start and/or end times.' )
_LOGGER . debug ( 'Program data: %s' , program )
return
if now > p... |
def make_handlers ( base_url , server_processes ) :
"""Get tornado handlers for registered server _ processes""" | handlers = [ ]
for sp in server_processes :
handler = _make_serverproxy_handler ( sp . name , sp . command , sp . environment , sp . timeout , sp . absolute_url , sp . port , )
handlers . append ( ( ujoin ( base_url , sp . name , r'(.*)' ) , handler , dict ( state = { } ) , ) )
handlers . append ( ( ujoin (... |
def plot ( data : Dict [ str , np . array ] , fields : List [ str ] = None , * args , ** kwargs ) :
"""Plot simulation data .
: data : A dictionary of arrays .
: fields : A list of variables you want to plot ( e . g . [ ' x ' , y ' , ' c ' ] )""" | if plt is None :
return
if fields is None :
fields = [ 'x' , 'y' , 'm' , 'c' ]
labels = [ ]
lines = [ ]
for field in fields :
if min ( data [ field ] . shape ) > 0 :
f_lines = plt . plot ( data [ 't' ] , data [ field ] , * args , ** kwargs )
lines . extend ( f_lines )
labels . extend... |
def format_unencoded ( self , tokensource , outfile ) :
"""The formatting process uses several nested generators ; which of
them are used is determined by the user ' s options .
Each generator should take at least one argument , ` ` inner ` ` ,
and wrap the pieces of text generated by this .
Always yield 2 ... | source = self . _format_lines ( tokensource )
if self . hl_lines :
source = self . _highlight_lines ( source )
if not self . nowrap :
if self . linenos == 2 :
source = self . _wrap_inlinelinenos ( source )
if self . lineanchors :
source = self . _wrap_lineanchors ( source )
if self . lin... |
def drawMeanOneLognormal ( N , sigma = 1.0 , seed = 0 ) :
'''Generate arrays of mean one lognormal draws . The sigma input can be a number
or list - like . If a number , output is a length N array of draws from the
lognormal distribution with standard deviation sigma . If a list , output is
a length T list wh... | # Set up the RNG
RNG = np . random . RandomState ( seed )
if isinstance ( sigma , float ) : # Return a single array of length N
mu = - 0.5 * sigma ** 2
draws = RNG . lognormal ( mean = mu , sigma = sigma , size = N )
else : # Set up empty list to populate , then loop and populate list with draws
draws = [ ]... |
def get_objective_query_session_for_objective_bank ( self , objective_bank_id = None ) :
"""Gets the OsidSession associated with the objective query service
for the given objective bank .
arg : objectiveBankId ( osid . id . Id ) : the Id of the objective
bank
return : ( osid . learning . ObjectiveQuerySessi... | if not objective_bank_id :
raise NullArgument
if not self . supports_objective_query ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( )
try :
session = sessions . ObjectiveQuerySession ( objective_bank_id , runtime = self . _runtime )
except Att... |
def get_morph_files ( directory ) :
'''Get a list of all morphology files in a directory
Returns :
list with all files with extensions ' . swc ' , ' h5 ' or ' . asc ' ( case insensitive )''' | lsdir = ( os . path . join ( directory , m ) for m in os . listdir ( directory ) )
return list ( filter ( _is_morphology_file , lsdir ) ) |
def optional_args ( proxy = None ) :
'''Return the connection optional args .
. . note : :
Sensible data will not be returned .
. . versionadded : : 2017.7.0
CLI Example - select all devices connecting via port 1234:
. . code - block : : bash
salt - G ' optional _ args : port : 1234 ' test . ping
Outp... | opt_args = _get_device_grain ( 'optional_args' , proxy = proxy ) or { }
if opt_args and _FORBIDDEN_OPT_ARGS :
for arg in _FORBIDDEN_OPT_ARGS :
opt_args . pop ( arg , None )
return { 'optional_args' : opt_args } |
def touch ( self , name , data ) :
"""Create a ' file ' analog called ' name ' and put ' data ' to the d _ data dictionary
under key ' name ' .
The ' name ' can contain a path specifier .""" | b_OK = True
str_here = self . cwd ( )
# print ( " here ! " )
# print ( self . snode _ current )
# print ( self . snode _ current . d _ nodes )
l_path = name . split ( '/' )
if len ( l_path ) > 1 :
self . cd ( '/' . join ( l_path [ 0 : - 1 ] ) )
name = l_path [ - 1 ]
self . snode_current . d_data [ name ] = data
# p... |
def sum_of_gaussian_factory ( N ) :
"""Return a model of the sum of N Gaussians and a constant background .""" | name = "SumNGauss%d" % N
attr = { }
# parameters
for i in range ( N ) :
key = "amplitude_%d" % i
attr [ key ] = Parameter ( key )
key = "center_%d" % i
attr [ key ] = Parameter ( key )
key = "stddev_%d" % i
attr [ key ] = Parameter ( key )
attr [ 'background' ] = Parameter ( 'background' , defau... |
def _check_sdp_from_eigen ( w , tol = None ) :
"""Checks if some of the eigenvalues given are negative , up to a tolerance
level , with a default value of the tolerance depending on the eigenvalues .
Parameters
w : array - like , shape = ( n _ eigenvalues , )
Eigenvalues to check for non semidefinite positi... | if tol is None :
tol = w . max ( ) * len ( w ) * np . finfo ( w . dtype ) . eps
if tol < 0 :
raise ValueError ( "tol should be positive." )
if any ( w < - tol ) :
raise ValueError ( "Matrix is not positive semidefinite (PSD)." ) |
def login ( self ) :
"""Logs the user in , returns the result
Returns
bool - Whether or not the user logged in successfully""" | # Request index to obtain initial cookies and look more human
pg = self . getPage ( "http://www.neopets.com" )
form = pg . form ( action = "/login.phtml" )
form . update ( { 'username' : self . username , 'password' : self . password } )
pg = form . submit ( )
logging . getLogger ( "neolib.user" ) . info ( "Login check... |
def human_xor_00 ( X , y , model_generator , method_name ) :
"""XOR ( false / false )
This tests how well a feature attribution method agrees with human intuition
for an eXclusive OR operation combined with linear effects . This metric deals
specifically with the question of credit allocation for the followin... | return _human_xor ( X , model_generator , method_name , False , False ) |
def map ( self , layers = None , interactive = True , zoom = None , lat = None , lng = None , size = ( 800 , 400 ) , ax = None ) :
"""Produce a CARTO map visualizing data layers .
Examples :
Create a map with two data : py : class : ` Layer
< cartoframes . layer . Layer > ` \ s , and one : py : class : ` Base... | # TODO : add layers preprocessing method like
# layers = process _ layers ( layers )
# that uses up to layer limit value error
if layers is None :
layers = [ ]
elif not isinstance ( layers , collections . Iterable ) :
layers = [ layers ]
else :
layers = list ( layers )
if len ( layers ) > 8 :
raise Valu... |
def build_if_needed ( self ) :
"""Reset shader source if necesssary .""" | if self . _need_build :
self . _build ( )
self . _need_build = False
self . update_variables ( ) |
async def SwitchBlockOff ( self , message , type_ ) :
'''message : str
type _ : str
Returns - > Error''' | # map input types to rpc msg
_params = dict ( )
msg = dict ( type = 'Block' , request = 'SwitchBlockOff' , version = 2 , params = _params )
_params [ 'message' ] = message
_params [ 'type' ] = type_
reply = await self . rpc ( msg )
return reply |
def getCfgFilesInDirForTask ( aDir , aTask , recurse = False ) :
"""This is a specialized function which is meant only to keep the
same code from needlessly being much repeated throughout this
application . This must be kept as fast and as light as possible .
This checks a given directory for . cfg files matc... | if recurse :
flist = irafutils . rglob ( aDir , '*.cfg' )
else :
flist = glob . glob ( aDir + os . sep + '*.cfg' )
if aTask :
retval = [ ]
for f in flist :
try :
if aTask == getEmbeddedKeyVal ( f , TASK_NAME_KEY , '' ) :
retval . append ( f )
except Exception ... |
def cmd_genobstacles ( self , args ) :
'''genobstacles command parser''' | usage = "usage: genobstacles <start|stop|restart|clearall|status|set>"
if len ( args ) == 0 :
print ( usage )
return
if args [ 0 ] == "set" :
gen_settings . command ( args [ 1 : ] )
elif args [ 0 ] == "start" :
if self . have_home :
self . start ( )
else :
self . pending_start = True... |
def get_friends ( self , limit = 50 , cacheable = False ) :
"""Returns a list of the user ' s friends .""" | seq = [ ]
for node in _collect_nodes ( limit , self , self . ws_prefix + ".getFriends" , cacheable ) :
seq . append ( User ( _extract ( node , "name" ) , self . network ) )
return seq |
def set_value ( self , value ) :
"""Set the value of the target .
: param obj value : The value to set .""" | self . _value = value
setattr ( self . target , self . _name , value ) |
def countedArray ( expr , intExpr = None ) :
"""Helper to define a counted list of expressions .
This helper defines a pattern of the form : :
integer expr expr expr . . .
where the leading integer tells how many expr expressions follow .
The matched tokens returns the array of expr tokens as a list - the l... | arrayExpr = Forward ( )
def countFieldParseAction ( s , l , t ) :
n = t [ 0 ]
arrayExpr << ( n and Group ( And ( [ expr ] * n ) ) or Group ( empty ) )
return [ ]
if intExpr is None :
intExpr = Word ( nums ) . setParseAction ( lambda t : int ( t [ 0 ] ) )
else :
intExpr = intExpr . copy ( )
intExpr .... |
def is_url ( str_ ) :
"""heuristic check if str is url formatted""" | return any ( [ str_ . startswith ( 'http://' ) , str_ . startswith ( 'https://' ) , str_ . startswith ( 'www.' ) , '.org/' in str_ , '.com/' in str_ , ] ) |
def cases ( arg , case_result_pairs , default = None ) :
"""Create a case expression in one shot .
Returns
case _ expr : SimpleCase""" | builder = arg . case ( )
for case , result in case_result_pairs :
builder = builder . when ( case , result )
if default is not None :
builder = builder . else_ ( default )
return builder . end ( ) |
def search_games ( self , query , live = True ) :
"""Search for games that are similar to the query
: param query : the query string
: type query : : class : ` str `
: param live : If true , only returns games that are live on at least one
channel
: type live : : class : ` bool `
: returns : A list of g... | r = self . kraken_request ( 'GET' , 'search/games' , params = { 'query' : query , 'type' : 'suggest' , 'live' : live } )
games = models . Game . wrap_search ( r )
for g in games :
self . fetch_viewers ( g )
return games |
def translations ( self ) :
"""Yield all six translations of a nucleotide sequence .
@ return : A generator that produces six L { TranslatedRead } instances .""" | rc = self . reverseComplement ( ) . sequence
for reverseComplemented in False , True :
for frame in 0 , 1 , 2 :
seq = rc if reverseComplemented else self . sequence
# Get the suffix of the sequence for translation . I . e . ,
# skip 0 , 1 , or 2 initial bases , depending on the frame .
... |
def template_ellipsoid ( shape ) :
r"""Returns an ellipsoid binary structure of a of the supplied radius that can be used as
template input to the generalized hough transform .
Parameters
shape : tuple of integers
The main axes of the ellipsoid in voxel units .
Returns
template _ sphere : ndarray
A bo... | # prepare template array
template = numpy . zeros ( [ int ( x // 2 + ( x % 2 ) ) for x in shape ] , dtype = numpy . bool )
# in odd shape cases , this will include the ellipses middle line , otherwise not
# get real world offset to compute the ellipsoid membership
rw_offset = [ ]
for s in shape :
if int ( s ) % 2 =... |
def get ( self ) :
"""Return a Deferred that fires with a SourceStamp instance .""" | d = self . getBaseRevision ( )
d . addCallback ( self . getPatch )
d . addCallback ( self . done )
return d |
def VariantDir ( self , variant_dir , src_dir , duplicate = 1 ) :
"""Link the supplied variant directory to the source directory
for purposes of building files .""" | if not isinstance ( src_dir , SCons . Node . Node ) :
src_dir = self . Dir ( src_dir )
if not isinstance ( variant_dir , SCons . Node . Node ) :
variant_dir = self . Dir ( variant_dir )
if src_dir . is_under ( variant_dir ) :
raise SCons . Errors . UserError ( "Source directory cannot be under variant direc... |
def geocode ( address ) :
'''Query function to obtain a latitude and longitude from a location
string such as ` Houston , TX ` or ` Colombia ` . This uses an online lookup ,
currently wrapping the ` geopy ` library , and providing an on - disk cache
of queries .
Parameters
address : str
Search string to... | loc_tuple = None
try :
cache = geopy_cache ( )
loc_tuple = cache . cached_address ( address )
except : # Handle bugs in the cache , i . e . if there is no space on disk to create
# the database , by ignoring them
pass
if loc_tuple is not None :
return loc_tuple
else :
geocoder = geopy_geolocator ( )... |
def lengthen ( self ) :
'''Returns a new Vowel with its Length lengthened ,
and " : " appended to its IPA symbol .''' | vowel = deepcopy ( self )
if vowel [ Length ] == Length . short :
vowel [ Length ] = Length . long
elif vowel [ Length ] == Length . long :
vowel [ Length ] = Length . overlong
vowel . ipa += ':'
return vowel |
def crop_3dimage ( img , beg_coords , end_coords ) :
"""Crops a 3d image to the bounding box specified .""" | cropped_img = img [ beg_coords [ 0 ] : end_coords [ 0 ] , beg_coords [ 1 ] : end_coords [ 1 ] , beg_coords [ 2 ] : end_coords [ 2 ] ]
return cropped_img |
def report_accounts ( self , path , per_region = True , per_capita = False , pic_size = 1000 , format = 'rst' , ffname = None , ** kwargs ) :
"""Writes a report to the given path for the regional accounts
The report consists of a text file and a folder with the pics
( both names following parameter name )
Not... | if not per_region and not per_capita :
return
_plt = plt . isinteractive ( )
_rcParams = mpl . rcParams . copy ( )
rcParams = { 'figure.figsize' : ( 10 , 5 ) , 'figure.dpi' : 350 , 'axes.titlesize' : 20 , 'axes.labelsize' : 20 , }
plt . ioff ( )
if type ( path ) is str :
path = path . rstrip ( '\\' )
path =... |
def create_from_hdulist ( cls , hdulist , ** kwargs ) :
"""Creates and returns an HpxMap object from a FITS HDUList
extname : The name of the HDU with the map data
ebounds : The name of the HDU with the energy bin data""" | extname = kwargs . get ( 'hdu' , hdulist [ 1 ] . name )
ebins = fits_utils . find_and_read_ebins ( hdulist )
return cls . create_from_hdu ( hdulist [ extname ] , ebins ) |
def get_system_uptime_output_show_system_uptime_rbridge_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_system_uptime = ET . Element ( "get_system_uptime" )
config = get_system_uptime
output = ET . SubElement ( get_system_uptime , "output" )
show_system_uptime = ET . SubElement ( output , "show-system-uptime" )
rbridge_id = ET . SubElement ( show_system_uptime , "rbridge-id" )
rbrid... |
def create_connection ( self , from_obj , to_obj ) :
"""Creates and returns a connection between the given objects . If a
connection already exists , that connection will be returned instead .""" | self . _validate_ctypes ( from_obj , to_obj )
return Connection . objects . get_or_create ( relationship_name = self . name , from_pk = from_obj . pk , to_pk = to_obj . pk ) [ 0 ] |
def plot_map ( x , y , z , ax = None , cmap = None , ncontours = 100 , vmin = None , vmax = None , levels = None , cbar = True , cax = None , cbar_label = None , cbar_orientation = 'vertical' , norm = None , ** kwargs ) :
"""Plot a two - dimensional map from data on a grid .
Parameters
x : ndarray ( T )
Binne... | import matplotlib . pyplot as _plt
if ax is None :
fig , ax = _plt . subplots ( )
else :
fig = ax . get_figure ( )
mappable = ax . contourf ( x , y , z , ncontours , norm = norm , vmin = vmin , vmax = vmax , cmap = cmap , levels = levels , ** _prune_kwargs ( kwargs ) )
misc = dict ( mappable = mappable )
if cba... |
def convert_pdf_to_txt ( pdf , startpage = None ) :
"""Convert a pdf file to text and return the text .
This method requires pdftotext to be installed .
Parameters
pdf : str
path to pdf file
startpage : int , optional
the first page we try to convert
Returns
str
the converted text""" | if startpage is not None :
startpageargs = [ '-f' , str ( startpage ) ]
else :
startpageargs = [ ]
stdout = subprocess . Popen ( [ "pdftotext" , "-q" ] + startpageargs + [ pdf , "-" ] , stdout = subprocess . PIPE ) . communicate ( ) [ 0 ]
# python2 and 3
if not isinstance ( stdout , str ) :
stdout = stdout ... |
def get_function ( self ) :
"""Return function object for my function .
raise ProcessorConfigurationError when function could not be resolved .""" | if not hasattr ( self , '_function' ) :
try :
modname , funcname = self . function . rsplit ( '.' , 1 )
mod = import_module ( modname )
self . _function = getattr ( mod , funcname )
except ( ImportError , AttributeError , ValueError ) , err :
raise ProcessorConfigurationError ( e... |
def bigram ( self , items ) :
"""generate bigrams of either items = " tokens " or " stems " """ | def bigram_join ( tok_list ) :
text = nltk . bigrams ( tok_list )
return list ( map ( lambda x : x [ 0 ] + '.' + x [ 1 ] , text ) )
if items == "tokens" :
self . bigrams = list ( map ( bigram_join , self . tokens ) )
elif items == "stems" :
self . bigrams = list ( map ( bigram_join , self . stems ) )
el... |
def distance ( self , xyz = ( 0.00 , 0.00 , 0.00 ) , records = ( 'ATOM' , 'HETATM' ) ) :
"""Computes Euclidean distance between atoms and a 3D point .
Parameters
xyz : tuple , default : ( 0.00 , 0.00 , 0.00)
X , Y , and Z coordinate of the reference center for the distance
computation .
records : iterable... | if isinstance ( records , str ) :
warnings . warn ( 'Using a string as `records` argument is ' 'deprecated and will not be supported in future' ' versions. Please use a tuple or' ' other iterable instead' , DeprecationWarning )
records = ( records , )
df = pd . concat ( objs = [ self . df [ i ] for i in records... |
def get_repository_hierarchy_design_session ( self ) :
"""Gets the repository hierarchy design session .
return : ( osid . repository . RepositoryHierarchyDesignSession ) - a
` ` RepostoryHierarchyDesignSession ` `
raise : OperationFailed - unable to complete request
raise : Unimplemented -
` ` supports _... | if not self . supports_repository_hierarchy_design ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . RepositoryHierarchyDesignSession ( runtime = self . _runtime ) |
def setEditorData ( self , editor , index ) :
"""Provides the widget with data to manipulate .
Calls the setEditorValue of the config tree item at the index .
: type editor : QWidget
: type index : QModelIndex
Reimplemented from QStyledItemDelegate .""" | # We take the config value via the model to be consistent with setModelData
data = index . model ( ) . data ( index , Qt . EditRole )
editor . setData ( data ) |
def parseFile ( self , fil ) :
"""Opens a file and parses it""" | f = open ( fil )
self . parseStr ( f . read ( ) )
f . close ( ) |
def dumpgrants ( destination , as_json = None , setspec = None ) :
"""Harvest grants from OpenAIRE and store them locally .""" | if os . path . isfile ( destination ) :
click . confirm ( "Database '{0}' already exists." "Do you want to write to it?" . format ( destination ) , abort = True )
# no cover
dumper = OAIREDumper ( destination , setspec = setspec )
dumper . dump ( as_json = as_json ) |
def parse_environment_file_list ( names , world_size = ( 60 , 60 ) ) :
"""Extract information about spatial resources from all environment files in
a list .
Arguments :
names - a list of strings representing the paths to the environment files .
world _ size - a tuple representing the x and y coordinates of ... | # Convert single file to list if necessary
try :
names [ 0 ] = names [ 0 ]
except :
names = [ names ]
envs = [ ]
for name in names :
envs . append ( parse_environment_file ( name , world_size ) )
return envs |
def Copy ( self , name = None ) :
"""Returns a copy of this Cdf .
Args :
name : string name for the new Cdf""" | if name is None :
name = self . name
return Cdf ( list ( self . xs ) , list ( self . ps ) , name ) |
def contributors ( lancet , output ) :
"""List all contributors visible in the git history .""" | sorting = pygit2 . GIT_SORT_TIME | pygit2 . GIT_SORT_REVERSE
commits = lancet . repo . walk ( lancet . repo . head . target , sorting )
contributors = ( ( c . author . name , c . author . email ) for c in commits )
contributors = OrderedDict ( contributors )
template_content = content_from_path ( lancet . config . get ... |
def touch_import ( package , name , node ) :
"""Works like ` does _ tree _ import ` but adds an import statement
if it was not imported .""" | def is_import_stmt ( node ) :
return ( node . type == syms . simple_stmt and node . children and is_import ( node . children [ 0 ] ) )
root = find_root ( node )
if does_tree_import ( package , name , root ) :
return
# figure out where to insert the new import . First try to find
# the first import and then skip... |
async def on_message ( message ) :
"""The on _ message event handler for this module
Args :
message ( discord . Message ) : Input message""" | # Simplify message info
server = message . server
author = message . author
channel = message . channel
content = message . content
data = datatools . get_data ( )
if not data [ "discord" ] [ "servers" ] [ server . id ] [ _data . modulename ] [ "activated" ] :
return
# Only reply to server messages and don ' t repl... |
def random_draw ( self , size = None ) :
"""Draw random samples of the hyperparameters .
Parameters
size : None , int or array - like , optional
The number / shape of samples to draw . If None , only one sample is
returned . Default is None .""" | return scipy . asarray ( [ scipy . stats . lognorm . rvs ( s , loc = 0 , scale = em , size = size ) for s , em in zip ( self . sigma , self . emu ) ] ) |
def evaluate ( self , m ) :
"""Search for comments .""" | g = m . groupdict ( )
if g [ "strings" ] :
self . evaluate_strings ( g )
self . line_num += g [ 'strings' ] . count ( '\n' )
elif g [ "code" ] :
self . line_num += g [ "code" ] . count ( '\n' )
else :
if g [ 'block' ] :
self . evaluate_block ( g )
elif g [ 'start' ] is None :
self . ... |
def _load_state ( self , context ) :
"""Load state from cookie to the context
: type context : satosa . context . Context
: param context : Session context""" | try :
state = cookie_to_state ( context . cookie , self . config [ "COOKIE_STATE_NAME" ] , self . config [ "STATE_ENCRYPTION_KEY" ] )
except SATOSAStateError as e :
msg_tmpl = 'Failed to decrypt state {state} with {error}'
msg = msg_tmpl . format ( state = context . cookie , error = str ( e ) )
satosa_l... |
def future ( self , rev = None ) :
"""Return a Mapping of items after the given revision .
Default revision is the last one looked up .""" | if rev is not None :
self . seek ( rev )
return WindowDictFutureView ( self . _future ) |
def get_items_by_ids ( self , item_ids , item_type = None ) :
"""Given a list of item ids , return all the Item objects
Args :
item _ ids ( obj ) : List of item IDs to query
item _ type ( str ) : ( optional ) Item type to filter results with
Returns :
List of ` Item ` objects for given item IDs and given ... | urls = [ urljoin ( self . item_url , f"{i}.json" ) for i in item_ids ]
result = self . _run_async ( urls = urls )
items = [ Item ( r ) for r in result if r ]
if item_type :
return [ item for item in items if item . item_type == item_type ]
else :
return items |
def __sendCommand ( self , cmd ) :
"""send specific command to reference unit over serial port
Args :
cmd : OpenThread _ WpanCtl command string
Returns :
Fail : Failed to send the command to reference unit and parse it
Value : successfully retrieve the desired value from reference unit
Error : some erro... | logging . info ( '%s: sendCommand[%s]' , self . port , cmd )
if self . logThreadStatus == self . logStatus [ 'running' ] :
self . logThreadStatus = self . logStatus [ 'pauseReq' ]
while self . logThreadStatus != self . logStatus [ 'paused' ] and self . logThreadStatus != self . logStatus [ 'stop' ] :
pa... |
def close ( self ) :
"""Closes connection to the server .""" | if self . _protocol is not None :
self . _protocol . processor . close ( )
del self . _protocol |
def _get_current_userprofile ( ) :
"""Get current user profile .
. . note : : If the user is anonymous , then a
: class : ` invenio _ userprofiles . models . AnonymousUserProfile ` instance is
returned .
: returns : The : class : ` invenio _ userprofiles . models . UserProfile ` instance .""" | if current_user . is_anonymous :
return AnonymousUserProfile ( )
profile = g . get ( 'userprofile' , UserProfile . get_by_userid ( current_user . get_id ( ) ) )
if profile is None :
profile = UserProfile ( user_id = int ( current_user . get_id ( ) ) )
g . userprofile = profile
return profile |
def list_tables ( self , like = None , database = None ) :
"""List tables in the current ( or indicated ) database . Like the SHOW
TABLES command in the impala - shell .
Parameters
like : string , default None
e . g . ' foo * ' to match all tables starting with ' foo '
database : string , default None
I... | statement = 'SHOW TABLES'
if database :
statement += ' IN {0}' . format ( database )
if like :
m = ddl . fully_qualified_re . match ( like )
if m :
database , quoted , unquoted = m . groups ( )
like = quoted or unquoted
return self . list_tables ( like = like , database = database )
... |
def get_percentage_volume_change ( self ) :
"""Returns the percentage volume change .
Returns :
Volume change in percentage , e . g . , 0.055 implies a 5.5 % increase .""" | initial_vol = self . initial . lattice . volume
final_vol = self . final . lattice . volume
return final_vol / initial_vol - 1 |
def get_photo_url ( photo_id ) :
"""Request the photo download url with the photo id
: param photo _ id : The photo id of flickr
: type photo _ id : str
: return : Photo download url
: rtype : str""" | args = _get_request_args ( 'flickr.photos.getSizes' , photo_id = photo_id )
resp = requests . post ( API_URL , data = args )
resp_json = json . loads ( resp . text . encode ( 'utf-8' ) )
logger . debug ( json . dumps ( resp_json , indent = 2 ) )
size_list = resp_json [ 'sizes' ] [ 'size' ]
size_list_len = len ( size_li... |
def replace ( key , value , host = DEFAULT_HOST , port = DEFAULT_PORT , time = DEFAULT_TIME , min_compress_len = DEFAULT_MIN_COMPRESS_LEN ) :
'''Replace a key on the memcached server . This only succeeds if the key
already exists . This is the opposite of : mod : ` memcached . add
< salt . modules . memcached .... | if not isinstance ( time , six . integer_types ) :
raise SaltInvocationError ( '\'time\' must be an integer' )
if not isinstance ( min_compress_len , six . integer_types ) :
raise SaltInvocationError ( '\'min_compress_len\' must be an integer' )
conn = _connect ( host , port )
stats = conn . get_stats ( )
retur... |
def read ( self , num_bytes ) :
"""Read ` num _ bytes ` from the compressed data chunks .
Data is returned as ` bytes ` of length ` num _ bytes `
Will raise an EOFError if data is unavailable .
Note : Will always return ` num _ bytes ` of data ( unlike the file read method ) .""" | while len ( self . decoded ) < num_bytes :
try :
tag , data = next ( self . chunks )
except StopIteration :
raise EOFError ( )
if tag != b'IDAT' :
continue
self . decoded += self . decompressor . decompress ( data )
r = self . decoded [ : num_bytes ]
self . decoded = self . decod... |
def get_sequence_str ( self ) :
''': return : string representation of the sequence''' | sequence = self . get_sequence ( )
return '->' . join ( e . dst . name for e in sequence ) |
def _val_to_store_info ( self , val , min_compress_len ) :
"""Transform val to a storable representation , returning a tuple of the flags , the length of the new value , and the new value itself .""" | flags = 0
if isinstance ( val , str ) :
pass
elif isinstance ( val , int ) :
flags |= Client . _FLAG_INTEGER
val = "%d" % val
# force no attempt to compress this silly string .
min_compress_len = 0
elif isinstance ( val , long ) :
flags |= Client . _FLAG_LONG
val = "%d" % val
# force no ... |
def _normalize ( self , metric_name , submit_method , prefix ) :
"""Replace case - sensitive metric name characters , normalize the metric name ,
prefix and suffix according to its type .""" | metric_prefix = "mongodb." if not prefix else "mongodb.{0}." . format ( prefix )
metric_suffix = "ps" if submit_method == RATE else ""
# Replace case - sensitive metric name characters
for pattern , repl in iteritems ( self . CASE_SENSITIVE_METRIC_NAME_SUFFIXES ) :
metric_name = re . compile ( pattern ) . sub ( rep... |
def interp_w_v1 ( self ) :
"""Calculate the actual water stage based on linear interpolation .
Required control parameters :
| llake _ control . V |
| llake _ control . W |
Required state sequence :
| llake _ states . V |
Calculated state sequence :
| llake _ states . W |
Examples :
Prepare a mode... | con = self . parameters . control . fastaccess
new = self . sequences . states . fastaccess_new
for jdx in range ( 1 , con . n ) :
if con . v [ jdx ] >= new . v :
break
new . w = ( ( new . v - con . v [ jdx - 1 ] ) * ( con . w [ jdx ] - con . w [ jdx - 1 ] ) / ( con . v [ jdx ] - con . v [ jdx - 1 ] ) + con... |
def qteInsertKey ( self , keysequence : QtmacsKeysequence , macroName : str ) :
"""Insert a new key into the key map and associate it with a
macro .
If the key sequence is already associated with a macro then it
will be overwritten .
| Args |
* ` ` keysequence ` ` ( * * QtmacsKeysequence * * ) : associate... | # Get a dedicated reference to self to facilitate traversing
# through the key map .
keyMap = self
# Get the key sequence as a list of tuples , where each tuple
# contains the the control modifier and the key code , and both
# are specified as Qt constants .
keysequence = keysequence . toQtKeylist ( )
# Traverse the sh... |
def basis_state ( i , n ) :
"""` ` n x 1 ` ` ` sympy . Matrix ` representing the ` i ` ' th eigenstate of an
` n ` - dimensional Hilbert space ( ` i ` > = 0)""" | v = sympy . zeros ( n , 1 )
v [ i ] = 1
return v |
def notify ( title , message , api_key = NTFY_API_KEY , provider_key = None , priority = 0 , url = None , retcode = None ) :
"""Optional parameters :
* ` ` api _ key ` ` - use your own application token
* ` ` provider _ key ` ` - if you are whitelisted
* ` ` priority ` `
* ` ` url ` `""" | data = { 'apikey' : api_key , 'application' : 'ntfy' , 'event' : title , 'description' : message , }
if MIN_PRIORITY <= priority <= MAX_PRIORITY :
data [ 'priority' ] = priority
else :
raise ValueError ( 'priority must be an integer from {:d} to {:d}' . format ( MIN_PRIORITY , MAX_PRIORITY ) )
if url is not Non... |
def get_warcinfo ( self ) :
'''Returns WARCINFO record from the archieve as a single string including
WARC header . Expects the record to be in the beginning of the archieve ,
otherwise it will be not found .''' | if self . searched_for_warcinfo :
return self . warcinfo
prev_line = None
in_warcinfo_record = False
self . searched_for_warcinfo = True
for line in self . file_object :
if not in_warcinfo_record :
if line [ : 11 ] == b'WARC-Type: ' :
if line [ : 19 ] == b'WARC-Type: warcinfo' :
... |
def get_operator ( self , operator ) :
"""| coro |
Checks the players stats for this operator , only loading them if they haven ' t already been found
Parameters
operator : str
the name of the operator
Returns
: class : ` Operator `
the operator object found""" | if operator in self . operators :
return self . operators [ operator ]
result = yield from self . load_operator ( operator )
return result |
def recurse ( self , value , max_depth = 6 , _depth = 0 , ** kwargs ) :
"""Given ` ` value ` ` , recurse ( using the parent serializer ) to handle
coercing of newly defined values .""" | string_max_length = kwargs . get ( 'string_max_length' , None )
_depth += 1
if _depth >= max_depth :
try :
value = text_type ( repr ( value ) ) [ : string_max_length ]
except Exception as e :
import traceback
traceback . print_exc ( )
self . manager . logger . exception ( e )
... |
def q ( line , cell = None , _ns = None ) :
"""Run q code .
Options :
- l ( dir | script ) - pre - load database or script
- h host : port - execute on the given host
- o var - send output to a variable named var .
- i var1 , . . , varN - input variables
-1 / - 2 - redirect stdout / stderr""" | if cell is None :
return pyq . q ( line )
if _ns is None :
_ns = vars ( sys . modules [ '__main__' ] )
input = output = None
preload = [ ]
outs = { }
try :
h = pyq . q ( '0i' )
if line :
for opt , value in getopt ( line . split ( ) , "h:l:o:i:12" ) [ 0 ] :
if opt == '-l' :
... |
def discover_engines ( self , executor = None ) :
"""Discover configured engines .
: param executor : Optional executor module override""" | if executor is None :
executor = getattr ( settings , 'FLOW_EXECUTOR' , { } ) . get ( 'NAME' , 'resolwe.flow.executors.local' )
self . executor = self . load_executor ( executor )
logger . info ( __ ( "Loaded '{}' executor." , str ( self . executor . __class__ . __module__ ) . replace ( '.prepare' , '' ) ) )
expres... |
def read_config ( desired_type : Type [ ConfigParser ] , file_object : TextIOBase , logger : Logger , * args , ** kwargs ) -> ConfigParser :
"""Helper method to read a configuration file according to the ' configparser ' format , and return it as a dictionary
of dictionaries ( section > [ property > value ] )
:... | # see https : / / docs . python . org / 3 / library / configparser . html for details
config = ConfigParser ( )
config . read_file ( file_object )
return config |
def draw ( self , img , pixmapper , bounds ) :
'''draw the thumbnail on the image''' | if self . hidden :
return
thumb = self . img ( )
( px , py ) = pixmapper ( self . latlon )
# find top left
( w , h ) = image_shape ( thumb )
px -= w // 2
py -= h // 2
( px , py , sx , sy , w , h ) = self . clip ( px , py , w , h , img )
thumb_roi = thumb [ sy : sy + h , sx : sx + w ]
img [ py : py + h , px : px + w... |
def run ( self ) -> Generator [ Tuple [ int , int , str , type ] , None , None ] :
"""Yields :
tuple ( line _ number : int , offset : int , text : str , check : type )""" | if is_test_file ( self . filename ) :
self . load ( )
for func in self . all_funcs ( ) :
try :
for error in func . check_all ( ) :
yield ( error . line_number , error . offset , error . text , Checker )
except ValidationError as error :
yield error . to_fl... |
def split_pow_tgh ( self , text ) :
"""Split a power / toughness string on the correct slash .
Correctly accounts for curly braces to denote fractions .
E . g . , ' 2/2 ' - - > [ ' 2 ' , ' 2 ' ]
'3{1/2 } / 3{1/2 } ' - - > [ ' 3{1/2 } ' , ' 3{1/2 } ' ]""" | return [ n for n in re . split ( r"/(?=([^{}]*{[^{}]*})*[^{}]*$)" , text ) if n is not None ] [ : 2 ] |
def _set_circuit_type ( self , v , load = False ) :
"""Setter method for circuit _ type , mapped from YANG variable / routing _ system / interface / ve / intf _ isis / interface _ isis / circuit _ type ( enumeration )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ circ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'level-1-2' : { 'value' : 3 } , u'level-2' : { 'value' : 2 } , u'level-1' : { 'value' : 1 } } , ) , is_leaf = True , yang_name =... |
def safe_load ( fname ) :
"""Load the file fname and make sure it can be done in parallel
Parameters
fname : str
The path name""" | lock = fasteners . InterProcessLock ( fname + '.lck' )
lock . acquire ( )
try :
with open ( fname ) as f :
return ordered_yaml_load ( f )
except :
raise
finally :
lock . release ( ) |
def _fetch_dataframe ( self ) :
"""Return a pandas dataframe with all the training jobs , along with their
hyperparameters , results , and metadata . This also includes a column to indicate
if a training job was the best seen so far .""" | def reshape ( training_summary ) : # Helper method to reshape a single training job summary into a dataframe record
out = { }
for k , v in training_summary [ 'TunedHyperParameters' ] . items ( ) : # Something ( bokeh ? ) gets confused with ints so convert to float
try :
v = float ( v )
... |
def get_theme ( self ) :
"""Gets theme settings from settings service . Falls back to default ( LMS ) theme
if settings service is not available , xblock theme settings are not set or does
contain mentoring theme settings .""" | xblock_settings = self . get_xblock_settings ( default = { } )
if xblock_settings and self . theme_key in xblock_settings :
return xblock_settings [ self . theme_key ]
return self . default_theme_config |
def wait_for_port_open ( self , postmaster , timeout ) :
"""Waits until PostgreSQL opens ports .""" | for _ in polling_loop ( timeout ) :
with self . _cancellable_lock :
if self . _is_cancelled :
return False
if not postmaster . is_running ( ) :
logger . error ( 'postmaster is not running' )
self . set_state ( 'start failed' )
return False
isready = self . pg_isre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.