signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get ( self , file_id , session = None ) :
"""Get a file from GridFS by ` ` " _ id " ` ` .
Returns an instance of : class : ` ~ gridfs . grid _ file . GridOut ` ,
which provides a file - like interface for reading .
: Parameters :
- ` file _ id ` : ` ` " _ id " ` ` of the file to get
- ` session ` ( op... | gout = GridOut ( self . __collection , file_id , session = session )
# Raise NoFile now , instead of on first attribute access .
gout . _ensure_file ( )
return gout |
def _sanitize_numbers ( uncleaned_numbers ) :
"""Convert strings to integers if possible""" | cleaned_numbers = [ ]
for x in uncleaned_numbers :
try :
cleaned_numbers . append ( int ( x ) )
except ValueError :
cleaned_numbers . append ( x )
return cleaned_numbers |
def calc_cat_clust_order ( net , inst_rc ) :
'''cluster category subset of data''' | from . __init__ import Network
from copy import deepcopy
from . import calc_clust , run_filter
inst_keys = list ( net . dat [ 'node_info' ] [ inst_rc ] . keys ( ) )
all_cats = [ x for x in inst_keys if 'cat-' in x ]
if len ( all_cats ) > 0 :
for inst_name_cat in all_cats :
tmp_name = 'dict_' + inst_name_cat... |
def notify ( self , new_jobs_count ) :
"""We just queued new _ jobs _ count jobs on this queue , wake up the workers if needed""" | if not self . use_notify ( ) :
return
# Not really useful to send more than 100 notifs ( to be configured )
count = min ( new_jobs_count , 100 )
notify_key = redis_key ( "notify" , self )
context . connections . redis . lpush ( notify_key , * ( [ 1 ] * count ) )
context . connections . redis . expire ( notify_key ,... |
def eval ( self , expr ) :
"""Evaluate an expression .
This does * * not * * add its argument ( or its result ) as an element of me !
That is the responsibility of the code that created the object . This
means that you need to : meth : ` Environment . rec _ new ` any expression you
get from user input befor... | if self . depth >= self . max_depth :
raise LimitationError ( 'too much nesting' )
if self . steps >= self . max_steps :
raise LimitationError ( 'too many steps' )
self . depth += 1
self . steps += 1
res = expr . eval ( self )
self . depth -= 1
return res |
def lex ( filename ) :
"""Generates tokens from an nginx config file""" | with io . open ( filename , mode = 'r' , encoding = 'utf-8' ) as f :
it = _lex_file_object ( f )
it = _balance_braces ( it , filename )
for token , line , quoted in it :
yield ( token , line , quoted ) |
def get_env_key ( obj , key = None ) :
"""Return environment variable key to use for lookups within a
namespace represented by the package name .
For example , any varialbes for predix . security . uaa are stored
as PREDIX _ SECURITY _ UAA _ KEY""" | return str . join ( '_' , [ obj . __module__ . replace ( '.' , '_' ) . upper ( ) , key . upper ( ) ] ) |
def _get_initialized_channels_for_service ( self , org_id , service_id ) :
'''return [ channel ]''' | channels_dict = self . _get_initialized_channels_dict_for_service ( org_id , service_id )
return list ( channels_dict . values ( ) ) |
def list_from_metadata ( cls , url , metadata ) :
'''return a list of DatalakeRecords for the url and metadata''' | key = cls . _get_key ( url )
metadata = Metadata ( ** metadata )
ct = cls . _get_create_time ( key )
time_buckets = cls . get_time_buckets_from_metadata ( metadata )
return [ cls ( url , metadata , t , ct , key . size ) for t in time_buckets ] |
def _convert_to_namecheap ( self , record ) :
"""converts from lexicon format record to namecheap format record ,
suitable to sending through the api to namecheap""" | name = record [ 'name' ]
if name . endswith ( '.' ) :
name = name [ : - 1 ]
short_name = name [ : name . find ( self . domain ) - 1 ]
processed_record = { 'Type' : record [ 'type' ] , 'Name' : short_name , 'TTL' : record [ 'ttl' ] , 'Address' : record [ 'content' ] , 'HostId' : record [ 'id' ] }
return processed_re... |
def expand_args ( ** args_to_expand ) :
"""Expand the given lists into the length of the layers .
This is used as a convenience so that the user does not need to specify the
complete list of parameters for model initialization .
IE the user can just specify one parameter and this function will expand it""" | layers = args_to_expand [ 'layers' ]
try :
items = args_to_expand . iteritems ( )
except AttributeError :
items = args_to_expand . items ( )
for key , val in items :
if isinstance ( val , list ) and len ( val ) != len ( layers ) :
args_to_expand [ key ] = [ val [ 0 ] for _ in layers ]
return args_to... |
def main ( argString = None ) :
"""The main function of the module .
: param argString : the options .
: type argString : list""" | # Getting and checking the options
args = parseArgs ( argString )
checkArgs ( args )
merge_related_samples ( args . ibs_related , args . out , args . no_status ) |
def coordinates ( self , x , y ) :
'''return coordinates of a pixel in the map''' | state = self . state
return state . mt . coord_from_area ( x , y , state . lat , state . lon , state . width , state . ground_width ) |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'name' ) and self . name is not None :
_dict [ 'name' ] = self . name
if hasattr ( self , 'limit' ) and self . limit is not None :
_dict [ 'limit' ] = self . limit
return _dict |
def parse_qs ( self , qs ) :
"""Parse query string , but enforce one instance of each variable .
Return a dict with the variables on success
Return None on parse error""" | qs_state = urllib2 . urlparse . parse_qs ( qs )
ret = { }
for qs_var , qs_value_list in qs_state . items ( ) :
if len ( qs_value_list ) > 1 :
return None
ret [ qs_var ] = qs_value_list [ 0 ]
return ret |
def prepData4Call ( self , * args , ** kwargs ) :
"""NAME :
prepData4Call
PURPOSE :
prepare stream data for the _ _ call _ _ method
INPUT :
_ _ call _ _ inputs
OUTPUT :
( dOmega , dangle ) ; wrt the progenitor ; each [ 3 , nobj ]
HISTORY :
2013-12-04 - Written - Bovy ( IAS )""" | # First calculate the actionAngle coordinates if they ' re not given
# as such
freqsAngles = self . _parse_call_args ( * args , ** kwargs )
dOmega = freqsAngles [ : 3 , : ] - numpy . tile ( self . _progenitor_Omega . T , ( freqsAngles . shape [ 1 ] , 1 ) ) . T
dangle = freqsAngles [ 3 : , : ] - numpy . tile ( self . _p... |
def _reformat ( p , buf ) :
"""Apply format of ` ` p ` ` to data in 1 - d array ` ` buf ` ` .""" | if numpy . ndim ( buf ) != 1 :
raise ValueError ( "Buffer ``buf`` must be 1-d." )
if hasattr ( p , 'keys' ) :
ans = _gvar . BufferDict ( p )
if ans . size != len ( buf ) :
raise ValueError ( "p, buf size mismatch: %d, %d" % ( ans . size , len ( buf ) ) )
ans = _gvar . BufferDict ( ans , buf = bu... |
def _extract_links_from_asset_tags_in_text ( self , text ) :
"""Scan the text and extract asset tags and links to corresponding
files .
@ param text : Page text .
@ type text : str
@ return : @ see CourseraOnDemand . _ extract _ links _ from _ text""" | # Extract asset tags from instructions text
asset_tags_map = self . _extract_asset_tags ( text )
ids = list ( iterkeys ( asset_tags_map ) )
if not ids :
return { }
# asset tags contain asset names and ids . We need to make another
# HTTP request to get asset URL .
asset_urls = self . _extract_asset_urls ( ids )
sup... |
def pop ( self , idx = - 1 ) :
"""Remove and return item at * idx * ( default last ) . Raises IndexError if
list is empty or index is out of range . Negative indices are supported ,
as for slice indices .""" | # pylint : disable = arguments - differ
if not self . _len :
raise IndexError ( 'pop index out of range' )
_lists = self . _lists
if idx == 0 :
val = _lists [ 0 ] [ 0 ]
self . _delete ( 0 , 0 )
return val
if idx == - 1 :
pos = len ( _lists ) - 1
loc = len ( _lists [ pos ] ) - 1
val = _lists ... |
def _iadd_spmatrix ( self , X , alpha = 1.0 ) :
"""Add a sparse matrix : math : ` X ` to : py : class : ` cspmatrix ` .""" | assert self . is_factor is False , "cannot add spmatrix to a cspmatrix factor"
n = self . symb . n
snptr = self . symb . snptr
snode = self . symb . snode
relptr = self . symb . relptr
snrowidx = self . symb . snrowidx
sncolptr = self . symb . sncolptr
blkptr = self . symb . blkptr
blkval = self . blkval
if self . symb... |
def create_unsigned_tx ( inputs , outputs , change_address = None , include_tosigntx = False , verify_tosigntx = False , min_confirmations = 0 , preference = 'high' , coin_symbol = 'btc' , api_key = None ) :
'''Create a new transaction to sign . Doesn ' t ask for or involve private keys .
Behind the scenes , bloc... | # Lots of defensive checks
assert isinstance ( inputs , list ) , inputs
assert isinstance ( outputs , list ) , outputs
assert len ( inputs ) >= 1 , inputs
assert len ( outputs ) >= 1 , outputs
inputs_cleaned = [ ]
for input_obj in inputs : # ` input ` is a reserved word
if 'address' in input_obj :
address =... |
def cmd ( send , msg , _ ) :
"""Converts morse to ascii .
Syntax : { command } < text >""" | demorse_codes = { '.----' : '1' , '-.--' : 'y' , '..-' : 'u' , '...' : 's' , '-.-.' : 'c' , '.-.-.' : '+' , '--..--' : ',' , '-.-' : 'k' , '.--.' : 'p' , '----.' : '9' , '-----' : '0' , ' ' : ' ' , '...--' : '3' , '-....-' : '-' , '...-..-' : '$' , '..---' : '2' , '.--.-.' : '@' , '-...-' : '=' , '-....' : '6' , '...-... |
def channels_archive ( self , room_id , ** kwargs ) :
"""Archives a channel .""" | return self . __call_api_post ( 'channels.archive' , roomId = room_id , kwargs = kwargs ) |
def set_special ( index , color , iterm_name = "h" , alpha = 100 ) :
"""Convert a hex color to a special sequence .""" | if OS == "Darwin" and iterm_name :
return "\033]P%s%s\033\\" % ( iterm_name , color . strip ( "#" ) )
if index in [ 11 , 708 ] and alpha != "100" :
return "\033]%s;[%s]%s\033\\" % ( index , alpha , color )
return "\033]%s;%s\033\\" % ( index , color ) |
def bubble_to_dot ( bblfile : str , dotfile : str = None , render : bool = False , oriented : bool = False ) :
"""Write in dotfile a graph equivalent to those depicted in bubble file""" | tree = BubbleTree . from_bubble_file ( bblfile , oriented = bool ( oriented ) )
return tree_to_dot ( tree , dotfile , render = render ) |
def set_sound_mode_dict ( self , sound_mode_dict ) :
"""Set the matching dictionary used to match the raw sound mode .""" | error_msg = ( "Syntax of sound mode dictionary not valid, " "use: OrderedDict([('COMMAND', ['VALUE1','VALUE2'])])" )
if isinstance ( sound_mode_dict , dict ) :
mode_list = list ( sound_mode_dict . values ( ) )
for sublist in mode_list :
if isinstance ( sublist , list ) :
for element in subli... |
def run_command ( self , cmd , sudo = False , capture = True , quiet = None , return_result = False ) :
'''run _ command is a wrapper for the global run _ command , checking first
for sudo and exiting on error if needed . The message is returned as
a list of lines for the calling function to parse , and stdout ... | # First preference to function , then to client setting
if quiet == None :
quiet = self . quiet
result = run_cmd ( cmd , sudo = sudo , capture = capture , quiet = quiet )
# If one line is returned , squash dimension
if len ( result [ 'message' ] ) == 1 :
result [ 'message' ] = result [ 'message' ] [ 0 ]
# If th... |
def get_by_id ( self , institution_id , _options = None ) :
'''Fetch a single institution by id .
: param str institution _ id :''' | options = _options or { }
return self . client . post_public_key ( '/institutions/get_by_id' , { 'institution_id' : institution_id , 'options' : options , } ) |
def getfullfilename ( file_path ) :
'''Get full filename ( with extension )''' | warnings . warn ( "getfullfilename() is deprecated and will be removed in near future. Use chirptext.io.write_file() instead" , DeprecationWarning )
if file_path :
return os . path . basename ( file_path )
else :
return '' |
def is_line_in_file ( filename : str , line : str ) -> bool :
"""Detects whether a line is present within a file .
Args :
filename : file to check
line : line to search for ( as an exact match )""" | assert "\n" not in line
with open ( filename , "r" ) as file :
for fileline in file :
if fileline == line :
return True
return False |
def _draw ( self , data ) :
"""Draw text""" | self . _cursor . clearSelection ( )
self . _cursor . setPosition ( self . _last_cursor_pos )
if '\x07' in data . txt :
print ( '\a' )
txt = data . txt . replace ( '\x07' , '' )
if '\x08' in txt :
parts = txt . split ( '\x08' )
else :
parts = [ txt ]
for i , part in enumerate ( parts ) :
if part :
... |
def from_id ( self , tiger , queue , state , task_id , load_executions = 0 ) :
"""Loads a task with the given ID from the given queue in the given
state . An integer may be passed in the load _ executions parameter
to indicate how many executions should be loaded ( starting from the
latest ) . If the task doe... | if load_executions :
pipeline = tiger . connection . pipeline ( )
pipeline . get ( tiger . _key ( 'task' , task_id ) )
pipeline . lrange ( tiger . _key ( 'task' , task_id , 'executions' ) , - load_executions , - 1 )
serialized_data , serialized_executions = pipeline . execute ( )
else :
serialized_d... |
def stop ( name , call = None ) :
"""Stop a running machine .
@ param name : Machine to stop
@ type name : str
@ param call : Must be " action "
@ type call : str""" | if call != 'action' :
raise SaltCloudSystemExit ( 'The instance action must be called with -a or --action.' )
log . info ( "Stopping machine: %s" , name )
vb_stop_vm ( name )
machine = vb_get_machine ( name )
del machine [ "name" ]
return treat_machine_dict ( machine ) |
def operations ( * operations ) :
'''Decorator for marking Resource methods as HTTP operations .
This decorator does a number of different things :
- It transfer onto itself docstring and annotations from the decorated
method , so as to be " transparent " with regards to introspection .
- It tranform the me... | def decorator ( method ) :
def wrapper ( cls , request , start_response , ** kwargs ) :
result_cache = [ ]
try :
yield from method ( cls , request , ** kwargs )
except Respond as e : # Inject messages as taken from signature
status = e . status
msg = utils... |
def optimal_parameters ( reconstruction , fom , phantoms , data , initial = None , univariate = False ) :
r"""Find the optimal parameters for a reconstruction method .
Notes
For a forward operator : math : ` A : X \ to Y ` , a reconstruction operator
parametrized by : math : ` \ theta ` is some operator
: m... | def func ( lam ) : # Function to be minimized by scipy
return sum ( fom ( reconstruction ( datai , lam ) , phantomi ) for phantomi , datai in zip ( phantoms , data ) )
# Pick resolution to fit the one used by the space
tol = np . finfo ( phantoms [ 0 ] . space . dtype ) . resolution * 10
if univariate : # We use a ... |
def within ( self , lat , lon , radius ) :
'''Convenience method to apply a $ loc / $ within / $ center filter . Radius is in meters .''' | return self . filter ( filter_helpers . within_ ( lat , lon , radius ) ) |
def send_video_note ( self , * args , ** kwargs ) :
"""See : func : ` send _ video `""" | return send_video_note ( * args , ** self . _merge_overrides ( ** kwargs ) ) . run ( ) |
def create_requests ( self , request_to_create ) :
"""CreateRequests .
[ Preview API ] Create a new symbol request .
: param : class : ` < Request > < azure . devops . v5_0 . symbol . models . Request > ` request _ to _ create : The symbol request to create .
: rtype : : class : ` < Request > < azure . devops... | content = self . _serialize . body ( request_to_create , 'Request' )
response = self . _send ( http_method = 'POST' , location_id = 'ebc09fe3-1b20-4667-abc5-f2b60fe8de52' , version = '5.0-preview.1' , content = content )
return self . _deserialize ( 'Request' , response ) |
def _d_helper ( vec , vname , color , bw , titlesize , xt_labelsize , linewidth , markersize , credible_interval , point_estimate , hpd_markers , outline , shade , ax , ) :
"""Plot an individual dimension .
Parameters
vec : array
1D array from trace
vname : str
variable name
color : str
matplotlib col... | if vec . dtype . kind == "f" :
if credible_interval != 1 :
hpd_ = hpd ( vec , credible_interval )
new_vec = vec [ ( vec >= hpd_ [ 0 ] ) & ( vec <= hpd_ [ 1 ] ) ]
else :
new_vec = vec
density , xmin , xmax = _fast_kde ( new_vec , bw = bw )
density *= credible_interval
x = np .... |
def DownloadCollection ( coll_path , target_path , token = None , overwrite = False , dump_client_info = False , flatten = False , max_threads = 10 ) :
"""Iterate through a Collection object downloading all files .
Args :
coll _ path : Path to an AFF4 collection .
target _ path : Base directory to write to . ... | completed_clients = set ( )
coll = _OpenCollectionPath ( coll_path )
if coll is None :
logging . error ( "%s is not a valid collection. Typo? " "Are you sure something was written to it?" , coll_path )
return
thread_pool = threadpool . ThreadPool . Factory ( "Downloader" , max_threads )
thread_pool . Start ( )
... |
def _get_larger_chroms ( ref_file ) :
"""Retrieve larger chromosomes , avoiding the smaller ones for plotting .""" | from scipy . cluster . vq import kmeans , vq
all_sizes = [ ]
for c in ref . file_contigs ( ref_file ) :
all_sizes . append ( float ( c . size ) )
all_sizes . sort ( )
if len ( all_sizes ) > 5 : # separate out smaller chromosomes and haplotypes with kmeans
centroids , _ = kmeans ( np . array ( all_sizes ) , 2 )
... |
def reset ( self ) :
"""Resets the foreground and background color value back to the original
when initialised .""" | self . _fgcolor = self . default_fgcolor
self . _bgcolor = self . default_bgcolor |
def relations_to ( self , target , include_object = False ) :
'''list all relations pointing at an object''' | relations = self . _get_item_node ( target ) . incoming
if include_object :
for k in relations :
for v in relations [ k ] :
if hasattr ( v , 'obj' ) : # filter dead links
yield v . obj , k
else :
yield from relations |
def _get_ids_from_name_private ( self , name ) :
"""Get private images which match the given name .""" | results = self . list_private_images ( name = name )
return [ result [ 'id' ] for result in results ] |
def _support_diag_dump ( self ) :
'''Collect log info for debug''' | # check insights config
cfg_block = [ ]
pconn = InsightsConnection ( self . config )
logger . info ( 'Insights version: %s' , get_nvr ( ) )
reg_check = registration_check ( pconn )
cfg_block . append ( 'Registration check:' )
for key in reg_check :
cfg_block . append ( key + ': ' + str ( reg_check [ key ] ) )
lastu... |
def dmail_delete ( self , dmail_id ) :
"""Delete a dmail . You can only delete dmails you own ( Requires login ) .
Parameters :
dmail _ id ( int ) : where dmail _ id is the dmail id .""" | return self . _get ( 'dmails/{0}.json' . format ( dmail_id ) , method = 'DELETE' , auth = True ) |
def _init_map ( self , record_types = None , ** kwargs ) :
"""Initialize form map""" | osid_objects . OsidObjectForm . _init_map ( self , record_types = record_types )
self . _my_map [ 'outputScore' ] = self . _output_score_default
self . _my_map [ 'gradeSystemId' ] = str ( kwargs [ 'grade_system_id' ] )
self . _my_map [ 'inputScoreEndRange' ] = self . _input_score_end_range_default
self . _my_map [ 'inp... |
def _format_firewall_stdout ( cmd_ret ) :
'''Helper function to format the stdout from the get _ firewall _ status function .
cmd _ ret
The return dictionary that comes from a cmd . run _ all call .''' | ret_dict = { 'success' : True , 'rulesets' : { } }
for line in cmd_ret [ 'stdout' ] . splitlines ( ) :
if line . startswith ( 'Name' ) :
continue
if line . startswith ( '---' ) :
continue
ruleset_status = line . split ( )
ret_dict [ 'rulesets' ] [ ruleset_status [ 0 ] ] = bool ( ruleset_... |
def __is_valid_value_for_arg ( self , arg , value , check_extension = True ) :
"""Check if value is allowed for arg
Some commands only allow a limited set of values . The method
always returns True for methods that do not provide such a
set .
: param arg : the argument ' s name
: param value : the value t... | if "values" not in arg and "extension_values" not in arg :
return True
if "values" in arg and value . lower ( ) in arg [ "values" ] :
return True
if "extension_values" in arg :
extension = arg [ "extension_values" ] . get ( value . lower ( ) )
if extension :
condition = ( check_extension and ext... |
def export_vms ( self , vms_names = None , standalone = False , export_dir = '.' , compress = False , init_file_name = 'LagoInitFile' , out_format = YAMLOutFormatPlugin ( ) , collect_only = False , with_threads = True , ) :
"""Export vm images disks and init file .
The exported images and init file can be used to... | return self . virt_env . export_vms ( vms_names , standalone , export_dir , compress , init_file_name , out_format , collect_only , with_threads ) |
def get_source ( fileobj ) :
"""Translate fileobj into file contents .
fileobj is either a string or a dict . If it ' s a string , that ' s the
file contents . If it ' s a string , then the filename key contains
the name of the file whose contents we are to use .
If the dict contains a true value for the ke... | if not isinstance ( fileobj , dict ) :
return fileobj
else :
try :
with io . open ( fileobj [ "filename" ] , encoding = "utf-8" , errors = "ignore" ) as f :
return f . read ( )
finally :
if fileobj . get ( 'delete_after_use' ) :
try :
os . remove ( fil... |
def check_mod_enabled ( mod ) :
'''Checks to see if the specific mod symlink is in / etc / apache2 / mods - enabled .
This will only be functional on Debian - based operating systems ( Ubuntu ,
Mint , etc ) .
CLI Examples :
. . code - block : : bash
salt ' * ' apache . check _ mod _ enabled status
salt ... | if mod . endswith ( '.load' ) or mod . endswith ( '.conf' ) :
mod_file = mod
else :
mod_file = '{0}.load' . format ( mod )
return os . path . islink ( '/etc/apache2/mods-enabled/{0}' . format ( mod_file ) ) |
def complement ( self , alphabet ) :
"""Returns the complement of DFA
Args :
alphabet ( list ) : The input alphabet
Returns :
None""" | states = sorted ( self . states , key = attrgetter ( 'initial' ) , reverse = True )
for state in states :
if state . final :
state . final = False
else :
state . final = True |
def rsp_process ( rsp , sampling_rate = 1000 ) :
"""Automated processing of RSP signals .
Parameters
rsp : list or array
Respiratory ( RSP ) signal array .
sampling _ rate : int
Sampling rate ( samples / second ) .
Returns
processed _ rsp : dict
Dict containing processed RSP features .
Contains th... | processed_rsp = { "df" : pd . DataFrame ( { "RSP_Raw" : np . array ( rsp ) } ) }
biosppy_rsp = dict ( biosppy . signals . resp . resp ( rsp , sampling_rate = sampling_rate , show = False ) )
processed_rsp [ "df" ] [ "RSP_Filtered" ] = biosppy_rsp [ "filtered" ]
# RSP Rate
rsp_rate = biosppy_rsp [ "resp_rate" ] * 60
# G... |
def py_to_go_cookie ( py_cookie ) :
'''Convert a python cookie to the JSON - marshalable Go - style cookie form .''' | # TODO ( perhaps ) :
# HttpOnly
# Creation
# LastAccess
# Updated
# not done properly : CanonicalHost .
go_cookie = { 'Name' : py_cookie . name , 'Value' : py_cookie . value , 'Domain' : py_cookie . domain , 'HostOnly' : not py_cookie . domain_specified , 'Persistent' : not py_cookie . discard , 'Secure' : py_cookie . ... |
def fetchMore ( self , parentIndex ) : # TODO : Make LazyLoadRepoTreeModel ?
"""Fetches any available data for the items with the parent specified by the parent index .""" | parentItem = self . getItem ( parentIndex )
if not parentItem :
return
if not parentItem . canFetchChildren ( ) :
return
# TODO : implement InsertItems to optimize ?
for childItem in parentItem . fetchChildren ( ) :
self . insertItem ( childItem , parentIndex = parentIndex )
# Check that Rti implementation ... |
def save_location ( self , filename : str , location : PostLocation , mtime : datetime ) -> None :
"""Save post location name and Google Maps link .""" | filename += '_location.txt'
location_string = ( location . name + "\n" + "https://maps.google.com/maps?q={0},{1}&ll={0},{1}\n" . format ( location . lat , location . lng ) )
with open ( filename , 'wb' ) as text_file :
shutil . copyfileobj ( BytesIO ( location_string . encode ( ) ) , text_file )
os . utime ( filena... |
def flatten_errors ( cfg , res , levels = None , results = None ) :
"""An example function that will turn a nested dictionary of results
( as returned by ` ` ConfigObj . validate ` ` ) into a flat list .
` ` cfg ` ` is the ConfigObj instance being checked , ` ` res ` ` is the results
dictionary returned by ` ... | if levels is None : # first time called
levels = [ ]
results = [ ]
if res == True :
return results
if res == False or isinstance ( res , Exception ) :
results . append ( ( levels [ : ] , None , res ) )
if levels :
levels . pop ( )
return results
for ( key , val ) in res . items ( ) :
... |
def _get_factors ( self , element ) :
"""Get factors for categorical axes .""" | xdim , ydim = element . dimensions ( ) [ : 2 ]
xvals , yvals = [ element . dimension_values ( i , False ) for i in range ( 2 ) ]
coords = tuple ( [ v if vals . dtype . kind in 'SU' else dim . pprint_value ( v ) for v in vals ] for dim , vals in [ ( xdim , xvals ) , ( ydim , yvals ) ] )
if self . invert_axes :
coord... |
def _find_geophysical_vars ( self , ds , refresh = False ) :
'''Returns a list of geophysical variables . Modifies
` self . _ geophysical _ vars `
: param netCDF4 . Dataset ds : An open netCDF dataset
: param bool refresh : if refresh is set to True , the cache is
invalidated .
: rtype : list
: return :... | if self . _geophysical_vars . get ( ds , None ) and refresh is False :
return self . _geophysical_vars [ ds ]
self . _geophysical_vars [ ds ] = cfutil . get_geophysical_variables ( ds )
return self . _geophysical_vars [ ds ] |
def list_subscriptions ( self , service ) :
"""Asks for a list of all subscribed accounts and devices , along with their statuses .""" | data = { 'service' : service , }
return self . _perform_post_request ( self . list_subscriptions_endpoint , data , self . token_header ) |
def rank_for_in ( self , leaderboard_name , member ) :
'''Retrieve the rank for a member in the named leaderboard .
@ param leaderboard _ name [ String ] Name of the leaderboard .
@ param member [ String ] Member name .
@ return the rank for a member in the leaderboard .''' | member_score = str ( float ( self . score_for_in ( leaderboard_name , member ) ) )
if self . order == self . ASC :
try :
return self . redis_connection . zcount ( leaderboard_name , '-inf' , '(%s' % member_score ) + 1
except :
return None
else :
try :
return self . redis_connection .... |
def _sincedb_init ( self ) :
"""Initializes the sincedb schema in an sqlite db""" | if not self . _sincedb_path :
return
if not os . path . exists ( self . _sincedb_path ) :
self . _log_debug ( 'initializing sincedb sqlite schema' )
conn = sqlite3 . connect ( self . _sincedb_path , isolation_level = None )
conn . execute ( """
create table sincedb (
fid ... |
def _get_redis_server ( opts = None ) :
'''Return the Redis server instance .
Caching the object instance .''' | global REDIS_SERVER
if REDIS_SERVER :
return REDIS_SERVER
if not opts :
opts = _get_redis_cache_opts ( )
if opts [ 'cluster_mode' ] :
REDIS_SERVER = StrictRedisCluster ( startup_nodes = opts [ 'startup_nodes' ] , skip_full_coverage_check = opts [ 'skip_full_coverage_check' ] )
else :
REDIS_SERVER = redi... |
def _operatorOperands ( tokenlist ) :
"generator to extract operators and operands in pairs" | it = iter ( tokenlist )
while 1 :
try :
yield ( it . next ( ) , it . next ( ) )
except StopIteration :
break |
def get_field_resolver ( self , field_resolver : GraphQLFieldResolver ) -> GraphQLFieldResolver :
"""Wrap the provided resolver with the middleware .
Returns a function that chains the middleware functions with the provided
resolver function .""" | if self . _middleware_resolvers is None :
return field_resolver
if field_resolver not in self . _cached_resolvers :
self . _cached_resolvers [ field_resolver ] = reduce ( lambda chained_fns , next_fn : partial ( next_fn , chained_fns ) , self . _middleware_resolvers , field_resolver , )
return self . _cached_re... |
def evolve ( self , rho : Density ) -> Density :
"""Apply the action of this gate upon a density""" | # TODO : implement without explicit channel creation ?
chan = self . aschannel ( )
return chan . evolve ( rho ) |
def read_epub ( name , options = None ) :
"""Creates new instance of EpubBook with the content defined in the input file .
> > > book = ebooklib . read _ epub ( ' book . epub ' )
: Args :
- name : full path to the input file
- options : extra options as dictionary ( optional )
: Returns :
Instance of Ep... | reader = EpubReader ( name , options )
book = reader . load ( )
reader . process ( )
return book |
def _list_subnets_by_identifier ( self , identifier ) :
"""Returns a list of IDs of the subnet matching the identifier .
: param string identifier : The identifier to look up
: returns : List of matching IDs""" | identifier = identifier . split ( '/' , 1 ) [ 0 ]
results = self . list_subnets ( identifier = identifier , mask = 'id' )
return [ result [ 'id' ] for result in results ] |
def parse_lit ( self , lines ) :
'''Parse a string line - by - line delineating comments and code
: returns : An tuple of boolean / list - of - string pairs . True designates a
comment ; False designates code .''' | comment_char = '#'
# TODO : move this into a directive option
comment = re . compile ( r'^\s*{0}[ \n]' . format ( comment_char ) )
section_test = lambda val : bool ( comment . match ( val ) )
sections = [ ]
for is_doc , group in itertools . groupby ( lines , section_test ) :
if is_doc :
text = [ comment . s... |
def formatMessage ( self , record : logging . LogRecord ) -> str :
"""Convert the already filled log record to a string .""" | level_color = "0"
text_color = "0"
fmt = ""
if record . levelno <= logging . DEBUG :
fmt = "\033[0;37m" + logging . BASIC_FORMAT + "\033[0m"
elif record . levelno <= logging . INFO :
level_color = "1;36"
lmsg = record . message . lower ( )
if self . GREEN_RE . search ( lmsg ) :
text_color = "1;3... |
def scale_axes_from_data ( self ) :
"""Restrict data limits for Y - axis based on what you can see""" | # get tight limits for X - axis
if self . args . xmin is None :
self . args . xmin = min ( fs . xspan [ 0 ] for fs in self . spectra )
if self . args . xmax is None :
self . args . xmax = max ( fs . xspan [ 1 ] for fs in self . spectra )
# autoscale view for Y - axis
cropped = [ fs . crop ( self . args . xmin ,... |
def init_app ( self , app ) :
"""Setup the logging handlers , level and formatters .
Level ( DEBUG , INFO , CRITICAL , etc ) is determined by the
app . config [ ' FLASK _ LOG _ LEVEL ' ] setting , and defaults to
` ` None ` ` / ` ` logging . NOTSET ` ` .""" | config_log_level = app . config . get ( 'FLASK_LOG_LEVEL' , None )
# Set up format for default logging
hostname = platform . node ( ) . split ( '.' ) [ 0 ]
formatter = ( '[%(asctime)s] %(levelname)s %(process)d [%(name)s] ' '%(filename)s:%(lineno)d - ' '[{hostname}] - %(message)s' ) . format ( hostname = hostname )
con... |
def apply_computation ( cls , state : BaseState , message : Message , transaction_context : BaseTransactionContext ) -> 'BaseComputation' :
"""Perform the computation that would be triggered by the VM message .""" | with cls ( state , message , transaction_context ) as computation : # Early exit on pre - compiles
if message . code_address in computation . precompiles :
computation . precompiles [ message . code_address ] ( computation )
return computation
show_debug2 = computation . logger . show_debug2
... |
def can_fetch_pool ( self , request : Request ) :
'''Return whether the request can be fetched based on the pool .''' | url_info = request . url_info
user_agent = request . fields . get ( 'User-agent' , '' )
if self . _robots_txt_pool . has_parser ( url_info ) :
return self . _robots_txt_pool . can_fetch ( url_info , user_agent )
else :
raise NotInPoolError ( ) |
def load_slice ( self , state , start , end ) :
"""Return the memory objects overlapping with the provided slice .
: param start : the start address
: param end : the end address ( non - inclusive )
: returns : tuples of ( starting _ addr , memory _ object )""" | items = [ ]
if start > self . _page_addr + self . _page_size or end < self . _page_addr :
l . warning ( "Calling load_slice on the wrong page." )
return items
for addr in range ( max ( start , self . _page_addr ) , min ( end , self . _page_addr + self . _page_size ) ) :
i = addr - self . _page_addr
mo =... |
def expectation ( self , observables , statistics , lag_multiple = 1 , observables_mean_free = False , statistics_mean_free = False ) :
r"""Compute future expectation of observable or covariance using the approximated Koopman operator .
Parameters
observables : np . ndarray ( ( input _ dimension , n _ observabl... | # TODO : implement the case lag _ multiple = 0
dim = self . dimension ( )
S = np . diag ( np . concatenate ( ( [ 1.0 ] , self . singular_values [ 0 : dim ] ) ) )
V = self . V [ : , 0 : dim ]
U = self . U [ : , 0 : dim ]
m_0 = self . mean_0
m_t = self . mean_t
assert lag_multiple >= 1 , 'lag_multiple = 0 not implemented... |
def dump_submission_data ( self ) :
"""Dumps the current submission data to the submission file .""" | # renew the dashboard config
self . submission_data [ "dashboard_config" ] = self . dashboard . get_persistent_config ( )
# write the submission data to the output file
self . _outputs [ "submission" ] . dump ( self . submission_data , formatter = "json" , indent = 4 ) |
def _get_cache_name ( function ) :
"""returns a name for the module ' s cache db .""" | module_name = _inspect . getfile ( function )
module_name = _os . path . abspath ( module_name )
cache_name = module_name
# fix for ' < string > ' or ' < stdin > ' in exec or interpreter usage .
cache_name = cache_name . replace ( '<' , '_lt_' )
cache_name = cache_name . replace ( '>' , '_gt_' )
tmpdir = _os . getenv (... |
def add_permission_for_apigateway ( self , function_name , region_name , account_id , rest_api_id , random_id = None ) : # type : ( str , str , str , str , Optional [ str ] ) - > None
"""Authorize API gateway to invoke a lambda function is needed .
This method will first check if API gateway has permission to cal... | source_arn = self . _build_source_arn_str ( region_name , account_id , rest_api_id )
self . _add_lambda_permission_if_needed ( source_arn = source_arn , function_arn = function_name , service_name = 'apigateway' , ) |
def load_saved_records ( self , status , records ) :
"""Load ALDB records from a set of saved records .""" | if isinstance ( status , ALDBStatus ) :
self . _status = status
else :
self . _status = ALDBStatus ( status )
for mem_addr in records :
rec = records [ mem_addr ]
control_flags = int ( rec . get ( 'control_flags' , 0 ) )
group = int ( rec . get ( 'group' , 0 ) )
rec_addr = rec . get ( 'address' ... |
def _set_xml_from_keys ( self , root , item , ** kwargs ) :
"""Create SubElements of root with kwargs .
Args :
root : Element to add SubElements to .
item : Tuple key / value pair from self . data _ keys to add .
kwargs :
For each item in self . data _ keys , if it has a
corresponding kwarg , create a S... | key , val = item
target_key = root . find ( key )
if target_key is None :
target_key = ElementTree . SubElement ( root , key )
if isinstance ( val , dict ) :
for dict_item in val . items ( ) :
self . _set_xml_from_keys ( target_key , dict_item , ** kwargs )
return
# Convert kwarg data to the appropr... |
def surrogate_escape ( error ) :
"""Simulate the Python 3 ` ` surrogateescape ` ` handler , but for Python 2 only .""" | chars = error . object [ error . start : error . end ]
assert len ( chars ) == 1
val = ord ( chars )
val += 0xdc00
return __builtin__ . unichr ( val ) , error . end |
def strip_prefixes ( g : Graph ) :
"""Remove the prefixes from the graph for aesthetics""" | return re . sub ( r'^@prefix .* .\n' , '' , g . serialize ( format = "turtle" ) . decode ( ) , flags = re . MULTILINE ) . strip ( ) |
def mask ( self , dims = None , base = None , fill = 'deeppink' , stroke = 'black' , background = None ) :
"""Create a mask image with colored regions .
Parameters
dims : tuple , optional , default = None
Dimensions of embedding image ,
will be ignored if background image is provided .
base : array - like... | fill = getcolor ( fill )
stroke = getcolor ( stroke )
background = getcolor ( background )
if dims is None and base is None :
region = one ( self . coordinates - self . bbox [ 0 : 2 ] )
else :
region = self
base = getbase ( base = base , dims = dims , extent = self . extent , background = background )
if fill i... |
def remove_header_search_paths ( self , paths , target_name = None , configuration_name = None ) :
"""Removes the given search paths from the HEADER _ SEARCH _ PATHS section of the target on the configurations
: param paths : A string or array of strings
: param target _ name : Target name or list of target nam... | self . remove_search_paths ( XCBuildConfigurationFlags . HEADER_SEARCH_PATHS , paths , target_name , configuration_name ) |
def add_param ( self , param_name , layer_index , blob_index ) :
"""Add a param to the . params file""" | blobs = self . layers [ layer_index ] . blobs
self . dict_param [ param_name ] = mx . nd . array ( caffe . io . blobproto_to_array ( blobs [ blob_index ] ) ) |
def text_filter ( regex_base , value ) :
"""Helper method to regex replace images with captions in different markups""" | regex = regex_base % { 're_cap' : r'[a-zA-Z0-9\.\,:;/_ \(\)\-\!\?"]+' , 're_img' : r'[a-zA-Z0-9\.:/_\-\% ]+' }
images = re . findall ( regex , value )
for i in images :
image = i [ 1 ]
if image . startswith ( settings . MEDIA_URL ) :
image = image [ len ( settings . MEDIA_URL ) : ]
im = get_thumbnai... |
def GetEntries ( self , parser_mediator , top_level = None , ** unused_kwargs ) :
"""Extracts relevant install history entries .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
top _ level ( dict [ str , object ] ) : plis... | for entry in top_level :
datetime_value = entry . get ( 'date' , None )
package_identifiers = entry . get ( 'packageIdentifiers' , [ ] )
if not datetime_value or not package_identifiers :
continue
display_name = entry . get ( 'displayName' , '<UNKNOWN>' )
display_version = entry . get ( 'dis... |
def user_record ( uid , type = 0 ) :
"""获取用户的播放列表 , 必须登录
: param uid : 用户的ID , 可通过登录或者其他接口获取
: param type : ( optional ) 数据类型 , 0 : 获取所有记录 , 1 : 获取 weekData""" | if uid is None :
raise ParamsError ( )
r = NCloudBot ( )
r . method = 'USER_RECORD'
r . data = { 'type' : type , 'uid' : uid , "csrf_token" : "" }
r . send ( )
return r . response |
def agg_grid ( grid , agg = None ) :
"""Many functions return a 2d list with a complex data type in each cell .
For instance , grids representing environments have a set of resources ,
while reading in multiple data files at once will yield a list
containing the values for that cell from each file . In order ... | grid = deepcopy ( grid )
if agg is None :
if type ( grid [ 0 ] [ 0 ] ) is list and type ( grid [ 0 ] [ 0 ] [ 0 ] ) is str :
agg = string_avg
else :
agg = mode
for i in range ( len ( grid ) ) :
for j in range ( len ( grid [ i ] ) ) :
grid [ i ] [ j ] = agg ( grid [ i ] [ j ] )
return ... |
def reload_webservers ( ) :
"""Reload apache2 and nginx""" | if env . verbosity :
print env . host , "RELOADING apache2"
with settings ( warn_only = True ) :
a = sudo ( "/etc/init.d/apache2 reload" )
if env . verbosity :
print '' , a
if env . verbosity : # Reload used to fail on Ubuntu but at least in 10.04 it works
print env . host , "RELOADING nginx"
wi... |
def reload_config ( self , async = True , verbose = False ) :
'''Initiate a config reload . This may take a while on large installations .''' | # If we ' re using an API version older than 4.5.0 , don ' t use async
api_version = float ( self . api_version ( ) [ 'api_version' ] )
if api_version < 4.5 :
async = False
url = '{}/{}{}' . format ( self . rest_url , 'reload' , '?asynchronous=1' if async else '' )
return self . __auth_req_post ( url , verbose = ve... |
def _all_dims ( x , default_dims = None ) :
"""Returns a list of dims in x or default _ dims if the rank is unknown .""" | if x . get_shape ( ) . ndims is not None :
return list ( xrange ( x . get_shape ( ) . ndims ) )
else :
return default_dims |
def from_master_password ( cls , password , network = BitcoinMainNet ) :
"""Generate a new key from a master password .
This password is hashed via a single round of sha256 and is highly
breakable , but it ' s the standard brainwallet approach .
See ` PrivateKey . from _ master _ password _ slow ` for a sligh... | password = ensure_bytes ( password )
key = sha256 ( password ) . hexdigest ( )
return cls . from_hex_key ( key , network ) |
def latinize ( mapping , bind , values ) :
"""Transliterate a given string into the latin alphabet .""" | for v in values :
if isinstance ( v , six . string_types ) :
v = transliterate ( v )
yield v |
def build_content_handler ( parent , filter_func ) :
"""Build a ` ~ xml . sax . handler . ContentHandler ` with a given filter""" | from ligo . lw . lsctables import use_in
class _ContentHandler ( parent ) : # pylint : disable = too - few - public - methods
def __init__ ( self , document ) :
super ( _ContentHandler , self ) . __init__ ( document , filter_func )
return use_in ( _ContentHandler ) |
def _onerror ( self , result ) :
"""To execute on execution failure
: param cdumay _ result . Result result : Execution result
: return : Execution result
: rtype : cdumay _ result . Result""" | self . _set_status ( "FAILED" , result )
logger . error ( "{}.Failed: {}[{}]: {}" . format ( self . __class__ . __name__ , self . __class__ . path , self . uuid , result ) , extra = dict ( kmsg = Message ( self . uuid , entrypoint = self . __class__ . path , params = self . params ) . dump ( ) , kresult = ResultSchema ... |
def handle_default_args ( args ) :
"""Include handling of any default arguments that all commands should
implement here ( for example , specifying the pythonpath ) .""" | if hasattr ( args , 'pythonpath' ) :
if args . pythonpath :
sys . path . insert ( 0 , args . pythonpath ) |
def stop_program ( self , turn_off_load = True ) :
"""Stops running programmed test sequence
: return : None""" | self . __set_buffer_start ( self . CMD_STOP_PROG )
self . __set_checksum ( )
self . __send_buffer ( )
if turn_off_load and self . load_on :
self . load_on = False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.