signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def focus_last_child ( self ) :
"""move focus to last child of currently focussed one""" | w , focuspos = self . get_focus ( )
child = self . _tree . last_child_position ( focuspos )
if child is not None :
self . set_focus ( child ) |
def save ( self , filename = None ) :
"""Save the document to file .
Arguments :
* filename ( str ) : The filename to save to . If not set ( ` ` None ` ` , default ) , saves to the same file as loaded from .""" | if not filename :
filename = self . filename
if not filename :
raise Exception ( "No filename specified" )
if filename [ - 4 : ] . lower ( ) == '.bz2' :
f = bz2 . BZ2File ( filename , 'wb' )
f . write ( self . xmlstring ( ) . encode ( 'utf-8' ) )
f . close ( )
elif filename [ - 3 : ] . lower ( ) == ... |
def groupby ( iterable , key = 0 , filter = None ) :
"""wrapper to itertools . groupby that returns a list of each group , rather
than a generator and accepts integers or strings as the key and
automatically converts them to callables with itemgetter ( key )
Arguments :
iterable : iterable
key : string , ... | if isinstance ( key , ( basestring , int ) ) :
key = itemgetter ( key )
elif isinstance ( key , ( tuple , list ) ) :
key = itemgetter ( * key )
for label , grp in igroupby ( iterable , key ) :
yield label , list ( grp ) |
def setup ( ) :
"""import the matplotlib modules and set the style""" | import sys
already_loaded = 'matplotlib' in sys . modules
# just make sure we can access matplotlib as mpl
import matplotlib as mpl
if not already_loaded :
mpl . use ( 'Agg' )
import matplotlib . pyplot as plt
plt . style . use ( 'seaborn' )
general_settings ( )
import mpl_toolkits . axes_grid1 as axes_grid1
axes_g... |
def __parse_content ( tuc_content , content_to_be_parsed ) :
"""parses the passed " tuc _ content " for
- meanings
- synonym
received by querying the glosbe API
Called by
- meaning ( )
- synonym ( )
: param tuc _ content : passed on the calling Function . A list object
: param content _ to _ be _ pa... | initial_parsed_content = { }
i = 0
for content_dict in tuc_content :
if content_to_be_parsed in content_dict . keys ( ) :
contents_raw = content_dict [ content_to_be_parsed ]
if content_to_be_parsed == "phrase" : # for ' phrase ' , ' contents _ raw ' is a dictionary
initial_parsed_conten... |
def get_tissue_in_references ( self , entry ) :
"""get list of models . TissueInReference from XML node entry
: param entry : XML node entry
: return : list of : class : ` pyuniprot . manager . models . TissueInReference ` objects""" | tissue_in_references = [ ]
query = "./reference/source/tissue"
tissues = { x . text for x in entry . iterfind ( query ) }
for tissue in tissues :
if tissue not in self . tissues :
self . tissues [ tissue ] = models . TissueInReference ( tissue = tissue )
tissue_in_references . append ( self . tissues [ ... |
def log ( message : typing . Union [ str , typing . List [ str ] ] , whitespace : int = 0 , whitespace_top : int = 0 , whitespace_bottom : int = 0 , indent_by : int = 0 , trace : bool = True , file_path : str = None , append_to_file : bool = True , ** kwargs ) -> str :
"""Logs a message to the console with the form... | m = add_to_message ( message )
for key , value in kwargs . items ( ) :
m . append ( '{key}: {value}' . format ( key = key , value = value ) )
pre_whitespace = int ( max ( whitespace , whitespace_top ) )
post_whitespace = int ( max ( whitespace , whitespace_bottom ) )
if pre_whitespace :
m . insert ( 0 , max ( 0... |
def DatabaseDirectorySize ( root_path , extension ) :
"""Compute size ( in bytes ) and number of files of a file - based data store .""" | directories = collections . deque ( [ root_path ] )
total_size = 0
total_files = 0
while directories :
directory = directories . popleft ( )
try :
items = os . listdir ( directory )
except OSError :
continue
for comp in items :
path = os . path . join ( directory , comp )
... |
def get_lats_from_cartesian ( x__ , y__ , z__ , thr = 0.8 ) :
"""Get latitudes from cartesian coordinates .""" | # if we are at low latitudes - small z , then get the
# latitudes only from z . If we are at high latitudes ( close to the poles )
# then derive the latitude using x and y :
lats = np . where ( np . logical_and ( np . less ( z__ , thr * EARTH_RADIUS ) , np . greater ( z__ , - 1. * thr * EARTH_RADIUS ) ) , 90 - rad2deg ... |
def set ( self , instance , value , ** kw ) :
"""Converts the value into a DateTime object before setting .""" | if value :
try :
value = DateTime ( value )
except SyntaxError :
logger . warn ( "Value '{}' is not a valid DateTime string" . format ( value ) )
return False
self . _set ( instance , value , ** kw ) |
def _identifier_as_cid ( self , identifier ) :
"""Returns a container uuid for identifier .
If identifier is an image UUID or image tag , create a temporary
container and return its uuid .""" | def __cname_matches ( container , identifier ) :
return any ( [ n for n in ( container [ 'Names' ] or [ ] ) if matches ( n , '/' + identifier ) ] )
# Determine if identifier is a container
containers = [ c [ 'Id' ] for c in self . client . containers ( all = True ) if ( __cname_matches ( c , identifier ) or matches... |
def _parse_image_multilogs_string ( config , ret , repo ) :
'''Parse image log strings into grokable data''' | image_logs , infos = [ ] , None
if ret and ret . strip ( ) . startswith ( '{' ) and ret . strip ( ) . endswith ( '}' ) :
pushd = 0
buf = ''
for char in ret :
buf += char
if char == '{' :
pushd += 1
if char == '}' :
pushd -= 1
if pushd == 0 :
... |
def factorize ( self , A ) :
"""Factorizes A .
Parameters
A : matrix
For symmetric systems , should contain only lower diagonal part .""" | A = coo_matrix ( A )
self . mumps . set_centralized_assembled_values ( A . data )
self . mumps . run ( job = 2 ) |
def can_undo ( self ) :
"""Are there actions to undo ?""" | return bool ( self . _undo ) or bool ( self . _open and self . _open [ 0 ] ) |
def delete_workflow ( self , workflow_id ) :
"""Delete a workflow from the database
: param workflow _ id :
: return : None""" | deleted = False
with switch_db ( WorkflowDefinitionModel , "hyperstream" ) :
workflows = WorkflowDefinitionModel . objects ( workflow_id = workflow_id )
if len ( workflows ) == 1 :
workflows [ 0 ] . delete ( )
deleted = True
else :
logging . debug ( "Workflow with id {} does not exis... |
def quote_code ( self , key ) :
"""Returns string quoted code""" | code = self . grid . code_array ( key )
quoted_code = quote ( code )
if quoted_code is not None :
self . set_code ( key , quoted_code ) |
def get_default_config ( self ) :
"""Returns the default collector settings""" | config = super ( OneWireCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'owfs' , 'owfs' : '/mnt/1wire' , # ' scan ' : { ' temperature ' : ' t ' } ,
# ' id : 24 . BB00000 ' : { ' file _ with _ value ' : ' alias ' } ,
} )
return config |
def __get_smtp ( self ) :
"""Return the appropraite smtplib depending on wherther we ' re using TLS""" | use_tls = self . config [ 'shutit.core.alerting.emailer.use_tls' ]
if use_tls :
smtp = SMTP ( self . config [ 'shutit.core.alerting.emailer.smtp_server' ] , self . config [ 'shutit.core.alerting.emailer.smtp_port' ] )
smtp . starttls ( )
else :
smtp = SMTP_SSL ( self . config [ 'shutit.core.alerting.emailer... |
def eventgroups ( ctx , sport ) :
"""[ bookie ] List event groups for a sport
: param str sport : Sports id""" | sport = Sport ( sport , peerplays_instance = ctx . peerplays )
click . echo ( pretty_print ( sport . eventgroups , ctx = ctx ) ) |
def track_statistic ( self , name , description = '' , max_rows = None ) :
"""Create a Statistic object in the Tracker .""" | if name in self . _tables :
raise TableConflictError ( name )
if max_rows is None :
max_rows = AnonymousUsageTracker . MAX_ROWS_PER_TABLE
self . register_table ( name , self . uuid , 'Statistic' , description )
self . _tables [ name ] = Statistic ( name , self , max_rows = max_rows ) |
async def emit ( self , event , data , namespace , room = None , skip_sid = None , callback = None , ** kwargs ) :
"""Emit a message to a single client , a room , or all the clients
connected to the namespace .
Note : this method is a coroutine .""" | if namespace not in self . rooms or room not in self . rooms [ namespace ] :
return
tasks = [ ]
for sid in self . get_participants ( namespace , room ) :
if sid != skip_sid :
if callback is not None :
id = self . _generate_ack_id ( sid , namespace , callback )
else :
id =... |
def populate ( self , terminal = None , styles = None , default_esc_seq = '' ) :
'''Get the concrete ( including terminal escape sequences )
representation of this string .
: parameter Terminal terminal : The terminal object to use for turning
formatting attributes such as : attr : ` Root . format . blue ` in... | terminal = terminal or get_terminal ( )
styles = styles or { }
return '' . join ( s . populate ( terminal , styles , default_esc_seq ) for s in self . _content ) |
def replace ( cls , obj , field , value , state ) :
"""This is method for replace operation . It is separated to provide a
possibility to easily override it in your Parameters .
Args :
obj ( object ) : an instance to change .
field ( str ) : field name
value ( str ) : new value
state ( dict ) : inter - ... | if not hasattr ( obj , field ) :
raise ValidationError ( "Field '%s' does not exist, so it cannot be patched" % field )
setattr ( obj , field , value )
return True |
def show_more ( request , post_process_fun , get_fun , object_class , should_cache = True , template = 'common_json.html' , to_json_kwargs = None ) :
"""Return list of objects of the given type .
GET parameters :
limit :
number of returned objects ( default 10 , maximum 100)
page :
current page number
f... | if not should_cache and 'json_orderby' in request . GET :
return render_json ( request , { 'error' : "Can't order the result according to the JSON field, because the caching for this type of object is turned off. See the documentation." } , template = 'questions_json.html' , help_text = show_more . __doc__ , status... |
def encode ( self , cube_dimensions ) :
"""Produces a numpy array of integers which encode
the supplied cube dimensions .""" | return np . asarray ( [ getattr ( cube_dimensions [ d ] , s ) for d in self . _dimensions for s in self . _schema ] , dtype = np . int32 ) |
def write ( self , cmd_args ) :
"""Execute Vagrant write command .
: param list cmd _ args :
Command argument list .""" | args = [ "vagrant" ]
args . extend ( cmd_args )
subprocess . call ( args ) |
def _looks_like_functools_member ( node , member ) :
"""Check if the given Call node is a functools . partial call""" | if isinstance ( node . func , astroid . Name ) :
return node . func . name == member
elif isinstance ( node . func , astroid . Attribute ) :
return ( node . func . attrname == member and isinstance ( node . func . expr , astroid . Name ) and node . func . expr . name == "functools" ) |
def jc ( result , reference ) :
"""Jaccard coefficient
Computes the Jaccard coefficient between the binary objects in two images .
Parameters
result : array _ like
Input data containing objects . Can be any type but will be converted
into binary : background where 0 , object everywhere else .
reference ... | result = numpy . atleast_1d ( result . astype ( numpy . bool ) )
reference = numpy . atleast_1d ( reference . astype ( numpy . bool ) )
intersection = numpy . count_nonzero ( result & reference )
union = numpy . count_nonzero ( result | reference )
jc = float ( intersection ) / float ( union )
return jc |
def post_refresh_system_metadata ( request ) :
"""MNStorage . systemMetadataChanged ( session , did , serialVersion ,
dateSysMetaLastModified ) → boolean .""" | d1_gmn . app . views . assert_db . post_has_mime_parts ( request , ( ( 'field' , 'pid' ) , ( 'field' , 'serialVersion' ) , ( 'field' , 'dateSysMetaLastModified' ) , ) , )
d1_gmn . app . views . assert_db . is_existing_object ( request . POST [ 'pid' ] )
d1_gmn . app . models . sysmeta_refresh_queue ( request . POST [ '... |
def add_error ( self , error ) :
"""Record an error from expect APIs .
This method generates a position stamp for the expect . The stamp is
composed of a timestamp and the number of errors recorded so far .
Args :
error : Exception or signals . ExceptionRecord , the error to add .""" | self . _count += 1
self . _record . add_error ( 'expect@%s+%s' % ( time . time ( ) , self . _count ) , error ) |
def edterm ( trmtyp , source , target , et , fixref , abcorr , obsrvr , npts ) :
"""Compute a set of points on the umbral or penumbral terminator of
a specified target body , where the target shape is modeled as an
ellipsoid .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / edt... | trmtyp = stypes . stringToCharP ( trmtyp )
source = stypes . stringToCharP ( source )
target = stypes . stringToCharP ( target )
et = ctypes . c_double ( et )
fixref = stypes . stringToCharP ( fixref )
abcorr = stypes . stringToCharP ( abcorr )
obsrvr = stypes . stringToCharP ( obsrvr )
trgepc = ctypes . c_double ( )
o... |
def from2dBlocks ( arr ) :
"""input needs to be 4d array ( 2d array of 2d arrays )""" | s = arr . shape
s0 , s1 = s [ 0 ] * s [ 2 ] , s [ 1 ] * s [ 3 ]
return unblockshaped ( arr . reshape ( s [ 0 ] * s [ 1 ] , s [ 2 ] , s [ 3 ] ) , s0 , s1 ) |
def delete ( self ) :
"""Delete the link and free the resources""" | if not self . _created :
return
try :
node1 = self . _nodes [ 0 ] [ "node" ]
adapter_number1 = self . _nodes [ 0 ] [ "adapter_number" ]
port_number1 = self . _nodes [ 0 ] [ "port_number" ]
except IndexError :
return
try :
yield from node1 . delete ( "/adapters/{adapter_number}/ports/{port_number... |
def match_hail_sizes ( model_tracks , obs_tracks , track_pairings ) :
"""Given forecast and observed track pairings , maximum hail sizes are associated with each paired forecast storm
track timestep . If the duration of the forecast and observed tracks differ , then interpolation is used for the
intermediate ti... | unpaired = list ( range ( len ( model_tracks ) ) )
for p , pair in enumerate ( track_pairings ) :
model_track = model_tracks [ pair [ 0 ] ]
unpaired . remove ( pair [ 0 ] )
obs_track = obs_tracks [ pair [ 1 ] ]
obs_hail_sizes = np . array ( [ step [ obs_track . masks [ t ] == 1 ] . max ( ) for t , step ... |
def logp_gradient_of_set ( variable_set , calculation_set = None ) :
"""Calculates the gradient of the joint log posterior with respect to all the variables in variable _ set .
Calculation of the log posterior is restricted to the variables in calculation _ set .
Returns a dictionary of the gradients .""" | logp_gradients = { }
for variable in variable_set :
logp_gradients [ variable ] = logp_gradient ( variable , calculation_set )
return logp_gradients |
def __isValidZIP ( self , suffix ) :
"""Determine if the suffix is ` . zip ` format""" | if suffix and isinstance ( suffix , string_types ) :
if suffix . endswith ( ".zip" ) :
return True
return False |
def recarray_from_hdf5_group ( * args , ** kwargs ) :
"""Load a recarray from columns stored as separate datasets with an
HDF5 group .
Either provide an h5py group as a single positional argument ,
or provide two positional arguments giving the HDF5 file path and the
group node path within the file .
The ... | import h5py
h5f = None
if len ( args ) == 1 :
group = args [ 0 ]
elif len ( args ) == 2 :
file_path , node_path = args
h5f = h5py . File ( file_path , mode = 'r' )
try :
group = h5f [ node_path ]
except Exception as e :
h5f . close ( )
raise e
else :
raise ValueError ( 'b... |
def diskdata ( ) :
"""Get total disk size in GB .""" | p = os . popen ( "/bin/df -l -P" )
ddata = { }
tsize = 0
for line in p . readlines ( ) :
d = line . split ( )
if ( "/dev/sd" in d [ 0 ] or "/dev/hd" in d [ 0 ] or "/dev/mapper" in d [ 0 ] ) :
tsize = tsize + int ( d [ 1 ] )
ddata [ "Disk_GB" ] = int ( tsize ) / 1000000
p . close ( )
return ddata |
def load_pa11y_results ( stdout , spider , url ) :
"""Load output from pa11y , filtering out the ignored messages .
The ` stdout ` parameter is a bytestring , not a unicode string .""" | if not stdout :
return [ ]
results = json . loads ( stdout . decode ( 'utf8' ) )
ignore_rules = ignore_rules_for_url ( spider , url )
for rule in ignore_rules :
results = [ result for result in results if not ignore_rule_matches_result ( rule , result ) ]
return results |
def _cached_css_compile ( pattern , namespaces , custom , flags ) :
"""Cached CSS compile .""" | custom_selectors = process_custom ( custom )
return cm . SoupSieve ( pattern , CSSParser ( pattern , custom = custom_selectors , flags = flags ) . process_selectors ( ) , namespaces , custom , flags ) |
def _registrant_publication ( reg_pub , rules ) :
"""Separate the registration from the publication in a given
string .
: param reg _ pub : A string of digits representing a registration
and publication .
: param rules : A list of RegistrantRules which designate where
to separate the values in the string ... | for rule in rules :
if rule . min <= reg_pub <= rule . max :
reg_len = rule . registrant_length
break
else :
raise Exception ( 'Registrant/Publication not found in registrant ' 'rule list.' )
registrant , publication = reg_pub [ : reg_len ] , reg_pub [ reg_len : ]
return registrant , publication |
def sum_of_fifth_powers ( count : int ) -> int :
"""A python function that computes the sum of count natural numbers raised to the fifth power .
Args :
count ( int ) : number of natural numbers to included in the calculation .
Returns :
int : sum of the first ' count ' natural numbers raised to the fifth po... | total = 0
for num in range ( 1 , count + 1 ) :
total += num ** 5
return total |
def crl ( self ) :
"""Returns up to date CRL of this CA""" | revoked_certs = self . get_revoked_certs ( )
crl = crypto . CRL ( )
now_str = timezone . now ( ) . strftime ( generalized_time )
for cert in revoked_certs :
revoked = crypto . Revoked ( )
revoked . set_serial ( bytes_compat ( cert . serial_number ) )
revoked . set_reason ( b'unspecified' )
revoked . set... |
def _writeSedimentTable ( self , session , fileObject , mapTable , replaceParamFile ) :
"""Write Sediment Mapping Table Method
This method writes the sediments special mapping table case .""" | # Write the sediment mapping table header
fileObject . write ( '%s\n' % ( mapTable . name ) )
fileObject . write ( 'NUM_SED %s\n' % ( mapTable . numSed ) )
# Write the value header line
fileObject . write ( 'Sediment Description%sSpec. Grav%sPart. Dia%sOutput Filename\n' % ( ' ' * 22 , ' ' * 3 , ' ' * 5 ) )
# Retrive t... |
def login ( request , template_name = None , extra_context = None , ** kwargs ) :
"""Logs a user in using the : class : ` ~ openstack _ auth . forms . Login ` form .""" | # If the user enabled websso and the default redirect
# redirect to the default websso url
if ( request . method == 'GET' and utils . is_websso_enabled and utils . is_websso_default_redirect ( ) ) :
protocol = utils . get_websso_default_redirect_protocol ( )
region = utils . get_websso_default_redirect_region (... |
def invert ( self ) :
"""Invert the transform""" | libfn = utils . get_lib_fn ( 'inverseTransform%s' % ( self . _libsuffix ) )
inv_tx_ptr = libfn ( self . pointer )
new_tx = ANTsTransform ( precision = self . precision , dimension = self . dimension , transform_type = self . transform_type , pointer = inv_tx_ptr )
return new_tx |
def is_file ( package ) :
"""Determine if a package name is for a File dependency .""" | if hasattr ( package , "keys" ) :
return any ( key for key in package . keys ( ) if key in [ "file" , "path" ] )
if os . path . exists ( str ( package ) ) :
return True
for start in SCHEME_LIST :
if str ( package ) . startswith ( start ) :
return True
return False |
def path_regex ( self ) :
"""Return the regex for the path to the build folder .""" | if self . locale_build :
return self . build_list_regex
return '%s/' % urljoin ( self . build_list_regex , self . builds [ self . build_index ] ) |
def create_queue_service ( self ) :
'''Creates a QueueService object with the settings specified in the
CloudStorageAccount .
: return : A service object .
: rtype : : class : ` ~ azure . storage . queue . queueservice . QueueService `''' | try :
from azure . storage . queue . queueservice import QueueService
return QueueService ( self . account_name , self . account_key , sas_token = self . sas_token , is_emulated = self . is_emulated )
except ImportError :
raise Exception ( 'The package azure-storage-queue is required. ' + 'Please install it... |
def createMonitor ( self , callback = None , errback = None , ** kwargs ) :
"""Create a monitor""" | import ns1 . monitoring
monitor = ns1 . monitoring . Monitor ( self . config )
return monitor . create ( callback = callback , errback = errback , ** kwargs ) |
def set_enabled_scanners ( self , scanners ) :
"""Set only the provided scanners by group and / or IDs and disable all others .""" | self . logger . debug ( 'Disabling all current scanners' )
self . zap . ascan . disable_all_scanners ( )
self . enable_scanners ( scanners ) |
def readpartial ( self , start , end ) :
'Get a part of the file , from start byte to end byte ( integers )' | # return self . jfs . raw ( ' % s ? mode = bin ' % self . path ,
return self . jfs . raw ( url = self . path , params = { 'mode' : 'bin' } , # note that we deduct 1 from end because
# in http Range requests , the end value is included in the slice ,
# whereas in python , it is not
extra_headers = { 'Range' : 'bytes=%s-... |
def spawn ( spec , kwargs , pass_fds = ( ) ) :
"""Invoke a python function in a subprocess .""" | r , w = os . pipe ( )
for fd in [ r ] + list ( pass_fds ) :
set_inheritable ( fd , True )
preparation_data = get_preparation_data ( )
r_handle = get_handle ( r )
args , env = get_command_line ( pipe_handle = r_handle )
process = subprocess . Popen ( args , env = env , close_fds = False )
to_child = os . fdopen ( w ... |
def morphRange ( fromDataList , toDataList ) :
'''Changes the scale of values in one distribution to that of another
ie The maximum value in fromDataList will be set to the maximum value in
toDataList . The 75 % largest value in fromDataList will be set to the
75 % largest value in toDataList , etc .
Small ... | # Isolate and sort pitch values
fromPitchList = [ dataTuple [ 1 ] for dataTuple in fromDataList ]
toPitchList = [ dataTuple [ 1 ] for dataTuple in toDataList ]
fromPitchListSorted = sorted ( fromPitchList )
toPitchListSorted = sorted ( toPitchList )
# Bin pitch values between 0 and 1
fromListRel = makeSequenceRelative ... |
def post ( self , path , params = '' , data = None ) :
"""POST Method Wrapper of the REST API""" | self . result = None
data = data or { }
headers = { 'Content-Type' : 'application/json' , 'x-qx-client-application' : self . client_application }
url = str ( self . credential . config [ 'url' ] + path + '?access_token=' + self . credential . get_token ( ) + params )
retries = self . retries
while retries > 0 :
res... |
def iterator ( self , envelope ) :
""": meth : ` WMessengerOnionSessionFlowProto . iterator ` implementation""" | iterator = WMessengerOnionSessionFlowSequence . FlowSequenceIterator ( WMessengerOnionSessionFlowProto . IteratorInfo ( '' ) , * self . __flows )
return iterator . next ( envelope ) |
def set_root_logger_from_verbosity ( verbosity = 0 ) :
"""Configure root logger according to both application settings
and verbosity level .""" | kwargs = { }
if verbosity == 1 :
kwargs . update ( level = logging . INFO )
elif verbosity > 1 :
kwargs . update ( level = logging . DEBUG )
set_root_logger ( ** kwargs ) |
def get_settings ( ) :
"""This function returns a dict containing default settings""" | s = getattr ( settings , 'CLAMAV_UPLOAD' , { } )
s = { 'CONTENT_TYPE_CHECK_ENABLED' : s . get ( 'CONTENT_TYPE_CHECK_ENABLED' , False ) , # LAST _ HANDLER is not a user configurable option ; we return
# it with the settings dict simply because it ' s convenient .
'LAST_HANDLER' : getattr ( settings , 'FILE_UPLOAD_HANDLE... |
def patch ( self , url , data = None , ** kwargs ) :
"""Sends a PATCH request . Returns : class : ` Response ` object .
: param url : URL for the new : class : ` Request ` object .
: param data : ( optional ) Dictionary or bytes to send in the body of the : class : ` Request ` .
: param * * kwargs : Optional ... | return self . request ( 'patch' , url , data = data , ** kwargs ) |
def do_tree ( self , params ) :
"""\x1b [1mNAME \x1b [0m
tree - Print the tree under a given path
\x1b [1mSYNOPSIS \x1b [0m
tree [ path ] [ max _ depth ]
\x1b [1mOPTIONS \x1b [0m
* path : the path ( default : cwd )
* max _ depth : max recursion limit ( 0 is no limit ) ( default : 0)
\x1b [1mEXAMPLES \... | self . show_output ( "." )
for child , level in self . _zk . tree ( params . path , params . max_depth ) :
self . show_output ( u"%s├── %s" , u"│ " * level , child ) |
def help_center_category_update ( self , id , data , locale = None , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / help _ center / categories # update - category" | api_path = "/api/v2/help_center/categories/{id}.json"
api_path = api_path . format ( id = id )
if locale :
api_opt_path = "/api/v2/help_center/{locale}/categories/{id}.json"
api_path = api_opt_path . format ( id = id , locale = locale )
return self . call ( api_path , method = "PUT" , data = data , ** kwargs ) |
def has_space ( self , length = 1 , offset = 0 ) :
"""Returns boolean if self . pos + length < working string length .""" | return self . pos + ( length + offset ) - 1 < self . length |
def get_conversions ( self ) :
"""Extract Conversion INDRA Statements from the BioPAX model .
This method uses a custom BioPAX Pattern
( one that is not implemented PatternBox ) to query for
BiochemicalReactions whose left and right hand sides are collections
of SmallMolecules . This pattern thereby extract... | # NOTE : This pattern gets all reactions in which a protein is the
# controller and chemicals are converted . But with this pattern only
# a single chemical is extracted from each side . This can be misleading
# since we want to capture all inputs and all outputs of the
# conversion . So we need to step back to the con... |
def calc_cf_sm_v1 ( self ) :
"""Calculate capillary flow and update soil moisture .
Required control parameters :
| NmbZones |
| ZoneType |
| FC |
| CFlux |
Required fluxes sequence :
Required state sequence :
| UZ |
Calculated flux sequence :
| CF |
Updated state sequence :
| SM |
Basic e... | con = self . parameters . control . fastaccess
flu = self . sequences . fluxes . fastaccess
sta = self . sequences . states . fastaccess
for k in range ( con . nmbzones ) :
if con . zonetype [ k ] in ( FIELD , FOREST ) :
if con . fc [ k ] > 0. :
flu . cf [ k ] = con . cflux [ k ] * ( 1. - sta . ... |
def wait_for_focus ( self , title , timeOut = 5 ) :
"""Wait for window with the given title to have focus
Usage : C { window . wait _ for _ focus ( title , timeOut = 5 ) }
If the window becomes active , returns True . Otherwise , returns False if
the window has not become active by the time the timeout has el... | regex = re . compile ( title )
waited = 0
while waited <= timeOut :
if regex . match ( self . mediator . interface . get_window_title ( ) ) :
return True
if timeOut == 0 :
break
# zero length timeout , if not matched go straight to end
time . sleep ( 0.3 )
waited += 0.3
return False |
def render ( self , context = None , clean = False ) :
"""Render email with provided context
Arguments
context : dict
| context | If not specified then the
: attr : ` ~ mail _ templated . EmailMessage . context ` property is
used .
Keyword Arguments
clean : bool
If ` ` True ` ` , remove any template... | # Load template if it is not loaded yet .
if not self . template :
self . load_template ( self . template_name )
# The signature of the ` render ( ) ` method was changed in Django 1.7.
# https : / / docs . djangoproject . com / en / 1.8 / ref / templates / upgrading / # get - template - and - select - template
if h... |
def fetch_tokens ( self , client_id = None , client_secret = None , code = None , redirect_uri = None , ** kwargs ) :
"""Exchange authorization code for token .
Args :
client _ id ( str ) : OAuth2 client ID . Defaults to ` ` None ` ` .
client _ secret ( str ) : OAuth2 client secret . Defaults to ` ` None ` ` ... | client_id = client_id or self . client_id
client_secret = client_secret or self . client_secret
redirect_uri = redirect_uri or self . redirect_uri
data = { 'grant_type' : 'authorization_code' , 'client_id' : client_id , 'client_secret' : client_secret , 'code' : code , 'redirect_uri' : redirect_uri }
r = self . _httpcl... |
def _readmodule ( module , path , inpackage = None ) :
'''Do the hard work for readmodule [ _ ex ] .
If INPACKAGE is given , it must be the dotted name of the package in
which we are searching for a submodule , and then PATH must be the
package search path ; otherwise , we are searching for a top - level
mo... | # Compute the full module name ( prepending inpackage if set )
if inpackage is not None :
fullmodule = "%s.%s" % ( inpackage , module )
else :
fullmodule = module
# Check in the cache
if fullmodule in _modules :
return _modules [ fullmodule ]
# Initialize the dict for this module ' s contents
dict = Ordered... |
def as_node ( cls , obj ) :
"""Convert obj into a Node instance .
Return :
obj if obj is a Node instance ,
cast obj to : class : ` FileNode ` instance of obj is a string .
None if obj is None""" | if isinstance ( obj , cls ) :
return obj
elif is_string ( obj ) : # Assume filepath .
return FileNode ( obj )
elif obj is None :
return obj
else :
raise TypeError ( "Don't know how to convert %s to Node instance." % obj ) |
def slice ( self , key ) :
"""Slice Scene by dataset index .
. . note : :
DataArrays that do not have an ` ` area ` ` attribute will not be
sliced .""" | if not self . all_same_area :
raise RuntimeError ( "'Scene' has different areas and cannot " "be usefully sliced." )
# slice
new_scn = self . copy ( )
new_scn . wishlist = self . wishlist
for area , dataset_ids in self . iter_by_area ( ) :
if area is not None : # assume dimensions for area are y and x
o... |
def scorable_block_completion ( sender , ** kwargs ) : # pylint : disable = unused - argument
"""When a problem is scored , submit a new BlockCompletion for that block .""" | if not waffle . waffle ( ) . is_enabled ( waffle . ENABLE_COMPLETION_TRACKING ) :
return
course_key = CourseKey . from_string ( kwargs [ 'course_id' ] )
block_key = UsageKey . from_string ( kwargs [ 'usage_id' ] )
block_cls = XBlock . load_class ( block_key . block_type )
if XBlockCompletionMode . get_mode ( block_... |
def execute_command_with_connection ( self , context , command , * args ) :
"""Note : session & vcenter _ data _ model & reservation id objects will be injected dynamically to the command
: param command :
: param context : instance of ResourceCommandContext or AutoLoadCommandContext
: type context : cloudshe... | logger = self . context_based_logger_factory . create_logger_for_context ( logger_name = 'vCenterShell' , context = context )
if not command :
logger . error ( COMMAND_CANNOT_BE_NONE )
raise Exception ( COMMAND_CANNOT_BE_NONE )
try :
command_name = command . __name__
logger . info ( LOG_FORMAT . format ... |
def verify_repository ( self , repository , master_timeout = 10 , timeout = 10 , body = '' , params = { } , callback = None , ** kwargs ) :
"""Returns a list of nodes where repository was successfully verified or
an error message if verification process failed .
` < http : / / www . elasticsearch . org / guide ... | query_params = ( 'master_timeout' , 'timeout' , )
params = self . _filter_params ( query_params , params )
url = self . mk_url ( * [ '_snapshot' , repository , '_verify' ] , ** params )
self . client . fetch ( self . mk_req ( url , body = body , method = 'POST' , ** kwargs ) , callback = callback ) |
def assertTimeZoneEqual ( self , dt , tz , msg = None ) :
'''Fail unless ` ` dt ` ` ' s ` ` tzinfo ` ` attribute equals ` ` tz ` ` as
determined by the ' = = ' operator .
Parameters
dt : datetime
tz : timezone
msg : str
If not provided , the : mod : ` marbles . mixins ` or
: mod : ` unittest ` standar... | if not isinstance ( dt , datetime ) :
raise TypeError ( 'First argument is not a datetime object' )
if not isinstance ( tz , timezone ) :
raise TypeError ( 'Second argument is not a timezone object' )
self . assertEqual ( dt . tzinfo , tz , msg = msg ) |
def get_java_remote_console_url ( self , ip = None ) :
"""Generates a Single Sign - On ( SSO ) session for the iLO Java Applet console and returns the URL to launch it .
If the server hardware is unmanaged or unsupported , the resulting URL will not use SSO and the iLO Java Applet
will prompt for credentials . ... | uri = "{}/javaRemoteConsoleUrl" . format ( self . data [ "uri" ] )
if ip :
uri = "{}?ip={}" . format ( uri , ip )
return self . _helper . do_get ( uri ) |
def _extract ( self , raw : str , station : str = None ) -> str :
"""Extracts the report message from XML response""" | resp = parsexml ( raw )
try :
report = resp [ 'response' ] [ 'body' ] [ 'items' ] [ 'item' ] [ self . rtype . lower ( ) + 'Msg' ]
except KeyError :
raise self . make_err ( raw )
# Replace line breaks
report = report . replace ( '\n' , '' )
# Remove excess leading and trailing data
for item in ( self . rtype . u... |
def _zip ( self ) -> ArrayValue :
"""Zip the receiver into an array and return it .""" | res = list ( self . before )
res . reverse ( )
res . append ( self . value )
res . extend ( list ( self . after ) )
return ArrayValue ( res , self . timestamp ) |
def specific_file_rst_filename ( self , source_filename : str ) -> str :
"""Gets the RST filename corresponding to a source filename .
See the help for the constructor for more details .
Args :
source _ filename : source filename within current project
Returns :
RST filename
Note in particular : the way... | highest_code_to_target = relative_filename_within_dir ( source_filename , self . highest_code_dir )
bname = basename ( source_filename )
result = join ( self . autodoc_rst_root_dir , dirname ( highest_code_to_target ) , bname + EXT_RST )
log . debug ( "Source {!r} -> RST {!r}" , source_filename , result )
return result |
def ack ( self , tup ) :
"""Indicate that processing of a Tuple has succeeded .
: param tup : the Tuple to acknowledge .
: type tup : : class : ` str ` or : class : ` pystorm . component . Tuple `""" | tup_id = tup . id if isinstance ( tup , Tuple ) else tup
self . send_message ( { "command" : "ack" , "id" : tup_id } ) |
def get_resource_cache ( resourceid ) :
"""Get a cached dictionary related to an individual resourceid .
: param resourceid : String resource id .
: return : dict""" | if not resourceid :
raise ResourceInitError ( "Resource id missing" )
if not DutInformationList . _cache . get ( resourceid ) :
DutInformationList . _cache [ resourceid ] = dict ( )
return DutInformationList . _cache [ resourceid ] |
def close ( self ) :
"""Clean up NetworkTables listeners""" | NetworkTables . removeGlobalListener ( self . _nt_on_change )
NetworkTables . removeConnectionListener ( self . _nt_connected ) |
def _serialize_pages ( self ) :
"""Return a JSON API compliant pagination links section
If the paginator has a value for a given link then this
method will also add the same links to the response
objects ` link ` header according to the guidance of
RFC 5988.
Falcon has a native add _ link helper for formi... | pages = self . req . pages . to_dict ( )
links = { }
for key , val in pages . items ( ) :
if val :
params = self . req . params
params . update ( val )
links [ key ] = '%s?%s' % ( self . req . path , urlencode ( params ) )
self . resp . add_link ( links [ key ] , key )
else :
... |
def subscribe ( self , stream_type , ** parameters ) :
"""Subscribe to stream with give parameters .""" | parameters [ "stream_type" ] = stream_type
if ( stream_type == "result" ) and ( "buffering" not in parameters ) :
parameters [ "buffering" ] = True
self . socketIO . emit ( self . EVENT_NAME_SUBSCRIBE , parameters ) |
def create_collection ( self , name , codec_options = None , read_preference = None , write_concern = None , read_concern = None , ** kwargs ) :
"""Create a new : class : ` ~ pymongo . collection . Collection ` in this
database .
Normally collection creation is automatic . This method should
only be used to s... | if name in self . collection_names ( ) :
raise CollectionInvalid ( "collection %s already exists" % name )
return Collection ( self , name , True , codec_options , read_preference , write_concern , read_concern , ** kwargs ) |
def generate_public_ssh_key ( ssh_private_key_file ) :
"""Generate SSH public key from private key file .""" | try :
with open ( ssh_private_key_file , "rb" ) as key_file :
key = key_file . read ( )
except FileNotFoundError :
raise IpaUtilsException ( 'SSH private key file: %s cannot be found.' % ssh_private_key_file )
try :
private_key = serialization . load_pem_private_key ( key , password = None , backend... |
def kill_workflow ( self ) :
'''Kills the workflow .
See also
: func : ` tmserver . api . workflow . kill _ workflow `
: class : ` tmlib . workflow . workflow . Workflow `''' | logger . info ( 'kill workflow of experiment "%s"' , self . experiment_name )
content = dict ( )
url = self . _build_api_url ( '/experiments/{experiment_id}/workflow/kill' . format ( experiment_id = self . _experiment_id ) )
res = self . _session . post ( url )
res . raise_for_status ( ) |
def find_clique_embedding ( k , m = None , target_graph = None ) :
"""Find an embedding of a k - sized clique on a Pegasus graph ( target _ graph ) .
This clique is found by transforming the Pegasus graph into a K2,2 Chimera graph and then
applying a Chimera clique finding algorithm . The results are then conve... | # Organize parameter values
if target_graph is None :
if m is None :
raise TypeError ( "m and target_graph cannot both be None." )
target_graph = pegasus_graph ( m )
m = target_graph . graph [ 'rows' ]
# We only support square Pegasus graphs
_ , nodes = k
# Deal with differences in ints vs coordinate ta... |
def resolve_name ( name ) :
"""Resolve a dotted name to some object ( usually class , module , or function ) .
Supported naming formats include :
1 . path . to . module : method
2 . path . to . module . ClassName
> > > resolve _ name ( ' coilmq . store . memory . MemoryQueue ' )
< class ' coilmq . store .... | if ':' in name : # Normalize foo . bar . baz : main to foo . bar . baz . main
# ( since our logic below will handle that )
name = '%s.%s' % tuple ( name . split ( ':' ) )
name = name . split ( '.' )
used = name . pop ( 0 )
found = __import__ ( used )
for n in name :
used = used + '.' + n
try :
found... |
def create ( self , chat_id = None , name = None , owner = None , user_list = None ) :
"""创建群聊会话
详情请参考
https : / / work . weixin . qq . com / api / doc # 90000/90135/90245
限制说明 :
只允许企业自建应用调用 , 且应用的可见范围必须是根部门 ;
群成员人数不可超过管理端配置的 “ 群成员人数上限 ” , 且最大不可超过500人 ;
每企业创建群数不可超过1000 / 天 ;
: param chat _ id : 群聊的唯一标... | data = optionaldict ( chatid = chat_id , name = name , owner = owner , userlist = user_list , )
return self . _post ( 'appchat/create' , data = data ) |
def Rmarkdown ( script = None , input = None , output = None , args = '{input:r}, output_file={output:ar}' , ** kwargs ) :
'''Convert input file to output using Rmarkdown
The input can be specified in three ways :
1 . instant script , which is assumed to be in md format
Rmarkdown : output = ' report . html ' ... | if not R_library ( 'rmarkdown' ) . target_exists ( ) :
raise RuntimeError ( 'Library rmarkdown does not exist' )
input = sos_targets ( collect_input ( script , input ) )
output = sos_targets ( output )
if len ( output ) == 0 :
write_to_stdout = True
output = sos_targets ( tempfile . NamedTemporaryFile ( mod... |
def _get_path_for_op_id ( self , id : str ) -> Optional [ str ] :
"""Searches the spec for a path matching the operation id .
Args :
id : operation id
Returns :
path to the endpoint , or None if not found""" | for path_key , path_value in self . _get_spec ( ) [ 'paths' ] . items ( ) :
for method in self . METHODS :
if method in path_value :
if self . OPERATION_ID_KEY in path_value [ method ] :
if path_value [ method ] [ self . OPERATION_ID_KEY ] == id :
return path_... |
def getNetworkName ( self ) :
"""get Thread Network name""" | print '%s call getNetworkname' % self . port
networkName = self . __sendCommand ( WPANCTL_CMD + 'getprop -v Network:Name' ) [ 0 ]
return self . __stripValue ( networkName ) |
def address_exclude ( self , other ) :
"""Remove an address from a larger block .
For example :
addr1 = IPNetwork ( ' 10.1.1.0/24 ' )
addr2 = IPNetwork ( ' 10.1.1.0/26 ' )
addr1 . address _ exclude ( addr2 ) =
[ IPNetwork ( ' 10.1.1.64/26 ' ) , IPNetwork ( ' 10.1.1.128/25 ' ) ]
or IPv6:
addr1 = IPNetw... | if not self . _version == other . _version :
raise TypeError ( "%s and %s are not of the same version" % ( str ( self ) , str ( other ) ) )
if not isinstance ( other , _BaseNet ) :
raise TypeError ( "%s is not a network object" % str ( other ) )
if other not in self :
raise ValueError ( '%s not contained in... |
def remove_dups ( seq ) :
"""remove duplicates from a sequence , preserving order""" | seen = set ( )
seen_add = seen . add
return [ x for x in seq if not ( x in seen or seen_add ( x ) ) ] |
def eeg_select_channels ( raw , channel_names ) :
"""Select one or several channels by name and returns them in a dataframe .
Parameters
raw : mne . io . Raw
Raw EEG data .
channel _ names : str or list
Channel ' s name ( s ) .
Returns
channels : pd . DataFrame
Channel .
Example
> > > import neu... | if isinstance ( channel_names , list ) is False :
channel_names = [ channel_names ]
channels , time_index = raw . copy ( ) . pick_channels ( channel_names ) [ : ]
if len ( channel_names ) > 1 :
channels = pd . DataFrame ( channels . T , columns = channel_names )
else :
channels = pd . Series ( channels [ 0 ... |
def itervalues ( d , ** kw ) :
"""Return an iterator over the values of a dictionary .""" | if not PY2 :
return iter ( d . values ( ** kw ) )
return d . itervalues ( ** kw ) |
def open_handle ( self , dwDesiredAccess = win32 . PROCESS_ALL_ACCESS ) :
"""Opens a new handle to the process .
The new handle is stored in the L { hProcess } property .
@ warn : Normally you should call L { get _ handle } instead , since it ' s much
" smarter " and tries to reuse handles and merge access ri... | hProcess = win32 . OpenProcess ( dwDesiredAccess , win32 . FALSE , self . dwProcessId )
try :
self . close_handle ( )
except Exception :
warnings . warn ( "Failed to close process handle: %s" % traceback . format_exc ( ) )
self . hProcess = hProcess |
def find_orphans ( model ) :
"""Return metabolites that are only consumed in reactions .
Metabolites that are involved in an exchange reaction are never
considered to be orphaned .
Parameters
model : cobra . Model
The metabolic model under investigation .""" | exchange = frozenset ( model . exchanges )
return [ met for met in model . metabolites if ( len ( met . reactions ) > 0 ) and all ( ( not rxn . reversibility ) and ( rxn not in exchange ) and ( rxn . metabolites [ met ] < 0 ) for rxn in met . reactions ) ] |
def _is_deserialized ( cls , cls_target , obj ) :
""": type cls _ target : type
: type obj : int | str | bool | float | bytes | unicode | list | dict | object
: rtype : bool""" | if cls_target is None :
return True
if cls_target in { list , dict } :
return True
if cls . _is_bytes_type ( cls_target ) :
return True
if obj is None :
return True
if type ( obj ) in { list , cls_target } :
return True
return False |
def hostname ( ) :
'''Return fqdn , hostname , domainname''' | # This is going to need some work
# Provides :
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = { }
if salt . utils . platform . is_proxy ( ) :
return grains
grains [ 'localhost' ] = socket . gethostname ( )
if __FQDN__ is None :
__FQDN__ = salt . utils . network . get_fqhostname ( )
# On some distro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.