signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def auth ( self , auth_method , key ) :
"""Sets authentication info for current tag""" | self . method = auth_method
self . key = key
if self . debug :
print ( "Changing used auth key to " + str ( key ) + " using method " + ( "A" if auth_method == self . rfid . auth_a else "B" ) ) |
def can_group_commands ( command , next_command ) :
"""Returns a boolean representing whether these commands can be
grouped together or not .
A few things are taken into account for this decision :
For ` ` set ` ` commands :
- Are all arguments other than the key / value the same ?
For ` ` delete ` ` and ... | multi_capable_commands = ( 'get' , 'set' , 'delete' )
if next_command is None :
return False
name = command . get_name ( )
# TODO : support multi commands
if name not in multi_capable_commands :
return False
if name != next_command . get_name ( ) :
return False
# if the shared args ( key , or key / value ) ... |
def remove_first_pyinstrument_frame_processor ( frame , options ) :
'''The first frame when using the command line is always the _ _ main _ _ function . I want to remove
that from the output .''' | if frame is None :
return None
if 'pyinstrument' in frame . file_path and len ( frame . children ) == 1 :
frame = frame . children [ 0 ]
frame . remove_from_parent ( )
return frame
return frame |
def stepfiles_iterator ( path_prefix , wait_minutes = 0 , min_steps = 0 , path_suffix = ".index" , sleep_sec = 10 ) :
"""Continuously yield new files with steps in filename as they appear .
This is useful for checkpoint files or other files whose names differ just in
an integer marking the number of steps and m... | # Wildcard D * - [ 0-9 ] * does not match D / x - 1 , so if D is a directory let
# path _ prefix = " D / " .
if not path_prefix . endswith ( os . sep ) and os . path . isdir ( path_prefix ) :
path_prefix += os . sep
stepfiles = _read_stepfiles_list ( path_prefix , path_suffix , min_steps )
tf . logging . info ( "Fo... |
def get_unspents ( address , blockchain_client ) :
"""Get the spendable transaction outputs , also known as UTXOs or
unspent transaction outputs .
NOTE : this will only return unspents if the address provided is present
in the bitcoind server . Use the chain , blockchain , or blockcypher API
to grab the uns... | if isinstance ( blockchain_client , BitcoindClient ) :
bitcoind = blockchain_client . bitcoind
version_byte = blockchain_client . version_byte
elif isinstance ( blockchain_client , AuthServiceProxy ) :
bitcoind = blockchain_client
version_byte = 0
else :
raise Exception ( 'A BitcoindClient object is... |
def _rm_get_repeat_coords_from_header ( parts ) :
"""extract the repeat coordinates of a repeat masker match from a header line .
An example header line is : :
239 29.42 1.92 0.97 chr1 11 17 ( 41 ) C XX # YY ( 74 ) 104 1 m _ b1s502i1 4
239 29.42 1.92 0.97 chr1 11 17 ( 41 ) XX # YY 1 104 ( 74 ) m _ b1s502i1 4 ... | assert ( ( parts [ 8 ] == "C" and len ( parts ) == 15 ) or ( len ( parts ) == 14 ) )
if len ( parts ) == 14 :
s = int ( parts [ 9 ] )
e = int ( parts [ 10 ] ) + 1
else :
s = int ( parts [ 12 ] )
e = int ( parts [ 11 ] ) + 1
if ( s >= e ) :
raise AlignmentIteratorError ( "invalid repeatmakser header:... |
def count_results ( cube , q ) :
"""Get the count of records matching the query .""" | q = select ( columns = [ func . count ( True ) ] , from_obj = q . alias ( ) )
return cube . engine . execute ( q ) . scalar ( ) |
def check_is_created ( method ) :
"""Make sure the Object DOES have an id , already .""" | def check ( self , * args , ** kwargs ) :
if self . id is None :
raise NotCreatedError ( '%s does not exists.' % self . __class__ . __name__ )
return method ( self , * args , ** kwargs )
return check |
def getGrid ( self , use_mask = True ) :
"""Returns GDALGrid object of GSSHA model bounds
Paramters :
use _ mask ( bool ) : If True , uses watershed mask . Otherwise , it uses the elevaiton grid .
Returns :
GDALGrid""" | grid_card_name = "WATERSHED_MASK"
if not use_mask :
grid_card_name = "ELEVATION"
return self . getGridByCard ( grid_card_name ) |
def TAPQuery ( query ) :
"""The _ _ main _ _ part of the script""" | tapURL = "http://cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/sync"
# # Some default parameters for that TAP service queries .
tapParams = { 'REQUEST' : 'doQuery' , 'LANG' : 'ADQL' , 'FORMAT' : 'votable' , 'QUERY' : query }
cnt = 0
while True :
try :
print "running query"
r = urllib2 . urlopen ( tapURL , ur... |
def search_keys ( text , keyserver = None , user = None ) :
'''Search keys from keyserver
text
Text to search the keyserver for , e . g . email address , keyID or fingerprint .
keyserver
Keyserver to use for searching for GPG keys , defaults to pgp . mit . edu .
user
Which user ' s keychain to access , ... | if GPG_1_3_1 :
raise SaltInvocationError ( 'The search_keys function is not support with this version of python-gnupg.' )
else :
if not keyserver :
keyserver = 'pgp.mit.edu'
_keys = [ ]
for _key in _search_keys ( text , keyserver , user ) :
tmp = { 'keyid' : _key [ 'keyid' ] , 'uids' : _... |
def lai ( self ) :
"""Leaf area index ( LAI ) , or the surface area of leaves to surface area ground .
Trezza and Allen , 2014
: param ndvi : normalized difference vegetation index [ - ]
: return : LAI [ - ]""" | ndvi = self . ndvi ( )
lai = 7.0 * ( ndvi ** 3 )
lai = where ( lai > 6. , 6. , lai )
return lai |
def elem_to_container ( elem , container = dict , ** options ) :
"""Convert XML ElementTree Element to a collection of container objects .
Elements are transformed to a node under special tagged nodes , attrs , text
and children , to store the type of these elements basically , however , in
some special cases... | dic = container ( )
if elem is None :
return dic
elem . tag = _tweak_ns ( elem . tag , ** options )
# { ns } tag - > ns _ prefix : tag
subdic = dic [ elem . tag ] = container ( )
options [ "container" ] = container
if elem . text :
_process_elem_text ( elem , dic , subdic , ** options )
if elem . attrib :
_... |
def load_from_file ( self , path ) :
"""Load cookies from the file .
Content of file should be a JSON - serialized list of dicts .""" | with open ( path ) as inf :
data = inf . read ( )
if data :
items = json . loads ( data )
else :
items = { }
for item in items :
extra = dict ( ( x , y ) for x , y in item . items ( ) if x not in [ 'name' , 'value' , 'domain' ] )
self . set ( item [ 'name' ] , item [ 'value' ] , item... |
def crossref_paths ( self ) :
"""Just like crossrefs , but all the targets are munged to : all .""" | return set ( [ address . new ( repo = x . repo , path = x . path ) for x in self . crossrefs ] ) |
def add_translations ( self , module_name , translations_dir = "translations" , domain = "messages" ) :
"""Add translations from external module .
For example : :
babel . add _ translations ( ' abilian . core ' )
Will add translations files from ` abilian . core ` module .""" | module = importlib . import_module ( module_name )
for path in ( Path ( p , translations_dir ) for p in module . __path__ ) :
if not ( path . exists ( ) and path . is_dir ( ) ) :
continue
if not os . access ( str ( path ) , os . R_OK ) :
self . app . logger . warning ( "Babel translations: read ... |
def register_auth_method ( self , auth_method ) :
"""Register a new authentication method
name
the name of the authentication method , typically displayed by the webapp
input _ to _ display
Only available after that the Plugin Manager is loaded""" | if not self . _loaded :
raise PluginManagerNotLoadedException ( )
self . _user_manager . register_auth_method ( auth_method ) |
def _get_stddevs ( self , C , stddev_types , num_sites ) :
"""Return standard deviations as defined in tables below""" | assert all ( stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types )
stddevs = [ np . zeros ( num_sites ) + C [ 'SigmaTot' ] for _ in stddev_types ]
return stddevs |
def dataframe ( self , predicate = None , filtered_columns = None , columns = None , df_class = None ) :
"""Return the partition as a Pandas dataframe
: param predicate : If defined , a callable that is called for each row , and if it returns true , the
row is included in the output .
: param filtered _ colum... | from operator import itemgetter
from ambry . pands import AmbryDataFrame
df_class = df_class or AmbryDataFrame
if columns :
ig = itemgetter ( * columns )
else :
ig = None
columns = self . table . header
if filtered_columns :
def maybe_quote ( v ) :
from six import string_types
if isinsta... |
def extract_zip ( archive , compression , cmd , verbosity , interactive , outdir ) :
"""Extract a ZIP archive with the zipfile Python module .""" | try :
with zipfile . ZipFile ( archive ) as zfile :
zfile . extractall ( outdir )
except Exception as err :
msg = "error extracting %s: %s" % ( archive , err )
raise util . PatoolError ( msg )
return None |
def clear ( self , event , ts = None ) :
"""Clear all stored record of event .
: param event : event name to be cleared .
: param ts : timestamp used locate the namespace""" | return self . r . delete ( self . _keygen ( event , ts ) ) |
def get_events ( self , name = None , time = None , chan = None , stage = None , qual = None ) :
"""Get list of events in the file .
Parameters
name : str , optional
name of the event of interest
time : tuple of two float , optional
start and end time of the period of interest
chan : tuple of str , opti... | # get events inside window
events = self . rater . find ( 'events' )
if name is not None :
pattern = "event_type[@type='" + name + "']"
else :
pattern = "event_type"
if chan is not None :
if isinstance ( chan , ( tuple , list ) ) :
if chan [ 0 ] is not None :
chan = ', ' . join ( chan )
... |
def new_data ( self , mem , addr , data ) :
"""Callback for when new memory data has been fetched""" | if mem . id == self . id :
if addr == 0 :
if self . _parse_and_check_header ( data [ 0 : 8 ] ) :
if self . _parse_and_check_elements ( data [ 9 : 11 ] ) :
self . valid = True
self . _update_finished_cb ( self )
self . _update_finished_cb = None
... |
def step_into ( self ) :
"""Take a forward step ( into ) for all active states in the state machine""" | logger . debug ( "Execution step into ..." )
self . run_to_states = [ ]
if self . finished_or_stopped ( ) :
self . set_execution_mode ( StateMachineExecutionStatus . FORWARD_INTO )
self . _run_active_state_machine ( )
else :
self . set_execution_mode ( StateMachineExecutionStatus . FORWARD_INTO ) |
def flush ( self ) :
"""Flush input buffers .""" | if self . debug :
sys . stderr . write ( "%s: FLUSH INPUT (%i bytes waiting)\n" % ( self . __class__ . __name__ , self . ser . inWaiting ( ) ) )
self . ser . flushInput ( ) |
def now_millis ( absolute = False ) -> int :
"""Return current millis since epoch as integer .""" | millis = int ( time . time ( ) * 1e3 )
if absolute :
return millis
return millis - EPOCH_MICROS // 1000 |
def get ( self , bounce_type = None , inactive = None , email_filter = None , message_id = None , count = None , offset = None , api_key = None , secure = None , test = None , ** request_args ) :
'''Builds query string params from inputs . It handles offset and
count defaults and validation .
: param bounce _ t... | params = self . _construct_params ( bounce_type = bounce_type , inactive = inactive , email_filter = email_filter , message_id = message_id , count = count , offset = offset )
url = self . _get_api_url ( secure = secure )
headers = self . _get_headers ( api_key = api_key , test = test , request_args = request_args )
re... |
def compute_cell_sizes ( dataset , length = False , area = True , volume = True ) :
"""This filter computes sizes for 1D ( length ) , 2D ( area ) and 3D ( volume )
cells .
Parameters
length : bool
Specify whether or not to compute the length of 1D cells .
area : bool
Specify whether or not to compute th... | alg = vtk . vtkCellSizeFilter ( )
alg . SetInputDataObject ( dataset )
alg . SetComputeArea ( area )
alg . SetComputeVolume ( volume )
alg . SetComputeLength ( length )
alg . SetComputeVertexCount ( False )
alg . Update ( )
return _get_output ( alg ) |
def fix_multiclass_predict_proba ( y_proba , # type : np . ndarray
seen_classes , complete_classes ) : # type : ( . . . ) - > np . ndarray
"""Add missing columns to predict _ proba result .
When a multiclass classifier is fit on a dataset which only contains
a subset of possible classes its predict _ proba resu... | assert set ( complete_classes ) >= set ( seen_classes )
y_proba_fixed = np . zeros ( shape = ( y_proba . shape [ 0 ] , len ( complete_classes ) ) , dtype = y_proba . dtype , )
class_mapping = np . searchsorted ( complete_classes , seen_classes )
y_proba_fixed [ : , class_mapping ] = y_proba
return y_proba_fixed |
def __system_methodSignature ( method_name , ** kwargs ) :
"""Returns an array describing the signature of the given method name .
The result is an array with :
- Return type as first elements
- Types of method arguments from element 1 to N
: param method _ name : Name of a method available for current entr... | entry_point = kwargs . get ( ENTRY_POINT_KEY )
protocol = kwargs . get ( PROTOCOL_KEY )
method = registry . get_method ( method_name , entry_point , protocol )
if method is None :
raise RPCInvalidParams ( 'Unknown method {}. Unable to retrieve signature.' . format ( method_name ) )
return method . signature |
def set_access_cookies ( response , encoded_access_token , max_age = None ) :
"""Takes a flask response object , and an encoded access token , and configures
the response to set in the access token in a cookie . If ` JWT _ CSRF _ IN _ COOKIES `
is ` True ` ( see : ref : ` Configuration Options ` ) , this will a... | if not config . jwt_in_cookies :
raise RuntimeWarning ( "set_access_cookies() called without " "'JWT_TOKEN_LOCATION' configured to use cookies" )
# Set the access JWT in the cookie
response . set_cookie ( config . access_cookie_name , value = encoded_access_token , max_age = max_age or config . cookie_max_age , sec... |
def _class_instance_from_name ( class_name , * arg , ** kwarg ) :
"""class _ name is of the form modA . modB . modC . class module _ path splits on " . "
and the import _ path is then [ ' modA ' , ' modB ' , ' modC ' ] the _ _ import _ _ call is
really annoying but essentially it reads like :
import class fro... | # we first look in tc . extensions for the class name
module_path = class_name . split ( '.' )
import_path = module_path [ 0 : - 1 ]
module = __import__ ( '.' . join ( import_path ) , fromlist = [ module_path [ - 1 ] ] )
class_ = getattr ( module , module_path [ - 1 ] )
instance = class_ ( * arg , ** kwarg )
return ins... |
def digital_write_pullup ( pin_num , value , hardware_addr = 0 ) :
"""Writes the value to the input pullup specified .
. . note : : This function is for familiarality with users of other types of
IO board . Consider accessing the ` ` gppub ` ` attribute of a
PiFaceDigital object :
> > > pfd = PiFaceDigital ... | _get_pifacedigital ( hardware_addr ) . gppub . bits [ pin_num ] . value = value |
def send_request ( self , send_function = None ) :
"""Sends the assembled request on the child object .
@ type send _ function : function reference
@ keyword send _ function : A function reference ( passed without the
parenthesis ) to a function that will send the request . This
allows for overriding the de... | # Send the request and get the response back .
try : # If the user has overridden the send function , use theirs
# instead of the default .
if send_function : # Follow the overridden function .
self . response = send_function ( )
else : # Default scenario , business as usual .
self . response = ... |
def process_request ( self , request ) :
"""Check if user is logged in""" | assert hasattr ( request , 'user' )
if not request . user . is_authenticated ( ) :
path = request . path_info . lstrip ( '/' )
if not any ( m . match ( path ) for m in EXEMPT_URLS ) :
return HttpResponseRedirect ( reverse ( settings . LOGIN_URL ) ) |
def get_comparable_values ( self ) :
"""Return a tupple of values representing the unicity of the object""" | return ( str ( self . name ) , str ( self . description ) , str ( self . type ) , bool ( self . optional ) , str ( self . constraints ) if isinstance ( self , Constraintable ) else "" ) |
def probe_git ( ) :
"""Return a git repository instance if it exists .""" | try :
repo = git . Repo ( )
except git . InvalidGitRepositoryError :
LOGGER . warning ( "We highly recommend keeping your model in a git repository." " It allows you to track changes and to easily collaborate with" " others via online platforms such as https://github.com.\n" )
return
if repo . is_dirty ( ) ... |
def digest ( self , data = None ) :
"""Finalizes digest operation and return digest value
Optionally hashes more data before finalizing""" | if self . digest_finalized :
return self . digest_out . raw [ : self . digest_size ]
if data is not None :
self . update ( data )
self . digest_out = create_string_buffer ( 256 )
length = c_long ( 0 )
result = libcrypto . EVP_DigestFinal_ex ( self . ctx , self . digest_out , byref ( length ) )
if result != 1 :
... |
def _update_templatetype ( templatetype , existing_tt = None ) :
"""Add or update a templatetype . If an existing template type is passed in ,
update that one . Otherwise search for an existing one . If not found , add .""" | if existing_tt is None :
if "id" in templatetype and templatetype . id is not None :
tmpltype_i = db . DBSession . query ( TemplateType ) . filter ( TemplateType . id == templatetype . id ) . one ( )
else :
tmpltype_i = TemplateType ( )
else :
tmpltype_i = existing_tt
tmpltype_i . template_i... |
def busmap_by_stubs ( network , matching_attrs = None ) :
"""Create a busmap by reducing stubs and stubby trees
( i . e . sequentially reducing dead - ends ) .
Parameters
network : pypsa . Network
matching _ attrs : None | [ str ]
bus attributes clusters have to agree on
Returns
busmap : pandas . Seri... | busmap = pd . Series ( network . buses . index , network . buses . index )
G = network . graph ( )
def attrs_match ( u , v ) :
return ( matching_attrs is None or ( network . buses . loc [ u , matching_attrs ] == network . buses . loc [ v , matching_attrs ] ) . all ( ) )
while True :
stubs = [ ]
for u in G .... |
def __PrintDocstring ( self , printer , method_info , method_name , name ) :
"""Print a docstring for a service method .""" | if method_info . description :
description = util . CleanDescription ( method_info . description )
first_line , newline , remaining = method_info . description . partition ( '\n' )
if not first_line . endswith ( '.' ) :
first_line = '%s.' % first_line
description = '%s%s%s' % ( first_line , newl... |
def DocumentPackages ( self , packages , index_base = None , showprivate = False , notify = True , showinh = False , intro_pages = None , append_material = None , extra = None ) :
"""This is the high level API to use to generate documentation pages for any given package ( s ) .
Args :
packages ( list ( module )... | if index_base is None :
gram = ''
if isinstance ( packages , list ) and len ( packages ) > 1 :
gram = 's'
if len ( packages ) < 3 :
names = ' and ' . join ( [ '``%s``' % p . __name__ for p in packages ] )
else :
names = [ '``%s``' % p . __name__ for p in packages ... |
def save ( self , * args , ** kwargs ) :
"""automatically update updated date field""" | # auto fill updated field with current time unless explicitly disabled
auto_update = kwargs . get ( 'auto_update' , True )
if auto_update :
self . updated = now ( )
# remove eventual auto _ update
if 'auto_update' in kwargs :
kwargs . pop ( 'auto_update' )
super ( BaseDate , self ) . save ( * args , ** kwargs ) |
def index ( self ) :
"""Index all files / directories below the current BIDSNode .""" | config_list = self . config
layout = self . layout
for ( dirpath , dirnames , filenames ) in os . walk ( self . path ) : # If layout configuration file exists , delete it
layout_file = self . layout . config_filename
if layout_file in filenames :
filenames . remove ( layout_file )
for f in filenames... |
def is_Tuple_ellipsis ( tpl ) :
"""Python version independent function to check if a typing . Tuple object
contains an ellipsis .""" | try :
return tpl . __tuple_use_ellipsis__
except AttributeError :
try :
if tpl . __args__ is None :
return False
# Python 3.6
if tpl . __args__ [ - 1 ] is Ellipsis :
return True
except AttributeError :
pass
return False |
def clone_repo ( self , repo_name , remote_repo , ref ) :
"""Clones the given repo and returns the Repository object .""" | self . shallow_clone = False
dirname , repo = self . set_up_clone ( repo_name , remote_repo )
if os . path . isdir ( "%s/.git" % dirname ) :
log . debug ( "Updating %s to %s" , repo . download_location , dirname )
self . executor ( "cd %s && git checkout master" % dirname )
self . pull ( dirname )
else :
... |
def server_prepare_root_bin_dir ( ) :
'''Install custom commands for user root at ' / root / bin / ' .''' | commands = [ 'run_backup' ]
for command in commands :
install_file_legacy ( flo ( '/root/bin/{command}' ) , sudo = True )
sudo ( flo ( 'chmod 755 /root/bin/{command}' ) )
if command == 'run_backup' :
sudo ( 'ln -snf /root/bin/run_backup /etc/cron.daily/run_backup' ) |
def gf_poly_mul ( p , q ) :
'''Multiply two polynomials , inside Galois Field ( but the procedure is generic ) . Optimized function by precomputation of log .''' | # Pre - allocate the result array
r = bytearray ( len ( p ) + len ( q ) - 1 )
# Precompute the logarithm of p
lp = [ gf_log [ p [ i ] ] for i in xrange ( len ( p ) ) ]
# Compute the polynomial multiplication ( just like the outer product of two vectors , we multiply each coefficients of p with all coefficients of q )
f... |
def _store_basic_estimation_results ( self , results_dict ) :
"""Extracts the basic estimation results ( i . e . those that need no further
calculation or logic applied to them ) and stores them on the model
object .
Parameters
results _ dict : dict .
The estimation result dictionary that is output from
... | # Store the log - likelilhood , fitted probabilities , residuals , and
# individual chi - square statistics
self . log_likelihood = results_dict [ "final_log_likelihood" ]
self . fitted_probs = results_dict [ "chosen_probs" ]
self . long_fitted_probs = results_dict [ "long_probs" ]
self . long_residuals = results_dict ... |
def parse_table_name ( name , project_id = None , dataset_id = None ) :
"""Parses a table name into its individual parts .
Args :
name : the name to parse , or a tuple , dictionary or array containing the parts .
project _ id : the expected project ID . If the name does not contain a project ID ,
this will ... | _project_id = _dataset_id = _table_id = _decorator = None
if isinstance ( name , basestring ) : # Try to parse as absolute name first .
m = re . match ( _ABS_TABLE_NAME_PATTERN , name , re . IGNORECASE )
if m is not None :
_project_id , _dataset_id , _table_id , _decorator = m . groups ( )
else : # ... |
async def service_info ( self , name ) :
"""Pull descriptive info of a service by name .
Information returned includes the service ' s user friendly
name and whether it was preregistered or added dynamically .
Returns :
dict : A dictionary of service information with the following keys
set :
long _ name... | return await self . send_command ( OPERATIONS . CMD_QUERY_INFO , { 'name' : name } , MESSAGES . QueryInfoResponse , timeout = 5.0 ) |
def find_kernel_specs ( self ) :
"""Returns a dict mapping kernel names to resource directories .""" | # let real installed kernels overwrite envs with the same name :
# this is the same order as the get _ kernel _ spec way , which also prefers
# kernels from the jupyter dir over env kernels .
specs = self . find_kernel_specs_for_envs ( )
specs . update ( super ( EnvironmentKernelSpecManager , self ) . find_kernel_specs... |
def handle_part ( self , params ) :
"""Handle a client parting from channel ( s ) .""" | for pchannel in params . split ( ',' ) :
if pchannel . strip ( ) in self . server . channels : # Send message to all clients in all channels user is in , and
# remove the user from the channels .
channel = self . server . channels . get ( pchannel . strip ( ) )
response = ':%s PART :%s' % ( self... |
def define ( self , schema , * , validate = True ) :
"""Store the task graph definition ( schema ) .
The schema has to adhere to the following rules :
A key in the schema dict represents a parent task and the value one or more
children :
{ parent : [ child ] } or { parent : [ child1 , child2 ] }
The data ... | self . _schema = schema
if validate :
self . validate ( self . make_graph ( self . _schema ) ) |
def get_so_far ( self ) :
"""Returns the ` str ` bytes of this message that have been parsed and
returned . The string passed into a message ' s constructor can be
regenerated by concatenating ` ` get _ so _ far ` ` and ` get _ remainder ` .""" | position = self . packet . tell ( )
self . rewind ( )
return self . packet . read ( position ) |
def _parse_sections ( morph_fd ) :
'''returns array of all the sections that exist
The format is nested lists that correspond to the s - expressions''' | sections = [ ]
token_iter = _get_tokens ( morph_fd )
for token in token_iter :
if token == '(' : # find top - level sections
section = _parse_section ( token_iter )
if not _match_section ( section , UNWANTED_SECTIONS ) :
sections . append ( section )
return sections |
def _qualify_map ( key , content ) :
"""When a dictionary key is optional / optionalnull / mandatory , its corresponding
_ value _ is decorated in an Optional / OptionalNull / Mandatory tuple .
This function undo the decoration when necessary .""" | if not isinstance ( key , basestring ) :
return key , content
min_len = None
max_len = None
modifier = [ ]
m = RE_MATCH_CSTR ( key )
if not m :
raise KeyError ( "Unable to parse, invalid key: %r" % key )
if m . group ( 3 ) is not None :
min_len = max_len = int ( m . group ( 3 ) )
elif m . group ( 4 ) is not... |
def repo_data ( PACKAGES_TXT , repo , flag ) :
"""Grap data packages""" | ( name , location , size , unsize , rname , rlocation , rsize , runsize ) = ( [ ] for i in range ( 8 ) )
for line in PACKAGES_TXT . splitlines ( ) :
if _meta_ . rsl_deps in [ "on" , "ON" ] and "--resolve-off" not in flag :
status ( 0.000005 )
if line . startswith ( "PACKAGE NAME:" ) :
name . app... |
def set_acls ( path , acls , version = - 1 , profile = None , hosts = None , scheme = None , username = None , password = None , default_acl = None ) :
'''Set acls on a znode
path
path to znode
acls
list of acl dictionaries to set on the znode
version
only set acls if version matches ( Default : - 1 ( a... | conn = _get_zk_conn ( profile = profile , hosts = hosts , scheme = scheme , username = username , password = password , default_acl = default_acl )
if acls is None :
acls = [ ]
acls = [ make_digest_acl ( ** acl ) for acl in acls ]
conn = _get_zk_conn ( profile = profile , hosts = hosts , scheme = scheme , username ... |
def append ( self , * other ) :
"""Append self with other stream ( s ) . Chaining this way has the behaviour :
` ` self = Stream ( self , * others ) ` `""" | self . _data = it . chain ( self . _data , Stream ( * other ) . _data )
return self |
def _authenticate ( self ) :
"""Logs - in the user and checks the domain name""" | if not self . _get_provider_option ( 'auth_username' ) or not self . _get_provider_option ( 'auth_password' ) :
raise Exception ( 'No valid authentication data passed, expected: auth-username and auth-password' )
response = self . _request_login ( self . _get_provider_option ( 'auth_username' ) , self . _get_provid... |
def get_version ( self , diff_to_increase_ratio ) :
"""Gets version
: param diff _ to _ increase _ ratio : Ratio to convert number of changes into
: return : Version of this code , based on commits diffs""" | diffs = self . get_diff_amounts ( )
version = Version ( )
for diff in diffs :
version . increase_by_changes ( diff , diff_to_increase_ratio )
return version |
def send_email_smtp ( to , subject , html_content , config , files = None , data = None , images = None , dryrun = False , cc = None , bcc = None , mime_subtype = 'mixed' ) :
"""Send an email with html content , eg :
send _ email _ smtp (
' test @ example . com ' , ' foo ' , ' < b > Foo < / b > bar ' , [ ' / de... | smtp_mail_from = config . get ( 'SMTP_MAIL_FROM' )
to = get_email_address_list ( to )
msg = MIMEMultipart ( mime_subtype )
msg [ 'Subject' ] = subject
msg [ 'From' ] = smtp_mail_from
msg [ 'To' ] = ', ' . join ( to )
msg . preamble = 'This is a multi-part message in MIME format.'
recipients = to
if cc :
cc = get_em... |
def CopyFromDateTimeString ( self , time_string ) :
"""Copies a SYSTEMTIME structure from a date and time string .
Args :
time _ string ( str ) : date and time value formatted as :
YYYY - MM - DD hh : mm : ss . # # # # # [ + - ] # # : # #
Where # are numeric digits ranging from 0 to 9 and the seconds
frac... | date_time_values = self . _CopyDateTimeFromString ( time_string )
year = date_time_values . get ( 'year' , 0 )
month = date_time_values . get ( 'month' , 0 )
day_of_month = date_time_values . get ( 'day_of_month' , 0 )
hours = date_time_values . get ( 'hours' , 0 )
minutes = date_time_values . get ( 'minutes' , 0 )
sec... |
def updateIfNeeded ( self ) :
"""update address index .""" | headBlock = self . db . reader . _get_head_block ( )
if headBlock is not None : # avoid restarting search if head block is same & we already initialized
# this is required for fastSync handling
if self . lastBlock is not None :
self . lastBlock = max ( self . lastBlock , headBlock . number )
else :
... |
def create_transaction ( self , * args : Any , ** kwargs : Any ) -> BaseTransaction :
"""Passthrough helper to the current VM class .""" | return self . get_vm ( ) . create_transaction ( * args , ** kwargs ) |
def record_timing ( self , duration , * path ) :
"""Record a timing .
This method records a timing to the application ' s namespace
followed by a calculated path . Each element of ` path ` is
converted to a string and normalized before joining the
elements by periods . The normalization process is little
... | self . application . statsd . send ( path , duration * 1000.0 , 'ms' ) |
def stream_compute_ecc_hash ( ecc_manager , hasher , file , max_block_size , header_size , resilience_rates ) :
'''Generate a stream of hash / ecc blocks , of variable encoding rate and size , given a file .''' | curpos = file . tell ( )
# init the reading cursor at the beginning of the file
# Find the total size to know when to stop
# size = os . fstat ( file . fileno ( ) ) . st _ size # old way of doing it , doesn ' t work with StringIO objects
file . seek ( 0 , os . SEEK_END )
# alternative way of finding the total size : go... |
def forward ( self , step ) :
"""Move the turtle forward .
: param step : Integer . Distance to move forward .""" | x = self . pos_x + math . cos ( math . radians ( self . rotation ) ) * step
y = self . pos_y + math . sin ( math . radians ( self . rotation ) ) * step
prev_brush_state = self . brush_on
self . brush_on = True
self . move ( x , y )
self . brush_on = prev_brush_state |
def search ( self , search_phrase , limit = None ) :
"""Finds partitions by search phrase .
Args :
search _ phrase ( str or unicode ) :
limit ( int , optional ) : how many results to generate . None means without limit .
Yields :
PartitionSearchResult instances .""" | query_string = self . _make_query_from_terms ( search_phrase )
self . _parsed_query = query_string
schema = self . _get_generic_schema ( )
parser = QueryParser ( 'doc' , schema = schema )
query = parser . parse ( query_string )
logger . debug ( 'Searching partitions using `{}` query.' . format ( query ) )
with self . i... |
def _get_modules ( self , names ) :
"""An internal method that gets the ` names ` from sys . modules and returns
them as a list""" | loaded_modules = [ ]
for name in names :
loaded_modules . append ( sys . modules [ name ] )
return loaded_modules |
def get_coordinates ( node_class ) :
"""Generate coordinates for a node in a given class .""" | quadrant_size = ( 2 * math . pi / 8.0 )
quadrant = get_quadrant_from_class ( node_class )
begin_angle = quadrant_size * quadrant
r = 200 + 800 * random . random ( )
alpha = begin_angle + random . random ( ) * quadrant_size
x = r * math . cos ( alpha )
y = r * math . sin ( alpha )
return x , y |
def bitmap_pattern_to_list ( self , bmp_pat ) :
"""takes a list of bitmap points ( drawn via Life screen )
and converts to a list of full coordinates""" | res = [ ]
x = 1
y = 1
lines = bmp_pat . split ( '\n' )
for line in lines :
y += 1
for char in line :
x += 1
if char == 'X' :
res . append ( [ y , x ] )
return res |
def _set_set_dscp ( self , v , load = False ) :
"""Setter method for set _ dscp , mapped from YANG variable / policy _ map / class / set / set _ dscp ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ set _ dscp is considered as a private
method . Backends ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = set_dscp . set_dscp , is_container = 'container' , presence = False , yang_name = "set_dscp" , rest_name = "" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , ext... |
def initialize ( self , endog , freq_weights ) :
'''Initialize the response variable .
Parameters
endog : array
Endogenous response variable
Returns
If ` endog ` is binary , returns ` endog `
If ` endog ` is a 2d array , then the input is assumed to be in the format
( successes , failures ) and
succ... | # if not np . all ( np . asarray ( freq _ weights ) = = 1 ) :
# self . variance = V . Binomial ( n = freq _ weights )
if ( endog . ndim > 1 and endog . shape [ 1 ] > 1 ) :
y = endog [ : , 0 ]
# overwrite self . freq _ weights for deviance below
self . n = endog . sum ( 1 )
return y * 1. / self . n , sel... |
def validate_properties ( self , model , context = None ) :
"""Validate simple properties
Performs validation on simple properties to return a result object .
: param model : object or dict
: param context : object , dict or None
: return : shiftschema . result . Result""" | result = Result ( )
for property_name in self . properties :
prop = self . properties [ property_name ]
value = self . get ( model , property_name )
errors = prop . validate ( value = value , model = model , context = context )
if errors :
result . add_errors ( errors = errors , property_name = ... |
def register ( self , arguments = list ( ) ) :
"""Register a target file with arguments ( if required ) to a event _ control file
which we want to be notified events .""" | target_name = self . target_name
if target_name in [ 'memory.usage_in_bytes' , 'memory.memsw.usage_in_bytes' ] :
threshold = arguments [ 0 ]
line = "%d %d %d\0" % ( self . event_fd , self . target_fd , long ( threshold ) )
elif target_name in [ 'memory.pressure_level' ] :
threshold = arguments [ 0 ]
lin... |
def draw_image ( pixelmap , img ) :
'''Draws the image based on the given pixelmap .''' | for item in pixelmap :
color = item [ 2 ]
# Access the rectangle edges .
pixelbox = ( item [ 0 ] [ 0 ] , item [ 0 ] [ 1 ] , item [ 1 ] [ 0 ] , item [ 1 ] [ 1 ] )
draw = ImageDraw . Draw ( img )
draw . rectangle ( pixelbox , fill = color ) |
def get_meta ( meta , name ) :
"""Retrieves the metadata variable ' name ' from the ' meta ' dict .""" | assert name in meta
data = meta [ name ]
if data [ 't' ] in [ 'MetaString' , 'MetaBool' ] :
return data [ 'c' ]
elif data [ 't' ] == 'MetaInlines' : # Handle bug in pandoc 2.2.3 and 2.2.3.1 : Return boolean value rather
# than strings , as appropriate .
if len ( data [ 'c' ] ) == 1 and data [ 'c' ] [ 0 ] [ 't' ... |
def sort_func ( self , entry ) :
"""Return the key attribute to determine how data is sorted .
Time will need to be converted to 24 hour time .
In instances when float attributes will have an ' n / a ' string , return 0.""" | key = entry [ self . sort ]
if self . sort in FLOAT_ATTRIBUTES and not isinstance ( key , float ) :
return 0
# If value is ' n / a ' string
elif self . sort == 'time' :
return convert_time ( key )
elif self . sort == 'date' :
return convert_date ( key )
return key |
def relaxedEMDS ( X0 , N , d , C , b , KE , print_out = False , lamda = 10 ) :
"""Find the set of points from an edge kernel with geometric constraints , using convex rank relaxation .""" | E = C . shape [ 1 ]
X = Variable ( ( E , E ) , PSD = True )
constraints = [ C [ i , : ] * X == b [ i ] for i in range ( C . shape [ 0 ] ) ]
obj = Minimize ( trace ( X ) + lamda * norm ( KE - X ) )
prob = Problem ( obj , constraints )
try : # CVXOPT is more accurate than SCS , even though slower .
total_cost = prob ... |
def remove_file ( master_ip , filename , spark_on_toil ) :
"""Remove the given file from hdfs with master at the given IP address
: type masterIP : MasterAddress""" | master_ip = master_ip . actual
ssh_call = [ 'ssh' , '-o' , 'StrictHostKeyChecking=no' , master_ip ]
if spark_on_toil :
output = check_output ( ssh_call + [ 'docker' , 'ps' ] )
container_id = next ( line . split ( ) [ 0 ] for line in output . splitlines ( ) if 'apache-hadoop-master' in line )
ssh_call += [ '... |
def validation_epoch ( self , epoch_info , source : 'vel.api.Source' ) :
"""Run a single evaluation epoch""" | self . eval ( )
iterator = tqdm . tqdm ( source . val_loader ( ) , desc = "Validation" , unit = "iter" , file = sys . stdout )
with torch . no_grad ( ) :
for batch_idx , ( data , target ) in enumerate ( iterator ) :
batch_info = BatchInfo ( epoch_info , batch_idx )
batch_info . on_validation_batch_b... |
def StartFlowAndWorker ( client_id , flow_name , ** kwargs ) :
"""Launches the flow and worker and waits for it to finish .
Args :
client _ id : The client common name we issue the request .
flow _ name : The name of the flow to launch .
* * kwargs : passthrough to flow .
Returns :
A flow session id .
... | # Empty token , only works with raw access .
queue = rdfvalue . RDFURN ( "DEBUG-%s-" % getpass . getuser ( ) )
if "token" in kwargs :
token = kwargs . pop ( "token" )
else :
token = access_control . ACLToken ( username = "GRRConsole" )
session_id = flow . StartAFF4Flow ( client_id = client_id , flow_name = flow... |
def update_peer ( self , current_name , new_name , new_url , username , password , peer_type = "REPLICATION" ) :
"""Update a replication peer .
@ param current _ name : The name of the peer to updated .
@ param new _ name : The new name for the peer .
@ param new _ url : The new url for the peer .
@ param u... | if self . _get_resource_root ( ) . version < 11 :
peer_type = None
peer = ApiCmPeer ( self . _get_resource_root ( ) , name = new_name , url = new_url , username = username , password = password , type = peer_type )
return self . _put ( "peers/" + current_name , ApiCmPeer , data = peer , api_version = 3 ) |
def generate_secret ( length = 30 ) :
"""Generate an ASCII secret using random . SysRandom
Based on oauthlib ' s common . generate _ token function""" | rand = random . SystemRandom ( )
ascii_characters = string . ascii_letters + string . digits
return '' . join ( rand . choice ( ascii_characters ) for _ in range ( length ) ) |
def ai ( board , who = 'x' ) :
"""Returns best next board
> > > b = Board ( ) ; b . _ rows = [ [ ' x ' , ' o ' , ' ' ] , [ ' x ' , ' o ' , ' ' ] , [ ' ' , ' ' , ' ' ] ]
> > > ai ( b )
< Board | xo . xo . x . . | >""" | return sorted ( board . possible ( ) , key = lambda b : value ( b , who ) ) [ - 1 ] |
def get_objective_lookup_session_for_objective_bank ( self , objective_bank_id , proxy , * args , ** kwargs ) :
"""Gets the ` ` OsidSession ` ` associated with the objective lookup service for the given objective bank .
: param objective _ bank _ id : the ` ` Id ` ` of the objective bank
: type objective _ bank... | if not objective_bank_id :
raise NullArgument
if not self . supports_objective_lookup ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( )
proxy = self . _convert_proxy ( proxy )
try :
session = sessions . ObjectiveLookupSession ( objective_bank_i... |
def _is_updated ( old_conf , new_conf ) :
'''Compare the API results to the current statefile data''' | changed = { }
# Dirty json hacking to get parameters in the same format
new_conf = _json_to_unicode ( salt . utils . json . loads ( salt . utils . json . dumps ( new_conf , ensure_ascii = False ) ) )
old_conf = salt . utils . json . loads ( salt . utils . json . dumps ( old_conf , ensure_ascii = False ) )
for key , val... |
def _custom_argv ( argv ) :
"""Overwrite argv [ 1 : ] with argv , restore on exit .""" | backup_argv = sys . argv
sys . argv = backup_argv [ : 1 ] + argv
try :
yield
finally :
sys . argv = backup_argv |
def reader ( path ) :
"""Turns a path to a dump file into a file - like object of ( decompressed )
XML data assuming that ' 7z ' is installed and will know what to do .
: Parameters :
path : ` str `
the path to the dump file to read""" | p = subprocess . Popen ( [ '7z' , 'e' , '-so' , path ] , stdout = subprocess . PIPE , stderr = file_open ( os . devnull , "w" ) )
return io . TextIOWrapper ( p . stdout , encoding = 'utf-8' , errors = 'replace' ) |
def edit_required_status_checks ( self , strict = github . GithubObject . NotSet , contexts = github . GithubObject . NotSet ) :
""": calls : ` PATCH / repos / : owner / : repo / branches / : branch / protection / required _ status _ checks < https : / / developer . github . com / v3 / repos / branches > ` _
: st... | assert strict is github . GithubObject . NotSet or isinstance ( strict , bool ) , strict
assert contexts is github . GithubObject . NotSet or all ( isinstance ( element , ( str , unicode ) ) or isinstance ( element , ( str , unicode ) ) for element in contexts ) , contexts
post_parameters = { }
if strict is not github ... |
def fill ( self , ** kwargs ) :
'''Loads the relationships into this model . They are not loaded by
default''' | setattr ( self . obj , self . name , self . get ( ** kwargs ) ) |
def mission_item_reached_send ( self , seq , force_mavlink1 = False ) :
'''A certain mission item has been reached . The system will either hold
this position ( or circle on the orbit ) or ( if the
autocontinue on the WP was set ) continue to the next
MISSION .
seq : Sequence ( uint16 _ t )''' | return self . send ( self . mission_item_reached_encode ( seq ) , force_mavlink1 = force_mavlink1 ) |
def add_bounding_box ( self , color = None , corner_factor = 0.5 , line_width = None , opacity = 1.0 , render_lines_as_tubes = False , lighting = None , reset_camera = None ) :
"""Adds an unlabeled and unticked box at the boundaries of
plot . Useful for when wanting to plot outer grids while
still retaining all... | if lighting is None :
lighting = rcParams [ 'lighting' ]
self . remove_bounding_box ( )
if color is None :
color = rcParams [ 'font' ] [ 'color' ]
rgb_color = parse_color ( color )
self . _bounding_box = vtk . vtkOutlineCornerSource ( )
self . _bounding_box . SetBounds ( self . bounds )
self . _bounding_box . S... |
def tplot_options ( option , value ) :
"""This function allows the user to set several global options for the generated plots .
Parameters :
option : str
The name of the option . See section below
value : str / int / float / list
The value of the option . See section below .
Options :
Options Value ty... | option = option . lower ( )
temp = tplot_utilities . set_tplot_options ( option , value , pytplot . tplot_opt_glob )
pytplot . tplot_opt_glob = temp
return |
def _check_sane_and_get_gpg_version ( self ) :
"""Check that everything runs alright , and grab the gpg binary ' s
version number while we ' re at it , storing it as : data : ` binary _ version ` .
: raises RuntimeError : if we cannot invoke the gpg binary .""" | proc = self . _open_subprocess ( [ "--list-config" , "--with-colons" ] )
result = self . _result_map [ 'list' ] ( self )
self . _read_data ( proc . stdout , result )
if proc . returncode :
raise RuntimeError ( "Error invoking gpg: %s" % result . data )
else :
try :
proc . terminate ( )
except OSErro... |
def list_comments ( self , topic_id , start = 0 ) :
"""回复列表
: param topic _ id : 话题ID
: param start : 翻页
: return : 带下一页的列表""" | xml = self . api . xml ( API_GROUP_GET_TOPIC % topic_id , params = { 'start' : start } )
xml_results = xml . xpath ( '//ul[@id="comments"]/li' )
results = [ ]
for item in xml_results :
try :
author_avatar = item . xpath ( './/img/@src' ) [ 0 ]
author_url = item . xpath ( './/div[@class="user-face"]/... |
def _get_publish ( self ) :
"""Find this publish on remote""" | publishes = self . _get_publishes ( self . client )
for publish in publishes :
if publish [ 'Distribution' ] == self . distribution and publish [ 'Prefix' ] . replace ( "/" , "_" ) == ( self . prefix or '.' ) and publish [ 'Storage' ] == self . storage :
return publish
raise NoSuchPublish ( "Publish %s (%s)... |
def receive_prepare ( self , msg ) :
'''Returns either a Promise or a Nack in response . The Acceptor ' s state must be persisted to disk
prior to transmitting the Promise message .''' | if self . promised_id is None or msg . proposal_id >= self . promised_id :
self . promised_id = msg . proposal_id
return Promise ( self . network_uid , msg . from_uid , self . promised_id , self . accepted_id , self . accepted_value )
else :
return Nack ( self . network_uid , msg . from_uid , msg . proposal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.