signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def install_database ( name , owner , template = 'template0' , encoding = 'UTF8' , locale = 'en_US.UTF-8' ) :
"""Require a PostgreSQL database .
from fabtools import require
require . postgres . database ( ' myapp ' , owner = ' dbuser ' )""" | create_database ( name , owner , template = template , encoding = encoding , locale = locale ) |
def sideral ( date , longitude = 0. , model = 'mean' , eop_correction = True , terms = 106 ) : # pragma : no cover
"""Sideral time as a rotation matrix""" | theta = _sideral ( date , longitude , model , eop_correction , terms )
return rot3 ( np . deg2rad ( - theta ) ) |
def show_get_string_message_box ( self , caption : str , text : str , accepted_fn , rejected_fn = None , accepted_text : str = None , rejected_text : str = None ) -> None :
"""Show a dialog box and ask for a string .
Caption describes the user prompt . Text is the initial / default string .
Accepted function mu... | workspace = self . __document_controller . workspace_controller
workspace . pose_get_string_message_box ( caption , text , accepted_fn , rejected_fn , accepted_text , rejected_text ) |
def decode_cpu_id ( self , cpuid ) :
"""Decode the CPU id into a string""" | ret = ( )
for i in cpuid . split ( ':' ) :
ret += ( eval ( '0x' + i ) , )
return ret |
def compute_similarities ( hdf5_file , data , N_processes ) :
"""Compute a matrix of pairwise L2 Euclidean distances among samples from ' data ' .
This computation is to be done in parallel by ' N _ processes ' distinct processes .
Those processes ( which are instances of the class ' Similarities _ worker ' )
... | slice_queue = multiprocessing . JoinableQueue ( )
pid_list = [ ]
for i in range ( N_processes ) :
worker = Similarities_worker ( hdf5_file , '/aff_prop_group/similarities' , data , slice_queue )
worker . daemon = True
worker . start ( )
pid_list . append ( worker . pid )
for rows_slice in chunk_generato... |
def save ( self , * args , ** kwargs ) :
"""Keep the unique order in sync .""" | objects = self . get_filtered_manager ( )
old_pos = getattr ( self , '_original_sort_order' , None )
new_pos = self . sort_order
if old_pos is None and self . _unique_togethers_changed ( ) :
self . sort_order = None
new_pos = None
try :
with transaction . atomic ( ) :
self . _save ( objects , old_po... |
def apply_chord ( self , header , partial_args , group_id , body , ** options ) :
u"""Instantiate a linking ChordData object before executing subtasks .
Parameters
header : a list of incomplete subtask signatures , with partial
different - per - instance arguments already set .
partial _ args : list of same... | callback_entry = TaskMeta . objects . create ( task_id = body . id )
chord_data = ChordData . objects . create ( callback_result = callback_entry )
for subtask in header :
subtask_entry = TaskMeta . objects . create ( task_id = subtask . id )
chord_data . completed_results . add ( subtask_entry )
if body . opti... |
def default_instance ( ) :
"""For use like a singleton , return the existing instance
of the object or a new instance""" | if ConfigManager . _instance is None :
with threading . Lock ( ) :
if ConfigManager . _instance is None :
ConfigManager . _instance = ConfigManager ( )
return ConfigManager . _instance |
def get_or_create_regex_namespace_entry ( self , namespace : str , pattern : str , name : str ) -> NamespaceEntry :
"""Get a namespace entry from a regular expression .
Need to commit after !
: param namespace : The name of the namespace
: param pattern : The regular expression pattern for the namespace
: p... | namespace = self . ensure_regex_namespace ( namespace , pattern )
n_filter = and_ ( Namespace . pattern == pattern , NamespaceEntry . name == name )
name_model = self . session . query ( NamespaceEntry ) . join ( Namespace ) . filter ( n_filter ) . one_or_none ( )
if name_model is None :
name_model = NamespaceEntry... |
def to_canonical_factor ( self ) :
u"""Returns an equivalent CanonicalDistribution object .
The formulas for calculating the cannonical factor parameters
for N ( μ ; Σ ) = C ( K ; h ; g ) are as follows -
K = sigma ^ ( - 1)
h = sigma ^ ( - 1 ) * mu
g = - ( 0.5 ) * mu . T * sigma ^ ( - 1 ) * mu -
log ( (... | from pgmpy . factors . continuous import CanonicalDistribution
mu = self . mean
sigma = self . covariance
K = self . precision_matrix
h = np . dot ( K , mu )
g = - ( 0.5 ) * np . dot ( mu . T , h ) [ 0 , 0 ] - np . log ( np . power ( 2 * np . pi , len ( self . variables ) / 2 ) * np . power ( abs ( np . linalg . det ( ... |
def ocr ( img , mrz_mode = True , extra_cmdline_params = '' ) :
"""Runs Tesseract on a given image . Writes an intermediate tempfile and then runs the tesseract command on the image .
This is a simplified modification of image _ to _ string from PyTesseract , which is adapted to SKImage rather than PIL .
In pri... | input_file_name = '%s.bmp' % _tempnam ( )
output_file_name_base = '%s' % _tempnam ( )
output_file_name = "%s.txt" % output_file_name_base
try : # Prevent annoying warning about lossy conversion to uint8
if str ( img . dtype ) . startswith ( 'float' ) and np . nanmin ( img ) >= 0 and np . nanmax ( img ) <= 1 :
... |
def as_dict ( self ) :
"""Return the configuration as a dict""" | dictionary = { }
for section in self . parser . sections ( ) :
dictionary [ section ] = { }
for option in self . parser . options ( section ) :
dictionary [ section ] [ option ] = self . parser . get ( section , option )
return dictionary |
def columns_dataset ( self ) :
"""Implement high level cache system for columns and dataset .""" | cache = self . cache
cache_key = 'columns_dataset'
if cache_key not in cache :
columns_dataset = super ( CachedModelVectorBuilder , self ) . columns_dataset
cache [ cache_key ] = columns_dataset
self . cache = cache
return cache [ cache_key ] |
def send ( self , data ) :
"""Send some part of message to the socket .""" | bytes_sent = self . _sock . send ( extract_bytes ( data ) )
self . bytes_written += bytes_sent
return bytes_sent |
def index_of_item ( self , item ) :
"""Get the index for the given TreeItem
: param item : the treeitem to query
: type item : : class : ` TreeItem `
: returns : the index of the item
: rtype : : class : ` QtCore . QModelIndex `
: raises : ValueError""" | # root has an invalid index
if item == self . _root :
return QtCore . QModelIndex ( )
# find all parents to get their index
parents = [ item ]
i = item
while True :
parent = i . parent ( )
# break if parent is root because we got all parents we need
if parent == self . _root :
break
if paren... |
def set_group_status ( group_id , status , ** kwargs ) :
"""Set the status of a group to ' X '""" | user_id = kwargs . get ( 'user_id' )
try :
group_i = db . DBSession . query ( ResourceGroup ) . filter ( ResourceGroup . id == group_id ) . one ( )
except NoResultFound :
raise ResourceNotFoundError ( "ResourceGroup %s not found" % ( group_id ) )
group_i . network . check_write_permission ( user_id )
group_i . ... |
def pdchAssignmentCommand ( ChannelDescription_presence = 0 , CellChannelDescription_presence = 0 , MobileAllocation_presence = 0 , StartingTime_presence = 0 , FrequencyList_presence = 0 , ChannelDescription_presence1 = 0 , FrequencyChannelSequence_presence = 0 , MobileAllocation_presence1 = 0 , PacketChannelDescriptio... | a = TpPd ( pd = 0x6 )
b = MessageType ( mesType = 0x23 )
# 00100011
c = ChannelDescription ( )
packet = a / b / c
if ChannelDescription_presence is 1 :
d = ChannelDescriptionHdr ( ieiCD = 0x62 , eightBitCD = 0x0 )
packet = packet / d
if CellChannelDescription_presence is 1 :
e = CellChannelDescriptionHdr ( ... |
def MakeDeployableBinary ( self , template_path , output_path ) :
"""This will add the config to the client template and create a . deb .""" | buildpackage_binary = "/usr/bin/dpkg-buildpackage"
if not os . path . exists ( buildpackage_binary ) :
logging . error ( "dpkg-buildpackage not found, unable to repack client." )
return
with utils . TempDirectory ( ) as tmp_dir :
template_dir = os . path . join ( tmp_dir , "dist" )
utils . EnsureDirExis... |
def create_delete_model ( record ) :
"""Create a security group model from a record .""" | data = cloudwatch . get_historical_base_info ( record )
group_id = cloudwatch . filter_request_parameters ( 'groupId' , record )
# vpc _ id = cloudwatch . filter _ request _ parameters ( ' vpcId ' , record )
# group _ name = cloudwatch . filter _ request _ parameters ( ' groupName ' , record )
arn = get_arn ( group_id ... |
def set_monthly ( self , interval , * , day_of_month = None , days_of_week = None , index = None , ** kwargs ) :
"""Set to repeat every month on specified days for every x no . of days
: param int interval : no . of days to repeat at
: param int day _ of _ month : repeat day of a month
: param list [ str ] da... | if not day_of_month and not days_of_week :
raise ValueError ( 'Must provide day_of_month or days_of_week values' )
if day_of_month and days_of_week :
raise ValueError ( 'Must provide only one of the two options' )
self . set_daily ( interval , ** kwargs )
if day_of_month :
self . __day_of_month = day_of_mon... |
def chunk ( self , iterable , n , fillvalue = None ) :
"itertools recipe : Collect data into fixed - length chunks or blocks" | # grouper ( ' ABCDEFG ' , 3 , ' x ' ) - - > ABC DEF Gxx
args = [ iter ( iterable ) ] * n
return izip_longest ( fillvalue = fillvalue , * args ) |
def _createbound ( obj ) :
"""Create a new BoundNode representing a given object .""" | # Start by allowing objects to define custom unbound reference hooks
try :
kls = obj . _unboundreference_ ( )
except AttributeError :
kls = type ( obj )
unbound = _createunbound ( kls )
def valueget ( ) :
return obj
for t in ( BoundBitfieldNode , BoundStructureNode , BoundArrayNode ) :
if isinstance ( u... |
def greaterThan ( self , value ) :
"""Sets the operator type to Query . Op . GreaterThan and sets the
value to the inputted value .
: param value < variant >
: return < Query >
: sa _ _ gt _ _
: usage | > > > from orb import Query as Q
| > > > query = Q ( ' test ' ) . greaterThan ( 1)
| > > > print qu... | newq = self . copy ( )
newq . setOp ( Query . Op . GreaterThan )
newq . setValue ( value )
return newq |
def trigger_hook ( self , name , * args , ** kwargs ) :
"""Recursively call a method named ` ` name ` ` with the provided args and
keyword args if defined .""" | method = getattr ( self , name , None )
if is_callable ( method ) :
method ( * args , ** kwargs )
try :
children = self . children
except AttributeError :
return
else :
if children is not None :
for child in children :
method = getattr ( child , 'trigger_hook' , None )
if... |
def measures ( dirnames , measure_func , t_steady = None ) :
"""Calculate a measure of a set of model output directories ,
for a measure function which returns an associated uncertainty .
Parameters
dirnames : list [ str ]
Model output directory paths .
measure _ func : function
Function which takes a :... | measures , measure_errs = [ ] , [ ]
for dirname in dirnames :
meas , meas_err = get_average_measure ( dirname , measure_func , t_steady )
measures . append ( meas )
measure_errs . append ( meas_err )
return np . array ( measures ) , np . array ( measure_errs ) |
def add ( self , defn ) :
"""Adds the given Command Definition to this Command Dictionary .""" | self [ defn . name ] = defn
self . opcodes [ defn . _opcode ] = defn |
def store_groups_in_session ( sender , user , request , ** kwargs ) :
"""When a user logs in , fetch its groups and store them in the users session .
This is required by ws4redis , since fetching groups accesses the database , which is a blocking
operation and thus not allowed from within the websocket loop .""... | if hasattr ( user , 'groups' ) :
request . session [ 'ws4redis:memberof' ] = [ g . name for g in user . groups . all ( ) ] |
def get ( self , * args , ** kwargs ) :
"""Sends a GET request to a reddit path determined by ` ` args ` ` . Basically ` ` . get ( ' foo ' , ' bar ' , ' baz ' ) ` ` will GET http : / / www . reddit . com / foo / bar / baz / . json . ` ` kwargs ` ` supplied will be passed to : meth : ` requests . get ` after having ... | kwargs = self . _inject_request_kwargs ( kwargs )
url = reddit_url ( * args )
r = requests . get ( url , ** kwargs )
# print r . url
if r . status_code == 200 :
thing = self . _thingify ( json . loads ( r . content ) , path = urlparse ( r . url ) . path )
return thing
else :
raise BadResponse ( r ) |
def get_elapsed_time ( self , issue ) :
"""Gets the elapsed time since the last mark ( either the updated time of the last log or the time that the issue was
marked in progress )""" | last_mark = None
# Get the last mark from the work logs
worklogs = self . get_worklog ( issue )
if worklogs :
last_worklog = worklogs [ - 1 ]
last_mark = dateutil . parser . parse ( last_worklog . raw [ 'updated' ] )
# If no worklogs , get the time since the issue was marked In Progress
if not last_mark :
l... |
def list_milestones ( self , project_id , find = None ) :
"""This lets you query the list of milestones for a project . You can
either return all milestones , or only those that are late , completed ,
or upcoming .""" | path = '/projects/%u/milestones/list' % project_id
req = ET . Element ( 'request' )
if find is not None :
ET . SubElement ( req , 'find' ) . text = str ( find )
return self . _request ( path , req ) |
def add_auth_attribute ( attr , value , actor = False ) :
"""Helper function for login managers . Adds authorization attributes
to : obj : ` current _ auth ` for the duration of the request .
: param str attr : Name of the attribute
: param value : Value of the attribute
: param bool actor : Whether this at... | if attr in ( 'actor' , 'anchors' , 'is_anonymous' , 'not_anonymous' , 'is_authenticated' , 'not_authenticated' ) :
raise AttributeError ( "Attribute name %s is reserved by current_auth" % attr )
# Invoking current _ auth will also create it on the local stack . We can
# then proceed to set attributes on it .
ca = c... |
def parse_time_arg ( s ) :
"""Parse a time stamp in the " year - month - day hour - minute " format .""" | try :
return time . strptime ( s , "%Y-%m-%d %H:%M" )
except ValueError as e :
raise argparse . ArgumentTypeError ( e ) |
def parse_date ( value : Union [ date , StrIntFloat ] ) -> date :
"""Parse a date / int / float / string and return a datetime . date .
Raise ValueError if the input is well formatted but not a valid date .
Raise ValueError if the input isn ' t well formatted .""" | if isinstance ( value , date ) :
if isinstance ( value , datetime ) :
return value . date ( )
else :
return value
number = get_numeric ( value )
if number is not None :
return from_unix_seconds ( number ) . date ( )
match = date_re . match ( cast ( str , value ) )
if not match :
raise er... |
def create_transfer_learning_tuner ( parent , additional_parents = None , estimator = None , sagemaker_session = None ) :
"""Creates a new ` ` HyperParameterTuner ` ` by copying the request fields from the provided parent to the new instance
of ` ` HyperparameterTuner ` ` followed by addition of warm start config... | parent_tuner = HyperparameterTuner . attach ( tuning_job_name = parent , sagemaker_session = sagemaker_session )
return parent_tuner . transfer_learning_tuner ( additional_parents = additional_parents , estimator = estimator ) |
def create ( vm_ ) :
'''Create a single VM from a data dict''' | try : # Check for required profile parameters before sending any API calls .
if vm_ [ 'profile' ] and config . is_profile_configured ( __opts__ , __active_provider_name__ or 'parallels' , vm_ [ 'profile' ] , vm_ = vm_ ) is False :
return False
except AttributeError :
pass
__utils__ [ 'cloud.fire_event' ... |
def set_umask ( mask ) :
'''Temporarily set the umask and restore once the contextmanager exits''' | if mask is None or salt . utils . platform . is_windows ( ) : # Don ' t attempt on Windows , or if no mask was passed
yield
else :
try :
orig_mask = os . umask ( mask )
# pylint : disable = blacklisted - function
yield
finally :
os . umask ( orig_mask ) |
def blit ( self , dest : "Console" , dest_x : int = 0 , dest_y : int = 0 , src_x : int = 0 , src_y : int = 0 , width : int = 0 , height : int = 0 , fg_alpha : float = 1.0 , bg_alpha : float = 1.0 , key_color : Optional [ Tuple [ int , int , int ] ] = None , ) -> None :
"""Blit from this console onto the ` ` dest ` ... | # The old syntax is easy to detect and correct .
if hasattr ( src_y , "console_c" ) :
( src_x , # type : ignore
src_y , width , height , dest , # type : ignore
dest_x , dest_y , ) = ( dest , dest_x , dest_y , src_x , src_y , width , height )
warnings . warn ( "Parameter names have been moved around, see... |
def add ( context , filenames ) :
"""Add data on Linux system calls .
Arguments shall be * . tbl files from Linux x86 source code ,
or output from grep .
Delete the old database before adding if necessary .""" | logging . info ( _ ( 'Current Mode: Add Linux data' ) )
context . obj [ 'database' ] . add_data ( filenames )
sys . exit ( 0 ) |
def get_batch_for_key ( data ) :
"""Retrieve batch information useful as a unique key for the sample .""" | batches = _get_batches ( data , require_bam = False )
if len ( batches ) == 1 :
return batches [ 0 ]
else :
return tuple ( batches ) |
def apply_published_filter ( self , queryset , operation , value ) :
"""Add the appropriate Published filter to a given elasticsearch query .
: param queryset : The DJES queryset object to be filtered .
: param operation : The type of filter ( before / after ) .
: param value : The date or datetime value bein... | if operation not in [ "after" , "before" ] :
raise ValueError ( """Publish filters only use before or after for range filters.""" )
return queryset . filter ( Published ( ** { operation : value } ) ) |
def create_redis_client ( self ) :
"""Create a redis client .""" | return ray . services . create_redis_client ( self . _redis_address , self . _ray_params . redis_password ) |
def to_int_list ( values ) :
"""Converts the given list of vlues into a list of integers . If the
integer conversion fails ( e . g . non - numeric strings or None - values ) , this
filter will include a 0 instead .""" | results = [ ]
for v in values :
try :
results . append ( int ( v ) )
except ( TypeError , ValueError ) :
results . append ( 0 )
return results |
def bin2hexline ( data , add_addr = True , width = 16 ) :
"""Format binary data to a Hex - Editor like format . . .
> > > data = bytearray ( [ i for i in range ( 256 ) ] )
> > > print ( ' \\ n ' . join ( bin2hexline ( data , width = 16 ) ) )
0000 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f . . . . .
001... | data = bytearray ( data )
# same as string . printable but without \ t \ n \ r \ v \ f ; )
printable = string . digits + string . ascii_letters + string . punctuation + " "
addr = 0
lines = [ ]
run = True
line_width = 4 + ( width * 3 ) + 1
while run :
if add_addr :
line = [ "%04i" % addr ]
else :
... |
def compute ( mechanism , subsystem , purviews , cause_purviews , effect_purviews ) :
"""Compute a | Concept | for a mechanism , in this | Subsystem | with the
provided purviews .""" | concept = subsystem . concept ( mechanism , purviews = purviews , cause_purviews = cause_purviews , effect_purviews = effect_purviews )
# Don ' t serialize the subsystem .
# This is replaced on the other side of the queue , and ensures
# that all concepts in the CES reference the same subsystem .
concept . subsystem = ... |
def set_area ( self , area ) :
"""The area to retrieve listings from . Use an array to search multiple areas .
: param area :
: return :""" | self . _area = area . replace ( " " , "-" ) . lower ( ) if isinstance ( area , str ) else ',' . join ( map ( lambda x : x . lower ( ) . replace ( ' ' , '-' ) , area ) ) |
def include_file ( self , uri , ** kwargs ) :
"""Include a file at the given ` ` uri ` ` .""" | _include_file ( self . context , uri , self . _templateuri , ** kwargs ) |
def get_external_references ( self ) :
"""Returns the external references of the element
@ rtype : L { CexternalReference }
@ return : the external references ( iterator )""" | node = self . node . find ( 'externalReferences' )
if node is not None :
ext_refs = CexternalReferences ( node )
for ext_ref in ext_refs :
yield ext_ref |
def ns ( self , prefix , tag ) :
"""Given a prefix and an XML tag , output the qualified name
for proper namespace handling on output .""" | return etree . QName ( self . prefixes [ prefix ] , tag ) |
def restore_directory_state ( self , fname ) :
"""Restore directory expanded state""" | root = osp . normpath ( to_text_string ( fname ) )
if not osp . exists ( root ) : # Directory has been ( re ) moved outside Spyder
return
for basename in os . listdir ( root ) :
path = osp . normpath ( osp . join ( root , basename ) )
if osp . isdir ( path ) and path in self . __expanded_state :
sel... |
def ifftn ( a , s = None , axes = None , norm = None ) :
"""Compute the N - dimensional inverse discrete Fourier Transform .
This function computes the inverse of the N - dimensional discrete
Fourier Transform over any number of axes in an M - dimensional array by
means of the Fast Fourier Transform ( FFT ) .... | unitary = _unitary ( norm )
output = mkl_fft . ifftn ( a , s , axes )
if unitary :
output *= sqrt ( _tot_size ( output , axes ) )
return output |
def main ( ) :
"""Simple stdin / stdout interface .""" | if len ( sys . argv ) == 2 and sys . argv [ 1 ] in Locales :
locale = sys . argv [ 1 ]
convertfunc = convert
elif len ( sys . argv ) == 3 and sys . argv [ 1 ] == '-w' and sys . argv [ 2 ] in Locales :
locale = sys . argv [ 2 ]
convertfunc = convert_for_mw
else :
thisfile = __file__ if __name__ == '_... |
def valid_configs ( self ) :
"""Return a list of slots having a valid configurtion . Requires firmware 2.1.""" | if self . ykver ( ) < ( 2 , 1 , 0 ) :
raise YubiKeyUSBHIDError ( 'Valid configs unsupported in firmware %s' % ( self . version ( ) ) )
res = [ ]
if self . touch_level & self . CONFIG1_VALID == self . CONFIG1_VALID :
res . append ( 1 )
if self . touch_level & self . CONFIG2_VALID == self . CONFIG2_VALID :
re... |
def _set_multi_bit_value_format_character ( self ) :
"""Set format character for multibit values .
The format character depends on size of the value and whether values
are signed or unsigned .""" | self . MULTI_BIT_VALUE_FORMAT_CHARACTER = self . MULTI_BIT_VALUE_FORMAT_CHARACTER . upper ( )
if self . SIGNED_VALUES :
self . MULTI_BIT_VALUE_FORMAT_CHARACTER = self . MULTI_BIT_VALUE_FORMAT_CHARACTER . lower ( ) |
def path ( self ) :
"""Return the full path to the Group , including any parent Groups .""" | # If root , return ' / '
if self . dataset is self :
return ''
else : # Otherwise recurse
return self . dataset . path + '/' + self . name |
def flatten ( self ) :
"""If the current Matrix consists of Blockmatrixes as elementes method
flattens the Matrix into one Matrix only consisting of the 2nd level
elements
[ [ [ 1 2 ] [ [ 3 4 ] to [ [ 1 2 3 4]
[5 6 ] ] [ 7 8 ] ] ] [ 5 6 7 8 ] ]""" | blocksize = self . get_array ( ) [ 0 ] [ 0 ] . get_width ( )
width = self . get_width ( ) * blocksize
columnsNew = [ [ ] for dummy in xrange ( width ) ]
for row in self . get_array ( ) :
index = 0
for submatrix in row :
for column in submatrix . get_array ( False ) :
columnsNew [ index ] += ... |
def links ( self ) :
"""Return a dictionary of links to related resources that should be
included in the * Link * header of an HTTP response .
: rtype : dict""" | link_dict = { 'self' : self . resource_uri ( ) }
for relationship in inspect ( # pylint : disable = maybe - no - member
self . __class__ ) . relationships :
if 'collection' not in relationship . key :
instance = getattr ( self , relationship . key )
if instance :
link_dict [ str ( relati... |
def append ( self , value ) :
"""Append an item to the end of an open ConsList .
Args :
value ( : class : ` Conjunction ` , : class : ` Term ` ) : item to add
Raises :
: class : ` TdlError ` : when appending to a closed list""" | if self . _avm is not None and not self . terminated :
path = self . _last_path
if path :
path += '.'
self [ path + LIST_HEAD ] = value
self . _last_path = path + LIST_TAIL
self [ self . _last_path ] = AVM ( )
else :
raise TdlError ( 'Cannot append to a closed list.' ) |
def only_published ( cls , at = None ) :
"""Produce a query fragment suitable for selecting documents public .
Now ( no arguments ) , at a specific time ( datetime argument ) , or relative to now ( timedelta ) .""" | if isinstance ( at , timedelta ) :
at = utcnow ( ) + at
else :
at = at or utcnow ( )
pub , ret = cls . published , cls . retracted
publication = ( - pub ) | ( pub == None ) | ( pub <= at )
retraction = ( - ret ) | ( ret == None ) | ( ret > at )
return publication & retraction |
def dump_emails ( part ) :
"""Show the sent emails ' tested parts , to aid in debugging .""" | print ( "Sent emails:" )
for email in mail . outbox :
print ( getattr ( email , part ) ) |
def is_downloaded ( self , file_path ) :
"""Check if the data file is already downloaded .""" | if os . path . exists ( file_path ) :
self . chatbot . logger . info ( 'File is already downloaded' )
return True
return False |
def write ( self ) :
"""Return FASTQ formatted string
Returns :
str : FASTQ formatted string containing entire FASTQ entry""" | if self . description :
return '@{0} {1}{4}{2}{4}+{4}{3}{4}' . format ( self . id , self . description , self . sequence , self . quality , os . linesep )
else :
return '@{0}{3}{1}{3}+{3}{2}{3}' . format ( self . id , self . sequence , self . quality , os . linesep ) |
def opcode_list ( self , script ) :
"""Disassemble the given script . Returns a list of opcodes .""" | opcodes = [ ]
new_pc = 0
try :
for opcode , data , pc , new_pc in self . get_opcodes ( script ) :
opcodes . append ( self . disassemble_for_opcode_data ( opcode , data ) )
except ScriptError :
opcodes . append ( binascii . hexlify ( script [ new_pc : ] ) . decode ( "utf8" ) )
return opcodes |
def _port_add_or_delete_policy ( action , name , sel_type = None , protocol = None , port = None , sel_range = None ) :
'''. . versionadded : : 2019.2.0
Performs the action as called from ` ` port _ add _ policy ` ` or ` ` port _ delete _ policy ` ` .
Returns the result of the call to semanage .''' | if action not in [ 'add' , 'delete' ] :
raise SaltInvocationError ( 'Actions supported are "add" and "delete", not "{0}".' . format ( action ) )
if action == 'add' and not sel_type :
raise SaltInvocationError ( 'SELinux Type is required to add a policy' )
( protocol , port ) = _parse_protocol_port ( name , prot... |
def _parse_tree ( self , node ) :
"""Parse a < image > object""" | if 'type' in node . attrib :
self . kind = node . attrib [ 'type' ]
if 'width' in node . attrib :
self . width = int ( node . attrib [ 'width' ] )
if 'height' in node . attrib :
self . height = int ( node . attrib [ 'height' ] )
self . url = node . text |
def down ( self , migration_id ) :
"""Rollback to migration .""" | if not self . check_directory ( ) :
return
for migration in self . get_migrations_to_down ( migration_id ) :
logger . info ( 'Rollback migration %s' % migration . filename )
migration_module = self . load_migration_file ( migration . filename )
if hasattr ( migration_module , 'down' ) :
migratio... |
def process_request ( self , request ) :
"""Redirects the current request if there is a matching Redirect model
with the current request URL as the old _ path field .""" | site = request . site
cache_key = '{prefix}-{site}' . format ( prefix = settings . REDIRECT_CACHE_KEY_PREFIX , site = site . domain )
redirects = cache . get ( cache_key )
if redirects is None :
redirects = { redirect . old_path : redirect . new_path for redirect in Redirect . objects . filter ( site = site ) }
... |
def handle_cmd ( self , cmd ) :
"""Handles a single server command .""" | cmd = cmd . strip ( )
segments = [ ]
for s in cmd . split ( ) : # remove bash - like comments
if s . startswith ( '#' ) :
break
# TODO implement escape sequences ( also for \ # )
segments . append ( s )
args = [ ]
if not len ( segments ) :
return
# process more specific commands first
while segm... |
def write_injections ( self , injection_file ) :
"""Writes injection parameters from the given injection file .
Everything in the injection file is copied to ` ` injections _ group ` ` .
Parameters
injection _ file : str
Path to HDF injection file .""" | try :
with h5py . File ( injection_file , "r" ) as fp :
super ( BaseInferenceFile , self ) . copy ( fp , self . injections_group )
except IOError :
logging . warn ( "Could not read %s as an HDF file" , injection_file ) |
def cache ( self , key , value ) :
"""Add an entry to the cache .
A weakref to the value is stored , rather than a direct reference . The
value must have a C { _ _ finalizer _ _ } method that returns a callable which
will be invoked when the weakref is broken .
@ param key : The key identifying the cache en... | fin = value . __finalizer__ ( )
try : # It ' s okay if there ' s already a cache entry for this key as long
# as the weakref has already been broken . See the comment in
# get ( ) for an explanation of why this might happen .
if self . data [ key ] ( ) is not None :
raise CacheInconsistency ( "Duplicate cac... |
def set_data ( self , frames ) :
"""Prepare the input of model""" | data_frames = [ ]
for frame in frames : # frame H x W x C
frame = frame . swapaxes ( 0 , 1 )
# swap width and height to form format W x H x C
if len ( frame . shape ) < 3 :
frame = np . array ( [ frame ] ) . swapaxes ( 0 , 2 ) . swapaxes ( 0 , 1 )
# Add grayscale channel
data_frames . ap... |
def find_all_sift ( im_source , im_search , min_match_count = 4 , maxcnt = 0 ) :
'''使用sift算法进行多个相同元素的查找
Args :
im _ source ( string ) : 图像 、 素材
im _ search ( string ) : 需要查找的图片
threshold : 阈值 , 当相识度小于该阈值的时候 , 就忽略掉
maxcnt : 限制匹配的数量
Returns :
A tuple of found [ ( point , rectangle ) , . . . ]
A tuple ... | sift = _sift_instance ( )
flann = cv2 . FlannBasedMatcher ( { 'algorithm' : FLANN_INDEX_KDTREE , 'trees' : 5 } , dict ( checks = 50 ) )
kp_sch , des_sch = sift . detectAndCompute ( im_search , None )
if len ( kp_sch ) < min_match_count :
return None
kp_src , des_src = sift . detectAndCompute ( im_source , None )
if... |
def get ( self , url , timeout = None , headers = None , params = None , cache_ext = None ) :
"""Make get request to url ( might use cache )
: param url : Url to make request to
: type url : str | unicode
: param timeout : Timeout for request ( default : None )
None - > infinite timeout
: type timeout : N... | if headers is None :
headers = { }
cached = cache_info = None
# TODO : add params to caching key
if self . cache :
cached , cache_info = self . cache . get ( url )
if cache_ext : # Check local cache
if not cache_info :
cache_info = cache_ext
if cache_info . access_time and cache_ext . access_tim... |
def convert_id_to_model ( value , parameter ) :
'''Converts to a Model object .
' ' , ' - ' , ' 0 ' , None convert to parameter default
Anything else is assumed an object id and sent to ` . get ( id = value ) ` .''' | value = _check_default ( value , parameter , ( '' , '-' , '0' , None ) )
if isinstance ( value , ( int , str ) ) : # only convert if we have the id
try :
return parameter . type . objects . get ( id = value )
except ( MultipleObjectsReturned , ObjectDoesNotExist ) as e :
raise ValueError ( str (... |
def radio_status_encode ( self , rssi , remrssi , txbuf , noise , remnoise , rxerrors , fixed ) :
'''Status generated by radio and injected into MAVLink stream .
rssi : Local signal strength ( uint8 _ t )
remrssi : Remote signal strength ( uint8 _ t )
txbuf : Remaining free buffer space in percent . ( uint8 _... | return MAVLink_radio_status_message ( rssi , remrssi , txbuf , noise , remnoise , rxerrors , fixed ) |
def do_gh ( self , arg ) :
"""gh - go with exception handled""" | if self . cmdprefix :
raise CmdError ( "prefix not allowed" )
if arg :
raise CmdError ( "too many arguments" )
if self . lastEvent :
self . lastEvent . continueStatus = win32 . DBG_EXCEPTION_HANDLED
return self . do_go ( arg ) |
def get_transaction_history ( self , max_wait = 5.0 ) :
"""Download full account history .
Uses request _ transaction _ history to get the transaction
history URL , then polls the given URL until it ' s ready ( or
the max _ wait time is reached ) and provides the decoded
response .
Parameters
max _ wait... | url = self . request_transaction_history ( )
if not url :
return False
ready = False
start = time ( )
delay = 0.1
while not ready and delay :
response = requests . head ( url )
ready = response . ok
if not ready :
sleep ( delay )
time_remaining = max_wait - time ( ) + start
max_d... |
def system_qos_qos_service_policy_attach_rbridge_id_add_rb_add_range ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
system_qos = ET . SubElement ( config , "system-qos" , xmlns = "urn:brocade.com:mgmt:brocade-policer" )
qos = ET . SubElement ( system_qos , "qos" )
service_policy = ET . SubElement ( qos , "service-policy" )
direction_key = ET . SubElement ( service_policy , "direction" )
direction_k... |
def _serialize ( self , value , * args , ** kwargs ) :
"""Serialize given datetime to timestamp .""" | if value is not None :
value = super ( MSTimestamp , self ) . _serialize ( value , * args ) * 1e3
return value |
def set_misc ( self ) :
'''Set more parameters , after the tank is better defined than in the
_ _ init _ _ function .
Notes
Two of D , L , and L _ over _ D must be known when this function runs .
The other one is set from the other two first thing in this function .
a _ ratio parameters are used to calcul... | if self . D and self . L : # If L and D are known , get L _ over _ D
self . L_over_D = self . L / self . D
elif self . D and self . L_over_D : # Otherwise , if L _ over _ D and D are provided , get L
self . L = self . D * self . L_over_D
elif self . L and self . L_over_D : # Otherwise , if L _ over _ D and L ar... |
def read_port_stats ( self ) :
""": return : dictionary { group name { stat name : value } } .
Sea XenaPort . stats _ captions .""" | stats_with_captions = OrderedDict ( )
for stat_name in self . stats_captions . keys ( ) :
stats_with_captions [ stat_name ] = self . read_stat ( self . stats_captions [ stat_name ] , stat_name )
return stats_with_captions |
def _get_var_res ( self , graph , var , other_var ) :
"""Get the weights from our graph""" | with tf . Session ( graph = graph ) as sess :
sess . run ( other_var [ "init" ] )
# all _ vars = tf . all _ variables ( )
# print ( " All variable names " )
# print ( [ var . name for var in all _ vars ] )
# print ( " All variable values " )
# print ( sess . run ( all _ vars ) )
var_res = se... |
def _RunAction ( self , rule , client_id ) :
"""Run all the actions specified in the rule .
Args :
rule : Rule which actions are to be executed .
client _ id : Id of a client where rule ' s actions are to be executed .
Returns :
Number of actions started .""" | actions_count = 0
try :
if self . _CheckIfHuntTaskWasAssigned ( client_id , rule . hunt_id ) :
logging . info ( "Foreman: ignoring hunt %s on client %s: was started " "here before" , client_id , rule . hunt_id )
else :
logging . info ( "Foreman: Starting hunt %s on client %s." , rule . hunt_id ,... |
def getClientContact ( self ) :
"""Returns info from the Client contact who coordinates with the lab""" | pc = getToolByName ( api . portal . get ( ) , 'portal_catalog' )
contentFilter = { 'portal_type' : 'Contact' , 'id' : self . client_contact }
cnt = pc ( contentFilter )
cntdict = { 'uid' : '' , 'id' : '' , 'fullname' : '' , 'url' : '' }
if len ( cnt ) == 1 :
cnt = cnt [ 0 ] . getObject ( )
cntdict = { 'uid' : c... |
def get_config_bool_option ( parser : ConfigParser , section : str , option : str , default : bool = None ) -> bool :
"""Retrieves a boolean value from a parser .
Args :
parser : instance of : class : ` ConfigParser `
section : section name within config file
option : option ( variable ) name within that se... | if not parser . has_section ( section ) :
raise ValueError ( "config missing section: " + section )
return parser . getboolean ( section , option , fallback = default ) |
def _figure_data ( self , plot , fmt = 'png' , bbox_inches = 'tight' , as_script = False , ** kwargs ) :
"""Render matplotlib figure object and return the corresponding
data . If as _ script is True , the content will be split in an
HTML and a JS component .
Similar to IPython . core . pylabtools . print _ fi... | if fmt in [ 'gif' , 'mp4' , 'webm' ] :
if sys . version_info [ 0 ] == 3 and mpl . __version__ [ : - 2 ] in [ '1.2' , '1.3' ] :
raise Exception ( "<b>Python 3 matplotlib animation support broken <= 1.3</b>" )
with mpl . rc_context ( rc = plot . fig_rcparams ) :
anim = plot . anim ( fps = self ... |
def pem_to_der ( cert , return_multiple = True ) :
"""Converts a given certificate or list to PEM format""" | # initialize the certificate array
cert_list = [ ]
# If certificate is in DER then un - armour it
if pem . detect ( cert ) :
for _ , _ , der_bytes in pem . unarmor ( cert , multiple = True ) :
cert_list . append ( der_bytes )
else :
cert_list . append ( cert )
# return multiple if return _ multiple is s... |
def codemirror_field_css_bundle ( field ) :
"""Filter to get CodeMirror CSS bundle name needed for a single field .
Example :
{ % load djangocodemirror _ tags % }
{ { form . myfield | codemirror _ field _ css _ bundle } }
Arguments :
field ( djangocodemirror . fields . CodeMirrorField ) : A form field .
... | manifesto = CodemirrorAssetTagRender ( )
manifesto . register_from_fields ( field )
try :
bundle_name = manifesto . css_bundle_names ( ) [ 0 ]
except IndexError :
msg = ( "Given field with configuration name '{}' does not have a " "Javascript bundle name" )
raise CodeMirrorFieldBundleError ( msg . format ( ... |
def read ( self ) :
"""read a single message from the queue""" | resp = self . sqs_client . receive_message ( QueueUrl = self . queue_url , MaxNumberOfMessages = 1 , AttributeNames = ( 'SentTimestamp' , ) , WaitTimeSeconds = self . recv_wait_time_seconds , )
if resp [ 'ResponseMetadata' ] [ 'HTTPStatusCode' ] != 200 :
raise Exception ( 'Invalid status code from sqs: %s' % resp [... |
def ascii85decode ( data ) :
"""In ASCII85 encoding , every four bytes are encoded with five ASCII
letters , using 85 different types of characters ( as 256 * * 4 < 85 * * 5 ) .
When the length of the original bytes is not a multiple of 4 , a special
rule is used for round up .
The Adobe ' s ASCII85 impleme... | n = b = 0
out = b''
for c in data :
if b'!' <= c and c <= b'u' :
n += 1
b = b * 85 + ( ord ( c ) - 33 )
if n == 5 :
out += struct . pack ( '>L' , b )
n = b = 0
elif c == b'z' :
assert n == 0
out += b'\0\0\0\0'
elif c == b'~' :
if n :
... |
def wait ( self , timeout = - 1 ) :
"""Wait for the child to exit .
Wait for at most * timeout * seconds , or indefinitely if * timeout * is
None . Return the value of the : attr : ` returncode ` attribute .""" | if self . _process is None :
raise RuntimeError ( 'no child process' )
if timeout == - 1 :
timeout = self . _timeout
if not self . _child_exited . wait ( timeout ) :
raise Timeout ( 'timeout waiting for child to exit' )
return self . returncode |
def _aggregrate_scores ( its , tss , num_sentences ) :
"""rerank the two vectors by
min aggregrate rank , reorder""" | final = [ ]
for i , el in enumerate ( its ) :
for j , le in enumerate ( tss ) :
if el [ 2 ] == le [ 2 ] :
assert el [ 1 ] == le [ 1 ]
final . append ( ( el [ 1 ] , i + j , el [ 2 ] ) )
_final = sorted ( final , key = lambda tup : tup [ 1 ] ) [ : num_sentences ]
return sorted ( _final... |
def display_bounding_boxes ( img , blocks , alternatecolors = False , color = Color ( "blue" ) ) :
"""Displays each of the bounding boxes passed in ' boxes ' on an image of the pdf
pointed to by pdf _ file
boxes is a list of 5 - tuples ( page , top , left , bottom , right )""" | draw = Drawing ( )
draw . fill_color = Color ( "rgba(0, 0, 0, 0)" )
draw . stroke_color = color
for block in blocks :
top , left , bottom , right = block [ - 4 : ]
if alternatecolors :
draw . stroke_color = Color ( "rgba({},{},{}, 1)" . format ( str ( np . random . randint ( 255 ) ) , str ( np . random ... |
def process ( self , body ) :
"""Process the specified soap envelope body and replace I { multiref } node
references with the contents of the referenced node .
@ param body : A soap envelope body node .
@ type body : L { Element }
@ return : The processed I { body }
@ rtype : L { Element }""" | self . nodes = [ ]
self . catalog = { }
self . build_catalog ( body )
self . update ( body )
body . children = self . nodes
return body |
def add_work_item ( self , work_item ) :
"""Add a WorkItems .
Args :
work _ item : A WorkItem .""" | with self . _conn :
self . _conn . execute ( '''
INSERT INTO work_items
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''' , _work_item_to_row ( work_item ) ) |
def add ( self , visualization ) :
"""Creates a new visualization
: param visualization : instance of Visualization
: return :""" | res = self . es . create ( index = self . index , id = visualization . id or str ( uuid . uuid1 ( ) ) , doc_type = self . doc_type , body = visualization . to_kibana ( ) , refresh = True )
return res |
def putRequest ( self , request , block = True , timeout = 0 ) :
"""Put work request into work queue and save its id for later .""" | # don ' t reuse old work requests
# print ' \ tthread pool putting work request % s ' % request
self . _requests_queue . put ( request , block , timeout )
self . workRequests [ request . requestID ] = request |
def list ( self , page = 1 , per_page = 10 , omit = None ) :
"""List groups by page .
The API allows certain fields to be excluded from the results so that
very large groups can be fetched without exceeding the maximum
response size . At the time of this writing , only ' memberships ' is
supported .
: par... | return pagers . GroupList ( self , self . _raw_list , page = page , per_page = per_page , omit = omit ) |
def children ( self ) :
""": return : a : class : ` NodeList ` of this node ' s child nodes .""" | impl_nodelist = self . adapter . get_node_children ( self . impl_node )
return self . _convert_nodelist ( impl_nodelist ) |
def get_cookbook_dirs ( self , base_dir = None ) :
"""Find cookbook directories .""" | if base_dir is None :
base_dir = self . env_root
cookbook_dirs = [ ]
dirs_to_skip = set ( [ '.git' ] )
for root , dirs , files in os . walk ( base_dir ) : # pylint : disable = W0612
dirs [ : ] = [ d for d in dirs if d not in dirs_to_skip ]
for name in files :
if name == 'metadata.rb' :
i... |
def connect_route53 ( aws_access_key_id = None , aws_secret_access_key = None , ** kwargs ) :
""": type aws _ access _ key _ id : string
: param aws _ access _ key _ id : Your AWS Access Key ID
: type aws _ secret _ access _ key : string
: param aws _ secret _ access _ key : Your AWS Secret Access Key
: rty... | from boto . route53 import Route53Connection
return Route53Connection ( aws_access_key_id , aws_secret_access_key , ** kwargs ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.