signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def preformatted_text ( source : str ) -> str :
"""Renders preformatted text box""" | environ . abort_thread ( )
if not source :
return ''
source = render_utils . html_escape ( source )
return '<pre class="preformatted-textbox">{text}</pre>' . format ( text = str ( textwrap . dedent ( source ) ) ) |
def return_real_id_base ( dbpath , set_object ) :
"""Generic function which returns a list of real _ id ' s
Parameters
dbpath : string , path to SQLite database file
set _ object : object ( either TestSet or TrainSet ) which is stored in the database
Returns
return _ list : list of real _ id values for th... | engine = create_engine ( 'sqlite:////' + dbpath )
session_cl = sessionmaker ( bind = engine )
session = session_cl ( )
return_list = [ ]
for i in session . query ( set_object ) . order_by ( set_object . id ) :
return_list . append ( i . real_id )
session . close ( )
return return_list |
def argmax ( self , axis = None , skipna = True , * args , ** kwargs ) :
"""Returns the indices of the maximum values along an axis .
See ` numpy . ndarray . argmax ` for more information on the
` axis ` parameter .
See Also
numpy . ndarray . argmax""" | nv . validate_argmax ( args , kwargs )
nv . validate_minmax_axis ( axis )
i8 = self . asi8
if self . hasnans :
mask = self . _isnan
if mask . all ( ) or not skipna :
return - 1
i8 = i8 . copy ( )
i8 [ mask ] = 0
return i8 . argmax ( ) |
def create_api_integration_response ( restApiId , resourcePath , httpMethod , statusCode , selectionPattern , responseParameters = None , responseTemplates = None , region = None , key = None , keyid = None , profile = None ) :
'''Creates an integration response for a given method in a given API
CLI Example :
.... | try :
resource = describe_api_resource ( restApiId , resourcePath , region = region , key = key , keyid = keyid , profile = profile ) . get ( 'resource' )
if resource :
responseParameters = dict ( ) if responseParameters is None else responseParameters
responseTemplates = dict ( ) if responseTem... |
def static ( self , uri , file_or_directory , * args , ** kwargs ) :
"""Create a blueprint static route from a decorated function .
: param uri : endpoint at which the route will be accessible .
: param file _ or _ directory : Static asset .""" | static = FutureStatic ( uri , file_or_directory , args , kwargs )
self . statics . append ( static ) |
def learn ( self , fit = 0 , size = 0 , configure = None ) :
"""Learns all ( nearly ) optimal logical networks with give fitness and size tolerance .
The first optimum logical network found is saved in the attribute : attr : ` optimum ` while
all enumerated logical networks are saved in the attribute : attr : `... | encodings = [ 'guess' , 'fixpoint' , 'rss' ]
if self . optimum is None :
clingo = self . __get_clingo__ ( encodings + [ 'opt' ] )
if configure is not None :
configure ( clingo . conf )
clingo . ground ( [ ( "base" , [ ] ) ] )
clingo . solve ( on_model = self . __keep_last__ )
self . stats [ ... |
def get_machine ( self , key ) :
"""Returns the number of the machine which key gets sent to .""" | h = self . hash ( key )
# edge case where we cycle past hash value of 1 and back to 0.
if h > self . hash_tuples [ - 1 ] [ 2 ] :
return self . hash_tuples [ 0 ] [ 0 ]
hash_values = map ( lambda x : x [ 2 ] , self . hash_tuples )
index = bisect . bisect_left ( hash_values , h )
return self . hash_tuples [ index ] [ ... |
def set_initial_representations ( self ) :
"""Set the initial representations""" | self . update_model_dict ( )
self . rc ( "background solid white" )
self . rc ( "setattr g display 0" )
# Hide all pseudobonds
self . rc ( "~display #%i & :/isHet & ~:%s" % ( self . model_dict [ self . plipname ] , self . hetid ) ) |
def heading ( headingtext , headinglevel , lang = 'en' ) :
'''Make a new heading , return the heading element''' | lmap = { 'en' : 'Heading' , 'it' : 'Titolo' }
# Make our elements
paragraph = makeelement ( 'p' )
pr = makeelement ( 'pPr' )
pStyle = makeelement ( 'pStyle' , attributes = { 'val' : lmap [ lang ] + str ( headinglevel ) } )
run = makeelement ( 'r' )
text = makeelement ( 't' , tagtext = headingtext )
# Add the text the r... |
def _create_meta_cache ( self ) :
"""Try to dump metadata to a file .""" | try :
with open ( self . _cache_filename , 'wb' ) as f :
compat . pickle . dump ( self . _document_meta , f , 1 )
except ( IOError , compat . pickle . PickleError ) :
pass |
def send_keyboard_input ( text = None , key_list = None ) :
"""Args :
text ( None ) :
key _ list ( list ) :
References :
http : / / stackoverflow . com / questions / 14788036 / python - win32api - sendmesage
http : / / www . pinvoke . net / default . aspx / user32 . sendinput
CommandLine :
python - m ... | # key _ mapping = {
# ' enter ' :
if WIN32 : # raise NotImplementedError ( )
# import win32api
# import win32gui
# import win32con
# hwnd = win32gui . GetForegroundWindow ( )
# print ( ' entering text into % r ' % ( win32gui . GetWindowText ( hwnd ) , ) )
# win32con . VK _ RETURN
# def callback ( hwnd , hwnds ) :
# if ... |
def declare ( self , queue = '' , virtual_host = '/' , passive = False , durable = False , auto_delete = False , arguments = None ) :
"""Declare a Queue .
: param str queue : Queue name
: param str virtual _ host : Virtual host name
: param bool passive : Do not create
: param bool durable : Durable queue
... | if passive :
return self . get ( queue , virtual_host = virtual_host )
queue_payload = json . dumps ( { 'durable' : durable , 'auto_delete' : auto_delete , 'arguments' : arguments or { } , 'vhost' : virtual_host } )
return self . http_client . put ( API_QUEUE % ( quote ( virtual_host , '' ) , queue ) , payload = qu... |
def _get_measures ( self , et ) :
"""Get a list of measures in < continuous > or < SurveyOptions > section""" | list_of_measures = [ ]
for tag in et . findall ( "option" ) :
if tag . attrib . get ( "value" , "true" ) == "true" :
list_of_measures . append ( tag . attrib [ "name" ] )
return list_of_measures |
def handle_url ( url , session , res ) :
"""Parse one search result page .""" | print ( "Parsing" , url , file = sys . stderr )
try :
data = getPageContent ( url , session )
except IOError as msg :
print ( "ERROR:" , msg , file = sys . stderr )
return
for match in url_matcher . finditer ( data ) :
url = match . group ( 1 ) + '/'
name = unescape ( match . group ( 2 ) )
name ... |
def lbest_idx ( state , idx ) :
"""lbest Neighbourhood topology function .
Neighbourhood size is determined by state . params [ ' n _ s ' ] .
Args :
state : cipy . algorithms . pso . State : The state of the PSO algorithm .
idx : int : index of the particle in the swarm .
Returns :
int : The index of th... | swarm = state . swarm
n_s = state . params [ 'n_s' ]
cmp = comparator ( swarm [ 0 ] . best_fitness )
indices = __lbest_indices__ ( len ( swarm ) , n_s , idx )
best = None
for i in indices :
if best is None or cmp ( swarm [ i ] . best_fitness , swarm [ best ] . best_fitness ) :
best = i
return best |
def parse_250_row ( row : list ) -> BasicMeterData :
"""Parse basic meter data record ( 250)""" | return BasicMeterData ( row [ 1 ] , row [ 2 ] , row [ 3 ] , row [ 4 ] , row [ 5 ] , row [ 6 ] , row [ 7 ] , float ( row [ 8 ] ) , parse_datetime ( row [ 9 ] ) , row [ 10 ] , row [ 11 ] , row [ 12 ] , float ( row [ 13 ] ) , parse_datetime ( row [ 14 ] ) , row [ 15 ] , row [ 16 ] , row [ 17 ] , float ( row [ 18 ] ) , row... |
def inherit_docstrings ( cls ) :
"""Class decorator for inheriting docstrings .
Automatically inherits base class doc - strings if not present in the
derived class .""" | @ functools . wraps ( cls )
def _inherit_docstrings ( cls ) :
if not isinstance ( cls , ( type , colorise . compat . ClassType ) ) :
raise RuntimeError ( "Type is not a class" )
for name , value in colorise . compat . iteritems ( vars ( cls ) ) :
if isinstance ( getattr ( cls , name ) , types . ... |
def fetch_query_from_pgdb ( self , qname , query , con , cxn , limit = None , force = False ) :
"""Supply either an already established connection , or connection parameters .
The supplied connection will override any separate cxn parameter
: param qname : The name of the query to save the output to
: param q... | if con is None and cxn is None :
LOG . error ( "ERROR: you need to supply connection information" )
return
if con is None and cxn is not None :
con = psycopg2 . connect ( host = cxn [ 'host' ] , database = cxn [ 'database' ] , port = cxn [ 'port' ] , user = cxn [ 'user' ] , password = cxn [ 'password' ] )
o... |
def connect_signals ( self , target ) :
"""This is deprecated . Pass your controller to connect signals the old
way .""" | if self . connected :
raise RuntimeError ( "GtkBuilder can only connect signals once" )
self . builder . connect_signals ( target )
self . connected = True |
def new ( cls , alias , certs , key , key_format = 'pkcs8' ) :
"""Helper function to create a new PrivateKeyEntry .
: param str alias : The alias for the Private Key Entry
: param list certs : An list of certificates , as byte strings .
The first one should be the one belonging to the private key ,
the othe... | timestamp = int ( time . time ( ) ) * 1000
cert_chain = [ ]
for cert in certs :
cert_chain . append ( ( 'X.509' , cert ) )
pke = cls ( timestamp = timestamp , # Alias must be lower case or it will corrupt the keystore for Java Keytool and Keytool Explorer
alias = alias . lower ( ) , cert_chain = cert_chain )
if key... |
def _set_complete_option ( cls ) :
"""Check and set complete option .""" | get_config = cls . context . get_config
complete = get_config ( 'complete' , None )
if complete is None :
conditions = [ get_config ( 'transitions' , False ) , get_config ( 'named_transitions' , False ) , ]
complete = not any ( conditions )
cls . context . new_meta [ 'complete' ] = complete |
def inventory ( self , inventory_name ) :
"""Decorator to register filters for given inventory . For a function " abc " , it has the same effect
: param inventory _ name :
: return :
. . code - block : : python
tic = CtsTextInventoryCollection ( )
latin = CtsTextInventoryMetadata ( " urn : perseus : latin... | def decorator ( f ) :
self . add ( func = f , inventory_name = inventory_name )
return f
return decorator |
def updated ( self , user , options ) :
"""True if the issue was commented by given user""" | for comment in self . comments :
created = dateutil . parser . parse ( comment [ "created" ] ) . date ( )
try :
if ( comment [ "author" ] [ "emailAddress" ] == user . email and created >= options . since . date and created < options . until . date ) :
return True
except KeyError :
... |
def pause ( self , movie = None , show = None , episode = None , progress = 0.0 , ** kwargs ) :
"""Send the scrobble " pause ' action .
Use this method when the video is paused . The playback progress will be saved and
: code : ` Trakt [ ' sync / playback ' ] . get ( ) ` can be used to resume the video from thi... | return self . action ( 'pause' , movie , show , episode , progress , ** kwargs ) |
def add_dos ( self , label , dos ) :
"""Adds a dos for plotting .
Args :
label :
label for the DOS . Must be unique .
dos :
Dos object""" | energies = dos . energies - dos . efermi if self . zero_at_efermi else dos . energies
densities = dos . get_smeared_densities ( self . sigma ) if self . sigma else dos . densities
efermi = dos . efermi
self . _doses [ label ] = { 'energies' : energies , 'densities' : densities , 'efermi' : efermi } |
def do_identity ( args ) :
"""Executes the config commands subcommands .""" | if args . subcommand == 'policy' and args . policy_cmd == 'create' :
_do_identity_policy_create ( args )
elif args . subcommand == 'policy' and args . policy_cmd == 'list' :
_do_identity_policy_list ( args )
elif args . subcommand == 'role' and args . role_cmd == 'create' :
_do_identity_role_create ( args )... |
def send_wsgi_response ( status , headers , content , start_response , cors_handler = None ) :
"""Dump reformatted response to CGI start _ response .
This calls start _ response and returns the response body .
Args :
status : A string containing the HTTP status code to send .
headers : A list of ( header , ... | if cors_handler :
cors_handler . update_headers ( headers )
# Update content length .
content_len = len ( content ) if content else 0
headers = [ ( header , value ) for header , value in headers if header . lower ( ) != 'content-length' ]
headers . append ( ( 'Content-Length' , '%s' % content_len ) )
start_response... |
def convertImagesToPIL ( self , images , dither , nq = 0 ) :
"""convertImagesToPIL ( images , nq = 0)
Convert images to Paletted PIL images , which can then be
written to a single animaged GIF .""" | # Convert to PIL images
images2 = [ ]
for im in images :
if isinstance ( im , Image . Image ) :
images2 . append ( im )
elif np and isinstance ( im , np . ndarray ) :
if im . ndim == 3 and im . shape [ 2 ] == 3 :
im = Image . fromarray ( im , 'RGB' )
elif im . ndim == 3 and i... |
def parse ( cls , backend , ik , spk , spk_signature , otpks ) :
"""Use this method when creating a bundle from data you retrieved directly from some
PEP node . This method applies an additional decoding step to the public keys in
the bundle . Pass the same structure as the constructor expects .""" | ik = backend . decodePublicKey ( ik ) [ 0 ]
spk [ "key" ] = backend . decodePublicKey ( spk [ "key" ] ) [ 0 ]
otpks = list ( map ( lambda otpk : { "key" : backend . decodePublicKey ( otpk [ "key" ] ) [ 0 ] , "id" : otpk [ "id" ] } , otpks ) )
return cls ( ik , spk , spk_signature , otpks ) |
def discover ( app , module_name = None ) :
"""Automatically apply the permission logics written in the specified
module .
Examples
Assume if you have a ` ` perms . py ` ` in ` ` your _ app ` ` as : :
from permission . logics import AuthorPermissionLogic
PERMISSION _ LOGICS = (
( ' your _ app . your _ m... | from permission . compat import import_module
from permission . compat import get_model
from permission . conf import settings
from permission . utils . logics import add_permission_logic
variable_name = settings . PERMISSION_AUTODISCOVER_VARIABLE_NAME
module_name = module_name or settings . PERMISSION_AUTODISCOVER_MOD... |
def _subtask_result ( self , idx , value ) :
"""Receive a result from a single subtask .""" | self . _results [ idx ] = value
if len ( self . _results ) == self . _num_tasks :
self . set_result ( [ self . _results [ i ] for i in range ( self . _num_tasks ) ] ) |
def get_psf_sky ( self , ra , dec ) :
"""Determine the local psf at a given sky location .
The psf is returned in degrees .
Parameters
ra , dec : float
The sky position ( degrees ) .
Returns
a , b , pa : float
The psf semi - major axis , semi - minor axis , and position angle in ( degrees ) .
If a p... | # If we don ' t have a psf map then we just fall back to using the beam
# from the fits header ( including ZA scaling )
if self . data is None :
beam = self . wcshelper . get_beam ( ra , dec )
return beam . a , beam . b , beam . pa
x , y = self . sky2pix ( [ ra , dec ] )
# We leave the interpolation in the hand... |
def verify ( self , message , signature ) :
"""Verified the signature attached to the supplied message using NTLM2 Session Security
: param message : The message whose signature will verified
: return : True if the signature is valid , otherwise False""" | # Parse the signature header
mac = _Ntlm2MessageSignature ( )
mac . from_string ( signature )
# validate the sequence
if mac [ 'sequence' ] != self . incoming_sequence :
raise Exception ( "The message was not received in the correct sequence." )
# extract the supplied checksum
checksum = struct . pack ( '<q' , mac ... |
def to_text ( self ) :
"""Render a Text MessageElement as plain text
: returns : The plain text representation of the row .
: rtype : basestring""" | row = '---\n'
for index , cell in enumerate ( self . cells ) :
if index > 0 :
row += ', '
row += cell . to_text ( )
row += '---'
return row |
def main ( ) :
"""The main function of the script""" | desc = 'Generate files to benchmark'
parser = argparse . ArgumentParser ( description = desc )
parser . add_argument ( '--src' , dest = 'src_dir' , default = 'src' , help = 'The directory containing the templates' )
parser . add_argument ( '--out' , dest = 'out_dir' , default = 'generated' , help = 'The output director... |
def dump_seek ( self , reading_id ) :
"""Seek the dump streamer to a given ID .
Returns :
( int , int , int ) : Two error codes and the count of remaining readings .
The first error code covers the seeking process .
The second error code covers the stream counting process ( cannot fail )
The third item in... | if self . dump_walker is None :
return ( pack_error ( ControllerSubsystem . SENSOR_LOG , SensorLogError . STREAM_WALKER_NOT_INITIALIZED ) , Error . NO_ERROR , 0 )
try :
exact = self . dump_walker . seek ( reading_id , target = 'id' )
except UnresolvedIdentifierError :
return ( pack_error ( ControllerSubsyst... |
def time ( lancet , issue ) :
"""Start an Harvest timer for the given issue .
This command takes care of linking the timer with the issue tracker page
for the given issue . If the issue is not passed to command it ' s taken
from currently active branch .""" | issue = get_issue ( lancet , issue )
with taskstatus ( "Starting harvest timer" ) as ts :
lancet . timer . start ( issue )
ts . ok ( "Started harvest timer" ) |
def exec_rabbitmqctl_list ( self , resources , args = [ ] , rabbitmq_opts = [ '-q' , '--no-table-headers' ] ) :
"""Execute a ` ` rabbitmqctl ` ` command to list the given resources .
: param resources : the resources to list , e . g . ` ` ' vhosts ' ` `
: param args : a list of args for the command
: param ra... | command = 'list_{}' . format ( resources )
return self . exec_rabbitmqctl ( command , args , rabbitmq_opts ) |
def get_products ( self , product_ids ) :
"""This function ( and backend API ) is being obsoleted . Don ' t use it anymore .""" | if self . product_set_id is None :
raise ValueError ( 'product_set_id must be specified' )
data = { 'ids' : product_ids }
return self . client . get ( self . base_url + '/products' , json = data ) |
def is_number_type_geographical ( num_type , country_code ) :
"""Tests whether a phone number has a geographical association ,
as represented by its type and the country it belongs to .
This version of isNumberGeographical exists since calculating the phone
number type is expensive ; if we have already done t... | return ( num_type == PhoneNumberType . FIXED_LINE or num_type == PhoneNumberType . FIXED_LINE_OR_MOBILE or ( ( country_code in _GEO_MOBILE_COUNTRIES ) and num_type == PhoneNumberType . MOBILE ) ) |
def dry_lapse ( pressure , temperature , ref_pressure = None ) :
r"""Calculate the temperature at a level assuming only dry processes .
This function lifts a parcel starting at ` temperature ` , conserving
potential temperature . The starting pressure can be given by ` ref _ pressure ` .
Parameters
pressure... | if ref_pressure is None :
ref_pressure = pressure [ 0 ]
return temperature * ( pressure / ref_pressure ) ** mpconsts . kappa |
def frame ( self , frame ) :
"""Return a path go the given frame in the sequence . Integer or string
digits are treated as a frame number and padding is applied , all other
values are passed though .
Examples :
> > > seq . frame ( 1)
/ foo / bar . 0001 . exr
> > > seq . frame ( " # " )
/ foo / bar . #... | try :
zframe = str ( int ( frame ) ) . zfill ( self . _zfill )
except ValueError :
zframe = frame
# There may have been no placeholder for frame IDs in
# the sequence , in which case we don ' t want to insert
# a frame ID
if self . _zfill == 0 :
zframe = ""
return "" . join ( ( self . _dir , self . _base , ... |
def escape_latex ( text ) :
r"""Escape characters of given text .
This function takes the given text and escapes characters
that have a special meaning in LaTeX : # $ % ^ & _ { } ~ \""" | text = unicode ( text . decode ( 'utf-8' ) )
CHARS = { '&' : r'\&' , '%' : r'\%' , '$' : r'\$' , '#' : r'\#' , '_' : r'\_' , '{' : r'\{' , '}' : r'\}' , '~' : r'\~{}' , '^' : r'\^{}' , '\\' : r'\textbackslash{}' , }
escaped = "" . join ( [ CHARS . get ( char , char ) for char in text ] )
return escaped . encode ( 'utf-... |
def partialclass ( cls , * args , ** kwargs ) :
"""Returns a partially instantiated class
: return : A partial class instance
: rtype : cls
> > > source = partialclass ( Source , url = " https : / / pypi . org / simple " )
> > > source
< class ' _ _ main _ _ . Source ' >
> > > source ( name = " pypi " )... | name_attrs = [ n for n in ( getattr ( cls , name , str ( cls ) ) for name in ( "__name__" , "__qualname__" ) ) if n is not None ]
name_attrs = name_attrs [ 0 ]
type_ = type ( name_attrs , ( cls , ) , { "__init__" : partialmethod ( cls . __init__ , * args , ** kwargs ) } )
# Swiped from attrs . make _ class
try :
ty... |
def get_root ( w ) :
"""Simple method to access root for a widget""" | next_level = w
while next_level . master :
next_level = next_level . master
return next_level |
def slang_date ( self , locale = "en" ) :
"""" Returns human slang representation of date .
Keyword Arguments :
locale - - locale to translate to , e . g . ' fr ' for french .
( default : ' en ' - English )""" | dt = pendulum . instance ( self . datetime ( ) )
try :
return _translate ( dt , locale )
except KeyError :
pass
delta = humanize . time . abs_timedelta ( timedelta ( seconds = ( self . epoch - now ( ) . epoch ) ) )
format_string = "DD MMM"
if delta . days >= 365 :
format_string += " YYYY"
return dt . format... |
def load_history ( self , obj = None ) :
"""Load history from a text file in user home directory""" | if osp . isfile ( self . LOG_PATH ) :
history = [ line . replace ( '\n' , '' ) for line in open ( self . LOG_PATH , 'r' ) . readlines ( ) ]
else :
history = [ ]
return history |
def enable_unique_tokens ( self ) :
"""Enable the use of unique access tokens on all grant types that support
this option .""" | for grant_type in self . grant_types :
if hasattr ( grant_type , "unique_token" ) :
grant_type . unique_token = True |
def sdk_normalize ( filename ) :
"""Normalize a path to strip out the SDK portion , normally so that it
can be decided whether it is in a system path or not .""" | if filename . startswith ( '/Developer/SDKs/' ) :
pathcomp = filename . split ( '/' )
del pathcomp [ 1 : 4 ]
filename = '/' . join ( pathcomp )
return filename |
def find_discrete ( start_time , end_time , f , epsilon = EPSILON , num = 12 ) :
"""Find the times when a function changes value .
Searches between ` ` start _ time ` ` and ` ` end _ time ` ` , which should both
be : class : ` ~ skyfield . timelib . Time ` objects , for the occasions where
the function ` ` f ... | ts = start_time . ts
jd0 = start_time . tt
jd1 = end_time . tt
if jd0 >= jd1 :
raise ValueError ( 'your start_time {0} is later than your end_time {1}' . format ( start_time , end_time ) )
periods = ( jd1 - jd0 ) / f . rough_period
if periods < 1.0 :
periods = 1.0
jd = linspace ( jd0 , jd1 , periods * num // 1.... |
def walk_nodes ( self , node , original ) :
"""Iterate over the nodes recursively yielding the templatetag ' sass _ src '""" | try : # try with django - compressor < 2.1
nodelist = self . parser . get_nodelist ( node , original = original )
except TypeError :
nodelist = self . parser . get_nodelist ( node , original = original , context = None )
for node in nodelist :
if isinstance ( node , SassSrcNode ) :
if node . is_sass... |
def dict_row_strategy ( column_names ) :
"""Dict row strategy , rows returned as dictionaries""" | # replace empty column names with indices
column_names = [ ( name or idx ) for idx , name in enumerate ( column_names ) ]
def row_factory ( row ) :
return dict ( zip ( column_names , row ) )
return row_factory |
def load_api_folder ( api_folder_path ) :
"""load api definitions from api folder .
Args :
api _ folder _ path ( str ) : api files folder .
api file should be in the following format :
" api " : {
" def " : " api _ login " ,
" request " : { } ,
" validate " : [ ]
" api " : {
" def " : " api _ logo... | api_definition_mapping = { }
api_items_mapping = load_folder_content ( api_folder_path )
for api_file_path , api_items in api_items_mapping . items ( ) : # TODO : add JSON schema validation
if isinstance ( api_items , list ) :
for api_item in api_items :
key , api_dict = api_item . popitem ( )
... |
def get_list_header ( self ) :
"""Creates a list of dictionaries with the field names , labels ,
field links , field css classes , order _ url and order _ direction ,
this simplifies the creation of a table in a template .""" | result = [ ]
for field_name in self . get_fields ( ) :
item = { }
if isinstance ( field_name , tuple ) : # custom property that is not a field of the model
item [ "name" ] = field_name [ 0 ]
item [ "label" ] = field_name [ 1 ]
else :
item [ "name" ] = field_name
item [ "label... |
def SCG ( f , gradf , x , optargs = ( ) , maxiters = 500 , max_f_eval = np . inf , xtol = None , ftol = None , gtol = None ) :
"""Optimisation through Scaled Conjugate Gradients ( SCG )
f : the objective function
gradf : the gradient function ( should return a 1D np . ndarray )
x : the initial condition
Ret... | if xtol is None :
xtol = 1e-6
if ftol is None :
ftol = 1e-6
if gtol is None :
gtol = 1e-5
sigma0 = 1.0e-7
fold = f ( x , * optargs )
# Initial function value .
function_eval = 1
fnow = fold
gradnew = gradf ( x , * optargs )
# Initial gradient .
function_eval += 1
# if any ( np . isnan ( gradnew ) ) :
# rais... |
def fix_missing_locations ( node ) :
"""Some nodes require a line number and the column offset . Without that
information the compiler will abort the compilation . Because it can be
a dull task to add appropriate line numbers and column offsets when
adding new nodes this function can help . It copies the line... | def _fix ( node , lineno , col_offset ) :
if 'lineno' in node . _attributes :
if not hasattr ( node , 'lineno' ) :
node . lineno = lineno
else :
lineno = node . lineno
if 'col_offset' in node . _attributes :
if not hasattr ( node , 'col_offset' ) :
nod... |
def _add_global_counter ( self ) :
"""Adds a global counter , called once for setup by @ property global _ step .""" | assert self . _global_step is None
# Force this into the top - level namescope . Instead of forcing top - level
# here , we could always call this in _ _ init _ _ ( ) and then keep whatever
# namescopes are around then .
with self . g . as_default ( ) , self . g . name_scope ( None ) :
try :
self . _global_... |
def graph_memoized ( func ) :
"""Like memoized , but keep one cache per default graph .""" | # TODO it keeps the graph alive
from . . compat import tfv1
GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__'
@ memoized
def func_with_graph_arg ( * args , ** kwargs ) :
kwargs . pop ( GRAPH_ARG_NAME )
return func ( * args , ** kwargs )
@ functools . wraps ( func )
def wrapper ( * args , ** kwargs ) :
assert G... |
def get_autoscaling_group_properties ( asg_client , env , service ) :
"""Gets the autoscaling group properties based on the service name that is provided . This function will attempt the find
the autoscaling group base on the following logic :
1 . If the service name provided matches the autoscaling group name ... | try : # See if { { ENV } } - { { SERVICE } } matches ASG name
response = asg_client . describe_auto_scaling_groups ( AutoScalingGroupNames = [ "{}-{}" . format ( env , service ) ] )
if len ( response [ "AutoScalingGroups" ] ) == 0 : # See if { { ENV } } - { { SERVICE } } matches ASG tag name
response = ... |
def AnalizarLiquidacion ( self , aut , liq = None , ajuste = False ) :
"Método interno para analizar la respuesta de AFIP" | # proceso los datos básicos de la liquidación ( devuelto por consultar ) :
if liq :
self . params_out = dict ( pto_emision = liq . get ( 'ptoEmision' ) , nro_orden = liq . get ( 'nroOrden' ) , cuit_comprador = liq . get ( 'cuitComprador' ) , nro_act_comprador = liq . get ( 'nroActComprador' ) , nro_ing_bruto_comp... |
def prettyDateDifference ( startTime , finishTime = None ) :
"""Get a datetime object or a int ( ) Epoch timestamp and return a
pretty string like ' an hour ago ' , ' Yesterday ' , ' 3 months ago ' ,
' just now ' , etc""" | from datetime import datetime
if startTime is None :
return None
if not isinstance ( startTime , ( int , datetime ) ) :
raise RuntimeError ( "Cannot parse time" )
endTime = finishTime or datetime . now ( )
if isinstance ( startTime , int ) :
diff = endTime - datetime . fromtimestamp ( startTime )
elif isins... |
def get_plugin_class ( self , typ ) :
"""get class by name""" | if typ in self . _class :
return self . _class [ typ ]
# try to import by same name
try :
importlib . import_module ( "%s.%s" % ( self . namespace , typ ) )
if typ in self . _class :
return self . _class [ typ ]
except ImportError as e :
self . log . debug ( "ImportError " + str ( e ) )
raise Va... |
def post_load ( fn = None , pass_many = False , pass_original = False ) :
"""Register a method to invoke after deserializing an object . The method
receives the deserialized data and returns the processed data .
By default , receives a single datum at a time , transparently handling the ` ` many ` `
argument ... | return set_hook ( fn , ( POST_LOAD , pass_many ) , pass_original = pass_original ) |
def _make_data ( data ) -> Tuple [ List [ Dict ] , List [ Dict ] ] :
"""Transform table data into JSON .""" | jsdata = [ ]
for idx , row in data . iterrows ( ) :
row . index = row . index . astype ( str )
rdict = row . to_dict ( )
rdict . update ( dict ( key = str ( idx ) ) )
jsdata . append ( rdict )
return jsdata , Table . _make_columns ( data . columns ) |
def get_readonly_fields ( self , request , obj = None ) :
"""Makes ` created _ by ` , ` create _ date ` & ` update _ date ` readonly when
editing .
Author : Himanshu Shankar ( https : / / himanshus . com )""" | # Get read only fields from super
fields = list ( super ( CreateUpdateAdmin , self ) . get_readonly_fields ( request = request , obj = obj ) )
# Loop over ownership info field
for k , v in self . ownership_info [ 'fields' ] . items ( ) : # Check if model has k attribute
# and field k is readonly
# and k is not already ... |
def handle_decoded_payload ( self , data ) :
'''Override this method if you wish to handle the decoded data
differently .''' | # Ensure payload is unicode . Disregard failure to decode binary blobs .
if six . PY2 :
data = salt . utils . data . decode ( data , keep = True )
if 'user' in data :
log . info ( 'User %s Executing command %s with jid %s' , data [ 'user' ] , data [ 'fun' ] , data [ 'jid' ] )
else :
log . info ( 'Executing ... |
def decode_exactly ( code , bits_per_char = 6 ) :
"""Decode a geohash on a hilbert curve as a lng / lat position with error - margins
Decodes the geohash ` code ` as a lng / lat position with error - margins . It assumes ,
that the length of ` code ` corresponds to the precision ! And that each character
in `... | assert bits_per_char in ( 2 , 4 , 6 )
if len ( code ) == 0 :
return 0. , 0. , _LNG_INTERVAL [ 1 ] , _LAT_INTERVAL [ 1 ]
bits = len ( code ) * bits_per_char
level = bits >> 1
dim = 1 << level
code_int = decode_int ( code , bits_per_char )
if CYTHON_AVAILABLE and bits <= MAX_BITS :
x , y = hash2xy_cython ( code_i... |
def _get_local_dict ( self ) :
"""Retrieve ( or initialize ) the thread - local data to use .""" | try :
return getattr ( THREAD_STORE , self . namespace )
except AttributeError :
local_var = dict ( * self . args , ** self . kwargs )
setattr ( THREAD_STORE , self . namespace , local_var )
return local_var |
def pool_update ( self , pool_id , name = None , description = None , post_ids = None , is_active = None , category = None ) :
"""Update a pool ( Requires login ) ( UNTESTED ) .
Parameters :
pool _ id ( int ) : Where pool _ id is the pool id .
name ( str ) :
description ( str ) :
post _ ids ( str ) : List... | params = { 'pool[name]' : name , 'pool[description]' : description , 'pool[post_ids]' : post_ids , 'pool[is_active]' : is_active , 'pool[category]' : category }
return self . _get ( 'pools/{0}.json' . format ( pool_id ) , params , method = 'PUT' , auth = True ) |
def inspect_config ( app ) :
"""Inspect the Sphinx configuration and update for slide - linking .
If links from HTML to slides are enabled , make sure the sidebar
configuration includes the template and add the necessary theme
directory as a loader so the sidebar template can be located .
If the sidebar con... | # avoid import cycles : /
from hieroglyph import writer
# only reconfigure Sphinx if we ' re generating HTML
if app . builder . name not in HTML_BUILDERS :
return
if app . config . slide_link_html_to_slides : # add the slide theme dir as a Loader
app . builder . templates . loaders . append ( SphinxFileSystemLo... |
def _decode ( cls , value ) :
"""Decode the given value , reverting ' % ' - encoded groups .""" | value = cls . _DEC_RE . sub ( lambda x : '%c' % int ( x . group ( 1 ) , 16 ) , value )
return json . loads ( value ) |
def vector_args ( self , args ) :
"""Yields each of the individual lane pairs from the arguments , in
order from most significan to least significant""" | for i in reversed ( range ( self . _vector_count ) ) :
pieces = [ ]
for vec in args :
pieces . append ( vec [ ( i + 1 ) * self . _vector_size - 1 : i * self . _vector_size ] )
yield pieces |
def draw_eccs ( n , per = 10 , binsize = 0.1 , fuzz = 0.05 , maxecc = 0.97 ) :
"""draws eccentricities appropriate to given periods , generated according to empirical data from Multiple Star Catalog""" | if np . size ( per ) == 1 or np . std ( np . atleast_1d ( per ) ) == 0 :
if np . size ( per ) > 1 :
per = per [ 0 ]
if per == 0 :
es = np . zeros ( n )
else :
ne = 0
while ne < 10 :
mask = np . absolute ( np . log10 ( MSC_TRIPLEPERS ) - np . log10 ( per ) ) < bins... |
def add_detector ( self , detector_cls ) :
"""Add a ` ` Detector ` ` to scrubadub""" | if not issubclass ( detector_cls , detectors . base . Detector ) :
raise TypeError ( ( '"%(detector_cls)s" is not a subclass of Detector' ) % locals ( ) )
# TODO : should add tests to make sure filth _ cls is actually a proper
# filth _ cls
name = detector_cls . filth_cls . type
if name in self . _detectors :
r... |
def segment_volume ( seg ) :
'''Compute the volume of a segment .
Approximated as a conical frustum .''' | r0 = seg [ 0 ] [ COLS . R ]
r1 = seg [ 1 ] [ COLS . R ]
h = point_dist ( seg [ 0 ] , seg [ 1 ] )
return math . pi * h * ( ( r0 * r0 ) + ( r0 * r1 ) + ( r1 * r1 ) ) / 3.0 |
def items ( self ) :
"""Behave like ` dict . items ` for mapping types ( iterator over ( key , value )
pairs ) , and like ` iter ` for sequence types ( iterator over values ) .""" | if self . empty :
return iter ( [ ] )
val = self . value
if hasattr ( val , "iteritems" ) :
return val . iteritems ( )
elif hasattr ( val , "items" ) :
return val . items ( )
else :
return iter ( self ) |
def clear_db_attribute ( self , table , record , column ) :
"""Clears values from ' column ' in ' record ' in ' table ' .
This method is corresponding to the following ovs - vsctl command : :
$ ovs - vsctl clear TBL REC COL""" | command = ovs_vsctl . VSCtlCommand ( 'clear' , ( table , record , column ) )
self . run_command ( [ command ] ) |
def trainHMM_fromFile ( wav_file , gt_file , hmm_model_name , mt_win , mt_step ) :
'''This function trains a HMM model for segmentation - classification using a single annotated audio file
ARGUMENTS :
- wav _ file : the path of the audio filename
- gt _ file : the path of the ground truth filename
( a csv f... | [ seg_start , seg_end , seg_labs ] = readSegmentGT ( gt_file )
flags , class_names = segs2flags ( seg_start , seg_end , seg_labs , mt_step )
[ fs , x ] = audioBasicIO . readAudioFile ( wav_file )
[ F , _ , _ ] = aF . mtFeatureExtraction ( x , fs , mt_win * fs , mt_step * fs , round ( fs * 0.050 ) , round ( fs * 0.050 )... |
def server_id ( self ) :
"asks the server at the other end for its unique id ." | c_result = dbus . dbus_connection_get_server_id ( self . _dbobj )
result = ct . cast ( c_result , ct . c_char_p ) . value . decode ( )
dbus . dbus_free ( c_result )
return result |
def add_entry ( self , row ) :
"""This will parse the VCF entry and also store it within the VCFFile . It will also
return the VCFEntry as well .""" | var_call = VCFEntry ( self . individuals )
var_call . parse_entry ( row )
self . entries [ ( var_call . chrom , var_call . pos ) ] = var_call
return var_call |
def Nads_in_slab ( self ) :
"""Returns the TOTAL number of adsorbates in the slab on BOTH sides""" | return sum ( [ self . composition . as_dict ( ) [ a ] for a in self . ads_entries_dict . keys ( ) ] ) |
def save ( self , ** fields ) :
"""Save the instance to the remote Transifex server .
If it was pre - populated , it updates the instance on the server ,
otherwise it creates a new object .
Any values given in ` fields ` will be attempted to be saved
on the object . The same goes for any other values alread... | for field in fields :
if field in self . writable_fields :
setattr ( self , field , fields [ field ] )
else :
self . _handle_wrong_field ( field , ATTR_TYPE_WRITE )
if self . _populated_fields :
self . _update ( ** self . _modified_fields )
else :
self . _create ( ** self . _modified_fie... |
def add_checkpoint_file ( self , filename ) :
"""Add filename as a checkpoint file for this DAG node
@ param filename : checkpoint filename to add""" | if filename not in self . __checkpoint_files :
self . __checkpoint_files . append ( filename )
if not isinstance ( self . job ( ) , CondorDAGManJob ) :
if self . job ( ) . get_universe ( ) == 'grid' :
self . add_checkpoint_macro ( filename ) |
def OneResult ( parser ) :
"Parse like parser , but return exactly one result , not a tuple ." | def parse ( text ) :
results = parser ( text )
assert len ( results ) == 1 , "Expected one result but got %r" % ( results , )
return results [ 0 ]
return parse |
def to_dict ( self , converter = None ) :
"""Returns a copy dict of the current object
If a converter function is given , pass each value to it .
Per default the values are converted by ` self . stringify ` .""" | if converter is None :
converter = self . stringify
out = dict ( )
for k , v in self . iteritems ( ) :
out [ k ] = converter ( v )
return out |
def _compare_by_version ( path1 , path2 ) :
"""Returns the current / latest learned path .
Checks if given paths are from same source / peer and then compares their
version number to determine which path is received later . If paths are from
different source / peer return None .""" | if path1 . source == path2 . source :
if path1 . source_version_num > path2 . source_version_num :
return path1
else :
return path2
return None |
def setup_partitioning ( portal ) :
"""Setups the enhanced partitioning system""" | logger . info ( "Setting up the enhanced partitioning system" )
# Add " Create partition " transition
add_create_partition_transition ( portal )
# Add getAncestorsUIDs index in analyses catalog
add_partitioning_indexes ( portal )
# Adds metadata columns for partitioning
add_partitioning_metadata ( portal )
# Setup defa... |
async def _async_supervisor ( func , animation_ , step , * args , ** kwargs ) :
"""Supervisor for running an animation with an asynchronous function .
Args :
func : A function to be run alongside an animation .
animation _ : An infinite generator that produces
strings for the animation .
step : Seconds be... | with ThreadPoolExecutor ( max_workers = 2 ) as pool :
with _terminating_event ( ) as event :
pool . submit ( animate_cli , animation_ , step , event )
result = await func ( * args , ** kwargs )
return result |
def print_variables ( self ) :
"""Prints out magic variables available in config files
alongside with their values and descriptions .
May be useful for debugging .
http : / / uwsgi - docs . readthedocs . io / en / latest / Configuration . html # magic - variables""" | print_out = partial ( self . print_out , format_options = 'green' )
print_out ( '===== variables =====' )
for var , hint in self . vars . get_descriptions ( ) . items ( ) :
print_out ( ' %' + var + ' = ' + var + ' = ' + hint . replace ( '%' , '%%' ) )
print_out ( '=====================' )
return self |
def __convertLongToString ( self , iValue ) :
"""convert a long hex integer to string
remove ' 0x ' and ' L ' return string
Args :
iValue : long integer in hex format
Returns :
string of this long integer without " 0x " and " L " """ | string = ''
strValue = str ( hex ( iValue ) )
string = strValue . lstrip ( '0x' )
string = string . rstrip ( 'L' )
return string |
def load_img ( path , grayscale = False , target_size = None ) :
"""Utility function to load an image from disk .
Args :
path : The image file path .
grayscale : True to convert to grayscale image ( Default value = False )
target _ size : ( w , h ) to resize . ( Default value = None )
Returns :
The load... | img = io . imread ( path , grayscale )
if target_size :
img = transform . resize ( img , target_size , preserve_range = True ) . astype ( 'uint8' )
return img |
def valid_ipv4 ( ip ) :
"""check if ip is a valid ipv4""" | match = _valid_ipv4 . match ( ip )
if match is None :
return False
octets = match . groups ( )
if len ( octets ) != 4 :
return False
first = int ( octets [ 0 ] )
if first < 1 or first > 254 :
return False
for i in range ( 1 , 4 ) :
octet = int ( octets [ i ] )
if octet < 0 or octet > 255 :
r... |
def patch ( args ) :
"""% prog patch reference . fasta reads . fasta
Run PBJelly with reference and reads .""" | from jcvi . formats . base import write_file
from jcvi . formats . fasta import format
p = OptionParser ( patch . __doc__ )
p . add_option ( "--cleanfasta" , default = False , action = "store_true" , help = "Clean FASTA to remove description [default: %default]" )
p . add_option ( "--highqual" , default = False , actio... |
def get_ports_strings_from_list ( data ) :
"""Transform a list of port numbers to the list of strings with port ranges
Example : [ 10 , 12 , 13 , 14 , 15 ] - > [ ' 10 ' , ' 12-15 ' ]""" | if len ( data ) == 0 :
return [ ]
# Transform diff _ ports list to the ranges list
first = 0
result = [ ]
for it in range ( 1 , len ( data ) ) :
if data [ first ] == data [ it ] - ( it - first ) :
continue
result . append ( PortsRangeHelper . PortsRange ( start = data [ first ] , end = data [ it - 1... |
def asString ( self ) :
"""Returns this query with an AsString function added to it .
: return < Query >""" | q = self . copy ( )
q . addFunction ( Query . Function . AsString )
return q |
def utils_doc ( * args ) :
'''. . versionadded : : Neon
Return the docstrings for all utils modules . Optionally , specify a module
or a function to narrow the selection .
The strings are aggregated into a single document on the master for easy
reading .
Multiple modules / functions can be specified .
C... | docs = { }
if not args :
for fun in __utils__ :
docs [ fun ] = __utils__ [ fun ] . __doc__
return _strip_rst ( docs )
for module in args :
_use_fnmatch = False
if '*' in module :
target_mod = module
_use_fnmatch = True
elif module : # allow both " sys " and " sys . " to match... |
def load_config ( filename , config_dir = None , copy_default_config = True ) :
"""Loads the specified config file .
Parameters
filename : : obj : ` str `
Config file name , e . g . ' config _ grid . cfg ' .
config _ dir : : obj : ` str ` , optional
Path to config file . If None uses default edisgo config... | if not config_dir :
config_file = os . path . join ( get_default_config_path ( ) , filename )
else :
config_file = os . path . join ( config_dir , filename )
# config file does not exist - > copy default
if not os . path . isfile ( config_file ) :
if copy_default_config :
logger . in... |
def set_date_range ( self , start = None , end = None ) :
"""Update date range of stats , charts , etc . If None then
the original date range is used . So to reset to the original
range , just call with no args .
Args :
* start ( date ) : start date
* end ( end ) : end date""" | start = self . _start if start is None else pd . to_datetime ( start )
end = self . _end if end is None else pd . to_datetime ( end )
self . _update ( self . _prices . loc [ start : end ] ) |
def Hash ( self ) :
"""Get the hash of the transaction .
Returns :
UInt256:""" | if not self . __hash :
ba = bytearray ( binascii . unhexlify ( self . GetHashData ( ) ) )
hash = Crypto . Hash256 ( ba )
self . __hash = UInt256 ( data = hash )
return self . __hash |
def reset ( self ) :
"""Reset the instance
- reset rows and header""" | self . _hline_string = None
self . _row_size = None
self . _header = [ ]
self . _rows = [ ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.