signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _get_localized_field_checks ( self ) :
"""Get the checks we must perform for the localized fields .""" | localized_fields_checks = [ ]
for localized_field in self . instance . localized_fields :
if self . cleaned_data . get ( localized_field ) is None :
continue
f = getattr ( self . instance . __class__ , localized_field , None )
if f and f . unique :
if f . unique :
local_name = ge... |
def cache_url ( self , var = DEFAULT_CACHE_ENV , default = NOTSET , backend = None ) :
"""Returns a config dictionary , defaulting to CACHE _ URL .
: rtype : dict""" | return self . cache_url_config ( self . url ( var , default = default ) , backend = backend ) |
def getContainer ( name_or_id ) :
'''Get the container with the given name or ID ( str ) . No side effects .
Idempotent . Returns None if the container does not exist . Otherwise , the
continer is returned''' | require_str ( "name_or_id" , name_or_id )
container = None
try :
container = client . containers . get ( name_or_id )
except NotFound as exc : # Return None when the container is not found
pass
except APIError as exc :
eprint ( "Unhandled error" )
raise exc
return container |
def force_invalidate ( self , cache_key ) :
"""Force - invalidate the cached item .""" | try :
if self . cacheable ( cache_key ) :
os . unlink ( self . _sha_file ( cache_key ) )
except OSError as e :
if e . errno != errno . ENOENT :
raise |
def float_input ( message , low , high ) :
'''Ask a user for a float input between two values
args :
message ( str ) : Prompt for user
low ( float ) : Low value , user entered value must be > this value to be accepted
high ( float ) : High value , user entered value must be < this value to be accepted
ret... | float_in = low - 1.0
while ( float_in < low ) or ( float_in > high ) :
inp = input ( 'Enter a ' + message + ' (float between ' + str ( low ) + ' and ' + str ( high ) + '): ' )
if re . match ( '^([0-9]*[.])?[0-9]+$' , inp ) is not None :
float_in = float ( inp )
else :
print ( colored ( 'Must... |
def _get_prefixes ( self , metric_type ) :
"""Get prefixes where applicable
Add metric prefix counters , timers respectively if
: attr : ` prepend _ metric _ type ` flag is True .
: param str metric _ type : The metric type
: rtype : list""" | prefixes = [ ]
if self . _prepend_metric_type :
prefixes . append ( self . METRIC_TYPES [ metric_type ] )
return prefixes |
def updateAfterDecorator ( function ) :
"""Function updateAfterDecorator
Decorator to ensure local dict is sync with remote foreman""" | def _updateAfterDecorator ( self , * args , ** kwargs ) :
ret = function ( self , * args , ** kwargs )
self . reload ( )
return ret
return _updateAfterDecorator |
def get ( ctx , uri ) :
"""Perform an HTTP GET of the provided URI
The URI provided is relative to the / ws base to allow for easy navigation of
the resources exposed by the WVA . Example Usage : :
$ wva get /
{ ' ws ' : [ ' vehicle ' ,
' hw ' ,
' config ' ,
' state ' ,
' files ' ,
' alarms ' ,
... | http_client = get_wva ( ctx ) . get_http_client ( )
cli_pprint ( http_client . get ( uri ) ) |
def processor ( status , sender , instance , updated = None , addition = '' ) :
"""This is the standard logging processor .
This is used to send the log to the handler and to other systems .""" | logger = logging . getLogger ( __name__ )
if validate_instance ( instance ) :
user = get_current_user ( )
application = instance . _meta . app_label
model_name = instance . __class__ . __name__
level = settings . AUTOMATED_LOGGING [ 'loglevel' ] [ 'model' ]
if status == 'change' :
corrected ... |
def __safe_name ( self , method_name ) :
"""Restrict method name to a - zA - Z0-9 _ , first char lowercase .""" | # Endpoints backend restricts what chars are allowed in a method name .
safe_name = re . sub ( r'[^\.a-zA-Z0-9_]' , '' , method_name )
# Strip any number of leading underscores .
safe_name = safe_name . lstrip ( '_' )
# Ensure the first character is lowercase .
# Slice from 0:1 rather than indexing [ 0 ] in case safe _... |
def render_response ( self , ** kwargs ) :
"""Render the graph , and return a Flask response""" | from flask import Response
return Response ( self . render ( ** kwargs ) , mimetype = 'image/svg+xml' ) |
def _start_enqueue_thread ( self ) :
"""Internal method to start the enqueue thread which adds the events in an internal queue .""" | self . _enqueueThreadSignal . acquire ( )
self . _enqueueThread = Thread ( target = self . _enqueue_function )
self . _enqueueThread . daemon = True
self . _enqueueThread . start ( )
self . _enqueueThreadSignal . wait ( )
self . _enqueueThreadSignal . release ( ) |
def asok ( cluster , hostname ) :
"""Example usage : :
> > > from ceph _ deploy . util . paths import mon
> > > mon . asok ( ' mycluster ' , ' myhostname ' )
/ var / run / ceph / mycluster - mon . myhostname . asok""" | asok_file = '%s-mon.%s.asok' % ( cluster , hostname )
return join ( constants . base_run_path , asok_file ) |
def append ( self , item ) :
"""Try to add an item to this element .
If the item is of the wrong type , and if this element has a sub - type ,
then try to create such a sub - type and insert the item into that , instead .
This happens recursively , so ( in python - markup ) :
L [ u ' Foo ' ]
actually crea... | okay = True
if not isinstance ( item , self . contentType ) :
if hasattr ( self . contentType , 'contentType' ) :
try :
item = self . contentType ( content = [ item ] )
except TypeError :
okay = False
else :
okay = False
if not okay :
raise TypeError ( "Wrong ... |
def postponed_to ( self ) :
"""Date that the event was postponed to ( in the local time zone ) .""" | toDate = getLocalDate ( self . date , self . time_from , self . tz )
return dateFormat ( toDate ) |
def convert_dist ( feed : "Feed" , new_dist_units : str ) -> "Feed" :
"""Convert the distances recorded in the ` ` shape _ dist _ traveled ` `
columns of the given Feed to the given distance units .
New distance units must lie in : const : ` . constants . DIST _ UNITS ` .
Return the resulting feed .""" | feed = feed . copy ( )
if feed . dist_units == new_dist_units : # Nothing to do
return feed
old_dist_units = feed . dist_units
feed . dist_units = new_dist_units
converter = hp . get_convert_dist ( old_dist_units , new_dist_units )
if hp . is_not_null ( feed . stop_times , "shape_dist_traveled" ) :
feed . stop_... |
def _merge_layout ( x : go . Layout , y : go . Layout ) -> go . Layout :
"""Merge attributes from two layouts .""" | xjson = x . to_plotly_json ( )
yjson = y . to_plotly_json ( )
if 'shapes' in yjson and 'shapes' in xjson :
xjson [ 'shapes' ] += yjson [ 'shapes' ]
yjson . update ( xjson )
return go . Layout ( yjson ) |
def qos_rcv_queue_multicast_rate_limit_limit ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
qos = ET . SubElement ( config , "qos" , xmlns = "urn:brocade.com:mgmt:brocade-qos" )
rcv_queue = ET . SubElement ( qos , "rcv-queue" )
multicast = ET . SubElement ( rcv_queue , "multicast" )
rate_limit = ET . SubElement ( multicast , "rate-limit" )
limit = ET . SubElement ( rate_limi... |
def deriv2 ( self , p ) :
"""Second derivative of the link function g ' ' ( p )
implemented through numerical differentiation""" | from statsmodels . tools . numdiff import approx_fprime
p = np . atleast_1d ( p )
# Note : special function for norm . ppf does not support complex
return np . diag ( approx_fprime ( p , self . deriv , centered = True ) ) |
def deserialize ( self , value , ** kwargs ) :
"""Deserialization of value .
: return : Deserialized value .
: raises : : class : ` halogen . exception . ValidationError ` exception if value is not valid .""" | for validator in self . validators :
validator . validate ( value , ** kwargs )
return value |
def random_secret_exponent ( curve_order ) :
"""Generates a random secret exponent .""" | # run a rejection sampling algorithm to ensure the random int is less
# than the curve order
while True : # generate a random 256 bit hex string
random_hex = hexlify ( dev_urandom_entropy ( 32 ) )
random_int = int ( random_hex , 16 )
if random_int >= 1 and random_int < curve_order :
break
return ran... |
def query_row ( stmt , args = ( ) , factory = None ) :
"""Execute a query . Returns the first row of the result set , or ` None ` .""" | for row in query ( stmt , args , factory ) :
return row
return None |
def _convert_xml_to_service_properties ( xml ) :
'''< ? xml version = " 1.0 " encoding = " utf - 8 " ? >
< StorageServiceProperties >
< Logging >
< Version > version - number < / Version >
< Delete > true | false < / Delete >
< Read > true | false < / Read >
< Write > true | false < / Write >
< Retent... | service_properties_element = ETree . fromstring ( xml )
service_properties = ServiceProperties ( )
# Logging
logging = service_properties_element . find ( 'Logging' )
if logging is not None :
service_properties . logging = Logging ( )
service_properties . logging . version = logging . find ( 'Version' ) . text
... |
def terminal_type ( cls ) :
"""returns darwin , cygwin , cmd , or linux""" | what = sys . platform
kind = 'UNDEFINED_TERMINAL_TYPE'
if 'linux' in what :
kind = 'linux'
elif 'darwin' in what :
kind = 'darwin'
elif 'cygwin' in what :
kind = 'cygwin'
elif 'windows' in what :
kind = 'windows'
return kind |
def _create_response_future ( self , query , parameters , trace , custom_payload , timeout , execution_profile = EXEC_PROFILE_DEFAULT , paging_state = None , host = None ) :
"""Returns the ResponseFuture before calling send _ request ( ) on it""" | prepared_statement = None
if isinstance ( query , six . string_types ) :
query = SimpleStatement ( query )
elif isinstance ( query , PreparedStatement ) :
query = query . bind ( parameters )
if self . cluster . _config_mode == _ConfigMode . LEGACY :
if execution_profile is not EXEC_PROFILE_DEFAULT :
... |
def delete ( self , obj ) :
"""Returns
object : full copy of new obj""" | full = deepcopy ( obj )
frag = full
parts , last = self . parts [ : - 1 ] , self . parts [ - 1 ]
for part in parts :
if isinstance ( frag , dict ) :
frag = frag [ part ]
elif isinstance ( frag , ( list , tuple ) ) :
frag = frag [ int ( part ) ]
if isinstance ( frag , dict ) :
frag . pop ( la... |
def load ( self , context ) :
"""Returns the debugger plugin , if possible .
Args :
context : The TBContext flags including ` add _ arguments ` .
Returns :
A DebuggerPlugin instance or None if it couldn ' t be loaded .""" | if not ( context . flags . debugger_data_server_grpc_port > 0 or context . flags . debugger_port > 0 ) :
return None
flags = context . flags
try : # pylint : disable = g - import - not - at - top , unused - import
import tensorflow
except ImportError :
raise ImportError ( 'To use the debugger plugin, you ne... |
def logpt ( self , t , xp , x ) :
"""PDF of X _ t | X _ { t - 1 } = xp""" | return self . ssm . PX ( t , xp ) . logpdf ( x ) |
def from_dict ( self , document ) :
"""Create functional data object from JSON document retrieved from
database .
Parameters
document : JSON
Json document in database
Returns
FunctionalDataHandle
Handle for functional data object""" | identifier = str ( document [ '_id' ] )
active = document [ 'active' ]
# The directory is not materilaized in database to allow moving the
# base directory without having to update the database .
directory = os . path . join ( self . directory , identifier )
timestamp = datetime . datetime . strptime ( document [ 'time... |
def stash ( cwd , action = 'save' , opts = '' , git_opts = '' , user = None , password = None , ignore_retcode = False , output_encoding = None ) :
'''Interface to ` git - stash ( 1 ) ` _ , returns the stdout from the git command
cwd
The path to the git checkout
opts
Any additional options to add to the com... | cwd = _expand_path ( cwd , user )
command = [ 'git' ] + _format_git_opts ( git_opts )
command . extend ( [ 'stash' , action ] )
command . extend ( _format_opts ( opts ) )
return _git_run ( command , cwd = cwd , user = user , password = password , ignore_retcode = ignore_retcode , output_encoding = output_encoding ) [ '... |
def Boolean ( v ) :
"""Convert human - readable boolean values to a bool .
Accepted values are 1 , true , yes , on , enable , and their negatives .
Non - string values are cast to bool .
> > > validate = Schema ( Boolean ( ) )
> > > validate ( True )
True
> > > validate ( " 1 " )
True
> > > validate... | if isinstance ( v , basestring ) :
v = v . lower ( )
if v in ( '1' , 'true' , 'yes' , 'on' , 'enable' ) :
return True
if v in ( '0' , 'false' , 'no' , 'off' , 'disable' ) :
return False
raise ValueError
return bool ( v ) |
def prepend_multi ( self , keys , format = None , persist_to = 0 , replicate_to = 0 ) :
"""Prepend to multiple keys . Multi variant of : meth : ` prepend `
. . seealso : : : meth : ` prepend ` , : meth : ` upsert _ multi ` , : meth : ` upsert `""" | return _Base . prepend_multi ( self , keys , format = format , persist_to = persist_to , replicate_to = replicate_to ) |
def subscribe_async ( self , subject , ** kwargs ) :
"""Schedules callback from subscription to be processed asynchronously
in the next iteration of the loop .""" | kwargs [ "is_async" ] = True
sid = yield self . subscribe ( subject , ** kwargs )
raise tornado . gen . Return ( sid ) |
def read_collection_from_yaml ( desired_type : Type [ Any ] , file_object : TextIOBase , logger : Logger , conversion_finder : ConversionFinder , fix_imports : bool = True , errors : str = 'strict' , ** kwargs ) -> Any :
"""Parses a collection from a yaml file .
: param desired _ type :
: param file _ object : ... | res = yaml . load ( file_object )
# convert if required
return ConversionFinder . convert_collection_values_according_to_pep ( res , desired_type , conversion_finder , logger , ** kwargs ) |
def findbeam_Guinier ( data , orig_initial , mask , rmin , rmax , maxiter = 100 , extent = 10 , callback = None ) :
"""Find the beam by minimizing the width of a Gaussian centered at the
origin ( i . e . maximizing the radius of gyration in a Guinier scattering ) .
Inputs :
data : scattering matrix
orig _ i... | orig_initial = np . array ( orig_initial )
mask = 1 - mask . astype ( np . uint8 )
data = data . astype ( np . double )
pix = np . arange ( rmin * 1.0 , rmax * 1.0 , 1 )
pix2 = pix ** 2
def targetfunc ( orig , data , mask , orig_orig , callback ) :
I = radintpix ( data , None , orig [ 0 ] + orig_orig [ 0 ] , orig [... |
async def sendPhoto ( self , chat_id , photo , caption = None , parse_mode = None , disable_notification = None , reply_to_message_id = None , reply_markup = None ) :
"""See : https : / / core . telegram . org / bots / api # sendphoto
: param photo :
- string : ` ` file _ id ` ` for a photo existing on Telegram... | p = _strip ( locals ( ) , more = [ 'photo' ] )
return await self . _api_request_with_file ( 'sendPhoto' , _rectify ( p ) , 'photo' , photo ) |
def _make_compile_argv ( self , compile_request ) :
"""Return a list of arguments to use to compile sources . Subclasses can override and append .""" | sources_minus_headers = list ( self . _iter_sources_minus_headers ( compile_request ) )
if len ( sources_minus_headers ) == 0 :
raise self . _HeaderOnlyLibrary ( )
compiler = compile_request . compiler
compiler_options = compile_request . compiler_options
# We are going to execute in the target output , so get abso... |
def _validate_molecule_env_var ( self , molecule_env_var , field , value ) :
"""Readonly but with a custom error .
The rule ' s arguments are validated against this schema :
{ ' type ' : ' boolean ' }""" | # TODO ( retr0h ) : This needs to be better handled .
pattern = r'^[{$]+MOLECULE[_a-z0-9A-Z]+[}]*$'
if molecule_env_var :
if re . match ( pattern , value ) :
msg = ( 'cannot reference $MOLECULE special variables ' 'in this section' )
self . _error ( field , msg ) |
def insertItem ( self , childItem , position = None , parentIndex = None ) :
"""Inserts a childItem before row ' position ' under the parent index .
If position is None the child will be appended as the last child of the parent .
Returns the index of the new inserted child .""" | if parentIndex is None :
parentIndex = QtCore . QModelIndex ( )
parentItem = self . getItem ( parentIndex , altItem = self . invisibleRootItem )
nChildren = parentItem . nChildren ( )
if position is None :
position = nChildren
assert 0 <= position <= nChildren , "position should be 0 < {} <= {}" . format ( posi... |
def parse_response ( self , request ) :
"""Internal method .
Parse data received from server . If REQUEST is not None
true is returned if the request with that serial number
was received , otherwise false is returned .
If REQUEST is - 1 , we ' re parsing the server connection setup
response .""" | if request == - 1 :
return self . parse_connection_setup ( )
# Parse ordinary server response
gotreq = 0
while 1 :
if self . data_recv : # Check the first byte to find out what kind of response it is
rtype = byte2int ( self . data_recv )
# Are we ' re waiting for additional data for the current pack... |
def remove_child_repositories ( self , repository_id ) :
"""Removes all children from a repository .
arg : repository _ id ( osid . id . Id ) : the ` ` Id ` ` of a repository
raise : NotFound - ` ` repository _ id ` ` not in hierarchy
raise : NullArgument - ` ` repository _ id ` ` is ` ` null ` `
raise : Op... | # Implemented from template for
# osid . resource . BinHierarchyDesignSession . remove _ child _ bin _ template
if self . _catalog_session is not None :
return self . _catalog_session . remove_child_catalogs ( catalog_id = repository_id )
return self . _hierarchy_session . remove_children ( id_ = repository_id ) |
def file_tree ( start_path ) :
"""Create a nested dictionary that represents the folder structure of ` start _ path ` .
Liberally adapted from
http : / / code . activestate . com / recipes / 577879 - create - a - nested - dictionary - from - oswalk /""" | nested_dirs = { }
root_dir = start_path . rstrip ( os . sep )
start = root_dir . rfind ( os . sep ) + 1
for path , dirs , files in os . walk ( root_dir ) :
folders = path [ start : ] . split ( os . sep )
subdir = dict . fromkeys ( files )
parent = reduce ( dict . get , folders [ : - 1 ] , nested_dirs )
... |
def start ( self , request : Request ) -> Response :
'''Start a file or directory listing download .
Args :
request : Request .
Returns :
A Response populated with the initial data connection reply .
Once the response is received , call : meth : ` download ` .
Coroutine .''' | if self . _session_state != SessionState . ready :
raise RuntimeError ( 'Session not ready' )
response = Response ( )
yield from self . _prepare_fetch ( request , response )
response . file_transfer_size = yield from self . _fetch_size ( request )
if request . restart_value :
try :
yield from self . _co... |
async def page_view ( self , url : str , title : str , user_id : str , user_lang : str = '' ) -> None :
"""Log a page view .
: param url : URL of the " page "
: param title : Title of the " page "
: param user _ id : ID of the user seeing the page .
: param user _ lang : Current language of the UI .""" | ga_url = 'https://www.google-analytics.com/collect'
args = { 'v' : '1' , 'ds' : 'web' , 'de' : 'UTF-8' , 'tid' : self . ga_id , 'cid' : self . hash_user_id ( user_id ) , 't' : 'pageview' , 'dh' : self . ga_domain , 'dp' : url , 'dt' : title , }
if user_lang :
args [ 'ul' ] = user_lang
logger . debug ( 'GA settings ... |
def make_err ( self , errtype , message , original , loc , ln = None , reformat = True , * args , ** kwargs ) :
"""Generate an error of the specified type .""" | if ln is None :
ln = self . adjust ( lineno ( loc , original ) )
errstr , index = getline ( loc , original ) , col ( loc , original ) - 1
if reformat :
errstr , index = self . reformat ( errstr , index )
return errtype ( message , errstr , index , ln , * args , ** kwargs ) |
def _calc_size_stats ( self ) :
"""get the size in bytes and num records of the content""" | self . total_records = 0
self . total_length = 0
self . total_nodes = 0
if type ( self . content [ 'data' ] ) is dict :
self . total_length += len ( str ( self . content [ 'data' ] ) )
self . total_records += 1
self . total_nodes = sum ( len ( x ) for x in self . content [ 'data' ] . values ( ) )
elif hasat... |
def setDragTable ( self , table ) :
"""Sets the table that will be linked with the drag query for this
record . This information will be added to the drag & drop information
when this record is dragged from the tree and will be set into
the application / x - table format for mime data .
: sa setDragQuery , ... | if table and table . schema ( ) :
self . setDragData ( 'application/x-orb-table' , table . schema ( ) . name ( ) )
else :
self . setDragData ( 'application/x-orb-table' , None ) |
def set_source_variable ( self , source_id , variable , value ) :
"""Change the value of a source variable .""" | source_id = int ( source_id )
return self . _send_cmd ( "SET S[%d].%s=\"%s\"" % ( source_id , variable , value ) ) |
def click_absolute ( self , x , y , button ) :
"""Send a mouse click relative to the screen ( absolute )
Usage : C { mouse . click _ absolute ( x , y , button ) }
@ param x : x - coordinate in pixels , relative to upper left corner of window
@ param y : y - coordinate in pixels , relative to upper left corner... | self . interface . send_mouse_click ( x , y , button , False ) |
def add_size_info ( self ) :
"""Get size of URL content from HTTP header .""" | if self . headers and "Content-Length" in self . headers and "Transfer-Encoding" not in self . headers : # Note that content - encoding causes size differences since
# the content data is always decoded .
try :
self . size = int ( self . getheader ( "Content-Length" ) )
except ( ValueError , OverflowErr... |
def comment_thread ( context , parent ) :
"""Return a list of child comments for the given parent , storing all
comments in a dict in the context when first called , using parents
as keys for retrieval on subsequent recursive calls from the
comments template .""" | if "all_comments" not in context :
comments = defaultdict ( list )
if "request" in context and context [ "request" ] . user . is_staff :
comments_queryset = parent . comments . all ( )
else :
comments_queryset = parent . comments . visible ( )
for comment in comments_queryset . select_re... |
def _serialize ( self , zenpy_object ) :
"""Serialize a Zenpy object to JSON""" | # If it ' s a dict this object has already been serialized .
if not type ( zenpy_object ) == dict :
log . debug ( "Setting dirty object: {}" . format ( zenpy_object ) )
self . _dirty_object = zenpy_object
return json . loads ( json . dumps ( zenpy_object , default = json_encode_for_zendesk ) ) |
def submitQuest ( self ) :
"""Submits the active quest , returns result
Returns
bool - True if successful , otherwise False""" | form = pg . form ( action = "kitchen2.phtml" )
pg = form . submit ( )
if "Woohoo" in pg . content :
try :
self . prize = pg . find ( text = "The Chef waves his hands, and you may collect your prize..." ) . parent . parent . find_all ( "b" ) [ - 1 ] . text
except Exception :
logging . getLogger (... |
def _decrypt_and_extract ( self , fname ) :
'''This does the extraction ( e . g . , it decrypts the image and writes it to a new file on disk ) .''' | with open ( fname , "r" ) as fp_in :
encrypted_data = fp_in . read ( )
decrypted_data = self . _hilink_decrypt ( encrypted_data )
with open ( binwalk . core . common . unique_file_name ( fname [ : - 4 ] , "dec" ) , "w" ) as fp_out :
fp_out . write ( decrypted_data ) |
async def src_reload ( app , path : str = None ) :
"""prompt each connected browser to reload by sending websocket message .
: param path : if supplied this must be a path relative to app [ ' static _ path ' ] ,
eg . reload of a single file is only supported for static resources .
: return : number of sources... | cli_count = len ( app [ WS ] )
if cli_count == 0 :
return 0
is_html = None
if path :
path = str ( Path ( app [ 'static_url' ] ) / Path ( path ) . relative_to ( app [ 'static_path' ] ) )
is_html = mimetypes . guess_type ( path ) [ 0 ] == 'text/html'
reloads = 0
aux_logger . debug ( 'prompting source reload f... |
def anchor_id ( self ) :
"""Yields the anchor tag as parsed from the original token .
Chunks that are anchors have a tag with an " A " prefix ( e . g . , " A1 " ) .
Chunks that are PNP attachmens ( or chunks inside a PNP ) have " P " ( e . g . , " P1 " ) .
Chunks inside a PNP can be both anchor and attachment... | id = ""
f = lambda ch : filter ( lambda k : self . sentence . _anchors [ k ] == ch , self . sentence . _anchors )
if self . pnp and self . pnp . anchor :
id += "-" + "-" . join ( f ( self . pnp ) )
if self . anchor :
id += "-" + "-" . join ( f ( self ) )
if self . attachments :
id += "-" + "-" . join ( f ( ... |
def assert_looks_like ( first , second , msg = None ) :
"""Compare two strings if all contiguous whitespace is coalesced .""" | first = _re . sub ( "\s+" , " " , first . strip ( ) )
second = _re . sub ( "\s+" , " " , second . strip ( ) )
if first != second :
raise AssertionError ( msg or "%r does not look like %r" % ( first , second ) ) |
def full_upload ( self , _type , block_num ) :
"""Uploads a full block body from AG .
The whole block ( including header and footer ) is copied into the user
buffer .
: param block _ num : Number of Block""" | _buffer = buffer_type ( )
size = c_int ( sizeof ( _buffer ) )
block_type = snap7 . snap7types . block_types [ _type ]
result = self . library . Cli_FullUpload ( self . pointer , block_type , block_num , byref ( _buffer ) , byref ( size ) )
check_error ( result , context = "client" )
return bytearray ( _buffer ) , size ... |
def save_current_figure_as ( self ) :
"""Save the currently selected figure .""" | if self . current_thumbnail is not None :
self . save_figure_as ( self . current_thumbnail . canvas . fig , self . current_thumbnail . canvas . fmt ) |
def expand_constants ( ins : Instruction , * , cf ) -> Instruction :
"""Replace CONSTANT _ INDEX operands with the literal Constant object from
the constant pool .
: param ins : Instruction to potentially modify .
: param cf : The ClassFile instance used to resolve Constants .
: return : Potentially modifie... | for i , operand in enumerate ( ins . operands ) :
if not isinstance ( operand , Operand ) :
continue
if operand . op_type == OperandTypes . CONSTANT_INDEX :
ins . operands [ i ] = cf . constants [ operand . value ]
return ins |
def get_as_datadict ( self ) :
"""Get information about this object as a dictionary . Used by WebSocket interface to pass some
relevant information to client applications .""" | return dict ( type = self . __class__ . __name__ , tags = list ( self . tags ) ) |
def set_main_fan ( self , main_fan ) :
"""Set the main fan config .
: param main _ fan : Value to set the main fan
: type main _ fan : int [ 0-10]
: returns : None
: raises : InvalidInput""" | if type ( main_fan ) != int and main_fan not in range ( 0 , 11 ) :
raise InvalidInput ( "Main fan value must be int between 0-10" )
self . _config [ 'main_fan' ] = main_fan
self . _q . put ( self . _config ) |
def as_allocate_quota_request ( self , timer = datetime . utcnow ) :
"""Makes a ` ServicecontrolServicesAllocateQuotaRequest ` from this instance
Returns :
a ` ` ServicecontrolServicesAllocateQuotaRequest ` `
Raises :
ValueError : if the fields in this instance are insufficient to
to create a valid ` ` Se... | if not self . service_name :
raise ValueError ( u'the service name must be set' )
if not self . operation_id :
raise ValueError ( u'the operation id must be set' )
if not self . operation_name :
raise ValueError ( u'the operation name must be set' )
op = super ( Info , self ) . as_operation ( timer = timer ... |
def del_network ( self , ** kwargs ) :
"""Deletes the network for the specified VNI .
Usage :
Method URI
DELETE / vtep / networks / { vni }
Request parameters :
Attribute Description
vni Virtual Network Identifier . ( e . g . 10)
Example : :
$ curl - X DELETE http : / / localhost : 8080 / vtep / net... | try :
body = self . vtep_app . del_network ( ** kwargs )
except ( BGPSpeakerNotFound , DatapathNotFound , VniNotFound ) as e :
return e . to_response ( status = 404 )
return Response ( content_type = 'application/json' , body = json . dumps ( body ) ) |
def _read_coefficients ( self ) :
"""Read & save the calibration coefficients""" | coeff = self . _read_register ( _BME280_REGISTER_DIG_T1 , 24 )
coeff = list ( struct . unpack ( '<HhhHhhhhhhhh' , bytes ( coeff ) ) )
coeff = [ float ( i ) for i in coeff ]
self . _temp_calib = coeff [ : 3 ]
self . _pressure_calib = coeff [ 3 : ]
self . _humidity_calib = [ 0 ] * 6
self . _humidity_calib [ 0 ] = self . ... |
def get_attribute_options ( self , attribute = None ) :
"""Returns a copy of the mapping options for the given attribute name
or a copy of all mapping options , if no attribute name is provided .
All options that were not explicitly configured are given a default
value of ` None ` .
: param tuple attribute ... | attribute_key = self . __make_key ( attribute )
if attribute_key is None :
opts = defaultdict ( self . _default_attributes_options . copy )
for attr , mp_options in iteritems_ ( self . __attribute_options ) :
opts [ attr ] . update ( mp_options )
else :
opts = self . _default_attributes_options . co... |
def handler ( event , context ) : # pylint : disable = W0613
"""Historical vpc event collector .
This collector is responsible for processing Cloudwatch events and polling events .""" | records = deserialize_records ( event [ 'Records' ] )
# Split records into two groups , update and delete .
# We don ' t want to query for deleted records .
update_records , delete_records = group_records_by_type ( records , UPDATE_EVENTS )
capture_delete_records ( delete_records )
# filter out error events
update_reco... |
def to_internal ( self , attribute_profile , external_dict ) :
"""Converts the external data from " type " to internal
: type attribute _ profile : str
: type external _ dict : dict [ str , str ]
: rtype : dict [ str , str ]
: param attribute _ profile : From which external type to convert ( ex : oidc , sam... | internal_dict = { }
for internal_attribute_name , mapping in self . from_internal_attributes . items ( ) :
if attribute_profile not in mapping :
logger . debug ( "no attribute mapping found for internal attribute '%s' the attribute profile '%s'" % ( internal_attribute_name , attribute_profile ) )
# ... |
def _set_min_reps ( self ) :
"""Populate the _ rendered dictionary with entries corresponding
to the minimum number of reps to go to for each exercise
and for the entire duration .
Examples
> > > program = Program ( ' My training program ' , duration = 2)
> > > bench _ press = DynamicExercise ( ' Bench ' ... | min_percent = self . minimum_percentile
# If the mode is weekly , set minimum reps on a weekly basis
if self . _min_reps_consistency == 'weekly' : # Set up generator . Only one is needed
exercise = self . days [ 0 ] . dynamic_exercises [ 0 ]
margs = exercise . min_reps , exercise . max_reps , min_percent
lo... |
def add_variables_from_file ( self , file_path ) :
"""Adds all OpenFisca variables contained in a given file to the tax and benefit system .""" | try :
file_name = path . splitext ( path . basename ( file_path ) ) [ 0 ]
# As Python remembers loaded modules by name , in order to prevent collisions , we need to make sure that :
# - Files with the same name , but located in different directories , have a different module names . Hence the file path hash... |
def push ( self , x ) :
"""Insert new element x in the heap .
Assumption : x is not already in the heap""" | assert x not in self . rank
i = len ( self . heap )
self . heap . append ( x )
# add a new leaf
self . rank [ x ] = i
self . up ( i ) |
def list_networks_on_dhcp_agent ( self , dhcp_agent , ** _params ) :
"""Fetches a list of dhcp agents hosting a network .""" | return self . get ( ( self . agent_path + self . DHCP_NETS ) % dhcp_agent , params = _params ) |
def Reboot ( self , target_mode = b'' , timeout_ms = None ) :
"""Reboots the device .
Args :
target _ mode : Normal reboot when unspecified . Can specify other target
modes such as ' recovery ' or ' bootloader ' .
timeout _ ms : Optional timeout in milliseconds to wait for a response .
Returns :
Usually... | return self . _SimpleCommand ( b'reboot' , arg = target_mode or None , timeout_ms = timeout_ms ) |
def replace_traceback_format_tb ( ) :
"""Replaces these functions from the traceback module by our own :
- traceback . format _ tb
- traceback . StackSummary . format
- traceback . StackSummary . extract
Note that this kind of monkey patching might not be safe under all circumstances
and is not officially... | import traceback
traceback . format_tb = format_tb
if hasattr ( traceback , "StackSummary" ) :
traceback . StackSummary . format = format_tb
traceback . StackSummary . extract = _StackSummary_extract |
def get_device_configs ( ) :
'''Return a ` pandas . DataFrame ` , where each row corresponds to an available
device configuration , including the ` device ` ( i . e . , the name of the
device ) .''' | frames = [ ]
for i in range ( 2 ) :
for device in get_video_sources ( ) :
df_device_i = get_configs ( device )
df_device_i . insert ( 0 , 'device' , str ( device ) )
frames . append ( df_device_i )
device_configs = pd . concat ( frames ) . drop_duplicates ( )
device_configs [ 'label' ] = dev... |
def search ( query , medium , credentials ) :
"""Searches MyAnimeList for a [ medium ] matching the keyword ( s ) given by query .
: param query The keyword ( s ) to search with .
: param medium Anime or manga ( tokens . Medium . ANIME or tokens . Medium . MANGA ) .
: return A list of all items that are of ty... | helpers . check_creds ( credentials , header )
if len ( query ) == 0 :
raise ValueError ( constants . INVALID_EMPTY_QUERY )
api_query = helpers . get_query_url ( medium , query )
if api_query is None :
raise ValueError ( constants . INVALID_MEDIUM )
search_resp = requests . get ( api_query , auth = credentials ... |
def _produce_output ( report , failed , setup ) :
'''Produce output from the report dictionary generated by _ generate _ report''' | report_format = setup . get ( 'report_format' , 'yaml' )
log . debug ( 'highstate output format: %s' , report_format )
if report_format == 'json' :
report_text = salt . utils . json . dumps ( report )
elif report_format == 'yaml' :
string_file = StringIO ( )
salt . utils . yaml . safe_dump ( report , string... |
def before_all ( context ) :
"""Initialization method that will be executed before the test execution
: param context : behave context""" | # Use pytest asserts if behave _ pytest is installed
install_pytest_asserts ( )
# Get ' Config _ environment ' property from user input ( e . g . - D Config _ environment = ios )
env = context . config . userdata . get ( 'Config_environment' )
# Deprecated : Get ' env ' property from user input ( e . g . - D env = ios ... |
def report_estimation_accuracy ( request ) :
"""Idea from Software Estimation , Demystifying the Black Art , McConnel 2006 Fig 3-3.""" | contracts = ProjectContract . objects . filter ( status = ProjectContract . STATUS_COMPLETE , type = ProjectContract . PROJECT_FIXED )
data = [ ( 'Target (hrs)' , 'Actual (hrs)' , 'Point Label' ) ]
for c in contracts :
if c . contracted_hours ( ) == 0 :
continue
pt_label = "%s (%.2f%%)" % ( c . name , c... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : ExecutionStepContextContext for this ExecutionStepContextInstance
: rtype : twilio . rest . studio . v1 . flow . execution... | if self . _context is None :
self . _context = ExecutionStepContextContext ( self . _version , flow_sid = self . _solution [ 'flow_sid' ] , execution_sid = self . _solution [ 'execution_sid' ] , step_sid = self . _solution [ 'step_sid' ] , )
return self . _context |
def split_path ( path_ ) :
"""Split the requested path into ( locale , path ) .
locale will be empty if it isn ' t found .""" | path = path_ . lstrip ( '/' )
# Use partitition instead of split since it always returns 3 parts
first , _ , rest = path . partition ( '/' )
lang = first . lower ( )
if lang in settings . LANGUAGE_URL_MAP :
return settings . LANGUAGE_URL_MAP [ lang ] , rest
else :
supported = find_supported ( first )
if len... |
def _load ( self , url ) :
"""Load from remote , but check local file content to identify duplicate content . If local file is found with
same hash then it is used with metadata from remote object to avoid fetching full content .
: param url :
: return :""" | self . _logger . debug ( 'Loading url %s into resource cache' % url )
retriever = get_resource_retriever ( url )
content_path = os . path . join ( self . path , self . _hash_path ( url ) )
try :
if url in self . metadata :
headers = retriever . fetch ( content_path , last_etag = self . metadata [ url ] [ 'e... |
def handle ( self , * args , ** options ) :
"""Django command handler .""" | self . verbosity = int ( options . get ( 'verbosity' ) )
self . quiet = options . get ( 'quiet' )
self . _set_logger_level ( )
try :
connection . close ( )
self . filename = options . get ( 'input_filename' )
self . path = options . get ( 'input_path' )
self . servername = options . get ( 'servername' )... |
def auto_download ( status , credentials = None , subjects_path = None , overwrite = False , release = 'HCP_1200' , database = 'hcp-openaccess' , retinotopy_path = None , retinotopy_cache = True ) :
'''auto _ download ( True ) enables automatic downloading of HCP subject data when the subject ID
is requested . Th... | global _auto_download_options , _retinotopy_path
status = ( [ 'structure' , 'retinotopy' ] if status is True else [ ] if status is False else [ status ] if pimms . is_str ( status ) else status )
_auto_download_options = { 'structure' : False , 'retinotopy' : False }
for s in status :
if s . lower ( ) == 'structure... |
def get_folder_contents_iter ( self , uri ) :
"""Return iterator for directory contents .
uri - - mediafire URI
Example :
for item in get _ folder _ contents _ iter ( ' mf : / / / Documents ' ) :
print ( item )""" | resource = self . get_resource_by_uri ( uri )
if not isinstance ( resource , Folder ) :
raise NotAFolderError ( uri )
folder_key = resource [ 'folderkey' ]
for item in self . _folder_get_content_iter ( folder_key ) :
if 'filename' in item : # Work around https : / / mediafire . mantishub . com / view . php ? id... |
def wait_for_responses ( self , * msgs , ** kwargs ) :
"""Returns a list of ( success , response ) tuples . If success
is False , response will be an Exception . Otherwise , response
will be the normal query response .
If fail _ on _ error was left as True and one of the requests
failed , the corresponding ... | if self . is_closed or self . is_defunct :
raise ConnectionShutdown ( "Connection %s is already closed" % ( self , ) )
timeout = kwargs . get ( 'timeout' )
fail_on_error = kwargs . get ( 'fail_on_error' , True )
waiter = ResponseWaiter ( self , len ( msgs ) , fail_on_error )
# busy wait for sufficient space on the ... |
def _mainthread_accept_clients ( self ) :
"""Accepts new clients and sends them to the to _ handle _ accepted within a subthread""" | try :
if self . _accept_selector . select ( timeout = self . block_time ) :
client = self . _server_socket . accept ( )
logging . info ( 'Client connected: {}' . format ( client [ 1 ] ) )
self . _threads_limiter . start_thread ( target = self . _subthread_handle_accepted , args = ( client , ... |
def getWordList ( ipFile , delim ) :
"""extract a unique list of words and have line numbers that word appears""" | indexedWords = { }
totWords = 0
totLines = 0
with codecs . open ( ipFile , "r" , encoding = 'utf-8' , errors = 'replace' ) as f :
for line in f :
totLines = totLines + 1
words = multi_split ( line , delim )
totWords = totWords + len ( words )
for word in words :
cleanedWo... |
def get_url_rev_and_auth ( self , url ) :
"""Prefixes stub URLs like ' user @ hostname : user / repo . git ' with ' ssh : / / ' .
That ' s required because although they use SSH they sometimes don ' t
work with a ssh : / / scheme ( e . g . GitHub ) . But we need a scheme for
parsing . Hence we remove it again... | if '://' not in url :
assert 'file:' not in url
url = url . replace ( 'git+' , 'git+ssh://' )
url , rev , user_pass = super ( Git , self ) . get_url_rev_and_auth ( url )
url = url . replace ( 'ssh://' , '' )
else :
url , rev , user_pass = super ( Git , self ) . get_url_rev_and_auth ( url )
return ur... |
def get_raw_default_config_and_read_file_list ( ) :
"""Returns a ConfigParser object and a list of filenames that were parsed to initialize it""" | global _CONFIG , _READ_DEFAULT_FILES
if _CONFIG is not None :
return _CONFIG , _READ_DEFAULT_FILES
with _CONFIG_LOCK :
if _CONFIG is not None :
return _CONFIG , _READ_DEFAULT_FILES
try : # noinspection PyCompatibility
from ConfigParser import SafeConfigParser
except ImportError : # noins... |
def _getfunctionlist ( self ) :
"""( internal use )""" | try :
eventhandler = self . obj . __eventhandler__
except AttributeError :
eventhandler = self . obj . __eventhandler__ = { }
return eventhandler . setdefault ( self . event , [ ] ) |
def workflow ( self , workflow_name : Optional [ str ] = None , use_default : bool = True ) -> SoS_Workflow :
'''Return a workflow with name _ step + name _ step specified in wf _ name
This function might be called recursively because of nested
workflow .''' | if workflow_name is None and not use_default :
return SoS_Workflow ( self . content , '' , '' , self . sections , self . global_stmts )
allowed_steps = None
if not workflow_name :
wf_name = ''
else : # if consists of multiple workflows
if '+' in workflow_name :
wfs = [ ]
for wf in workflow_n... |
def hms ( segundos ) : # TODO : mover para util . py
"""Retorna o número de horas , minutos e segundos a partir do total de
segundos informado .
. . sourcecode : : python
> > > hms ( 1)
(0 , 0 , 1)
> > > hms ( 60)
(0 , 1 , 0)
> > > hms ( 3600)
(1 , 0 , 0)
> > > hms ( 3601)
(1 , 0 , 1)
> > > h... | h = ( segundos / 3600 )
m = ( segundos - ( 3600 * h ) ) / 60
s = ( segundos - ( 3600 * h ) - ( m * 60 ) ) ;
return ( h , m , s ) |
def perform_service_validate ( self , ticket = None , service_url = None , headers = None , ) :
'''Fetch a response from the remote CAS ` serviceValidate ` endpoint .''' | url = self . _get_service_validate_url ( ticket , service_url = service_url )
logging . debug ( '[CAS] ServiceValidate URL: {}' . format ( url ) )
return self . _perform_cas_call ( url , ticket = ticket , headers = headers ) |
def unique_list_dicts ( dlist , key ) :
"""Return a list of dictionaries which are sorted for only unique entries .
: param dlist :
: param key :
: return list :""" | return list ( dict ( ( val [ key ] , val ) for val in dlist ) . values ( ) ) |
def run ( command , encoding = None , decode = True , cwd = None ) :
"""Run a command [ cmd , arg1 , arg2 , . . . ] .
Returns the output ( stdout + stderr ) .
Raises CommandFailed in cases of error .""" | if not encoding :
encoding = locale . getpreferredencoding ( )
try :
with open ( os . devnull , 'rb' ) as devnull :
pipe = subprocess . Popen ( command , stdin = devnull , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , cwd = cwd )
except OSError as e :
raise Failure ( "could not run %s:... |
def add_mismatch ( self , entity , * traits ) :
"""Add a mismatching entity to the index .
We do this by simply adding the mismatch to the index .
: param collections . Hashable entity : an object to be mismatching the values of ` traits _ indexed _ by `
: param list traits : a list of hashable traits to inde... | for trait in traits :
self . index [ trait ] . add ( entity ) |
def remove_dups_wothout_set ( head ) :
"""Time Complexity : O ( N ^ 2)
Space Complexity : O ( 1)""" | current = head
while current :
runner = current
while runner . next :
if runner . next . val == current . val :
runner . next = runner . next . next
else :
runner = runner . next
current = current . next |
def read_from_config ( cp , ** kwargs ) :
"""Initializes a model from the given config file .
The section must have a ` ` name ` ` argument . The name argument corresponds to
the name of the class to initialize .
Parameters
cp : WorkflowConfigParser
Config file parser to read .
\**kwargs :
All other k... | # use the name to get the distribution
name = cp . get ( "model" , "name" )
return models [ name ] . from_config ( cp , ** kwargs ) |
def write ( self , destination , source_model , name = None ) :
"""Save sources - to multiple
shapefiles corresponding to different source typolgies / geometries
( ' _ point ' , ' _ area ' , ' _ simple ' , ' _ complex ' , ' _ planar ' )""" | if os . path . exists ( destination + ".shp" ) :
os . system ( "rm %s.*" % destination )
self . destination = destination
self . filter_params ( source_model )
w_area = shapefile . Writer ( shapefile . POLYGON )
w_point = shapefile . Writer ( shapefile . POINT )
w_simple = shapefile . Writer ( shapefile . POLYLINE ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.