signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def generate ( cls ) :
"""Generates a random : class : ` ~ PrivateKey ` object
: rtype : : class : ` ~ PrivateKey `""" | return cls ( libnacl . randombytes ( PrivateKey . SIZE ) , encoder = encoding . RawEncoder ) |
def max_input_length ( self ) -> int :
"""Returns maximum input length for TranslatorInput objects passed to translate ( )""" | if self . source_with_eos :
return self . _max_input_length - C . SPACE_FOR_XOS
else :
return self . _max_input_length |
def values ( self ) :
"""A : class : ` werkzeug . datastructures . CombinedMultiDict ` that combines
: attr : ` args ` and : attr : ` form ` .""" | args = [ ]
for d in self . args , self . form :
if not isinstance ( d , MultiDict ) :
d = MultiDict ( d )
args . append ( d )
return CombinedMultiDict ( args ) |
def cli ( conf ) :
"""The fedora - messaging command line interface .""" | if conf :
if not os . path . isfile ( conf ) :
raise click . exceptions . BadParameter ( "{} is not a file" . format ( conf ) )
try :
config . conf . load_config ( config_path = conf )
except exceptions . ConfigurationException as e :
raise click . exceptions . BadParameter ( str ( e... |
def send ( self , sender , recipients , cc = None , bcc = None , subject = '' , body = '' , attachments = None , content = 'text' ) :
"""Sends the email
: param sender : The server of the message
: param recipients : The recipients ( To : ) of the message
: param cc : The CC recipients of the message
: para... | if not self . connected :
self . _logger . error ( ( 'Server not connected, cannot send message, ' 'please connect() first and disconnect() when ' 'the connection is not needed any more' ) )
return False
try :
message = Message ( sender , recipients , cc , bcc , subject , body , attachments , content )
... |
def _get_stddevs ( self , C , stddev_types , num_sites ) :
"""Return total standard deviation .""" | stddevs = [ ]
for stddev_type in stddev_types :
assert stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES
stddevs . append ( np . log ( 10 ** C [ 'sigma' ] ) + np . zeros ( num_sites ) )
return stddevs |
def _use_remote_connection ( self , kwargs ) :
'''Determine if connection is local or remote''' | kwargs [ 'host' ] = kwargs . get ( 'host' )
kwargs [ 'username' ] = kwargs . get ( 'username' )
kwargs [ 'password' ] = kwargs . get ( 'password' )
if kwargs [ 'host' ] is None or kwargs [ 'username' ] is None or kwargs [ 'password' ] is None :
return False
else :
return True |
def _notify_unload_dll ( self , event ) :
"""Notify the unload of a module .
@ warning : This method is meant to be used internally by the debugger .
@ type event : L { UnloadDLLEvent }
@ param event : Unload DLL event .
@ rtype : bool
@ return : C { True } to call the user - defined handle , C { False } ... | bCallHandler1 = _BreakpointContainer . _notify_unload_dll ( self , event )
bCallHandler2 = event . get_process ( ) . _notify_unload_dll ( event )
return bCallHandler1 and bCallHandler2 |
def split_content_version ( self ) :
"""Remove and return the version ( s ) from the cached content . First the
internal version , and if versioning is activated , the template one .
And finally save the content , but only if all versions match .
The content saved is the encoded one ( if " compress " or
" c... | try :
nb_parts = 2
if self . options . versioning :
nb_parts = 3
parts = self . content . split ( self . VERSION_SEPARATOR , nb_parts - 1 )
assert len ( parts ) == nb_parts
self . content_internal_version = parts [ 0 ]
if self . options . versioning :
self . content_version = par... |
def _build ( self , lexer ) :
"""Build : class : ` ~ ctfile . ctfile . Ctab ` instance .
: return : : class : ` ~ ctfile . ctfile . Ctab ` instance .
: rtype : : class : ` ~ ctfile . ctfile . Ctab ` .""" | atom_number = 1
while True :
token = next ( lexer )
key = token . __class__ . __name__
if key == 'CtabCountsLine' :
self [ key ] . update ( token . _asdict ( ) )
elif key == 'CtabAtomBlock' :
self [ key ] . append ( Atom ( atom_number = str ( atom_number ) , ** token . _asdict ( ) ) )
... |
def authenticate_with_serviceaccount ( reactor , ** kw ) :
"""Create an ` ` IAgent ` ` which can issue authenticated requests to a
particular Kubernetes server using a service account token .
: param reactor : The reactor with which to configure the resulting agent .
: param bytes path : The location of the s... | config = KubeConfig . from_service_account ( ** kw )
policy = https_policy_from_config ( config )
token = config . user [ "token" ]
agent = HeaderInjectingAgent ( _to_inject = Headers ( { u"authorization" : [ u"Bearer {}" . format ( token ) ] } ) , _agent = Agent ( reactor , contextFactory = policy ) , )
return agent |
def _rand1 ( self ) :
"generate a single random sample" | Z = _unwhiten_cf ( self . _S_cf , self . _genA ( ) )
return Z . dot ( Z . T ) |
def validate_owner_repo ( ctx , param , value ) :
"""Ensure that owner / repo is formatted correctly .""" | # pylint : disable = unused - argument
form = "OWNER/REPO"
return validate_slashes ( param , value , minimum = 2 , maximum = 2 , form = form ) |
def removeOntology ( self ) :
"""Removes an ontology from the repo .""" | self . _openRepo ( )
ontology = self . _repo . getOntologyByName ( self . _args . ontologyName )
def func ( ) :
self . _updateRepo ( self . _repo . removeOntology , ontology )
self . _confirmDelete ( "Ontology" , ontology . getName ( ) , func ) |
def _cnvkit_metrics ( cnns , target_bed , antitarget_bed , cov_interval , items ) :
"""Estimate noise of a sample using a flat background .
Only used for panel / targeted data due to memory issues with whole genome
samples .""" | if cov_interval == "genome" :
return cnns
target_cnn = [ x [ "file" ] for x in cnns if x [ "cnntype" ] == "target" ] [ 0 ]
background_file = "%s-flatbackground.cnn" % utils . splitext_plus ( target_cnn ) [ 0 ]
background_file = cnvkit_background ( [ ] , background_file , items , target_bed , antitarget_bed )
cnr_fi... |
def get_article_content ( self , url , del_qqmusic = True , del_mpvoice = True , unlock_callback = None , identify_image_callback = None , hosting_callback = None , raw = False ) :
"""获取文章原文 , 避免临时链接失效
Parameters
url : str or unicode
原文链接 , 临时链接
raw : bool
True : 返回原始html
False : 返回处理后的html
del _ qqmu... | resp = self . __get_by_unlock ( url , unlock_platform = self . __unlock_wechat , unlock_callback = unlock_callback , identify_image_callback = identify_image_callback )
resp . encoding = 'utf-8'
if '链接已过期' in resp . text :
raise WechatSogouException ( 'get_article_content 链接 [{}] 已过期' . format ( url ) )
if raw :
... |
def get_all_child_edges ( self ) :
"""Return tuples for all child GO IDs , containing current GO ID and child GO ID .""" | all_child_edges = set ( )
for parent in self . children :
all_child_edges . add ( ( parent . item_id , self . item_id ) )
all_child_edges |= parent . get_all_child_edges ( )
return all_child_edges |
def getCol ( self , x ) :
"""return the x - th column , starting at 0""" | return [ self . getCell ( x , i ) for i in self . __size_range ] |
def remove_father ( self , father ) :
"""Remove the father node . Do nothing if the node is not a father
Args :
fathers : list of fathers to add""" | self . _fathers = [ x for x in self . _fathers if x . node_id != father . node_id ] |
def get_task_result ( self , task_id ) :
"""Get task result from worker . If the task is not finished , return None .
It ' s prefered to use : class : ` carotte . Task ` object directly .
: param string task _ id : Task ID
: returns : Task dict
: rtype : dict""" | data = { 'action' : 'get_result' , 'id' : task_id }
self . __send_pyobj ( data )
task = self . __recv_pyobj ( )
return task |
def show_pan_mark ( viewer , tf , color = 'red' ) :
"""Show a mark in the pan position ( center of window ) .
Parameters
viewer : an ImageView subclass instance
If True , show the color bar ; else remove it if present .
tf : bool
If True , show the mark ; else remove it if present .
color : str
Color ... | tag = '_$pan_mark'
radius = 10
canvas = viewer . get_private_canvas ( )
try :
mark = canvas . get_object_by_tag ( tag )
if not tf :
canvas . delete_object_by_tag ( tag )
else :
mark . color = color
except KeyError :
if tf :
Point = canvas . get_draw_class ( 'point' )
canv... |
def make_package_tree ( matrix = None , labels = None , width = 25 , height = 10 , title = None , font_size = None ) :
'''make package tree will make a dendrogram comparing a matrix of packages
: param matrix : a pandas df of packages , with names in index and columns
: param labels : a list of labels correspon... | from matplotlib import pyplot as plt
from scipy . cluster . hierarchy import ( dendrogram , linkage )
if font_size is None :
font_size = 8.
from scipy . cluster . hierarchy import cophenet
from scipy . spatial . distance import pdist
if not isinstance ( matrix , pandas . DataFrame ) :
bot . info ( "No pandas Da... |
def ensure_port_cleanup ( bound_addresses , maxtries = 30 , sleeptime = 2 ) :
"""This makes sure any open ports are closed .
Does this by connecting to them until they give connection
refused . Servers should call like : :
import paste . script
ensure _ port _ cleanup ( [ 80 , 443 ] )""" | atexit . register ( _cleanup_ports , bound_addresses , maxtries = maxtries , sleeptime = sleeptime ) |
def parse_input ( s ) :
"""Parse the given input and intelligently transform it into an absolute ,
non - naive , timezone - aware datetime object for the UTC timezone .
The input can be specified as a millisecond - precision UTC timestamp ( or
delta against Epoch ) , with or without a terminating ' L ' . Alte... | if isinstance ( s , six . integer_types ) :
s = str ( s )
elif not isinstance ( s , six . string_types ) :
raise ValueError ( s )
original = s
if s [ - 1 : ] == 'L' :
s = s [ : - 1 ]
sign = { '-' : - 1 , '=' : 0 , '+' : 1 } . get ( s [ 0 ] , None )
if sign is not None :
s = s [ 1 : ]
ts = 0
for unit in ... |
def as_completed ( fs , timeout = None ) :
"""An iterator over the given futures that yields each as it completes .
Args :
fs : The sequence of Futures ( possibly created by different Executors ) to
iterate over .
timeout : The maximum number of seconds to wait . If None , then there
is no limit on the wa... | if timeout is not None :
end_time = timeout + time . time ( )
fs = set ( fs )
with _AcquireFutures ( fs ) :
finished = set ( f for f in fs if f . _state in [ CANCELLED_AND_NOTIFIED , FINISHED ] )
pending = fs - finished
waiter = _create_and_install_waiters ( fs , _AS_COMPLETED )
try :
for future in ... |
def send_im ( self , target , message , mentions = None , parse = None , update_msg_id = None , wrap_length = 5000 ) :
"""Send text message .
: param target : Target user UIN or chat ID .
: param message : Message text .
: param mentions : Iterable with UINs to mention in message .
: param parse : Iterable ... | try :
responses = set ( )
for text in wrap ( string = str ( message ) , length = wrap_length ) :
response = self . http_session . post ( url = "{}/im/sendIM" . format ( self . api_base_url ) , data = { "r" : uuid . uuid4 ( ) , "aimsid" : self . token , "t" : target , "message" : text , "mentions" : ( me... |
def create ( cls , name , vm , size , snapshotprofile , datacenter , source , disk_type = 'data' , background = False ) :
"""Create a disk and attach it to a vm .""" | if isinstance ( size , tuple ) :
prefix , size = size
if source :
size = None
disk_params = cls . disk_param ( name , size , snapshotprofile )
disk_params [ 'datacenter_id' ] = int ( Datacenter . usable_id ( datacenter ) )
disk_params [ 'type' ] = disk_type
if source :
disk_id = int ( Image . usable_id ( so... |
def list ( self ) :
"""Get ' s all of the LXC ' s and creates objects for them""" | service = self . _service
lxc_names = service . list_names ( )
lxc_list = [ ]
for name in lxc_names :
lxc = self . get ( name )
lxc_list . append ( lxc )
return lxc_list |
def ReadIndex ( self , index_file = None ) :
"""Reads the IndexTable index file of commands and templates .
Args :
index _ file : String , file where template / command mappings reside .
Raises :
CliTableError : A template column was not found in the table .""" | self . index_file = index_file or self . index_file
fullpath = os . path . join ( self . template_dir , self . index_file )
if self . index_file and fullpath not in self . INDEX :
self . index = IndexTable ( self . _PreParse , self . _PreCompile , fullpath )
self . INDEX [ fullpath ] = self . index
else :
s... |
def get_list_w_id2nts ( ids , id2nts , flds , dflt_null = "" ) :
"""Return a new list of namedtuples by combining " dicts " of namedtuples or objects .""" | combined_nt_list = [ ]
# 1 . Instantiate namedtuple object
ntobj = cx . namedtuple ( "Nt" , " " . join ( flds ) )
# 2 . Fill dict with namedtuple objects for desired ids
for item_id in ids : # 2a . Combine various namedtuples into a single namedtuple
nts = [ id2nt . get ( item_id ) for id2nt in id2nts ]
vals = ... |
def translate ( self , type_ ) :
"""Given a built - in , an otherwise known type , or a name of known type , return its corresponding wrapper type : :
> > > Types . translate ( int )
< _ IntType ( ' int ' , ' integer ' ) >
> > > Types . translate ( ' string ' )
< _ StrType ( ' str ' , ' string ' , ' unicode... | if isinstance ( type_ , six . string_types ) :
for t in self . all_types :
if type_ in t . aliases :
return t
raise ValueError ( 'Failed to recognise type by name {!r}' . format ( type_ ) )
for t in self . all_types :
if type_ in t . builtin_types :
return t
return type_ |
def __remove_category ( self , id ) :
"""move all activities to unsorted and remove category""" | affected_query = """
SELECT id
FROM facts
WHERE activity_id in (SELECT id FROM activities where category_id=?)
"""
affected_ids = [ res [ 0 ] for res in self . fetchall ( affected_query , ( id , ) ) ]
update = "update activities set category_id = -1 where category_id = ?"
... |
def __store_any ( self , o , method_name , member ) :
"""Determines type of member and stores it accordingly
: param mixed o : Any parent object
: param str method _ name : The name of the method or attribuet
: param mixed member : Any child object""" | if should_exclude ( eval ( "o." + method_name ) , self . __exclusion_list ) :
self . __store__ [ method_name ] = eval ( "o." + method_name )
return
if hasattr ( member , '__call__' ) :
self . __store_callable ( o , method_name , member )
elif inspect . isclass ( member ) :
self . __store_class ( o , met... |
async def get_info ( self ) :
"""Return a client . ModelInfo object for this Model .
Retrieves latest info for this Model from the api server . The
return value is cached on the Model . info attribute so that the
valued may be accessed again without another api call , if
desired .
This method is called au... | facade = client . ClientFacade . from_connection ( self . connection ( ) )
self . _info = await facade . ModelInfo ( )
log . debug ( 'Got ModelInfo: %s' , vars ( self . info ) )
return self . info |
def attach_ip ( self , server , family = 'IPv4' ) :
"""Attach a new ( random ) IPAddress to the given server ( object or UUID ) .""" | body = { 'ip_address' : { 'server' : str ( server ) , 'family' : family } }
res = self . request ( 'POST' , '/ip_address' , body )
return IPAddress ( cloud_manager = self , ** res [ 'ip_address' ] ) |
def execute_command ( self , generator , write_concern , session ) :
"""Execute using write commands .""" | # nModified is only reported for write commands , not legacy ops .
full_result = { "writeErrors" : [ ] , "writeConcernErrors" : [ ] , "nInserted" : 0 , "nUpserted" : 0 , "nMatched" : 0 , "nModified" : 0 , "nRemoved" : 0 , "upserted" : [ ] , }
op_id = _randint ( )
def retryable_bulk ( session , sock_info , retryable ) :... |
def name ( self , address ) :
"""Look up the name that the address points to , using a
reverse lookup . Reverse lookup is opt - in for name owners .
: param address :
: type address : hex - string""" | reversed_domain = address_to_reverse_domain ( address )
return self . resolve ( reversed_domain , get = 'name' ) |
def as_dict ( self , join = '.' ) :
"""Returns all the errors in this collection as a path to message
dictionary . Paths are joined with the ` ` join ` ` string .""" | result = { }
for e in self . errors :
result . update ( e . as_dict ( join ) )
return result |
def _get_distance_term ( self , C , rhypo , mag ) :
"""Returns the distance scaling term""" | h_eff = self . _get_effective_distance ( mag )
r_val = np . sqrt ( rhypo ** 2.0 + h_eff ** 2.0 )
return C [ "c3" ] * np . log10 ( r_val ) |
async def open ( self ) -> 'Wallet' :
"""Explicit entry . Open wallet as configured , for later closure via close ( ) .
For use when keeping wallet open across multiple calls .
Raise any IndyError causing failure to open wallet , WalletState if wallet already open ,
or AbsentWallet on attempt to enter wallet ... | LOGGER . debug ( 'Wallet.open >>>' )
created = False
while True :
try :
self . _handle = await wallet . open_wallet ( json . dumps ( self . config ) , json . dumps ( self . access_creds ) )
LOGGER . info ( 'Opened wallet %s on handle %s' , self . name , self . handle )
break
except IndyE... |
def sinus_values_by_hz ( framerate , hz , max_value ) :
"""Create sinus values with the given framerate and Hz .
Note :
We skip the first zero - crossing , so the values can be used directy in a loop .
> > > values = sinus _ values _ by _ hz ( 22050 , 1200 , 255)
> > > len ( values ) # 22050 / 1200Hz = 18,3... | count = int ( round ( float ( framerate ) / float ( hz ) ) )
count += 1
values = tuple ( sinus_values ( count , max_value ) )
values = values [ 1 : ]
return values |
def persisted ( cls , seconds = 0 , minutes = 0 , hours = 0 , days = 0 , weeks = 0 ) :
"""Cache the return of the function for given time .
Default to 1 day .
: param weeks : as name
: param seconds : as name
: param minutes : as name
: param hours : as name
: param days : as name
: return : return of... | days += weeks * 7
hours += days * 24
minutes += hours * 60
seconds += minutes * 60
if seconds == 0 : # default to 1 day
seconds = 24 * 60 * 60
def get_persisted_file ( hash_number ) :
folder = cls . get_persist_folder ( )
if not os . path . exists ( folder ) :
os . makedirs ( folder )
return os ... |
def fromfile ( cls , fileobj , coltype = LIGOTimeGPS ) :
"""Return a Cache object whose entries are read from an open file .""" | c = [ cls . entry_class ( line , coltype = coltype ) for line in fileobj ]
return cls ( c ) |
def pin_chat_message ( chat_id , message_id , disable_notification = None , ** kwargs ) :
"""Use this method to pin a message in a supergroup or a channel . The bot must be an administrator in the chat for this to work and
must have the ‘ can _ pin _ messages ’ admin right in the supergroup or ‘ can _ edit _ mess... | # required args
params = dict ( chat_id = chat_id , message_id = message_id )
params . update ( _clean_params ( disable_notification = disable_notification , ) )
return TelegramBotRPCRequest ( 'pinChatMessage' , params = params , on_result = lambda result : result , ** kwargs ) |
def sense_tta ( self , target ) :
"""Sense for a Type A Target is supported for 106 , 212 and 424
kbps . However , there may not be any target that understands the
activation commands in other than 106 kbps .""" | log . debug ( "polling for NFC-A technology" )
if target . brty not in ( "106A" , "212A" , "424A" ) :
message = "unsupported bitrate {0}" . format ( target . brty )
raise nfc . clf . UnsupportedTargetError ( message )
self . chipset . in_set_rf ( target . brty )
self . chipset . in_set_protocol ( self . chipset... |
def get_input_media_referenced_files ( self , var_name ) :
"""Generates a tuple with the value for the json / url argument and a dictionary for the multipart file upload .
Will return something which might be similar to
` ( ' attach : / / { var _ name } ' , { var _ name : ( ' foo . png ' , open ( ' foo . png ' ... | # file to be uploaded
string = 'attach://{name}' . format ( name = var_name )
return string , self . get_request_files ( var_name ) |
def _getResourceClass ( self ) :
"""Return the concrete subclass of Resource that ' s appropriate for auto - deploying this module .""" | if self . fromVirtualEnv :
subcls = VirtualEnvResource
elif os . path . isdir ( self . _resourcePath ) :
subcls = DirectoryResource
elif os . path . isfile ( self . _resourcePath ) :
subcls = FileResource
elif os . path . exists ( self . _resourcePath ) :
raise AssertionError ( "Neither a file or a dire... |
def sample ( self ) :
"""Sample from M - H algorithm
Returns
chain : np . array
Chains for each parameter
mean _ est : np . array
Mean values for each parameter
median _ est : np . array
Median values for each parameter
upper _ 95 _ est : np . array
Upper 95 % credibility interval for each paramet... | acceptance = 1
finish = 0
while ( acceptance < 0.234 or acceptance > 0.4 ) or finish == 0 : # If acceptance is in range , proceed to sample , else continue tuning
if not ( acceptance < 0.234 or acceptance > 0.4 ) :
finish = 1
if not self . quiet_progress :
print ( "" )
print ... |
def _do_print ( self , cmd , args ) :
"""Display symbols .
p Display names of inspectable objects .
p < id > Display the content of an object .""" | name = args [ 0 ] . strip ( )
if not name :
self . stderr . write ( 'TODO: Display names of inspectable objects.\n' )
return
try :
code = textwrap . dedent ( r'''
self.stdout.write(name + ':\n' + textwrap.indent(pprint.pformat({}), ' ') + '\n')
''' ) . format ( nam... |
def hdel ( self , name , * keys ) :
"""Delete one or more hash field .
: param name : str the name of the redis key
: param keys : on or more members to remove from the key .
: return : Future ( )""" | with self . pipe as pipe :
m_encode = self . memberparse . encode
keys = [ m_encode ( m ) for m in self . _parse_values ( keys ) ]
return pipe . hdel ( self . redis_key ( name ) , * keys ) |
def get_kbd_values_by_def ( confdict , searchwith = "" ) :
"""Return a list of values by searching a dynamic kb .
: param confdict : dictionary with keys " field " , " expression "
and " collection " name
: param searchwith : a term to search with
: return : list of values""" | from invenio_search . api import Query
# get the configuration so that we see what the field is
if not confdict :
return [ ]
if 'field' not in confdict :
return [ ]
field = confdict [ 'field' ]
expression = confdict [ 'expression' ]
collection = ""
if 'collection' in confdict :
collection = confdict [ 'coll... |
def encloses_annulus ( x_min , x_max , y_min , y_max , nx , ny , r_in , r_out ) :
'''Encloses function backported from old photutils''' | gout = circular_overlap_grid ( x_min , x_max , y_min , y_max , nx , ny , r_out , 1 , 1 )
gin = circular_overlap_grid ( x_min , x_max , y_min , y_max , nx , ny , r_in , 1 , 1 )
return gout - gin |
def _get_types ( func , clsm , slf , clss = None , prop_getter = False , unspecified_type = Any , infer_defaults = None ) :
"""Helper for get _ types and get _ member _ types .""" | func0 = util . _actualfunc ( func , prop_getter )
# check consistency regarding special case with ' self ' - keyword
if not slf :
argNames = util . getargnames ( util . getargspecs ( func0 ) )
if len ( argNames ) > 0 :
if clsm :
if argNames [ 0 ] != 'cls' :
util . _warn_argna... |
def remote_file_size ( self , remote_cmd = "" , remote_file = None ) :
"""Get the file size of the remote file .""" | if remote_file is None :
if self . direction == "put" :
remote_file = self . dest_file
elif self . direction == "get" :
remote_file = self . source_file
if not remote_cmd :
remote_cmd = "dir {}/{}" . format ( self . file_system , remote_file )
remote_out = self . ssh_ctl_chan . send_command ... |
def setup ( self , app : web . Application ) :
"""Installation routes to app . router
: param app : instance of aiohttp . web . Application""" | if self . app is app :
raise ValueError ( 'The router is already configured ' 'for this application' )
self . app = app
routes = sorted ( ( ( r . name , ( r , r . url_for ( ) . human_repr ( ) ) ) for r in self . routes ( ) ) , key = utils . sort_key )
exists = set ( )
# type : Set [ str ]
for name , ( route , path ... |
def pretty_str ( self , indent = 0 ) :
"""Return a human - readable string representation of this object .
Kwargs :
indent ( int ) : The amount of spaces to use as indentation .""" | spaces = ' ' * indent
pretty = spaces + 'class ' + self . name
if self . superclasses :
superclasses = ', ' . join ( self . superclasses )
pretty += '(' + superclasses + ')'
pretty += ':\n'
if self . members :
pretty += '\n\n' . join ( c . pretty_str ( indent + 2 ) for c in self . members )
else :
prett... |
def quilc_compile_payload ( quil_program , isa , specs ) :
"""REST payload for : py : func : ` ForestConnection . _ quilc _ compile `""" | if not quil_program :
raise ValueError ( "You have attempted to compile an empty program." " Please provide an actual program." )
if not isinstance ( quil_program , Program ) :
raise TypeError ( "quil_program must be a Program object." )
if not isinstance ( isa , ISA ) :
raise TypeError ( "isa must be an IS... |
def fused_multiply_adder ( mult_A , mult_B , add , signed = False , reducer = adders . wallace_reducer , adder_func = adders . kogge_stone ) :
"""Generate efficient hardware for a * b + c .
Multiplies two wirevectors together and adds a third wirevector to the
multiplication result , all in
one step . By doin... | # TODO : Specify the length of the result wirevector
return generalized_fma ( ( ( mult_A , mult_B ) , ) , ( add , ) , signed , reducer , adder_func ) |
def glitter_startbody ( context ) :
"""Template tag which renders the glitter overlay and sidebar . This is only
shown to users with permission to edit the page .""" | user = context . get ( 'user' )
path_body = 'glitter/include/startbody.html'
path_plus = 'glitter/include/startbody_%s_%s.html'
rendered = ''
if user is not None and user . is_staff :
templates = [ path_body ]
# We ' ve got a page with a glitter object :
# - May need a different startbody template
# - C... |
def variable_length_to_fixed_length_vector_encoding ( self , vector_encoding_name , left_edge = 4 , right_edge = 4 , max_length = 15 ) :
"""Encode variable - length sequences using a fixed - length encoding designed
for preserving the anchor positions of class I peptides .
The sequences must be of length at lea... | cache_key = ( "fixed_length_vector_encoding" , vector_encoding_name , left_edge , right_edge , max_length )
if cache_key not in self . encoding_cache :
fixed_length_sequences = ( self . sequences_to_fixed_length_index_encoded_array ( self . sequences , left_edge = left_edge , right_edge = right_edge , max_length = ... |
def is_path_python_module ( thepath ) :
"""Given a path , find out of the path is a python module or is inside
a python module .""" | thepath = path . normpath ( thepath )
if path . isfile ( thepath ) :
base , ext = path . splitext ( thepath )
if ext in _py_suffixes :
return True
return False
if path . isdir ( thepath ) :
for suffix in _py_suffixes :
if path . isfile ( path . join ( thepath , '__init__%s' % suffix ) ) ... |
def get_first ( self , n = 1 ) :
"""Retrieve the first n rows from the table
: param n : number of rows to return
: return : list of rows""" | rows = [ ]
# Get values from the partial db first
if self . tracker . dbcon_master and check_table_exists ( self . tracker . dbcon_master , self . name ) :
rows . extend ( get_first_row ( self . tracker . dbcon_master , self . name , n ) )
# Then add rows from the master if required
if len ( rows ) < n and self . t... |
def keygrip_nist256 ( vk ) :
"""Compute keygrip for NIST256 curve public keys .""" | curve = vk . curve . curve
gen = vk . curve . generator
g = ( 4 << 512 ) | ( gen . x ( ) << 256 ) | gen . y ( )
point = vk . pubkey . point
q = ( 4 << 512 ) | ( point . x ( ) << 256 ) | point . y ( )
return _compute_keygrip ( [ [ 'p' , util . num2bytes ( curve . p ( ) , size = 32 ) ] , [ 'a' , util . num2bytes ( curve ... |
def read_user_data ( self , user_data_path ) :
"""Reads and parses a user _ data file .
Args :
user _ data _ path ( str ) :
path to the userdata file
Returns :
str : the parsed user data file""" | raw_user_data = read_value_from_path ( user_data_path )
variables = self . get_variables ( )
return parse_user_data ( variables , raw_user_data , self . name ) |
def classify ( self , peer_dir_meta ) :
"""Classify this entry as ' new ' , ' unmodified ' , or ' modified ' .""" | assert self . classification is None
peer_entry_meta = None
if peer_dir_meta : # Metadata is generally available , so we can detect ' new ' or ' modified '
peer_entry_meta = peer_dir_meta . get ( self . name , False )
if self . is_dir ( ) : # Directories are considered ' unmodified ' ( would require deep traver... |
def __get_url ( url ) :
"""Load json data from url and return result .""" | log . info ( "Retrieving weather data (%s)..." , url )
result = { SUCCESS : False , MESSAGE : None }
try :
r = requests . get ( url )
result [ STATUS_CODE ] = r . status_code
result [ HEADERS ] = r . headers
result [ CONTENT ] = r . text
if ( 200 == r . status_code ) :
result [ SUCCESS ] = ... |
def isDirty ( self , CachableItem ) :
"""True if cached information requires update for ICachableItem""" | _cachedItem = self . get ( CachableItem )
if not _cachedItem :
return True
_newCacheItem = self . mapper . get ( CachableItem )
return False if _cachedItem == _newCacheItem else True |
def container_instance_from_string ( id ) :
"""Create a ContainerInstance from an id string""" | try :
service , instance = id . rsplit ( '_' , 1 )
instance = int ( instance )
except ( TypeError , ValueError ) :
raise context . ValueError ( "Invalid container id %r" % id )
return _proto . ContainerInstance ( service_name = service , instance = instance ) |
def all_keys ( self ) :
'''Merge managed keys with local keys''' | keys = self . list_keys ( )
keys . update ( self . local_keys ( ) )
return keys |
def uncomment_or_update_or_append_line ( filename , prefix , new_line , comment = '#' , keep_backup = True , update_or_append_line = update_or_append_line ) :
'''Remove the comment of an commented out line and make the line " active " .
If such an commented out line not exists it would be appended .''' | uncommented = update_or_append_line ( filename , prefix = comment + prefix , new_line = new_line , keep_backup = keep_backup , append = False )
if not uncommented :
update_or_append_line ( filename , prefix , new_line , keep_backup = keep_backup , append = True ) |
def spectra ( self , alpha = None , nmax = None , convention = 'power' , unit = 'per_l' , base = 10. ) :
"""Return the spectra of one or more Slepian functions .
Usage
spectra = x . spectra ( [ alpha , nmax , convention , unit , base ] )
Returns
spectra : ndarray , shape ( lmax + 1 , nmax )
A matrix with ... | if alpha is None :
if nmax is None :
nmax = self . nmax
spectra = _np . zeros ( ( self . lmax + 1 , nmax ) )
for iwin in range ( nmax ) :
coeffs = self . to_array ( iwin )
spectra [ : , iwin ] = _spectrum ( coeffs , normalization = '4pi' , convention = convention , unit = unit , base... |
def _pfp__build ( self , stream = None , save_offset = False ) :
"""Build the field and write the result into the stream
: stream : An IO stream that can be written to
: returns : None""" | if save_offset and stream is not None :
self . _pfp__offset = stream . tell ( )
# returns either num bytes written or total data
res = utils . binary ( "" ) if stream is None else 0
# iterate IN ORDER
for child in self . _pfp__children :
child_res = child . _pfp__build ( stream , save_offset )
res += child_... |
def _get_reference ( self ) :
"""Sets up references to important components . A reference is typically an
index or a list of indices that point to the corresponding elements
in a flattened array , which is how MuJoCo stores physical simulation data .""" | super ( ) . _get_reference ( )
self . hole_body_id = self . sim . model . body_name2id ( "hole" )
self . cyl_body_id = self . sim . model . body_name2id ( "cylinder" ) |
def delete_alarms ( deployment_id , alert_id = None , metric_name = None , api_key = None , profile = 'telemetry' ) :
'''delete an alert specified by alert _ id or if not specified blows away all the alerts
in the current deployment .
Returns ( bool success , str message ) tuple .
CLI Example :
salt myminio... | auth = _auth ( profile = profile )
if alert_id is None : # Delete all the alarms associated with this deployment
alert_ids = get_alert_config ( deployment_id , api_key = api_key , profile = profile )
else :
alert_ids = [ alert_id ]
if not alert_ids :
return False , "failed to find alert associated with depl... |
def discharge ( ctx , content , key , locator , checker ) :
'''Handles a discharge request as received by the / discharge
endpoint .
@ param ctx The context passed to the checker { checkers . AuthContext }
@ param content URL and form parameters { dict }
@ param locator Locator used to add third party cavea... | id = content . get ( 'id' )
if id is not None :
id = id . encode ( 'utf-8' )
else :
id = content . get ( 'id64' )
if id is not None :
id = utils . b64decode ( id )
caveat = content . get ( 'caveat64' )
if caveat is not None :
caveat = utils . b64decode ( caveat )
return bakery . discharge ( ctx ... |
def get_users_with_permission ( obj , permission ) :
"""Return users with specific permission on object .
: param obj : Object to return users for
: param permission : Permission codename""" | user_model = get_user_model ( )
return user_model . objects . filter ( userobjectpermission__object_pk = obj . pk , userobjectpermission__permission__codename = permission , ) . distinct ( ) |
def db_create ( name , user = None , host = None , port = None , maintenance_db = None , password = None , tablespace = None , encoding = None , lc_collate = None , lc_ctype = None , owner = None , template = None , runas = None ) :
'''Adds a databases to the Postgres server .
CLI Example :
. . code - block : :... | # Base query to create a database
query = 'CREATE DATABASE "{0}"' . format ( name )
# " With " - options to create a database
with_args = salt . utils . odict . OrderedDict ( [ ( 'TABLESPACE' , _quote_ddl_value ( tablespace , '"' ) ) , # owner needs to be enclosed in double quotes so postgres
# doesn ' t get thrown by ... |
def handle_process_output ( process , stdout_handler , stderr_handler , finalizer = None , decode_streams = True ) :
"""Registers for notifications to lean that process output is ready to read , and dispatches lines to
the respective line handlers .
This function returns once the finalizer returns
: return : ... | # Use 2 " pump " threads and wait for both to finish .
def pump_stream ( cmdline , name , stream , is_decode , handler ) :
try :
for line in stream :
if handler :
if is_decode :
line = line . decode ( defenc )
handler ( line )
except Except... |
def set ( cls , color ) :
"""Sets the terminal to the passed color .
: param color : one of the availabe colors .""" | sys . stdout . write ( cls . colors . get ( color , cls . colors [ 'RESET' ] ) ) |
def tablename_from_link ( klass , link ) :
"""Helper method for URL ' s that look like / api / now / v1 / table / FOO / sys _ id etc .""" | arr = link . split ( "/" )
i = arr . index ( "table" )
tn = arr [ i + 1 ]
return tn |
def VerifyStructure ( self , parser_mediator , lines ) :
"""Verifies whether content corresponds to an SCCM log file .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
lines ( str ) : one or more lines from the text file .... | # Identify the token to which we attempt a match .
match = self . _PARSING_COMPONENTS [ 'msg_left_delimiter' ] . match
# Because logs files can lead with a partial event ,
# we can ' t assume that the first character ( post - BOM )
# in the file is the beginning of our match - so we
# look for match anywhere in lines .... |
def create ( self , metric_id , value , timestamp = None ) :
"""Add a Metric Point to a Metric
: param int metric _ id : Metric ID
: param int value : Value to plot on the metric graph
: param str timestamp : Unix timestamp of the point was measured
: return : Created metric point data ( : class : ` dict ` ... | data = ApiParams ( )
data [ 'value' ] = value
data [ 'timestamp' ] = timestamp
return self . _post ( 'metrics/%s/points' % metric_id , data = data ) [ 'data' ] |
def parse_args_kwargs ( self , * args , ** kwargs ) :
'''Parse the arguments with keywords .''' | # unpack the arginfo
keys , defdict = self . arginfo
assigned = keys [ : len ( args ) ]
not_assigned = keys [ len ( args ) : ]
# validate kwargs
for key in kwargs :
assert key not in assigned
assert key in keys
# integrate args and kwargs
knowns = dict ( defdict , ** kwargs )
parsed_args = args + tuple ( [ know... |
def Update ( self , menu = None , tooltip = None , filename = None , data = None , data_base64 = None , ) :
'''Updates the menu , tooltip or icon
: param menu : menu defintion
: param tooltip : string representing tooltip
: param filename : icon filename
: param data : icon raw image
: param data _ base64... | # Menu
if menu is not None :
self . TaskBarIcon . menu = menu
if filename :
self . icon = wx . Icon ( filename , wx . BITMAP_TYPE_ANY )
elif data_base64 :
self . icon = PyEmbeddedImage ( data_base64 ) . GetIcon ( )
elif not self . icon :
self . icon = PyEmbeddedImage ( DEFAULT_BASE64_ICON ) . GetIcon ( ... |
def getFileHandle ( self , dataFile , openMethod ) :
"""Returns handle associated to the filename . If the file is
already opened , update its priority in the cache and return
its handle . Otherwise , open the file using openMethod , store
it in the cache and return the corresponding handle .""" | if dataFile in self . _memoTable :
handle = self . _memoTable [ dataFile ]
self . _update ( dataFile , handle )
return handle
else :
try :
handle = openMethod ( dataFile )
except ValueError :
raise exceptions . FileOpenFailedException ( dataFile )
self . _memoTable [ dataFile ] =... |
def _get_artifact_context ( run , file_type ) :
"""Gets the artifact details for the given run and file _ type .""" | sha1sum = None
image_file = False
log_file = False
config_file = False
if request . path == '/image' :
image_file = True
if file_type == 'before' :
sha1sum = run . ref_image
elif file_type == 'diff' :
sha1sum = run . diff_image
elif file_type == 'after' :
sha1sum = run . image
... |
def calc_rr ( qrs_locs , fs = None , min_rr = None , max_rr = None , qrs_units = 'samples' , rr_units = 'samples' ) :
"""Compute rr intervals from qrs indices by extracting the time
differences .
Parameters
qrs _ locs : numpy array
1d array of qrs locations .
fs : float , optional
Sampling frequency of ... | rr = np . diff ( qrs_locs )
# Empty input qrs _ locs
if not len ( rr ) :
return rr
# Convert to desired output rr units if needed
if qrs_units == 'samples' and rr_units == 'seconds' :
rr = rr / fs
elif qrs_units == 'seconds' and rr_units == 'samples' :
rr = rr * fs
# Apply rr interval filters
if min_rr is n... |
def parse_result ( self , data ) :
"""Returns a YHSM _ GeneratedAEAD instance , or throws pyhsm . exception . YHSM _ CommandFailed .""" | # typedef struct {
# uint8 _ t nonce [ YSM _ AEAD _ NONCE _ SIZE ] ; / / Nonce ( publicId for Yubikey AEADs )
# uint32 _ t keyHandle ; / / Key handle
# YSM _ STATUS status ; / / Status
# uint8 _ t numBytes ; / / Number of bytes in AEAD block
# uint8 _ t aead [ YSM _ AEAD _ MAX _ SIZE ] ; / / AEAD block
# } YSM _ AEAD _... |
def list_controller_revision_for_all_namespaces ( self , ** kwargs ) : # noqa : E501
"""list _ controller _ revision _ for _ all _ namespaces # noqa : E501
list or watch objects of kind ControllerRevision # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP requ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . list_controller_revision_for_all_namespaces_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . list_controller_revision_for_all_namespaces_with_http_info ( ** kwargs )
# noqa : E501
return dat... |
def generate ( env ) :
"""Add Builders and construction variables for javah to an Environment .""" | java_javah = SCons . Tool . CreateJavaHBuilder ( env )
java_javah . emitter = emit_java_headers
env [ '_JAVAHOUTFLAG' ] = JavaHOutFlagGenerator
env [ 'JAVAH' ] = 'javah'
env [ 'JAVAHFLAGS' ] = SCons . Util . CLVar ( '' )
env [ '_JAVAHCLASSPATH' ] = getJavaHClassPath
env [ 'JAVAHCOM' ] = '$JAVAH $JAVAHFLAGS $_JAVAHOUTFL... |
def _fill_gaps ( tr ) :
"""Interpolate through gaps and work - out where gaps are .
: param tr : Gappy trace ( e . g . tr . data is np . ma . MaskedArray )
: type tr : ` obspy . core . stream . Trace `
: return : gaps , trace , where gaps is a list of dict""" | tr = tr . split ( )
gaps = tr . get_gaps ( )
tr = tr . detrend ( ) . merge ( fill_value = 0 ) [ 0 ]
gaps = [ { 'starttime' : gap [ 4 ] , 'endtime' : gap [ 5 ] } for gap in gaps ]
return gaps , tr |
def call_sync_callbacks ( self ) :
"""Call every sync callback with CPU cycles trigger""" | current_cycles = self . cycles
for callback_cycles , callback in self . sync_callbacks : # get the CPU cycles count of the last call
last_call_cycles = self . sync_callbacks_cyles [ callback ]
if current_cycles - last_call_cycles > callback_cycles : # this callback should be called
# Save the current cycles... |
def get_url ( url , parser = 'html' ) :
"""Requests the specified url and returns a BeautifulSoup object with its
contents .""" | url = request . quote ( url , safe = ':/?=&' )
logger . debug ( 'URL: %s' , url )
req = request . Request ( url , headers = { 'User-Agent' : 'foobar' } )
try :
response = request . urlopen ( req )
except HTTPError :
raise
except ( ssl . SSLError , URLError ) : # Some websites ( like metal - archives ) use older... |
async def set_topic ( self , channel , topic ) :
"""Set topic on channel .
Users should only rely on the topic actually being changed when receiving an on _ topic _ change callback .""" | if not self . is_channel ( channel ) :
raise ValueError ( 'Not a channel: {}' . format ( channel ) )
elif not self . in_channel ( channel ) :
raise NotInChannel ( channel )
await self . rawmsg ( 'TOPIC' , channel , topic ) |
def get_rackspace_info ( connection , server_id ) :
"""queries Rackspace for details about a particular server id""" | server = connection . servers . get ( server_id )
data = { }
data [ 'ip_address' ] = server . accessIPv4
data [ 'accessIPv4' ] = server . accessIPv4
data [ 'accessIPv6' ] = server . accessIPv6
data [ 'addresses' ] = server . addresses
data [ 'created' ] = server . created
data [ 'flavor' ] = server . flavor
data [ 'id'... |
def get_transcript_preferences ( course_id ) :
"""Retrieves course wide transcript preferences
Arguments :
course _ id ( str ) : course id""" | try :
transcript_preference = TranscriptPreference . objects . get ( course_id = course_id )
except TranscriptPreference . DoesNotExist :
return
return TranscriptPreferenceSerializer ( transcript_preference ) . data |
def update ( self , items ) :
"""Updates the dependencies in the inverse relationship format , i . e . from an iterable or dict that is structured
as ` ( item , dependent _ items ) ` . Note that this implementation is only valid for 1:1 relationships , i . e . that each
node has also exactly one dependent . For... | for parent , sub_item in _iterate_dependencies ( items ) :
dep = self . _deps [ sub_item ]
if parent not in dep . parent :
dep . parent . append ( parent ) |
def load_extensions_from_config ( ** config ) :
"""Loads extensions""" | extensions = [ ]
if 'EXTENSIONS' in config :
for ext in config [ 'EXTENSIONS' ] :
try :
extensions . append ( locate ( ext ) )
except Exception as e :
print ( e )
return extensions |
def initialize_tasks ( self ) :
"""Load the input queue to capacity .
Overfilling causes a deadlock when ` queue . put ` blocks when
full , so further tasks are enqueued as results are returned .""" | # Add a poison pill to shutdown each process .
self . tasks = chain ( self . iterable , [ POISON_PILL ] * self . num_processes )
for task in islice ( self . tasks , Q_MAX_SIZE ) :
log . debug ( 'Putting %s on queue' , task )
self . task_queue . put ( task ) |
def legal_date ( year , month , day ) :
'''Checks if a given date is a legal positivist date''' | try :
assert year >= 1
assert 0 < month <= 14
assert 0 < day <= 28
if month == 14 :
if isleap ( year + YEAR_EPOCH - 1 ) :
assert day <= 2
else :
assert day == 1
except AssertionError :
raise ValueError ( "Invalid Positivist date: ({}, {}, {})" . format ( year ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.