signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def acquire_discharge ( self , cav , payload ) :
'''Request a discharge macaroon from the caveat location
as an HTTP URL .
@ param cav Third party { pymacaroons . Caveat } to be discharged .
@ param payload External caveat data { bytes } .
@ return The acquired macaroon { macaroonbakery . Macaroon }''' | resp = self . _acquire_discharge_with_token ( cav , payload , None )
# TODO Fabrice what is the other http response possible ? ?
if resp . status_code == 200 :
return bakery . Macaroon . from_dict ( resp . json ( ) . get ( 'Macaroon' ) )
cause = Error . from_dict ( resp . json ( ) )
if cause . code != ERR_INTERACTI... |
def query_one ( cls , * args , ** kwargs ) :
"""Same as collection . find _ one , but return Document then dict""" | doc = cls . _coll . find_one ( * args , ** kwargs )
if doc :
return cls . from_storage ( doc ) |
def check_platform ( self , dataset ) :
'''int platform _ variable ; / / . . . . . RECOMMENDED - a container variable storing information about the platform . If more than one , can expand each attribute into a variable . For example , platform _ call _ sign and platform _ nodc _ code . See instrument _ parameter _... | # Check for the platform variable
platforms = util . get_platform_variables ( dataset )
if not platforms :
return Result ( BaseCheck . MEDIUM , False , 'A container variable storing information about the platform exists' , [ 'Create a variable to store the platform information' ] )
results = [ ]
for platform in pla... |
def find_distributions ( path_item , only = False ) :
"""Yield distributions accessible via ` path _ item `""" | importer = get_importer ( path_item )
finder = _find_adapter ( _distribution_finders , importer )
return finder ( importer , path_item , only ) |
def _markup ( self , entry ) :
"""Recursively generates HTML for the current entry .
Parameters
entry : object
Object to convert to HTML . Maybe be a single entity or contain multiple and / or nested objects .
Returns
str
String of HTML formatted json .""" | if entry is None :
return ""
if isinstance ( entry , list ) :
list_markup = "<ul>"
for item in entry :
list_markup += "<li>{:s}</li>" . format ( self . _markup ( item ) )
list_markup += "</ul>"
return list_markup
if isinstance ( entry , dict ) :
return self . convert ( entry )
# default ... |
def connect ( self , force = False ) :
'''Establish a connection''' | # Don ' t re - establish existing connections
if not force and self . alive ( ) :
return True
self . _reset ( )
# Otherwise , try to connect
with self . _socket_lock :
try :
logger . info ( 'Creating socket...' )
self . _socket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM )
... |
def get_ZXY_freqs ( Data , zfreq , xfreq , yfreq , bandwidth = 5000 ) :
"""Determines the exact z , x and y peak frequencies from approximate
frequencies by finding the highest peak in the PSD " close to " the
approximate peak frequency . By " close to " I mean within the range :
approxFreq - bandwidth / 2 to... | trapfreqs = [ ]
for freq in [ zfreq , xfreq , yfreq ] :
z_f_fit_lower = take_closest ( Data . freqs , freq - bandwidth / 2 )
z_f_fit_upper = take_closest ( Data . freqs , freq + bandwidth / 2 )
z_indx_fit_lower = int ( _np . where ( Data . freqs == z_f_fit_lower ) [ 0 ] [ 0 ] )
z_indx_fit_upper = int ( ... |
def _get_model_nodes ( self , model ) :
"""Find all the non - auto created nodes of the model .""" | nodes = [ ( name , node ) for name , node in model . _nodes . items ( ) if node . _is_auto_created is False ]
nodes . sort ( key = lambda n : n [ 0 ] )
return nodes |
def _maintain_dep_graph ( self , p_todo ) :
"""Makes sure that the dependency graph is consistent according to the
given todo .""" | dep_id = p_todo . tag_value ( 'id' )
# maintain dependency graph
if dep_id :
self . _parentdict [ dep_id ] = p_todo
self . _depgraph . add_node ( hash ( p_todo ) )
# connect all tasks we have in memory so far that refer to this
# task
for dep in [ dep for dep in self . _todos if dep . has_tag ( 'p' ... |
def ask_int ( msg = "Enter an integer" , dft = None , vld = None , hlp = None ) :
"""Prompts the user for an integer .""" | vld = vld or [ int ]
return ask ( msg , dft = dft , vld = vld , fmt = partial ( cast , typ = int ) , hlp = hlp ) |
def pos ( self , element = None ) :
'''Tries to decide about the part of speech .''' | tags = [ ]
if element :
if re . search ( '[\w|\s]+ [m|f]\.' , element , re . U ) :
tags . append ( 'NN' )
if '[VERB]' in element :
tags . append ( 'VB' )
if 'adj.' in element and re . search ( '([\w|\s]+, [\w|\s]+)' , element , re . U ) :
tags . append ( 'JJ' )
else :
for element... |
def get_order_in_album ( self , reversed_ordering = True ) :
'''Returns image order number . It is calculated as ( number + 1 ) of images
attached to the same content _ object whose order is greater
( if ' reverse _ ordering ' is True ) or lesser ( if ' reverse _ ordering ' is
False ) than image ' s order .''... | lookup = 'order__gt' if reversed_ordering else 'order__lt'
return self . __class__ . objects . for_model ( self . content_object , self . content_type ) . filter ( ** { lookup : self . order } ) . count ( ) + 1 |
def calculate_size ( name , replica_timestamps , target_replica ) :
"""Calculates the request payload size""" | data_size = 0
data_size += calculate_size_str ( name )
data_size += INT_SIZE_IN_BYTES
for replica_timestamps_item in replica_timestamps :
key = replica_timestamps_item [ 0 ]
val = replica_timestamps_item [ 1 ]
data_size += calculate_size_str ( key )
data_size += LONG_SIZE_IN_BYTES
data_size += calculate... |
def PushBack ( self , string = "" , ** _ ) :
"""Push the match back on the stream .""" | precondition . AssertType ( string , Text )
self . buffer = string + self . buffer
self . processed_buffer = self . processed_buffer [ : - len ( string ) ] |
def isUserCert ( self , name ) :
'''Checks if a user certificate exists .
Args :
name ( str ) : The name of the user keypair .
Examples :
Check if the user cert " myuser " exists :
exists = cdir . isUserCert ( ' myuser ' )
Returns :
bool : True if the certificate is present , False otherwise .''' | crtpath = self . _getPathJoin ( 'users' , '%s.crt' % name )
return os . path . isfile ( crtpath ) |
def fetch_metric ( self , cursor , results , tags ) :
'''Because we need to query the metrics by matching pairs , we can ' t query
all of them together without having to perform some matching based on
the name afterwards so instead we query instance by instance .
We cache the list of instance so that we don '... | if self . sql_name not in results :
self . log . warning ( "Couldn't find {} in results" . format ( self . sql_name ) )
return
tags = tags + self . tags
results_list = results [ self . sql_name ]
done_instances = [ ]
for ndx , row in enumerate ( results_list ) :
ctype = row [ 0 ]
cval = row [ 1 ]
in... |
def getEdges ( self , fromVol ) :
"""Return the edges available from fromVol .""" | return [ self . toObj . diff ( diff ) for diff in self . _client . getEdges ( self . toArg . vol ( fromVol ) ) ] |
def render_pdf ( template , file_ , url_fetcher = staticfiles_url_fetcher , context = None , ) :
"""Writes the PDF data into ` ` file _ ` ` . Note that ` ` file _ ` ` can actually be a
Django Response object as well .
This function may be used as a helper that can be used to save a PDF file
to a file ( or any... | context = context or { }
html = get_template ( template ) . render ( context )
HTML ( string = html , base_url = 'not-used://' , url_fetcher = url_fetcher , ) . write_pdf ( target = file_ , ) |
def sanitizeparameters ( parameters ) :
"""Construct a dictionary of parameters , for internal use only""" | if not isinstance ( parameters , dict ) :
d = { }
for x in parameters :
if isinstance ( x , tuple ) and len ( x ) == 2 :
for parameter in x [ 1 ] :
d [ parameter . id ] = parameter
elif isinstance ( x , clam . common . parameters . AbstractParameter ) :
d ... |
def _gap ( src_interval , tar_interval ) :
"""Refer section 3.1 ; gap function .
: param src _ interval : first argument or interval 1
: param tar _ interval : second argument or interval 2
: return : Interval representing gap between two intervals""" | assert src_interval . bits == tar_interval . bits , "Number of bits should be same for operands"
# use the same variable names as in paper
s = src_interval
t = tar_interval
( _ , b ) = ( s . lower_bound , s . upper_bound )
( c , _ ) = ( t . lower_bound , t . upper_bound )
w = s . bits
# case 1
if ( not t . _surrounds_m... |
def method_codes_to_geomagia ( magic_method_codes , geomagia_table ) :
"""Looks at the MagIC method code list and returns the correct GEOMAGIA code number depending
on the method code list and the GEOMAGIA table specified . Returns O , GEOMAGIA ' s " Not specified " value , if no match .
When mutiple codes are ... | codes = magic_method_codes
geomagia = geomagia_table . lower ( )
geomagia_code = '0'
if geomagia == 'alteration_monit_corr' :
if "DA-ALT-V" or "LP-PI-ALT-PTRM" or "LP-PI-ALT-PMRM" in codes :
geomagia_code = '1'
elif "LP-PI-ALT-SUSC" in codes :
geomagia_code = '2'
elif "DA-ALT-RS" or "LP-PI-A... |
def _set_version ( self , version ) :
'''Set up this object based on the capabilities of the
known versions of Redmine''' | # Store the version we are evaluating
self . version = version or None
# To evaluate the version capabilities ,
# assume the best - case if no version is provided .
version_check = version or 9999.0
if version_check < 1.0 :
raise RedmineError ( 'This library will only work with ' 'Redmine version 1.0 and higher.' )... |
def verify ( self ) :
"""Ensure all expected calls were called ,
raise AssertionError otherwise .
You do not need to use this directly . Use fudge . verify ( )""" | try :
for exp in self . get_expected_calls ( ) :
exp . assert_called ( )
exp . assert_times_called ( )
for fake , call_order in self . get_expected_call_order ( ) . items ( ) :
call_order . assert_order_met ( finalize = True )
finally :
self . clear_calls ( ) |
def total_review_average ( obj , normalize_to = 100 ) :
"""Returns the average for all reviews of the given object .""" | ctype = ContentType . objects . get_for_model ( obj )
total_average = 0
reviews = models . Review . objects . filter ( content_type = ctype , object_id = obj . id )
for review in reviews :
total_average += review . get_average_rating ( normalize_to )
if reviews :
total_average /= reviews . count ( )
return tota... |
async def serialize_rctsig_prunable ( self , ar , type , inputs , outputs , mixin ) :
"""Serialize rct sig
: param ar :
: type ar : x . Archive
: param type :
: param inputs :
: param outputs :
: param mixin :
: return :""" | if type == RctType . Null :
return True
if type != RctType . Full and type != RctType . Bulletproof and type != RctType . Simple and type != RctType . Bulletproof2 :
raise ValueError ( 'Unknown type' )
if is_rct_bp ( type ) :
await ar . tag ( 'bp' )
await ar . begin_array ( )
bps = [ 0 ]
if ar .... |
def _stopOnFailure ( self , f ) :
"utility method to stop the service when a failure occurs" | if self . running :
d = defer . maybeDeferred ( self . stopService )
d . addErrback ( log . err , 'while stopping broken HgPoller service' )
return f |
def ProcessListDirectory ( self , responses ) :
"""Processes the results of the ListDirectory client action .
Args :
responses : a flow Responses object .""" | if not responses . success :
raise flow . FlowError ( "Unable to list directory." )
with data_store . DB . GetMutationPool ( ) as pool :
for response in responses :
stat_entry = rdf_client_fs . StatEntry ( response )
filesystem . CreateAFF4Object ( stat_entry , self . client_urn , pool , token =... |
def check_syntax ( code ) :
"""Return True if syntax is okay .""" | try :
return compile ( code , '<string>' , 'exec' , dont_inherit = True )
except ( SyntaxError , TypeError , ValueError ) :
return False |
def find_one ( self , query = None ) :
"""Equivalent to ` ` find ( query , limit = 1 ) [ 0 ] ` `""" | try :
return self . find ( query = query , limit = 1 ) [ 0 ]
except ( sqlite3 . OperationalError , IndexError ) :
return None |
def translate_key_val ( val , delimiter = '=' ) :
'''CLI input is a list of key / val pairs , but the API expects a dictionary in
the format { key : val }''' | if isinstance ( val , dict ) :
return val
val = translate_stringlist ( val )
new_val = { }
for item in val :
try :
lvalue , rvalue = split ( item , delimiter , 1 )
except ( AttributeError , TypeError , ValueError ) :
raise SaltInvocationError ( '\'{0}\' is not a key{1}value pair' . format ( ... |
def mainline ( self ) :
"""Returns the main line of the game ( variation A ) as a ' GameTree ' .""" | if self . variations :
return GameTree ( self . data + self . variations [ 0 ] . mainline ( ) )
else :
return self |
def get_iex_next_day_ex_date ( start = None , ** kwargs ) :
"""MOVED to iexfinance . refdata . get _ iex _ next _ day _ ex _ date""" | import warnings
warnings . warn ( WNG_MSG % ( "get_iex_next_day_ex_date" , "refdata.get_iex_next_day_ex_date" ) )
return NextDay ( start = start , ** kwargs ) . fetch ( ) |
def _main ( ) :
"""Usage : tabulate [ options ] [ FILE . . . ]
Pretty - print tabular data .
See also https : / / bitbucket . org / astanin / python - tabulate
FILE a filename of the file with tabular data ;
if " - " or missing , read data from stdin .
Options :
- h , - - help show this message
-1 , -... | import getopt
import sys
import textwrap
usage = textwrap . dedent ( _main . __doc__ )
try :
opts , args = getopt . getopt ( sys . argv [ 1 : ] , "h1o:s:F:f:" , [ "help" , "header" , "output" , "sep=" , "float=" , "format=" ] )
except getopt . GetoptError as e :
print ( e )
print ( usage )
sys . exit ( ... |
def read_plugin_config ( self ) :
"""Read plugin - specific configuration values .""" | folders = self . config [ "pluginfolders" ]
modules = plugins . get_plugin_modules ( folders )
for pluginclass in plugins . get_plugin_classes ( modules ) :
section = pluginclass . __name__
if self . has_section ( section ) :
self . config [ "enabledplugins" ] . append ( section )
self . config ... |
def lstsq ( a , b , rcond = None , weighted = False , extrainfo = False ) :
"""Least - squares solution ` ` x ` ` to ` ` a @ x = b ` ` for | GVar | \ s .
Here ` ` x ` ` is defined to be the solution that minimizes ` ` | | b - a @ x | | ` ` .
If ` ` b ` ` has a covariance matrix , another option is to weight the... | a = numpy . asarray ( a )
b = numpy . asarray ( b )
if a . ndim != 2 :
raise ValueError ( 'a must have dimension 2: actual shape = ' + str ( a . shape ) )
if a . shape [ 0 ] != b . shape [ 0 ] :
raise ValueError ( 'a and b shapes mismatched: {} vs {}' . format ( a . shape , b . shape ) )
if rcond is None :
... |
def page_template ( template , key = PAGE_LABEL ) :
"""Return a view dynamically switching template if the request is Ajax .
Decorate a view that takes a * template * and * extra _ context * keyword
arguments ( like generic views ) .
The template is switched to * page _ template * if request is ajax and
if ... | def decorator ( view ) :
@ wraps ( view )
def decorated ( request , * args , ** kwargs ) : # Trust the developer : he wrote ` ` context . update ( extra _ context ) ` `
# in his view .
extra_context = kwargs . setdefault ( 'extra_context' , { } )
extra_context [ 'page_template' ] = template
... |
def distribute ( self , f , n ) :
"""Distribute the computations amongst the multiprocessing pools
Parameters
f : function
Function to be distributed to the processors
n : int
The values in range ( 0 , n ) will be passed as arguments to the
function f .""" | if self . pool is None :
return [ f ( i ) for i in range ( n ) ]
else :
return self . pool . map ( f , range ( n ) ) |
def subset ( self , subset_id ) :
"""Returns information regarding the set""" | if subset_id in self . subsetcache :
return self . subsetcache [ subset_id ]
set_uri = self . get_set_uri ( subset_id )
for row in self . graph . query ( "SELECT ?seturi ?setid ?setlabel ?setopen WHERE { ?seturi rdf:type skos:Collection . OPTIONAL { ?seturi skos:notation ?setid } OPTIONAL { ?seturi skos:prefLabel ?... |
def _list_items ( action , key , profile = None , subdomain = None , api_key = None ) :
'''List items belonging to an API call .
This method should be in utils . pagerduty .''' | items = _query ( profile = profile , subdomain = subdomain , api_key = api_key , action = action )
ret = { }
for item in items [ action ] :
ret [ item [ key ] ] = item
return ret |
def setup_left_panel ( self ) :
"""Setup the UI for left panel .
Generate all exposure , combobox , and edit button .""" | hazard = self . parent . step_kw_subcategory . selected_subcategory ( )
left_panel_heading = QLabel ( tr ( 'Classifications' ) )
left_panel_heading . setFont ( big_font )
self . left_layout . addWidget ( left_panel_heading )
inner_left_layout = QGridLayout ( )
row = 0
for exposure in exposure_all :
special_case = F... |
def _get_matplot_dict ( self , option , prop , defdict ) :
"""Returns a copy of the settings dictionary for the specified option in
curargs with update values where the value is replaced by the key from
the relevant default dictionary .
: arg option : the key in self . curargs to update .
: arg defdict : th... | cargs = self . curargs [ option ]
result = cargs . copy ( )
for varname in cargs :
if prop in cargs [ varname ] :
name = cargs [ varname ] [ prop ]
for key , val in list ( defdict . items ( ) ) :
if val == name :
cargs [ varname ] [ prop ] = key
break
retu... |
def setup_storage ( self ) :
"""Save existing FileField storages and patch them with test instance ( s ) .
If storage _ per _ field is False ( default ) this function will create a
single instance here and assign it to self . storage to be used for all
filefields .
If storage _ per _ field is True , an inde... | if self . storage_callable is not None and not self . storage_per_field :
self . storage = self . get_storage_from_callable ( field = None )
super ( override_storage , self ) . setup_storage ( ) |
def entries ( self ) :
"""Provides access to entry management methods for the given content type .
API reference : https : / / www . contentful . com / developers / docs / references / content - management - api / # / reference / entries
: return : : class : ` ContentTypeEntriesProxy < contentful _ management .... | return ContentTypeEntriesProxy ( self . _client , self . space . id , self . _environment_id , self . id ) |
def toList ( self ) :
"""Returns date as signed list .""" | date = self . date ( )
sign = '+' if date [ 0 ] >= 0 else '-'
date [ 0 ] = abs ( date [ 0 ] )
return list ( sign ) + date |
def _syncronous_batch_evaluation ( self , x ) :
"""Evaluates the function a x , where x can be a single location or a batch . The evaluation is performed in parallel
according to the number of accessible cores .""" | from multiprocessing import Process , Pipe
# - - - parallel evaluation of the function
divided_samples = [ x [ i : : self . n_procs ] for i in range ( self . n_procs ) ]
pipe = [ Pipe ( ) for i in range ( self . n_procs ) ]
proc = [ Process ( target = spawn ( self . _eval_func ) , args = ( c , k ) ) for k , ( p , c ) i... |
def make_image ( location , size , fmt ) :
'''Create a blank virtual machine image file of the specified size in
megabytes . The image can be created in any format supported by qemu
CLI Example :
. . code - block : : bash
salt ' * ' qemu _ img . make _ image / tmp / image . qcow 2048 qcow2
salt ' * ' qemu... | if not os . path . isabs ( location ) :
return ''
if not os . path . isdir ( os . path . dirname ( location ) ) :
return ''
if not __salt__ [ 'cmd.retcode' ] ( 'qemu-img create -f {0} {1} {2}M' . format ( fmt , location , size ) , python_shell = False ) :
return location
return '' |
def _spec_trace ( trace , cmap = None , wlen = 0.4 , log = False , trc = 'k' , tralpha = 0.9 , size = ( 10 , 2.5 ) , axes = None , title = None ) :
"""Function to plot a trace over that traces spectrogram .
Uses obspys spectrogram routine .
: type trace : obspy . core . trace . Trace
: param trace : trace to ... | import matplotlib . pyplot as plt
if not axes :
fig = plt . figure ( figsize = size )
ax1 = fig . add_subplot ( 111 )
else :
ax1 = axes
trace . spectrogram ( wlen = wlen , log = log , show = False , cmap = cmap , axes = ax1 )
fig = plt . gcf ( )
ax2 = ax1 . twinx ( )
y = trace . data
x = np . linspace ( 0 ,... |
def comments ( self , limit = None ) :
"""GETs newest comments from this subreddit . Calls : meth : ` narwal . Reddit . comments ` .
: param limit : max number of links to return""" | return self . _reddit . comments ( self . display_name , limit = limit ) |
def save_items ( self , rows = None , verbose = False ) :
"""Return a dictionary of row data for selected rows :
{1 : { col1 : val1 , col2 : val2 } , . . . }
If a list of row numbers isn ' t provided , get data for all .""" | if rows :
rows = rows
else :
rows = list ( range ( self . GetNumberRows ( ) ) )
cols = list ( range ( self . GetNumberCols ( ) ) )
data = { }
for row in rows :
data [ row ] = { }
for col in cols :
col_name = self . GetColLabelValue ( col )
if verbose :
print ( col_name , ":" ... |
def tolist ( self ) -> List [ bool ] :
"""Convert the set to a list of 64 bools .""" | result = [ False ] * 64
for square in self :
result [ square ] = True
return result |
def parse_single_report ( f ) :
"""Parse a gatk varianteval varianteval""" | # Fixme : Separate GATKReport parsing and data subsetting . A GATKReport parser now available from the GATK MultiqcModel .
data = dict ( )
in_CompOverlap = False
in_CountVariants = False
in_TiTv = False
for l in f : # Detect section headers
if '#:GATKTable:CompOverlap' in l :
in_CompOverlap = True
elif ... |
def update ( self , friendly_name = None , description = None , query = None ) :
"""Selectively updates View information .
Any parameters that are None ( the default ) are not applied in the update .
Args :
friendly _ name : if not None , the new friendly name .
description : if not None , the new descripti... | self . _table . _load_info ( )
if query is not None :
if isinstance ( query , _query . Query ) :
query = query . sql
self . _table . _info [ 'view' ] = { 'query' : query }
self . _table . update ( friendly_name = friendly_name , description = description ) |
def getclientloansurl ( idclient , * args , ** kwargs ) :
"""Request Client loans URL .
How to use it ? By default MambuLoan uses getloansurl as the urlfunc .
Override that behaviour by sending getclientloansurl ( this function )
as the urlfunc to the constructor of MambuLoans ( note the final ' s ' )
and v... | getparams = [ ]
if kwargs :
try :
if kwargs [ "fullDetails" ] == True :
getparams . append ( "fullDetails=true" )
else :
getparams . append ( "fullDetails=false" )
except Exception as ex :
pass
try :
getparams . append ( "accountState=%s" % kwargs [ "a... |
def nm_to_rgb ( nm ) :
"""Convert a wavelength to corresponding RGB values [ 0.0-1.0 ] .
Parameters
nm : int or float
The wavelength of light .
Returns
List of [ R , G , B ] values between 0 and 1
` original code ` _ _
_ _ http : / / www . physics . sfasu . edu / astro / color / spectra . html""" | w = int ( nm )
# color - - - - -
if w >= 380 and w < 440 :
R = - ( w - 440. ) / ( 440. - 350. )
G = 0.0
B = 1.0
elif w >= 440 and w < 490 :
R = 0.0
G = ( w - 440. ) / ( 490. - 440. )
B = 1.0
elif w >= 490 and w < 510 :
R = 0.0
G = 1.0
B = - ( w - 510. ) / ( 510. - 490. )
elif w >= 51... |
def on_epoch_end ( self , last_metrics , ** kwargs ) :
"Set the final result in ` last _ metrics ` ." | return add_metrics ( last_metrics , self . val / self . count ) |
def _submit_rate ( self , metric_name , val , metric , custom_tags = None , hostname = None ) :
"""Submit a metric as a rate , additional tags provided will be added to
the ones from the label provided via the metrics object .
` custom _ tags ` is an array of ' tag : value ' that will be added to the
metric w... | _tags = self . _metric_tags ( metric_name , val , metric , custom_tags , hostname )
self . rate ( '{}.{}' . format ( self . NAMESPACE , metric_name ) , val , _tags , hostname = hostname ) |
def extract_file_from_tar ( bytes_io , expected_file ) :
"""extract a file from a bytes _ io tar . Returns bytes""" | with open ( 'temp' , 'wb+' ) as f :
bytes_io . seek ( 0 )
shutil . copyfileobj ( bytes_io , f , length = 131072 )
tar = tarfile . open ( 'temp' , mode = 'r:gz' )
os . remove ( 'temp' )
return tar . extractfile ( expected_file ) . read ( ) |
def _get_representative ( self , obj ) :
"""Finds and returns the root of the set containing ` obj ` .""" | if obj not in self . _parents :
self . _parents [ obj ] = obj
self . _weights [ obj ] = 1
self . _prev_next [ obj ] = [ obj , obj ]
self . _min_values [ obj ] = obj
return obj
path = [ obj ]
root = self . _parents [ obj ]
while root != path [ - 1 ] :
path . append ( root )
root = self . _par... |
def display_system ( sys , style = 'vdw' ) :
'''Display the system * sys * with the default viewer .''' | v = QtViewer ( )
# v . add _ post _ processing ( FXAAEffect )
v . add_post_processing ( SSAOEffect )
if style == 'vdw' :
sr = v . add_renderer ( AtomRenderer , sys . r_array , sys . type_array , backend = 'impostors' )
if style == 'ball-and-stick' :
sr = v . add_renderer ( BallAndStickRenderer , sys . r_array ,... |
def _print_topics ( self , header : str , cmds : List [ str ] , verbose : bool ) -> None :
"""Customized version of print _ topics that can switch between verbose or traditional output""" | import io
if cmds :
if not verbose :
self . print_topics ( header , cmds , 15 , 80 )
else :
self . stdout . write ( '{}\n' . format ( str ( header ) ) )
widest = 0
# measure the commands
for command in cmds :
width = utils . ansi_safe_wcswidth ( command )
... |
def plot2d ( points , cells , mesh_color = "k" , show_axes = False ) :
"""Plot a 2D mesh using matplotlib .""" | import matplotlib . pyplot as plt
from matplotlib . collections import LineCollection
fig = plt . figure ( )
ax = fig . gca ( )
plt . axis ( "equal" )
if not show_axes :
ax . set_axis_off ( )
xmin = numpy . amin ( points [ : , 0 ] )
xmax = numpy . amax ( points [ : , 0 ] )
ymin = numpy . amin ( points [ : , 1 ] )
y... |
def drape ( raster , feature ) :
"""Convert a 2D feature to a 3D feature by sampling a raster
Parameters :
raster ( rasterio ) : raster to provide the z coordinate
feature ( dict ) : fiona feature record to convert
Returns :
result ( Point or Linestring ) : shapely Point or LineString of xyz coordinate tr... | coords = feature [ 'geometry' ] [ 'coordinates' ]
geom_type = feature [ 'geometry' ] [ 'type' ]
if geom_type == 'Point' :
xyz = sample ( raster , [ coords ] )
result = Point ( xyz [ 0 ] )
elif geom_type == 'LineString' :
xyz = sample ( raster , coords )
points = [ Point ( x , y , z ) for x , y , z in xy... |
def get_asset_contents_by_genus_type_for_asset ( self , asset_content_genus_type , asset_id ) :
"""Gets an ` ` AssetContentList ` ` from the given GenusType and Asset Id .
In plenary mode , the returned list contains all known asset contents or
an error results . Otherwise , the returned list may contain only
... | return AssetContentList ( self . _provider_session . get_asset_contents_by_genus_type_for_asset ( asset_content_genus_type , asset_id ) , self . _config_map ) |
def update ( self , password = values . unset ) :
"""Update the CredentialInstance
: param unicode password : The password will not be returned in the response
: returns : Updated CredentialInstance
: rtype : twilio . rest . api . v2010 . account . sip . credential _ list . credential . CredentialInstance""" | return self . _proxy . update ( password = password , ) |
def lookup ( self , dotted_path , lineno = None ) :
"""Given a dotted path in the format ` ` class _ name ` ` or
` ` class _ name : method _ name ` ` this performs an alias lookup . For
methods the line number must be supplied or the result is
unreliable .""" | rv = None
try :
rv = rustcall ( _lib . lsm_proguard_mapping_convert_dotted_path , self . _get_ptr ( ) , dotted_path . encode ( 'utf-8' ) , lineno or 0 )
return _ffi . string ( rv ) . decode ( 'utf-8' , 'replace' )
finally :
if rv is not None :
_lib . lsm_buffer_free ( rv ) |
def encrypt ( byte_data , secret_key = '' ) :
'''uses cryptography module to encrypt byte data
cipher : AES ( 128 bit block _ size )
hash : sha512
key size : 256 bit ( first 32 bytes of secret key hash )
vector size : 128 bit ( next 16 bytes of secret key hash )
padding : PKCS7
cipher mode : CBC
backe... | # validate input
if not isinstance ( byte_data , bytes ) :
raise TypeError ( '\nbyte data input must be a byte datatype.' )
# validate secret key or create secret key
if secret_key :
if not isinstance ( secret_key , str ) :
raise TypeError ( '\nsecret key input must be a utf-8 encoded string.' )
else :
... |
def command ( self , dbname , spec , slave_ok = False , read_preference = ReadPreference . PRIMARY , codec_options = DEFAULT_CODEC_OPTIONS , check = True , allowable_errors = None , check_keys = False , read_concern = DEFAULT_READ_CONCERN , write_concern = None , parse_write_concern_error = False , collation = None ) :... | if self . max_wire_version < 4 and not read_concern . ok_for_legacy :
raise ConfigurationError ( 'read concern level of %s is not valid ' 'with a max wire version of %d.' % ( read_concern . level , self . max_wire_version ) )
if not ( write_concern is None or write_concern . acknowledged or collation is None ) :
... |
def next_week_day ( base_date , weekday ) :
"""Finds next weekday""" | day_of_week = base_date . weekday ( )
end_of_this_week = base_date + timedelta ( days = 6 - day_of_week )
day = end_of_this_week + timedelta ( days = 1 )
while day . weekday ( ) != weekday :
day = day + timedelta ( days = 1 )
return day |
def get_updates ( self , offset = None , limit = 100 , poll_timeout = 0 , allowed_updates = None , request_timeout = None , delta = timedelta ( milliseconds = 100 ) , error_as_empty = False ) :
"""Use this method to receive incoming updates using long polling . An Array of Update objects is returned .
You can cho... | from datetime import datetime
assert ( offset is None or isinstance ( offset , int ) )
assert ( limit is None or isinstance ( limit , int ) )
assert ( poll_timeout is None or isinstance ( poll_timeout , int ) )
assert ( allowed_updates is None or isinstance ( allowed_updates , list ) )
if poll_timeout and not request_t... |
def wait ( self , auth , resource , options , defer = False ) :
"""This is a HTTP Long Polling API which allows a user to wait on specific resources to be
updated .
Args :
auth : < cik > for authentication
resource : < ResourceID > to specify what resource to wait on .
options : Options for the wait inclu... | # let the server control the timeout
return self . _call ( 'wait' , auth , [ resource , options ] , defer , notimeout = True ) |
def serve_coll_page ( self , environ , coll = '$root' ) :
"""Render and serve a collections search page ( search . html ) .
: param dict environ : The WSGI environment dictionary for the request
: param str coll : The name of the collection to serve the collections search page for
: return : The WbResponse co... | if not self . is_valid_coll ( coll ) :
self . raise_not_found ( environ , 'No handler for "/{0}"' . format ( coll ) )
self . setup_paths ( environ , coll )
metadata = self . get_metadata ( coll )
view = BaseInsertView ( self . rewriterapp . jinja_env , 'search.html' )
wb_prefix = environ . get ( 'SCRIPT_NAME' )
if ... |
def sync_one ( self , aws_syncr , amazon , route ) :
"""Make sure this role exists and has only what policies we want it to have""" | route_info = amazon . route53 . route_info ( route . name , route . zone )
target = route . record_target
if callable ( target ) :
target = target ( amazon )
if not route_info :
amazon . route53 . create_route ( route . name , route . zone , route . record_type , target )
else :
amazon . route53 . modify_ro... |
def feed ( self , token , test_newline = True ) :
"""Consume a token and calculate the new line & column .
As an optional optimization , set test _ newline = False is token doesn ' t contain a newline .""" | if test_newline :
newlines = token . count ( self . newline_char )
if newlines :
self . line += newlines
self . line_start_pos = self . char_pos + token . rindex ( self . newline_char ) + 1
self . char_pos += len ( token )
self . column = self . char_pos - self . line_start_pos + 1 |
def read_asc_grid ( filename , footer = 0 ) :
"""Reads ASCII grid file ( * . asc ) .
Parameters
filename : str
Name of * . asc file .
footer : int , optional
Number of lines at bottom of * . asc file to skip .
Returns
grid _ array : numpy array , shape ( M , N )
( M , N ) array of grid values , wher... | ncols = None
nrows = None
xllcorner = None
xllcenter = None
yllcorner = None
yllcenter = None
cellsize = None
dx = None
dy = None
no_data = None
header_lines = 0
with io . open ( filename , 'r' ) as f :
while True :
string , value = f . readline ( ) . split ( )
header_lines += 1
if string . ... |
def Q_weir_rectangular_full_SIA ( h1 , h2 , b ) :
r'''Calculates the flow rate across a full - channel rectangular weir from
the height of the liquid above the crest of the weir , the liquid depth
beneath it , and the width of the channel . Model from [ 1 ] _ as reproduced in
[2 ] _ .
Flow rate is given by ... | Q = 2 / 3. * 2 ** 0.5 * ( 0.615 + 0.000615 / ( h1 + 0.0016 ) ) * b * g ** 0.5 * h1 + 0.5 * ( h1 / ( h1 + h2 ) ) ** 2 * b * g ** 0.5 * h1 ** 1.5
return Q |
def load_tasks_from_file ( self , file_path ) :
"""Imports specified python module and returns subclasses of BaseTask from it
: param file _ path : a fully qualified file path for a python module to import CustomTasks from
: type file _ path : ` str `
: return : a dict of CustomTasks , where key is CustomTask... | file_name , module_path , objects = Loader . import_custom_python_file ( file_path )
result = { }
for entry in objects :
try :
if issubclass ( entry , BaseTask ) :
if entry . __name__ != BaseTask . __name__ and entry . name == BaseTask . name :
raise GOSTaskException ( "Class {cl... |
def get_ugali_dir ( ) :
"""Get the path to the ugali data directory from the environment""" | dirname = os . getenv ( 'UGALIDIR' )
# Get the HOME directory
if not dirname :
dirname = os . path . join ( os . getenv ( 'HOME' ) , '.ugali' )
if not os . path . exists ( dirname ) :
from ugali . utils . logger import logger
msg = "Creating UGALIDIR:\n%s" % dirname
logger . warning ( msg )
return mkdir... |
def forall ( self , method ) :
"""TODO : I AM NOT HAPPY THAT THIS WILL NOT WORK WELL WITH WINDOW FUNCTIONS
THE parts GIVE NO INDICATION OF NEXT ITEM OR PREVIOUS ITEM LIKE rownum
DOES . MAYBE ALGEBRAIC EDGES SHOULD BE LOOPED DIFFERENTLY ? ON THE
OTHER HAND , MAYBE WINDOW FUNCTIONS ARE RESPONSIBLE FOR THIS COMP... | if not self . is_value :
Log . error ( "Not dealing with this case yet" )
matrix = self . data . values ( ) [ 0 ]
parts = [ e . domain . partitions for e in self . edges ]
for c in matrix . _all_combos ( ) :
method ( matrix [ c ] , [ parts [ i ] [ cc ] for i , cc in enumerate ( c ) ] , self ) |
def apply_panes_settings ( self ) :
"""Update dockwidgets features settings""" | for plugin in ( self . widgetlist + self . thirdparty_plugins ) :
features = plugin . FEATURES
if CONF . get ( 'main' , 'vertical_dockwidget_titlebars' ) :
features = features | QDockWidget . DockWidgetVerticalTitleBar
plugin . dockwidget . setFeatures ( features )
plugin . update_margins ( ) |
def set ( self , request_url , response_json ) :
"""Checks if the maximum size of the cache has been reached and in case
discards the least recently used item from ' usage _ recency ' and ' table ' ;
then adds the response _ json to be cached to the ' table ' dict using as
a lookup key the request _ url of th... | if self . size ( ) == self . _max_size :
popped = self . _usage_recency . pop ( )
del self . _table [ popped ]
current_time = timeutils . now ( 'unix' )
if request_url not in self . _table :
self . _table [ request_url ] = { 'data' : response_json , 'insertion_time' : current_time }
self . _usage_recenc... |
def union ( graphs , use_tqdm : bool = False ) :
"""Take the union over a collection of graphs into a new graph .
Assumes iterator is longer than 2 , but not infinite .
: param iter [ BELGraph ] graphs : An iterator over BEL graphs . Can ' t be infinite .
: param use _ tqdm : Should a progress bar be displaye... | it = iter ( graphs )
if use_tqdm :
it = tqdm ( it , desc = 'taking union' )
try :
target = next ( it )
except StopIteration as e :
raise ValueError ( 'no graphs given' ) from e
try :
graph = next ( it )
except StopIteration :
return target
else :
target = target . copy ( )
left_full_join ( t... |
def gen_rand_str ( * size , use = None , keyspace = None ) :
"""Generates a random string using random module specified in @ use within
the @ keyspace
@ * size : # int size range for the length of the string
@ use : the random module to use
@ keyspace : # str chars allowed in the random string
from vital ... | keyspace = keyspace or ( string . ascii_letters + string . digits )
keyspace = [ char for char in keyspace ]
use = use or _random
use . seed ( )
if size :
size = size if len ( size ) == 2 else ( size [ 0 ] , size [ 0 ] )
else :
size = ( 10 , 12 )
return '' . join ( use . choice ( keyspace ) for _ in range ( use... |
def _parse_title ( dom , details ) :
"""Parse title / name of the book .
Args :
dom ( obj ) : HTMLElement containing whole HTML page .
details ( obj ) : HTMLElement containing slice of the page with details .
Returns :
str : Book ' s title .
Raises :
AssertionError : If title not found .""" | title = details . find ( "h1" )
# if the header is missing , try to parse title from the < title > tag
if not title :
title = dom . find ( "title" )
assert title , "Can't find <title> tag!"
return title [ 0 ] . getContent ( ) . split ( "|" ) [ 0 ] . strip ( )
return title [ 0 ] . getContent ( ) . strip ( ) |
def insert ( self , dct , toa = None , comment = "" ) :
"""Create a document
: param dict dct :
: param toa toa : Optional time of action , triggers this to be handled as a future insert action for a new document
: param str comment : A comment
: rtype str :
: returns string bson id :""" | if self . schema :
jsonschema . validate ( dct , self . schema )
bson_obj = yield self . collection . insert ( dct )
raise Return ( bson_obj . __str__ ( ) ) |
def expand_by_device ( original_parallelism , device_parallelism , data ) :
"""Opposite of reduce _ by _ device ( ) .
Args :
original _ parallelism : a expert _ utils . Parallelism object .
device _ parallelism : a expert _ utils . Parallelism object .
data : a list of tensors with length device _ paralleli... | device_to_datum = { device_parallelism . devices [ i ] : data [ i ] for i in range ( device_parallelism . n ) }
return [ device_to_datum [ d ] for d in original_parallelism . devices ] |
def _model_predict_is ( self , h , recalculate = False , fit_once = True ) :
"""Outputs ensemble model predictions for the end - of - period data
Parameters
h : int
How many steps at the end of the series to run the ensemble on
recalculate : boolean
Whether to recalculate the predictions or not
fit _ on... | if len ( self . model_predictions_is ) == 0 or h != self . h or recalculate is True :
for no , model in enumerate ( self . model_list ) :
if no == 0 :
result = model . predict_is ( h , fit_once = fit_once )
result . columns = [ model . model_name ]
else :
new_fram... |
def _get_rho ( self , v ) :
"""convert unit - cell volume in A ^ 3 to density in g / cm ^ 3
: param v : unit cell volume in A ^ 3
: return : density in g / cm ^ 3
: note : internal function""" | v_mol = vol_uc2mol ( v , self . z )
# in m ^ 3
rho = self . mass / v_mol * 1.e-6
# in g / cm ^ 3
return rho |
def get_sampling_strategy ( self , sensor_name ) :
"""Get the current sampling strategy for the named sensor
Parameters
sensor _ name : str
Name of the sensor ( normal or escaped form )
Returns
strategy : tuple of str
contains ( < strat _ name > , [ < strat _ parm1 > , . . . ] ) where the strategy names... | cache_key = self . _get_strategy_cache_key ( sensor_name )
cached = self . _strategy_cache . get ( cache_key )
if not cached :
return resource . normalize_strategy_parameters ( 'none' )
else :
return cached |
def _replace_nans ( self , data ) : # return data
"""Checks floating point data columns for nans , and replaces these with
the generic Stata for missing value ( . )""" | for c in data :
dtype = data [ c ] . dtype
if dtype in ( np . float32 , np . float64 ) :
if dtype == np . float32 :
replacement = self . MISSING_VALUES [ 'f' ]
else :
replacement = self . MISSING_VALUES [ 'd' ]
data [ c ] = data [ c ] . fillna ( replacement )
retu... |
def _updateNonDefaultsForInspector ( self , inspectorRegItem , inspector ) :
"""Store the ( non - default ) config values for the current inspector in a local dictionary .
This dictionary is later used to store value for persistence .
This function must be called after the inspector was drawn because that may u... | if inspectorRegItem and inspector :
key = inspectorRegItem . identifier
logger . debug ( "_updateNonDefaultsForInspector: {} {}" . format ( key , type ( inspector ) ) )
self . _inspectorsNonDefaults [ key ] = inspector . config . getNonDefaultsDict ( )
else :
logger . debug ( "_updateNonDefaultsForInspe... |
def _get_sqs_conn ( profile , region = None , key = None , keyid = None ) :
'''Get a boto connection to SQS .''' | if profile :
if isinstance ( profile , six . string_types ) :
_profile = __opts__ [ profile ]
elif isinstance ( profile , dict ) :
_profile = profile
key = _profile . get ( 'key' , None )
keyid = _profile . get ( 'keyid' , None )
region = _profile . get ( 'region' , None )
if not reg... |
def add_input_distortions ( flip_left_right , random_crop , random_scale , random_brightness , module_spec ) :
"""Creates the operations to apply the specified distortions .
During training it can help to improve the results if we run the images
through simple distortions like crops , scales , and flips . These... | input_height , input_width = hub . get_expected_image_size ( module_spec )
input_depth = hub . get_num_image_channels ( module_spec )
jpeg_data = tf . placeholder ( tf . string , name = 'DistortJPGInput' )
decoded_image = tf . image . decode_jpeg ( jpeg_data , channels = input_depth )
# Convert from full range of uint8... |
def set ( self , e , k , v , real_k = None , check_kw_name = False ) :
"""override base to handle escape case : replace \" to " """ | if self . escape :
v = v . strip ( ) . replace ( "\\" + self . quote , self . quote )
return super ( kv_transformer , self ) . set ( e , k , v , real_k = real_k , check_kw_name = check_kw_name ) |
def sync_luigi_config ( self , push = True , pull = True , expand = True ) :
"""Synchronizes sections starting with ` ` " luigi _ " ` ` with the luigi configuration parser . First ,
when * push * is * True * , options that exist in law but * * not * * in luigi are stored as defaults
in the luigi config . Then ,... | prefix = "luigi_"
lparser = luigi . configuration . LuigiConfigParser . instance ( )
if push :
for section in self . sections ( ) :
if not section . startswith ( prefix ) :
continue
lsection = section [ len ( prefix ) : ]
if not lparser . has_section ( lsection ) :
lp... |
def FinalizeConfigInit ( config , token , admin_password = None , redownload_templates = False , repack_templates = True , prompt = True ) :
"""Performs the final steps of config initialization .""" | config . Set ( "Server.initialized" , True )
print ( "\nWriting configuration to %s." % config [ "Config.writeback" ] )
config . Write ( )
print ( "Initializing the datastore." )
# Reload the config and initialize the GRR database .
server_startup . Init ( )
print ( "\nStep 3: Adding GRR Admin User" )
try :
CreateU... |
def go_to_index ( self , index ) :
"""Create a new : class : ` . CompletionState ` object with the new index .""" | return CompletionState ( self . original_document , self . current_completions , complete_index = index ) |
def wormhole ( context , dump_timing , transit_helper , relay_url , appid ) :
"""Create a Magic Wormhole and communicate through it .
Wormholes are created by speaking the same magic CODE in two
different places at the same time . Wormholes are secure against
anyone who doesn ' t use the same code .""" | context . obj = cfg = Config ( )
cfg . appid = appid
cfg . relay_url = relay_url
cfg . transit_helper = transit_helper
cfg . dump_timing = dump_timing |
def of_text ( self , text , encoding = "utf-8" ) :
"""Use default hash method to return hash value of a piece of string
default setting use ' utf - 8 ' encoding .""" | m = self . hash_algo ( )
m . update ( text . encode ( encoding ) )
if self . return_int :
return int ( m . hexdigest ( ) , 16 )
else :
return m . hexdigest ( ) |
def p_definition_list ( p ) :
"""definition _ list : definition definition _ list
| definition""" | if len ( p ) == 3 :
p [ 0 ] = p [ 1 ] + p [ 2 ]
elif len ( p ) == 2 :
p [ 0 ] = p [ 1 ]
else :
raise RuntimeError ( "Invalid production rules 'p_action_list'" ) |
def visualize_saliency_with_losses ( input_tensor , losses , seed_input , wrt_tensor = None , grad_modifier = 'absolute' , keepdims = False ) :
"""Generates an attention heatmap over the ` seed _ input ` by using positive gradients of ` input _ tensor `
with respect to weighted ` losses ` .
This function is int... | opt = Optimizer ( input_tensor , losses , wrt_tensor = wrt_tensor , norm_grads = False )
grads = opt . minimize ( seed_input = seed_input , max_iter = 1 , grad_modifier = grad_modifier , verbose = False ) [ 1 ]
if not keepdims :
channel_idx = 1 if K . image_data_format ( ) == 'channels_first' else - 1
grads = n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.