signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def debug_btn_clicked ( self , widget , data = None ) :
"""Event in case that debug button is pressed .""" | self . store . clear ( )
self . thread = threading . Thread ( target = self . logs_update )
self . thread . start ( ) |
def add_dynamic_kb ( kbname , tag , collection = "" , searchwith = "" ) :
"""A convenience method .""" | kb_id = add_kb ( kb_name = kbname , kb_type = 'dynamic' )
save_kb_dyn_config ( kb_id , tag , searchwith , collection )
return kb_id |
def send_media_group ( self , chat_id , media , disable_notification = None , reply_to_message_id = None ) :
"""Use this method to send a group of photos or videos as an album . On success , an array of the sent Messages is returned .
https : / / core . telegram . org / bots / api # sendmediagroup
Parameters : ... | from pytgbot . api_types . sendable . input_media import InputMediaPhoto
from pytgbot . api_types . sendable . input_media import InputMediaVideo
assert_type_or_raise ( chat_id , ( int , unicode_type ) , parameter_name = "chat_id" )
assert_type_or_raise ( media , ( list , list ) , parameter_name = "media" )
assert_type... |
def context_info ( zap_helper , context_name ) :
"""Get info about the given context .""" | with zap_error_handler ( ) :
info = zap_helper . get_context_info ( context_name )
console . info ( 'ID: {}' . format ( info [ 'id' ] ) )
console . info ( 'Name: {}' . format ( info [ 'name' ] ) )
console . info ( 'Authentication type: {}' . format ( info [ 'authType' ] ) )
console . info ( 'Included regexes: {}' .... |
def createvaluesdict ( self ) :
"""function processes the / proc / cpuinfo file , use file = / sys to use kernel > = 4.13 location
: return : dictionary used as the full - text output for the module""" | cpus_offline = 0
if self . file == '/sys' :
with open ( '/sys/devices/system/cpu/online' ) as f :
line = f . readline ( )
cpus_online = [ int ( cpu ) for cpu in line . split ( ',' ) if cpu . find ( '-' ) < 0 ]
cpus_online_range = [ cpu_range for cpu_range in line . split ( ',' ) if cpu_range... |
def delimit_words ( string : str ) -> Generator [ str , None , None ] :
"""Delimit a string at word boundaries .
> > > import uqbar . strings
> > > list ( uqbar . strings . delimit _ words ( " i want to believe " ) )
[ ' i ' , ' want ' , ' to ' , ' believe ' ]
> > > list ( uqbar . strings . delimit _ words ... | # TODO : Reimplement this
wordlike_characters = ( "<" , ">" , "!" )
current_word = ""
for i , character in enumerate ( string ) :
if ( not character . isalpha ( ) and not character . isdigit ( ) and character not in wordlike_characters ) :
if current_word :
yield current_word
current... |
def getDocFactory ( self , fragmentName , default = None ) :
"""For a given fragment , return a loaded Nevow template .
@ param fragmentName : the name of the template ( can include relative
paths ) .
@ param default : a default loader ; only used if provided and the
given fragment name cannot be resolved .... | if fragmentName in self . cachedLoaders :
return self . cachedLoaders [ fragmentName ]
segments = fragmentName . split ( '/' )
segments [ - 1 ] += '.html'
file = self . directory
for segment in segments :
file = file . child ( segment )
if file . exists ( ) :
loader = xmlfile ( file . path )
self . cach... |
def import_all_modules ( package , skip = None , verbose = False , prefix = "" , depth = 0 ) :
"""Recursively imports all subpackages , modules , and submodules of a
given package .
' package ' should be an imported package , not a string .
' skip ' is a list of modules or subpackages not to import .""" | skip = [ ] if skip is None else skip
for ff , modname , ispkg in pkgutil . walk_packages ( path = package . __path__ , prefix = prefix , onerror = lambda x : None ) :
if ff . path not in package . __path__ [ 0 ] : # Solves weird bug
continue
if verbose :
print ( '\t' * depth , modname )
if m... |
def show_prediction ( self , ** kwargs ) :
"""Call : func : ` eli5 . show _ prediction ` for the locally - fit
classification pipeline . Keyword arguments are passed
to : func : ` eli5 . show _ prediction ` .
: func : ` fit ` must be called before using this method .""" | self . _fix_target_names ( kwargs )
return eli5 . show_prediction ( self . clf_ , self . doc_ , vec = self . vec_ , ** kwargs ) |
def childAtPath ( self , path ) :
"""Get a child at I { path } where I { path } is a ( / ) separated
list of element names that are expected to be children .
@ param path : A ( / ) separated list of element names .
@ type path : basestring
@ return : The leaf node at the end of I { path }
@ rtype : L { El... | if self . __root is None :
return None
if path [ 0 ] == '/' :
path = path [ 1 : ]
path = path . split ( '/' , 1 )
if self . getChild ( path [ 0 ] ) is None :
return None
if len ( path ) > 1 :
return self . __root . childAtPath ( path [ 1 ] )
else :
return self . __root |
def filter_edges ( graph : BELGraph , edge_predicates : EdgePredicates ) -> EdgeIterator :
"""Apply a set of filters to the edges iterator of a BEL graph .
: return : An iterable of edges that pass all predicates""" | compound_edge_predicate = and_edge_predicates ( edge_predicates = edge_predicates )
for u , v , k in graph . edges ( keys = True ) :
if compound_edge_predicate ( graph , u , v , k ) :
yield u , v , k |
def dump_json_body ( handler ) :
"""Automatically serialize response bodies with json . dumps .
Returns a 500 error if the response cannot be serialized
Usage : :
> > > from lambda _ decorators import dump _ json _ body
> > > @ dump _ json _ body
. . . def handler ( event , context ) :
. . . return { ' ... | @ wraps ( handler )
def wrapper ( event , context ) :
response = handler ( event , context )
if 'body' in response :
try :
response [ 'body' ] = json . dumps ( response [ 'body' ] )
except Exception as exception :
return { 'statusCode' : 500 , 'body' : str ( exception ) }... |
def setup_deploy_key ( keypath = 'github_deploy_key' , key_ext = '.enc' , env_name = 'DOCTR_DEPLOY_ENCRYPTION_KEY' ) :
"""Decrypts the deploy key and configures it with ssh
The key is assumed to be encrypted as keypath + key _ ext , and the
encryption key is assumed to be set in the environment variable
` ` e... | key = os . environ . get ( env_name , os . environ . get ( "DOCTR_DEPLOY_ENCRYPTION_KEY" , None ) )
if not key :
raise RuntimeError ( "{env_name} or DOCTR_DEPLOY_ENCRYPTION_KEY environment variable is not set. Make sure you followed the instructions from 'doctr configure' properly. You may need to re-run 'doctr con... |
def make_instance ( self , command ) :
"""Create and initialize an instance of a user - defined class .
command must be a string in the form :
( < instance - name > of < class - name > < slot - override > * )
< slot - override > : = = ( < slot - name > < constant > * )
Python equivalent of the CLIPS make - ... | ist = lib . EnvMakeInstance ( self . _env , command . encode ( ) )
if ist == ffi . NULL :
raise CLIPSError ( self . _env )
return Instance ( self . _env , ist ) |
def memoize ( fn ) :
"""Simple memoization decorator for functions and methods ,
assumes that all arguments to the function can be hashed and
compared .""" | memoized_values = { }
@ wraps ( fn )
def wrapped_fn ( * args , ** kwargs ) :
key = ( args , tuple ( sorted ( kwargs . items ( ) ) ) )
try :
return memoized_values [ key ]
except KeyError :
memoized_values [ key ] = fn ( * args , ** kwargs )
return memoized_values [ key ]
return wrapp... |
def handle_heartbeat_response ( msg ) :
"""Process an internal heartbeat response message .""" | if not msg . gateway . is_sensor ( msg . node_id ) :
return None
handle_smartsleep ( msg )
msg . gateway . sensors [ msg . node_id ] . heartbeat = msg . payload
msg . gateway . alert ( msg )
return None |
def get_comparable_values_for_ordering ( self ) :
"""Return a tupple of values representing the unicity of the object""" | return ( 0 if self . position >= 0 else 1 , int ( self . position ) , str ( self . name ) , str ( self . description ) ) |
def checkout_create_push_branch ( repo , name ) :
"""Checkout this branch . Create it if necessary , and push it to origin .""" | try :
repo . git . checkout ( name )
_LOGGER . info ( "Checkout %s success" , name )
except GitCommandError :
_LOGGER . info ( "Checkout %s was impossible (branch does not exist). Creating it and push it." , name )
checkout_and_create_branch ( repo , name )
repo . git . push ( 'origin' , name , set_... |
def widget_from_tuple ( o ) :
"""Make widgets from a tuple abbreviation .""" | if _matches ( o , ( Real , Real ) ) :
min , max , value = _get_min_max_value ( o [ 0 ] , o [ 1 ] )
if all ( isinstance ( _ , Integral ) for _ in o ) :
cls = IntSlider
else :
cls = FloatSlider
return cls ( value = value , min = min , max = max )
elif _matches ( o , ( Real , Real , Real ) ... |
def _get_indexable_sentences ( document ) :
"""Parameters
document : Text
Article , book , paragraph , chapter , etc . Anything that is considered a document on its own .
Yields
str
json representation of elasticsearch type sentence""" | def unroll_lists ( list_of_lists ) :
for i in itertools . product ( * [ set ( j ) for j in list_of_lists ] ) :
yield ' ' . join ( i )
sents = document . split_by_sentences ( )
for order , sent in enumerate ( sents ) :
postags = list ( unroll_lists ( sent . postag_lists ) )
lemmas = list ( unroll_lis... |
def close ( self ) :
"""Cleans up the export endpoint""" | publish = False
exporterid = rsid = exception = export_ref = ed = None
with self . __lock :
if not self . __closed :
exporterid = self . __exportref . get_export_container_id ( )
export_ref = self . __exportref
rsid = self . __exportref . get_remoteservice_id ( )
ed = self . __export... |
def merge_variables ( variables , ** kwargs ) :
'''Concatenates Variables along row axis .
Args :
variables ( list ) : List of Variables to merge . Variables can have
different names ( and all Variables that share a name will be
concatenated together ) .
Returns :
A list of Variables .''' | var_dict = OrderedDict ( )
for v in variables :
if v . name not in var_dict :
var_dict [ v . name ] = [ ]
var_dict [ v . name ] . append ( v )
return [ merge_variables ( vars_ , ** kwargs ) for vars_ in list ( var_dict . values ( ) ) ] |
def _create_user ( self ) :
"""Create a new user""" | def error ( field , message ) :
if field :
message = "%s: %s" % ( field , message )
self . context . plone_utils . addPortalMessage ( message , 'error' )
return self . request . response . redirect ( self . context . absolute_url ( ) + "/login_details" )
form = self . request . form
contact = self .... |
def build_url ( host , path ) :
"""Builds a valid URL from a host and path which may or may not have slashes in the proper place .
Does not conform to ` IETF RFC 1808 < https : / / tools . ietf . org / html / rfc1808 . html > ` _ but instead joins the host and path as given .
Does not append any additional slas... | host += "/" if not host . endswith ( "/" ) else ""
path = path . lstrip ( "/" )
return parse . urljoin ( host , path ) |
def offset ( self , position ) :
"""Offset of given position from stranded start of this locus .
For example , if a Locus goes from 10 . . 20 and is on the negative strand ,
then the offset of position 13 is 7 , whereas if the Locus is on the
positive strand , then the offset is 3.""" | if position > self . end or position < self . start :
raise ValueError ( "Position %d outside valid range %d..%d of %s" % ( position , self . start , self . end , self ) )
elif self . on_forward_strand :
return position - self . start
else :
return self . end - position |
def get_mimetype ( self , path ) :
'''Get mimetype of given path calling all registered mime functions ( and
default ones ) .
: param path : filesystem path of file
: type path : str
: returns : mimetype
: rtype : str''' | for fnc in self . _mimetype_functions :
mime = fnc ( path )
if mime :
return mime
return mimetype . by_default ( path ) |
def sep ( self , p ) :
"""Angular spearation between objects in radians .
Parameters
p : AngularPosition
The object to which the separation from the current object
is to be calculated .
Notes
This method calls the function sep ( ) . See its docstring for
details .
See also
sep""" | return sep ( self . alpha . r , self . delta . r , p . alpha . r , p . delta . r ) |
def _get_query_result ( query , raw_result , ** kwargs ) :
"""Get query results helper .""" | if raw_result :
return query ( ** kwargs )
if kwargs :
return QueryResult ( query , ** kwargs )
return query . result |
def get_reqs ( which = "main" ) :
"""Gets requirements from all _ reqs with versions .""" | reqs = [ ]
for req in all_reqs [ which ] :
req_str = req + ">=" + ver_tuple_to_str ( min_versions [ req ] )
if req in version_strictly :
req_str += ",<" + ver_tuple_to_str ( min_versions [ req ] [ : - 1 ] ) + "." + str ( min_versions [ req ] [ - 1 ] + 1 )
reqs . append ( req_str )
return reqs |
def _download_rtd_zip ( rtd_version = None , ** kwargs ) :
"""Download and extract HTML ZIP from RTD to installed doc data path .
Download is skipped if content already exists .
Parameters
rtd _ version : str or ` None `
RTD version to download ; e . g . , " latest " , " stable " , or " v2.6.0 " .
If not ... | # https : / / github . com / ejeschke / ginga / pull / 451 # issuecomment - 298403134
if not toolkit . family . startswith ( 'qt' ) :
raise ValueError ( 'Downloaded documentation not compatible with {} ' 'UI toolkit browser' . format ( toolkit . family ) )
if rtd_version is None :
rtd_version = _find_rtd_versio... |
def pdf_link ( self , link_f , y , Y_metadata = None ) :
"""Likelihood function given link ( f )
. . math : :
\\ ln p ( y _ { i } | \\ lambda ( f _ { i } ) ) = - \\ frac { N \\ ln 2 \\ pi } { 2 } - \\ frac { \\ ln | K | } { 2 } - \\ frac { ( y _ { i } - \\ lambda ( f _ { i } ) ) ^ { T } \\ sigma ^ { - 2 } ( y _... | # Assumes no covariance , exp , sum , log for numerical stability
return np . exp ( np . sum ( np . log ( stats . norm . pdf ( y , link_f , np . sqrt ( self . variance ) ) ) ) ) |
def check ( self , pointer , expected , raise_onerror = False ) :
"""Check if value exists into object .
: param pointer : the path to search in
: param expected : the expected value
: param raise _ onerror : should raise on error ?
: return : boolean""" | obj = self . document
for token in Pointer ( pointer ) :
try :
obj = token . extract ( obj , bypass_ref = True )
except ExtractError as error :
if raise_onerror :
raise Error ( * error . args )
logger . exception ( error )
return False
return obj == expected |
def read_all ( filename ) :
"""Reads the serialized objects from disk . Caller must wrap objects in appropriate Python wrapper classes .
: param filename : the file with the serialized objects
: type filename : str
: return : the list of JB _ OBjects
: rtype : list""" | array = javabridge . static_call ( "Lweka/core/SerializationHelper;" , "readAll" , "(Ljava/lang/String;)[Ljava/lang/Object;" , filename )
if array is None :
return None
else :
return javabridge . get_env ( ) . get_object_array_elements ( array ) |
def remote ( fn , name = None , types = None ) :
"""Decorator that adds a remote attribute to a function .
fn - - function being decorated
name - - aliased name of the function , used for remote proxies
types - - a argument type specifier , can be used to ensure
arguments are of the correct type""" | if not name :
name = fn . __name__
fn . remote = { "name" : name , "types" : types }
return fn |
def peeklist ( self , fmt , ** kwargs ) :
"""Interpret next bits according to format string ( s ) and return list .
fmt - - One or more strings with comma separated tokens describing
how to interpret the next bits in the bitstring .
kwargs - - A dictionary or keyword - value pairs - the keywords used in the
... | pos = self . _pos
return_values = self . readlist ( fmt , ** kwargs )
self . _pos = pos
return return_values |
def store_mo ( self , state , new_mo , overwrite = True ) : # pylint : disable = unused - argument
"""Stores a memory object .
: param new _ mo : the memory object
: param overwrite : whether to overwrite objects already in memory ( if false , just fill in the holes )""" | start , end = self . _resolve_range ( new_mo )
if overwrite :
self . store_overwrite ( state , new_mo , start , end )
else :
self . store_underwrite ( state , new_mo , start , end ) |
def compute_distance_matrix ( points ) :
"""Return a matrix of distance ( in meters ) between every point in a given list
of ( lat , lon ) location tuples .""" | n = len ( points )
return [ [ 1000 * great_circle_distance ( points [ i ] , points [ j ] ) for j in range ( n ) ] for i in range ( n ) ] |
def post ( self , request , format = None ) :
"""validate password change operation and return result""" | serializer_class = self . get_serializer_class ( )
serializer = serializer_class ( data = request . data , instance = request . user )
if serializer . is_valid ( ) :
serializer . save ( )
return Response ( { 'detail' : _ ( u'Password successfully changed' ) } )
return Response ( serializer . errors , status = 4... |
def _writeBlock ( self ) :
"""Write a block of data to the remote writer""" | if self . interrupted or self . fp is None :
if self . debug :
log . msg ( 'WorkerFileUploadCommand._writeBlock(): end' )
return True
length = self . blocksize
if self . remaining is not None and length > self . remaining :
length = self . remaining
if length <= 0 :
if self . stderr is None :
... |
def bipart ( func , seq ) :
r"""Like a partitioning version of ` filter ` . Returns
` ` [ itemsForWhichFuncReturnedFalse , itemsForWhichFuncReturnedTrue ] ` ` .
Example :
> > > bipart ( bool , [ 1 , None , 2,3,0 , [ ] , [ 0 ] ] )
[ [ None , 0 , [ ] ] , [ 1 , 2 , 3 , [ 0 ] ] ]""" | if func is None :
func = bool
res = [ [ ] , [ ] ]
for i in seq :
res [ not not func ( i ) ] . append ( i )
return res |
def get_csv_import_info ( self , path ) :
"""Launches the csv dialog and returns csv _ info
csv _ info is a tuple of dialect , has _ header , digest _ types
Parameters
path : String
\t File path of csv file""" | csvfilename = os . path . split ( path ) [ 1 ]
try :
filterdlg = CsvImportDialog ( self . main_window , csvfilepath = path )
except csv . Error , err : # Display modal warning dialog
msg = _ ( "'{filepath}' does not seem to be a valid CSV file.\n \n" "Opening it yielded the error:\n{error}" )
msg = msg . fo... |
def handle ( self , message ) :
'''Attempts to send a message to the specified destination in Discord .
Extends Legobot . Lego . handle ( )
Args :
message ( Legobot . Message ) : message w / metadata to send .''' | logger . debug ( message )
if Utilities . isNotEmpty ( message [ 'metadata' ] [ 'opts' ] ) :
target = message [ 'metadata' ] [ 'opts' ] [ 'target' ]
self . botThread . create_message ( target , message [ 'text' ] ) |
def toggle_view ( self , checked ) :
"""Toggle view""" | if checked :
self . dockwidget . show ( )
self . dockwidget . raise_ ( )
# Start a client in case there are none shown
if not self . clients :
if self . main . is_setting_up :
self . create_new_client ( give_focus = False )
else :
self . create_new_client ( give_f... |
def draw_text ( self , content ) :
"""Draws text cell content to context""" | wx2pango_alignment = { "left" : pango . ALIGN_LEFT , "center" : pango . ALIGN_CENTER , "right" : pango . ALIGN_RIGHT , }
cell_attributes = self . code_array . cell_attributes [ self . key ]
angle = cell_attributes [ "angle" ]
if angle in [ - 90 , 90 ] :
rect = self . rect [ 1 ] , self . rect [ 0 ] , self . rect [ 3... |
def fbpe_key ( code ) :
"""input :
' S0102-67202009000300001'
output :
' S0102-6720(09)000300001'""" | begin = code [ 0 : 10 ]
year = code [ 12 : 14 ]
end = code [ 14 : ]
return '%s(%s)%s' % ( begin , year , end ) |
def export ( self , node ) :
"""Return JSON for tree starting at ` node ` .""" | dictexporter = self . dictexporter or DictExporter ( )
data = dictexporter . export ( node )
return json . dumps ( data , ** self . kwargs ) |
def validate_clip_with_axis ( axis , args , kwargs ) :
"""If ' NDFrame . clip ' is called via the numpy library , the third
parameter in its signature is ' out ' , which can takes an ndarray ,
so check if the ' axis ' parameter is an instance of ndarray , since
' axis ' itself should either be an integer or N... | if isinstance ( axis , ndarray ) :
args = ( axis , ) + args
axis = None
validate_clip ( args , kwargs )
return axis |
def parse_route_spec_config ( data ) :
"""Parse and sanity check the route spec config .
The config data is a blob of JSON that needs to be in this format :
" < CIDR - 1 > " : [ " host - 1 - ip " , " host - 2 - ip " , " host - 3 - ip " ] ,
" < CIDR - 2 > " : [ " host - 4 - ip " , " host - 5 - ip " ] ,
" < C... | # Sanity checking on the data object
if type ( data ) is not dict :
raise ValueError ( "Expected dictionary at top level" )
try :
for k , v in data . items ( ) :
utils . ip_check ( k , netmask_expected = True )
if type ( v ) is not list :
raise ValueError ( "Expect list of IPs as val... |
def _ParseFileHeader ( self , file_object ) :
"""Parses the file header .
Args :
file _ object ( dfvfs . FileIO ) : a file - like object to parse .
Raises :
ParseError : if the file header cannot be read .""" | file_header_map = self . _GetDataTypeMap ( 'chrome_cache_data_block_file_header' )
try :
file_header , _ = self . _ReadStructureFromFileObject ( file_object , 0 , file_header_map )
except ( ValueError , errors . ParseError ) as exception :
raise errors . ParseError ( 'Unable to parse data block file header with... |
def deserialize_property ( value : Any ) -> Any :
"""Deserializes a single protobuf value ( either ` Struct ` or ` ListValue ` ) into idiomatic
Python values .""" | if value == UNKNOWN :
return None
# ListValues are projected to lists
if isinstance ( value , struct_pb2 . ListValue ) :
return [ deserialize_property ( v ) for v in value ]
# Structs are projected to dictionaries
if isinstance ( value , struct_pb2 . Struct ) :
return deserialize_properties ( value )
# Ever... |
def Nu_sphere_Churchill ( Pr , Gr ) :
r'''Calculates Nusselt number for natural convection around a sphere
according to the Churchill [ 1 ] _ correlation . Sphere must be isothermal .
. . math : :
Nu _ D = 2 + \ frac { 0.589Ra _ D ^ { 1/4 } } { \ left [ 1 + ( 0.469 / Pr ) ^ { 9/16 } \ right ] ^ { 4/9 } }
\ ... | Ra = Pr * Gr
Nu = 2 + ( 0.589 * Ra ** 0.25 / ( 1 + ( 0.469 / Pr ) ** ( 9 / 16. ) ) ** ( 4 / 9. ) * ( 1 + 7.44E-8 * Ra / ( 1 + ( 0.469 / Pr ) ** ( 9 / 16. ) ) ** ( 16 / 9. ) ) ** ( 1 / 12. ) )
return Nu |
def is_meta_url ( attr , attrs ) :
"""Check if the meta attributes contain a URL .""" | res = False
if attr == "content" :
equiv = attrs . get_true ( 'http-equiv' , u'' ) . lower ( )
scheme = attrs . get_true ( 'scheme' , u'' ) . lower ( )
res = equiv in ( u'refresh' , ) or scheme in ( u'dcterms.uri' , )
if attr == "href" :
rel = attrs . get_true ( 'rel' , u'' ) . lower ( )
res = rel i... |
def zeta ( x , context = None ) :
"""Return the value of the Riemann zeta function on x .""" | return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_zeta , ( BigFloat . _implicit_convert ( x ) , ) , context , ) |
def p ( i , sample_size , weights ) :
"""Given a weighted set and sample size return the probabilty that the
weight ` i ` will be present in the sample .
Created to test the output of the ` SomeOf ` maker class . The math was
provided by Andy Blackshaw - thank you dad : )""" | # Determine the initial pick values
weight_i = weights [ i ]
weights_sum = sum ( weights )
# Build a list of weights that don ' t contain the weight ` i ` . This list will
# be used to build the possible picks before weight ` i ` .
other_weights = list ( weights )
del other_weights [ i ]
# Calculate the probability
pro... |
def put_content ( self , content ) :
"""Makes a ` ` PUT ` ` request with the content in the body .
: raise : An : exc : ` requests . RequestException ` if it is not 2xx .""" | r = requests . request ( self . method if self . method else 'PUT' , self . url , data = content , ** self . storage_args )
if self . raise_for_status :
r . raise_for_status ( ) |
def to_dict ( self ) :
"""Return dict representation of public key to embed in DID document .""" | return { 'id' : self . id , 'type' : str ( self . type . ver_type ) , 'controller' : canon_ref ( self . did , self . controller ) , ** self . type . specification ( self . value ) } |
def join ( iterable , sep ) :
"""Like str . join , but yields an iterable .""" | i = 0
for i , item in enumerate ( iterable ) :
if i == 0 :
yield item
else :
yield sep
yield item |
def _properties_element ( self , parent_element ) :
"""Returns properties XML element .""" | testsuites_properties = etree . SubElement ( parent_element , "properties" )
etree . SubElement ( testsuites_properties , "property" , { "name" : "polarion-testrun-id" , "value" : str ( self . testrun_id ) } , )
etree . SubElement ( testsuites_properties , "property" , { "name" : "polarion-project-id" , "value" : str (... |
def RegisterCheck ( cls , check , source = "unknown" , overwrite_if_exists = False ) :
"""Adds a check to the registry , refresh the trigger to check map .""" | if not overwrite_if_exists and check . check_id in cls . checks :
raise DefinitionError ( "Check named %s already exists and " "overwrite_if_exists is set to False." % check . check_id )
check . loaded_from = source
cls . checks [ check . check_id ] = check
cls . triggers . Update ( check . triggers , check ) |
def getTypeStr ( _type ) :
r"""Gets the string representation of the given type .""" | if isinstance ( _type , CustomType ) :
return str ( _type )
if hasattr ( _type , '__name__' ) :
return _type . __name__
return '' |
def make_basic_table ( self , file_type ) :
"""Create table of key - value items in ' file _ type ' .""" | table_data = { sample : items [ 'kv' ] for sample , items in self . mod_data [ file_type ] . items ( ) }
table_headers = { }
for column_header , ( description , header_options ) in file_types [ file_type ] [ 'kv_descriptions' ] . items ( ) :
table_headers [ column_header ] = { 'rid' : '{}_{}_bbmstheader' . format (... |
def to_annot ( self , annot , category , name , s_freq = 512 ) :
"""Write matched events to Wonambi XML file for visualization .
Parameters
annot : instance of Annotations
Annotations file
category : str
' tp _ cons ' , ' tp _ det ' , ' tp _ std ' , ' fp ' or ' fn '
name : str
name for the event type ... | if 'tp_cons' == category :
cons = consensus ( ( self . detection , self . standard ) , 1 , s_freq )
events = cons . events
elif 'tp_det' == category :
events = asarray ( self . detection ) [ self . tp . any ( axis = 1 ) ]
elif 'tp_std' == category :
events = asarray ( self . standard ) [ self . tp . any... |
def list_all_quantities ( self , include_native = False , with_info = False ) :
"""Return a list of all available quantities in this catalog .
If * include _ native * is ` True ` , includes native quantities .
If * with _ info * is ` True ` , return a dict with quantity info .
See also : list _ all _ native _... | q = set ( self . _quantity_modifiers )
if include_native :
q . update ( self . _native_quantities )
return { k : self . get_quantity_info ( k ) for k in q } if with_info else list ( q ) |
def main ( ) :
"""Main entry point for CLI commands .""" | options = docopt ( __doc__ , version = __version__ )
if options [ 'segment' ] :
segment ( options [ '<file>' ] , options [ '--output' ] , options [ '--target-duration' ] , options [ '--mpegts' ] , ) |
def reconstruct_indices ( self ) :
"""Reconstruct word indices in case of word removals .
Vocabulary does not handle empty indices when words are removed ,
hence it need to be told explicity about when to reconstruct them .""" | del self . i2f , self . f2i
self . f2i , self . i2f = { } , { }
for i , w in enumerate ( self . words ) :
self . f2i [ w ] = i
self . i2f [ i ] = w |
def _get_example_csv ( self ) :
"""For dimension parsing""" | station_key = self . json [ "station" ] [ 0 ] [ "key" ]
period = "corrected-archive"
url = self . url . replace ( ".json" , "/station/{}/period/{}/data.csv" . format ( station_key , period ) )
r = requests . get ( url )
if r . status_code == 200 :
return DataCsv ( ) . from_string ( r . content )
else :
raise Ex... |
def get_attribute_item_groups ( network_id , attr_id , ** kwargs ) :
"""Get all the group items in a network with a given attribute _ id""" | user_id = kwargs . get ( 'user_id' )
network_i = _get_network ( network_id )
network_i . check_read_permission ( user_id )
group_items_i = db . DBSession . query ( AttrGroupItem ) . filter ( AttrGroupItem . network_id == network_id , AttrGroupItem . attr_id == attr_id ) . all ( )
return group_items_i |
def get_blobs_zip ( self , blob_ids , repository_id , project = None , filename = None , ** kwargs ) :
"""GetBlobsZip .
[ Preview API ] Gets one or more blobs in a zip file download .
: param [ str ] blob _ ids : Blob IDs ( SHA1 hashes ) to be returned in the zip file .
: param str repository _ id : The name ... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if repository_id is not None :
route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' )
query_parameters = { }
if filename is not None :
... |
def save ( self , * args ) :
"""Put text in my store , return True if it changed""" | if self . name_wid is None or self . store is None :
Logger . debug ( "{}: Not saving, missing name_wid or store" . format ( type ( self ) . __name__ ) )
return
if not ( self . name_wid . text or self . name_wid . hint_text ) :
Logger . debug ( "{}: Not saving, no name" . format ( type ( self ) . __name__ )... |
def _migrate_resource ( instance , migrations , version = '' ) :
"""Migrate a resource instance
Subresources are migrated first , then the resource is recursively migrated
: param instance : a perch . Document instance
: param migrations : the migrations for a resource
: param version : the current resource... | if version not in migrations :
return instance
instance = _migrate_subresources ( instance , migrations [ version ] [ 'subresources' ] )
for migration in migrations [ version ] [ 'migrations' ] :
instance = migration ( instance )
instance . _resource [ 'doc_version' ] = unicode ( migration . version )
i... |
def eval_fieldnames ( string_ , varname = "fieldnames" ) :
"""Evaluates string _ , must evaluate to list of strings . Also converts field names to uppercase""" | ff = eval ( string_ )
if not isinstance ( ff , list ) :
raise RuntimeError ( "{0!s} must be a list" . format ( varname ) )
if not all ( [ isinstance ( x , str ) for x in ff ] ) :
raise RuntimeError ( "{0!s} must be a list of strings" . format ( varname ) )
ff = [ x . upper ( ) for x in ff ]
return ff |
def get_cim_ns ( namespaces ) :
"""Tries to obtain the CIM version from the given map of namespaces and
returns the appropriate * nsURI * and * packageMap * .""" | try :
ns = namespaces [ 'cim' ]
if ns . endswith ( '#' ) :
ns = ns [ : - 1 ]
except KeyError :
ns = ''
logger . error ( 'No CIM namespace defined in input file.' )
CIM16nsURI = 'http://iec.ch/TC57/2013/CIM-schema-cim16'
nsuri = ns
import CIM14 , CIM15
if ns == CIM14 . nsURI :
ns = 'CIM14'
el... |
def find_peaks ( signal ) :
"""Locate peaks based on derivative .
Parameters
signal : list or array
Signal .
Returns
peaks : array
An array containing the peak indices .
Example
> > > signal = np . sin ( np . arange ( 0 , np . pi * 10 , 0.05 ) )
> > > peaks = nk . find _ peaks ( signal )
> > > n... | derivative = np . gradient ( signal , 2 )
peaks = np . where ( np . diff ( np . sign ( derivative ) ) ) [ 0 ]
return ( peaks ) |
def _param_grad_helper ( self , dL_dK , X , X2 , target ) :
"""derivative of the covariance matrix with respect to the parameters .""" | if X2 is None :
X2 = X
dist = np . abs ( X - X2 . T )
ly = 1 / self . lengthscaleY
lu = np . sqrt ( 3 ) / self . lengthscaleU
# ly = self . lengthscaleY
# lu = self . lengthscaleU
dk1theta1 = np . exp ( - ly * dist ) * 2 * ( - lu ) / ( lu + ly ) ** 3
# c = np . sqrt ( 3)
# t1 = c / lu
# t2 = 1 / ly
# dk1theta1 = np... |
def readTable ( self , tableName ) :
"""Read the table corresponding to the specified name , equivalent to the
AMPL statement :
. . code - block : : ampl
read table tableName ;
Args :
tableName : Name of the table to be read .""" | lock_and_call ( lambda : self . _impl . readTable ( tableName ) , self . _lock ) |
def attribute ( self , value ) :
"""Setter for * * self . _ _ attribute * * attribute .
: param value : Attribute value .
: type value : unicode""" | if value is not None :
assert type ( value ) is unicode , "'{0}' attribute: '{1}' type is not 'unicode'!" . format ( "attribute" , value )
self . __attribute = value |
def draw_graph ( adata , layout = None , ** kwargs ) -> Union [ Axes , List [ Axes ] , None ] :
"""Scatter plot in graph - drawing basis .
Parameters
{ adata _ color _ etc }
layout : { { ' fa ' , ' fr ' , ' drl ' , . . . } } , optional ( default : last computed )
One of the ` draw _ graph ` layouts , see
... | if layout is None :
layout = str ( adata . uns [ 'draw_graph' ] [ 'params' ] [ 'layout' ] )
basis = 'draw_graph_' + layout
if 'X_' + basis not in adata . obsm_keys ( ) :
raise ValueError ( 'Did not find {} in adata.obs. Did you compute layout {}?' . format ( 'draw_graph_' + layout , layout ) )
return plot_scatt... |
def render ( C , styles , margin = '' , indent = '\t' ) :
"""output css text from styles .
margin is what to put at the beginning of every line in the output .
indent is how much to indent indented lines ( such as inside braces ) .""" | from unum import Unum
s = ""
# render the css text
for k in styles . keys ( ) :
s += margin
if type ( styles [ k ] ) == Unum :
s += k + ' ' + str ( styles [ k ] ) + ';'
elif type ( styles [ k ] ) in [ str , String ] :
s += k + ' ' + styles [ k ] + ';'
elif type ( styles [ k ] ) in [ dict... |
def _set_flexport ( self , v , load = False ) :
"""Setter method for flexport , mapped from YANG variable / hardware / flexport ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ flexport is considered as a private
method . Backends looking to populate this vari... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "id" , flexport . flexport , yang_name = "flexport" , rest_name = "flexport" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'id' , extensions = ... |
def set_pubnote ( self , pubnote ) :
"""Parse pubnote and populate correct fields .""" | if 'publication_info' in self . obj . get ( 'reference' , { } ) :
self . add_misc ( u'Additional pubnote: {}' . format ( pubnote ) )
return
if self . RE_VALID_PUBNOTE . match ( pubnote ) :
pubnote = split_pubnote ( pubnote )
pubnote = convert_old_publication_info_to_new ( [ pubnote ] ) [ 0 ]
self . ... |
def construct ( self , method , lowcut , highcut , samp_rate , filt_order , prepick , save_progress = False , ** kwargs ) :
"""Generate a Tribe of Templates .
See : mod : ` eqcorrscan . core . template _ gen ` for available methods .
: param method : Method of Tribe generation .
: param kwargs : Arguments for... | templates , catalog , process_lengths = template_gen . template_gen ( method = method , lowcut = lowcut , highcut = highcut , filt_order = filt_order , samp_rate = samp_rate , prepick = prepick , return_event = True , save_progress = save_progress , ** kwargs )
for template , event , process_len in zip ( templates , ca... |
def touch ( self ) :
"""Touch all of the related models for the relationship .""" | column = self . get_related ( ) . get_updated_at_column ( )
self . raw_update ( { column : self . get_related ( ) . fresh_timestamp ( ) } ) |
def copy_random_pointer_v2 ( head ) :
""": type head : RandomListNode
: rtype : RandomListNode""" | copy = defaultdict ( lambda : RandomListNode ( 0 ) )
copy [ None ] = None
node = head
while node :
copy [ node ] . label = node . label
copy [ node ] . next = copy [ node . next ]
copy [ node ] . random = copy [ node . random ]
node = node . next
return copy [ head ] |
def get_resources ( self , request , ** resources ) :
"""Parse resource objects from URL and request .
: return dict : Resources .""" | if self . parent :
resources = self . parent . get_resources ( request , ** resources )
pks = ( resources . get ( self . _meta . name ) or request . REQUEST . getlist ( self . _meta . name ) or getattr ( request , 'data' , None ) and request . data . get ( self . _meta . name ) )
if not pks or self . _meta . querys... |
def search ( self , search_term , num_results , ** kwargs ) :
"""Gets x number of Google image result urls for
a given search term .
Arguments
search _ term : str
tearm to search for
num _ results : int
number of url results to return
return [ ' url ' , ' url ' ]""" | results = [ ]
count = 1
try :
while len ( results ) <= num_results :
search_results = self . service . cse ( ) . list ( q = search_term , cx = self . cse_id , searchType = "image" , fileType = self . file_type , start = count , ** kwargs ) . execute ( )
results . extend ( [ r [ 'link' ] for r in sea... |
def xview ( self , * args ) :
"""Update inplace widgets position when doing horizontal scroll""" | self . after_idle ( self . __updateWnds )
ttk . Treeview . xview ( self , * args ) |
def normalize ( self , dt ) :
"""Clamp dt to every Nth : py : attr : ` ~ _ DatetimeParameterBase . interval ` starting at
: py : attr : ` ~ _ DatetimeParameterBase . start ` .""" | if dt is None :
return None
dt = self . _convert_to_dt ( dt )
dt = dt . replace ( microsecond = 0 )
# remove microseconds , to avoid float rounding issues .
delta = ( dt - self . start ) . total_seconds ( )
granularity = ( self . _timedelta * self . interval ) . total_seconds ( )
return dt - datetime . timedelta ( ... |
def filter_on_wire_representation ( ava , acs , required = None , optional = None ) :
""": param ava : A dictionary with attributes and values
: param acs : List of tuples ( Attribute Converter name ,
Attribute Converter instance )
: param required : A list of saml . Attributes
: param optional : A list of ... | acsdic = dict ( [ ( ac . name_format , ac ) for ac in acs ] )
if required is None :
required = [ ]
if optional is None :
optional = [ ]
res = { }
for attr , val in ava . items ( ) :
done = False
for req in required :
try :
_name = acsdic [ req . name_format ] . _to [ attr ]
... |
def _sort_lines ( self ) :
"""Haproxy writes its logs after having gathered all information
related to each specific connection . A simple request can be
really quick but others can be really slow , thus even if one connection
is logged later , it could have been accepted before others that are
already proc... | self . _valid_lines = sorted ( self . _valid_lines , key = lambda line : line . accept_date , ) |
def fill_rawq ( self ) :
"""Fill raw queue from exactly one recv ( ) system call .
Set self . eof when connection is closed .""" | if self . irawq >= len ( self . rawq ) :
self . rawq = b''
self . irawq = 0
# The buffer size should be fairly small so as to avoid quadratic
# behavior in process _ rawq ( ) above
buf = yield from self . _reader . read ( 50 )
self . eof = ( not buf )
self . rawq = self . rawq + buf |
def get_all_player_ids ( ids = "shots" ) :
"""Returns a pandas DataFrame containing the player IDs used in the
stats . nba . com API .
Parameters
ids : { " shots " | " all _ players " | " all _ data " } , optional
Passing in " shots " returns a DataFrame that contains the player IDs of
all players have sh... | url = "http://stats.nba.com/stats/commonallplayers?IsOnlyCurrentSeason=0&LeagueID=00&Season=2015-16"
# get the web page
response = requests . get ( url , headers = HEADERS )
response . raise_for_status ( )
# access ' resultSets ' , which is a list containing the dict with all the data
# The ' header ' key accesses the ... |
def vocab_counter ( args ) :
"""Calculate the vocabulary .""" | if isinstance ( args . input , TextFiles ) :
v = CountedVocabulary . from_textfiles ( args . input , workers = args . workers )
else :
v = CountedVocabulary . from_textfile ( args . input , workers = args . workers )
if args . min_count > 1 :
v = v . min_count ( args . min_count )
if args . most_freq > 0 :
... |
def open ( path , mode = None , ac_parser = None , ** options ) :
"""Open given configuration file with appropriate open flag .
: param path : Configuration file path
: param mode :
Can be ' r ' and ' rb ' for reading ( default ) or ' w ' , ' wb ' for writing .
Please note that even if you specify ' r ' or ... | psr = find ( path , forced_type = ac_parser )
if mode is not None and mode . startswith ( 'w' ) :
return psr . wopen ( path , ** options )
return psr . ropen ( path , ** options ) |
def send_document ( self , peer : Peer , document : str , reply : int = None , on_success : callable = None , reply_markup : botapi . ReplyMarkup = None ) :
"""Send document to peer .
: param peer : Peer to send message to .
: param document : File path to document to send .
: param reply : Message object or ... | pass |
def constrain_property ( self , prop , ** kwargs ) :
"""Constrains property for each population
See : func : ` vespa . stars . StarPopulation . constrain _ property ` ;
all arguments passed to that function for each population .""" | if prop not in self . constraints :
self . constraints . append ( prop )
for pop in self . poplist :
try :
pop . constrain_property ( prop , ** kwargs )
except AttributeError :
logging . info ( '%s model does not have property stars.%s (constraint not applied)' % ( pop . model , prop ) ) |
def prepare ( self , hash , start , end , name , sources , sample = None ) :
"""Prepare a historics query which can later be started .
Uses API documented at http : / / dev . datasift . com / docs / api / rest - api / endpoints / historicsprepare
: param hash : The hash of a CSDL create the query for
: type h... | if len ( sources ) == 0 :
raise HistoricSourcesRequired ( )
if not isinstance ( sources , list ) :
sources = [ sources ]
params = { 'hash' : hash , 'start' : start , 'end' : end , 'name' : name , 'sources' : ',' . join ( sources ) }
if sample :
params [ 'sample' ] = sample
return self . request . post ( 'pr... |
def set_app_os_tag ( self , os_tag , app_tag , update_os , update_app ) :
"""Update the app and / or os tags .""" | update_os = bool ( update_os )
update_app = bool ( update_app )
if update_os :
self . os_info = _unpack_version ( os_tag )
if update_app :
self . app_info = _unpack_version ( app_tag )
return [ Error . NO_ERROR ] |
def get_page ( pno , zoom = False , max_size = None , first = False ) :
"""Return a PNG image for a document page number .""" | dlist = dlist_tab [ pno ]
# get display list of page number
if not dlist : # create if not yet there
dlist_tab [ pno ] = doc [ pno ] . getDisplayList ( )
dlist = dlist_tab [ pno ]
r = dlist . rect
# the page rectangle
clip = r
# ensure image fits screen :
# exploit , but do not exceed width or height
zoom_0 = 1... |
def make_random_models_table ( n_sources , param_ranges , random_state = None ) :
"""Make a ` ~ astropy . table . Table ` containing randomly generated
parameters for an Astropy model to simulate a set of sources .
Each row of the table corresponds to a source whose parameters are
defined by the column names ... | prng = check_random_state ( random_state )
sources = Table ( )
for param_name , ( lower , upper ) in param_ranges . items ( ) : # Generate a column for every item in param _ ranges , even if it
# is not in the model ( e . g . flux ) . However , such columns will
# be ignored when rendering the image .
sources [ par... |
def rmglob ( pattern : str ) -> None :
"""Deletes all files whose filename matches the glob ` ` pattern ` ` ( via
: func : ` glob . glob ` ) .""" | for f in glob . glob ( pattern ) :
os . remove ( f ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.