signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _set_session ( ) :
"""Sets global _ _ SESSION and _ _ USER _ ID if they haven ' t been set""" | global __SESSION
global __USER_ID
if __SESSION is None :
try :
__SESSION = AuthorizedSession ( google . auth . default ( [ 'https://www.googleapis.com/auth/userinfo.profile' , 'https://www.googleapis.com/auth/userinfo.email' ] ) [ 0 ] )
health ( )
__USER_ID = id_token . verify_oauth2_token (... |
def merge_stylesheets ( Class , fn , * cssfns ) :
"""merge the given CSS files , in order , into a single stylesheet . First listed takes priority .""" | stylesheet = Class ( fn = fn )
for cssfn in cssfns :
css = Class ( fn = cssfn )
for sel in sorted ( css . styles . keys ( ) ) :
if sel not in stylesheet . styles :
stylesheet . styles [ sel ] = css . styles [ sel ]
else :
for prop in [ prop for prop in css . styles [ sel ... |
def relative_probability_from_lookup_table ( self , jump_lookup_table ) :
"""Relative probability of accepting this jump from a lookup - table .
Args :
jump _ lookup _ table ( LookupTable ) : the lookup table to be used for this jump .
Returns :
( Float ) : relative probability of accepting this jump .""" | l1 = self . initial_site . label
l2 = self . final_site . label
c1 = self . initial_site . nn_occupation ( )
c2 = self . final_site . nn_occupation ( )
return jump_lookup_table . jump_probability [ l1 ] [ l2 ] [ c1 ] [ c2 ] |
def find_commands ( cls ) :
"""Finds commands by finding the subclasses of Command""" | cmds = [ ]
for subclass in cls . __subclasses__ ( ) :
cmds . append ( subclass )
cmds . extend ( find_commands ( subclass ) )
return cmds |
def _relation_exists ( self , connection , relation ) :
"""Returns True if relation ( table or view ) exists in the sqlite db . Otherwise returns False .
Args :
connection ( apsw . Connection ) : connection to sqlite database who stores mpr data .
partition ( orm . Partition ) :
Returns :
boolean : True i... | query = 'SELECT 1 FROM sqlite_master WHERE (type=\'table\' OR type=\'view\') AND name=?;'
cursor = connection . cursor ( )
cursor . execute ( query , [ relation ] )
result = cursor . fetchall ( )
return result == [ ( 1 , ) ] |
def setup_requires ( ) :
"""Return required packages
Plus any version tests and warnings""" | from pkg_resources import parse_version
required = [ 'cython>=0.24.0' ]
numpy_requirement = 'numpy>=1.7.1'
try :
import numpy
except Exception :
required . append ( numpy_requirement )
else :
if parse_version ( numpy . __version__ ) < parse_version ( '1.7.1' ) :
required . append ( numpy_requirement... |
def p_mp_setQualifier ( p ) :
"""mp _ setQualifier : qualifierDeclaration""" | qualdecl = p [ 1 ]
ns = p . parser . handle . default_namespace
if p . parser . verbose :
p . parser . log ( _format ( "Setting qualifier {0!A}" , qualdecl . name ) )
try :
p . parser . handle . SetQualifier ( qualdecl )
except CIMError as ce :
if ce . status_code == CIM_ERR_INVALID_NAMESPACE :
if p... |
def add_element ( source , path , value , separator = r'[/.]' , ** kwargs ) :
"""Add element into a list or dict easily using a path .
Parameter Type Description
source list or dict element where add the value .
path string path to add the value in element .
value ¿ all ? value to add in source .
separato... | return _add_element_by_names ( source , exclude_empty_values ( re . split ( separator , path ) ) , value , ** kwargs ) |
def set_subdata ( self , data , offset = 0 , copy = False ) :
"""Set a sub - region of the buffer ( deferred operation ) .
Parameters
data : ndarray
Data to be uploaded
offset : int
Offset in buffer where to start copying data ( in bytes )
copy : bool
Since the operation is deferred , data may change ... | data = np . array ( data , copy = copy )
nbytes = data . nbytes
if offset < 0 :
raise ValueError ( "Offset must be positive" )
elif ( offset + nbytes ) > self . _nbytes :
raise ValueError ( "Data does not fit into buffer" )
# If the whole buffer is to be written , we clear any pending data
# ( because they will... |
def incr ( self , key , delta = 1 ) :
"""Add delta to value in the cache . If the key does not exist , raise a
ValueError exception .""" | value = self . get ( key )
if value is None :
raise ValueError ( "Key '%s' not found" % key )
new_value = value + delta
self . set ( key , new_value )
return new_value |
def setViewWidget ( self , viewWidget ) :
"""Sets the view widget linked with this toolbar .
: param viewWidget | < XViewWidget >""" | self . _viewWidget = viewWidget
if viewWidget :
viewWidget . resetFinished . connect ( self . clearActive ) |
def validate ( self , val ) :
"""For a val to pass validation , val must be of the correct type and have
all required fields present .""" | self . validate_type_only ( val )
self . validate_fields_only ( val )
return val |
def duplicate ( self , parent ) :
"""Duplicates this current view for another . Subclass this method to
provide any additional duplication options .
: param parent | < QWidget >
: return < XView > | instance of this class""" | # only return a single singleton instance
if self . isViewSingleton ( ) :
return self
output = type ( self ) . createInstance ( parent , self . viewWidget ( ) )
# save / restore the current settings
xdata = ElementTree . Element ( 'data' )
self . saveXml ( xdata )
new_name = output . objectName ( )
output . setObje... |
def build_remap_symbols ( self , name_generator , children_only = None ) :
"""The children _ only flag is inapplicable , but this is included as
the Scope class is defined like so .
Here this simply just place the catch symbol with the next
replacement available .""" | replacement = name_generator ( skip = ( self . _reserved_symbols ) )
self . remapped_symbols [ self . catch_symbol ] = next ( replacement )
# also to continue down the children .
for child in self . children :
child . build_remap_symbols ( name_generator , False ) |
def delete_existing_cname ( env , zone_id , dns_name ) :
"""Delete an existing CNAME record .
This is used when updating to multi - region for deleting old records . The
record can not just be upserted since it changes types .
Args :
env ( str ) : Deployment environment .
zone _ id ( str ) : Route53 zone ... | client = boto3 . Session ( profile_name = env ) . client ( 'route53' )
startrecord = None
newrecord_name = dns_name
startrecord = find_existing_record ( env , zone_id , newrecord_name , check_key = 'Type' , check_value = 'CNAME' )
if startrecord :
LOG . info ( "Deleting old record: %s" , newrecord_name )
_respo... |
def to_dictionary ( self , key_selector = lambda item : item . key , value_selector = list ) :
"""Build a dictionary from the source sequence .
Args :
key _ selector : A unary callable to extract a key from each item .
By default the key of the Grouping .
value _ selector : A unary callable to extract a val... | return super ( Lookup , self ) . to_dictionary ( key_selector , value_selector ) |
def _assemble_and_send_request ( self ) :
"""Fires off the Fedex request .
@ warning : NEVER CALL THIS METHOD DIRECTLY . CALL send _ request ( ) ,
WHICH RESIDES ON FedexBaseService AND IS INHERITED .""" | # Fire off the query .
return self . client . service . processShipment ( WebAuthenticationDetail = self . WebAuthenticationDetail , ClientDetail = self . ClientDetail , TransactionDetail = self . TransactionDetail , Version = self . VersionId , RequestedShipment = self . RequestedShipment ) |
def traceroute ( domain , method = "udp" , cmd_arguments = None , external = None , log_prefix = '' ) :
"""This function uses centinel . command to issue
a traceroute command , wait for it to finish execution and
parse the results out to a dictionary .
: param domain : the domain to be queried
: param metho... | # the method specified by the function parameter here will
# over - ride the ones given in cmd _ arguments because
# traceroute will use the last one in the argument list .
_cmd_arguments = [ ]
logging . debug ( "%sRunning traceroute for " "%s using %s probes." % ( log_prefix , domain , method ) )
results = { "method" ... |
def trim ( self , lower = None , upper = None ) :
"""Trim values in accordance with : math : ` WAeS \\ leq PWMax \\ cdot WATS ` .
> > > from hydpy . models . lland import *
> > > parameterstep ( ' 1d ' )
> > > nhru ( 7)
> > > pwmax ( 2 . )
> > > states . wats = 0 . , 0 . , 0 . , 5 . , 5 . , 5 . , 5.
> >... | pwmax = self . subseqs . seqs . model . parameters . control . pwmax
wats = self . subseqs . wats
if upper is None :
upper = pwmax * wats
lland_sequences . State1DSequence . trim ( self , lower , upper ) |
def units ( self , value ) :
"""Set the units for every model in the scene without
converting any units just setting the tag .
Parameters
value : str
Value to set every geometry unit value to""" | for m in self . geometry . values ( ) :
m . units = value |
def dropped ( self , param , event ) :
"""Adds the dropped parameter * param * into the protocol list .
Re - implemented from : meth : ` AbstractDragView < sparkle . gui . abstract _ drag _ view . AbstractDragView . dropped > `""" | if event . source ( ) == self or isinstance ( param , AddLabel ) :
index = self . indexAt ( event . pos ( ) )
self . model ( ) . insertRows ( index . row ( ) , 1 )
if event . source ( ) == self :
self . model ( ) . setData ( index , param )
else :
self . hintRequested . emit ( 'Select Co... |
def _check_minions_directories ( self ) :
'''Return the minion keys directory paths''' | minions_accepted = os . path . join ( self . opts [ 'pki_dir' ] , self . ACC )
minions_pre = os . path . join ( self . opts [ 'pki_dir' ] , self . PEND )
minions_rejected = os . path . join ( self . opts [ 'pki_dir' ] , self . REJ )
minions_denied = os . path . join ( self . opts [ 'pki_dir' ] , self . DEN )
return min... |
def augment_pipeline ( pl , head_pipe = None , tail_pipe = None ) :
"""Augment the pipeline by adding a new pipe section to each stage that has one or more pipes . Can be used for debugging
: param pl :
: param DebugPipe :
: return :""" | for k , v in iteritems ( pl ) :
if v and len ( v ) > 0 :
if head_pipe and k != 'source' : # Can ' t put anything before the source .
v . insert ( 0 , head_pipe )
if tail_pipe :
v . append ( tail_pipe ) |
def input ( self ) :
"""Dictionary access to all input variables
That can be boundary conditions and other gridded quantities
independent of the ` process `
: type : dict""" | input_dict = { }
for key in self . _input_vars :
try :
input_dict [ key ] = getattr ( self , key )
except :
pass
return input_dict |
def predictive_gradients ( self , Xnew , kern = None ) :
"""Compute the derivatives of the predicted latent function with respect
to X *
Given a set of points at which to predict X * ( size [ N * , Q ] ) , compute the
derivatives of the mean and variance . Resulting arrays are sized :
dmu _ dX * - - [ N * ,... | if kern is None :
kern = self . kern
mean_jac = np . empty ( ( Xnew . shape [ 0 ] , Xnew . shape [ 1 ] , self . output_dim ) )
for i in range ( self . output_dim ) :
mean_jac [ : , : , i ] = kern . gradients_X ( self . posterior . woodbury_vector [ : , i : i + 1 ] . T , Xnew , self . _predictive_variable )
# Gr... |
def _items ( self ) :
"""Parse url and yield namedtuple Torrent for every torrent on page""" | torrents = map ( self . _get_torrent , self . _get_rows ( ) )
for t in torrents :
yield t |
def term ( self , term , ** kwargs ) :
"""Adds a term to the current query , creating a Clause and adds it to
the list of clauses making up this Query .
The term is not tokenized and used " as is " . Any conversion to token
or token - like strings should be performed before calling this method .
For example... | if isinstance ( term , ( list , tuple ) ) :
for t in term :
self . term ( t , ** kwargs )
else :
self . clause ( str ( term ) , ** kwargs )
return self |
def tag ( self , tagname , message = None , force = True ) :
"""Create an annotated tag .""" | return git_tag ( self . repo_dir , tagname , message = message , force = force ) |
def _getRadius ( self , location ) :
"""Returns the radius associated with the given location .
This is a bit of an awkward argument to the CoordinateEncoder , which
specifies the resolution ( in was used to encode differently depending on
speed in the GPS encoder ) . Since the coordinates are object - centri... | # TODO : find better heuristic
return int ( math . sqrt ( sum ( [ coord ** 2 for coord in location ] ) ) ) |
def partition_horizontal_twice ( thelist , numbers ) :
"""numbers is split on a comma to n and n2.
Break a list into peices each peice alternating between n and n2 items long
` ` partition _ horizontal _ twice ( range ( 14 ) , " 3,4 " ) ` ` gives : :
[ [ 0 , 1 , 2 ] ,
[3 , 4 , 5 , 6 ] ,
[7 , 8 , 9 ] ,
[... | n , n2 = numbers . split ( ',' )
try :
n = int ( n )
n2 = int ( n2 )
thelist = list ( thelist )
except ( ValueError , TypeError ) :
return [ thelist ]
newlists = [ ]
while thelist :
newlists . append ( thelist [ : n ] )
thelist = thelist [ n : ]
newlists . append ( thelist [ : n2 ] )
the... |
def unframe ( packet ) :
"""Strip leading DLE and trailing DLE / ETX from packet .
: param packet : TSIP packet with leading DLE and trailing DLE / ETX .
: type packet : Binary string .
: return : TSIP packet with leading DLE and trailing DLE / ETX removed .
: raise : ` ` ValueError ` ` if ` packet ` does n... | if is_framed ( packet ) :
return packet . lstrip ( CHR_DLE ) . rstrip ( CHR_ETX ) . rstrip ( CHR_DLE )
else :
raise ValueError ( 'packet does not contain leading DLE and trailing DLE/ETX' ) |
def lookup_effective_breakpoint ( cls , file_name , line_number , frame ) :
"""Checks if there is an enabled breakpoint at given file _ name and
line _ number . Check breakpoint condition if any .
: return : found , enabled and condition verified breakpoint or None
: rtype : IKPdbBreakpoint or None""" | bp = cls . breakpoints_by_file_and_line . get ( ( file_name , line_number ) , None )
if not bp :
return None
if not bp . enabled :
return None
if not bp . condition :
return bp
try :
value = eval ( bp . condition , frame . f_globals , frame . f_locals )
return bp if value else None
except :
pass... |
def save_model ( self , fname ) :
"""Save the model to a file .
The model is saved in an XGBoost internal binary format which is
universal among the various XGBoost interfaces . Auxiliary attributes of
the Python Booster object ( such as feature _ names ) will not be saved .
To preserve all attributes , pic... | if isinstance ( fname , STRING_TYPES ) : # assume file name
_check_call ( _LIB . XGBoosterSaveModel ( self . handle , c_str ( fname ) ) )
else :
raise TypeError ( "fname must be a string" ) |
def kendalltau_dist ( params1 , params2 = None ) :
r"""Compute the Kendall tau distance between two models .
This function computes the Kendall tau distance between the rankings
induced by two parameter vectors . Let : math : ` \ sigma _ i ` be the rank of item
` ` i ` ` in the model described by ` ` params1 ... | assert params2 is None or len ( params1 ) == len ( params2 )
ranks1 = rankdata ( params1 , method = "ordinal" )
if params2 is None :
ranks2 = np . arange ( 1 , len ( params1 ) + 1 , dtype = float )
else :
ranks2 = rankdata ( params2 , method = "ordinal" )
tau , _ = kendalltau ( ranks1 , ranks2 )
n_items = len (... |
def setup_docstring_style_convention ( self , text ) :
"""Handle convention changes .""" | if text == 'Custom' :
self . docstring_style_select . label . setText ( _ ( "Show the following errors:" ) )
self . docstring_style_ignore . label . setText ( _ ( "Ignore the following errors:" ) )
else :
self . docstring_style_select . label . setText ( _ ( "Show the following errors in addition " "to the ... |
def get_conf ( conf , sect , opt ) :
"""Gets a config ' opt ' from ' conf ' file , under section ' sect ' .
If no ' opt ' exists under ' sect ' , it looks for option on the default _ configs
dictionary
If there exists an environmental variable named MAMBUPY _ { upper _ case _ opt } ,
it overrides whatever t... | argu = getattr ( args , "mambupy_" + opt . lower ( ) )
if not argu :
envir = os . environ . get ( "MAMBUPY_" + opt . upper ( ) )
if not envir :
try :
return conf . get ( sect , opt )
except NoSectionError :
return default_configs [ opt ]
return envir
return argu |
def remote_daemon ( conf_file ) :
"""Run the external control daemon .
: param conf _ file : Name of the configuration file .""" | eventlet . monkey_patch ( )
conf = config . Config ( conf_file = conf_file )
daemon = remote . RemoteControlDaemon ( None , conf )
daemon . serve ( ) |
def window ( iterable , n = 2 , s = 1 ) :
r"""Move an ` n ` - item ( default 2 ) windows ` s ` steps ( default 1 ) at a time
over ` iterable ` .
Examples :
> > > list ( window ( range ( 6 ) , 2 ) )
[ ( 0 , 1 ) , ( 1 , 2 ) , ( 2 , 3 ) , ( 3 , 4 ) , ( 4 , 5 ) ]
> > > list ( window ( range ( 6 ) , 3 ) )
[ ... | assert n >= s
last = [ ]
for elt in iterable :
last . append ( elt )
if len ( last ) == n :
yield tuple ( last ) ;
last = last [ s : ] |
def load ( fp , encoding = None , cls = JSONTreeDecoder , object_hook = None , parse_float = None , parse_int = None , parse_constant = None , object_pairs_hook = None , ** kargs ) :
"""JSON load from file function that defaults the loading class to be
JSONTreeDecoder""" | return json . load ( fp , encoding , cls , object_hook , parse_float , parse_int , parse_constant , object_pairs_hook , ** kargs ) |
def log ( self , txt : str ) -> bool :
"""Log txt ( if any ) to the log file ( if any ) . Return value indicates whether it is ok to terminate on the first
error or whether we need to continue processing .
: param txt : text to log .
: return : True if we aren ' t logging , False if we are .""" | self . nerrors += 1
if self . _logfile is not None :
print ( txt , file = self . _logfile )
return not self . logging |
def delete_object ( connection , container : str , object_meta_data : dict ) -> None :
"""Delete single object from objectstore""" | connection . delete_object ( container , object_meta_data [ 'name' ] ) |
def setFormatMetadata ( self , format ) :
"""Set format image metadata to what has been reliably identified .""" | assert ( ( self . needMetadataUpdate ( CoverImageMetadata . FORMAT ) ) or ( self . format is format ) )
self . format = format
self . check_metadata &= ~ CoverImageMetadata . FORMAT |
def decompress_file ( filepath ) :
"""Decompresses a file with the correct extension . Automatically detects
gz , bz2 or z extension .
Args :
filepath ( str ) : Path to file .
compression ( str ) : A compression mode . Valid options are " gz " or
" bz2 " . Defaults to " gz " .""" | toks = filepath . split ( "." )
file_ext = toks [ - 1 ] . upper ( )
from monty . io import zopen
if file_ext in [ "BZ2" , "GZ" , "Z" ] :
with open ( "." . join ( toks [ 0 : - 1 ] ) , 'wb' ) as f_out , zopen ( filepath , 'rb' ) as f_in :
f_out . writelines ( f_in )
os . remove ( filepath ) |
def _make_request ( self , url , ** kwargs ) :
"""Make a request to an OAuth2 endpoint""" | response = requests . post ( url , ** kwargs )
try :
return response . json ( )
except ValueError :
pass
return parse_qs ( response . content ) |
def compute ( self , rtdc_ds ) :
"""Compute the feature with self . method
Parameters
rtdc _ ds : instance of RTDCBase
The dataset to compute the feature for
Returns
feature : array - or list - like
The computed data feature ( read - only ) .""" | data = self . method ( rtdc_ds )
dsize = len ( rtdc_ds ) - len ( data )
if dsize > 0 :
msg = "Growing feature {} in {} by {} to match event number!"
warnings . warn ( msg . format ( self . feature_name , rtdc_ds , abs ( dsize ) ) , BadFeatureSizeWarning )
data . resize ( len ( rtdc_ds ) , refcheck = False )... |
def switch_user ( self , username , password ) :
"""Change the client ' s username .
: param username : the username to switch to
: type username : str
: param password : the password for the username
: type password : str""" | self . _username = username
self . _password = password |
def label ( self ) :
"""" Return first child that of the column that is marked as a label""" | for c in self . table . columns :
if c . parent == self . name and 'label' in c . valuetype :
return PartitionColumn ( c , self . _partition ) |
def validate_data_columns ( self , data_columns , min_itemsize ) :
"""take the input data _ columns and min _ itemize and create a data
columns spec""" | if not len ( self . non_index_axes ) :
return [ ]
axis , axis_labels = self . non_index_axes [ 0 ]
info = self . info . get ( axis , dict ( ) )
if info . get ( 'type' ) == 'MultiIndex' and data_columns :
raise ValueError ( "cannot use a multi-index on axis [{0}] with " "data_columns {1}" . format ( axis , data_... |
def from_yaml_file ( f ) :
"""Read a yaml file and convert to Python objects ( including rpcq messages ) .""" | return from_json ( to_json ( yaml . load ( f , Loader = yaml . Loader ) ) ) |
def validate_types ( schemas_and_tables ) :
'''normalize a list of desired annotation types
if passed None returns all types , otherwise checks that types exist
Parameters
types : list [ str ] or None
Returns
list [ str ]
list of types
Raises
UnknownAnnotationTypeException
If types contains an inv... | all_types = get_types ( )
if not ( all ( sn in all_types for sn , tn in schemas_and_tables ) ) :
bad_types = [ sn for sn , tn in schemas_and_tables if sn not in all_types ]
msg = '{} are invalid types' . format ( bad_types )
raise UnknownAnnotationTypeException ( msg ) |
def export_data ( self , phases = [ ] , filename = None , filetype = 'vtp' ) :
r"""Export the pore and throat data from the given object ( s ) into the
specified file and format .
Parameters
phases : list of OpenPNM Phase Objects
The data on each supplied phase will be added to file
filename : string
Th... | project = self
network = self . network
if filename is None :
filename = project . name + '_' + time . strftime ( '%Y%b%d_%H%M%p' )
# Infer filetype from extension on file name . . . if given
if '.' in filename :
exts = [ 'vtk' , 'vtp' , 'vtu' , 'csv' , 'xmf' , 'xdmf' , 'hdf' , 'hdf5' , 'h5' , 'mat' ]
if fi... |
def get_batch_result_ids ( self , job_id , batch_id ) :
"""Get result IDs of a batch that has completed processing .
: param job _ id : job _ id as returned by ' create _ operation _ job ( . . . ) '
: param batch _ id : batch _ id as returned by ' create _ batch ( . . . ) '
: return : list of batch result IDs... | response = requests . get ( self . _get_batch_results_url ( job_id , batch_id ) , headers = self . _get_batch_info_headers ( ) )
response . raise_for_status ( )
root = ET . fromstring ( response . text )
result_ids = [ r . text for r in root . findall ( '%sresult' % self . API_NS ) ]
return result_ids |
def sample_dynamic_data ( params ) :
"""Helper function .""" | model_key = os . path . basename ( params [ 'model' ] ) . replace ( '.txt' , '' )
if 'writedir' not in params or params [ 'writedir' ] is None :
params [ 'writedir' ] = settings . writedir + model_key + '_sim'
if not os . path . exists ( params [ 'writedir' ] ) :
os . makedirs ( params [ 'writedir' ] )
readwrit... |
def safe_compile ( self , settings , sourcepath , destination ) :
"""Safe compile
It won ' t raise compile error and instead return compile success state
as a boolean with a message .
It will create needed directory structure first if it contain some
directories that does not allready exists .
Args :
se... | source_map_destination = None
if settings . SOURCE_MAP :
source_map_destination = self . change_extension ( destination , "map" )
try :
content = sass . compile ( filename = sourcepath , output_style = settings . OUTPUT_STYLES , source_comments = settings . SOURCE_COMMENTS , include_paths = settings . LIBRARY_P... |
def get_owned_games ( self , steamID , include_appinfo = 1 , include_played_free_games = 0 , appids_filter = None , format = None ) :
"""Request a list of games owned by a given steam id .
steamID : The users id
include _ appinfo : boolean .
include _ played _ free _ games : boolean .
appids _ filter : a js... | parameters = { 'steamid' : steamID , 'include_appinfo' : include_appinfo , 'include_played_free_games' : include_played_free_games }
if format is not None :
parameters [ 'format' ] = format
if appids_filter is not None :
parameters [ 'appids_filter' ] = appids_filter
url = self . create_request_url ( self . int... |
def find_one ( self , filter = None , fields = None , skip = 0 , sort = None ) :
"""Similar to find . This method will only retrieve one row .
If no row matches , returns None""" | result = self . find ( filter = filter , fields = fields , skip = skip , limit = 1 , sort = sort )
if len ( result ) > 0 :
return result [ 0 ]
else :
return None |
def configure_replace ( self , ns , definition ) :
"""Register a replace endpoint .
The definition ' s func should be a replace function , which must :
- accept kwargs for the request and path data
- return the replaced item
: param ns : the namespace
: param definition : the endpoint definition""" | @ self . add_route ( ns . instance_path , Operation . Replace , ns )
@ request ( definition . request_schema )
@ response ( definition . response_schema )
@ wraps ( definition . func )
def replace ( ** path_data ) :
headers = dict ( )
request_data = load_request_data ( definition . request_schema )
# Replac... |
def get_statistics ( self , id_or_uri , port_name = '' ) :
"""Gets the statistics from an interconnect .
Args :
id _ or _ uri : Can be either the interconnect id or the interconnect uri .
port _ name ( str ) : A specific port name of an interconnect .
Returns :
dict : The statistics for the interconnect t... | uri = self . _client . build_uri ( id_or_uri ) + "/statistics"
if port_name :
uri = uri + "/" + port_name
return self . _client . get ( uri ) |
def require_valid_type ( value , * classes ) :
"""Checks that the specified object reference is instance of classes and
throws a : py : class : ` TypeError ` if it is not .
: param value : The object .
: type value : object
: param classes : The classes .
: type classes : list ( class )""" | if value is not None :
valid = False
for auxiliar_class in classes :
if isinstance ( value , auxiliar_class ) :
valid = True
break
if not valid :
raise TypeError ( ) |
def _start_frontend ( self , restart = False ) :
"""Check if it is enabled and start the frontend http & websocket""" | self . log ( self . config , self . config . frontendenabled , lvl = verbose )
if self . config . frontendenabled and not self . frontendrunning or restart :
self . log ( "Restarting webfrontend services on" , self . frontendtarget )
self . static = Static ( "/" , docroot = self . frontendtarget ) . register ( ... |
def general_setting ( key , default = None , expected_type = None , qsettings = None ) :
"""Helper function to get a value from settings .
: param key : Unique key for setting .
: type key : basestring
: param default : The default value in case of the key is not found or there
is an error .
: type defaul... | if qsettings is None :
qsettings = QSettings ( )
try :
if isinstance ( expected_type , type ) :
return qsettings . value ( key , default , type = expected_type )
else :
return qsettings . value ( key , default )
except TypeError as e :
LOGGER . debug ( 'exception %s' % e )
LOGGER . d... |
def replace_cr_with_newline ( message : str ) :
"""TQDM and requests use carriage returns to get the training line to update for each batch
without adding more lines to the terminal output . Displaying those in a file won ' t work
correctly , so we ' ll just make sure that each batch shows up on its one line . ... | if '\r' in message :
message = message . replace ( '\r' , '' )
if not message or message [ - 1 ] != '\n' :
message += '\n'
return message |
def npm ( usr_pwd = None , clean = False ) :
"""Handle npm for Node . js""" | # see if node is installed
try :
cmd ( 'which npm' )
except :
return
print ( '-[npm]----------' )
# awk , ignore 1st line and grab 1st word
p = cmd ( "npm outdated -g | awk 'NR>1 {print $1}'" )
if not p :
return
pkgs = getPackages ( p )
for p in pkgs :
cmd ( '{} {}' . format ( 'npm update -g ' , p ) , u... |
def simulate ( self , timepoints ) :
"""Simulate initialised solver for the specified timepoints
: param timepoints : timepoints that will be returned from simulation
: return : a list of trajectories for each of the equations in the problem .""" | solver = self . _solver
last_timepoint = timepoints [ - 1 ]
try :
simulated_timepoints , simulated_values = solver . simulate ( last_timepoint , ncp_list = timepoints )
except ( Exception , self . _solver_exception_class ) as e : # The exceptions thrown by solvers are usually hiding the real cause , try to see if i... |
def ObjectRemovedEventHandler ( analysis , event ) :
"""Actions to be done when an analysis is removed from an Analysis Request""" | # If all the remaining analyses have been submitted ( or verified ) , try to
# promote the transition to the Analysis Request
# Note there is no need to check if the Analysis Request allows a given
# transition , cause this is already managed by doActionFor
analysis_request = analysis . getRequest ( )
wf . doActionFor ... |
def creation_date ( path_to_file , return_datetime = True ) :
"""Retrieve a file ' s creation date .
Try to get the date that a file was created , falling back to when it was
last modified if that isn ' t possible .
See http : / / stackoverflow . com / a / 39501288/1709587 for explanation .
: param path _ t... | if platform . system ( ) == 'Windows' :
created_at = os . path . getctime ( path_to_file )
else :
stat = os . stat ( path_to_file )
try :
created_at = stat . st_birthtime
except AttributeError : # We ' re probably on Linux . No easy way to get creation dates here ,
# so we ' ll settle for wh... |
def get_data_byte_array ( self , buffer = False ) :
"""Return a list of data for all blocks in this chunk .""" | if buffer :
length = len ( self . dataList )
return BytesIO ( pack ( ">i" , length ) + self . get_data_byte_array ( ) )
else :
return array . array ( 'B' , self . dataList ) . tostring ( ) |
def import_settings ( quiet = True ) :
"""This method takes care of importing settings from the environment , and config . py file .
Order of operations :
1 . Imports all WILL _ settings from the environment , and strips off the WILL _
2 . Imports settings from config . py
3 . Sets defaults for any missing ... | settings = { }
# Import from environment , handle environment - specific parsing .
for k , v in os . environ . items ( ) :
if k [ : 5 ] == "WILL_" :
k = k [ 5 : ]
settings [ k ] = v
if "HIPCHAT_ROOMS" in settings and type ( settings [ "HIPCHAT_ROOMS" ] ) is type ( "tes" ) :
settings [ "HIPCHAT_R... |
def user_has_access ( self , user ) :
"""Check if a user has access to view information for the account
Args :
user ( : obj : ` User ` ) : User object to check
Returns :
True if user has access to the account , else false""" | if ROLE_ADMIN in user . roles :
return True
# Non - admin users should only see active accounts
if self . enabled :
if not self . required_roles :
return True
for role in self . required_roles :
if role in user . roles :
return True
return False |
def _clean_data ( data ) :
'''Removes SaltStack params from * * kwargs''' | for key in list ( data ) :
if key . startswith ( '__pub' ) :
del data [ key ]
return data |
def start ( self , timeout = None ) :
"""Start managed ioloop thread , or do nothing if not managed .
If a timeout is passed , it will block until the the event loop is alive
( or the timeout expires ) even if the ioloop is not managed .""" | if not self . _ioloop :
raise RuntimeError ( 'Call get_ioloop() or set_ioloop() first' )
self . _ioloop . add_callback ( self . _running . set )
if self . _ioloop_managed :
self . _run_managed_ioloop ( )
else : # TODO this seems inconsistent with what the docstring describes
self . _running . set ( )
if tim... |
def _get_http_args ( self , params ) :
"""Return a copy of the http _ args
Adds auth headers and ' source _ id ' , merges in params .""" | # Add the auth headers to any other headers
headers = self . http_args . get ( 'headers' , { } )
if self . auth is not None :
auth_headers = self . auth . get_headers ( )
headers . update ( auth_headers )
# build new http args with these headers
http_args = self . http_args . copy ( )
if self . _source_id is no... |
def equality ( self , indexes = None , value = None ) :
"""Math helper method . Given a column and optional indexes will return a list of booleans on the equality of the
value for that index in the DataFrame to the value parameter .
: param indexes : list of index values or list of booleans . If a list of boole... | indexes = [ True ] * len ( self . _index ) if indexes is None else indexes
compare_list = self . get_rows ( indexes , as_list = True )
return [ x == value for x in compare_list ] |
def followingPrefix ( prefix ) :
"""Returns a String that sorts just after all Strings beginning with a prefix""" | prefixBytes = array ( 'B' , prefix )
changeIndex = len ( prefixBytes ) - 1
while ( changeIndex >= 0 and prefixBytes [ changeIndex ] == 0xff ) :
changeIndex = changeIndex - 1 ;
if ( changeIndex < 0 ) :
return None
newBytes = array ( 'B' , prefix [ 0 : changeIndex + 1 ] )
newBytes [ changeIndex ] = newBytes [ cha... |
def drop_namespaces ( self ) :
"""Drop all namespaces .""" | self . session . query ( NamespaceEntry ) . delete ( )
self . session . query ( Namespace ) . delete ( )
self . session . commit ( ) |
def iter_detector_clss ( ) :
"""Iterate over all of the detectors that are included in this sub - package .
This is a convenience method for capturing all new Detectors that are added
over time and it is used both by the unit tests and in the
` ` Scrubber . _ _ init _ _ ` ` method .""" | return iter_subclasses ( os . path . dirname ( os . path . abspath ( __file__ ) ) , Detector , _is_abstract_detector , ) |
def _reconnect ( self ) :
"""Closes the existing database connection and re - opens it .""" | self . close ( )
self . _db = psycopg2 . connect ( ** self . _db_args )
if self . _search_path :
self . execute ( 'set search_path=%s;' % self . _search_path )
if self . _timezone :
self . execute ( "set timezone='%s';" % self . _timezone ) |
def update_campaign_stop ( self , campaign_id , ** kwargs ) : # noqa : E501
"""Stop a campaign . # noqa : E501
This command will begin the process of stopping a campaign . # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass asynchronous = ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . update_campaign_stop_with_http_info ( campaign_id , ** kwargs )
# noqa : E501
else :
( data ) = self . update_campaign_stop_with_http_info ( campaign_id , ** kwargs )
# noqa : E501
return data |
def get_params_for_handler ( self , class_scope , pyfunc ) :
""": type pyfunc : rope . base . pyobjectsdef . PyFunction""" | try :
cls , signal = self . handlers [ class_scope ] [ pyfunc . get_name ( ) ]
except KeyError :
return { }
attrs = { }
idx = 0
names = pyfunc . get_param_names ( False )
if pyfunc . get_kind ( ) in ( 'method' , 'classmethod' ) :
names = names [ 1 : ]
idx += 1
if names :
attrs [ idx ] = self . get_t... |
def spread ( nodes , n ) :
"""Distrubute master instances in different nodes
"192.168.0.1 " : [ node1 , node2 ] ,
"192.168.0.2 " : [ node3 , node4 ] ,
"192.168.0.3 " : [ node5 , node6]
} = > [ node1 , node3 , node5]""" | target = [ ]
while len ( target ) < n and nodes :
for ip , node_group in list ( nodes . items ( ) ) :
if not node_group :
nodes . pop ( ip )
continue
target . append ( node_group . pop ( 0 ) )
if len ( target ) >= n :
break
return target |
def get_objects ( self , flush = False , autosnap = True , ** kwargs ) :
'''Main API method for sub - classed cubes to override for the
generation of the objects which are to ( potentially ) be added
to the cube ( assuming no duplicates )''' | logger . debug ( 'Running get_objects(flush=%s, autosnap=%s, %s)' % ( flush , autosnap , kwargs ) )
if flush :
s = time ( )
result = self . flush ( autosnap = autosnap , ** kwargs )
diff = time ( ) - s
logger . debug ( "Flush complete (%ss)" % int ( diff ) )
return result
else :
return self |
def _sigma_ee_rel ( self , gam , eps ) :
"""Eq . A1 , A4 of Baring et al . ( 1999)
Use for Ee > 2 MeV""" | A = 1 - 8 / 3 * ( gam - 1 ) ** 0.2 / ( gam + 1 ) * ( eps / gam ) ** ( 1.0 / 3.0 )
return ( self . _sigma_1 ( gam , eps ) + self . _sigma_2 ( gam , eps ) ) * A |
def exists ( self , batch_id = None ) :
"""Returns True if batch _ id exists in the history .""" | try :
self . model . objects . get ( batch_id = batch_id )
except self . model . DoesNotExist :
return False
return True |
def check_y ( y , link , dist , min_samples = 1 , verbose = True ) :
"""tool to ensure that the targets :
- are in the domain of the link function
- are numerical
- have at least min _ samples
- is finite
Parameters
y : array - like
link : Link object
dist : Distribution object
min _ samples : int... | y = np . ravel ( y )
y = check_array ( y , force_2d = False , min_samples = min_samples , ndim = 1 , name = 'y data' , verbose = verbose )
with warnings . catch_warnings ( ) :
warnings . simplefilter ( "ignore" )
if np . any ( np . isnan ( link . link ( y , dist ) ) ) :
raise ValueError ( 'y data is not... |
def get ( ctx , key ) :
'''Retrieve the value for the given key .''' | file = ctx . obj [ 'FILE' ]
stored_value = get_key ( file , key )
if stored_value :
click . echo ( '%s=%s' % ( key , stored_value ) )
else :
exit ( 1 ) |
def save ( self , inplace = True ) :
"""Saves modification to the api server .""" | data = self . _modified_data ( )
data = data [ 'permissions' ]
if bool ( data ) :
url = six . text_type ( self . href ) + self . _URL [ 'permissions' ]
extra = { 'resource' : self . __class__ . __name__ , 'query' : data }
logger . info ( 'Modifying permissions' , extra = extra )
self . _api . patch ( ur... |
def copy_attr ( self , other ) :
"""Copies all other attributes ( not methods )
from the other object to this instance .""" | if not isinstance ( other , Symbol ) :
return
# Nothing done if not a Symbol object
tmp = re . compile ( '__.*__' )
for attr in ( x for x in dir ( other ) if not tmp . match ( x ) ) :
if ( hasattr ( self . __class__ , attr ) and str ( type ( getattr ( self . __class__ , attr ) ) in ( 'property' , 'function' , '... |
def fgm ( x , logits , y = None , eps = 0.3 , ord = np . inf , clip_min = None , clip_max = None , targeted = False , sanity_checks = True ) :
"""TensorFlow implementation of the Fast Gradient Method .
: param x : the input placeholder
: param logits : output of model . get _ logits
: param y : ( optional ) A... | asserts = [ ]
# If a data range was specified , check that the input was in that range
if clip_min is not None :
asserts . append ( utils_tf . assert_greater_equal ( x , tf . cast ( clip_min , x . dtype ) ) )
if clip_max is not None :
asserts . append ( utils_tf . assert_less_equal ( x , tf . cast ( clip_max , ... |
def get_filtered_keys ( self , suffix , * args , ** kwargs ) :
"""Returns the index keys to be used by the collection for the given args
For the parameters , see BaseIndex . get _ filtered _ keys""" | args = self . prepare_args ( args , transform = False )
for index in self . _indexes :
if index . can_handle_suffix ( suffix ) :
return index . get_filtered_keys ( suffix , * args , ** kwargs ) |
def nframes ( self ) :
"""Gets the number of frames in the source file .""" | length = ctypes . c_long ( )
size = ctypes . c_int ( ctypes . sizeof ( length ) )
check ( _coreaudio . ExtAudioFileGetProperty ( self . _obj , PROP_LENGTH , ctypes . byref ( size ) , ctypes . byref ( length ) ) )
return length . value |
def set_filter_type ( self , filter_type = None ) :
"""Set ( modify ) filtering mode for better compression
` filter _ type ` is number or name of filter type for better compression
see http : / / www . w3 . org / TR / PNG / # 9Filter - types for details
It ' s also possible to use adaptive strategy for choos... | if filter_type is None :
filter_type = 0
elif isinstance ( filter_type , basestring ) :
str_ftype = str ( filter_type ) . lower ( )
filter_names = { 'none' : 0 , 'sub' : 1 , 'up' : 2 , 'average' : 3 , 'paeth' : 4 }
if str_ftype in filter_names :
filter_type = filter_names [ str_ftype ]
self . fi... |
def parse_datetime ( dt , ignoretz = True , ** kwargs ) :
""": param dt : string datetime to convert into datetime object .
: return : datetime object if the string can be parsed into a datetime .
Otherwise , return None .
: see : http : / / labix . org / python - dateutil
Examples :
> > > parse _ datetim... | try :
return parse ( dt , ignoretz = ignoretz , ** kwargs )
except :
return None |
def get_credentials ( env = None ) :
"""Gets the TextMagic credentials from current environment
: param env : environment
: return : username , token""" | environ = env or os . environ
try :
username = environ [ "TEXTMAGIC_USERNAME" ]
token = environ [ "TEXTMAGIC_AUTH_TOKEN" ]
return username , token
except KeyError :
return None , None |
def do_loop_turn ( self ) :
"""Receiver daemon main loop
: return : None""" | # Begin to clean modules
self . check_and_del_zombie_modules ( )
# Maybe the arbiter pushed a new configuration . . .
if self . watch_for_new_conf ( timeout = 0.05 ) :
logger . info ( "I got a new configuration..." )
# Manage the new configuration
self . setup_new_conf ( )
# Maybe external modules raised ' ... |
def _set_modes ( self , v , load = False ) :
"""Setter method for modes , mapped from YANG variable / rbridge _ id / ag / pg / modes ( pg - policy - types )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ modes is considered as a private
method . Backends looking to p... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = TypedListType ( allowed_type = RestrictedClassType ( base_type = unicode , restriction_dict = { 'length' : [ u'1..10' ] } ) ) , is_leaf = False , yang_name = "modes" , rest_name = "modes" , parent = self , path_helper = self ... |
def api_version ( self ) :
"""Get Pagure API version .
: return :""" | request_url = "{}/api/0/version" . format ( self . instance )
return_value = self . _call_api ( request_url )
return return_value [ 'version' ] |
def channel_to_id ( slack , channel ) :
"""Surely there ' s a better way to do this . . .""" | channels = slack . api_call ( 'channels.list' ) . get ( 'channels' ) or [ ]
groups = slack . api_call ( 'groups.list' ) . get ( 'groups' ) or [ ]
if not channels and not groups :
raise RuntimeError ( "Couldn't get channels and groups." )
ids = [ c [ 'id' ] for c in channels + groups if c [ 'name' ] == channel ]
if ... |
def format ( self , record : logging . LogRecord ) -> str :
"""Formats a record and serializes it as a JSON str . If record message isnt
already a dict , initializes a new dict and uses ` default _ msg _ fieldname `
as a key as the record msg as the value .""" | msg : Union [ str , dict ] = record . msg
if not isinstance ( record . msg , dict ) :
msg = { self . default_msg_fieldname : msg }
if record . exc_info : # type : ignore
msg [ "exc_info" ] = record . exc_info
if record . exc_text : # type : ignore
msg [ "exc_text" ] = record . exc_text
# type : ignore
retur... |
def eye ( N , M = 0 , k = 0 , dtype = None , ** kwargs ) :
"""Returns a new symbol of 2 - D shpae , filled with ones on the diagonal and zeros elsewhere .
Parameters
N : int
Number of rows in the output .
M : int , optional
Number of columns in the output . If 0 , defaults to N .
k : int , optional
In... | if dtype is None :
dtype = _numpy . float32
return _internal . _eye ( N , M , k , dtype = dtype , ** kwargs ) |
def create_metadata ( * args , ** kwargs ) : # pylint : disable = unused - argument
"""Generate the metadata to send the napp package .""" | json_filename = kwargs . get ( 'json_filename' , 'kytos.json' )
readme_filename = kwargs . get ( 'readme_filename' , 'README.rst' )
ignore_json = kwargs . get ( 'ignore_json' , False )
metadata = { }
if not ignore_json :
try :
with open ( json_filename ) as json_file :
metadata = json . load ( j... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.