signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_cql_models ( app , connection = None , keyspace = None ) :
""": param app : django models module
: param connection : connection name
: param keyspace : keyspace
: return : list of all cassandra . cqlengine . Model within app that should be
synced to keyspace .""" | from . models import DjangoCassandraModel
models = [ ]
single_cassandra_connection = len ( list ( get_cassandra_connections ( ) ) ) == 1
is_default_connection = connection == DEFAULT_DB_ALIAS or single_cassandra_connection
for name , obj in inspect . getmembers ( app ) :
cql_model_types = ( cqlengine . models . Mod... |
def tasks ( ) :
'''Display registered tasks with their queue''' | tasks = get_tasks ( )
longest = max ( tasks . keys ( ) , key = len )
size = len ( longest )
for name , queue in sorted ( tasks . items ( ) ) :
print ( '* {0}: {1}' . format ( name . ljust ( size ) , queue ) ) |
def deconstruct ( self ) :
"""Deconstruct operation .""" | return ( self . __class__ . __name__ , [ ] , { 'process' : self . process , 'field' : self . _raw_field , 'new_field' : self . new_field , } ) |
def merge ( self , session , checksums , title ) :
'''Merges calcs into a new calc called DATASET
NB : this is the PUBLIC method
@ returns DATASET , error''' | calc = Output ( calcset = checksums )
cur_depth = 0
for nested_depth , grid_item , download_size in session . query ( model . Calculation . nested_depth , model . Grid . info , model . Metadata . download_size ) . filter ( model . Calculation . checksum == model . Grid . checksum , model . Grid . checksum == model . Me... |
def post_map ( self , url , map , auth_map = None ) :
"""Gera um XML a partir dos dados do dicionário e o envia através de uma requisição POST .
: param url : URL para enviar a requisição HTTP .
: param map : Dicionário com os dados do corpo da requisição HTTP .
: param auth _ map : Dicionário com a... | xml = dumps_networkapi ( map )
response_code , content = self . post ( url , xml , 'text/plain' , auth_map )
return response_code , content |
def generate_scan_configuration_description ( scan_parameters ) :
'''Generate scan parameter dictionary . This is the only way to dynamically create table with dictionary , cannot be done with tables . IsDescription
Parameters
scan _ parameters : list , tuple
List of scan parameters names ( strings ) .
Retu... | table_description = np . dtype ( [ ( key , tb . StringCol ( 512 , pos = idx ) ) for idx , key in enumerate ( scan_parameters ) ] )
return table_description |
def sparql_get ( self , owner , id , query , ** kwargs ) :
"""SPARQL query ( via GET )
This endpoint executes SPARQL queries against a dataset or data project . SPARQL results are available in a variety of formats . By default , ` application / sparql - results + json ` will be returned . Set the ` Accept ` heade... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . sparql_get_with_http_info ( owner , id , query , ** kwargs )
else :
( data ) = self . sparql_get_with_http_info ( owner , id , query , ** kwargs )
return data |
def _are_cmd_nodes_same ( node1 , node2 ) :
"""Checks to see if two cmddnodes are the same .
Two cmdnodes are defined to be the same if they have the same callbacks /
helptexts / summaries .""" | # Everything in node1 should be in node2
for propertytype in node1 :
if ( not propertytype in node2 or node1 [ propertytype ] != node2 [ propertytype ] ) :
return False
return True |
def __get_stock_row ( self , stock : Stock , depth : int ) -> str :
"""formats stock row""" | assert isinstance ( stock , Stock )
view_model = AssetAllocationViewModel ( )
view_model . depth = depth
# Symbol
view_model . name = stock . symbol
# Current allocation
view_model . curr_allocation = stock . curr_alloc
# Value in base currency
view_model . curr_value = stock . value_in_base_currency
# Value in securit... |
def get_members ( self , retrieve = False ) :
'''get pcdm : hasMember for this resource
Args :
retrieve ( bool ) : if True , issue . refresh ( ) on resource thereby confirming existence and retrieving payload''' | if self . exists and hasattr ( self . rdf . triples , 'pcdm' ) and hasattr ( self . rdf . triples . pcdm , 'hasMember' ) :
members = [ self . repo . parse_uri ( uri ) for uri in self . rdf . triples . pcdm . hasMember ]
# return
return members
else :
return [ ] |
def insert ( self , loc , column , value , allow_duplicates = False , inplace = False ) :
"""Insert column into molecule at specified location .
Wrapper around the : meth : ` pandas . DataFrame . insert ` method .""" | out = self if inplace else self . copy ( )
out . _frame . insert ( loc , column , value , allow_duplicates = allow_duplicates )
if not inplace :
return out |
async def create_subprocess_with_handle ( command , display_handle , * , shell = False , cwd , ** kwargs ) :
'''Writes subprocess output to a display handle as it comes in , and also
returns a copy of it as a string . Throws if the subprocess returns an
error . Note that cwd is a required keyword - only argumen... | # We ' re going to get chunks of bytes from the subprocess , and it ' s possible
# that one of those chunks ends in the middle of a unicode character . An
# incremental decoder keeps those dangling bytes around until the next
# chunk arrives , so that split characters get decoded properly . Use
# stdout ' s encoding , ... |
def _handle_download_result ( self , resource , tmp_dir_path , sha256 , dl_size ) :
"""Store dled file to definitive place , write INFO file , return path .""" | fnames = tf . io . gfile . listdir ( tmp_dir_path )
if len ( fnames ) > 1 :
raise AssertionError ( 'More than one file in %s.' % tmp_dir_path )
original_fname = fnames [ 0 ]
tmp_path = os . path . join ( tmp_dir_path , original_fname )
self . _recorded_sizes_checksums [ resource . url ] = ( dl_size , sha256 )
if se... |
def pretty_dumps ( data ) :
"""Return json string in pretty format .
* * 中文文档 * *
将字典转化成格式化后的字符串 。""" | try :
return json . dumps ( data , sort_keys = True , indent = 4 , ensure_ascii = False )
except :
return json . dumps ( data , sort_keys = True , indent = 4 , ensure_ascii = True ) |
def complete ( self , default_output = None ) :
"""Marks this asynchronous Pipeline as complete .
Args :
default _ output : What value the ' default ' output slot should be assigned .
Raises :
UnexpectedPipelineError if the slot no longer exists or this method was
called for a pipeline that is not async .... | # TODO : Enforce that all outputs expected by this async pipeline were
# filled before this complete ( ) function was called . May required all
# async functions to declare their outputs upfront .
if not self . async :
raise UnexpectedPipelineError ( 'May only call complete() method for asynchronous pipelines.' )
s... |
def _add_ubridge_ethernet_connection ( self , bridge_name , ethernet_interface , block_host_traffic = False ) :
"""Creates a connection with an Ethernet interface in uBridge .
: param bridge _ name : bridge name in uBridge
: param ethernet _ interface : Ethernet interface name
: param block _ host _ traffic :... | if sys . platform . startswith ( "linux" ) and block_host_traffic is False : # on Linux we use RAW sockets by default excepting if host traffic must be blocked
yield from self . _ubridge_send ( 'bridge add_nio_linux_raw {name} "{interface}"' . format ( name = bridge_name , interface = ethernet_interface ) )
elif sy... |
def default ( session ) :
"""Default unit test session .
This is intended to be run * * without * * an interpreter set , so
that the current ` ` python ` ` ( on the ` ` PATH ` ` ) or the version of
Python corresponding to the ` ` nox ` ` binary the ` ` PATH ` ` can
run the tests .""" | # Install all test dependencies , then install local packages in - place .
session . install ( "mock" , "pytest" , "pytest-cov" )
for local_dep in LOCAL_DEPS :
session . install ( "-e" , local_dep )
# Pyarrow does not support Python 3.7
dev_install = ".[all]"
session . install ( "-e" , dev_install )
# IPython does ... |
def hide_arp_holder_arp_entry_interfacetype_FortyGigabitEthernet_FortyGigabitEthernet ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
hide_arp_holder = ET . SubElement ( config , "hide-arp-holder" , xmlns = "urn:brocade.com:mgmt:brocade-arp" )
arp_entry = ET . SubElement ( hide_arp_holder , "arp-entry" )
arp_ip_address_key = ET . SubElement ( arp_entry , "arp-ip-address" )
arp_ip_address_key . text = kwargs . pop ( ... |
def spendables_for_address ( self , address ) :
"""Return a list of Spendable objects for the
given bitcoin address .""" | URL = self . api_domain + "/unspent?active=%s" % address
r = json . loads ( urlopen ( URL ) . read ( ) . decode ( "utf8" ) )
spendables = [ ]
for u in r [ "unspent_outputs" ] :
coin_value = u [ "value" ]
script = h2b ( u [ "script" ] )
previous_hash = h2b ( u [ "tx_hash" ] )
previous_index = u [ "tx_out... |
def refactor_froms_to_imports ( self , offset ) :
"""Converting imports of the form " from . . . " to " import . . . " .""" | refactor = ImportOrganizer ( self . project )
changes = refactor . froms_to_imports ( self . resource , offset )
return translate_changes ( changes ) |
def run_with_falcon ( self ) :
"""runs the falcon / http based test server""" | from wsgiref import simple_server
from zengine . server import app
httpd = simple_server . make_server ( self . manager . args . addr , int ( self . manager . args . port ) , app )
httpd . serve_forever ( ) |
def copy ( self ) :
"""Make a hard copy of ` self ` .
: return : A new LiveDefinition instance .
: rtype : angr . analyses . ddg . LiveDefinitions""" | ld = LiveDefinitions ( )
ld . _memory_map = self . _memory_map . copy ( )
ld . _register_map = self . _register_map . copy ( )
ld . _defs = self . _defs . copy ( )
return ld |
def _dataslice ( self , data , indices ) :
"""Returns slice of data element if the item is deep
indexable . Warns if attempting to slice an object that has not
been declared deep indexable .""" | if self . _deep_indexable and isinstance ( data , Dimensioned ) and indices :
return data [ indices ]
elif len ( indices ) > 0 :
self . param . warning ( 'Cannot index into data element, extra data' ' indices ignored.' )
return data |
def on_exit ( self ) :
"""When you click to exit , this function is called , prompts whether to save""" | answer = messagebox . askyesnocancel ( "Exit" , "Do you want to save as you quit the application?" )
if answer :
self . save ( )
self . quit ( )
self . destroy ( )
elif answer is None :
pass
# the cancel action
else :
self . quit ( )
self . destroy ( ) |
def build ( config , archiver , operators ) :
"""Build the history given a archiver and collection of operators .
: param config : The wily configuration
: type config : : namedtuple : ` wily . config . WilyConfig `
: param archiver : The archiver to use
: type archiver : : namedtuple : ` wily . archivers .... | try :
logger . debug ( f"Using {archiver.name} archiver module" )
archiver = archiver . cls ( config )
revisions = archiver . revisions ( config . path , config . max_revisions )
except InvalidGitRepositoryError : # TODO : This logic shouldn ' t really be here ( SoC )
logger . info ( f"Defaulting back t... |
def delete_app_info ( app_id ) :
"""delete app info from local db""" | try :
conn = get_conn ( )
c = conn . cursor ( )
c . execute ( "DELETE FROM container WHERE app_id='{0}'" . format ( app_id ) )
c . execute ( "DELETE FROM app WHERE id='{0}'" . format ( app_id ) )
conn . commit ( )
# print ' clear old app % s in db succeed ! ' % app _ id
except Exception , e :
... |
def query ( self , area = None , date = None , raw = None , area_relation = 'Intersects' , order_by = None , limit = None , offset = 0 , ** keywords ) :
"""Query the OpenSearch API with the coordinates of an area , a date interval
and any other search keywords accepted by the API .
Parameters
area : str , opt... | query = self . format_query ( area , date , raw , area_relation , ** keywords )
self . logger . debug ( "Running query: order_by=%s, limit=%s, offset=%s, query=%s" , order_by , limit , offset , query )
formatted_order_by = _format_order_by ( order_by )
response , count = self . _load_query ( query , formatted_order_by ... |
def _fullqualname_builtin_py3 ( obj ) :
"""Fully qualified name for ' builtin _ function _ or _ method ' objects in
Python 3.""" | if obj . __module__ is not None : # built - in functions
module = obj . __module__
else : # built - in methods
if inspect . isclass ( obj . __self__ ) :
module = obj . __self__ . __module__
else :
module = obj . __self__ . __class__ . __module__
return module + '.' + obj . __qualname__ |
def _build_mappings ( self , classes : Sequence [ type ] ) -> Tuple [ Mapping [ type , Sequence [ type ] ] , Mapping [ type , Sequence [ type ] ] ] :
"""Collect all bases and organize into parent / child mappings .""" | parents_to_children : MutableMapping [ type , Set [ type ] ] = { }
children_to_parents : MutableMapping [ type , Set [ type ] ] = { }
visited_classes : Set [ type ] = set ( )
class_stack = list ( classes )
while class_stack :
class_ = class_stack . pop ( )
if class_ in visited_classes :
continue
vis... |
def read_trailer ( self ) :
'''Read the HTTP trailer fields .
Returns :
bytes : The trailer data .
Coroutine .''' | _logger . debug ( 'Reading chunked trailer.' )
trailer_data_list = [ ]
while True :
trailer_data = yield from self . _connection . readline ( )
trailer_data_list . append ( trailer_data )
if not trailer_data . strip ( ) :
break
return b'' . join ( trailer_data_list ) |
def _fix_unmapped ( mapped_file , unmapped_file , data ) :
"""The unmapped . bam file up until at least Tophat 2.1.1 is broken in various
ways , see https : / / github . com / cbrueffer / tophat - recondition for details .
Run TopHat - Recondition to fix these issues .""" | out_file = os . path . splitext ( unmapped_file ) [ 0 ] + "_fixup.bam"
if file_exists ( out_file ) :
return out_file
assert os . path . dirname ( mapped_file ) == os . path . dirname ( unmapped_file )
cmd = config_utils . get_program ( "tophat-recondition" , data )
cmd += " -q"
tophat_out_dir = os . path . dirname ... |
def format_author_ed ( citation_elements ) :
"""Standardise to ( ed . ) and ( eds . )
e . g . Remove extra space in ( ed . )""" | for el in citation_elements :
if el [ 'type' ] == 'AUTH' :
el [ 'auth_txt' ] = el [ 'auth_txt' ] . replace ( '(ed. )' , '(ed.)' )
el [ 'auth_txt' ] = el [ 'auth_txt' ] . replace ( '(eds. )' , '(eds.)' )
return citation_elements |
def _request_access_token ( grant_type , client_id = None , client_secret = None , scopes = None , code = None , redirect_url = None , refresh_token = None ) :
"""Make an HTTP POST to request an access token .
Parameters
grant _ type ( str )
Either ' client _ credientials ' ( Client Credentials Grant )
or '... | url = build_url ( auth . AUTH_HOST , auth . ACCESS_TOKEN_PATH )
if isinstance ( scopes , set ) :
scopes = ' ' . join ( scopes )
args = { 'grant_type' : grant_type , 'client_id' : client_id , 'client_secret' : client_secret , 'scope' : scopes , 'code' : code , 'redirect_uri' : redirect_url , 'refresh_token' : refres... |
def convert2 ( self , imtls , sids ) :
"""Convert a probability map into a composite array of shape ( N , )
and dtype ` imtls . dt ` .
: param imtls :
DictArray instance
: param sids :
the IDs of the sites we are interested in
: returns :
an array of curves of shape ( N , )""" | assert self . shape_z == 1 , self . shape_z
curves = numpy . zeros ( len ( sids ) , imtls . dt )
for imt in curves . dtype . names :
curves_by_imt = curves [ imt ]
for i , sid in numpy . ndenumerate ( sids ) :
try :
pcurve = self [ sid ]
except KeyError :
pass
... |
def as_pyemu_matrix ( self , typ = Matrix ) :
"""Create a pyemu . Matrix from the Ensemble .
Parameters
typ : pyemu . Matrix or derived type
the type of matrix to return
Returns
pyemu . Matrix : pyemu . Matrix""" | x = self . values . copy ( ) . astype ( np . float )
return typ ( x = x , row_names = list ( self . index ) , col_names = list ( self . columns ) ) |
def all_gather ( data ) :
"""Run all _ gather on arbitrary picklable data ( not necessarily tensors )
Args :
data : any picklable object
Returns :
list [ data ] : list of data gathered from each rank""" | world_size = get_world_size ( )
if world_size == 1 :
return [ data ]
# serialized to a Tensor
buffer = pickle . dumps ( data )
storage = torch . ByteStorage . from_buffer ( buffer )
tensor = torch . ByteTensor ( storage ) . to ( "cuda" )
# obtain Tensor size of each rank
local_size = torch . IntTensor ( [ tensor . ... |
def _flush_decompressor ( self ) :
'''Return any data left in the decompressor .''' | if self . _decompressor :
try :
return self . _decompressor . flush ( )
except zlib . error as error :
raise ProtocolError ( 'zlib flush error: {0}.' . format ( error ) ) from error
else :
return b'' |
def _format_reinit_msg ( self , name , kwargs = None , triggered_directly = True ) :
"""Returns a message that informs about re - initializing a compoment .
Sometimes , the module or optimizer need to be
re - initialized . Not only should the user receive a message
about this but also should they be informed ... | msg = "Re-initializing {}" . format ( name )
if triggered_directly and kwargs :
msg += ( " because the following parameters were re-set: {}." . format ( ', ' . join ( sorted ( kwargs ) ) ) )
else :
msg += "."
return msg |
def _process_data ( * kwarg_names ) :
"""Helper function to handle data keyword argument""" | def _data_decorator ( func ) :
@ functools . wraps ( func )
def _mark_with_data ( * args , ** kwargs ) :
data = kwargs . pop ( 'data' , None )
if data is None :
return func ( * args , ** kwargs )
else :
data_args = [ data [ i ] if hashable ( data , i ) else i for ... |
def parse_url ( self ) -> RequestUrl :
"""获取url解析对象""" | if self . _URL is None :
current_url = b"%s://%s%s" % ( encode_str ( self . schema ) , encode_str ( self . host ) , self . _current_url )
self . _URL = RequestUrl ( current_url )
return cast ( RequestUrl , self . _URL ) |
def _update_trsys ( self , event ) :
"""Transform object ( s ) have changed for this Node ; assign these to the
visual ' s TransformSystem .""" | doc = self . document_node
scene = self . scene_node
root = self . root_node
self . transforms . visual_transform = self . node_transform ( scene )
self . transforms . scene_transform = scene . node_transform ( doc )
self . transforms . document_transform = doc . node_transform ( root )
Node . _update_trsys ( self , ev... |
def post_comment_ajax ( request , using = None ) :
"""Post a comment , via an Ajax call .""" | if not request . is_ajax ( ) :
return HttpResponseBadRequest ( "Expecting Ajax call" )
# This is copied from django _ comments .
# Basically that view does too much , and doesn ' t offer a hook to change the rendering .
# The request object is not passed to next _ redirect for example .
# This is a separate view to... |
def has_linguist_kwargs ( self , kwargs ) :
"""Parses the given kwargs and returns True if they contain
linguist lookups .""" | for k in kwargs :
if self . is_linguist_lookup ( k ) :
return True
return False |
def extract_first_elements ( nested_list ) :
"""A Python function that returns the first element of every sublist within the provided list .
Examples :
extract _ first _ elements ( [ [ 1 , 2 ] , [ 3 , 4 , 5 ] , [ 6 , 7 , 8 , 9 ] ] ) - > [ 1 , 3 , 6]
extract _ first _ elements ( [ [ 1 , 2 , 3 ] , [ 4 , 5 ] ] )... | return [ sublist [ 0 ] for sublist in nested_list ] |
def run ( self , lam , initial_values = None ) :
'''Run the graph - fused logit lasso with a fixed lambda penalty .''' | if initial_values is not None :
if self . k == 0 and self . trails is not None :
betas , zs , us = initial_values
else :
betas , us = initial_values
else :
if self . k == 0 and self . trails is not None :
betas = [ np . zeros ( self . num_nodes , dtype = 'double' ) for _ in self . bi... |
def sample_forward_transitions ( self , batch_size , batch_info , forward_steps : int , discount_factor : float ) -> Transitions :
"""Sample transitions from replay buffer with _ forward steps _ .
That is , instead of getting a transition s _ t - > s _ t + 1 with reward r ,
get a transition s _ t - > s _ t + n ... | raise NotImplementedError |
def add_404_page ( app ) :
"""Build an extra ` ` 404 . html ` ` page if no ` ` " 404 " ` ` key is in the
` ` html _ additional _ pages ` ` config .""" | is_epub = isinstance ( app . builder , EpubBuilder )
config_pages = app . config . html_additional_pages
if not is_epub and "404" not in config_pages :
yield ( "404" , { } , "404.html" ) |
def mark_best_classifications ( errors ) :
"""Convenience wrapper around mark _ best _ classification .
Finds the best match for each TextLogError in errors , handling no match
meeting the cut off score and then mark _ best _ classification to save that
information .""" | for text_log_error in errors :
best_match = get_best_match ( text_log_error )
if not best_match :
continue
mark_best_classification ( text_log_error , best_match . classified_failure ) |
def debug ( context ) :
"""Outputs a whole load of debugging information , including the current
context and imported modules .
Sample usage : :
< pre >
{ % debug % }
< / pre >""" | from pprint import pformat
output = [ pformat ( val ) for val in context ]
output . append ( '\n\n' )
output . append ( pformat ( sys . modules ) )
return '' . join ( output ) |
def validate ( self , value , model_instance ) :
"""Validates value and throws ValidationError . Subclasses should override
this to provide validation logic .""" | return super ( self . __class__ , self ) . validate ( value . value , model_instance ) |
def _gate_height ( self , gate ) :
"""Return the height to use for this gate .
: param string gate : The name of the gate whose height is desired .
: return : Height of the gate .
: rtype : float""" | try :
height = self . settings [ 'gates' ] [ gate . __class__ . __name__ ] [ 'height' ]
except KeyError :
height = .5
return height |
def peer_relation_id ( ) :
'''Get the peers relation id if a peers relation has been joined , else None .''' | md = metadata ( )
section = md . get ( 'peers' )
if section :
for key in section :
relids = relation_ids ( key )
if relids :
return relids [ 0 ]
return None |
def insert ( self , action : Action , where : 'Union[int, Delegate.Where]' ) :
"""add a new action with specific priority
> > > delegate : Delegate
> > > delegate . insert ( lambda task , product , ctx : print ( product ) , where = Delegate . Where . after ( lambda action : action . _ _ name _ _ = = ' myfunc ' ... | if isinstance ( where , int ) :
self . actions . insert ( where , action )
return
here = where ( self . actions )
self . actions . insert ( here , action ) |
def ping ( host , timeout = False , return_boolean = False ) :
'''Performs a ping to a host
CLI Example :
. . code - block : : bash
salt ' * ' network . ping archlinux . org
. . versionadded : : 2016.11.0
Return a True or False instead of ping output .
. . code - block : : bash
salt ' * ' network . pi... | if timeout : # Windows ping differs by having timeout be for individual echo requests . '
# Divide timeout by tries to mimic BSD behaviour .
timeout = int ( timeout ) * 1000 // 4
cmd = [ 'ping' , '-n' , '4' , '-w' , six . text_type ( timeout ) , salt . utils . network . sanitize_host ( host ) ]
else :
cmd =... |
def randomTraversal ( sensations , numTraversals ) :
"""Given a list of sensations , return the SDRs that would be obtained by
numTraversals random traversals of that set of sensations .
Each sensation is a dict mapping cortical column index to a pair of SDR ' s
( one location and one feature ) .""" | newSensations = [ ]
for _ in range ( numTraversals ) :
s = copy . deepcopy ( sensations )
random . shuffle ( s )
newSensations += s
return newSensations |
def setCurrent ( self , state = True ) :
"""Marks this view as the current source based on the inputed flag . This method will return True if the currency changes .
: return < bool > | changed""" | if self . _current == state :
return False
widget = self . viewWidget ( )
if widget :
for other in widget . findChildren ( type ( self ) ) :
if other . isCurrent ( ) :
other . _current = False
if not other . signalsBlocked ( ) :
other . currentStateChanged . emit ... |
def tripleexprlabel_to_iriref ( self , tripleExprLabel : ShExDocParser . TripleExprLabelContext ) -> Union [ ShExJ . BNODE , ShExJ . IRIREF ] :
"""tripleExprLabel : iri | blankNode""" | if tripleExprLabel . iri ( ) :
return self . iri_to_iriref ( tripleExprLabel . iri ( ) )
else :
return ShExJ . BNODE ( tripleExprLabel . blankNode ( ) . getText ( ) ) |
def describe_keyspaces ( self , ) :
"""list the defined keyspaces in this cluster""" | self . _seqid += 1
d = self . _reqs [ self . _seqid ] = defer . Deferred ( )
self . send_describe_keyspaces ( )
return d |
def t_ID ( t ) :
r'[ a - zA - Z ] [ a - zA - Z0-9 ] * [ $ % ] ?' | t . type = reserved . get ( t . value . lower ( ) , 'ID' )
callables = { api . constants . CLASS . array : 'ARRAY_ID' , }
if t . type != 'ID' :
t . value = t . type
else :
entry = api . global_ . SYMBOL_TABLE . get_entry ( t . value ) if api . global_ . SYMBOL_TABLE is not None else None
if entry :
... |
def q_tank ( sed_inputs = sed_dict ) :
"""Return the maximum flow through one sedimentation tank .
Parameters
sed _ inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed . yaml
Returns
float
Maximum flow through one sedimentation tank
... | return ( sed_inputs [ 'tank' ] [ 'L' ] * sed_inputs [ 'tank' ] [ 'vel_up' ] . to ( u . m / u . s ) * sed_inputs [ 'tank' ] [ 'W' ] . to ( u . m ) ) . magnitude |
def environment_var_to_bool ( env_var ) :
"""Converts an environment variable to a boolean
Returns False if the environment variable is False , 0 or a case - insenstive string " false "
or " 0 " .""" | # Try to see if env _ var can be converted to an int
try :
env_var = int ( env_var )
except ValueError :
pass
if isinstance ( env_var , numbers . Number ) :
return bool ( env_var )
elif is_a_string ( env_var ) :
env_var = env_var . lower ( ) . strip ( )
if env_var in "false" :
return False
... |
def copy_from ( self , src , dest ) :
"""copy a file or a directory from container or image to host system . If you are copying
directories , the target directory must not exist ( this function is using ` shutil . copytree `
to copy directories and that ' s a requirement of the function ) . In case the director... | p = self . p ( src )
if os . path . isfile ( p ) :
logger . info ( "copying file %s to %s" , p , dest )
shutil . copy2 ( p , dest )
else :
logger . info ( "copying directory %s to %s" , p , dest )
shutil . copytree ( p , dest ) |
def elem_add ( self , idx = None , name = None , ** kwargs ) :
"""overloading elem _ add function of a JIT class""" | self . jit_load ( )
if self . loaded :
return self . system . __dict__ [ self . name ] . elem_add ( idx , name , ** kwargs ) |
def _add_plots_to_output ( out , data ) :
"""Add CNVkit plots summarizing called copy number values .""" | out [ "plot" ] = { }
diagram_plot = _add_diagram_plot ( out , data )
if diagram_plot :
out [ "plot" ] [ "diagram" ] = diagram_plot
scatter = _add_scatter_plot ( out , data )
if scatter :
out [ "plot" ] [ "scatter" ] = scatter
scatter_global = _add_global_scatter_plot ( out , data )
if scatter_global :
out [... |
def _DrawTrips ( self , triplist , colpar = "" ) :
"""Generates svg polylines for each transit trip .
Args :
# Class Trip is defined in transitfeed . py
[ Trip , Trip , . . . ]
Returns :
# A string containing a polyline tag for each trip
' < polyline class = " T " stroke = " # 336633 " points = " 433,0 ... | stations = [ ]
if not self . _stations and triplist :
self . _stations = self . _CalculateYLines ( self . _TravelTimes ( triplist ) )
if not self . _stations :
self . _AddWarning ( "Failed to use traveltimes for graph" )
self . _stations = self . _CalculateYLines ( self . _Uniform ( triplist ) )... |
def bind ( cls , origin , handler , * , name = None ) :
"""Bind this object to the given origin and handler .
: param origin : An instance of ` Origin ` .
: param handler : An instance of ` bones . HandlerAPI ` .
: return : A subclass of this class .""" | name = cls . __name__ if name is None else name
attrs = { "_origin" : origin , "_handler" : handler , "__module__" : "origin" , # Could do better ?
}
return type ( name , ( cls , ) , attrs ) |
def do_alarm_definition_delete ( mc , args ) :
'''Delete the alarm definition .''' | fields = { }
fields [ 'alarm_id' ] = args . id
try :
mc . alarm_definitions . delete ( ** fields )
except ( osc_exc . ClientException , k_exc . HttpError ) as he :
raise osc_exc . CommandError ( '%s\n%s' % ( he . message , he . details ) )
else :
print ( 'Successfully deleted alarm definition' ) |
def expect_file_to_be_valid_json ( self , schema = None , result_format = None , include_config = False , catch_exceptions = None , meta = None ) :
"""schema : string
optional JSON schema file on which JSON data file is validated against
result _ format ( str or None ) :
Which output mode to use : ` BOOLEAN _... | success = False
if schema is None :
try :
with open ( self . _path , 'r' ) as f :
json . load ( f )
success = True
except ValueError :
success = False
else :
try :
with open ( schema , 'r' ) as s :
schema_data = s . read ( )
sdata = json . load... |
def get_bonded_structure ( self , structure , decorate = False ) :
"""Obtain a MoleculeGraph object using this NearNeighbor
class . Requires the optional dependency networkx
( pip install networkx ) .
Args :
structure : Molecule object .
decorate ( bool ) : whether to annotate site properties
with order... | # requires optional dependency which is why it ' s not a top - level import
from pymatgen . analysis . graphs import MoleculeGraph
if decorate : # Decorate all sites in the underlying structure
# with site properties that provides information on the
# coordination number and coordination pattern based
# on the ( curren... |
def delete ( self , using = None , soft = True , * args , ** kwargs ) :
"""Soft delete object ( set its ` ` is _ removed ` ` field to True ) .
Actually delete object if setting ` ` soft ` ` to False .""" | if soft :
self . is_removed = True
self . save ( using = using )
else :
return super ( SoftDeletableModel , self ) . delete ( using = using , * args , ** kwargs ) |
def append ( self , key , value , format = None , append = True , columns = None , dropna = None , ** kwargs ) :
"""Append to Table in file . Node must already exist and be Table
format .
Parameters
key : object
value : { Series , DataFrame }
format : ' table ' is the default
table ( t ) : table format ... | if columns is not None :
raise TypeError ( "columns is not a supported keyword in append, " "try data_columns" )
if dropna is None :
dropna = get_option ( "io.hdf.dropna_table" )
if format is None :
format = get_option ( "io.hdf.default_format" ) or 'table'
kwargs = self . _validate_format ( format , kwargs... |
def _begin_disconnection_action ( self , action ) :
"""Begin a disconnection attempt
Args :
action ( ConnectionAction ) : the action object describing what we are
connecting to and what the result of the operation was""" | conn_key = action . data [ 'id' ]
callback = action . data [ 'callback' ]
if self . _get_connection_state ( conn_key ) != self . Idle :
callback ( conn_key , self . id , False , 'Cannot start disconnection, connection is not idle' )
return
# Cannot be None since we checked above to make sure it exists
data = se... |
def _parse_header_id ( line ) :
"""Pull the transcript or protein identifier from the header line
which starts with ' > '""" | if type ( line ) is not binary_type :
raise TypeError ( "Expected header line to be of type %s but got %s" % ( binary_type , type ( line ) ) )
if len ( line ) <= 1 :
raise ValueError ( "No identifier on FASTA line" )
# split line at first space to get the unique identifier for
# this sequence
space_index = line... |
def get_queryset ( self ) :
"""Returns the list of items for this view .""" | forums = self . request . forum_permission_handler . get_moderation_queue_forums ( self . request . user , )
qs = super ( ) . get_queryset ( )
qs = qs . filter ( topic__forum__in = forums , approved = False )
return qs . order_by ( '-created' ) |
def config ( self ) :
"""load the passwords from the config file""" | if not hasattr ( self , '_config' ) :
raw_config = configparser . RawConfigParser ( )
f = self . _open ( )
if f :
raw_config . readfp ( f )
f . close ( )
self . _config = raw_config
return self . _config |
def is_inside_bounds ( value , params ) :
"""Return ` ` True ` ` if ` ` value ` ` is contained in ` ` params ` ` .
This method supports broadcasting in the sense that for
` ` params . ndim > = 2 ` ` , if more than one value is given , the inputs
are broadcast against each other .
Parameters
value : ` arra... | if value in params : # Single parameter
return True
else :
if params . ndim == 1 :
return params . contains_all ( np . ravel ( value ) )
else : # Flesh out and flatten to check bounds
bcast_value = np . broadcast_arrays ( * value )
stacked_value = np . vstack ( bcast_value )
... |
def move_tab ( self , index_from , index_to ) :
"""Move tab ( tabs themselves have already been moved by the tabwidget )""" | filename = self . filenames . pop ( index_from )
client = self . clients . pop ( index_from )
self . filenames . insert ( index_to , filename )
self . clients . insert ( index_to , client )
self . update_tabs_text ( )
self . sig_update_plugin_title . emit ( ) |
def ExtractEvents ( self , parser_mediator , registry_key , ** kwargs ) :
"""Extracts events from a Windows Registry key .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
registry _ key ( dfwinreg . WinRegistryKey ) : Win... | for subkey in registry_key . GetSubkeys ( ) :
drive_letter = subkey . name
if not drive_letter :
continue
values_dict = { 'DriveLetter' : drive_letter , 'Type' : 'Mapped Drive' }
# Get the remote path if it exists .
remote_path_value = subkey . GetValueByName ( 'RemotePath' )
if remote_p... |
def put_annotation ( self , key , value ) :
"""Annotate current active trace entity with a key - value pair .
Annotations will be indexed for later search query .
: param str key : annotation key
: param object value : annotation value . Any type other than
string / number / bool will be dropped""" | entity = self . get_trace_entity ( )
if entity and entity . sampled :
entity . put_annotation ( key , value ) |
def sources_to_nr_vars ( sources ) :
"""Converts a source type to number of sources mapping into
a source numbering variable to number of sources mapping .
If , for example , we have ' point ' , ' gaussian ' and ' sersic '
source types , then passing the following dict as an argument
sources _ to _ nr _ var... | sources = default_sources ( ** sources )
try :
return OrderedDict ( ( SOURCE_VAR_TYPES [ name ] , nr ) for name , nr in sources . iteritems ( ) )
except KeyError as e :
raise KeyError ( ( 'No source type ' '%s' ' is ' 'registered. Valid source types ' 'are %s' ) % ( e , SOURCE_VAR_TYPES . keys ( ) ) ) |
def clean ( self , data ) :
"""Method returns cleaned list of stock closing prices
( i . e . dict ( date = datetime . date ( 2015 , 1 , 2 ) , price = ' 23.21 ' ) ) .""" | cleaned_data = list ( )
if not isinstance ( data , list ) :
data = [ data ]
for item in data :
date = datetime . datetime . strptime ( item [ 'Date' ] , '%Y-%m-%d' ) . date ( )
cleaned_data . append ( dict ( price = item [ 'Adj_Close' ] , date = date ) )
return cleaned_data |
def getAllChildNodes ( self ) :
'''getAllChildNodes - Gets all the children , and their children ,
and their children , and so on , all the way to the end as a TagCollection .
Use . childNodes for a regular list
@ return TagCollection < AdvancedTag > - A TagCollection of all children ( and their children recu... | ret = TagCollection ( )
# Scan all the children of this node
for child in self . children : # Append each child
ret . append ( child )
# Append children ' s children recursive
ret += child . getAllChildNodes ( )
return ret |
def _is_valid_datatype ( datatype_instance ) :
"""Returns true if datatype _ instance is a valid datatype object and false otherwise .""" | # Remap so we can still use the python types for the simple cases
global _simple_type_remap
if datatype_instance in _simple_type_remap :
return True
# Now set the protobuf from this interface .
if isinstance ( datatype_instance , ( Int64 , Double , String , Array ) ) :
return True
elif isinstance ( datatype_ins... |
def get_hw_virt_ex_property ( self , property_p ) :
"""Returns the value of the specified hardware virtualization boolean property .
in property _ p of type : class : ` HWVirtExPropertyType `
Property type to query .
return value of type bool
Property value .
raises : class : ` OleErrorInvalidarg `
Inva... | if not isinstance ( property_p , HWVirtExPropertyType ) :
raise TypeError ( "property_p can only be an instance of type HWVirtExPropertyType" )
value = self . _call ( "getHWVirtExProperty" , in_p = [ property_p ] )
return value |
def get_instance ( self , payload ) :
"""Build an instance of TaskInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . autopilot . v1 . assistant . task . TaskInstance
: rtype : twilio . rest . autopilot . v1 . assistant . task . TaskInstance""" | return TaskInstance ( self . _version , payload , assistant_sid = self . _solution [ 'assistant_sid' ] , ) |
def process_request ( self , request ) :
"""Process a request .""" | batcher = PrioritizedBatcher . global_instance ( )
if batcher . is_started : # This can happen in old - style middleware if consequent middleware
# raises exception and thus ` process _ response ` is not called .
# Described under 3rd point of differences :
# https : / / docs . djangoproject . com / en / 1.11 / topics ... |
def map_frames ( self , old_indices ) :
'''Rewrite the feature indexes based on the next frame ' s identities
old _ indices - for each feature in the new frame , the index of the
old feature''' | nfeatures = len ( old_indices )
noldfeatures = len ( self . state_vec )
if nfeatures > 0 :
self . state_vec = self . state_vec [ old_indices ]
self . state_cov = self . state_cov [ old_indices ]
self . noise_var = self . noise_var [ old_indices ]
if self . has_cached_obs_vec :
self . obs_vec = s... |
def simulate ( t = 1000 , poly = ( 0. , ) , sinusoids = None , sigma = 0 , rw = 0 , irw = 0 , rrw = 0 ) :
"""Simulate a random signal with seasonal ( sinusoids ) , linear and quadratic trend , RW , IRW , and RRW
Arguments :
t ( int or list of float ) : number of samples or time vector , default = 1000
poly ( ... | if t and isinstance ( t , int ) :
t = np . arange ( t , dtype = np . float64 )
else :
t = np . array ( t , dtype = np . float64 )
N = len ( t )
poly = poly or ( 0. , )
poly = listify ( poly )
y = np . polyval ( poly , t )
sinusoids = listify ( sinusoids or [ ] )
if any ( isinstance ( ATP , ( int , float ) ) for... |
def get_filename ( self ) :
"""Return ` ` self . filename ` ` if set otherwise return the template basename with a ` ` . pdf ` ` extension .
: rtype : str""" | if self . filename is None :
name = splitext ( basename ( self . template_name ) ) [ 0 ]
return '{}.pdf' . format ( name )
return self . filename |
def comparable ( self ) :
"""str : comparable representation of the path specification .""" | sub_comparable_string = 'location: {0:s}' . format ( self . location )
return self . _GetComparable ( sub_comparable_string = sub_comparable_string ) |
def get_setting ( self , key , converter = None , choices = None ) :
'''Returns the settings value for the provided key .
If converter is str , unicode , bool or int the settings value will be
returned converted to the provided type .
If choices is an instance of list or tuple its item at position of the
se... | # TODO : allow pickling of settings items ?
# TODO : STUB THIS OUT ON CLI
value = self . addon . getSetting ( id = key )
if converter is str :
return value
elif converter is unicode :
return value . decode ( 'utf-8' )
elif converter is bool :
return value == 'true'
elif converter is int :
return int ( v... |
def _from_dict ( cls , _dict ) :
"""Initialize a TranslationModels object from a json dictionary .""" | args = { }
if 'models' in _dict :
args [ 'models' ] = [ TranslationModel . _from_dict ( x ) for x in ( _dict . get ( 'models' ) ) ]
else :
raise ValueError ( 'Required property \'models\' not present in TranslationModels JSON' )
return cls ( ** args ) |
def draw_points ( self , * points ) :
"""Draw multiple points on the current rendering target .
Args :
* points ( Point ) : The points to draw .
Raises :
SDLError : If an error is encountered .""" | point_array = ffi . new ( 'SDL_Point[]' , len ( points ) )
for i , p in enumerate ( points ) :
point_array [ i ] = p . _ptr [ 0 ]
check_int_err ( lib . SDL_RenderDrawPoints ( self . _ptr , point_array , len ( points ) ) ) |
def to_dict ( self , remove_nones = False ) :
"""Creates a dictionary representation of the object .
: param remove _ nones : Whether ` ` None ` ` values should be filtered out of the dictionary . Defaults to ` ` False ` ` .
: return : The dictionary representation .""" | if remove_nones :
return { k : v for k , v in self . to_dict ( ) . items ( ) if v is not None }
else :
raise NotImplementedError ( ) |
def show_prediction_labels_on_image ( img_path , predictions ) :
"""Shows the face recognition results visually .
: param img _ path : path to image to be recognized
: param predictions : results of the predict function
: return :""" | pil_image = Image . open ( img_path ) . convert ( "RGB" )
draw = ImageDraw . Draw ( pil_image )
for name , ( top , right , bottom , left ) in predictions : # Draw a box around the face using the Pillow module
draw . rectangle ( ( ( left , top ) , ( right , bottom ) ) , outline = ( 0 , 0 , 255 ) )
# There ' s a ... |
def addTable ( D ) :
"""Add any table type to the given dataset . Use prompts to determine index locations and table type .
: param dict D : Metadata ( dataset )
: param dict dat : Metadata ( table )
: return dict D : Metadata ( dataset )""" | _swap = { "1" : "measurement" , "2" : "summary" , "3" : "ensemble" , "4" : "distribution" }
print ( "What type of table would you like to add?\n" "1: measurement\n" "2: summary\n" "3: ensemble (under development)\n" "4: distribution (under development)\n" "\n Note: if you want to add a whole model, use the addModel() f... |
def restore ( self ) :
"""Restore the application config files .
Algorithm :
if exists mackup / file
if exists home / file
are you sure ?
if sure
rm home / file
link mackup / file home / file
else
link mackup / file home / file""" | # For each file used by the application
for filename in self . files :
( home_filepath , mackup_filepath ) = self . getFilepaths ( filename )
# If the file exists and is not already pointing to the mackup file
# and the folder makes sense on the current platform ( Don ' t sync
# any subfolder of ~ / Lib... |
def wrap_json_body ( func = None , * , preserve_raw_body = False ) :
"""A middleware that parses the body of json requests and
add it to the request under the ` body ` attribute ( replacing
the previous value ) . Can preserve the original value in
a new attribute ` raw _ body ` if you give preserve _ raw _ bo... | if func is None :
return functools . partial ( wrap_json_body , preserve_raw_body = preserve_raw_body )
@ functools . wraps ( func )
def wrapper ( request , * args , ** kwargs ) :
ctype , pdict = parse_header ( request . headers . get ( 'Content-Type' , '' ) )
if preserve_raw_body :
request . raw_bo... |
def extractDates ( inp , tz = None , now = None ) :
"""Extract semantic date information from an input string .
This is a convenience method which would only be used if
you ' d rather not initialize a DateService object .
Args :
inp ( str ) : The input string to be parsed .
tz : An optional Pytz timezone ... | service = DateService ( tz = tz , now = now )
return service . extractDates ( inp ) |
def handler ( self , event , context ) :
"""An AWS Lambda function which parses specific API Gateway input into a
WSGI request , feeds it to our WSGI app , procceses the response , and returns
that back to the API Gateway .""" | settings = self . settings
# If in DEBUG mode , log all raw incoming events .
if settings . DEBUG :
logger . debug ( 'Zappa Event: {}' . format ( event ) )
# Set any API Gateway defined Stage Variables
# as env vars
if event . get ( 'stageVariables' ) :
for key in event [ 'stageVariables' ] . keys ( ) :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.