signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _index_idiom ( el_name , index , alt = None ) :
"""Generate string where ` el _ name ` is indexed by ` index ` if there are enough
items or ` alt ` is returned .
Args :
el _ name ( str ) : Name of the ` container ` which is indexed .
index ( int ) : Index of the item you want to obtain from container . ... | el_index = "%s[%d]" % ( el_name , index )
if index == 0 :
cond = "%s" % el_name
else :
cond = "len(%s) - 1 >= %d" % ( el_name , index )
output = IND + "# pick element from list\n"
return output + IND + "%s = %s if %s else %s\n\n" % ( el_name , el_index , cond , repr ( alt ) ) |
def is_valid_ipv4 ( ip ) :
"""Return True if given ip is a valid IPv4 address .""" | if not _ipv4_re . match ( ip ) :
return False
a , b , c , d = [ int ( i ) for i in ip . split ( "." ) ]
return a <= 255 and b <= 255 and c <= 255 and d <= 255 |
def check_basic_auth ( user , passwd ) :
"""Checks user authentication using HTTP Basic Auth .""" | auth = request . authorization
return auth and auth . username == user and auth . password == passwd |
def attached_sessions ( self ) :
"""Return active : class : ` Session ` objects .
This will not work where multiple tmux sessions are attached .
Returns
list of : class : ` Session `""" | sessions = self . _sessions
attached_sessions = list ( )
for session in sessions :
if 'session_attached' in session : # for now session _ active is a unicode
if session . attached == '1' :
logger . debug ( 'session %s attached' , session . name )
attached_sessions . append ( session ... |
def apply_op ( input_layer , operation , * op_args , ** op_kwargs ) :
"""Applies the given operation to this before without adding any summaries .
Args :
input _ layer : The input layer for this op .
operation : An operation that takes a tensor and the supplied args .
* op _ args : Extra arguments for opera... | return input_layer . with_tensor ( operation ( input_layer . tensor , * op_args , ** op_kwargs ) ) |
def symlink ( target , link ) :
"""os . symlink ( ) but use a junction point on Windows .""" | if islink ( link ) :
unlink ( link )
if platform . system ( ) == "Windows" :
if sys . version_info [ : 2 ] < ( 3 , 5 ) :
with open ( os . devnull , "w" ) as nul :
subprocess . check_call ( [ "mklink" , "/J" , link , target ] , shell = True , stdout = nul )
else :
_winapi . Create... |
def plugin_class_validation ( self , plugin_class ) :
"""Plugin validation
Every workbench plugin must have a dependencies list ( even if it ' s empty ) .
Every workbench plugin must have an execute method .
Args :
plugin _ class : The loaded plugun class .
Returns :
True if dependencies and execute are... | try :
getattr ( plugin_class , 'dependencies' )
getattr ( plugin_class , 'execute' )
except AttributeError :
return False
return True |
def bind_sockets ( port : int , address : str = None , family : socket . AddressFamily = socket . AF_UNSPEC , backlog : int = _DEFAULT_BACKLOG , flags : int = None , reuse_port : bool = False , ) -> List [ socket . socket ] :
"""Creates listening sockets bound to the given port and address .
Returns a list of soc... | if reuse_port and not hasattr ( socket , "SO_REUSEPORT" ) :
raise ValueError ( "the platform doesn't support SO_REUSEPORT" )
sockets = [ ]
if address == "" :
address = None
if not socket . has_ipv6 and family == socket . AF_UNSPEC : # Python can be compiled with - - disable - ipv6 , which causes
# operations on... |
def get_account_info ( self ) :
"""Gets account info .
@ return : AccountInfo""" | attrs = { sconstant . A_BY : sconstant . V_NAME }
account = SOAPpy . Types . stringType ( data = self . auth_token . account_name , attrs = attrs )
params = { sconstant . E_ACCOUNT : account }
res = self . invoke ( zconstant . NS_ZIMBRA_ACC_URL , sconstant . GetAccountInfoRequest , params )
info = AccountInfo ( )
info ... |
def nfa_to_dfa ( start , end ) :
"""Convert an NFA to a DFA ( s )
Each DFA is initially a set of NFA states without labels . We start with the
DFA for the start NFA . Then we add labeled arcs to it pointing to another
set of NFAs ( the next state ) . Finally , we do the same thing to every DFA
that is found... | base_nfas = set ( )
start . find_unlabeled_states ( base_nfas )
state_stack = [ DFA ( base_nfas , end ) ]
for state in state_stack :
arcs = { }
for nfa in state . nfas :
for label , sub_nfa in nfa . arcs :
if label is not None :
sub_nfa . find_unlabeled_states ( arcs . setdef... |
def _cursor_position ( self , row = 0 , column = 0 ) :
"""Set the cursor to a specific row and column .
Obnoxiously row / column is 1 based , instead of zero based , so we need
to compensate . I know I ' ve created bugs in here somehow .
Confoundingly , inputs of 0 are still acceptable , and should move to
... | if row == 0 :
row = 1
if column == 0 :
column = 1
self . y = min ( row - 1 , self . size [ 0 ] - 1 )
self . x = min ( column - 1 , self . size [ 1 ] - 1 ) |
async def open ( self ) -> 'Verifier' :
"""Explicit entry . Perform ancestor opening operations ,
then parse cache from archive if so configured , and
synchronize revocation registry to tails tree content .
: return : current object""" | LOGGER . debug ( 'Verifier.open >>>' )
await super ( ) . open ( )
if self . config . get ( 'parse-caches-on-open' , False ) :
ArchivableCaches . parse ( self . dir_cache )
LOGGER . debug ( 'Verifier.open <<<' )
return self |
def audit_1_1 ( self ) :
"""1.1 Avoid the use of the " root " account ( Scored )""" | for row in self . credential_report :
if row [ "user" ] == "<root_account>" :
for field in "password_last_used" , "access_key_1_last_used_date" , "access_key_2_last_used_date" :
if row [ field ] != "N/A" and self . parse_date ( row [ field ] ) > datetime . now ( tzutc ( ) ) - timedelta ( days = ... |
def is_authorized ( job = None ) :
'''Returns true if the request is authorized for the job
if provided . If no job is provided , the user has to be admin
to be authorized .''' | if flogin . current_user . is_authenticated :
return True
if job :
job_key = flask . request . headers . get ( 'Authorization' )
if job_key == app . config . get ( 'SECRET_KEY' ) :
return True
return job [ 'job_key' ] == job_key
return False |
def set_ntp_config ( host , username , password , ntp_servers , protocol = None , port = None , host_names = None ) :
'''Set NTP configuration for a given host of list of host _ names .
host
The location of the host .
username
The username used to login to the host , such as ` ` root ` ` .
password
The ... | service_instance = salt . utils . vmware . get_service_instance ( host = host , username = username , password = password , protocol = protocol , port = port )
if not isinstance ( ntp_servers , list ) :
raise CommandExecutionError ( '\'ntp_servers\' must be a list.' )
# Get NTP Config Object from ntp _ servers
ntp_... |
def print_huffman_code_cwl ( code , p , v ) :
"""code - code dictionary with symbol - > code map , p , v is probability map""" | cwl = 0.0
for k , _v in code . items ( ) :
print ( u"%s -> %s" % ( k , _v ) )
cwl += p [ v . index ( k ) ] * len ( _v )
print ( u"cwl = %g" % cwl )
return cwl , code . values ( ) |
def _linkToParent ( self , feature , parentName ) :
"""Link a feature with its children""" | parentParts = self . byFeatureName . get ( parentName )
if parentParts is None :
raise GFF3Exception ( "Parent feature does not exist: {}" . format ( parentName ) , self . fileName )
# parent maybe disjoint
for parentPart in parentParts :
feature . parents . add ( parentPart )
parentPart . children . add ( ... |
def registerGeneralHandler ( self , handler ) :
"""注册通用事件处理函数监听""" | if handler not in self . __generalHandlers :
self . __generalHandlers . append ( handler ) |
def proxy_schema ( self , value ) :
"""Set the Proxy - Schema option of a request .
: param value : the Proxy - Schema value""" | option = Option ( )
option . number = defines . OptionRegistry . PROXY_SCHEME . number
option . value = str ( value )
self . add_option ( option ) |
def VFD_efficiency ( P , load = 1 ) :
r'''Returns the efficiency of a Variable Frequency Drive according to [ 1 ] _ .
These values are generic , and not standardized as minimum values .
Older VFDs often have much worse performance .
Parameters
P : float
Power , [ W ]
load : float , optional
Fraction o... | P = P / hp
# convert to hp
if P < 3 :
P = 3
elif P > 400 :
P = 400
if load < 0.016 :
load = 0.016
return round ( bisplev ( load , P , VFD_efficiency_tck ) , 4 ) |
def serialize ( script_string ) :
'''str - > bytearray''' | string_tokens = script_string . split ( )
serialized_script = bytearray ( )
for token in string_tokens :
if token == 'OP_CODESEPARATOR' or token == 'OP_PUSHDATA4' :
raise NotImplementedError ( '{} is a bad idea.' . format ( token ) )
if token in riemann . network . CODE_TO_INT_OVERWRITE :
serial... |
def set_debug ( enabled : bool ) :
"""Enable or disable debug logs for the entire package .
Parameters
enabled : bool
Whether debug should be enabled or not .""" | global _DEBUG_ENABLED
if not enabled :
log ( 'Disabling debug output...' , logger_name = _LOGGER_NAME )
_DEBUG_ENABLED = False
else :
_DEBUG_ENABLED = True
log ( 'Enabling debug output...' , logger_name = _LOGGER_NAME ) |
def get_relationships_for_destination_on_date ( self , destination_id , from_ , to ) :
"""Gets a ` ` RelationshipList ` ` corresponding to the given peer ` ` Id ` ` with a starting effective date in the given range inclusive .
arg : destination _ id ( osid . id . Id ) : a peer ` ` Id ` `
arg : from ( osid . cal... | # Implemented from template for
# osid . relationship . RelationshipLookupSession . get _ relationships _ for _ destination _ on _ date
relationship_list = [ ]
for relationship in self . get_relationships_for_destination ( ) :
if overlap ( from_ , to , relationship . start_date , relationship . end_date ) :
... |
def __add_hopscotch_tour_step ( self , message , selector = None , name = None , title = None , alignment = None ) :
"""Allows the user to add tour steps for a website .
@ Params
message - The message to display .
selector - The CSS Selector of the Element to attach to .
name - If creating multiple tours at... | arrow_offset_row = None
if not selector or selector == "html" :
selector = "head"
alignment = "bottom"
arrow_offset_row = "arrowOffset: '200',"
else :
arrow_offset_row = ""
step = ( """{
target: '%s',
title: '%s',
content: '%s',
%s
... |
def get_root_bins ( self ) :
"""Gets the root bins in the bin hierarchy .
A node with no parents is an orphan . While all bin ` ` Ids ` ` are
known to the hierarchy , an orphan does not appear in the
hierarchy unless explicitly added as a root node or child of
another node .
return : ( osid . resource . B... | # Implemented from template for
# osid . resource . BinHierarchySession . get _ root _ bins
if self . _catalog_session is not None :
return self . _catalog_session . get_root_catalogs ( )
return BinLookupSession ( self . _proxy , self . _runtime ) . get_bins_by_ids ( list ( self . get_root_bin_ids ( ) ) ) |
def center ( self , axis = 1 ) :
"""Subtract the mean either within or across records .
Parameters
axis : int , optional , default = 1
Which axis to center along , within ( 1 ) or across ( 0 ) records .""" | if axis == 1 :
return self . map ( lambda x : x - mean ( x ) )
elif axis == 0 :
meanval = self . mean ( ) . toarray ( )
return self . map ( lambda x : x - meanval )
else :
raise Exception ( 'Axis must be 0 or 1' ) |
def on_data ( self , data ) :
"""The function called when new data has arrived .
: param data : The list of data records received .""" | for d in data :
self . _populate_sub_entity ( d , 'Device' )
self . _populate_sub_entity ( d , 'Rule' )
date = dates . localize_datetime ( d [ 'activeFrom' ] )
click . echo ( '[{date}] {device} ({rule})' . format ( date = date , device = d [ 'device' ] . get ( 'name' , '**Unknown Vehicle' ) , rule = d [... |
def loado ( obj , class_ = None ) :
"""Convert a dictionary or a list of dictionaries into a single Physical Information Object or a list of such objects .
: param obj : Dictionary or list to convert to Physical Information Objects .
: param class _ : Subclass of : class : ` . Pio ` to produce , if not unambigu... | if isinstance ( obj , list ) :
return [ _dict_to_pio ( i , class_ = class_ ) for i in obj ]
elif isinstance ( obj , dict ) :
return _dict_to_pio ( obj , class_ = class_ )
else :
raise ValueError ( 'expecting list or dictionary as outermost structure' ) |
def bin_to_text ( ip ) :
"""Converts binary representation to human readable IPv4 or IPv6 string .
: param ip : binary representation of IPv4 or IPv6 address
: return : IPv4 or IPv6 address string""" | if len ( ip ) == 4 :
return ipv4_to_str ( ip )
elif len ( ip ) == 16 :
return ipv6_to_str ( ip )
else :
raise struct . error ( 'Invalid ip address length: %s' % len ( ip ) ) |
def GetUsernameForPath ( self , path ) :
"""Retrieves a username for a specific path .
This is determining if a specific path is within a user ' s directory and
returning the username of the user if so .
Args :
path ( str ) : path .
Returns :
str : username or None if the path does not appear to be with... | path = path . lower ( )
user_accounts = self . _user_accounts . get ( self . CURRENT_SESSION , { } )
for user_account in iter ( user_accounts . values ( ) ) :
if not user_account . user_directory :
continue
user_directory = user_account . user_directory . lower ( )
if path . startswith ( user_direct... |
def _read_socket ( self ) :
"""Process incoming messages from socket .""" | while True :
base_bytes = self . _socket . recv ( BASE_SIZE )
base = basemessage . parse ( base_bytes )
payload_bytes = self . _socket . recv ( base . payload_length )
self . _handle_message ( packet . parse ( base_bytes + payload_bytes ) ) |
def calc_point_dist ( vsA , entryA ) :
"""This function is used to determine the distance between two points .
Parameters
vsA : list or numpy . array or similar
An array of point 1 ' s position in the \ chi _ i coordinate system
entryA : list or numpy . array or similar
An array of point 2 ' s position in... | chi_diffs = vsA - entryA
val = ( ( chi_diffs ) * ( chi_diffs ) ) . sum ( )
return val |
def reverse_path ( dict_ , root , child_to_parents ) :
"""CommandLine :
python - m utool . util _ graph - - exec - reverse _ path - - show
Example :
> > > # ENABLE _ DOCTEST
> > > from utool . util _ graph import * # NOQA
> > > import utool as ut
> > > child _ to _ parents = {
> > > ' chip ' : [ ' dum... | # Hacky but illustrative
# TODO ; implement non - hacky version
allkeys = get_allkeys ( dict_ )
mat = np . zeros ( ( len ( allkeys ) , len ( allkeys ) ) )
for key in allkeys :
if key != root :
for parent in child_to_parents [ key ] :
rx = allkeys . index ( parent )
cx = allkeys . ind... |
def primers ( self , tm = 60 ) :
'''Design primers for amplifying the assembled sequence .
: param tm : melting temperature ( lower than overlaps is best ) .
: type tm : float
: returns : Primer list ( the output of coral . design . primers ) .
: rtype : list''' | self . primers = coral . design . primers ( self . template , tm = tm )
return self . primers |
def remove_entry_listener ( self , registration_id ) :
"""Removes the specified entry listener . Returns silently if there is no such listener added before .
: param registration _ id : ( str ) , id of registered listener .
: return : ( bool ) , ` ` true ` ` if registration is removed , ` ` false ` ` otherwise ... | return self . _stop_listening ( registration_id , lambda i : multi_map_remove_entry_listener_codec . encode_request ( self . name , i ) ) |
def _delete_masked_points ( * arrs ) :
"""Delete masked points from arrays .
Takes arrays and removes masked points to help with calculations and plotting .
Parameters
arrs : one or more array - like
source arrays
Returns
arrs : one or more array - like
arrays with masked elements removed""" | if any ( hasattr ( a , 'mask' ) for a in arrs ) :
keep = ~ functools . reduce ( np . logical_or , ( np . ma . getmaskarray ( a ) for a in arrs ) )
return tuple ( ma . asarray ( a [ keep ] ) for a in arrs )
else :
return arrs |
def _get_local_image_id ( docker_binary , docker_tag ) :
"""Get the image id of the local docker layer with the passed tag
: param docker _ tag : docker tag
: return : Image id as string or None if tag does not exist""" | cmd = [ docker_binary , "images" , "-q" , docker_tag ]
image_id_b = check_output ( cmd )
image_id = image_id_b . decode ( 'utf-8' ) . strip ( )
if not image_id :
raise RuntimeError ( 'Unable to find docker image id matching with tag {}' . format ( docker_tag ) )
return image_id |
def find_genome_length ( contig_lengths_dict ) :
"""Determine the total length of all the contigs for each strain
: param contig _ lengths _ dict : dictionary of strain name : reverse - sorted list of all contig lengths
: return : genome _ length _ dict : dictionary of strain name : total genome length""" | # Initialise the dictionary
genome_length_dict = dict ( )
for file_name , contig_lengths in contig_lengths_dict . items ( ) : # Use the sum ( ) method to add all the contig lengths in the list
genome_length_dict [ file_name ] = sum ( contig_lengths )
return genome_length_dict |
def fromtext ( self , text , encoding = 'utf-8' , mimetype = 'text/plain' ) :
"""set blob content from given text in StorageBlobModel instance . Parameters are :
- text ( required ) : path to a local file
- encoding ( optional ) : text encoding ( default is utf - 8)
- mimetype ( optional ) : set a mimetype . ... | if isinstance ( text , str ) :
text = text . encode ( encoding , 'ignore' )
# Load text into self . _ _ content _ _
self . content = bytes ( text )
self . properties . content_settings = ContentSettings ( content_type = mimetype , content_encoding = encoding )
else :
raise AzureStorageWrapException ... |
def list_out ( ) :
"""List all themes in a pretty format .""" | dark_themes = [ theme . name . replace ( ".json" , "" ) for theme in list_themes ( ) ]
ligh_themes = [ theme . name . replace ( ".json" , "" ) for theme in list_themes ( dark = False ) ]
user_themes = [ theme . name . replace ( ".json" , "" ) for theme in list_themes_user ( ) ]
if user_themes :
print ( "\033[1;32mU... |
def ddns ( self , domain_id , record_id , sub_domain , record_line , value ) :
'''Update record ' s value dynamically
If the ` ` value ` ` is different from the record ' s current value , then
perform a dynamic record update . Otherwise , nothing will be done .
: param str domain _ id : Domain ID
: param st... | record = self . info ( domain_id , record_id )
# If everything stay the same , no need to update
if record . sub_domain == sub_domain and record . record_line == record_line and record . value == value :
return
self . _api . do_post ( 'Record.Ddns' , domain_id = domain_id , record_id = record_id , sub_domain = sub_... |
def available_parameters_subset ( self , mx_params ) :
"""Takes an mxnet parameter collect ( from Block . collect _ params ( ) ) and
subsets it with the parameters available in this base network .""" | from copy import copy
from collections import OrderedDict
subset_params = copy ( mx_params )
subset_params . _params = OrderedDict ( [ ( k , v ) for k , v in mx_params . items ( ) if k in self . weight_names ] )
return subset_params |
def once ( self , event , callback ) :
'Define a callback to handle the first event emitted by the server' | self . _once_events . add ( event )
self . on ( event , callback ) |
def annual_event_counts_card ( kind = 'all' , current_year = None ) :
"""Displays years and the number of events per year .
kind is an Event kind ( like ' cinema ' , ' gig ' , etc . ) or ' all ' ( default ) .
current _ year is an optional date object representing the year we ' re already
showing information a... | if kind == 'all' :
card_title = 'Events per year'
else :
card_title = '{} per year' . format ( Event . get_kind_name_plural ( kind ) )
return { 'card_title' : card_title , 'kind' : kind , 'years' : annual_event_counts ( kind = kind ) , 'current_year' : current_year } |
def interpolate_slice ( slice_rows , slice_cols , interpolator ) :
"""Interpolate the given slice of the larger array .""" | fine_rows = np . arange ( slice_rows . start , slice_rows . stop , slice_rows . step )
fine_cols = np . arange ( slice_cols . start , slice_cols . stop , slice_cols . step )
return interpolator ( fine_cols , fine_rows ) |
def setLocked ( self , state = True ) :
"""Locks the node in both the x and y directions .
: param state < bool >""" | self . _xLocked = state
self . _yLocked = state |
def screenshot ( self , filename , scale = 1.0 , quality = 100 ) :
'''take screenshot .''' | result = self . server . screenshot ( filename , scale , quality )
if result :
return result
device_file = self . server . jsonrpc . takeScreenshot ( "screenshot.png" , scale , quality )
if not device_file :
return None
p = self . server . adb . cmd ( "pull" , device_file , filename )
p . wait ( )
self . server... |
def get_export_allowable_types ( cursor , exports_dirs , id , version ) :
"""Return export types .""" | request = get_current_request ( )
type_settings = request . registry . settings [ '_type_info' ]
type_names = [ k for k , v in type_settings ]
type_infos = [ v for k , v in type_settings ]
# We took the type _ names directly from the setting this function uses to
# check for valid types , so it should never raise an Ex... |
def to_db ( self , table , dtypes = None ) :
"""Save the main dataframe to the database""" | if self . _check_db ( ) is False :
return
if table not in self . db . tables :
self . db . create_table ( table )
self . info ( "Created table " , table )
self . start ( "Saving data to database table " + table + " ..." )
recs = self . to_records_ ( )
self . insert ( table , recs , dtypes )
self . end ( "Da... |
def _parse_bool_default_value ( property_name , default_value_string ) :
"""Parse and return the default value for a boolean property .""" | lowercased_value_string = default_value_string . lower ( )
if lowercased_value_string in { '0' , 'false' } :
return False
elif lowercased_value_string in { '1' , 'true' } :
return True
else :
raise AssertionError ( u'Unsupported default value for boolean property "{}": ' u'{}' . format ( property_name , def... |
def setInstallMode ( self , remote , on = True , t = 60 , mode = 1 , address = None ) :
"""Activate or deactivate installmode on CCU / Homegear""" | try :
args = [ on ]
if on and t :
args . append ( t )
if address :
args . append ( address )
else :
args . append ( mode )
return self . proxies [ "%s-%s" % ( self . _interface_id , remote ) ] . setInstallMode ( * args )
except Exception as err :
LOG . deb... |
def PhyDMSPrepAlignmentParser ( ) :
"""Returns * argparse . ArgumentParser * for ` ` phydms _ prepalignment ` ` .""" | parser = ArgumentParserNoArgHelp ( formatter_class = ArgumentDefaultsRawDescriptionFormatter , description = '\n' . join ( [ "Prepare alignment of protein-coding DNA sequences.\n" , "Steps:" , " * Any sequences specified by '--purgeseqs' are removed." , " * Sequences not of length divisible by 3 are removed." , " * Seq... |
def projectSphereFilter ( actor ) :
"""Project a spherical - like object onto a plane .
. . hint : : | projectsphere | | projectsphere . py | _""" | poly = actor . polydata ( )
psf = vtk . vtkProjectSphereFilter ( )
psf . SetInputData ( poly )
psf . Update ( )
a = Actor ( psf . GetOutput ( ) )
return a |
def has_readable_server ( self , read_preference = ReadPreference . PRIMARY ) :
"""Does this topology have any readable servers available matching the
given read preference ?
: Parameters :
- ` read _ preference ` : an instance of a read preference from
: mod : ` ~ pymongo . read _ preferences ` . Defaults ... | common . validate_read_preference ( "read_preference" , read_preference )
return any ( self . apply_selector ( read_preference , None ) ) |
def ray_bounds ( ray_origins , ray_directions , bounds , buffer_dist = 1e-5 ) :
"""Given a set of rays and a bounding box for the volume of interest
where the rays will be passing through , find the bounding boxes
of the rays as they pass through the volume .
Parameters
ray _ origins : ( m , 3 ) float , ray... | ray_origins = np . asanyarray ( ray_origins , dtype = np . float64 )
ray_directions = np . asanyarray ( ray_directions , dtype = np . float64 )
# bounding box we are testing against
bounds = np . asanyarray ( bounds )
# find the primary axis of the vector
axis = np . abs ( ray_directions ) . argmax ( axis = 1 )
axis_bo... |
def on_quote_changed ( self , tiny_quote ) :
"""报价 、 摆盘实时数据变化时 , 会触发该回调""" | # TinyQuoteData
data = tiny_quote
str_log = "on_quote_changed symbol=%s open=%s high=%s close=%s low=%s" % ( data . symbol , data . openPrice , data . highPrice , data . lastPrice , data . lowPrice )
self . log ( str_log ) |
def getPhotos ( self ) :
"""Returns list of Photos .""" | method = 'flickr.photosets.getPhotos'
data = _doget ( method , photoset_id = self . id )
photos = data . rsp . photoset . photo
p = [ ]
for photo in photos :
p . append ( Photo ( photo . id , title = photo . title , secret = photo . secret , server = photo . server ) )
return p |
def _repr_pretty_ ( self , p , cycle ) :
"""Pretty printer for the spark cnofiguration""" | from IPython . lib . pretty import RepresentationPrinter
assert isinstance ( p , RepresentationPrinter )
p . begin_group ( 1 , "SparkConfiguration(" )
def kv ( k , v , do_comma = True ) :
p . text ( k )
p . pretty ( v )
if do_comma :
p . text ( ", " )
p . breakable ( )
kv ( "launcher_arguments: ... |
def reduce ( self , dimensions = None , function = None , ** reduce_map ) :
"""Reduces the Raster using functions provided via the
kwargs , where the keyword is the dimension to be reduced .
Optionally a label _ prefix can be provided to prepend to
the result Element label .""" | function , dims = self . _reduce_map ( dimensions , function , reduce_map )
if len ( dims ) == self . ndims :
if isinstance ( function , np . ufunc ) :
return function . reduce ( self . data , axis = None )
else :
return function ( self . data )
else :
dimension = dims [ 0 ]
other_dimens... |
def _unjsonify ( x , isattributes = False ) :
"""Convert JSON string to an ordered defaultdict .""" | if isattributes :
obj = json . loads ( x )
return dict_class ( obj )
return json . loads ( x ) |
def is_enabled ( ) :
"""Returns ` ` True ` ` if bcrypt should be used .""" | enabled = getattr ( settings , "BCRYPT_ENABLED" , True )
if not enabled :
return False
# Are we under a test ?
if hasattr ( mail , 'outbox' ) :
return getattr ( settings , "BCRYPT_ENABLED_UNDER_TEST" , False )
return True |
def watch ( self , limit = None , timeout = None ) :
"""Block method to watch the clipboard changing .""" | start_time = time . time ( )
count = 0
while not timeout or time . time ( ) - start_time < timeout :
new = self . read ( )
if new != self . temp :
count += 1
self . callback ( new )
if count == limit :
break
self . temp = new
time . sleep ( self . interval ) |
def project ( self , X , Q = None ) :
"""Project X into PCA space , defined by the Q highest eigenvalues .
Y = X dot V""" | if Q is None :
Q = self . Q
if Q > X . shape [ 1 ] :
raise IndexError ( "requested dimension larger then input dimension" )
X = self . center ( X )
return X . dot ( self . eigvectors [ : , : Q ] ) |
def pop ( self , key , * args ) :
'Remove * key * from maps [ 0 ] and return its value . Raise KeyError if * key * not in maps [ 0 ] .' | try :
return self . maps [ 0 ] . pop ( key , * args )
except KeyError :
raise KeyError ( 'Key not found in the first mapping: {!r}' . format ( key ) ) |
def delete_gauge ( self , slug ) :
"""Removes all gauges with the given ` ` slug ` ` .""" | key = self . _gauge_key ( slug )
self . r . delete ( key )
# Remove the Gauge
self . r . srem ( self . _gauge_slugs_key , slug ) |
def get_config ( config_base , custom_file = None , configspec = None ) :
"""Loads a configuration file from multiple locations , and merge the results into one .
This function will load configuration files from a number of locations in sequence ,
and will overwrite values in the previous level if they are rede... | logger = logging . getLogger ( __name__ )
logger . debug ( "Expanding variables" )
home = os . path . expanduser ( "~" )
loc = os . path . dirname ( os . path . abspath ( inspect . getfile ( inspect . currentframe ( ) ) ) )
logger . debug ( "Create empty config" )
config = ConfigObj ( )
# Merge in config file in progra... |
def _gen_ticket ( prefix = None , lg = settings . CAS_TICKET_LEN ) :
"""Generate a ticket with prefix ` ` prefix ` ` and length ` ` lg ` `
: param unicode prefix : An optional prefix ( probably ST , PT , PGT or PGTIOU )
: param int lg : The length of the generated ticket ( with the prefix )
: return : A rando... | random_part = u'' . join ( random . choice ( string . ascii_letters + string . digits ) for _ in range ( lg - len ( prefix or "" ) - 1 ) )
if prefix is not None :
return u'%s-%s' % ( prefix , random_part )
else :
return random_part |
def reset_secret ( self ) :
"""Resets the client secret for this client .""" | result = self . _client . post ( "{}/reset_secret" . format ( OAuthClient . api_endpoint ) , model = self )
if not 'id' in result :
raise UnexpectedResponseError ( 'Unexpected response when resetting secret!' , json = result )
self . _populate ( result )
return self . secret |
def get_alternatives ( self , rank ) :
"""Description :
Returns the alternative ( s ) with the given ranking in the
computed aggregate ranking . An error is thrown if the
ranking does not exist .""" | if self . ranks_to_alts is None :
raise ValueError ( "Aggregate ranking must be created first" )
try :
alts = self . ranks_to_alts [ rank ]
return alts
except KeyError :
raise KeyError ( "No ranking \"{}\" found in " . format ( str ( rank ) ) + "the aggregate ranking" ) |
def bulk_write ( self , requests , ordered = True , bypass_document_validation = False , session = None ) :
"""Send a batch of write operations to the server .
Requests are passed as a list of write operation instances (
: class : ` ~ pymongo . operations . InsertOne ` ,
: class : ` ~ pymongo . operations . U... | common . validate_list ( "requests" , requests )
blk = _Bulk ( self , ordered , bypass_document_validation )
for request in requests :
try :
request . _add_to_bulk ( blk )
except AttributeError :
raise TypeError ( "%r is not a valid request" % ( request , ) )
write_concern = self . _write_concer... |
def resolve_image_name ( self , image_name ) :
"""Look up an AMI for the connected region based on an image name .
: param image _ name : The name of the image to resolve .
: type image _ name : str
: return : The AMI for the given image .
: rtype : str""" | # look at each scope in order of size
scopes = [ 'self' , 'amazon' , 'aws-marketplace' ]
if image_name in self . remote_images :
return self . remote_images [ image_name ]
for scope in scopes :
logger . info ( 'Retrieving available AMIs owned by %s...' , scope )
remote_images = self . ec2 . get_all_images (... |
def _ExpandUsersHomeDirectoryPathSegments ( cls , path_segments , path_separator , user_accounts ) :
"""Expands a path to contain all users home or profile directories .
Expands the artifacts path variable " % % users . homedir % % " or
" % % users . userprofile % % " .
Args :
path _ segments ( list [ str ]... | if not path_segments :
return [ ]
user_paths = [ ]
first_path_segment = path_segments [ 0 ] . lower ( )
if first_path_segment not in ( '%%users.homedir%%' , '%%users.userprofile%%' ) :
if cls . _IsWindowsDrivePathSegment ( path_segments [ 0 ] ) :
path_segments [ 0 ] = ''
user_path = path_separator .... |
def createNoiseExperimentArgs ( ) :
"""Run the probability of false negatives with noise experiment .""" | experimentArguments = [ ]
n = 6000
for a in [ 128 ] :
noisePct = 0.75
while noisePct <= 0.85 :
noise = int ( round ( noisePct * a , 0 ) )
# Some parameter combinations are just not worth running !
experimentArguments . append ( ( "./sdr_calculations2" , "results_noise_10m/temp_" + str ( ... |
def anchor ( self , value ) :
"""Setter for * * self . _ _ anchor * * attribute .
: param value : Attribute value .
: type value : int""" | if value is not None :
assert type ( value ) is int , "'{0}' attribute: '{1}' type is not 'int'!" . format ( "anchor" , value )
assert value in range ( 0 , 9 ) , "'{0}' attribute: '{1}' need to be in '0' to '8' range!" . format ( "anchor" , value )
self . __anchor = value |
def _init ( self ) :
"""initialize all values based on provided input
: return : None""" | self . col_count = len ( self . col_list )
# list of lengths of longest entries in columns
self . col_longest = self . get_all_longest_col_lengths ( )
self . data_length = sum ( self . col_longest . values ( ) )
if self . terminal_width > 0 : # free space is space which should be equeally distributed for all columns
# ... |
def add_group ( self , group_name , group_client_names ) :
"""Add a new : class : ` ClientGroup ` to container groups member .
Add the group named * group _ name * with sequence of client names to the
container groups member . From there it will be wrapped appropriately
in the higher - level thread - safe con... | group_configs = self . _resources_spec . get ( 'groups' , { } )
group_configs [ group_name ] = group_client_names
self . _resources_spec [ 'groups' ] = group_configs
self . _init_groups ( ) |
def _set_scene_transform ( self , tr ) :
"""Called by subclasses to configure the viewbox scene transform .""" | # todo : check whether transform has changed , connect to
# transform . changed event
pre_tr = self . pre_transform
if pre_tr is None :
self . _scene_transform = tr
else :
self . _transform_cache . roll ( )
self . _scene_transform = self . _transform_cache . get ( [ pre_tr , tr ] )
# Mark the transform dyna... |
def pclink ( self , parent , child ) :
"""Create a parent - child relationship .""" | if parent . _children is None :
parent . _children = set ( )
if child . _parents is None :
child . _parents = set ( )
parent . _children . add ( child )
child . _parents . add ( parent ) |
def get_field_groups ( layer_purpose , layer_subcategory = None ) :
"""Obtain list of field groups from layer purpose and subcategory .
: param layer _ purpose : The layer purpose .
: type layer _ purpose : str
: param layer _ subcategory : Exposure or hazard value .
: type layer _ subcategory : str
: ret... | layer_purpose_dict = definition ( layer_purpose )
if not layer_purpose_dict :
return [ ]
field_groups = deepcopy ( layer_purpose_dict . get ( 'field_groups' , [ ] ) )
if layer_purpose in [ layer_purpose_exposure [ 'key' ] , layer_purpose_hazard [ 'key' ] ] :
if layer_subcategory :
subcategory = definiti... |
def cleanup ( self ) :
"""Clean up temporary tag checkout dir .""" | shutil . rmtree ( self . temp_tagdir )
# checkout _ from _ tag might operate on a subdirectory ( mostly
# ' gitclone ' ) , so cleanup the parent dir as well
parentdir = os . path . dirname ( self . temp_tagdir )
# ensure we don ' t remove anything important
if os . path . basename ( parentdir ) . startswith ( self . pa... |
def type ( self ) :
"""The function type for this node .
Possible values are : method , function , staticmethod , classmethod .
: type : str""" | builtin_descriptors = { "classmethod" , "staticmethod" }
for decorator in self . extra_decorators :
if decorator . func . name in builtin_descriptors :
return decorator . func . name
frame = self . parent . frame ( )
type_name = "function"
if isinstance ( frame , ClassDef ) :
if self . name == "__new__"... |
def _GetDayOfYear ( self , year , month , day_of_month ) :
"""Retrieves the day of the year for a specific day of a month in a year .
Args :
year ( int ) : year e . g . 1970.
month ( int ) : month , where 1 represents January .
day _ of _ month ( int ) : day of the month , where 1 represents the first day .... | if month not in range ( 1 , 13 ) :
raise ValueError ( 'Month value out of bounds.' )
days_per_month = self . _GetDaysPerMonth ( year , month )
if day_of_month < 1 or day_of_month > days_per_month :
raise ValueError ( 'Day of month value out of bounds.' )
day_of_year = day_of_month
for past_month in range ( 1 , ... |
def _expand_possible_file_value ( self , value ) :
"""If the value is a file , returns its contents . Otherwise return the original value .""" | if value and os . path . isfile ( str ( value ) ) :
with open ( value , 'r' ) as f :
return f . read ( )
return value |
def countLines ( filename , buf_size = 1048576 ) :
"""fast counting to the lines of a given filename
through only reading out a limited buffer""" | f = open ( filename )
try :
lines = 1
read_f = f . read
# loop optimization
buf = read_f ( buf_size )
# Empty file
if not buf :
return 0
while buf :
lines += buf . count ( '\n' )
buf = read_f ( buf_size )
return lines
finally :
f . close ( ) |
def reads_supporting_variants ( variants , samfile , ** kwargs ) :
"""Given a SAM / BAM file and a collection of variants , generates a sequence
of variants paired with reads which support each variant .""" | for variant , allele_reads in reads_overlapping_variants ( variants = variants , samfile = samfile , ** kwargs ) :
yield variant , filter_non_alt_reads_for_variant ( variant , allele_reads ) |
def _to_power_basis_degree8 ( nodes1 , nodes2 ) :
r"""Compute the coefficients of an * * intersection polynomial * * .
Helper for : func : ` to _ power _ basis ` in the case that B | eacute | zout ' s
` theorem ` _ tells us the * * intersection polynomial * * is degree
: math : ` 8 ` . This happens if the two... | evaluated = [ eval_intersection_polynomial ( nodes1 , nodes2 , t_val ) for t_val in _CHEB9 ]
return polynomial . polyfit ( _CHEB9 , evaluated , 8 ) |
def hoys ( self ) :
"""A sorted list of hours of year in this analysis period .""" | if self . _timestamps_data is None :
self . _calculate_timestamps ( )
return tuple ( moy / 60.0 for moy in self . _timestamps_data ) |
def _object_url ( self , objtype , objid ) :
"""Generate the URL for the specified object
Args :
objtype ( str ) : The object ' s type
objid ( int ) : The objects ID
Returns :
A string containing the URL of the object""" | return "{base_url}/api/{api_version}/{controller}/{obj_id}" . format ( base_url = self . _base_url ( ) , api_version = self . api_version , controller = self . _controller_name ( objtype ) , obj_id = objid ) |
def index2poly ( self , index ) :
"""manages the convention from an iterative index to the specific polynomial n , m , ( real / imaginary part )
: param index : int , index of list
: return : n , m bool""" | n = self . _index2n ( index )
num_prev = n * ( n + 1 ) / 2
num = index + 1
delta = int ( num - num_prev - 1 )
if n % 2 == 0 :
if delta == 0 :
m = delta
complex_bool = False
elif delta % 2 == 0 :
complex_bool = True
m = delta
else :
complex_bool = False
m = del... |
def libvlc_set_app_id ( p_instance , id , version , icon ) :
'''Sets some meta - information about the application .
See also L { libvlc _ set _ user _ agent } ( ) .
@ param p _ instance : LibVLC instance .
@ param id : Java - style application identifier , e . g . " com . acme . foobar " .
@ param version ... | f = _Cfunctions . get ( 'libvlc_set_app_id' , None ) or _Cfunction ( 'libvlc_set_app_id' , ( ( 1 , ) , ( 1 , ) , ( 1 , ) , ( 1 , ) , ) , None , None , Instance , ctypes . c_char_p , ctypes . c_char_p , ctypes . c_char_p )
return f ( p_instance , id , version , icon ) |
def run ( self ) :
"""Start the oplog worker .""" | ReplicationLagLogger ( self , 30 ) . start ( )
LOG . debug ( "OplogThread: Run thread started" )
while self . running is True :
LOG . debug ( "OplogThread: Getting cursor" )
cursor , cursor_empty = retry_until_ok ( self . init_cursor )
# we ' ve fallen too far behind
if cursor is None and self . checkpo... |
def workspace_from_url ( self , mets_url , dst_dir = None , clobber_mets = False , mets_basename = None , download = False , baseurl = None ) :
"""Create a workspace from a METS by URL .
Sets the mets . xml file
Arguments :
mets _ url ( string ) : Source mets URL
dst _ dir ( string , None ) : Target directo... | if dst_dir and not dst_dir . startswith ( '/' ) :
dst_dir = abspath ( dst_dir )
if mets_url is None :
if baseurl is None :
raise Exception ( "Must pass mets_url and/or baseurl to workspace_from_url" )
else :
mets_url = 'file://%s/%s' % ( baseurl , mets_basename if mets_basename else 'mets.xm... |
def dumps ( obj , * transformers ) :
"""Serializes Java primitive data and objects unmarshaled by load ( s ) before
into string .
: param obj : A Python primitive object , or one loaded using load ( s )
: param transformers : Custom transformers to use
: return : The serialized data as a string""" | marshaller = JavaObjectMarshaller ( )
# Add custom transformers
for transformer in transformers :
marshaller . add_transformer ( transformer )
return marshaller . dump ( obj ) |
def remove_step_method ( self , step_method ) :
"""Removes a step method .""" | try :
for s in step_method . stochastics :
self . step_method_dict [ s ] . remove ( step_method )
if hasattr ( self , "step_methods" ) :
self . step_methods . discard ( step_method )
self . _sm_assigned = False
except AttributeError :
for sm in step_method :
self . remove_step_me... |
def visit_break ( self , node , parent ) :
"""visit a Break node by returning a fresh instance of it""" | return nodes . Break ( getattr ( node , "lineno" , None ) , getattr ( node , "col_offset" , None ) , parent ) |
def unicode2str ( content ) :
"""Convert the unicode element of the content to str recursively .""" | if isinstance ( content , dict ) :
result = { }
for key in content . keys ( ) :
result [ unicode2str ( key ) ] = unicode2str ( content [ key ] )
return result
elif isinstance ( content , list ) :
return [ unicode2str ( element ) for element in content ]
elif isinstance ( content , int ) or isins... |
def _edges_from_permutation ( self , feature_pathway_dict ) :
"""Given a dictionary mapping each feature to the pathways
overrepresented in the feature , build a CoNetwork by
creating edges for every pairwise combination of pathways in a feature .""" | network_edges = { }
for feature , pathway_list in feature_pathway_dict . items ( ) :
for i in range ( len ( pathway_list ) ) :
for j in range ( i + 1 , len ( pathway_list ) ) :
vertex_i = pathway_list [ i ]
vertex_j = pathway_list [ j ]
new_edge = self . edge_tuple ( vert... |
def update_master_key ( self , seq_number , key ) :
"""Parameters :
- seq _ number
- key""" | self . send_update_master_key ( seq_number , key )
self . recv_update_master_key ( ) |
def add_prior ( self , twig = None , ** kwargs ) :
"""[ NOT IMPLEMENTED ]
: raises NotImplementedError : because it isn ' t""" | raise NotImplementedError
param = self . get_parameter ( twig = twig , ** kwargs )
# TODO : make sure param is a float parameter ?
func = _get_add_func ( _distributions , 'prior' )
# TODO : send smart defaults for priors based on limits of parameter
params = func ( ** kwargs )
metawargs = { k : v for k , v in params . ... |
def check_preprocessor ( self ) :
"""Initializes the preprocessor""" | if _is_arraylike ( self . preprocessor ) :
self . preprocessor_ = ArrayIndexer ( self . preprocessor )
elif callable ( self . preprocessor ) or self . preprocessor is None :
self . preprocessor_ = self . preprocessor
else :
raise ValueError ( "Invalid type for the preprocessor: {}. You should " "provide eit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.