signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def write_all ( self ) :
"""Write out all registered config files .""" | [ self . write ( k ) for k in six . iterkeys ( self . templates ) ] |
def check ( state_engine , nameop , block_id , checked_ops ) :
"""Verify the validity of an update to a name ' s associated data .
Use the nameop ' s 128 - bit name hash to find the name itself .
NAME _ UPDATE isn ' t allowed during an import , so the name ' s namespace must be ready .
Return True if accepted... | name_consensus_hash = nameop [ 'name_consensus_hash' ]
sender = nameop [ 'sender' ]
# deny updates if we exceed quota - - the only legal operations are to revoke or transfer .
sender_names = state_engine . get_names_owned_by_sender ( sender )
if len ( sender_names ) > MAX_NAMES_PER_SENDER :
log . warning ( "Sender ... |
def identical_format_path ( fmt1 , fmt2 ) :
"""Do the two ( long representation ) of formats target the same file ?""" | for key in [ 'extension' , 'prefix' , 'suffix' ] :
if fmt1 . get ( key ) != fmt2 . get ( key ) :
return False
return True |
def arange_col ( n , dtype = int ) :
"""Returns ` ` np . arange ` ` in a column form .
: param n : Length of the array .
: type n : int
: param dtype : Type of the array .
: type dtype : type
: returns : ` ` np . arange ` ` in a column form .
: rtype : ndarray""" | return np . reshape ( np . arange ( n , dtype = dtype ) , ( n , 1 ) ) |
def run ( self , fnc_name , hdrs_usr ) :
"""Read csv / tsv file and return specified data in a list of lists .""" | fnc = self . fncs [ fnc_name ]
with open ( self . fin ) as fin_stream :
for lnum , line in enumerate ( fin_stream ) :
line = line . rstrip ( '\r\n' )
# chomp
# Obtain Data if headers have been collected from the first line
if self . hdr2idx :
self . _init_data_line ( fnc ... |
def print_tree ( sent , token_attr ) :
"""Prints sentences tree as string using token _ attr from token ( like pos _ , tag _ etc . )
: param sent : sentence to print
: param token _ attr : choosen attr to present for tokens ( e . g . dep _ , pos _ , tag _ , . . . )""" | def __print_sent__ ( token , attr ) :
print ( "{" , end = " " )
[ __print_sent__ ( t , attr ) for t in token . lefts ]
print ( u"%s->%s(%s)" % ( token , token . dep_ , token . tag_ if not attr else getattr ( token , attr ) ) , end = "" )
[ __print_sent__ ( t , attr ) for t in token . rights ]
print ... |
def create_new_values ( self ) :
"""Create values created by the user input . Return the model instances QS .""" | model = self . queryset . model
pks = [ ]
extra_create_kwargs = self . extra_create_kwargs ( )
for value in self . _new_values :
create_kwargs = { self . create_field : value }
create_kwargs . update ( extra_create_kwargs )
new_item = self . create_item ( ** create_kwargs )
pks . append ( new_item . pk ... |
def get_queue_url ( queue_name ) :
"""Get the URL of the SQS queue to send events to .""" | client = boto3 . client ( "sqs" , CURRENT_REGION )
queue = client . get_queue_url ( QueueName = queue_name )
return queue [ "QueueUrl" ] |
def parse_response ( self , connection , command_name , ** options ) :
"Parses a response from the Redis server" | try :
response = connection . read_response ( )
except ResponseError :
if EMPTY_RESPONSE in options :
return options [ EMPTY_RESPONSE ]
raise
if command_name in self . response_callbacks :
return self . response_callbacks [ command_name ] ( response , ** options )
return response |
def move_next_cache ( self ) :
"""Moves files in the ' next ' cache dir to the root""" | if not os . path . isdir ( self . songcache_next_dir ) :
return
logger . debug ( "Moving next cache" )
files = os . listdir ( self . songcache_next_dir )
for f in files :
try :
os . rename ( "{}/{}" . format ( self . songcache_next_dir , f ) , "{}/{}" . format ( self . songcache_dir , f ) )
except P... |
def mosaicMethod ( self , value ) :
"""get / set the mosaic method""" | if value in self . __allowedMosaicMethods and self . _mosaicMethod != value :
self . _mosaicMethod = value |
def _config_bootstrap ( self ) -> None :
"""Handle the basic setup of the tool prior to user control .
Bootstrap will load all the available modules for searching and set
them up for use by this main class .""" | if self . output :
self . folder : str = os . getcwd ( ) + "/" + self . project
os . mkdir ( self . folder ) |
async def create_invite ( self , * , reason = None , ** fields ) :
"""| coro |
Creates an instant invite .
You must have : attr : ` ~ . Permissions . create _ instant _ invite ` permission to
do this .
Parameters
max _ age : : class : ` int `
How long the invite should last . If it ' s 0 then the invite... | data = await self . _state . http . create_invite ( self . id , reason = reason , ** fields )
return Invite . from_incomplete ( data = data , state = self . _state ) |
def post ( self , * args , ** kwargs ) :
"""Check if the current step is still available . It might not be if
conditions have changed .""" | if self . steps . current not in self . steps . all :
logger . warning ( "Current step '%s' is no longer valid, returning " "to last valid step in the wizard." , self . steps . current )
return self . render_goto_step ( self . steps . all [ - 1 ] )
# - - Duplicated code from upstream
# Look for a wizard _ goto ... |
def rotate ( matrix , angle ) :
r"""Rotate
This method rotates an input matrix about the input angle .
Parameters
matrix : np . ndarray
Input matrix array
angle : float
Rotation angle in radians
Returns
np . ndarray rotated matrix
Raises
ValueError
For invalid matrix shape
Examples
> > > f... | shape = np . array ( matrix . shape )
if shape [ 0 ] != shape [ 1 ] :
raise ValueError ( 'Input matrix must be square.' )
shift = ( shape - 1 ) // 2
index = np . array ( list ( product ( * np . array ( [ np . arange ( val ) for val in shape ] ) ) ) ) - shift
new_index = np . array ( np . dot ( index , rot_matrix ( ... |
def analysis ( self , frames = 'all' , ncpus = 1 , _ncpus = 1 , override = False , ** kwargs ) :
"""Perform structural analysis on a frame / set of frames .
Depending on the passed parameters a frame , a list of particular
frames , a range of frames ( from , to ) , or all frames can be analysed
with this func... | frames_for_analysis = [ ]
# First populate the frames _ for _ analysis list .
if isinstance ( frames , int ) :
frames_for_analysis . append ( frames )
if isinstance ( frames , list ) :
for frame in frames :
if isinstance ( frame , int ) :
frames_for_analysis . append ( frame )
else :... |
def load ( self , fobj , index = None ) :
"""Loads given DataFile object . * * tolerant with None * *
Args :
fobj : object of one of accepted classes
index : tab index to load fobj into . If not passed , loads into current tab""" | if index is None :
index = self . _get_tab_index ( )
page = self . pages [ index ]
if fobj is None :
return
if not isinstance ( fobj , tuple ( page . clss_load ) ) :
raise RuntimeError ( 'Object to load must be in {0!s} (not a {1!s})' . format ( [ x . __name__ for x in page . clss_load ] , fobj . __class__ ... |
def estimate_param_scan ( estimator , X , param_sets , evaluate = None , evaluate_args = None , failfast = True , return_estimators = False , n_jobs = 1 , progress_reporter = None , show_progress = True , return_exceptions = False ) :
"""Runs multiple estimations using a list of parameter settings
Parameters
es... | # make sure we have an estimator object
estimator = get_estimator ( estimator )
if hasattr ( estimator , 'show_progress' ) :
estimator . show_progress = show_progress
if n_jobs is None :
from pyemma . _base . parallel import get_n_jobs
n_jobs = get_n_jobs ( logger = getattr ( estimator , 'logger' , None ) )... |
async def setup_hostname ( ) -> str :
"""Intended to be run when the server starts . Sets the machine hostname .
The machine hostname is set from the systemd - generated machine - id , which
changes at every boot .
Once the hostname is set , we restart avahi .
This is a separate task from establishing and c... | machine_id = open ( '/etc/machine-id' ) . read ( ) . strip ( )
hostname = machine_id [ : 6 ]
with open ( '/etc/hostname' , 'w' ) as ehn :
ehn . write ( f'{hostname}\n' )
# First , we run hostnamed which will set the transient hostname
# and loaded static hostname from the value we just wrote to
# / etc / hostname
L... |
def fit_mle ( self , data , b = None ) :
"""% ( super ) s
b : float
The upper bound of the distribution . If None , fixed at sum ( data )""" | data = np . array ( data )
length = len ( data )
if not b :
b = np . sum ( data )
return _trunc_logser_solver ( length , b ) , b |
def _pick_idp ( self , came_from ) :
"""If more than one idp and if none is selected , I have to do wayf or
disco""" | _cli = self . sp
logger . debug ( "[_pick_idp] %s" , self . environ )
if "HTTP_PAOS" in self . environ :
if self . environ [ "HTTP_PAOS" ] == PAOS_HEADER_INFO :
if MIME_PAOS in self . environ [ "HTTP_ACCEPT" ] : # Where should I redirect the user to
# entityid - > the IdP to use
# relay _ st... |
def parse_metric_family ( self , response , scraper_config ) :
"""Parse the MetricFamily from a valid requests . Response object to provide a MetricFamily object ( see [ 0 ] )
The text format uses iter _ lines ( ) generator .
: param response : requests . Response
: return : core . Metric""" | input_gen = response . iter_lines ( chunk_size = self . REQUESTS_CHUNK_SIZE , decode_unicode = True )
if scraper_config [ '_text_filter_blacklist' ] :
input_gen = self . _text_filter_input ( input_gen , scraper_config )
for metric in text_fd_to_metric_families ( input_gen ) :
metric . type = scraper_config [ 't... |
def server_poweroff ( host = None , admin_username = None , admin_password = None , module = None ) :
'''Powers down the managed server .
host
The chassis host .
admin _ username
The username used to access the chassis .
admin _ password
The password used to access the chassis .
module
The element t... | return __execute_cmd ( 'serveraction powerdown' , host = host , admin_username = admin_username , admin_password = admin_password , module = module ) |
def get_plist_data_from_string ( data ) :
"""Parse plist data for a string . Tries biplist , falling back to
plistlib .""" | if has_biplist :
return biplist . readPlistFromString ( data )
# fall back to normal plistlist
try :
return plistlib . readPlistFromString ( data )
except Exception : # not parseable ( eg . not well - formed , or binary )
return { } |
def powernode_data ( self , name : str ) -> Powernode :
"""Return a Powernode object describing the given powernode""" | self . assert_powernode ( name )
contained_nodes = frozenset ( self . nodes_in ( name ) )
return Powernode ( size = len ( contained_nodes ) , contained = frozenset ( self . all_in ( name ) ) , contained_pnodes = frozenset ( self . powernodes_in ( name ) ) , contained_nodes = contained_nodes , ) |
def validate_proof ( proof : List [ Keccak256 ] , root : Keccak256 , leaf_element : Keccak256 ) -> bool :
"""Checks that ` leaf _ element ` was contained in the tree represented by
` merkleroot ` .""" | hash_ = leaf_element
for pair in proof :
hash_ = hash_pair ( hash_ , pair )
return hash_ == root |
def complete_opt ( self , text , line , begidx , endidx ) :
"""Autocomplete for options""" | tokens = line . split ( )
if len ( tokens ) == 1 :
if text :
return
else :
option = ""
else :
option = tokens [ 1 ]
if len ( tokens ) == 1 or ( len ( tokens ) == 2 and text ) :
return [ name [ 4 : ] + " " for name in dir ( self ) if name . startswith ( "opt_" + text ) ]
method = getattr ... |
def _url_chunk_join ( self , * args ) :
"""Join the arguments together to form a predictable URL chunk .""" | # Strip slashes from either side of each path piece .
pathlets = map ( lambda s : s . strip ( '/' ) , args )
# Remove empty pieces .
pathlets = filter ( None , pathlets )
url = '/' . join ( pathlets )
# If this is a directory , add a trailing slash .
if args [ - 1 ] . endswith ( '/' ) :
url = '%s/' % url
return url |
def loadmask ( self , filename : str ) -> np . ndarray :
"""Load a mask file .""" | mask = scipy . io . loadmat ( self . find_file ( filename , what = 'mask' ) )
maskkey = [ k for k in mask . keys ( ) if not ( k . startswith ( '_' ) or k . endswith ( '_' ) ) ] [ 0 ]
return mask [ maskkey ] . astype ( np . bool ) |
def create_user ( username , password = None , email = None , first_name = "" , last_name = "" , role = "MEMBER" , login_method = None ) :
"""Create a new user
: param username :
: param password :
: param email :
: param first _ name :
: param last _ name :
: param role : str
: return : AuthUser""" | if not login_method :
login_method = "email" if "@" in username else "username"
def cb ( ) :
return _user ( models . AuthUser . new ( username = username , password = password , email = email , first_name = first_name , last_name = last_name , login_method = login_method , role = role ) )
return signals . creat... |
def main ( self , spin , data ) :
"""The function which uses irc rfc regex to extract
the basic arguments from the msg .""" | data = data . decode ( self . encoding )
field = re . match ( RFC_REG , data )
if not field :
return
prefix = self . extract_prefix ( field . group ( 'prefix' ) )
command = field . group ( 'command' ) . upper ( )
args = self . extract_args ( field . group ( 'arguments' ) )
spawn ( spin , command , * ( prefix + args... |
def wait ( self , timeout : Optional [ float ] = None ) -> None :
"""Makes the current process wait for the signal . If it is closed , it will join the signal ' s queue .
: param timeout :
If this parameter is not ` ` None ` ` , it is taken as a delay at the end of which the process times out , and
stops wait... | if _logger is not None :
self . _log ( INFO , "wait" )
while not self . is_on :
self . _queue . join ( timeout ) |
def forward ( self , X ) :
"""Forward function .
: param X : The input ( batch ) of the model contains word sequences for lstm ,
features and feature weights .
: type X : For word sequences : a list of torch . Tensor pair ( word sequence
and word mask ) of shape ( batch _ size , sequence _ length ) .
For ... | s = X [ : - 2 ]
f = X [ - 2 ]
w = X [ - 1 ]
batch_size = len ( f )
# Generate lstm weight indices
x_idx = self . _cuda ( torch . as_tensor ( np . arange ( 1 , self . settings [ "lstm_dim" ] + 1 ) ) . repeat ( batch_size , 1 ) )
outputs = self . _cuda ( torch . Tensor ( [ ] ) )
# Calculate textual features from LSTMs
fo... |
def orient_import2 ( self , event ) :
"""initialize window to import an AzDip format file into the working directory""" | pmag_menu_dialogs . ImportAzDipFile ( self . parent , self . parent . WD ) |
def _inferSchemaFromList ( self , data , names = None ) :
"""Infer schema from list of Row or tuple .
: param data : list of Row or tuple
: param names : list of column names
: return : : class : ` pyspark . sql . types . StructType `""" | if not data :
raise ValueError ( "can not infer schema from empty dataset" )
first = data [ 0 ]
if type ( first ) is dict :
warnings . warn ( "inferring schema from dict is deprecated," "please use pyspark.sql.Row instead" )
schema = reduce ( _merge_type , ( _infer_schema ( row , names ) for row in data ) )
if ... |
async def connect ( url , * , apikey = None , insecure = False ) :
"""Connect to a remote MAAS instance with ` apikey ` .
Returns a new : class : ` Profile ` which has NOT been saved . To connect AND
save a new profile : :
profile = connect ( url , apikey = apikey )
profile = profile . replace ( name = " ma... | url = api_url ( url )
url = urlparse ( url )
if url . username is not None :
raise ConnectError ( "Cannot provide user-name explicitly in URL (%r) when connecting; " "use login instead." % url . username )
if url . password is not None :
raise ConnectError ( "Cannot provide password explicitly in URL (%r) when ... |
def unescape ( s ) :
r"""Inverse of ` escape ` .
> > > unescape ( r ' \ x41 \ n \ x42 \ n \ x43 ' )
' A \ nB \ nC '
> > > unescape ( r ' \ u86c7 ' )
u ' \ u86c7'
> > > unescape ( u ' ah ' )
u ' ah '""" | if re . search ( r'(?<!\\)\\(\\\\)*[uU]' , s ) or isinstance ( s , unicode ) :
return unescapeUnicode ( s )
else :
return unescapeAscii ( s ) |
def identify_missing ( self , df , check_start = True ) :
"""Identify missing data .
Parameters
df : pd . DataFrame ( )
Dataframe to check for missing data .
check _ start : bool
turns 0 to 1 for the first observation , to display the start of the data
as the beginning of the missing data event
Return... | # Check start changes the first value of df to 1 , when the data stream is initially missing
# This allows the diff function to acknowledge the missing data
data_missing = df . isnull ( ) * 1
col_name = str ( data_missing . columns [ 0 ] )
# When there is no data stream at the beginning we change it to 1
if check_start... |
def get_ref_dict ( self , schema ) :
"""Method to create a dictionary containing a JSON reference to the
schema in the spec""" | schema_key = make_schema_key ( schema )
ref_schema = build_reference ( "schema" , self . openapi_version . major , self . refs [ schema_key ] )
if getattr ( schema , "many" , False ) :
return { "type" : "array" , "items" : ref_schema }
return ref_schema |
def get_agents ( ) :
"""Provides a list of hostnames / IPs of all agents in the cluster""" | agent_list = [ ]
agents = __get_all_agents ( )
for agent in agents :
agent_list . append ( agent [ "hostname" ] )
return agent_list |
def generate_message ( directory , m ) :
'''generate per - message header and implementation file''' | f = open ( os . path . join ( directory , 'MVMessage%s.h' % m . name_camel_case ) , mode = 'w' )
t . write ( f , '''
//
// MVMessage${name_camel_case}.h
// MAVLink communications protocol built from ${basename}.xml
//
// Created by mavgen_objc.py
// http://qgroundcontrol.org/mavlink
//
#import "MVMessage.h"
/*!
... |
def _concat ( self , data ) :
"""Concatenate and slice the accepted data types to the defined
length .""" | if isinstance ( data , np . ndarray ) :
data_length = len ( data )
if data_length < self . length :
prev_chunk = self . data [ - ( self . length - data_length ) : ]
data = np . concatenate ( [ prev_chunk , data ] )
elif data_length > self . length :
data = data [ - self . length : ]
... |
def purge_archived_resources ( user , table ) :
"""Remove the entries to be purged from the database .""" | if user . is_not_super_admin ( ) :
raise dci_exc . Unauthorized ( )
where_clause = sql . and_ ( table . c . state == 'archived' )
query = table . delete ( ) . where ( where_clause )
flask . g . db_conn . execute ( query )
return flask . Response ( None , 204 , content_type = 'application/json' ) |
def get_pillar ( opts , grains , minion_id , saltenv = None , ext = None , funcs = None , pillar_override = None , pillarenv = None , extra_minion_data = None ) :
'''Return the correct pillar driver based on the file _ client option''' | file_client = opts [ 'file_client' ]
if opts . get ( 'master_type' ) == 'disable' and file_client == 'remote' :
file_client = 'local'
ptype = { 'remote' : RemotePillar , 'local' : Pillar } . get ( file_client , Pillar )
# If local pillar and we ' re caching , run through the cache system first
log . debug ( 'Determ... |
def delete_repository_tag ( self , project_id , tag_name ) :
"""Deletes a tag of a repository with given name .
: param project _ id : The ID of a project
: param tag _ name : The name of a tag
: return : Dictionary containing delete tag
: raise : HttpError : If invalid response returned""" | return self . delete ( '/projects/{project_id}/repository/tags/{tag_name}' . format ( project_id = project_id , tag_name = tag_name ) ) |
def attach_process ( self , command , for_legion = False , broken_counter = None , pidfile = None , control = None , daemonize = None , touch_reload = None , signal_stop = None , signal_reload = None , honour_stdin = None , uid = None , gid = None , new_pid_ns = None , change_dir = None ) :
"""Attaches a command / ... | rule = KeyValue ( locals ( ) , keys = [ 'command' , 'broken_counter' , 'pidfile' , 'control' , 'daemonize' , 'touch_reload' , 'signal_stop' , 'signal_reload' , 'honour_stdin' , 'uid' , 'gid' , 'new_pid_ns' , 'change_dir' , ] , aliases = { 'command' : 'cmd' , 'broken_counter' : 'freq' , 'touch_reload' : 'touch' , 'signa... |
def add_instance ( self , instance ) :
"""Append ` instance ` to model
Arguments :
instance ( dict ) : Serialised instance
Schema :
instance . json""" | assert isinstance ( instance , dict )
item = defaults [ "common" ] . copy ( )
item . update ( defaults [ "instance" ] )
item . update ( instance [ "data" ] )
item . update ( instance )
item [ "itemType" ] = "instance"
item [ "isToggled" ] = instance [ "data" ] . get ( "publish" , True )
item [ "hasCompatible" ] = True
... |
def timestring ( self , pattern = "%Y-%m-%d %H:%M:%S" , timezone = None ) :
"""Returns a time string .
: param pattern = " % Y - % m - % d % H : % M : % S "
The format used . By default , an ISO - type format is used . The
syntax here is identical to the one used by time . strftime ( ) and
time . strptime (... | if timezone is None :
timezone = self . timezone
timestamp = self . __timestamp__ - timezone
timestamp -= LOCALTZ
return _strftime ( pattern , _gmtime ( timestamp ) ) |
def _get_binop_contexts ( context , left , right ) :
"""Get contexts for binary operations .
This will return two inference contexts , the first one
for x . _ _ op _ _ ( y ) , the other one for y . _ _ rop _ _ ( x ) , where
only the arguments are inversed .""" | # The order is important , since the first one should be
# left . _ _ op _ _ ( right ) .
for arg in ( right , left ) :
new_context = context . clone ( )
new_context . callcontext = contextmod . CallContext ( args = [ arg ] )
new_context . boundnode = None
yield new_context |
def _synthesize_multiple_python ( self , text_file , output_file_path , quit_after = None , backwards = False ) :
"""Synthesize multiple fragments via a Python call .
: rtype : tuple ( result , ( anchors , current _ time , num _ chars ) )""" | self . log ( u"Synthesizing multiple via a Python call..." )
ret = self . _synthesize_multiple_generic ( helper_function = self . _synthesize_single_python_helper , text_file = text_file , output_file_path = output_file_path , quit_after = quit_after , backwards = backwards )
self . log ( u"Synthesizing multiple via a ... |
def namespace_from_url ( url ) :
"""Construct a dotted namespace string from a URL .""" | parsed = urlparse ( url )
if parsed . hostname is None or parsed . hostname in [ 'localhost' , 'localhost.localdomain' ] or ( _ipv4_re . search ( parsed . hostname ) ) :
return None
namespace = parsed . hostname . split ( '.' )
namespace . reverse ( )
if namespace and not namespace [ 0 ] :
namespace . pop ( 0 )... |
def visit_Assignment ( self , node ) :
"""Visitor for ` Assignment ` AST node .""" | obj_memory = self . memory [ node . left . identifier . name ]
obj_program = self . visit ( node . right )
if obj_memory is not None :
obj_program_value = obj_program . value
obj_program = obj_memory
obj_program . value = obj_program_value
self . memory [ node . left . identifier . name ] = obj_program |
def chi_perp_from_mass1_mass2_xi2 ( mass1 , mass2 , xi2 ) :
"""Returns the in - plane spin from mass1 , mass2 , and xi2 for the
secondary mass .""" | q = q_from_mass1_mass2 ( mass1 , mass2 )
a1 = 2 + 3 * q / 2
a2 = 2 + 3 / ( 2 * q )
return q ** 2 * a2 / a1 * xi2 |
def connect_head_node_proxy_with_path ( self , name , path , ** kwargs ) : # noqa : E501
"""connect _ head _ node _ proxy _ with _ path # noqa : E501
connect HEAD requests to proxy of Node # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pas... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . connect_head_node_proxy_with_path_with_http_info ( name , path , ** kwargs )
# noqa : E501
else :
( data ) = self . connect_head_node_proxy_with_path_with_http_info ( name , path , ** kwargs )
# noqa : E501
re... |
def get_scoped_package_version_metadata_from_recycle_bin ( self , feed_id , package_scope , unscoped_package_name , package_version ) :
"""GetScopedPackageVersionMetadataFromRecycleBin .
[ Preview API ] Get information about a scoped package version in the recycle bin .
: param str feed _ id : Name or ID of the... | route_values = { }
if feed_id is not None :
route_values [ 'feedId' ] = self . _serialize . url ( 'feed_id' , feed_id , 'str' )
if package_scope is not None :
route_values [ 'packageScope' ] = self . _serialize . url ( 'package_scope' , package_scope , 'str' )
if unscoped_package_name is not None :
route_va... |
def get_locale ( ) :
"""Search the default platform locale and norm it .
@ returns ( locale , encoding )
@ rtype ( string , string )""" | try :
loc , encoding = locale . getdefaultlocale ( )
except ValueError : # locale configuration is broken - ignore that
loc , encoding = None , None
if loc is None :
loc = "C"
else :
loc = norm_locale ( loc )
if encoding is None :
encoding = "ascii"
return ( loc , encoding ) |
def build_layers ( node , disambiguate_names = True ) :
"""Return a list of GeoJSON FeatureCollections , one for each folder in the given KML DOM node that contains geodata .
Name each FeatureCollection ( via a ` ` ' name ' ` ` attribute ) according to its corresponding KML folder name .
If ` ` disambiguate _ n... | layers = [ ]
names = [ ]
for i , folder in enumerate ( get ( node , 'Folder' ) ) :
name = val ( get1 ( folder , 'name' ) )
geojson = build_feature_collection ( folder , name )
if geojson [ 'features' ] :
layers . append ( geojson )
names . append ( name )
if not layers : # No folders , so us... |
def run_command_line ( args = None ) :
"""Entry point for the FlowCal and flowcal console scripts .
Parameters
args : list of strings , optional
Command line arguments . If None or not specified , get arguments
from ` ` sys . argv ` ` .
See Also
FlowCal . excel _ ui . run ( )
http : / / amir . rachum ... | # Get arguments from ` ` sys . argv ` ` if necessary .
# ` ` sys . argv ` ` has the name of the script as its first element . We remove
# this element because it will break ` ` parser . parse _ args ( ) ` ` later . In fact ,
# ` ` parser . parse _ args ( ) ` ` , if provided with no arguments , will also use
# ` ` sys .... |
def extract_bugs ( changelog ) :
"""Takes output from git log - - oneline and extracts bug numbers""" | bug_regexp = re . compile ( r'\bbug (\d+)\b' , re . IGNORECASE )
bugs = set ( )
for line in changelog :
for bug in bug_regexp . findall ( line ) :
bugs . add ( bug )
return sorted ( list ( bugs ) ) |
def _bca ( ab_estimates , sample_point , n_boot , alpha = 0.05 ) :
"""Get ( 1 - alpha ) * 100 bias - corrected confidence interval estimate
Note that this is similar to the " cper " module implemented in
: py : func : ` pingouin . compute _ bootci ` .
Parameters
ab _ estimates : 1d array - like
Array with... | # Bias of bootstrap estimates
z0 = norm . ppf ( np . sum ( ab_estimates < sample_point ) / n_boot )
# Adjusted intervals
adjusted_ll = norm . cdf ( 2 * z0 + norm . ppf ( alpha / 2 ) ) * 100
adjusted_ul = norm . cdf ( 2 * z0 + norm . ppf ( 1 - alpha / 2 ) ) * 100
ll = np . percentile ( ab_estimates , q = adjusted_ll )
u... |
def community_topic_subscription_create ( self , topic_id , data , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / help _ center / subscriptions # create - topic - subscription" | api_path = "/api/v2/community/topics/{topic_id}/subscriptions.json"
api_path = api_path . format ( topic_id = topic_id )
return self . call ( api_path , method = "POST" , data = data , ** kwargs ) |
def user ( self , ** params ) :
"""Stream user
Accepted params found at :
https : / / dev . twitter . com / docs / api / 1.1 / get / user""" | url = 'https://userstream.twitter.com/%s/user.json' % self . streamer . api_version
self . streamer . _request ( url , params = params ) |
def poll_integration_information_for_waiting_integration_alerts ( ) :
"""poll _ integration _ information _ for _ waiting _ integration _ alerts .""" | if not polling_integration_alerts :
return
logger . debug ( "Polling information for waiting integration alerts" )
for integration_alert in polling_integration_alerts :
configured_integration = integration_alert . configured_integration
integration = configured_integration . integration
polling_duration... |
def rosmsg ( self ) :
""": obj : ` sensor _ msgs . CamerInfo ` : Returns ROS CamerInfo msg""" | from sensor_msgs . msg import CameraInfo , RegionOfInterest
from std_msgs . msg import Header
msg_header = Header ( )
msg_header . frame_id = self . _frame
msg_roi = RegionOfInterest ( )
msg_roi . x_offset = 0
msg_roi . y_offset = 0
msg_roi . height = 0
msg_roi . width = 0
msg_roi . do_rectify = 0
msg = CameraInfo ( )
... |
def parse ( source , segmenter = 'nlapi' , language = None , max_length = None , classname = None , attributes = None , ** kwargs ) :
"""Parses input source .
Args :
source ( str ) : Input source to process .
segmenter ( : obj : ` str ` , optional ) : Segmenter to use [ default : nlapi ] .
language ( : obj ... | parser = get_parser ( segmenter , ** kwargs )
return parser . parse ( source , language = language , max_length = max_length , classname = classname , attributes = attributes ) |
def AddrStrToScriptHash ( address ) :
"""Convert a public address to a script hash .
Args :
address ( str ) : base 58 check encoded public address .
Raises :
ValueError : if the address length of address version is incorrect .
Exception : if the address checksum fails .
Returns :
UInt160:""" | data = b58decode ( address )
if len ( data ) != 25 :
raise ValueError ( 'Not correct Address, wrong length.' )
if data [ 0 ] != settings . ADDRESS_VERSION :
raise ValueError ( 'Not correct Coin Version' )
checksum = Crypto . Default ( ) . Hash256 ( data [ : 21 ] ) [ : 4 ]
if checksum != data [ 21 : ] :
rais... |
def ListDescendentPathInfos ( self , client_id , path_type , components , timestamp = None , max_depth = None , cursor = None ) :
"""Lists path info records that correspond to descendants of given path .""" | path_infos = [ ]
query = ""
path = mysql_utils . ComponentsToPath ( components )
values = { "client_id" : db_utils . ClientIDToInt ( client_id ) , "path_type" : int ( path_type ) , "path" : db_utils . EscapeWildcards ( path ) , }
query += """
SELECT path, directory, UNIX_TIMESTAMP(p.timestamp),
stat_entr... |
def experimental ( name = None ) :
"""A simple decorator to mark functions and methods as experimental .""" | def inner ( func ) :
@ functools . wraps ( func )
def wrapper ( * fargs , ** kw ) :
fname = name
if name is None :
fname = func . __name__
warnings . warn ( "%s" % fname , category = ExperimentalWarning , stacklevel = 2 )
return func ( * fargs , ** kw )
return wra... |
def transform ( self , transform , node ) :
"""Transforms a node following the transform especification
: param transform : Transform node
: type transform : lxml . etree . Element
: param node : Element to transform
: type node : str
: return : Transformed node in a String""" | method = transform . get ( 'Algorithm' )
if method not in constants . TransformUsageDSigTransform :
raise Exception ( 'Method not allowed' )
# C14N methods are allowed
if method in constants . TransformUsageC14NMethod :
return self . canonicalization ( method , etree . fromstring ( node ) )
# Enveloped method r... |
def as_dict ( self ) :
"""Return a dictionary containing the current values
of the object .
Returns :
( dict ) : The object represented as a dictionary""" | out = { }
for prop in self :
propval = getattr ( self , prop )
if hasattr ( propval , 'for_json' ) :
out [ prop ] = propval . for_json ( )
elif isinstance ( propval , list ) :
out [ prop ] = [ getattr ( x , 'for_json' , lambda : x ) ( ) for x in propval ]
elif isinstance ( propval , ( Pr... |
def _create_PmtInf_node ( self ) :
"""Method to create the blank payment information nodes as a dict .""" | ED = dict ( )
# ED is element dict
ED [ 'PmtInfNode' ] = ET . Element ( "PmtInf" )
ED [ 'PmtInfIdNode' ] = ET . Element ( "PmtInfId" )
ED [ 'PmtMtdNode' ] = ET . Element ( "PmtMtd" )
ED [ 'BtchBookgNode' ] = ET . Element ( "BtchBookg" )
ED [ 'NbOfTxsNode' ] = ET . Element ( "NbOfTxs" )
ED [ 'CtrlSumNode' ] = ET . Eleme... |
def CallState ( self , next_state = "" , start_time = None ) :
"""This method is used to schedule a new state on a different worker .
This is basically the same as CallFlow ( ) except we are calling
ourselves . The state will be invoked at a later time .
Args :
next _ state : The state in this flow to be in... | # Check if the state is valid
if not getattr ( self . flow_obj , next_state ) :
raise FlowRunnerError ( "Next state %s is invalid." % next_state )
# Queue the response message to the parent flow
request_state = rdf_flow_runner . RequestState ( id = self . GetNextOutboundId ( ) , session_id = self . context . sessio... |
def get_tag ( expnum , key ) :
"""given a key , return the vospace tag value .
@ param expnum : Number of the CFHT exposure that a tag value is needed for
@ param key : The process tag ( such as mkpsf _ 00 ) that is being looked up .
@ return : the value of the tag
@ rtype : str""" | uri = tag_uri ( key )
force = uri not in get_tags ( expnum )
value = get_tags ( expnum , force = force ) . get ( uri , None )
return value |
def add ( TargetGroup , NewMember , Config = None , Args = None ) :
r"""Adds members to an existing group .
Args :
TargetGroup ( Group ) : The target group for the addition .
NewMember ( Group / Task ) : The member to be added .
Config ( dict ) : The config for the member .
Args ( OrderedDict ) : ArgConfi... | Member = Task ( NewMember , Args or { } , Config or { } ) if isfunction ( NewMember ) else Group ( NewMember , Config or { } )
ParentMembers = TargetGroup . __ec_member__ . Members
ParentMembers [ Member . Config [ 'name' ] ] = Member
alias = Member . Config . get ( 'alias' )
if alias :
ParentMembers [ alias ] = Me... |
def ppaged ( self , msg : str , end : str = '\n' , chop : bool = False ) -> None :
"""Print output using a pager if it would go off screen and stdout isn ' t currently being redirected .
Never uses a pager inside of a script ( Python or text ) or when output is being redirected or piped or when
stdout or stdin ... | import subprocess
if msg is not None and msg != '' :
try :
msg_str = '{}' . format ( msg )
if not msg_str . endswith ( end ) :
msg_str += end
# Attempt to detect if we are not running within a fully functional terminal .
# Don ' t try to use the pager when being run by a ... |
def aggregate ( self , rankings , breaking = "full" , k = None ) :
"""Description :
Takes in a set of rankings and computes the
Plackett - Luce model aggregate ranking .
Parameters :
rankings : set of rankings to aggregate
breaking : type of breaking to use
k : number to be used for top , bottom , and p... | breakings = { "full" : self . _full , "top" : self . _top , "bottom" : self . _bot , "adjacent" : self . _adj , "position" : self . _pos }
if ( k == None and ( breaking != "full" != breaking != "position" ) ) :
raise ValueError ( "k cannot be None for non-full or non-position breaking" )
break_mat = breakings [ bre... |
def inverse_transform ( self , X , copy = None ) :
"""Scale back the data to the original representation .
: param X : Scaled data matrix .
: type X : numpy . ndarray , shape [ n _ samples , n _ features ]
: param bool copy : Copy the X data matrix .
: return : X data matrix with the scaling operation rever... | check_is_fitted ( self , 'scale_' )
copy = copy if copy is not None else self . copy
if sparse . issparse ( X ) :
if self . with_mean :
raise ValueError ( "Cannot uncenter sparse matrices: pass `with_mean=False` " "instead See docstring for motivation and alternatives." )
if not sparse . isspmatrix_csr ... |
def _is_dst ( dt ) :
"""Returns True if a given datetime object represents a time with
DST shift .""" | # we can ' t use ` dt . timestamp ( ) ` here since it requires a ` utcoffset `
# and we don ' t want to get into a recursive loop
localtime = time . localtime ( time . mktime ( ( dt . year , dt . month , dt . day , dt . hour , dt . minute , dt . second , dt . weekday ( ) , 0 , # day of the year
- 1 # dst
) ) )
return l... |
def prune_by_missing_percent ( df , percentage = 0.4 ) :
"""The method to remove the attributes ( genes ) with more than a percentage of missing values
: param df : the dataframe containing the attributes to be pruned
: param percentage : the percentage threshold ( 0.4 by default )
: return : the pruned dataf... | mask = ( df . isnull ( ) . sum ( ) / df . shape [ 0 ] ) . map ( lambda x : True if x < percentage else False )
pruned_df = df [ df . columns [ mask . values ] ]
return pruned_df |
def from_json ( cls , data , json_schema_class = None ) :
"""This class overwrites the from _ json method , thus making sure that if ` from _ json ` is called from this class instance , it will provide its JSON schema as a default one""" | schema = cls . json_schema if json_schema_class is None else json_schema_class ( )
return super ( InfinityVertex , cls ) . from_json ( data = data , json_schema_class = schema . __class__ ) |
def __create ( self , short_description , period , ** kwargs ) :
"""Call documentation : ` / preapproval / create
< https : / / www . wepay . com / developer / reference / preapproval # create > ` _ , plus
extra keyword parameters :
: keyword str access _ token : will be used instead of instance ' s
` ` acc... | params = { 'short_description' : short_description , 'period' : period }
return self . make_call ( self . __create , params , kwargs ) |
def defaults ( self ) :
"""Return default metadata .""" | return dict ( access_right = 'open' , description = self . description , license = 'other-open' , publication_date = self . release [ 'published_at' ] [ : 10 ] , related_identifiers = list ( self . related_identifiers ) , version = self . version , title = self . title , upload_type = 'software' , ) |
def roots ( self ) :
"""Utilises Boyd ' s O ( n ^ 2 ) recursive subdivision algorithm . The chebfun
is recursively subsampled until it is successfully represented to
machine precision by a sequence of piecewise interpolants of degree
100 or less . A colleague matrix eigenvalue solve is then applied to
each ... | if self . size ( ) == 1 :
return np . array ( [ ] )
elif self . size ( ) <= 100 :
ak = self . coefficients ( )
v = np . zeros_like ( ak [ : - 1 ] )
v [ 1 ] = 0.5
C1 = linalg . toeplitz ( v )
C2 = np . zeros_like ( C1 )
C1 [ 0 , 1 ] = 1.
C2 [ - 1 , : ] = ak [ : - 1 ]
C = C1 - .5 / ak ... |
def render_heading ( self , token ) :
"""Overrides super ( ) . render _ heading ; stores rendered heading first ,
then returns it .""" | rendered = super ( ) . render_heading ( token )
content = self . parse_rendered_heading ( rendered )
if not ( self . omit_title and token . level == 1 or token . level > self . depth or any ( cond ( content ) for cond in self . filter_conds ) ) :
self . _headings . append ( ( token . level , content ) )
return rend... |
def dayofyear ( self ) :
"""Day of the year index ( the first of January = 0 . . . ) .
For reasons of consistency between leap years and non - leap years ,
assuming a daily time step , index 59 is always associated with the
29th of February . Hence , it is missing in non - leap years :
> > > from hydpy impo... | def _dayofyear ( date ) :
return ( date . dayofyear - 1 + ( ( date . month > 2 ) and ( not date . leapyear ) ) )
return _dayofyear |
def _long2bytes ( n , blocksize = 0 ) :
"""Convert a long integer to a byte string .
If optional blocksize is given and greater than zero , pad the front
of the byte string with binary zeros so that the length is a multiple
of blocksize .""" | # After much testing , this algorithm was deemed to be the fastest .
s = ''
pack = struct . pack
while n > 0 : # # # CHANGED FROM ' > I ' TO ' < I ' . ( DCG )
s = pack ( '<I' , n & 0xffffffffL ) + s
n = n >> 32
# Strip off leading zeros .
for i in range ( len ( s ) ) :
if s [ i ] <> '\000' :
break
e... |
def render_markdown ( text , context = None ) :
"""Turn markdown into HTML .""" | if context is None or not isinstance ( context , dict ) :
context = { }
markdown_html = _transform_markdown_into_html ( text )
sanitised_markdown_html = _sanitise_markdown_html ( markdown_html )
return mark_safe ( sanitised_markdown_html ) |
def _shrink ( v , gamma ) :
"""Soft - shrinkage of an array with parameter gamma .
Parameters
v : array
Array containing the values to be applied to the shrinkage operator
gamma : float
Shrinkage parameter .
Returns
v : array
The same input array after the shrinkage operator was applied .""" | pos = v > gamma
neg = v < - gamma
v [ pos ] -= gamma
v [ neg ] += gamma
v [ np . logical_and ( ~ pos , ~ neg ) ] = .0
return v |
def create_document ( self , doc : Dict , mime_type : str = None , url : str = "http://ex.com/123" , doc_id = None , type_ = None ) -> Document :
"""Factory method to wrap input JSON docs in an ETK Document object .
Args :
doc ( object ) : a JSON object containing a document in CDR format .
mime _ type ( str ... | return Document ( self , doc , mime_type , url , doc_id = doc_id ) . with_type ( type_ ) |
def check_rotation ( rotation ) :
"""checks rotation parameter if illegal value raises exception""" | if rotation not in ALLOWED_ROTATION :
allowed_rotation = ', ' . join ( ALLOWED_ROTATION )
raise UnsupportedRotation ( 'Rotation %s is not allwoed. Allowed are %s' % ( rotation , allowed_rotation ) ) |
def build_gtapp ( appname , dry_run , ** kwargs ) :
"""Build an object that can run ScienceTools application
Parameters
appname : str
Name of the application ( e . g . , gtbin )
dry _ run : bool
Print command but do not run it
kwargs : arguments used to invoke the application
Returns ` GtApp . GtApp `... | pfiles_orig = _set_pfiles ( dry_run , ** kwargs )
gtapp = GtApp . GtApp ( appname )
update_gtapp ( gtapp , ** kwargs )
_reset_pfiles ( pfiles_orig )
return gtapp |
def bundle ( self , ref , capture_exceptions = False ) :
"""Return a bundle build on a dataset , with the given vid or id reference""" | from . . orm . exc import NotFoundError
if isinstance ( ref , Dataset ) :
ds = ref
else :
try :
ds = self . _db . dataset ( ref )
except NotFoundError :
ds = None
if not ds :
try :
p = self . partition ( ref )
ds = p . _bundle . dataset
except NotFoundError :
... |
def find_adsorption_sites ( self , distance = 2.0 , put_inside = True , symm_reduce = 1e-2 , near_reduce = 1e-2 , positions = [ 'ontop' , 'bridge' , 'hollow' ] , no_obtuse_hollow = True ) :
"""Finds surface sites according to the above algorithm . Returns
a list of corresponding cartesian coordinates .
Args :
... | ads_sites = { k : [ ] for k in positions }
if 'ontop' in positions :
ads_sites [ 'ontop' ] = [ s . coords for s in self . surface_sites ]
if 'subsurface' in positions : # Get highest site
ref = self . slab . sites [ np . argmax ( self . slab . cart_coords [ : , 2 ] ) ]
# Project diff between highest site an... |
def escape_dictionary ( dictionary , datetime_format = '%Y-%m-%d %H:%M:%S' ) :
"""Escape dictionary values with keys as column names and values column values
@ type dictionary : dict
@ param dictionary : Key - values""" | for k , v in dictionary . iteritems ( ) :
if isinstance ( v , datetime . datetime ) :
v = v . strftime ( datetime_format )
if isinstance ( v , basestring ) :
v = CoyoteDb . db_escape ( str ( v ) )
v = '"{}"' . format ( v )
if v is True :
v = 1
if v is False :
v = ... |
def set_position ( self , pos , which = 'both' ) :
"""Identical to Axes . set _ position ( This docstring is overwritten ) .""" | self . _polar . set_position ( pos , which )
if self . _overlay_axes is not None :
self . _overlay_axes . set_position ( pos , which )
LambertAxes . set_position ( self , pos , which ) |
def add_link_headers ( response , links ) :
"""Return * response * with the proper link headers set , based on the contents
of * links * .
: param response : : class : ` flask . Response ` response object for links to be
added
: param dict links : Dictionary of links to be added
: rtype : class : ` flask ... | link_string = '<{}>; rel=self' . format ( links [ 'self' ] )
for link in links . values ( ) :
link_string += ', <{}>; rel=related' . format ( link )
response . headers [ 'Link' ] = link_string
return response |
def apply_security_groups ( name , security_groups , region = None , key = None , keyid = None , profile = None ) :
'''Apply security groups to ELB .
CLI example :
. . code - block : : bash
salt myminion boto _ elb . apply _ security _ groups myelb ' [ " mysecgroup1 " ] ' ''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
if isinstance ( security_groups , six . string_types ) :
security_groups = salt . utils . json . loads ( security_groups )
try :
conn . apply_security_groups_to_lb ( name , security_groups )
log . info ( 'Applied security_g... |
def remove ( self ) :
"""todo : Docstring for remove
: return :
: rtype :""" | logger . debug ( "" )
rd = self . repo_dir
logger . debug ( "pkg path %s" , rd )
if not rd :
print ( "unable to find pkg '%s'. %s" % ( self . name , did_u_mean ( self . name ) ) )
return
# Does the repo have any uncommitted changes ?
# Is the repo out of sync ( needs a push ? )
# Are you sure ?
resp = input ( s... |
def __learn_labels ( self , labels ) :
"""Learns new labels , this method is intended for internal use
Args :
labels ( : obj : ` list ` of : obj : ` str ` ) : Labels to learn""" | if self . feature_length > 0 :
result = list ( self . labels . classes_ )
else :
result = [ ]
for label in labels :
result . append ( label )
self . labels . fit ( result ) |
def upload_process_reach_files ( output_dir , pmid_info_dict , reader_version , num_cores ) : # At this point , we have a directory full of JSON files
# Collect all the prefixes into a set , then iterate over the prefixes
# Collect prefixes
json_files = glob . glob ( os . path . join ( output_dir , '*.json' ) )
... | return stmts_by_pmid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.