signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def benchmark_multi ( optimizer ) :
"""Benchmark an optimizer configuration on multiple functions .""" | # Get our benchmark stats
all_stats = benchmark . compare ( optimizer , PROBLEMS , runs = 100 )
return benchmark . aggregate ( all_stats ) |
def _get_repos ( self ) :
"""Gets a list of all the installed repositories in this server .""" | result = { }
for xmlpath in self . installed :
repo = RepositorySettings ( self , xmlpath )
result [ repo . name . lower ( ) ] = repo
return result |
def _display_stream ( normalized_data , stream ) :
"""print stream message from docker - py stream .""" | try :
stream . write ( normalized_data [ 'stream' ] )
except UnicodeEncodeError :
stream . write ( normalized_data [ 'stream' ] . encode ( "utf-8" ) ) |
def random_transform ( self , sample , seed = None ) :
"""Randomly augment a single image tensor .
# Arguments
sample : 3D or 4D tensor , single sample .
seed : random seed .
# Returns
A randomly transformed version of the input ( same shape ) .""" | img_row_axis = self . row_axis - 1
img_col_axis = self . col_axis - 1
img_channel_axis = self . channel_axis - 1
transform_matrix = self . get_random_transform_matrix ( sample , seed )
if transform_matrix is not None :
h , w = sample . shape [ img_row_axis ] , sample . shape [ img_col_axis ]
transform_matrix = ... |
def get_forwarding_address ( destination_address , api_key , callback_url = None , coin_symbol = 'btc' ) :
"""Give a destination address and return an input address that will
automatically forward to the destination address . See
get _ forwarding _ address _ details if you also need the forwarding address ID . ... | assert api_key , 'api_key required'
resp_dict = get_forwarding_address_details ( destination_address = destination_address , api_key = api_key , callback_url = callback_url , coin_symbol = coin_symbol )
return resp_dict [ 'input_address' ] |
def handle_error ( self , message : str , e : mastodon . MastodonError ) -> OutputRecord :
"""Handle error while trying to do something .""" | self . lerror ( f"Got an error! {e}" )
# Handle errors if we know how .
try :
code = e [ 0 ] [ "code" ]
if code in self . handled_errors :
self . handled_errors [ code ]
else :
pass
except Exception :
pass
return TootRecord ( error = e ) |
def make_temp ( suffix = "" , prefix = "tmp" , dir = None ) :
"""Creates a temporary file with a closed stream and deletes it when done .
: return : A contextmanager retrieving the file path .""" | temporary = tempfile . mkstemp ( suffix = suffix , prefix = prefix , dir = dir )
os . close ( temporary [ 0 ] )
try :
yield temporary [ 1 ]
finally :
os . remove ( temporary [ 1 ] ) |
def verify_sns_subscription_current ( self , subscription_arn , topic_name , function_arn ) : # type : ( str , str , str ) - > bool
"""Verify a subscription arn matches the topic and function name .
Given a subscription arn , verify that the associated topic name
and function arn match up to the parameters pass... | sns_client = self . _client ( 'sns' )
try :
attributes = sns_client . get_subscription_attributes ( SubscriptionArn = subscription_arn ) [ 'Attributes' ]
return ( # Splitting on ' : ' is safe because topic names can ' t have
# a ' : ' char .
attributes [ 'TopicArn' ] . rsplit ( ':' , 1 ) [ 1 ] == topic_... |
def _points_within_distance ( self , pnt1 , pnt2 ) :
"""Returns true if lat / lon points are within given distance in metres .""" | if self . _get_distance ( pnt1 , pnt2 ) <= self . distance :
return True
return False |
def reflect_well ( value , bounds ) :
"""Given some boundaries , reflects the value until it falls within both
boundaries . This is done iteratively , reflecting left off of the
` boundaries . max ` , then right off of the ` boundaries . min ` , etc .
Parameters
value : float
The value to apply the reflec... | while value not in bounds :
value = bounds . _max . reflect_left ( value )
value = bounds . _min . reflect_right ( value )
return value |
def _handle_authn_response ( self , context , internal_response , idp ) :
"""See super class satosa . frontends . base . FrontendModule
: type context : satosa . context . Context
: type internal _ response : satosa . internal . InternalData
: type idp : saml . server . Server
: param context : The current ... | request_state = self . load_state ( context . state )
resp_args = request_state [ "resp_args" ]
sp_entity_id = resp_args [ "sp_entity_id" ]
internal_response . attributes = self . _filter_attributes ( idp , internal_response , context )
ava = self . converter . from_internal ( self . attribute_profile , internal_respon... |
def push_filters ( self , new_filters ) :
"""Add a filter to the tokenizer chain .""" | t = self . tokenizer
for f in new_filters :
t = f ( t )
self . tokenizer = t |
def set_xtick_suffix ( self , suffix ) :
"""Set the suffix for the ticks of the x - axis .
: param suffix : string added after each tick . If the value is
` degree ` or ` precent ` the corresponding symbols
will be added .""" | if suffix == 'degree' :
suffix = r'^\circ'
elif suffix == 'percent' :
suffix = r'\%'
self . ticks [ 'xsuffix' ] = suffix |
def parse_compound_file ( f , context = None ) :
"""Iterate over the compound entries in the given file""" | f . readline ( )
# Skip header
for lineno , row in enumerate ( csv . reader ( f , delimiter = '\t' ) ) :
compound_id , names , formula = row [ : 3 ]
names = ( decode_name ( name ) for name in names . split ( ',<br>' ) )
# ModelSEED sometimes uses an asterisk and number at
# the end of formulas . This se... |
def etype ( self ) -> Tuple [ str , str ] :
'''Returns the expression ' s type .''' | if self . _expr [ 0 ] in [ 'number' , 'boolean' ] :
return ( 'constant' , str ( type ( self . _expr [ 1 ] ) ) )
elif self . _expr [ 0 ] == 'pvar_expr' :
return ( 'pvar' , self . _expr [ 1 ] [ 0 ] )
elif self . _expr [ 0 ] == 'randomvar' :
return ( 'randomvar' , self . _expr [ 1 ] [ 0 ] )
elif self . _expr [... |
def cnn_model ( logits = False , input_ph = None , img_rows = 28 , img_cols = 28 , channels = 1 , nb_filters = 64 , nb_classes = 10 ) :
"""Defines a CNN model using Keras sequential model
: param logits : If set to False , returns a Keras model , otherwise will also
return logits tensor
: param input _ ph : T... | model = Sequential ( )
# Define the layers successively ( convolution layers are version dependent )
if tf . keras . backend . image_data_format ( ) == 'channels_first' :
input_shape = ( channels , img_rows , img_cols )
else :
assert tf . keras . backend . image_data_format ( ) == 'channels_last'
input_shap... |
def extract_isosurface ( pvol ) :
"""Extracts the largest isosurface from a volume .
The following example illustrates one of the usage scenarios :
. . code - block : : python
: linenos :
from geomdl import construct , multi
from geomdl . visualization import VisMPL
# Assuming that " myvol " variable st... | if pvol . pdimension != 3 :
raise GeomdlException ( "The input should be a spline volume" )
if len ( pvol ) != 1 :
raise GeomdlException ( "Can only operate on single spline volumes" )
# Extract surfaces from the parametric volume
isosrf = extract_surfaces ( pvol )
# Return the isosurface
return isosrf [ 'uv' ]... |
def build_ownership_map ( table , key_from_row , value_from_row ) :
"""Builds a dict mapping to lists of OwnershipPeriods , from a db table .""" | return _build_ownership_map_from_rows ( sa . select ( table . c ) . execute ( ) . fetchall ( ) , key_from_row , value_from_row , ) |
def compile_for_aexec ( source , filename = "<aexec>" , mode = "single" , dont_imply_dedent = False , local = { } ) :
"""Return a list of ( coroutine object , abstract base tree ) .""" | flags = ast . PyCF_ONLY_AST
if dont_imply_dedent :
flags |= codeop . PyCF_DONT_IMPLY_DEDENT
if compat . PY35 : # Avoid a syntax error by wrapping code with ` async def `
indented = '\n' . join ( line and ' ' * 4 + line for line in source . split ( '\n' ) )
coroutine = CORO_DEF + '\n' + indented + '\n'
i... |
def current_line ( self ) :
'''Get the text of the current source line as a string , with a trailing
newline character''' | if self . is_optimized_out ( ) :
return '(frame information optimized out)'
with open ( self . filename ( ) , 'r' ) as f :
all_lines = f . readlines ( )
# Convert from 1 - based current _ line _ num to 0 - based list offset :
return all_lines [ self . current_line_num ( ) - 1 ] |
def create_layout ( graph , graphviz_prog = DEFAULT_GRAPHVIZ_PROG ) :
"""Return { node : position } for given graph""" | graphviz_layout = graphutils . graphviz_layout ( graph , prog = graphviz_prog )
# print ( ' GRAPHIZ LAYOUT : ' , graphviz _ layout )
layout = { k : ( int ( x // 10 ) , int ( y // 10 ) ) for k , ( x , y ) in graphviz_layout . items ( ) }
# apply an offset for layouts to get all position > = 0
max_x = max ( layout . valu... |
def update_available_item_relationships ( app ) :
"""Update directive option _ spec with custom relationships defined in
configuration file ` ` traceability _ relationships ` ` variable . Both
keys ( relationships ) and values ( reverse relationships ) are added .
This handler should be called upon builder in... | env = app . builder . env
env . relationships = { }
for rel in list ( app . config . traceability_relationships . keys ( ) ) :
env . relationships [ rel ] = app . config . traceability_relationships [ rel ]
env . relationships [ app . config . traceability_relationships [ rel ] ] = rel
for rel in sorted ( list ... |
def zip_cluster ( data , k , init = None , max_iters = 100 ) :
"""Performs hard EM clustering using the zero - inflated Poisson distribution .
Args :
data ( array ) : A 2d array - genes x cells
k ( int ) : Number of clusters
init ( array , optional ) : Initial centers - genes x k array . Default : None , us... | genes , cells = data . shape
init , new_assignments = kmeans_pp ( data + eps , k , centers = init )
centers = np . copy ( init )
M = np . zeros ( centers . shape )
assignments = new_assignments
for c in range ( k ) :
centers [ : , c ] , M [ : , c ] = zip_fit_params_mle ( data [ : , assignments == c ] )
for it in ra... |
def _set_vlan_name ( self , v , load = False ) :
"""Setter method for vlan _ name , mapped from YANG variable / interface _ vlan / interface / vlan / vlan _ name ( string )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ vlan _ name is considered as a private
method .... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_dict = { 'length' : [ u'1 .. 32' ] } ) , is_leaf = True , yang_name = "vlan-name" , rest_name = "name" , parent = self , path_helper = self . _path_helper , extmethods =... |
def chat_post_message ( self , text , room_id = None , channel = None , ** kwargs ) :
"""Posts a new chat message .""" | if room_id :
return self . __call_api_post ( 'chat.postMessage' , roomId = room_id , text = text , kwargs = kwargs )
elif channel :
return self . __call_api_post ( 'chat.postMessage' , channel = channel , text = text , kwargs = kwargs )
else :
raise RocketMissingParamException ( 'roomId or channel required'... |
def export_default_instruments ( target_folder , source_folder = None , raise_errors = False , verbose = True ) :
"""tries to instantiate all the instruments that are imported in / instruments / _ _ init _ _ . py
and saves instruments that could be instantiate into a . b2 file in the folder path
Args :
target... | print ( 'export_def_instr called' )
instruments_to_load = get_classes_in_folder ( source_folder , Instrument , verbose = True )
print ( 'instruments to load:' )
print ( instruments_to_load )
if verbose :
print ( ( 'attempt to load {:d} instruments: ' . format ( len ( instruments_to_load ) ) ) )
loaded_instruments ,... |
def find ( fn , record ) :
"""Apply a function on the record and return the corresponding new record
: param fn : a function
: param record : a dictionary
: returns : a dictionary
> > > find ( max , { ' Terry ' : 30 , ' Graham ' : 35 , ' John ' : 27 } )
{ ' Graham ' : 35}""" | values_result = fn ( record . values ( ) )
keys_result = [ k for k , v in record . items ( ) if v == values_result ]
return { keys_result [ 0 ] : values_result } |
def watching ( w , watch , max_count = None , clear = True ) :
"""> > > len ( list ( watching ( True , 1 , 0 ) ) )
> > > len ( list ( watching ( True , 1 , 1 ) ) )
> > > len ( list ( watching ( True , None , 0 ) ) )""" | if w and not watch :
watch = 2
if watch and clear :
click . clear ( )
yield 0
if max_count is not None and max_count < 1 :
return
counter = 1
while watch and counter <= ( max_count or counter ) :
time . sleep ( watch )
counter += 1
if clear :
click . clear ( )
yield 0 |
def play ( events , speed_factor = 1.0 ) :
"""Plays a sequence of recorded events , maintaining the relative time
intervals . If speed _ factor is < = 0 then the actions are replayed as fast
as the OS allows . Pairs well with ` record ( ) ` .
Note : the current keyboard state is cleared at the beginning and r... | state = stash_state ( )
last_time = None
for event in events :
if speed_factor > 0 and last_time is not None :
_time . sleep ( ( event . time - last_time ) / speed_factor )
last_time = event . time
key = event . scan_code or event . name
press ( key ) if event . event_type == KEY_DOWN else relea... |
def setup_application ( self ) :
"""Allows us to use method , injected as dependency earlier to set
up argparser before autocompletion / running the app .""" | # figure out precise method name , specific to this use
name = 'configure_%s_app' % self . parent . name
# call generic set up method
getattr ( self . method , 'configure_app' , self . _no_op_setup ) ( self , self . parser )
# call specific set up method
getattr ( self . method , name , self . _no_op_setup ) ( self , s... |
def _parse_accented_syllable ( unparsed_syllable ) :
"""Return the syllable and tone of an accented Pinyin syllable .
Any accented vowels are returned without their accents .
Implements the following algorithm :
1 . If the syllable has an accent mark , convert that vowel to a
regular vowel and add the tone ... | if unparsed_syllable [ 0 ] == '\u00B7' : # Special case for middle dot tone mark .
return unparsed_syllable [ 1 : ] , '5'
for character in unparsed_syllable :
if character in _ACCENTED_VOWELS :
vowel , tone = _accented_vowel_to_numbered ( character )
return unparsed_syllable . replace ( characte... |
def _set_redistribute_bgp ( self , v , load = False ) :
"""Setter method for redistribute _ bgp , mapped from YANG variable / rbridge _ id / ipv6 / router / ospf / redistribute / redistribute _ bgp ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ redistribu... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = redistribute_bgp . redistribute_bgp , is_container = 'container' , presence = True , yang_name = "redistribute-bgp" , rest_name = "bgp" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , r... |
def extract ( self , obj , bypass_ref = False ) :
"""Extract subelement from obj , according to current token .
: param obj : the object source
: param bypass _ ref : disable JSON Reference errors""" | try :
if isinstance ( obj , Mapping ) :
if not bypass_ref and '$ref' in obj :
raise RefError ( obj , 'presence of a $ref member' )
obj = self . extract_mapping ( obj )
elif isinstance ( obj , Sequence ) and not isinstance ( obj , string_types ) :
obj = self . extract_sequence... |
def _cs_disassemble_one ( self , data , address ) :
"""Disassemble the data into an instruction in string form .""" | disasm = list ( self . _disassembler . disasm ( bytes ( data ) , address ) )
# TODO : Improve this check .
if len ( disasm ) > 0 :
return disasm [ 0 ]
else :
cs_arm = Cs ( CS_ARCH_ARM , CS_MODE_ARM )
cs_arm . detail = True
disasm = list ( cs_arm . disasm ( bytes ( data ) , address ) )
if len ( disas... |
def expr2truthtable ( expr ) :
"""Convert an expression into a truth table .""" | inputs = [ ttvar ( v . names , v . indices ) for v in expr . inputs ]
return truthtable ( inputs , expr . iter_image ( ) ) |
def solve_dp ( self , lam ) :
'''Solves the Graph - fused double Pareto ( non - convex , local optima only )''' | cur_converge = self . converge + 1
step = 0
# Get an initial estimate using the GFL
self . solve_gfl ( lam )
beta2 = np . copy ( self . beta )
while cur_converge > self . converge and step < self . max_dp_steps : # Weight each edge differently
u = lam / ( 1 + np . abs ( self . beta [ self . trails [ : : 2 ] ] - sel... |
def maturity_date ( self , value ) :
"""The date on which the asset matures and no longer holds value
: param value :
: return :""" | self . _maturity_date = parse ( value ) . date ( ) if isinstance ( value , type_check ) else value |
def authenticate ( user = None ) : # noqa : E501
"""Authenticate
Authenticate with the API # noqa : E501
: param user : The user authentication object .
: type user : dict | bytes
: rtype : AuthResponse""" | if connexion . request . is_json :
user = UserAuth . from_dict ( connexion . request . get_json ( ) )
# noqa : E501
return 'do some magic!' |
def setup_structure ( self , structure ) :
"""Sets up the structure for which the coordination geometries have to be identified . The structure is analyzed
with the space group analyzer and a refined structure is used
: param structure : A pymatgen Structure
: param""" | self . initial_structure = structure . copy ( )
if self . structure_refinement == self . STRUCTURE_REFINEMENT_NONE :
self . structure = structure . copy ( )
self . spg_analyzer = None
self . symmetrized_structure = None
else :
self . spg_analyzer = SpacegroupAnalyzer ( self . initial_structure , symprec... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'folders' ) and self . folders is not None :
_dict [ 'folders' ] = [ x . _to_dict ( ) for x in self . folders ]
if hasattr ( self , 'objects' ) and self . objects is not None :
_dict [ 'objects' ] = [ x . _to_dict ( ) for x in self . objects ]
if hasattr ( self , 'site_collection... |
def urljoin ( end_with_slash , * args ) :
"""> > > HelperURI . urljoin ( False , * ( ' http : / / 127.0.0.1:8000 ' , ' dumb _ upload ' ) )
' http : / / 127.0.0.1:8000 / dumb _ upload '
> > > HelperURI . urljoin ( True , * ( ' http : / / 127.0.0.1:8000 ' , ' dumb _ upload ' ) )
' http : / / 127.0.0.1:8000 / du... | last = args [ 0 ]
for i in args [ 1 : ] :
last = '%s/%s' % ( last . strip ( '/' ) , i . strip ( '/' ) )
if end_with_slash :
if last [ - 1 ] != '/' :
last += '/'
return last |
def Squeeze ( a , squeeze_dims ) :
"""Squeeze op , i . e . removes singular axes .""" | if not squeeze_dims :
squeeze_dims = list ( range ( len ( a . shape ) ) )
slices = [ ( 0 if ( dim == 1 and i in squeeze_dims ) else slice ( None ) ) for i , dim in enumerate ( a . shape ) ]
return np . copy ( a ) [ slices ] , |
def indent ( self , node , dirty = True ) :
"""Indent an item . Does nothing if the target has subitems .
Args :
node ( gkeepapi . node . ListItem ) : Item to indent .
dirty ( bool ) : Whether this node should be marked dirty .""" | if node . subitems :
return
self . _subitems [ node . id ] = node
node . super_list_item_id = self . id
node . parent_item = self
if dirty :
node . touch ( True ) |
def iter_tags ( self , number = - 1 , etag = None ) :
"""Iterates over tags on this repository .
: param int number : ( optional ) , return up to at most number tags .
Default : - 1 returns all available tags .
: param str etag : ( optional ) , ETag from a previous request to the same
endpoint
: returns :... | url = self . _build_url ( 'tags' , base_url = self . _api )
return self . _iter ( int ( number ) , url , RepoTag , etag = etag ) |
def import_attr ( path ) :
"""Given a a Python dotted path to a variable in a module ,
imports the module and returns the variable in it .""" | module_path , attr_name = path . rsplit ( "." , 1 )
return getattr ( import_module ( module_path ) , attr_name ) |
def close ( self ) :
"""Close the document controller .
This method must be called to shut down the document controller . There are several
paths by which it can be called , though .
* User quits application via menu item . The menu item will call back to Application . exit which will close each
document co... | assert self . __closed == False
self . __closed = True
self . finish_periodic ( )
# required to finish periodic operations during tests
# dialogs
for weak_dialog in self . __dialogs :
dialog = weak_dialog ( )
if dialog :
try :
dialog . request_close ( )
except Exception as e :
... |
def get_data ( self ) :
"""attempt to read measurements file in working directory .""" | meas_file = os . path . join ( self . WD , 'magic_measurements.txt' )
if not os . path . isfile ( meas_file ) :
print ( "-I- No magic_measurements.txt file" )
return { }
try :
meas_data , file_type = pmag . magic_read ( meas_file )
except IOError :
print ( "-I- No magic_measurements.txt file" )
retu... |
def enzyme ( ) :
"""Returns list of Enzyme Commission numbers by query paramaters
tags :
- Query functions
parameters :
- name : ec _ number
in : query
type : string
required : false
description : ' Enzyme Commission number '
default : ' 1.1.1.1'
- name : hgnc _ symbol
in : query
type : stri... | allowed_str_args = [ 'hgnc_symbol' , 'ec_number' ]
allowed_int_args = [ 'limit' , 'hgnc_identifier' ]
args = get_args ( request_args = request . args , allowed_int_args = allowed_int_args , allowed_str_args = allowed_str_args )
return jsonify ( query . enzyme ( ** args ) ) |
def get_target_n ( self ) :
'''getter''' | if isinstance ( self . __target_n , int ) is False :
raise TypeError ( "The type of __target_n must be int." )
return self . __target_n |
def sweHousesLon ( jd , lat , lon , hsys ) :
"""Returns lists with house and angle longitudes .""" | hsys = SWE_HOUSESYS [ hsys ]
hlist , ascmc = swisseph . houses ( jd , lat , lon , hsys )
angles = [ ascmc [ 0 ] , ascmc [ 1 ] , angle . norm ( ascmc [ 0 ] + 180 ) , angle . norm ( ascmc [ 1 ] + 180 ) ]
return ( hlist , angles ) |
def generated_tag_data ( tags ) :
"""Convert : obj : ` dict ` to S3 Tag list .
Args :
tags ( dict ) : Dictonary of tag key and tag value passed .
Returns :
list : List of dictionaries .""" | generated_tags = [ ]
for key , value in tags . items ( ) :
generated_tags . append ( { 'Key' : key , 'Value' : value , } )
return generated_tags |
def create ( cls , entry ) :
"""Factory that creates an bot config from an entry in INSTALLED _ APPS .""" | # trading _ bots . example . bot . ExampleBot
try : # If import _ module succeeds , entry is a path to a bot module ,
# which may specify a bot class with a default _ bot attribute .
# Otherwise , entry is a path to a bot class or an error .
module = import_module ( entry )
except ImportError : # Track that importi... |
def parseGithubImportPath ( self , path ) :
"""Definition : github . com / < project > / < repo >""" | parts = path . split ( "/" )
if len ( parts ) < 3 :
raise ValueError ( "Import path %s not in github.com/<project>/<repo> form" % path )
repo = { }
repo [ "prefix" ] = "/" . join ( parts [ : 3 ] )
repo [ "signature" ] = { "provider" : "github" , "username" : parts [ 1 ] , "project" : parts [ 2 ] }
return repo |
def parse_qsl ( qs , keep_blank_values = False , strict_parsing = False , encoding = 'utf-8' , errors = 'replace' ) :
"""Parse a query given as a string argument .
Arguments :
qs : percent - encoded query string to be parsed
keep _ blank _ values : flag indicating whether blank values in
percent - encoded q... | qs , _coerce_result = _coerce_args ( qs )
pairs = [ s2 for s1 in qs . split ( '&' ) for s2 in s1 . split ( ';' ) ]
r = [ ]
for name_value in pairs :
if not name_value and not strict_parsing :
continue
nv = name_value . split ( '=' , 1 )
if len ( nv ) != 2 :
if strict_parsing :
ra... |
def _fake_references ( self , namespace , ** params ) :
"""Implements a mock WBEM server responder for
: meth : ` ~ pywbem . WBEMConnection . References `""" | rc = None if params [ 'ResultClass' ] is None else params [ 'ResultClass' ] . classname
role = params [ 'Role' ]
obj_name = params [ 'ObjectName' ]
classname = obj_name . classname
pl = params [ 'PropertyList' ]
ico = params [ 'IncludeClassOrigin' ]
iq = params [ 'IncludeQualifiers' ]
if isinstance ( obj_name , CIMClas... |
def makeUnicodeMapFromSources ( self ) :
"""Create a dict with glyphName - > unicode value pairs
using the data in the sources .
If all master glyphs have the same unicode value
this value will be used in the map .
If master glyphs have conflicting value , a warning will be printed , no value will be used .... | values = { }
for locationName , ( source , loc ) in self . sources . items ( ) : # this will be expensive in large fonts
for glyph in source :
if glyph . unicodes is not None :
if glyph . name not in values :
values [ glyph . name ] = { }
for u in glyph . unicodes :
... |
def execute_sql ( self , sql , params = None , param_types = None , query_mode = None , partition = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , ) :
"""Perform an ` ` ExecuteStreamingSql ` ` API request .
: type sql : str
: param sq... | if self . _read_request_count > 0 :
if not self . _multi_use :
raise ValueError ( "Cannot re-use single-use snapshot." )
if self . _transaction_id is None :
raise ValueError ( "Transaction ID pending." )
if params is not None :
if param_types is None :
raise ValueError ( "Specify 'pa... |
def check_list_type ( objects , allowed_type , name , allow_none = True ) :
"""Verify that objects in list are of the allowed type or raise TypeError .
Args :
objects : The list of objects to check .
allowed _ type : The allowed type of items in ' settings ' .
name : Name of the list of objects , added to t... | if objects is None :
if not allow_none :
raise TypeError ( '%s is None, which is not allowed.' % name )
return objects
if not isinstance ( objects , ( tuple , list ) ) :
raise TypeError ( '%s is not a list.' % name )
if not all ( isinstance ( i , allowed_type ) for i in objects ) :
type_list = s... |
def get_contact_formatted_email ( self , contact ) :
"""Returns a string with the formatted email for the given contact""" | contact_name = contact . Title ( )
contact_email = contact . getEmailAddress ( )
return self . get_formatted_email ( ( contact_name , contact_email ) ) |
def parse_cdhit_clstr_file ( lines ) :
"""Returns a list of list of sequence ids representing clusters""" | clusters = [ ]
curr_cluster = [ ]
for l in lines :
if l . startswith ( '>Cluster' ) :
if not curr_cluster :
continue
clusters . append ( curr_cluster )
curr_cluster = [ ]
else :
curr_cluster . append ( clean_cluster_seq_id ( l . split ( ) [ 2 ] ) )
if curr_cluster :
... |
def read_csv ( fname ) :
"""Read a csv file into a DataAccessObject
: param fname : filename""" | values = defaultdict ( list )
with open ( fname ) as f :
reader = csv . DictReader ( f )
for row in reader :
for ( k , v ) in row . items ( ) :
values [ k ] . append ( v )
npvalues = { k : np . array ( values [ k ] ) for k in values . keys ( ) }
for k in npvalues . keys ( ) :
for datatyp... |
def polygon_from_points ( points ) :
"""Constructs a numpy - compatible polygon from a page representation .""" | polygon = [ ]
for pair in points . split ( " " ) :
x_y = pair . split ( "," )
polygon . append ( [ float ( x_y [ 0 ] ) , float ( x_y [ 1 ] ) ] )
return polygon |
def _generate_question ( self ) :
"""Generate a random arithmetic question
This method randomly generates a simple addition , subtraction , or
multiplication question with two integers between 1 and 10 , and then
returns both question ( formatted as a string ) and answer .""" | x = random . randint ( 1 , 10 )
y = random . randint ( 1 , 10 )
operator = random . choice ( ( '+' , '-' , '*' , ) )
if operator == '+' :
answer = x + y
elif operator == '-' : # Ensure we ' ll get a non - negative answer
if x < y :
x , y = y , x
answer = x - y
else : # Multiplication is hard , make ... |
def query_columns ( conn , query , name = None ) :
"""Lightweight query to retrieve column list of select query .
Notes
Strongly urged to specify a cursor name for performance .""" | with conn . cursor ( name ) as cursor :
cursor . itersize = 1
cursor . execute ( query )
cursor . fetchmany ( 0 )
column_names = [ column . name for column in cursor . description ]
return column_names |
def main_group ( ctx , verbose , quiet , access_token , config ) :
"""This is the command line interface to Mapbox web services .
Mapbox web services require an access token . Your token is shown
on the https : / / www . mapbox . com / studio / account / tokens / page when you are
logged in . The token can be... | ctx . obj = { }
config = config or os . path . join ( click . get_app_dir ( 'mapbox' ) , 'mapbox.ini' )
cfg = read_config ( config )
if cfg :
ctx . obj [ 'config_file' ] = config
ctx . obj [ 'cfg' ] = cfg
ctx . default_map = cfg
verbosity = ( os . environ . get ( 'MAPBOX_VERBOSE' ) or ctx . lookup_default ( 'mapbox... |
def configurar_interface_de_rede ( self , configuracao ) :
"""Sobrepõe : meth : ` ~ satcfe . base . FuncoesSAT . configurar _ interface _ de _ rede ` .
: return : Uma resposta SAT padrão .
: rtype : satcfe . resposta . padrao . RespostaSAT""" | resp = self . _http_post ( 'configurarinterfacederede' , configuracao = configuracao . documento ( ) )
conteudo = resp . json ( )
return RespostaSAT . configurar_interface_de_rede ( conteudo . get ( 'retorno' ) ) |
def run ( command , products = None , working_directory = '.' , force_local = False , stderr = True , quiet = False ) :
'''wrapper to run external programs
: command : list containing command and parameters
( formatted the same as subprocess ; must contain only strings )
: products : string or list of files t... | with run_in ( working_directory ) :
if products :
if isinstance ( products , basestring ) :
products = [ products ]
if all ( [ os . path . exists ( x ) for x in products ] ) :
return False
command = flatten ( command )
command = [ str ( x ) for x in command ]
quie... |
def _get_token ( self , request , refresh_token = False ) :
"""Extract a token from a request object .""" | if self . config . cookie_set ( ) :
token = self . _get_token_from_cookies ( request , refresh_token )
if token :
return token
else :
if self . config . cookie_strict ( ) :
raise exceptions . MissingAuthorizationCookie ( )
if self . config . query_string_set ( ) :
token = sel... |
def move_item_down ( self , item ) :
"""Move an item down in the list .
Essentially swap it with the item below it .
: param item : The item to be moved .""" | next_iter = self . _next_iter_for ( item )
if next_iter is not None :
self . model . swap ( self . _iter_for ( item ) , next_iter ) |
def pwm ( host , seq , m1 , m2 , m3 , m4 ) :
"""Sends control values directly to the engines , overriding control loops .
Parameters :
seq - - sequence number
m1 - - Integer : front left command
m2 - - Integer : front right command
m3 - - Integer : back right command
m4 - - Integer : back left command""... | at ( host , 'PWM' , seq , [ m1 , m2 , m3 , m4 ] ) |
def runCommands ( self , commands , args ) :
"""Given a list of commands , runCommands executes them .
This is one of the two key methods of MapExecutor .""" | errorCounter = 0
if args . list :
print '\n' . join ( commands )
else : # Each command is executed sequentially :
for command in commands :
process = subprocess . Popen ( command , stdout = subprocess . PIPE , stderr = subprocess . PIPE , shell = True )
stream = process . communicate ( )
... |
def consulta ( self , endereco , primeiro = False , uf = None , localidade = None , tipo = None , numero = None ) :
"""Consulta site e retorna lista de resultados""" | if uf is None :
url = 'consultaEnderecoAction.do'
data = { 'relaxation' : endereco . encode ( 'ISO-8859-1' ) , 'TipoCep' : 'ALL' , 'semelhante' : 'N' , 'cfm' : 1 , 'Metodo' : 'listaLogradouro' , 'TipoConsulta' : 'relaxation' , 'StartRow' : '1' , 'EndRow' : '10' }
else :
url = 'consultaLogradouroAction.do'
... |
def jtag_send ( self , tms , tdi , num_bits ) :
"""Sends data via JTAG .
Sends data via JTAG on the rising clock edge , TCK . At on each rising
clock edge , on bit is transferred in from TDI and out to TDO . The
clock uses the TMS to step through the standard JTAG state machine .
Args :
self ( JLink ) : t... | if not util . is_natural ( num_bits ) or num_bits <= 0 or num_bits > 32 :
raise ValueError ( 'Number of bits must be >= 1 and <= 32.' )
self . _dll . JLINKARM_StoreBits ( tms , tdi , num_bits )
return None |
def get_port_profile_status_input_port_profile_status ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_port_profile_status = ET . Element ( "get_port_profile_status" )
config = get_port_profile_status
input = ET . SubElement ( get_port_profile_status , "input" )
port_profile_status = ET . SubElement ( input , "port-profile-status" )
port_profile_status . text = kwargs . pop ( 'port... |
def _final_data ( self ) :
"""Returns
A list of tuples representing rows from the datatable ' s index
and final column , sorted accordingly .""" | dtbl = self . datatable
objs = object_session ( self )
if isinstance ( dtbl , Table ) :
return objs . query ( dtbl . c . indx , dtbl . c . final ) . all ( )
else :
raise Exception ( "Symbol has no datatable, likely need to cache first." ) |
def save_card ( self , card , cache = False ) :
"""Save the given card to the database . This calls each save event hook
on the save string before commiting it to the database .""" | if cache :
self . cache_card ( card )
carddict = card . save ( )
with sqlite3 . connect ( self . dbname ) as carddb :
carddb . execute ( "DELETE from CARDS where code = ?" , ( carddict [ "code" ] , ) )
carddb . execute ( "INSERT INTO CARDS VALUES(?, ?, ?, ?, ?)" , [ carddict [ key ] if isinstance ( carddict... |
def get_params ( self ) :
"""Get parameters .
: return : enabled , size , chunk _ delay , start _ delay""" | return self . enabled , self . size , self . chunk_delay , self . start_delay |
def act ( self ) :
"""Carries out the action associated with Stop button""" | g = get_root ( self ) . globals
g . clog . debug ( 'Stop pressed' )
# Stop exposure meter
# do this first , so timer doesn ' t also try to enable idle mode
g . info . timer . stop ( )
def stop_in_background ( ) :
try :
self . stopping = True
if execCommand ( g , 'abort' ) :
self . stoppe... |
def function ( self , x , y , Rs , theta_Rs , e1 , e2 , center_x = 0 , center_y = 0 ) :
"""returns double integral of NFW profile""" | phi_G , q = param_util . ellipticity2phi_q ( e1 , e2 )
x_shift = x - center_x
y_shift = y - center_y
cos_phi = np . cos ( phi_G )
sin_phi = np . sin ( phi_G )
e = min ( abs ( 1. - q ) , 0.99 )
xt1 = ( cos_phi * x_shift + sin_phi * y_shift ) * np . sqrt ( 1 - e )
xt2 = ( - sin_phi * x_shift + cos_phi * y_shift ) * np . ... |
def add_register_user ( self , username , first_name , last_name , email , password = "" , hashed_password = "" ) :
"""Add a registration request for the user .
: rtype : RegisterUser""" | register_user = self . registeruser_model ( )
register_user . username = username
register_user . email = email
register_user . first_name = first_name
register_user . last_name = last_name
if hashed_password :
register_user . password = hashed_password
else :
register_user . password = generate_password_hash (... |
def tis2hw ( size : Union [ int , TensorImageSize ] ) -> Tuple [ int , int ] :
"Convert ` int ` or ` TensorImageSize ` to ( height , width ) of an image ." | if type ( size ) is str :
raise RuntimeError ( "Expected size to be an int or a tuple, got a string." )
return listify ( size , 2 ) if isinstance ( size , int ) else listify ( size [ - 2 : ] , 2 ) |
def resolve_link ( self , snow_record , field_to_resolve , ** kparams ) :
"""Get the info from the link and return a SnowRecord .""" | try :
link = snow_record . links ( ) [ field_to_resolve ]
except KeyError as e :
return SnowRecord . NotFound ( self , snow_record . _table_name , "Could not find field %s in record" % field_to_resolve , [ snow_record , field_to_resolve , self ] )
if kparams :
link += ( '&' , '?' ) [ urlparse ( link ) . que... |
def mirror ( self , axes = 'x' ) :
"""Generates a symmetry of the Polyhedron respect global axes .
: param axes : ' x ' , ' y ' , ' z ' , ' xy ' , ' xz ' , ' yz ' . . .
: type axes : str
: returns : ` ` pyny . Polyhedron ` `""" | polygon = np . array ( [ [ 0 , 0 ] , [ 0 , 1 ] , [ 1 , 1 ] ] )
space = Space ( Place ( polygon , polyhedra = self ) )
return space . mirror ( axes , inplace = False ) [ 0 ] . polyhedra [ 0 ] |
def get_user_identity ( cls , instance_config ) :
"""Parse user identity out of init _ config
To guarantee a uniquely identifiable user , expects
{ " user " : { " name " : " my _ username " , " password " : " my _ password " ,
" domain " : { " id " : " my _ domain _ id " }""" | user = instance_config . get ( 'user' )
if not ( user and user . get ( 'name' ) and user . get ( 'password' ) and user . get ( "domain" ) and user . get ( "domain" ) . get ( "id" ) ) :
raise IncompleteIdentity ( )
identity = { "methods" : [ 'password' ] , "password" : { "user" : user } }
return identity |
def _prtstr ( self , obj , dashes ) :
"""Print object information using a namedtuple and a format pattern .""" | self . prt . write ( '{DASHES:{N}}' . format ( DASHES = self . fmt_dashes . format ( DASHES = dashes , ID = obj . item_id ) , N = self . dash_len ) )
self . prt . write ( "{INFO}\n" . format ( INFO = str ( obj ) ) ) |
def revert ( self , strip = 0 , root = None ) :
"""apply patch in reverse order""" | reverted = copy . deepcopy ( self )
reverted . _reverse ( )
return reverted . apply ( strip , root ) |
def iodp_samples ( samp_file , output_samp_file = None , output_dir_path = '.' , input_dir_path = '' , data_model_num = 3 ) :
"""Convert IODP samples data file into MagIC samples file .
Default is to overwrite samples . txt in your working directory .
Parameters
samp _ file : str
path to IODP sample file to... | samp_file_name = "samples.txt"
sample_alternatives = "sample_alternatives"
method_codes = "method_codes"
sample_name = "sample"
site_name = "site"
expedition_name = "expedition_name"
location_name = "location"
citation_name = "citation"
dip = "dip"
azimuth = "azimuth"
core_depth = "core_depth"
composite_depth = "compos... |
def _getLocalWhen ( self , date_from , date_to = None ) :
"""Returns a string describing when the event occurs ( in the local time zone ) .""" | dateFrom , timeFrom = getLocalDateAndTime ( date_from , self . time_from , self . tz , dt . time . min )
if date_to is not None :
dateTo , timeTo = getLocalDateAndTime ( date_to , self . time_to , self . tz )
else :
if self . time_to is not None :
dateTo , timeTo = getLocalDateAndTime ( date_from , self... |
def keywords ( self ) :
"""Distinct keywords ( ` ` name ` ` in : class : ` . models . Keyword ` )
: returns : all distinct keywords
: rtype : list [ str ]""" | return [ x [ 0 ] for x in self . session . query ( models . Keyword . name ) . all ( ) ] |
def style ( self ) :
"""Returns a default Style .""" | style = mapnik . Style ( )
rule = mapnik . Rule ( )
self . _symbolizer = self . symbolizer ( )
rule . symbols . append ( self . _symbolizer )
style . rules . append ( rule )
return style |
def get ( self , action , params = None , headers = None ) :
"""Makes a GET request""" | return self . request ( make_url ( self . endpoint , action ) , method = 'GET' , data = params , headers = headers ) |
def getMetadata ( L ) :
"""Get metadata from a LiPD data in memory
| Example
| m = lipd . getMetadata ( D [ " Africa - ColdAirCave . Sundqvist . 2013 " ] )
: param dict L : One LiPD record
: return dict d : LiPD record ( metadata only )""" | _l = { }
try : # Create a copy . Do not affect the original data .
_l = copy . deepcopy ( L )
# Remove values fields
_l = rm_values_fields ( _l )
except Exception as e : # Input likely not formatted correctly , though other problems can occur .
print ( "Error: Unable to get data. Please check that input... |
def show_top_losses ( self , k : int , max_len : int = 70 ) -> None :
"""Create a tabulation showing the first ` k ` texts in top _ losses along with their prediction , actual , loss , and probability of
actual class . ` max _ len ` is the maximum number of tokens displayed .""" | from IPython . display import display , HTML
items = [ ]
tl_val , tl_idx = self . top_losses ( )
for i , idx in enumerate ( tl_idx ) :
if k <= 0 :
break
k -= 1
tx , cl = self . data . dl ( self . ds_type ) . dataset [ idx ]
cl = cl . data
classes = self . data . classes
txt = ' ' . join ... |
def connect ( self ) :
"""Connects to RabbitMQ and starts listening""" | logger . info ( "Connecting to RabbitMQ on {broker_url}..." . format ( broker_url = self . broker_url ) )
super ( RabbitMQSubscriber , self ) . connect ( )
q = Queue ( exchange = self . exchange , exclusive = True , durable = False )
self . queue = q ( self . connection . default_channel )
self . queue . declare ( )
se... |
def plot_annotation ( ann_samp , n_annot , ann_sym , signal , n_sig , fs , time_units , ann_style , axes ) :
"Plot annotations , possibly overlaid on signals" | # Extend annotation style if necesary
if len ( ann_style ) == 1 :
ann_style = n_annot * ann_style
# Figure out downsample factor for time indices
if time_units == 'samples' :
downsample_factor = 1
else :
downsample_factor = { 'seconds' : float ( fs ) , 'minutes' : float ( fs ) * 60 , 'hours' : float ( fs ) ... |
def do_json_valid ( self , params ) :
"""\x1b [1mNAME \x1b [0m
json _ valid - Checks znodes for valid JSON
\x1b [1mSYNOPSIS \x1b [0m
json _ valid < path > [ recursive ]
\x1b [1mOPTIONS \x1b [0m
* recursive : recurse to all children ( default : false )
\x1b [1mEXAMPLES \x1b [0m
> json _ valid / some / ... | def check_valid ( path , print_path ) :
result = "no"
value , _ = self . _zk . get ( path )
if value is not None :
try :
x = json . loads ( value )
result = "yes"
except ValueError :
pass
if print_path :
self . show_output ( "%s: %s." , os . pa... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : WebhookContext for this WebhookInstance
: rtype : twilio . rest . messaging . v1 . session . webhook . WebhookContext""" | if self . _context is None :
self . _context = WebhookContext ( self . _version , session_sid = self . _solution [ 'session_sid' ] , sid = self . _solution [ 'sid' ] , )
return self . _context |
def parse_arguments ( filters , arguments , modern = False ) :
"""Return a dict of parameters .
Take a list of filters and for each try to get the corresponding
value in arguments or a default value . Then check that value ' s type .
The @ modern parameter indicates how the arguments should be
interpreted .... | params = DotDict ( )
for i in filters :
count = len ( i )
param = None
if count <= 1 :
param = arguments . get ( i [ 0 ] )
else :
param = arguments . get ( i [ 0 ] , i [ 1 ] )
# proceed and do the type checking
if count >= 3 :
types = i [ 2 ]
if modern :
... |
def query ( self , s = None , p = None , o = None ) :
"""Return all triples that satisfy the given expression . You may specify
all or none of the fields ( s , p , and o ) . For instance , if I wanted
to query for all the people who live in Kansas , I might write :
. . code - block : : python
for triple in ... | start , end = self . keys_for_query ( s , p , o )
if end is None :
if start in self . _z :
yield { 's' : s , 'p' : p , 'o' : o }
else :
raise StopIteration
else :
for key in self . _z . range_by_lex ( '[' + start , '[' + end ) :
keys , p1 , p2 , p3 = decode ( key ) . split ( '::' )
... |
def RelaxNGValidate ( self , rng ) :
"""Use RelaxNG schema to validate the document as it is
processed . Activation is only possible before the first
Read ( ) . If @ rng is None , then RelaxNG schema validation is
deactivated .""" | ret = libxml2mod . xmlTextReaderRelaxNGValidate ( self . _o , rng )
return ret |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.