signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get ( self , resource , operation_timeout = None , max_envelope_size = None , locale = None ) :
"""resource can be a URL or a ResourceLocator""" | if isinstance ( resource , str ) :
resource = ResourceLocator ( resource )
headers = self . _build_headers ( resource , Session . GetAction , operation_timeout , max_envelope_size , locale )
self . service . invoke . set_options ( tsoapheaders = headers )
return self . service . invoke |
def build ( python = PYTHON ) :
"""Build the bigfloat library for in - place testing .""" | clean ( )
local ( "LIBRARY_PATH={library_path} CPATH={include_path} {python} " "setup.py build_ext --inplace" . format ( library_path = LIBRARY_PATH , include_path = INCLUDE_PATH , python = python , ) ) |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'name' ) and self . name is not None :
_dict [ 'name' ] = self . name
if hasattr ( self , 'description' ) and self . description is not None :
_dict [ 'description' ] = self . description
if hasattr ( self , 'language' ) and self . language is not None :
_dict [ 'language' ] ... |
def delete ( cls , mp , part_number ) :
"""Get part number .""" | return cls . query . filter_by ( upload_id = mp . upload_id , part_number = part_number ) . delete ( ) |
def _entry_must_exist ( df , k1 , k2 ) :
"""Evaluate key - subkey existence .
Checks that the key - subkey combo exists in the
configuration options .""" | count = df [ ( df [ 'k1' ] == k1 ) & ( df [ 'k2' ] == k2 ) ] . shape [ 0 ]
if count == 0 :
raise NotRegisteredError ( "Option {0}.{1} not registered" . format ( k1 , k2 ) ) |
def is_up_url ( url , allow_redirects = False , timeout = 5 ) :
r"""Check URL to see if it is a valid web page , return the redirected location if it is
Returns :
None if ConnectionError
False if url is invalid ( any HTTP error code )
cleaned up URL ( following redirects and possibly adding HTTP schema " ht... | if not isinstance ( url , basestring ) or '.' not in url :
return False
normalized_url = prepend_http ( url )
session = requests . Session ( )
session . mount ( url , HTTPAdapter ( max_retries = 2 ) )
try :
resp = session . get ( normalized_url , allow_redirects = allow_redirects , timeout = timeout )
except Co... |
def do_where ( virtualenv = False , bare = True ) :
"""Executes the where functionality .""" | if not virtualenv :
if not project . pipfile_exists :
click . echo ( "No Pipfile present at project home. Consider running " "{0} first to automatically generate a Pipfile for you." "" . format ( crayons . green ( "`pipenv install`" ) ) , err = True , )
return
location = project . pipfile_locati... |
def add_route ( self , handler , uri , methods = frozenset ( { 'GET' } ) , host = None , strict_slashes = False ) :
"""Create a blueprint route from a function .
: param handler : function for handling uri requests . Accepts function ,
or class instance with a view _ class method .
: param uri : endpoint at w... | # Handle HTTPMethodView differently
if hasattr ( handler , 'view_class' ) :
http_methods = ( 'GET' , 'POST' , 'PUT' , 'HEAD' , 'OPTIONS' , 'PATCH' , 'DELETE' )
methods = set ( )
for method in http_methods :
if getattr ( handler . view_class , method . lower ( ) , None ) :
methods . add (... |
def state ( self ) :
"""Compute and return the device state .
: returns : Device state .""" | # Check if device is disconnected .
if not self . available :
return STATE_UNKNOWN
# Check if device is off .
if not self . screen_on :
return STATE_OFF
# Check if screen saver is on .
if not self . awake :
return STATE_IDLE
# Check if the launcher is active .
if self . launcher or self . settings :
ret... |
def check_permission ( instance , field , permission ) :
"""Check a permission for a given instance or field . Raises an error if
denied .
: param instance : The instance to check
: param field : The field name to check or None for instance
: param permission : The permission to check""" | if not get_permission_test ( instance , field , permission ) ( instance ) :
raise PermissionDeniedError ( permission , instance , instance , field ) |
def to_pb ( self ) :
"""Converts the row filter to a protobuf .
: rtype : : class : ` . data _ v2 _ pb2 . RowFilter `
: returns : The converted current object .""" | interleave = data_v2_pb2 . RowFilter . Interleave ( filters = [ row_filter . to_pb ( ) for row_filter in self . filters ] )
return data_v2_pb2 . RowFilter ( interleave = interleave ) |
def checkGradient ( self , h = 1e-6 , verbose = True ) :
"""utility function to check the gradient of the gp""" | grad_an = self . LMLgrad ( )
grad_num = { }
params0 = self . params . copy ( )
for key in list ( self . params . keys ( ) ) :
paramsL = params0 . copy ( )
paramsR = params0 . copy ( )
grad_num [ key ] = SP . zeros_like ( self . params [ key ] )
e = SP . zeros ( self . params [ key ] . shape [ 0 ] )
... |
def from_dict ( data , ctx ) :
"""Instantiate a new Account from a dict ( generally from loading a JSON
response ) . The data used to instantiate the Account is a shallow copy
of the dict passed in , with any complex child types instantiated
appropriately .""" | data = data . copy ( )
if data . get ( 'balance' ) is not None :
data [ 'balance' ] = ctx . convert_decimal_number ( data . get ( 'balance' ) )
if data . get ( 'pl' ) is not None :
data [ 'pl' ] = ctx . convert_decimal_number ( data . get ( 'pl' ) )
if data . get ( 'resettablePL' ) is not None :
data [ 'res... |
async def delete ( self , request , resource = None , ** kwargs ) :
"""Delete a resource .
Supports batch delete .""" | if resource :
resources = [ resource ]
else :
data = await self . parse ( request )
if data :
resources = list ( self . collection . where ( self . meta . model_pk << data ) )
if not resources :
raise RESTNotFound ( reason = 'Resource not found' )
for resource in resources :
resource . delet... |
def yang_modules ( self ) :
"""Return a list of advertised YANG module names with revisions .
Avoid repeated modules .""" | res = { }
for c in self . capabilities :
m = c . parameters . get ( "module" )
if m is None or m in res :
continue
res [ m ] = c . parameters . get ( "revision" )
return res . items ( ) |
def count_indents ( self , spacecount , tabs = 0 , offset = 0 ) :
"""Counts the number of indents that can be tabs or spacecount
number of spaces in a row from the current line .""" | if not self . has_space ( offset = offset ) :
return 0
spaces = 0
indents = 0
for char in self . string [ self . pos + offset - self . col : ] :
if char == ' ' :
spaces += 1
elif tabs and char == '\t' :
indents += 1
spaces = 0
else :
break
if spaces == spacecount :
... |
def push_build ( id , tag_prefix ) :
"""Push build to Brew""" | req = swagger_client . BuildRecordPushRequestRest ( )
req . tag_prefix = tag_prefix
req . build_record_id = id
response = utils . checked_api_call ( pnc_api . build_push , 'push' , body = req )
if response :
return utils . format_json_list ( response ) |
def merge_batches ( self , data ) :
"""Merge a list of data minibatches into one single instance representing the data
Parameters
data : list
List of minibatches to merge
Returns
( anonymous ) : sparse matrix | pd . DataFrame | list
Single complete list - like data merged from given batches""" | if isinstance ( data [ 0 ] , ssp . csr_matrix ) :
return ssp . vstack ( data )
if isinstance ( data [ 0 ] , pd . DataFrame ) or isinstance ( data [ 0 ] , pd . Series ) :
return pd . concat ( data )
return [ item for sublist in data for item in sublist ] |
def com_google_fonts_check_metadata_os2_weightclass ( ttFont , font_metadata ) :
"""Checking OS / 2 usWeightClass matches weight specified at METADATA . pb .""" | # Weight name to value mapping :
GF_API_WEIGHT_NAMES = { 250 : "Thin" , 275 : "ExtraLight" , 300 : "Light" , 400 : "Regular" , 500 : "Medium" , 600 : "SemiBold" , 700 : "Bold" , 800 : "ExtraBold" , 900 : "Black" }
CSS_WEIGHT_NAMES = { 100 : "Thin" , 200 : "ExtraLight" , 300 : "Light" , 400 : "Regular" , 500 : "Medium" ... |
def clear_sonos_playlist ( self , sonos_playlist , update_id = 0 ) :
"""Clear all tracks from a Sonos playlist .
This is a convenience method for : py : meth : ` reorder _ sonos _ playlist ` .
Example : :
device . clear _ sonos _ playlist ( sonos _ playlist )
Args :
sonos _ playlist
( : py : class : ` ~... | if not isinstance ( sonos_playlist , DidlPlaylistContainer ) :
sonos_playlist = self . get_sonos_playlist_by_attr ( 'item_id' , sonos_playlist )
count = self . music_library . browse ( ml_item = sonos_playlist ) . total_matches
tracks = ',' . join ( [ str ( x ) for x in range ( count ) ] )
if tracks :
return se... |
def list_assets_ddo ( self ) :
"""List all the ddos registered in the aquarius instance .
: return : List of DDO instance""" | return json . loads ( self . requests_session . get ( self . url ) . content ) |
def _get_fs ( thin_pathname ) :
"""Returns the file system type ( xfs , ext4 ) of a given device""" | cmd = [ 'lsblk' , '-o' , 'FSTYPE' , '-n' , thin_pathname ]
fs_return = util . subp ( cmd )
return fs_return . stdout . strip ( ) |
def show ( ctx ) :
"""Show migrations list""" | for app_name , app in ctx . obj [ 'config' ] [ 'apps' ] . items ( ) :
click . echo ( click . style ( app_name , fg = 'green' , bold = True ) )
for migration in app [ 'migrations' ] :
applied = ctx . obj [ 'db' ] . is_migration_applied ( app_name , migration )
click . echo ( ' {0} {1}' . format ... |
def select_groups ( adata , groups = 'all' , key = 'louvain' ) :
"""Get subset of groups in adata . obs [ key ] .""" | strings_to_categoricals ( adata )
if isinstance ( groups , list ) and isinstance ( groups [ 0 ] , int ) :
groups = [ str ( n ) for n in groups ]
categories = adata . obs [ key ] . cat . categories
groups_masks = np . array ( [ categories [ i ] == adata . obs [ key ] . values for i , name in enumerate ( categories )... |
def get_tty_password ( confirm ) :
"""When returning a password from a TTY we assume a user
is entering it on a keyboard so we ask for confirmation .""" | LOG . debug ( "Reading password from TTY" )
new_password = getpass ( 'Enter Password: ' , stream = sys . stderr )
if not new_password :
raise aomi . exceptions . AomiCommand ( "Must specify a password" )
if not confirm :
return new_password
confirm_password = getpass ( 'Again, Please: ' , stream = sys . stderr ... |
def modified_recipes ( branch = 'origin/master' ) :
"""Returns a set of modified recipes between the current branch and the one
in param .""" | # using the contrib version on purpose rather than sh . git , since it comes
# with a bunch of fixes , e . g . disabled TTY , see :
# https : / / stackoverflow . com / a / 20128598/185510
git_diff = sh . contrib . git . diff ( '--name-only' , branch )
recipes = set ( )
for file_path in git_diff :
if 'pythonforandro... |
def usearch_qf ( fasta_filepath , refseqs_fp = None , output_dir = None , percent_id = 0.97 , percent_id_err = 0.97 , minsize = 4 , abundance_skew = 2.0 , db_filepath = None , rev = False , label_prefix = "" , label_suffix = "" , retain_label_as_comment = False , count_start = 0 , perc_id_blast = 0.97 , save_intermedia... | # Save a list of intermediate filepaths in case they are to be removed .
intermediate_files = [ ]
# Need absolute paths to avoid problems with app controller
if output_dir :
output_dir = abspath ( output_dir ) + '/'
fasta_filepath = abspath ( fasta_filepath )
try :
if verbose :
print "Sorting sequences ... |
def delete_secret_versions ( self , path , versions , mount_point = DEFAULT_MOUNT_POINT ) :
"""Issue a soft delete of the specified versions of the secret .
This marks the versions as deleted and will stop them from being returned from reads ,
but the underlying data will not be removed . A delete can be undone... | if not isinstance ( versions , list ) or len ( versions ) == 0 :
error_msg = 'argument to "versions" must be a list containing one or more integers, "{versions}" provided.' . format ( versions = versions )
raise exceptions . ParamValidationError ( error_msg )
params = { 'versions' : versions , }
api_path = '/v1... |
def spawn ( self , __groups , __coro_fun , * args , ** kwargs ) :
"""Start a new coroutine and add it to the pool atomically .
: param groups : The groups the coroutine belongs to .
: type groups : : class : ` set ` of group keys
: param coro _ fun : Coroutine function to run
: param args : Positional argum... | # ensure the implicit group is included
__groups = set ( __groups ) | { ( ) }
return asyncio . ensure_future ( __coro_fun ( * args , ** kwargs ) ) |
def update_host ( self , url : URL ) -> None :
"""Update destination host , port and connection type ( ssl ) .""" | # get host / port
if not url . host :
raise InvalidURL ( url )
# basic auth info
username , password = url . user , url . password
if username :
self . auth = helpers . BasicAuth ( username , password or '' ) |
def chunks ( l , n ) :
'''chunk l in n sized bits''' | # http : / / stackoverflow . com / a / 3226719
# . . . not that this is hard to understand .
return [ l [ x : x + n ] for x in range ( 0 , len ( l ) , n ) ] ; |
def main ( ) :
"""parse command line options and either launch some configuration dialog or start an instance of _ MainLoop as a daemon""" | ( options , _ ) = _parse_args ( )
if options . change_password :
c . keyring_set_password ( c [ "username" ] )
sys . exit ( 0 )
if options . select :
courses = client . get_courses ( )
c . selection_dialog ( courses )
c . save ( )
sys . exit ( 0 )
if options . stop :
os . system ( "kill -2 `... |
def url_value_preprocessor ( self , func : Callable , name : AppOrBlueprintKey = None ) -> Callable :
"""Add a url value preprocessor .
This is designed to be used as a decorator . An example usage ,
. . code - block : : python
@ app . url _ value _ preprocessor
def value _ preprocessor ( endpoint , view _ ... | self . url_value_preprocessors [ name ] . append ( func )
return func |
def key ( self , key_id ) :
"""GET / : login / keys / : key
: param key _ id : identifier for an individual key record for the account
: type key _ id : : py : class : ` basestring `
: returns : details of the key
: rtype : : py : class : ` dict `""" | j , _ = self . request ( 'GET' , '/keys/' + str ( key_id ) )
return j |
def urlencode ( query , params ) :
"""Correctly convert the given query and parameters into a full query + query
string , ensuring the order of the params .""" | return query + '?' + "&" . join ( key + '=' + quote_plus ( str ( value ) ) for key , value in params ) |
def get_last_ticker ( self , symbol ) :
"""获取最新的ticker
: param symbol
: return :""" | params = { 'symbol' : symbol }
url = u . MARKET_URL + '/market/trade'
def _wrapper ( _func ) :
@ wraps ( _func )
def handle ( ) :
_func ( http_get_request ( url , params ) )
return handle
return _wrapper |
def clean_tempdir ( context , scenario ) :
"""Clean up temporary test dirs for passed tests .
Leave failed test dirs for manual inspection .""" | tempdir = getattr ( context , 'tempdir' , None )
if tempdir and scenario . status == 'passed' :
shutil . rmtree ( tempdir )
del ( context . tempdir ) |
def put_mapping ( self , doc_type = None , mapping = None , indices = None , ignore_conflicts = None ) :
"""Register specific mapping definition for a specific type against one or more indices .
( See : ref : ` es - guide - reference - api - admin - indices - put - mapping ` )""" | if not isinstance ( mapping , dict ) :
if mapping is None :
mapping = { }
if hasattr ( mapping , "as_dict" ) :
mapping = mapping . as_dict ( )
if doc_type :
path = self . conn . _make_path ( indices , doc_type , "_mapping" )
if doc_type not in mapping :
mapping = { doc_type : map... |
def get_network_ipv4 ( self , id_network ) :
"""Get networkipv4
: param id _ network : Identifier of the Network . Integer value and greater than zero .
: return : Following dictionary :
{ ' network ' : { ' id ' : < id _ networkIpv6 > ,
' network _ type ' : < id _ tipo _ rede > ,
' ambiente _ vip ' : < id... | if not is_valid_int_param ( id_network ) :
raise InvalidParameterError ( u'O id do rede ip4 foi informado incorretamente.' )
url = 'network/ipv4/id/' + str ( id_network ) + '/'
code , xml = self . submit ( None , 'GET' , url )
return self . response ( code , xml ) |
def poll ( self , timeout ) :
""": param float timeout : Timeout in seconds .""" | timeout = float ( timeout )
end_time = time . time ( ) + timeout
while True : # Keep reading until data is received or timeout
incoming = self . stream . read ( self . _max_read )
if incoming :
return incoming
if ( end_time - time . time ( ) ) < 0 :
raise ExpectTimeout ( )
time . sleep (... |
def get ( self ) :
"""Reads the remote file from Gist and save it locally""" | if self . gist :
content = self . github . read_gist_file ( self . gist )
self . local . save ( content ) |
def listen ( self ) :
"""Set up a quick connection . Returns on disconnect .
After calling ` connect ( ) ` , this waits for messages from the server
using ` select ` , and notifies the subscriber of any events .""" | import select
while self . connected :
r , w , e = select . select ( ( self . ws . sock , ) , ( ) , ( ) )
if r :
self . on_message ( )
elif e :
self . subscriber . on_sock_error ( e )
self . disconnect ( ) |
def _format_episode_numbers ( episodenumbers ) :
"""Format episode number ( s ) into string , using configured values .""" | if len ( episodenumbers ) == 1 :
epno = cfg . CONF . episode_single % episodenumbers [ 0 ]
else :
epno = cfg . CONF . episode_separator . join ( cfg . CONF . episode_single % x for x in episodenumbers )
return epno |
def _MergeIdenticalCaseInsensitive ( self , a , b ) :
"""Tries to merge two strings .
The string are required to be the same ignoring case . The second string is
always used as the merged value .
Args :
a : The first string .
b : The second string .
Returns :
The merged string . This is equal to the s... | if a . lower ( ) != b . lower ( ) :
raise MergeError ( "values must be the same (case insensitive) " "('%s' vs '%s')" % ( transitfeed . EncodeUnicode ( a ) , transitfeed . EncodeUnicode ( b ) ) )
return b |
def flush ( self , queue_name ) :
"""Drop all the messages from a queue .
Parameters :
queue _ name ( str ) : The queue to flush .""" | for name in ( queue_name , dq_name ( queue_name ) , xq_name ( queue_name ) ) :
self . channel . queue_purge ( name ) |
def get_urlpatterns ( self ) :
"""Returns the URL patterns managed by the considered factory / application .""" | return [ url ( r'' , include ( self . forum_urlpatterns_factory . urlpatterns ) ) , url ( r'' , include ( self . conversation_urlpatterns_factory . urlpatterns ) ) , url ( _ ( r'^feeds/' ) , include ( self . feeds_urlpatterns_factory . urlpatterns ) ) , url ( _ ( r'^member/' ) , include ( self . member_urlpatterns_fact... |
def check_key ( user , key , enc , comment , options , config = '.ssh/authorized_keys' , cache_keys = None , fingerprint_hash_type = None ) :
'''Check to see if a key needs updating , returns " update " , " add " or " exists "
CLI Example :
. . code - block : : bash
salt ' * ' ssh . check _ key < user > < key... | if cache_keys is None :
cache_keys = [ ]
enc = _refine_enc ( enc )
current = auth_keys ( user , config = config , fingerprint_hash_type = fingerprint_hash_type )
nline = _format_auth_line ( key , enc , comment , options )
# Removing existing keys from the auth _ keys isn ' t really a good idea
# in fact
# as :
# - ... |
def unique ( transactions ) :
"""Remove any duplicate entries .""" | seen = set ( )
# TODO : Handle comments
return [ x for x in transactions if not ( x in seen or seen . add ( x ) ) ] |
def allowMethodWithConditions ( self , verb , resource , conditions ) :
"""Adds an API Gateway method ( Http verb + Resource path ) to the list of allowed
methods and includes a condition for the policy statement . More on AWS policy
conditions here : http : / / docs . aws . amazon . com / IAM / latest / UserGu... | self . _addMethod ( "Allow" , verb , resource , conditions ) |
def perturb_tmat ( transmat , scale ) :
'''Perturbs each nonzero entry in the MSM transition matrix by treating it as a Gaussian random variable
with mean t _ ij and standard deviation equal to the standard error computed using " create _ perturb _ params " .
Returns a sampled transition matrix that takes into ... | output = np . vectorize ( np . random . normal ) ( transmat , scale )
output [ np . where ( output < 0 ) ] = 0
return ( output . transpose ( ) / np . sum ( output , axis = 1 ) ) . transpose ( ) |
def handle_json_wrapper_GET ( self , handler , parsed_params ) :
"""Call handler and output the return value in JSON .""" | schedule = self . server . schedule
result = handler ( parsed_params )
content = ResultEncoder ( ) . encode ( result )
self . send_response ( 200 )
self . send_header ( 'Content-Type' , 'text/plain' )
self . send_header ( 'Content-Length' , str ( len ( content ) ) )
self . end_headers ( )
self . wfile . write ( content... |
def factory ( method , description = "" , request_example = None , request_ctor = None , responses = None , method_choices = HTTP_METHODS , ) :
"""desc : Describes a single HTTP method of a URI
args :
- name : method
type : str
desc : The HTTP request method to use
- name : description
type : str
desc... | return RouteMethod ( method , description , request_example , DocString . from_ctor ( request_ctor ) if request_ctor else None , responses , method_choices , ) |
def ReadChildFlowObjects ( self , client_id , flow_id , cursor = None ) :
"""Reads flows that were started by a given flow from the database .""" | query = ( "SELECT " + self . FLOW_DB_FIELDS + "FROM flows WHERE client_id=%s AND parent_flow_id=%s" )
cursor . execute ( query , [ db_utils . ClientIDToInt ( client_id ) , db_utils . FlowIDToInt ( flow_id ) ] )
return [ self . _FlowObjectFromRow ( row ) for row in cursor . fetchall ( ) ] |
def PHASE ( angle , qubit ) :
"""Produces the PHASE gate : :
PHASE ( phi ) = [ [ 1 , 0 ] ,
[0 , exp ( 1j * phi ) ] ]
This is the same as the RZ gate .
: param angle : The angle to rotate around the z - axis on the bloch sphere .
: param qubit : The qubit apply the gate to .
: returns : A Gate object .""... | return Gate ( name = "PHASE" , params = [ angle ] , qubits = [ unpack_qubit ( qubit ) ] ) |
def weighted_choice ( weights , as_index_and_value_tuple = False ) :
"""Generate a non - uniform random choice based on a list of option tuples .
Treats each outcome as a discreet unit with a chance to occur .
Args :
weights ( list ) : a list of options where each option
is a tuple of form ` ` ( Any , float... | if not len ( weights ) :
raise ValueError ( 'List passed to weighted_choice() cannot be empty.' )
# Construct a line segment where each weight outcome is
# allotted a length equal to the outcome ' s weight ,
# pick a uniformally random point along the line , and take
# the outcome that point corresponds to
prob_sum... |
def _rgba ( r , g , b , a , ** kwargs ) :
"""Converts an rgba ( red , green , blue , alpha ) quadruplet into a color .""" | return ColorValue ( ( float ( r ) , float ( g ) , float ( b ) , float ( a ) ) ) |
def copy_contents ( self , fileinstance , progress_callback = None , chunk_size = None , ** kwargs ) :
"""Copy this file instance into another file instance .""" | if not fileinstance . readable :
raise ValueError ( 'Source file instance is not readable.' )
if not self . size == 0 :
raise ValueError ( 'File instance has data.' )
self . set_uri ( * self . storage ( ** kwargs ) . copy ( fileinstance . storage ( ** kwargs ) , chunk_size = chunk_size , progress_callback = pro... |
def transform ( self , X ) :
"""if already fit , can add new points and see where they fall""" | iclustup = [ ]
dims = self . n_components
if hasattr ( self , 'isort1' ) :
if X . shape [ 1 ] == self . v . shape [ 0 ] : # reduce dimensionality of X
X = X @ self . v
nclust = self . n_X
AtS = self . A . T @ self . S
vnorm = np . sum ( self . S * ( self . A @ AtS ) , axis = 0 ) [ np... |
def sync_to_db_from_config ( cls , druid_config , user , cluster , refresh = True ) :
"""Merges the ds config from druid _ config into one stored in the db .""" | session = db . session
datasource = ( session . query ( cls ) . filter_by ( datasource_name = druid_config [ 'name' ] ) . first ( ) )
# Create a new datasource .
if not datasource :
datasource = cls ( datasource_name = druid_config [ 'name' ] , cluster = cluster , owners = [ user ] , changed_by_fk = user . id , cre... |
def update_keys ( self ) :
"""Update the redis keys to listen for new jobs priorities .""" | self . keys = self . queue_model . get_waiting_keys ( self . queues )
if not self . keys :
self . log ( 'No queues yet' , level = 'warning' )
self . last_update_keys = datetime . utcnow ( ) |
def new_data ( self , mem , addr , data ) :
"""Callback for when new memory data has been fetched""" | done = False
if mem . id == self . id :
if addr == LocoMemory . MEM_LOCO_INFO :
self . nr_of_anchors = data [ 0 ]
if self . nr_of_anchors == 0 :
done = True
else :
self . anchor_data = [ AnchorData ( ) for _ in range ( self . nr_of_anchors ) ]
self . _requ... |
def set_start ( self , time , pad = None ) :
"""Set the start time of the datafind query .
@ param time : GPS start time of query .""" | if pad :
self . add_var_opt ( 'gps-start-time' , int ( time ) - int ( pad ) )
else :
self . add_var_opt ( 'gps-start-time' , int ( time ) )
self . __start = time
self . __set_output ( ) |
def add ( self , left_column , right_column , indexes = None ) :
"""Math helper method that adds element - wise two columns . If indexes are not None then will only perform the math
on that sub - set of the columns .
: param left _ column : first column name
: param right _ column : second column name
: par... | left_list , right_list = self . _get_lists ( left_column , right_column , indexes )
return [ l + r for l , r in zip ( left_list , right_list ) ] |
def get_apps ( exclude = ( ) , append = ( ) , current = { 'apps' : INSTALLED_APPS } ) :
"""Returns INSTALLED _ APPS without the apps listed in exclude and with the apps
listed in append .
The use of a mutable dict is intentional , in order to preserve the state of
the INSTALLED _ APPS tuple across multiple se... | current [ 'apps' ] = tuple ( [ a for a in current [ 'apps' ] if a not in exclude ] ) + tuple ( append )
return current [ 'apps' ] |
def change_interface_id ( self , newid ) :
"""Change the inline interface ID . The current format is
nicid = ' 1-2 ' , where ' 1 ' is the top level interface ID ( first ) ,
and ' 2 ' is the second interface in the pair . Consider the existing
nicid in case this is a VLAN .
: param str newid : string definin... | try :
newleft , newright = newid . split ( '-' )
except ValueError :
raise EngineCommandFailed ( 'You must provide two parts when changing ' 'the interface ID on an inline interface, i.e. 1-2.' )
first , second = self . nicid . split ( '-' )
if '.' in first and '.' in second :
firstvlan = first . split ( '.... |
def analyze_lib ( lib_dir , cover_filename , * , ignore_existing = False ) :
"""Recursively analyze library , and return a dict of path - > ( artist , album ) .""" | work = { }
stats = collections . OrderedDict ( ( ( k , 0 ) for k in ( "files" , "albums" , "missing covers" , "errors" ) ) )
with tqdm . tqdm ( desc = "Analyzing library" , unit = "dir" , postfix = stats ) as progress , tqdm_logging . redirect_logging ( progress ) :
for rootpath , rel_dirpaths , rel_filepaths in os... |
async def get_box_ids_json ( self ) -> str :
"""Return json object on lists of all unique box identifiers for credentials in wallet :
schema identifiers , credential definition identifiers , and revocation registry identifiers ; e . g . ,
" schema _ id " : [
" R17v42T4pk . . . : 2 : tombstone : 1.2 " ,
"9cH... | LOGGER . debug ( 'HolderProver.get_box_ids_json >>>' )
s_ids = set ( )
cd_ids = set ( )
rr_ids = set ( )
for cred in json . loads ( await self . get_creds_display_coarse ( ) ) :
s_ids . add ( cred [ 'schema_id' ] )
cd_ids . add ( cred [ 'cred_def_id' ] )
if cred [ 'rev_reg_id' ] :
rr_ids . add ( cre... |
def Deserialize ( self , reader ) :
"""Deserialize full object .
Args :
reader ( neo . IO . BinaryReader ) :""" | self . Magic = reader . ReadUInt32 ( )
self . Command = reader . ReadFixedString ( 12 ) . decode ( 'utf-8' )
self . Length = reader . ReadUInt32 ( )
if self . Length > self . PayloadMaxSizeInt :
raise Exception ( "invalid format- payload too large" )
self . Checksum = reader . ReadUInt32 ( )
self . Payload = reader... |
def locale ( self ) :
'''Do a lookup for the locale code that is set for this layout .
NOTE : USB HID specifies only 35 different locales . If your layout does not fit , it should be set to Undefined / 0
@ return : Tuple ( < USB HID locale code > , < name > )''' | name = self . json_data [ 'hid_locale' ]
# Set to Undefined / 0 if not set
if name is None :
name = "Undefined"
return ( int ( self . json_data [ 'from_hid_locale' ] [ name ] ) , name ) |
def set_circuit_breakers ( mv_grid , mode = 'load' , debug = False ) :
"""Calculates the optimal position of a circuit breaker on all routes of mv _ grid , adds and connects them to graph .
Args
mv _ grid : MVGridDing0
Description # TODO
debug : bool , defaults to False
If True , information is printed du... | # get power factor for loads and generators
cos_phi_load = cfg_ding0 . get ( 'assumptions' , 'cos_phi_load' )
cos_phi_feedin = cfg_ding0 . get ( 'assumptions' , 'cos_phi_gen' )
# iterate over all rings and circuit breakers
for ring , circ_breaker in zip ( mv_grid . rings_nodes ( include_root_node = False ) , mv_grid . ... |
def approximate_surface ( points , size_u , size_v , degree_u , degree_v , ** kwargs ) :
"""Surface approximation using least squares method with fixed number of control points .
This algorithm interpolates the corner control points and approximates the remaining control points . Please refer to
Algorithm A9.7 ... | # Keyword arguments
use_centripetal = kwargs . get ( 'centripetal' , False )
num_cpts_u = kwargs . get ( 'ctrlpts_size_u' , size_u - 1 )
# number of datapts , r + 1 > number of ctrlpts , n + 1
num_cpts_v = kwargs . get ( 'ctrlpts_size_v' , size_v - 1 )
# number of datapts , s + 1 > number of ctrlpts , m + 1
# Dimension... |
def is_parent_of_vault ( self , id_ , vault_id ) :
"""Tests if an ` ` Id ` ` is a direct parent of a vault .
arg : id ( osid . id . Id ) : an ` ` Id ` `
arg : vault _ id ( osid . id . Id ) : the ` ` Id ` ` of a vault
return : ( boolean ) - ` ` true ` ` if this ` ` id ` ` is a parent of
` ` vault _ id , ` ` ... | # Implemented from template for
# osid . resource . BinHierarchySession . is _ parent _ of _ bin
if self . _catalog_session is not None :
return self . _catalog_session . is_parent_of_catalog ( id_ = id_ , catalog_id = vault_id )
return self . _hierarchy_session . is_parent ( id_ = vault_id , parent_id = id_ ) |
def create ( hypervisor , identifier , configuration ) :
"""Creates a virtual network according to the given configuration .
@ param hypervisor : ( libvirt . virConnect ) connection to libvirt hypervisor .
@ param identifier : ( str ) UUID for the virtual network .
@ param configuration : ( dict ) network con... | counter = count ( )
xml_config = DEFAULT_NETWORK_XML
if not { 'configuration' , 'dynamic_address' } & set ( configuration . keys ( ) ) :
raise RuntimeError ( "Either configuration or dynamic_address must be specified" )
if 'configuration' in configuration :
with open ( configuration [ 'configuration' ] ) as xml... |
def select_with_correspondence ( self , selector , result_selector = KeyedElement ) :
'''Apply a callable to each element in an input sequence , generating a new
sequence of 2 - tuples where the first element is the input value and the
second is the transformed input value .
The generated sequence is lazily e... | if self . closed ( ) :
raise ValueError ( "Attempt to call select_with_correspondence() on a " "closed Queryable." )
if not is_callable ( selector ) :
raise TypeError ( "select_with_correspondence() parameter selector={0} is " "not callable" . format ( repr ( selector ) ) )
if not is_callable ( result_selector ... |
def _analyze_function_features ( self , all_funcs_completed = False ) :
"""For each function in the function _ manager , try to determine if it returns or not . A function does not return if
it calls another function that is known to be not returning , and this function does not have other exits .
We might as w... | changes = { 'functions_return' : [ ] , 'functions_do_not_return' : [ ] }
if self . _updated_nonreturning_functions is not None :
all_func_addrs = self . _updated_nonreturning_functions
# Convert addresses to objects
all_functions = [ self . kb . functions . get_by_addr ( f ) for f in all_func_addrs if self ... |
def chain ( self , block , count ) :
"""Returns a list of block hashes in the account chain starting at
* * block * * up to * * count * *
: param block : Block hash to start at
: type block : str
: param count : Number of blocks to return up to
: type count : int
: raises : : py : exc : ` nano . rpc . R... | block = self . _process_value ( block , 'block' )
count = self . _process_value ( count , 'int' )
payload = { "block" : block , "count" : count }
resp = self . call ( 'chain' , payload )
return resp . get ( 'blocks' ) or [ ] |
def sanitize_string ( string_or_unicode ) :
"""remove leading / trailing whitespace and always return unicode .""" | if isinstance ( string_or_unicode , unicode ) :
return string_or_unicode . strip ( )
elif isinstance ( string_or_unicode , str ) :
return string_or_unicode . decode ( 'utf-8' ) . strip ( )
else : # e . g . if input is None
return u'' |
def init_pypsa_network ( time_range_lim ) :
"""Instantiate PyPSA network
Parameters
time _ range _ lim :
Returns
network : PyPSA network object
Contains powerflow problem
snapshots : iterable
Contains snapshots to be analyzed by powerplow calculation""" | network = Network ( )
network . set_snapshots ( time_range_lim )
snapshots = network . snapshots
return network , snapshots |
def object_to_items ( data_structure ) :
"""Converts a object to a items list respecting also slots .
Use dict ( object _ to _ items ( obj ) ) to get a dictionary .""" | items = [ ]
# Get all items from dict
try :
items = list ( data_structure . __dict__ . items ( ) )
except :
pass
# Get all slots
hierarchy = [ data_structure ]
try :
hierarchy += inspect . getmro ( data_structure )
except :
pass
slots = [ ]
try :
for b in hierarchy :
try :
slots ... |
def make_dict_unstructure_fn ( cl , converter , ** kwargs ) : # type : ( Type [ T ] , Converter ) - > Callable [ [ T ] , Dict [ str , Any ] ]
"""Generate a specialized dict unstructuring function for a class .""" | cl_name = cl . __name__
fn_name = "unstructure_" + cl_name
globs = { "__c_u" : converter . unstructure }
lines = [ ]
post_lines = [ ]
attrs = cl . __attrs_attrs__
lines . append ( "def {}(i):" . format ( fn_name ) )
lines . append ( " res = {" )
for a in attrs :
attr_name = a . name
override = kwargs . pop (... |
def create_serialization_dir ( params : Params , serialization_dir : str , recover : bool , force : bool ) -> None :
"""This function creates the serialization directory if it doesn ' t exist . If it already exists
and is non - empty , then it verifies that we ' re recovering from a training with an identical con... | if recover and force :
raise ConfigurationError ( "Illegal arguments: both force and recover are true." )
if os . path . exists ( serialization_dir ) and force :
shutil . rmtree ( serialization_dir )
if os . path . exists ( serialization_dir ) and os . listdir ( serialization_dir ) :
if not recover :
... |
def format_python_stack ( self ) :
"""Return a traceback of Python frames , from where the error occurred
to where it was first caught and wrapped .""" | ret = [ "Traceback:\n" ]
ret . extend ( traceback . format_tb ( self . original_traceback ) )
return "" . join ( ret ) |
def get_default_template ( ) :
"""Returns default getTemplate request specification .
: return :""" | return { "format" : 1 , "protocol" : 1 , "environment" : Environment . DEV , # shows whether the UO should be for production ( live ) ,
# test ( pre - production testing ) , or dev ( development )
"maxtps" : "one" , # maximum guaranteed TPS
"core" : "empty" , # how many cards have UO loaded permanently
"persistence" : ... |
def askokcancel ( title = None , message = None , ** options ) :
"""Original doc : Ask if operation should proceed ; return true if the answer is ok""" | return psidialogs . ask_ok_cancel ( title = title , message = message ) |
def _normalize_hparams ( hparams ) :
"""Normalize a dict keyed by ` HParam ` s and / or raw strings .
Args :
hparams : A ` dict ` whose keys are ` HParam ` objects and / or strings
representing hyperparameter names , and whose values are
hyperparameter values . No two keys may have the same name .
Returns... | result = { }
for ( k , v ) in six . iteritems ( hparams ) :
if isinstance ( k , HParam ) :
k = k . name
if k in result :
raise ValueError ( "multiple values specified for hparam %r" % ( k , ) )
result [ k ] = v
return result |
def get_permissions ( cls ) :
"""Generates permissions for all CrudView based class methods .
Returns :
List of Permission objects .""" | perms = [ ]
for kls_name , kls in cls . registry . items ( ) :
for method_name in cls . __dict__ . keys ( ) :
if method_name . endswith ( '_view' ) :
perms . append ( "%s.%s" % ( kls_name , method_name ) )
return perms |
def to_string ( address , dns_format = False ) :
"""Convert address to string
: param address : WIPV4Address to convert
: param dns _ format : whether to use arpa - format or not
: return :""" | if isinstance ( address , WIPV4Address ) is False :
raise TypeError ( 'Invalid address type' )
address = [ str ( int ( x ) ) for x in address . __address ]
if dns_format is False :
return '.' . join ( address )
address . reverse ( )
return ( '.' . join ( address ) + '.in-addr.arpa' ) |
def bind_path ( self , name , folder ) :
"""Adds a mask that maps to a given folder relative to ` base _ path ` .""" | if not len ( name ) or name [ 0 ] != '/' or name [ - 1 ] != '/' :
raise ValueError ( "name must start and end with '/': {0}" . format ( name ) )
self . _folder_masks . insert ( 0 , ( name , folder ) ) |
def filter_search ( self , code = None , name = None , abilities = None , attributes = None , info = None ) :
"""Return a list of codes and names pertaining to cards that have the
given information values stored .
Can take a code integer , name string , abilities dict { phase : ability
list / " * " } , attrib... | command = "SELECT code, name FROM CARDS "
command += Where_filter_gen ( ( "code" , code ) , ( "name" , name ) , ( "abilities" , abilities ) , ( "attributes" , attributes ) , ( "info" , info ) )
with sqlite3 . connect ( self . dbname ) as carddb :
return carddb . execute ( command ) . fetchall ( ) |
def get_src_model ( self , name , paramsonly = False , reoptimize = False , npts = None , ** kwargs ) :
"""Compose a dictionary for a source with the current best - fit
parameters .
Parameters
name : str
paramsonly : bool
Skip computing TS and likelihood profile .
reoptimize : bool
Re - fit background... | self . logger . debug ( 'Generating source dict for ' + name )
optimizer = kwargs . get ( 'optimizer' , self . config [ 'optimizer' ] )
if npts is None :
npts = self . config [ 'gtlike' ] [ 'llscan_npts' ]
name = self . get_source_name ( name )
source = self . like [ name ] . src
spectrum = source . spectrum ( )
no... |
def _save ( self ) :
"""Saves the current state of this AssessmentTaken .
Should be called every time the sections map changes .""" | collection = JSONClientValidated ( 'assessment' , collection = 'AssessmentTaken' , runtime = self . _runtime )
collection . save ( self . _my_map ) |
def _multiply ( X , coef ) :
"""Multiple X by coef element - wise , preserving sparsity .""" | if sp . issparse ( X ) :
return X . multiply ( sp . csr_matrix ( coef ) )
else :
return np . multiply ( X , coef ) |
def _create_body ( self , name , description = None , volume = None , force = False ) :
"""Used to create the dict required to create a new snapshot""" | body = { "snapshot" : { "display_name" : name , "display_description" : description , "volume_id" : volume . id , "force" : str ( force ) . lower ( ) , } }
return body |
def zoom_in ( self , increment = 1 ) :
"""Zooms in the editor ( makes the font bigger ) .
: param increment : zoom level increment . Default is 1.""" | self . zoom_level += increment
TextHelper ( self ) . mark_whole_doc_dirty ( )
self . _reset_stylesheet ( ) |
def getUsersWithinEnterpriseGroup ( self , groupName , searchFilter = None , maxCount = 10 ) :
"""This operation returns the users that are currently assigned to the
enterprise group within the enterprise user / group store . You can
use the filter parameter to narrow down the user search .
Inputs :
groupNa... | params = { "f" : "json" , "groupName" : groupName , "maxCount" : maxCount }
if searchFilter :
params [ 'filters' ] = searchFilter
url = self . _url + "/groups/getUsersWithinEnterpriseGroup"
return self . _get ( url = url , param_dict = params , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) |
def open_phbst ( self ) :
"""Open PHBST file produced by Anaddb and returns : class : ` PhbstFile ` object .""" | from abipy . dfpt . phonons import PhbstFile
phbst_path = os . path . join ( self . workdir , "run.abo_PHBST.nc" )
if not phbst_path :
if self . status == self . S_OK :
logger . critical ( "%s reached S_OK but didn't produce a PHBST file in %s" % ( self , self . outdir ) )
return None
try :
return P... |
def bookmarks_index_changed ( self ) :
"""Update the UI when the bookmarks combobox has changed .""" | index = self . bookmarks_list . currentIndex ( )
if index >= 0 :
self . tool . reset ( )
rectangle = self . bookmarks_list . itemData ( index )
self . tool . set_rectangle ( rectangle )
self . canvas . setExtent ( rectangle )
self . ok_button . setEnabled ( True )
else :
self . ok_button . setDi... |
def process_frames ( self , data , sampling_rate , offset = 0 , last = False , utterance = None , corpus = None ) :
"""Execute the processing of this step and all dependent parent steps .""" | if offset == 0 :
self . steps_sorted = list ( nx . algorithms . dag . topological_sort ( self . graph ) )
self . _create_buffers ( )
self . _define_output_buffers ( )
# Update buffers with input data
self . _update_buffers ( None , data , offset , last )
# Go through the ordered ( by dependencies ) steps
fo... |
def get_observation ( self , observation_id ) :
"""Retrieve an existing : class : ` meteorpi _ model . Observation ` by its ID
: param string observation _ id :
UUID of the observation
: return :
A : class : ` meteorpi _ model . Observation ` instance , or None if not found""" | search = mp . ObservationSearch ( observation_id = observation_id )
b = search_observations_sql_builder ( search )
sql = b . get_select_sql ( columns = 'l.publicId AS obstory_id, l.name AS obstory_name, ' 'o.obsTime, s.name AS obsType, o.publicId, o.uid' , skip = 0 , limit = 1 , order = 'o.obsTime DESC' )
obs = list ( ... |
def get ( self , params , ** options ) :
"""Dispatches a GET request to / events of the API to get a set of recent changes to a resource .""" | options = self . client . _merge_options ( { 'full_payload' : True } )
return self . client . get ( '/events' , params , ** options ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.