signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def create_for ( line , search_result ) :
'''Create a new " for loop " line as a replacement for the original code .''' | try :
return line . format ( search_result . group ( "indented_for" ) , search_result . group ( "var" ) , search_result . group ( "start" ) , search_result . group ( "stop" ) , search_result . group ( "cond" ) )
except IndexError :
return line . format ( search_result . group ( "indented_for" ) , search_result ... |
def log_url ( self , url_data ) :
"""Write csv formatted url check info .""" | row = [ ]
if self . has_part ( "urlname" ) :
row . append ( url_data . base_url )
if self . has_part ( "parentname" ) :
row . append ( url_data . parent_url )
if self . has_part ( "baseref" ) :
row . append ( url_data . base_ref )
if self . has_part ( "result" ) :
row . append ( url_data . result )
if s... |
def _unscaled_dist ( self , X , X2 = None ) :
"""Compute the Euclidean distance between each row of X and X2 , or between
each pair of rows of X if X2 is None .""" | # X , = self . _ slice _ X ( X )
if X2 is None :
Xsq = np . sum ( np . square ( X ) , 1 )
r2 = - 2. * tdot ( X ) + ( Xsq [ : , None ] + Xsq [ None , : ] )
util . diag . view ( r2 ) [ : , ] = 0.
# force diagnoal to be zero : sometime numerically a little negative
r2 = np . clip ( r2 , 0 , np . inf )
... |
def has_methods ( * method_names ) :
"""Return a test function that , when given an object ( class or an
instance ) , returns ` ` True ` ` if that object has all of the ( regular ) methods
in ` ` method _ names ` ` . Note : this is testing for regular methods only and the
test function will correctly return `... | def test ( obj ) :
for method_name in method_names :
try :
method = getattr ( obj , method_name )
except AttributeError :
return False
else :
if not callable ( method ) :
return False
if not isinstance ( obj , type ) :
... |
def _get_delete_query ( self ) :
"""Get the query builder for a delete operation on the pivot .
: rtype : orator . orm . Builder""" | foreign = self . get_attribute ( self . __foreign_key )
query = self . new_query ( ) . where ( self . __foreign_key , foreign )
return query . where ( self . __other_key , self . get_attribute ( self . __other_key ) ) |
def make_processitem_stringlist_string ( string , condition = 'contains' , negate = False , preserve_case = False ) :
"""Create a node for ProcessItem / StringList / string
: return : A IndicatorItem represented as an Element node""" | document = 'ProcessItem'
search = 'ProcessItem/StringList/string'
content_type = 'string'
content = string
ii_node = ioc_api . make_indicatoritem_node ( condition , document , search , content_type , content , negate = negate , preserve_case = preserve_case )
return ii_node |
def write_logfile ( ) : # type : ( ) - > None
"""Write a DEBUG log file COMMAND - YYYYMMDD - HHMMSS . fffff . log .""" | command = os . path . basename ( os . path . realpath ( os . path . abspath ( sys . argv [ 0 ] ) ) )
now = datetime . datetime . now ( ) . strftime ( '%Y%m%d-%H%M%S.%f' )
filename = '{}-{}.log' . format ( command , now )
with open ( filename , 'w' ) as logfile :
if six . PY3 :
logfile . write ( _LOGFILE_STR... |
def split_demultiplexed_sampledata ( data , demultiplexed ) :
"""splits demultiplexed samples into separate entries in the global sample
datadict""" | datadicts = [ ]
samplename = dd . get_sample_name ( data )
for fastq in demultiplexed :
barcode = os . path . basename ( fastq ) . split ( "." ) [ 0 ]
datadict = copy . deepcopy ( data )
datadict = dd . set_sample_name ( datadict , samplename + "-" + barcode )
datadict = dd . set_description ( datadict ... |
def arithmetic_crossover ( random , mom , dad , args ) :
"""Return the offspring of arithmetic crossover on the candidates .
This function performs arithmetic crossover ( AX ) , which is similar to a
generalized weighted averaging of the candidate elements . The allele
of each parent is weighted by the * ax _... | ax_alpha = args . setdefault ( 'ax_alpha' , 0.5 )
ax_points = args . setdefault ( 'ax_points' , None )
crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 )
bounder = args [ '_ec' ] . bounder
children = [ ]
if random . random ( ) < crossover_rate :
bro = copy . copy ( dad )
sis = copy . copy ( mom )
... |
def get_token ( self , appname , username , password ) :
"""get the security token by connecting to TouchWorks API""" | ext_exception = TouchWorksException ( TouchWorksErrorMessages . GET_TOKEN_FAILED_ERROR )
data = { 'Username' : username , 'Password' : password }
resp = self . _http_request ( TouchWorksEndPoints . GET_TOKEN , data )
try :
logger . debug ( 'token : %s' % resp )
if not resp . text :
raise ext_exception
... |
def apply_cloud_providers_config ( overrides , defaults = None ) :
'''Apply the loaded cloud providers configuration .''' | if defaults is None :
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults . copy ( )
if overrides :
config . update ( overrides )
# Is the user still using the old format in the new configuration file ? !
for name , settings in six . iteritems ( config . copy ( ) ) :
if '.' in name :
log . warning... |
def find ( self , pattern ) :
"""Searches for a pattern in the current memory segment""" | pos = self . current_segment . data . find ( pattern )
if pos == - 1 :
return - 1
return pos + self . current_position |
def response_helper ( self , response , ** kwargs ) :
"""Response component helper that allows using a marshmallow
: class : ` Schema < marshmallow . Schema > ` in response definition .
: param dict parameter : response fields . May contain a marshmallow
Schema class or instance .""" | self . resolve_schema ( response )
if "headers" in response :
for header in response [ "headers" ] . values ( ) :
self . resolve_schema ( header )
return response |
def _setOutputNames ( self , rootname , suffix = '_drz' ) :
"""Define the default output filenames for drizzle products ,
these are based on the original rootname of the image
filename should be just 1 filename , so call this in a loop
for chip names contained inside a file .""" | # Define FITS output filenames for intermediate products
# Build names based on final DRIZZLE output name
# where ' output ' normally would have been created
# by ' process _ input ( ) '
outFinal = rootname + suffix + '.fits'
outSci = rootname + suffix + '_sci.fits'
outWeight = rootname + suffix + '_wht.fits'
outContex... |
def emit_accepted ( self ) :
"""Sends signal that the file dialog was closed properly .
Sends :
filename""" | if self . result ( ) :
filename = self . selectedFiles ( ) [ 0 ]
if os . path . isdir ( os . path . dirname ( filename ) ) :
self . dlg_accepted . emit ( filename ) |
def __roman_to_cyrillic ( self , word ) :
"""Transliterate a Russian word back into the Cyrillic alphabet .
A Russian word formerly transliterated into the Roman alphabet
in order to ease the stemming process , is transliterated back
into the Cyrillic alphabet , its original form .
: param word : The word t... | word = ( word . replace ( "i^u" , "\u044E" ) . replace ( "i^a" , "\u044F" ) . replace ( "shch" , "\u0449" ) . replace ( "kh" , "\u0445" ) . replace ( "t^s" , "\u0446" ) . replace ( "ch" , "\u0447" ) . replace ( "e`" , "\u044D" ) . replace ( "i`" , "\u0439" ) . replace ( "sh" , "\u0448" ) . replace ( "k" , "\u043A" ) . ... |
def get_grade_entry_query_session ( self ) :
"""Gets the ` ` OsidSession ` ` associated with the grade entry query service .
return : ( osid . grading . GradeEntryQuerySession ) - a
` ` GradeEntryQuerySession ` `
raise : OperationFailed - unable to complete request
raise : Unimplemented - ` ` supports _ gra... | if not self . supports_grade_entry_query ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . GradeEntryQuerySession ( runtime = self . _runtime ) |
def normalize_path_in ( self , client_file_name ) :
"""Translate a ( possibly incomplete ) file or module name received from debugging client
into an absolute file name .""" | _logger . p_debug ( "normalize_path_in(%s) with os.getcwd()=>%s" , client_file_name , os . getcwd ( ) )
# remove client CWD from file _ path
if client_file_name . startswith ( self . _CLIENT_CWD ) :
file_name = client_file_name [ len ( self . _CLIENT_CWD ) : ]
else :
file_name = client_file_name
# Try to find f... |
def write_string ( self ) :
"""Return a representation of the id map as a string . This string is
properly formatted to be written in ' / etc / subuid ' or ' / etc / subgid ' .""" | map_as_str = [ ]
for name , id_range_set in self . __map . items ( ) :
for id_range in id_range_set :
map_as_str . append ( name + ':' + str ( id_range . first ) + ':' + str ( id_range . count ) + '\n' )
# Remove trailing newline
if len ( map_as_str ) > 0 :
map_as_str [ - 1 ] = map_as_str [ - 1 ] [ : - ... |
def set ( self , item_name , item_value ) :
"""Sets the value of an option in the configuration .
: param str item _ name : The name of the option to set .
: param item _ value : The value of the option to set .""" | if self . prefix :
item_name = self . prefix + self . seperator + item_name
item_names = item_name . split ( self . seperator )
item_last = item_names . pop ( )
node = self . _storage
for item_name in item_names :
if not item_name in node :
node [ item_name ] = { }
node = node [ item_name ]
node [ i... |
def data ( self , resource_value , return_value = False ) :
"""Alias for metric _ name method
| HTTP Method | API Endpoint URI ' s |
| POST | / v2 / customMetrics / { id } | { name } / data |
Example
The weight value is optional .
. . code - block : : javascript
" value " : 1,
" weight " : 1,
* * Ke... | if return_value :
self . _request_entity = None
self . _request . add_payload ( 'returnValue' , True )
self . _request_uri = '{}/{}/data' . format ( self . _request_uri , resource_value ) |
def NDLimitExceeded_originator_switch_info_switchIpV6Address ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
NDLimitExceeded = ET . SubElement ( config , "NDLimitExceeded" , xmlns = "http://brocade.com/ns/brocade-notification-stream" )
originator_switch_info = ET . SubElement ( NDLimitExceeded , "originator-switch-info" )
switchIpV6Address = ET . SubElement ( originator_switch_info , "switch... |
def nonuniform_scale_samples ( params , bounds , dists ) :
"""Rescale samples in 0 - to - 1 range to other distributions
Arguments
problem : dict
problem definition including bounds
params : numpy . ndarray
numpy array of dimensions num _ params - by - N ,
where N is the number of samples
dists : list... | b = np . array ( bounds )
# initializing matrix for converted values
conv_params = np . zeros_like ( params )
# loop over the parameters
for i in range ( conv_params . shape [ 1 ] ) : # setting first and second arguments for distributions
b1 = b [ i ] [ 0 ]
b2 = b [ i ] [ 1 ]
if dists [ i ] == 'triang' : # ... |
def create_link_button ( self , text = "None" , uri = "None" ) :
"""Function creates a link button with corresponding text and
URI reference""" | link_btn = Gtk . LinkButton ( uri , text )
return link_btn |
def set_style ( rcdict , theme = None , grid = True , gridlines = u'-' , ticks = False , spines = True ) :
"""This code has been modified from seaborn . rcmod . set _ style ( )
: : Arguments : :
rcdict ( str ) : dict of " context " properties ( filled by set _ context ( ) )
theme ( str ) : name of theme to us... | # extract style and color info for theme
styleMap , clist = get_theme_style ( theme )
# extract style variables
figureFace = styleMap [ 'figureFace' ]
axisFace = styleMap [ 'axisFace' ]
textColor = styleMap [ 'textColor' ]
edgeColor = styleMap [ 'edgeColor' ]
gridColor = styleMap [ 'gridColor' ]
if not spines :
edg... |
def cmd_help ( * args ) :
"""Arguments : [ < command > ]
List available commands""" | if len ( args ) == 0 :
print ( "Possible commands are:" )
print ( "" )
for cmd_name in sorted ( COMMANDS . keys ( ) ) :
cmd_func = COMMANDS [ cmd_name ]
print ( "{}:" . format ( cmd_name ) )
print ( "=" * ( len ( cmd_name ) + 1 ) )
print ( " {}" . format ( cmd_func . __doc... |
def from_bytes ( cls , bitstream , prefix_len = None ) :
'''Look at the type of the message , instantiate the correct class and
let it parse the message .''' | # Convert to ConstBitStream ( if not already provided )
if not isinstance ( bitstream , ConstBitStream ) :
if isinstance ( bitstream , Bits ) :
bitstream = ConstBitStream ( auto = bitstream )
else :
bitstream = ConstBitStream ( bytes = bitstream )
# Skip the reserved bits
rsvd1 = bitstream . rea... |
def view_torrent ( self , torrent_id ) :
"""Retrieves and parses the torrent page for a given ` torrent _ id ` .
: param torrent _ id : the ID of the torrent to view
: raises TorrentNotFoundError : if the torrent does not exist
: returns : a : class : ` TorrentPage ` with a snapshot view of the torrent
deta... | params = { 'page' : 'view' , 'tid' : torrent_id , }
r = requests . get ( self . base_url , params = params )
content = self . _get_page_content ( r )
# Check if the content div has any child elements
if not len ( content ) : # The " torrent not found " text in the page has some unicode junk
# that we can safely ignore ... |
def delete_object ( request , model , post_delete_redirect , object_id = None , slug = None , slug_field = 'slug' , template_name = None , template_loader = loader , extra_context = None , login_required = False , context_processors = None , template_object_name = 'object' ) :
"""Generic object - delete function . ... | if extra_context is None :
extra_context = { }
if login_required and not request . user . is_authenticated :
return redirect_to_login ( request . path )
obj = lookup_object ( model , object_id , slug , slug_field )
if request . method == 'POST' :
obj . delete ( )
msg = ugettext ( "The %(verbose_name)s w... |
def stylize ( ax , name , feature ) :
'''Stylization modifications to the plots''' | ax . set_ylabel ( feature )
ax . set_title ( name , fontsize = 'small' ) |
def get_subs_dict ( self , qnodes = None ) :
"""Return substitution dict for replacements into the template
Subclasses may want to customize this method .""" | # d = self . qparams . copy ( )
d = self . qparams
d . update ( self . optimize_params ( qnodes = qnodes ) )
# clean null values
subs_dict = { k : v for k , v in d . items ( ) if v is not None }
# print ( " subs _ dict : " , subs _ dict )
return subs_dict |
async def umount ( self ) :
"""Unmount this partition .""" | self . _data = await self . _handler . unmount ( system_id = self . block_device . node . system_id , device_id = self . block_device . id , id = self . id ) |
def remove_node ( self , node ) :
"""Removes a node and its attributes from the hypergraph . Removes
every hyperedge that contains this node .
: param node : reference to the node being added .
: raises : ValueError - - No such node exists .
Examples :
> > > H = UndirectedHypergraph ( )
> > > H . add _ ... | if not self . has_node ( node ) :
raise ValueError ( "No such node exists." )
# Loop over every hyperedge in the star of the node ;
# i . e . , over every hyperedge that contains the node
for hyperedge_id in self . _star [ node ] :
frozen_nodes = self . _hyperedge_attributes [ hyperedge_id ] [ "__frozen_nodes" ... |
def golden_search ( f , a , b , xatol = 1e-6 , ftol = 1e-8 , expand_bounds = False ) :
"""Find minimum of a function on interval [ a , b ]
using golden section search .
If expand _ bounds = True , expand the interval so that the function is
first evaluated at x = a and x = b .""" | ratio = 2 / ( 1 + math . sqrt ( 5 ) )
if not expand_bounds :
x0 = a
x3 = b
else :
x0 = ( ratio * a - ( 1 - ratio ) * b ) / ( 2 * ratio - 1 )
x3 = ( ratio * b - ( 1 - ratio ) * a ) / ( 2 * ratio - 1 )
x1 = ratio * x0 + ( 1 - ratio ) * x3
x2 = ( 1 - ratio ) * x0 + ratio * x3
f1 = f ( x1 )
f2 = f ( x2 )
f0... |
def get_sam_name ( username ) :
r'''Gets the SAM name for a user . It basically prefixes a username without a
backslash with the computer name . If the user does not exist , a SAM
compatible name will be returned using the local hostname as the domain .
i . e . salt . utils . get _ same _ name ( ' Administrat... | try :
sid_obj = win32security . LookupAccountName ( None , username ) [ 0 ]
except pywintypes . error :
return '\\' . join ( [ platform . node ( ) [ : 15 ] . upper ( ) , username ] )
username , domain , _ = win32security . LookupAccountSid ( None , sid_obj )
return '\\' . join ( [ domain , username ] ) |
def get_data ( self ) :
"""Saves the handler ' s data for : func : ` . reloader . do _ reload `""" | data = { }
data [ 'guarded' ] = self . guarded [ : ]
data [ 'voiced' ] = copy . deepcopy ( self . voiced )
data [ 'opers' ] = copy . deepcopy ( self . opers )
data [ 'features' ] = self . features . copy ( )
data [ 'uptime' ] = self . uptime . copy ( )
data [ 'abuselist' ] = self . abuselist . copy ( )
data [ 'who_map'... |
def run_linter ( self , linter ) -> None :
"""Run a checker class""" | self . current = linter . name
if ( linter . name not in self . parser [ "all" ] . as_list ( "linters" ) or linter . base_pyversion > sys . version_info ) : # noqa : W503
return
if any ( x not in self . installed for x in linter . requires_install ) :
raise ModuleNotInstalled ( linter . requires_install )
linte... |
def p_expression_lor ( self , p ) :
'expression : expression LOR expression' | p [ 0 ] = Lor ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def remove_points_from_interval ( self , start , end ) :
"""Allow removal of all points from the time series within a interval
[ start : end ] .""" | for s , e , v in self . iterperiods ( start , end ) :
try :
del self . _d [ s ]
except KeyError :
pass |
def _get_stream_parameters ( kind , device , channels , dtype , latency , samplerate ) :
"""Generate PaStreamParameters struct .""" | if device is None :
if kind == 'input' :
device = _pa . Pa_GetDefaultInputDevice ( )
elif kind == 'output' :
device = _pa . Pa_GetDefaultOutputDevice ( )
info = device_info ( device )
if channels is None :
channels = info [ 'max_' + kind + '_channels' ]
dtype = np . dtype ( dtype )
try :
... |
def route ( app_or_blueprint , rule , ** options ) :
"""An alternative to : meth : ` flask . Flask . route ` or : meth : ` flask . Blueprint . route ` that
always adds the ` ` POST ` ` method to the allowed endpoint request methods .
You should use this for all your view functions that would need to use Sijax .... | def decorator ( f ) :
methods = options . pop ( 'methods' , ( 'GET' , 'POST' ) )
if 'POST' not in methods :
methods = tuple ( methods ) + ( 'POST' , )
options [ 'methods' ] = methods
app_or_blueprint . add_url_rule ( rule , None , f , ** options )
return f
return decorator |
def on ( self , event , handler = None ) :
"""Create , add or update an event with a handler or more attached .""" | if isinstance ( event , str ) and ' ' in event : # event is list str - based
self . on ( event . split ( ' ' ) , handler )
elif isinstance ( event , list ) : # many events contains same handler
for each in event :
self . on ( each , handler )
elif isinstance ( event , dict ) : # event is a dict of < eve... |
def read_element_using_argtuple ( self , argtuple ) :
"""takes a tuple of keys
returns node found in cfg _ dict
found by traversing cfg _ dict by successive
application of keys from element _ path""" | # doesn ' t support DELIMITED , only dict - based formats
if self . format == FMT_DELIMITED :
return None
node = self . cfg_dict
for key in argtuple :
node = node [ key ]
return node |
def queued ( values , qsize ) :
"""Queues up readings from * values * ( the number of readings queued is
determined by * qsize * ) and begins yielding values only when the queue is
full . For example , to " cascade " values along a sequence of LEDs : :
from gpiozero import LEDBoard , Button
from gpiozero . ... | values = [ _normalize ( v ) for v in values ]
if qsize < 1 :
raise ValueError ( "qsize must be 1 or larger" )
q = [ ]
it = iter ( values )
try :
for i in range ( qsize ) :
q . append ( next ( it ) )
for i in cycle ( range ( qsize ) ) :
yield q [ i ]
q [ i ] = next ( it )
except StopI... |
def harvest_collection ( community_name ) :
"""Harvest a Zenodo community ' s record metadata .
Examples
You can harvest record metadata for a Zenodo community via its identifier
name . For example , the identifier for LSST Data Management ' s Zenodo
collection is ` ` ' lsst - dm ' ` ` :
> > > import zeno... | url = zenodo_harvest_url ( community_name )
r = requests . get ( url )
r . status_code
xml_content = r . content
return Datacite3Collection . from_collection_xml ( xml_content ) |
def fit ( self , X , y , ** fit_params ) :
"""See ` ` NeuralNet . fit ` ` .
In contrast to ` ` NeuralNet . fit ` ` , ` ` y ` ` is non - optional to
avoid mistakenly forgetting about ` ` y ` ` . However , ` ` y ` ` can be
set to ` ` None ` ` in case it is derived dynamically from""" | # pylint : disable = useless - super - delegation
# this is actually a pylint bug :
# https : / / github . com / PyCQA / pylint / issues / 1085
return super ( ) . fit ( X , y , ** fit_params ) |
def _from_any ( any_pb ) :
"""Convert an ` ` Any ` ` protobuf into the actual class .
Uses the type URL to do the conversion .
. . note : :
This assumes that the type URL is already registered .
: type any _ pb : : class : ` google . protobuf . any _ pb2 . Any `
: param any _ pb : An any object to be conv... | klass = _TYPE_URL_MAP [ any_pb . type_url ]
return klass . FromString ( any_pb . value ) |
def trigger_event ( self , event , client , args , force_dispatch = False ) :
"""Trigger a new event that will be dispatched to all modules .""" | self . controller . process_event ( event , client , args , force_dispatch = force_dispatch ) |
def module2uri ( self , module_name ) :
"""Convert an encoded module name to an unencoded source uri""" | encoded_str = super ( EncodedModuleLoader , self ) . module2uri ( module_name )
encoded = encoded_str . encode ( 'ASCII' )
compressed = base64 . b64decode ( encoded , b'+&' )
return zlib . decompress ( compressed ) |
def graph_draw ( self , mode ) :
"""Draws grid graph using networkx
This method is for debugging purposes only .
Use ding0 . tools . plots . plot _ mv _ topology ( ) for advanced plotting .
Parameters
mode : str
Mode selection ' MV ' or ' LV ' .
Notes
The geo coords ( for used crs see database import ... | g = self . _graph
if mode == 'MV' : # get draw params from nodes and edges ( coordinates , colors , demands , etc . )
nodes_pos = { } ;
demands = { } ;
demands_pos = { }
nodes_color = [ ]
for node in g . nodes ( ) :
if isinstance ( node , ( StationDing0 , LVLoadAreaCentreDing0 , CableDistrib... |
def disable_beacons ( self ) :
'''Enable beacons''' | self . opts [ 'beacons' ] [ 'enabled' ] = False
# Fire the complete event back along with updated list of beacons
evt = salt . utils . event . get_event ( 'minion' , opts = self . opts )
evt . fire_event ( { 'complete' : True , 'beacons' : self . opts [ 'beacons' ] } , tag = '/salt/minion/minion_beacons_disabled_comple... |
def overlay_gateway_site_extend_vlan_add ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
overlay_gateway = ET . SubElement ( config , "overlay-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" )
name_key = ET . SubElement ( overlay_gateway , "name" )
name_key . text = kwargs . pop ( 'name' )
site = ET . SubElement ( overlay_gateway , "site" )
name_key = ET . SubEl... |
def __or ( funcs , args ) :
"""Support list sugar for " or " of two predicates . Used inside ` select ` .""" | results = [ ]
for f in funcs :
result = f ( args )
if result :
results . extend ( result )
return results |
def get_histogram ( data ) :
"""Return the histogram relative to the given data
Assume that the data are already sorted""" | count = len ( data )
if count < 2 :
raise StatisticsError ( 'Too few data points ({}) for get_histogram' . format ( count ) )
min_ = data [ 0 ]
max_ = data [ - 1 ]
std = stdev ( data )
bins = get_histogram_bins ( min_ , max_ , std , count )
res = { x : 0 for x in bins }
for value in data :
for bin_ in bins :
... |
def rpc_message_to_error ( rpc_error , request ) :
"""Converts a Telegram ' s RPC Error to a Python error .
: param rpc _ error : the RpcError instance .
: param request : the request that caused this error .
: return : the RPCError as a Python exception that represents this error .""" | # Try to get the error by direct look - up , otherwise regex
cls = rpc_errors_dict . get ( rpc_error . error_message , None )
if cls :
return cls ( request )
for msg_regex , cls in rpc_errors_re :
m = re . match ( msg_regex , rpc_error . error_message )
if m :
capture = int ( m . group ( 1 ) ) if m ... |
def switch_to_external_wf ( self ) :
"""External workflow switcher .
This method copies main workflow information into
a temporary dict ` main _ wf ` and makes external workflow
acting as main workflow .""" | # External WF name should be stated at main wf diagram and type should be service task .
if ( self . current . task_type == 'ServiceTask' and self . current . task . task_spec . type == 'external' ) :
log . debug ( "Entering to EXTERNAL WF" )
# Main wf information is copied to main _ wf .
main_wf = self . w... |
def ensure_dir_exists ( directory ) :
"Creates local directories if they don ' t exist ." | if directory . startswith ( 'gs://' ) :
return
if not os . path . exists ( directory ) :
dbg ( "Making dir {}" . format ( directory ) )
os . makedirs ( directory , exist_ok = True ) |
def adjustReplicas ( self , old_required_number_of_instances : int , new_required_number_of_instances : int ) :
"""Add or remove replicas depending on ` f `""" | # TODO : refactor this
replica_num = old_required_number_of_instances
while replica_num < new_required_number_of_instances :
self . replicas . add_replica ( replica_num )
self . processStashedMsgsForReplica ( replica_num )
replica_num += 1
while replica_num > new_required_number_of_instances :
replica_n... |
def get_args ( self , state , all_params , remainder , argspec , im_self ) :
'''Determines the arguments for a controller based upon parameters
passed the argument specification for the controller .''' | args = [ ]
varargs = [ ]
kwargs = dict ( )
valid_args = argspec . args [ : ]
if ismethod ( state . controller ) or im_self :
valid_args . pop ( 0 )
# pop off ` self `
pecan_state = state . request . pecan
remainder = [ x for x in remainder if x ]
if im_self is not None :
args . append ( im_self )
# grab the... |
def _cmd_line_parser ( ) :
'''return a command line parser . It is used when generating the documentation''' | parser = argparse . ArgumentParser ( )
parser . add_argument ( '--path' , help = ( 'path to test files, ' 'if not provided the script folder is used' ) )
parser . add_argument ( '--text_output' , action = 'store_true' , help = 'option to save the results to text file' )
parser . add_argument ( '--format' , default = 'r... |
def validate_key ( request , group = None , perm = None , keytype = None ) :
"""Validate the given key""" | def update_last_access ( ) :
if KEY_LAST_USED_UPDATE :
request . key . save ( )
if request . user . is_authenticated ( ) and is_valid_consumer ( request ) :
if not group and not perm and not keytype :
return update_last_access ( )
elif keytype :
if request . key . is_type ( keytype )... |
async def _watch ( self ) :
"""Start the watching loop .""" | file_name = os . path . basename ( self . _file_path )
logger . info ( 'Watching %s "%s"' , self . THING , self . _file_path , )
while self . _running :
evt = await self . _watcher . get_event ( )
if evt . name == file_name :
await self . _load ( )
logger . info ( 'Reloading changed %s from "%s"... |
async def connect ( self ) :
"""Connects to Telegram .""" | await self . _sender . connect ( self . _connection ( self . session . server_address , self . session . port , self . session . dc_id , loop = self . _loop , loggers = self . _log , proxy = self . _proxy ) )
self . session . auth_key = self . _sender . auth_key
self . session . save ( )
await self . _sender . send ( s... |
def parse_dsn ( dsn_string ) :
"""Parse a connection string and return the associated driver""" | dsn = urlparse ( dsn_string )
scheme = dsn . scheme . split ( '+' ) [ 0 ]
username = password = host = port = None
host = dsn . netloc
if '@' in host :
username , host = host . split ( '@' )
if ':' in username :
username , password = username . split ( ':' )
password = unquote ( password )
u... |
def save_to ( self , nameprefix , switch = False ) :
"""saves logger data to a different set of files , for
` ` switch = True ` ` also the loggers name prefix is switched to
the new value""" | if not nameprefix or not isinstance ( nameprefix , basestring ) :
raise _Error ( 'filename prefix must be a nonempty string' )
if nameprefix == self . default_prefix :
raise _Error ( 'cannot save to default name "' + nameprefix + '...", chose another name' )
if nameprefix == self . name_prefix :
return
for ... |
def list_directory ( self , * args , ** kwargs ) :
""": meth : ` . WNetworkClientProto . list _ directory ` method implementation""" | return tuple ( self . dav_client ( ) . list ( self . session_path ( ) ) ) |
def _get_file_event_handler ( self , file_path , save_name ) :
"""Get or create an event handler for a particular file .
file _ path : the file ' s actual path
save _ name : its path relative to the run directory ( aka the watch directory )""" | self . _file_pusher . update_file ( save_name , file_path )
# track upload progress
if save_name not in self . _file_event_handlers :
if save_name == 'wandb-history.jsonl' :
self . _file_event_handlers [ 'wandb-history.jsonl' ] = FileEventHandlerTextStream ( file_path , 'wandb-history.jsonl' , self . _api )... |
def list_staged_files ( self ) -> typing . List [ str ] :
""": return : staged files
: rtype : list of str""" | staged_files : typing . List [ str ] = [ x . a_path for x in self . repo . index . diff ( 'HEAD' ) ]
LOGGER . debug ( 'staged files: %s' , staged_files )
return staged_files |
def _generic_summary ( arg , exact_nunique = False , prefix = None ) :
"""Compute a set of summary metrics from the input value expression
Parameters
arg : value expression
exact _ nunique : boolean , default False
Compute the exact number of distinct values ( slower )
prefix : string , default None
Str... | metrics = [ arg . count ( ) , arg . isnull ( ) . sum ( ) . name ( 'nulls' ) ]
if exact_nunique :
unique_metric = arg . nunique ( ) . name ( 'uniques' )
else :
unique_metric = arg . approx_nunique ( ) . name ( 'uniques' )
metrics . append ( unique_metric )
return _wrap_summary_metrics ( metrics , prefix ) |
def video_get_size ( self , num = 0 ) :
"""Get the video size in pixels as 2 - tuple ( width , height ) .
@ param num : video number ( default 0 ) .""" | r = libvlc_video_get_size ( self , num )
if isinstance ( r , tuple ) and len ( r ) == 2 :
return r
else :
raise VLCException ( 'invalid video number (%s)' % ( num , ) ) |
def kube_pod_status_phase ( self , metric , scraper_config ) :
"""Phase a pod is in .""" | metric_name = scraper_config [ 'namespace' ] + '.pod.status_phase'
status_phase_counter = Counter ( )
for sample in metric . samples : # Counts aggregated cluster - wide to avoid no - data issues on pod churn ,
# pod granularity available in the service checks
tags = [ self . _label_to_tag ( 'namespace' , sample [ ... |
def get_model ( self ) :
"""Get a model if the formula was previously satisfied .""" | if self . lingeling and self . status == True :
model = pysolvers . lingeling_model ( self . lingeling )
return model if model != None else [ ] |
def _hexplot ( matrix , fig , colormap ) :
"""Internal function to plot a hexagonal map .""" | umatrix_min = matrix . min ( )
umatrix_max = matrix . max ( )
n_rows , n_columns = matrix . shape
cmap = plt . get_cmap ( colormap )
offsets = np . zeros ( ( n_columns * n_rows , 2 ) )
facecolors = [ ]
for row in range ( n_rows ) :
for col in range ( n_columns ) :
if row % 2 == 0 :
offsets [ row... |
def _iflat_tasks_wti ( self , status = None , op = "==" , nids = None , with_wti = True ) :
"""Generators that produces a flat sequence of task .
if status is not None , only the tasks with the specified status are selected .
nids is an optional list of node identifiers used to filter the tasks .
Returns :
... | nids = as_set ( nids )
if status is None :
for wi , work in enumerate ( self ) :
for ti , task in enumerate ( work ) :
if nids and task . node_id not in nids :
continue
if with_wti :
yield task , wi , ti
else :
yield task
el... |
def _call_marginalizevperp ( self , o , integrate_method = 'dopr54_c' , ** kwargs ) :
"""Call the DF , marginalizing over perpendicular velocity""" | # Get d , l , vlos
l = o . ll ( obs = [ 1. , 0. , 0. ] , ro = 1. ) * _DEGTORAD
vlos = o . vlos ( ro = 1. , vo = 1. , obs = [ 1. , 0. , 0. , 0. , 0. , 0. ] )
R = o . R ( use_physical = False )
phi = o . phi ( use_physical = False )
# Get local circular velocity , projected onto the los
if isinstance ( self . _pot , list... |
def _data ( self ) :
"""Cached data built from instance raw _ values as a dictionary .""" | d = { }
# Iterate all keys and values
for k , v in self . _row_values . items ( ) : # Split related model fields
attrs = k . rsplit ( '__' , 1 )
# Set value depending case
if len ( attrs ) == 2 : # Related model field , store nested
fk , fn = attrs
if fk not in d :
d [ fk ] = { }... |
def model ( self , * args , ** kwargs ) : # type : ( * Any , * * Any ) - > Part
"""Retrieve single KE - chain part model .
Uses the same interface as the : func : ` part ` method but returns only a single pykechain
: class : ` models . Part ` instance of category ` MODEL ` .
If additional ` keyword = value ` ... | kwargs [ 'category' ] = Category . MODEL
_parts = self . parts ( * args , ** kwargs )
if len ( _parts ) == 0 :
raise NotFoundError ( "No model fits criteria" )
if len ( _parts ) != 1 :
raise MultipleFoundError ( "Multiple models fit criteria" )
return _parts [ 0 ] |
def write_dag ( self , out = sys . stdout ) :
"""Write info for all GO Terms in obo file , sorted numerically .""" | for rec in sorted ( self . values ( ) ) :
print ( rec , file = out ) |
def assets2s3 ( ) :
"""Upload assets files to S3""" | import flask_s3
header ( "Assets2S3..." )
print ( "" )
print ( "Building assets files..." )
print ( "" )
build_assets ( application . app )
print ( "" )
print ( "Uploading assets files to S3 ..." )
flask_s3 . create_all ( application . app )
print ( "" ) |
def kernels ( gandi , vm , datacenter , flavor , match ) :
"""List available kernels .""" | if vm :
vm = gandi . iaas . info ( vm )
dc_list = gandi . datacenter . filtered_list ( datacenter , vm )
for num , dc in enumerate ( dc_list ) :
if num :
gandi . echo ( '\n' )
output_datacenter ( gandi , dc , [ 'dc_name' ] )
kmap = gandi . kernel . list ( dc [ 'id' ] , flavor , match )
for _... |
def cell_has_code ( lines ) :
"""Is there any code in this cell ?""" | for i , line in enumerate ( lines ) :
stripped_line = line . strip ( )
if stripped_line . startswith ( '#' ) :
continue
# Two consecutive blank lines ?
if not stripped_line :
if i > 0 and not lines [ i - 1 ] . strip ( ) :
return False
continue
return True
return F... |
def RegisterMessageHandler ( self , handler , lease_time , limit = 1000 ) :
"""Leases a number of message handler requests up to the indicated limit .""" | self . UnregisterMessageHandler ( )
self . handler_stop = False
self . handler_thread = threading . Thread ( name = "message_handler" , target = self . _MessageHandlerLoop , args = ( handler , lease_time , limit ) )
self . handler_thread . daemon = True
self . handler_thread . start ( ) |
def restart_on_change_helper ( lambda_f , restart_map , stopstart = False , restart_functions = None ) :
"""Helper function to perform the restart _ on _ change function .
This is provided for decorators to restart services if files described
in the restart _ map have changed after an invocation of lambda _ f (... | if restart_functions is None :
restart_functions = { }
checksums = { path : path_hash ( path ) for path in restart_map }
r = lambda_f ( )
# create a list of lists of the services to restart
restarts = [ restart_map [ path ] for path in restart_map if path_hash ( path ) != checksums [ path ] ]
# create a flat list o... |
def verify ( self , otp , for_time = None , valid_window = 0 ) :
"""Verifies the OTP passed in against the current time OTP
@ param [ String / Integer ] otp the OTP to check against
@ param [ Integer ] valid _ window extends the validity to this many counter ticks before and after the current one""" | if for_time is None :
for_time = datetime . datetime . now ( )
if valid_window :
for i in range ( - valid_window , valid_window + 1 ) :
if utils . strings_equal ( str ( otp ) , str ( self . at ( for_time , i ) ) ) :
return True
return False
return utils . strings_equal ( str ( otp ) , st... |
def get_service_list ( self ) -> list :
"""Get a list of docker services .
Only the manager nodes can retrieve all the services
Returns :
list , all the ids of the services in swarm""" | # Initialising empty list
services = [ ]
# Raise an exception if we are not a manager
if not self . _manager :
raise RuntimeError ( 'Only the Swarm manager node can retrieve' ' all the services.' )
service_list = self . _client . services . list ( )
for s_list in service_list :
services . append ( s_list . shor... |
def create_figures ( n , * fig_args , ** fig_kwargs ) :
'''Create multiple figures .
Args and Kwargs are passed to ` matplotlib . figure . Figure ` .
This routine is provided in order to avoid usage of pyplot which
is stateful and not thread safe . As drawing routines in tf - matplotlib
are called from py -... | return [ create_figure ( * fig_args , ** fig_kwargs ) for _ in range ( n ) ] |
def push ( self , x ) :
"""append items to the stack ; input can be a single value or a list""" | if isinstance ( x , list ) :
for item in x :
self . stack . append ( item )
else :
self . stack . append ( x ) |
def DocbookSlidesPdf ( env , target , source = None , * args , ** kw ) :
"""A pseudo - Builder , providing a Docbook toolchain for PDF slides output .""" | # Init list of targets / sources
target , source = __extend_targets_sources ( target , source )
# Init XSL stylesheet
__init_xsl_stylesheet ( kw , env , '$DOCBOOK_DEFAULT_XSL_SLIDESPDF' , [ 'slides' , 'fo' , 'plain.xsl' ] )
# Setup builder
__builder = __select_builder ( __lxml_builder , __libxml2_builder , __xsltproc_b... |
def listen ( self ) :
"""Instructs handler to listen to Django request and handle
CategoryList editor requests ( if any ) .
: return : None on success otherwise and exception from SitecatsException family is raised .""" | requested_action = self . _request . POST . get ( 'category_action' , False )
if not requested_action :
return None
# No action supplied . Pass .
if requested_action not in self . KNOWN_ACTIONS :
raise SitecatsSecurityException ( 'Unknown `category_action` - `%s` - requested.' )
category_base_id = self . _reque... |
def findlinestarts ( code , dup_lines = False ) :
"""Find the offsets in a byte code which are start of lines in the source .
Generate pairs ( offset , lineno ) as described in Python / compile . c .""" | if PYTHON3 :
byte_increments = code . co_lnotab [ 0 : : 2 ]
line_increments = code . co_lnotab [ 1 : : 2 ]
else :
byte_increments = [ ord ( c ) for c in code . co_lnotab [ 0 : : 2 ] ]
line_increments = [ ord ( c ) for c in code . co_lnotab [ 1 : : 2 ] ]
lastlineno = None
lineno = code . co_firstlineno
a... |
def roundvals ( self , col : str , precision : int = 2 ) :
"""Round floats in a column . Numbers are going to be
converted to floats if they are not already
: param col : column name
: type col : str
: param precision : float precision , defaults to 2
: param precision : int , optional
: example : ` ` d... | try :
self . df [ col ] = self . df [ col ] . astype ( "float64" )
self . df [ col ] = self . df [ col ] . apply ( lambda x : round ( x , precision ) )
except Exception as e :
self . err ( e , "Can not round column values" )
return
self . ok ( "Rounded values in column " + col ) |
def initialize ( template , service_name , environment = 'dev' ) :
"""Adds SERVICE _ NAME , SERVICE _ ENVIRONMENT , and DEFAULT _ TAGS to the template
: param template :
: param service _ name :
: param environment :
: return :""" | template . SERVICE_NAME = os . getenv ( 'SERVICE_NAME' , service_name )
template . SERVICE_ENVIRONMENT = os . getenv ( 'ENV' , environment ) . lower ( )
template . DEFAULT_TAGS = troposphere . Tags ( ** { 'service-name' : template . SERVICE_NAME , 'environment' : template . SERVICE_ENVIRONMENT } )
template . add_versio... |
def setAutoRangeOff ( self ) :
"""Turns off the auto range checkbox .
Calls _ refreshNodeFromTarget , not _ updateTargetFromNode , because setting auto range off
does not require a redraw of the target .""" | # TODO : catch exceptions . How ?
# / argos / hdf - eos / DeepBlue - SeaWiFS - 1.0 _ L3_20100101 _ v002-20110527T191319Z . h5 / aerosol _ optical _ thickness _ stddev _ ocean
if self . getRefreshBlocked ( ) :
logger . debug ( "setAutoRangeOff blocked for {}" . format ( self . nodeName ) )
return
if self . autoR... |
def add_error ( self , error , critical = False ) :
"""Adds an error to the state .
Args :
error : The text that will be added to the error list .
critical : If set to True and the error is checked with check _ errors , will
dfTimewolf will abort .""" | self . errors . append ( ( error , critical ) ) |
def go_to_line ( self , line ) :
"""Moves the text cursor to given line .
: param line : Line to go to .
: type line : int
: return : Method success .
: rtype : bool""" | cursor = self . textCursor ( )
cursor . setPosition ( self . document ( ) . findBlockByNumber ( line - 1 ) . position ( ) )
self . setTextCursor ( cursor )
return True |
def read_args ( ** kwargs ) :
"""Read controlfile parameter .""" | if kwargs . get ( "control" ) :
args = Namespace ( control = kwargs [ "control" ] )
elif config . CONTROLFILE :
args = Namespace ( control = config . CONTROLFILE )
elif config . DB . get ( "control_table_name" ) :
args = Namespace ( control = "sql" )
elif config . AWS . get ( "control_table_name" ) :
ar... |
def infer_ast_from_something ( self , obj , context = None ) :
"""infer astroid for the given class""" | if hasattr ( obj , "__class__" ) and not isinstance ( obj , type ) :
klass = obj . __class__
else :
klass = obj
try :
modname = klass . __module__
except AttributeError as exc :
raise exceptions . AstroidBuildingError ( "Unable to get module for {class_repr}." , cls = klass , class_repr = safe_repr ( kl... |
def read_uic_tag ( fh , tagid , planecount , offset ) :
"""Read a single UIC tag value from file and return tag name and value .
UIC1Tags use an offset .""" | def read_int ( count = 1 ) :
value = struct . unpack ( '<%iI' % count , fh . read ( 4 * count ) )
return value [ 0 ] if count == 1 else value
try :
name , dtype = TIFF . UIC_TAGS [ tagid ]
except IndexError : # unknown tag
return '_TagId%i' % tagid , read_int ( )
Fraction = TIFF . UIC_TAGS [ 4 ] [ 1 ]
i... |
def handle_program_options ( ) :
"""Parses the given options passed in at the command line .""" | parser = argparse . ArgumentParser ( description = "Calculate the alpha diversity\
of a set of samples using one or more \
metrics and output a kernal density \
estimator-smoothed histogram of the \
... |
def update_dispute ( self , idempotency_key = None , ** params ) :
"""Return a deferred .""" | url = self . instance_url ( ) + '/dispute'
headers = populate_headers ( idempotency_key )
d = self . request ( 'post' , url , params , headers )
d . addCallback ( lambda response : self . refresh_from ( { 'dispute' : response } , api_key , True ) )
return d . addCallback ( lambda _ : self . dispute ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.