signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_options ( ) :
"""get the command line switches""" | parser = argparse . ArgumentParser ( description = 'denovonear cli interface' )
# CLI options in common
parent = argparse . ArgumentParser ( add_help = False )
parent . add_argument ( "--out" , help = "output filename" )
parent . add_argument ( "--rates" , help = "Path to file containing sequence context-based mutation... |
async def parse_target ( self , runtime , target_str ) :
'''A target is a pipeline of a module into zero or more rules , and each
module and rule can itself be scoped with zero or more module names .''' | pipeline_parts = target_str . split ( RULE_SEPARATOR )
module = await self . resolve_module ( runtime , pipeline_parts [ 0 ] , target_str )
rules = [ ]
for part in pipeline_parts [ 1 : ] :
rule = await self . resolve_rule ( runtime , part )
rules . append ( rule )
return module , tuple ( rules ) |
async def factory ( self , request , path = "/" , as_ = None ) :
"""The user will ask for / path / to / the / parent / new / member - list
Where member - list is the list where the parent saves the children order
So in the test model MinimalMongoTree the only factory will be / new / children""" | counter , time = perf_counter ( ) , process_time ( )
if not path . startswith ( "/" ) :
path = "/{}" . format ( path )
resp = await self . resolve_path ( path )
if resp :
if "path" not in request . json :
request . json [ "path" ] = path
method = getattr ( resp [ "model" ] , resp [ "model" ] . facto... |
def get_item_ids ( self ) :
"""get item ids associated with this assessment part""" | if self . has_item_ids ( ) :
return IdList ( self . my_osid_object . _my_map [ 'itemIds' ] , runtime = self . my_osid_object . _runtime , proxy = self . my_osid_object . _proxy )
raise IllegalState ( ) |
def Validate ( self , value ) :
"""Validate an RDFValue instance .
Args :
value : An RDFValue instance or something which may be used to instantiate
the correct instance .
Raises :
TypeValueError : If the value is not a valid RDFValue instance or the
required type .
Returns :
A Valid RDFValue instan... | # Allow None as a default .
if value is None :
return
if not isinstance ( value , self . rdfclass ) : # Try to coerce the type to the correct rdf _ class .
try :
return self . rdfclass ( value )
except rdfvalue . InitializeError :
raise TypeValueError ( "Value for arg %s should be an %s" % (... |
def move_optimizer_to_cuda ( optimizer ) :
"""Move the optimizer state to GPU , if necessary .
After calling , any parameter specific state in the optimizer
will be located on the same device as the parameter .""" | for param_group in optimizer . param_groups :
for param in param_group [ 'params' ] :
if param . is_cuda :
param_state = optimizer . state [ param ]
for k in param_state . keys ( ) :
if isinstance ( param_state [ k ] , torch . Tensor ) :
param_stat... |
def build_option_parser ( self , description , version ) :
"""Return an argparse option parser for this application .
Subclasses may override this method to extend
the parser with more global options .
: param description : full description of the application
: paramtype description : str
: param version ... | parser = argparse . ArgumentParser ( description = description , add_help = False , )
parser . add_argument ( '--version' , action = 'version' , version = __version__ , )
parser . add_argument ( '-v' , '--verbose' , '--debug' , action = 'count' , dest = 'verbose_level' , default = self . DEFAULT_VERBOSE_LEVEL , help = ... |
def alias_name ( self , alias_name = None , is_previous_name = None , hgnc_symbol = None , hgnc_identifier = None , limit = None , as_df = False ) :
"""Method to query : class : ` . models . AliasName ` objects in database
: param alias _ name : alias name ( s )
: type alias _ name : str or tuple ( str ) or Non... | q = self . session . query ( models . AliasName )
model_queries_config = ( ( alias_name , models . AliasName . alias_name ) , ( is_previous_name , models . AliasName . is_previous_name ) , )
q = self . get_model_queries ( q , model_queries_config )
one_to_many_queries_config = ( ( hgnc_symbol , models . HGNC . symbol )... |
def delete_metric ( name ) :
"""Remove the named metric""" | with LOCK :
old_metric = REGISTRY . pop ( name , None )
# look for the metric name in the tags and remove it
for _ , tags in py3comp . iteritems ( TAGS ) :
if name in tags :
tags . remove ( name )
return old_metric |
def log_url ( self , url_data ) :
"""Write one node .""" | node = self . get_node ( url_data )
if node is not None :
self . writeln ( u' "%s" [' % dotquote ( node [ "label" ] ) )
if self . has_part ( "realurl" ) :
self . writeln ( u' href="%s",' % dotquote ( node [ "url" ] ) )
if node [ "dltime" ] >= 0 and self . has_part ( "dltime" ) :
self . w... |
def divide ( self , x1 , x2 , out = None ) :
"""Return the pointwise quotient of ` ` x1 ` ` and ` ` x2 ` `
Parameters
x1 : ` LinearSpaceElement `
Dividend in the quotient .
x2 : ` LinearSpaceElement `
Divisor in the quotient .
out : ` LinearSpaceElement ` , optional
Element to which the result is writ... | if out is None :
out = self . element ( )
if out not in self :
raise LinearSpaceTypeError ( '`out` {!r} is not an element of ' '{!r}' . format ( out , self ) )
if x1 not in self :
raise LinearSpaceTypeError ( '`x1` {!r} is not an element of ' '{!r}' . format ( x1 , self ) )
if x2 not in self :
raise Lin... |
def validate_tag ( self , key , value ) :
"""Check whether a tag value is valid
Args :
key : A tag key
value : A tag value
Returns :
` ( True or False ) `
A boolean indicating whether or not the value is valid""" | if key == 'owner' :
return validate_email ( value , self . partial_owner_match )
elif key == self . gdpr_tag :
return value in self . gdpr_tag_values
else :
return True |
def filter ( self , condition ) :
"""Filters rows using the given condition .
: func : ` where ` is an alias for : func : ` filter ` .
: param condition : a : class : ` Column ` of : class : ` types . BooleanType `
or a string of SQL expression .
> > > df . filter ( df . age > 3 ) . collect ( )
[ Row ( ag... | if isinstance ( condition , basestring ) :
jdf = self . _jdf . filter ( condition )
elif isinstance ( condition , Column ) :
jdf = self . _jdf . filter ( condition . _jc )
else :
raise TypeError ( "condition should be string or Column" )
return DataFrame ( jdf , self . sql_ctx ) |
def add_contact ( self , contact_id , scope = 'contact/invite' ) :
"""Add a contact
contact _ id can either be the mxit ID of a service or a Mxit user
User authentication required with the following scope : ' contact / invite '""" | return _put ( token = self . oauth . get_user_token ( scope ) , uri = '/user/socialgraph/contact/' + urllib . quote ( contact_id ) ) |
def create_card ( self , note = github . GithubObject . NotSet , content_id = github . GithubObject . NotSet , content_type = github . GithubObject . NotSet ) :
""": calls : ` POST / projects / columns / : column _ id / cards < https : / / developer . github . com / v3 / projects / cards / # create - a - project - ... | post_parameters = { }
if isinstance ( note , ( str , unicode ) ) :
assert content_id is github . GithubObject . NotSet , content_id
assert content_type is github . GithubObject . NotSet , content_type
post_parameters = { "note" : note }
else :
assert note is github . GithubObject . NotSet , note
ass... |
def apply_templates ( toks , templates ) :
"""Generate features for an item sequence by applying feature templates .
A feature template consists of a tuple of ( name , offset ) pairs ,
where name and offset specify a field name and offset from which
the template extracts a feature value . Generated features a... | for template in templates :
name = '|' . join ( [ '%s[%d]' % ( f , o ) for f , o in template ] )
for t in range ( len ( toks ) ) :
values_list = [ ]
for field , offset in template :
p = t + offset
if p < 0 or p >= len ( toks ) :
values_list = [ ]
... |
def _tchelper ( tc_deps , evals , deps ) :
"""modifies graph in place""" | for e in evals :
if e in tc_deps : # we ' ve already included it
continue
else :
if e in deps : # has additional dependnecies
tc_deps [ e ] = deps [ e ]
# add to tc _ deps the dependencies of the dependencies
_tchelper ( tc_deps , deps [ e ] , deps )
return tc... |
def __sort_up ( self ) :
"""Sort the updatable objects according to ascending order""" | if self . __do_need_sort_up :
self . __up_objects . sort ( self . __up_cmp )
self . __do_need_sort_up = False |
def __update_density ( self , compound = '' , element = '' ) :
"""Re - calculate the density of the element given due to stoichiometric changes as
well as the compound density ( if density is not locked )
Parameters :
compound : string ( default is ' ' ) name of compound
element : string ( default is ' ' ) ... | _density_element = 0
list_ratio = self . stack [ compound ] [ element ] [ 'isotopes' ] [ 'isotopic_ratio' ]
list_density = self . stack [ compound ] [ element ] [ 'isotopes' ] [ 'density' ] [ 'value' ]
ratio_density = zip ( list_ratio , list_density )
for _ratio , _density in ratio_density :
_density_element += np ... |
def _download_ned_source_metadata ( self ) :
"""* Query NED using the names of the NED sources in our local database to retrieve extra metadata *
* Usage : *
. . code - block : : python
stream . _ download _ ned _ source _ metadata ( )""" | self . log . debug ( 'starting the ``_download_ned_source_metadata`` method' )
self . dbTableName = "tcs_cat_ned_stream"
total , batches = self . _count_ned_sources_in_database_requiring_metadata ( )
self . log . info ( "%(total)s galaxies require metadata. Need to send %(batches)s batch requests to NED." % locals ( ) ... |
def gitignore_templates ( self ) :
"""Returns the list of available templates .
: returns : list of template names""" | url = self . _build_url ( 'gitignore' , 'templates' )
return self . _json ( self . _get ( url ) , 200 ) or [ ] |
def _pdf ( self , xloc , left , right , cache ) :
"""Probability density function .
Example :
> > > print ( chaospy . Uniform ( ) . pdf ( [ - 2 , 0 , 2 , 4 ] ) )
[0 . 1 . 0 . 0 . ]
> > > print ( chaospy . Add ( chaospy . Uniform ( ) , 2 ) . pdf ( [ - 2 , 0 , 2 , 4 ] ) )
[0 . 0 . 1 . 0 . ]
> > > print ( ... | left = evaluation . get_forward_cache ( left , cache )
right = evaluation . get_forward_cache ( right , cache )
if isinstance ( left , Dist ) :
if isinstance ( right , Dist ) :
raise evaluation . DependencyError ( "under-defined distribution {} or {}" . format ( left , right ) )
elif not isinstance ( right ... |
def grid ( self , dimensions = None , ** kwargs ) :
"""Groups data by supplied dimension ( s ) laying the groups along
the dimension ( s ) out in a GridSpace .
Args :
dimensions : Dimension / str or list
Dimension or list of dimensions to group by
Returns :
grid : GridSpace
GridSpace with supplied dim... | return self . groupby ( dimensions , container_type = GridSpace , ** kwargs ) |
def serialize_to_json ( self , response_data ) :
"""Returns the JSON string for the compiled data object .""" | indent = None
if settings . DEBUG :
indent = 4
# Serialize to JSON with Django ' s encoder : Adds date / time , decimal ,
# and UUID support .
return json . dumps ( response_data , indent = indent , cls = DjangoJSONEncoder ) |
def create_context ( self , state_hash , base_contexts , inputs , outputs ) :
"""Create a ExecutionContext to run a transaction against .
Args :
state _ hash : ( str ) : Merkle root to base state on .
base _ contexts ( list of str ) : Context ids of contexts that will
have their state applied to make this c... | for address in inputs :
if not self . namespace_is_valid ( address ) :
raise CreateContextException ( "Address or namespace {} listed in inputs is not " "valid" . format ( address ) )
for address in outputs :
if not self . namespace_is_valid ( address ) :
raise CreateContextException ( "Address ... |
def starts_by_depth ( bam_file , data , sample_size = 10000000 ) :
"""Return a set of x , y points where x is the number of reads sequenced and
y is the number of unique start sites identified
If sample size < total reads in a file the file will be downsampled .""" | binsize = ( sample_size / 100 ) + 1
seen_starts = set ( )
counted = 0
num_reads = [ ]
starts = [ ]
buffer = [ ]
downsampled = bam . downsample ( bam_file , data , sample_size )
with bam . open_samfile ( downsampled ) as samfile :
for read in samfile :
if read . is_unmapped :
continue
cou... |
def main ( ) :
"""Get an info report for a tile . Format is same as input tile but with
min / max values for values under ' data ' .""" | arguments = docopt ( __doc__ , version = 'tileinfo 0.1' )
src_name = arguments [ 'SOURCE' ]
src_format = arguments [ '--srcformat' ]
indent = arguments [ '--indent' ]
if isinstance ( indent , str ) and indent . lower ( ) == 'none' :
indent = None
elif isinstance ( indent , str ) :
indent = int ( indent )
else :... |
def list_external_jar_dependencies ( self , binary ) :
"""Returns the external jar dependencies of the given binary .
: param binary : The jvm binary target to list transitive external dependencies for .
: type binary : : class : ` pants . backend . jvm . targets . jvm _ binary . JvmBinary `
: returns : A lis... | classpath_products = self . context . products . get_data ( 'runtime_classpath' )
classpath_entries = classpath_products . get_artifact_classpath_entries_for_targets ( binary . closure ( bfs = True , include_scopes = Scopes . JVM_RUNTIME_SCOPES , respect_intransitive = True ) )
external_jars = OrderedSet ( jar_entry fo... |
def get_reference_templates ( self , ref_types ) :
"""Return the reference templates for the types as an ordered dictionary .""" | return OrderedDict ( [ ( x , self . get_reference_template ( x ) ) for x in ref_types ] ) |
def show_messages ( self ) :
"""Show all messages .""" | if isinstance ( self . static_message , MessageElement ) : # Handle sent Message instance
string = html_header ( )
if self . static_message is not None :
string += self . static_message . to_html ( )
# Keep track of the last ID we had so we can scroll to it
self . last_id = 0
for message in ... |
def list_probes ( ) :
"""Return the list of built - in probes .""" | curdir = op . realpath ( op . dirname ( __file__ ) )
return [ op . splitext ( fn ) [ 0 ] for fn in os . listdir ( op . join ( curdir , 'probes' ) ) if fn . endswith ( '.prb' ) ] |
def is_abstract_model ( model ) :
"""Given a model class , returns a boolean True if it is abstract and False if it is not .""" | return hasattr ( model , '_meta' ) and hasattr ( model . _meta , 'abstract' ) and model . _meta . abstract |
def main ( self , input ) :
""": type input : Complex
: rtype : Sfix""" | demod = self . demod . main ( input )
match = self . match . main ( demod )
return match |
def download_with_progress ( url , chunk_size , ** progress_kwargs ) :
"""Download streaming data from a URL , printing progress information to the
terminal .
Parameters
url : str
A URL that can be understood by ` ` requests . get ` ` .
chunk _ size : int
Number of bytes to read at a time from requests ... | resp = requests . get ( url , stream = True )
resp . raise_for_status ( )
total_size = int ( resp . headers [ 'content-length' ] )
data = BytesIO ( )
with progressbar ( length = total_size , ** progress_kwargs ) as pbar :
for chunk in resp . iter_content ( chunk_size = chunk_size ) :
data . write ( chunk )
... |
def min_cov_determinant ( prices , frequency = 252 , random_state = None ) :
"""Calculate the minimum covariance determinant , an estimator of the covariance matrix
that is more robust to noise .
: param prices : adjusted closing prices of the asset , each row is a date
and each column is a ticker / id .
: ... | if not isinstance ( prices , pd . DataFrame ) :
warnings . warn ( "prices are not in a dataframe" , RuntimeWarning )
prices = pd . DataFrame ( prices )
assets = prices . columns
X = prices . pct_change ( ) . dropna ( how = "all" )
X = np . nan_to_num ( X . values )
raw_cov_array = covariance . fast_mcd ( X , ra... |
def CheckApproversForLabel ( self , token , client_urn , requester , approvers , label ) :
"""Checks if requester and approvers have approval privileges for labels .
Checks against list of approvers for each label defined in approvers . yaml to
determine if the list of approvers is sufficient .
Args :
token... | auth = self . reader . GetAuthorizationForSubject ( label )
if not auth : # This label isn ' t listed in approvers . yaml
return True
if auth . requester_must_be_authorized :
if not self . CheckPermissions ( requester , label ) :
raise access_control . UnauthorizedAccess ( "User %s not in %s or groups:%... |
def mkAutoGui ( self ) :
""": summary : automatically generate simple gui in TCL""" | gui = GuiBuilder ( )
p0 = gui . page ( "Main" )
handlers = [ ]
for p in self . iterParams ( self . top ) :
name = self . getParamPhysicalName ( p )
p0 . param ( name )
for fn in paramManipulatorFns ( name ) :
handlers . append ( fn )
with open ( self . guiFile , "w" ) as f :
f . write ( gui . as... |
async def fetch_status ( self , request ) :
'''Fetches information pertaining to the valiator ' s status .''' | response = await self . _query_validator ( Message . CLIENT_STATUS_GET_REQUEST , client_status_pb2 . ClientStatusGetResponse , client_status_pb2 . ClientStatusGetRequest ( ) )
return self . _wrap_response ( request , data = { 'peers' : response [ 'peers' ] , 'endpoint' : response [ 'endpoint' ] } , metadata = self . _g... |
def bulk_create_posts ( self , posts , post_categories , post_tags , post_media_attachments ) :
"""Actually do a db bulk creation of posts , and link up the many - to - many fields
: param posts : the list of Post objects to bulk create
: param post _ categories : a mapping of Categories to add to newly created... | Post . objects . bulk_create ( posts )
# attach many - to - ones
for post_wp_id , categories in six . iteritems ( post_categories ) :
Post . objects . get ( site_id = self . site_id , wp_id = post_wp_id ) . categories . add ( * categories )
for post_id , tags in six . iteritems ( post_tags ) :
Post . objects . ... |
def open_local_file ( self , url ) :
"""Use local file .""" | import future . backports . email . utils as email_utils
import mimetypes
host , file = splithost ( url )
localname = url2pathname ( file )
try :
stats = os . stat ( localname )
except OSError as e :
raise URLError ( e . strerror , e . filename )
size = stats . st_size
modified = email_utils . formatdate ( stat... |
def total ( self ) :
"""Return the total number of records""" | if self . _result_cache :
return self . _result_cache . total
return self . all ( ) . total |
def read ( self , req , ino , size , off , fi ) :
"""Read data
Valid replies :
reply _ buf
reply _ err""" | self . reply_err ( req , errno . EIO ) |
def nlmsg_flags ( self , value ) :
"""Message flags setter .""" | self . bytearray [ self . _get_slicers ( 2 ) ] = bytearray ( c_uint16 ( value or 0 ) ) |
def createNorthPointer ( self ) :
'''Creates the north pointer relative to current heading .''' | self . headingNorthTri = patches . RegularPolygon ( ( 0.0 , 0.80 ) , 3 , 0.05 , color = 'k' , zorder = 4 )
self . axes . add_patch ( self . headingNorthTri )
self . headingNorthText = self . axes . text ( 0.0 , 0.675 , 'N' , color = 'k' , size = self . fontSize , horizontalalignment = 'center' , verticalalignment = 'ce... |
def align ( self , per_series_aligner , seconds = 0 , minutes = 0 , hours = 0 ) :
"""Copy the query and add temporal alignment .
If ` ` per _ series _ aligner ` ` is not : data : ` Aligner . ALIGN _ NONE ` , each time
series will contain data points only on the period boundaries .
Example : :
from google . ... | new_query = copy . deepcopy ( self )
new_query . _per_series_aligner = per_series_aligner
new_query . _alignment_period_seconds = seconds + 60 * ( minutes + 60 * hours )
return new_query |
def update_container ( self , container , blkio_weight = None , cpu_period = None , cpu_quota = None , cpu_shares = None , cpuset_cpus = None , cpuset_mems = None , mem_limit = None , mem_reservation = None , memswap_limit = None , kernel_memory = None , restart_policy = None ) :
"""Update resource configs of one o... | url = self . _url ( '/containers/{0}/update' , container )
data = { }
if blkio_weight :
data [ 'BlkioWeight' ] = blkio_weight
if cpu_period :
data [ 'CpuPeriod' ] = cpu_period
if cpu_shares :
data [ 'CpuShares' ] = cpu_shares
if cpu_quota :
data [ 'CpuQuota' ] = cpu_quota
if cpuset_cpus :
data [ 'Cp... |
def period_neighborhood_probability ( self , radius , smoothing , threshold , stride , start_time , end_time ) :
"""Calculate the neighborhood probability over the full period of the forecast
Args :
radius : circular radius from each point in km
smoothing : width of Gaussian smoother in km
threshold : inten... | neighbor_x = self . x [ : : stride , : : stride ]
neighbor_y = self . y [ : : stride , : : stride ]
neighbor_kd_tree = cKDTree ( np . vstack ( ( neighbor_x . ravel ( ) , neighbor_y . ravel ( ) ) ) . T )
neighbor_prob = np . zeros ( ( self . data . shape [ 0 ] , neighbor_x . shape [ 0 ] , neighbor_x . shape [ 1 ] ) )
pr... |
def fetch ( self , method , path , query = None , body = None , timeout = 0 , ** kwargs ) :
"""send a Message
: param method : string , something like " POST " or " GET "
: param path : string , the path part of a uri ( eg , / foo / bar )
: param body : dict , what you want to send to " method path "
: para... | ret = None
if not query :
query = { }
if not body :
body = { }
query . update ( body )
# body takes precedence
body = query
self . send_count += 1
payload = self . get_fetch_request ( method , path , body )
attempts = 1
max_attempts = self . attempts
success = False
while not success :
kwargs [ 'timeout' ] ... |
def update_state ( self ) :
"""Update state with latest info from Wink API .""" | response = self . api_interface . get_device_state ( self , id_override = self . parent . object_id ( ) , type_override = self . parent . object_type ( ) )
self . _update_state_from_response ( response ) |
def register_queryset ( self , queryset , validator = None , default = False ) :
"""Add a given queryset to the iterator with custom logic for iteration .
: param queryset : List of objects included in the reading list .
: param validator : Custom logic to determine a queryset ' s position in a reading _ list .... | if default or self . default_queryset is None :
self . default_queryset = queryset
return
if validator :
self . querysets [ validator ] = queryset
else :
raise ValueError ( """Querysets require validation logic to integrate with reading lists.""" ) |
def _load_jamo_short_names ( ) :
"""Function for parsing the Jamo short names from the Unicode Character Database ( UCD ) and generating a lookup table
For more info on how this is used , see the Unicode Standard , ch . 03 , section 3.12 , " Conjoining Jamo Behavior " and
ch . 04 , section 4.8 , " Name " .
ht... | filename = "Jamo.txt"
current_dir = os . path . abspath ( os . path . dirname ( __file__ ) )
with codecs . open ( os . path . join ( current_dir , filename ) , mode = "r" , encoding = "utf-8" ) as fp :
for line in fp :
if not line . strip ( ) or line . startswith ( "#" ) :
continue
#... |
def printable_str ( text , keep_newlines = False ) :
'''Escape any control or non - ASCII characters from string .
This function is intended for use with strings from an untrusted
source such as writing to a console or writing to logs . It is
designed to prevent things like ANSI escape sequences from
showin... | if isinstance ( text , str ) :
new_text = ascii ( text ) [ 1 : - 1 ]
else :
new_text = ascii ( text )
if keep_newlines :
new_text = new_text . replace ( '\\r' , '\r' ) . replace ( '\\n' , '\n' )
return new_text |
def main ( ) :
"""Sets up our command line options , prints the usage / help ( if warranted ) , and
runs : py : func : ` pyminifier . pyminify ` with the given command line options .""" | usage = '%prog [options] "<input file>"'
if '__main__.py' in sys . argv [ 0 ] : # python - m pyminifier
usage = 'pyminifier [options] "<input file>"'
parser = OptionParser ( usage = usage , version = __version__ )
parser . disable_interspersed_args ( )
parser . add_option ( "-o" , "--outfile" , dest = "outfile" , d... |
def get_mean_error ( x1 , x2 = - 1 , function = "MSE" ) :
"""This function returns desired mean error . Options are : MSE , MAE , RMSE
* * Args : * *
* ` x1 ` - first data series or error ( 1d array )
* * Kwargs : * *
* ` x2 ` - second series ( 1d array ) if first series was not error directly , \ then this... | if function == "MSE" :
return MSE ( x1 , x2 )
elif function == "MAE" :
return MAE ( x1 , x2 )
elif function == "RMSE" :
return RMSE ( x1 , x2 )
else :
raise ValueError ( 'The provided error function is not known' ) |
def get_synset_by_id ( self , mongo_id ) :
'''Builds a Synset object from the database entry with the given
ObjectId .
Arguments :
- ` mongo _ id ` : a bson . objectid . ObjectId object''' | cache_hit = None
if self . _synset_cache is not None :
cache_hit = self . _synset_cache . get ( mongo_id )
if cache_hit is not None :
return cache_hit
synset_dict = self . _mongo_db . synsets . find_one ( { '_id' : mongo_id } )
if synset_dict is not None :
synset = Synset ( self , synset_dict )
if self ... |
def _get_fields_for_class ( schema_graph , graphql_types , field_type_overrides , hidden_classes , cls_name ) :
"""Return a dict from field name to GraphQL field type , for the specified graph class .""" | properties = schema_graph . get_element_by_class_name ( cls_name ) . properties
# Add leaf GraphQL fields ( class properties ) .
all_properties = { property_name : _property_descriptor_to_graphql_type ( property_obj ) for property_name , property_obj in six . iteritems ( properties ) }
result = { property_name : graphq... |
def _ipython_key_completions_ ( self ) :
"""Provide method for the key - autocompletions in IPython .""" | return [ key for key in self . _data . _ipython_key_completions_ ( ) if key not in self . _data . data_vars ] |
def json_encode ( obj : Instance , ** kwargs ) -> str :
"""Encodes an object to JSON using our custom encoder .
The ` ` * * kwargs ` ` can be used to pass things like ` ` ' indent ' ` ` , for
formatting .""" | return json . dumps ( obj , cls = JsonClassEncoder , ** kwargs ) |
def spkw08 ( handle , body , center , inframe , first , last , segid , degree , n , states , epoch1 , step ) : # see libspice args for solution to array [ ] [ N ] problem
"""Write a type 8 segment to an SPK file .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / spkw08 _ c . html
... | handle = ctypes . c_int ( handle )
body = ctypes . c_int ( body )
center = ctypes . c_int ( center )
inframe = stypes . stringToCharP ( inframe )
first = ctypes . c_double ( first )
last = ctypes . c_double ( last )
segid = stypes . stringToCharP ( segid )
degree = ctypes . c_int ( degree )
n = ctypes . c_int ( n )
sta... |
def crude_search_scicrunch_via_label ( self , label : str ) -> dict :
"""Server returns anything that is simlar in any catagory""" | url = self . base_url + 'term/search/{term}?key={api_key}' . format ( term = label , api_key = self . api_key , )
return self . get ( url ) |
def ciphertext_length ( self ) :
"""Returns the length of the resulting ciphertext message in bytes .
: rtype : int""" | return aws_encryption_sdk . internal . formatting . ciphertext_length ( header = self . header , plaintext_length = self . stream_length ) |
def traceroute ( target , dport = 80 , minttl = 1 , maxttl = 30 , sport = RandShort ( ) , l4 = None , filter = None , timeout = 2 , verbose = None , ** kargs ) : # noqa : E501
"""Instant TCP traceroute
traceroute ( target , [ maxttl = 30 , ] [ dport = 80 , ] [ sport = 80 , ] [ verbose = conf . verb ] ) - > None #... | if verbose is None :
verbose = conf . verb
if filter is None : # we only consider ICMP error packets and TCP packets with at
# least the ACK flag set * and * either the SYN or the RST flag
# set
filter = "(icmp and (icmp[0]=3 or icmp[0]=4 or icmp[0]=5 or icmp[0]=11 or icmp[0]=12)) or (tcp and (tcp[13] & 0x16 > ... |
def save ( self , key , data ) :
"""Save data associated with key .""" | self . _db [ key ] = json . dumps ( data )
self . _db . sync ( ) |
def update_node_attributes ( self , attributes_flags = int ( Qt . ItemIsSelectable | Qt . ItemIsEnabled ) ) :
"""Updates the Node attributes .
: param attributes _ flags : Attributes flags .
: type attributes _ flags : int
: return : Method success .
: rtype : bool""" | self . traced . value = foundations . trace . is_traced ( self . __module )
self . traced . roles [ Qt . DisplayRole ] = foundations . strings . to_string ( self . traced . value ) . title ( ) |
def do_execute ( self ) :
"""The actual execution of the actor .
: return : None if successful , otherwise error message
: rtype : str""" | conv = self . config [ "setup" ] . shallow_copy ( )
conv . input = self . _input . payload
result = conv . convert ( )
if result is None :
if conv . output is not None :
self . _output . append ( Token ( conv . output ) )
return None |
def create_object ( cls , members ) :
"""Promise an object of class ` cls ` with content ` members ` .""" | obj = cls . __new__ ( cls )
obj . __dict__ = members
return obj |
def count ( self , request , filter = None ) :
"""Return the number of records matching the given filter .""" | if filter is None :
filter = create_filter ( request , self . mapped_class , self . geom_attr )
query = self . Session ( ) . query ( self . mapped_class )
if filter is not None :
query = query . filter ( filter )
return query . count ( ) |
def _collect_for_instance ( self , instance , connection ) :
"""Collects metrics for a named connection .""" | with connection . cursor ( ) as cursor :
for queue , metrics in self . get_queue_info ( instance , cursor ) :
for name , metric in metrics . items ( ) :
self . publish ( '.' . join ( ( instance , queue , name ) ) , metric )
with connection . cursor ( ) as cursor :
consumers = self . get_cons... |
def log_player_plays_monopoly ( self , player , resource ) :
""": param player : catan . game . Player
: param resource : catan . board . Terrain""" | self . _logln ( '{0} plays monopoly on {1}' . format ( player . color , resource . value ) ) |
def to_dade_matrix ( M , annotations = "" , filename = None ) :
"""Returns a Dade matrix from input numpy matrix . Any annotations are added
as header . If filename is provided and valid , said matrix is also saved
as text .""" | n , m = M . shape
A = np . zeros ( ( n + 1 , m + 1 ) )
A [ 1 : , 1 : ] = M
if not annotations :
annotations = np . array ( [ "" for _ in n ] , dtype = str )
A [ 0 , : ] = annotations
A [ : , 0 ] = annotations . T
if filename :
try :
np . savetxt ( filename , A , fmt = '%i' )
print ( "I saved inp... |
def lookup_imagenet_labels ( indices ) :
"""Utility function to return the image net label for the final ` dense ` layer output index .
Args :
indices : Could be a single value or an array of indices whose labels should be looked up .
Returns :
Image net label corresponding to the image category .""" | global _CLASS_INDEX
if _CLASS_INDEX is None :
with open ( os . path . join ( os . path . dirname ( __file__ ) , '../../resources/imagenet_class_index.json' ) ) as f :
_CLASS_INDEX = json . load ( f )
indices = listify ( indices )
return [ _CLASS_INDEX [ str ( idx ) ] [ 1 ] for idx in indices ] |
def account_id ( self , value ) :
"""The account _ id property .
Args :
value ( string ) . the property value .""" | if value == self . _defaults [ 'ai.user.accountId' ] and 'ai.user.accountId' in self . _values :
del self . _values [ 'ai.user.accountId' ]
else :
self . _values [ 'ai.user.accountId' ] = value |
def _hardClip ( sequence , quality , cigartuples ) :
"""Hard clip ( if necessary ) a sequence .
@ param sequence : A C { str } nucleotide sequence .
@ param quality : A C { str } quality string , or a C { list } of C { int } quality
values as returned by pysam , or C { None } if the SAM file had a ' * '
for... | hardClipCount = cigarLength = 0
for ( operation , length ) in cigartuples :
hardClipCount += operation == CHARD_CLIP
cigarLength += length if operation in _CONSUMES_QUERY else 0
sequenceLength = len ( sequence )
if quality is not None :
assert sequenceLength == len ( quality )
clipLeft = clipRight = 0
clipp... |
def is_row_empty ( self , row ) :
"""Returns True if every cell in the row is empty .""" | for cell in row :
if not self . is_cell_empty ( cell ) :
return False
return True |
def _compute_layer_version ( is_defined_within_template , arn ) :
"""Parses out the Layer version from the arn
Parameters
is _ defined _ within _ template bool
True if the resource is a Ref to a resource otherwise False
arn str
ARN of the Resource
Returns
int
The Version of the LayerVersion""" | if is_defined_within_template :
return None
try :
_ , layer_version = arn . rsplit ( ':' , 1 )
layer_version = int ( layer_version )
except ValueError :
raise InvalidLayerVersionArn ( arn + " is an Invalid Layer Arn." )
return layer_version |
def sign_in ( self , email = None , password = None ) :
"""Signs in a user , either with the specified email address and password , or a returning user .""" | from . pages . sign_in import SignIn
sign_in = SignIn ( self . selenium , self . timeout )
sign_in . sign_in ( email , password ) |
def ceil ( x , context = None ) :
"""Return the next higher or equal integer to x .
If the result is not exactly representable , it will be rounded according to
the current context . Note that the rounding step means that it ' s possible
for the result to be smaller than ` ` x ` ` . For example : :
> > > x ... | return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_rint_ceil , ( BigFloat . _implicit_convert ( x ) , ) , context , ) |
def _process_protocol_v2 ( self , argv , ifile , ofile ) :
"""Processes records on the ` input stream optionally writing records to the output stream .
: param ifile : Input file object .
: type ifile : file or InputType
: param ofile : Output file object .
: type ofile : file or OutputType
: return : : c... | debug = environment . splunklib_logger . debug
class_name = self . __class__ . __name__
debug ( '%s.process started under protocol_version=2' , class_name )
self . _protocol_version = 2
# Read search command metadata from splunkd
# noinspection PyBroadException
try :
debug ( 'Reading metadata' )
metadata , body... |
def poll ( self , timeout = None ) :
"""Poll a GPIO for the edge event configured with the . edge property .
` timeout ` can be a positive number for a timeout in seconds , 0 for a
non - blocking poll , or negative or None for a blocking poll . Defaults to
blocking poll .
Args :
timeout ( int , float , No... | if not isinstance ( timeout , ( int , float , type ( None ) ) ) :
raise TypeError ( "Invalid timeout type, should be integer, float, or None." )
# Setup epoll
p = select . epoll ( )
p . register ( self . _fd , select . EPOLLIN | select . EPOLLET | select . EPOLLPRI )
# Poll twice , as first call returns with curren... |
def clean ( self ) :
'''Auto populate urlhash from url''' | if not self . urlhash or 'url' in self . _get_changed_fields ( ) :
self . urlhash = hash_url ( self . url )
super ( Reuse , self ) . clean ( ) |
def cluster_rows_in_roi ( self , roi_mask = None , num_clusters_per_roi = 5 , metric = 'minkowski' ) :
"""Clusters the data within all the ROIs specified in a mask .
Parameters
roi _ mask : ndarray or None
volumetric mask defining the list of ROIs , with a label for each voxel .
This must be the same size i... | self . _set_roi_mask ( roi_mask )
try :
clusters = [ self . _summarize_in_roi ( self . roi_mask == label , num_clusters_per_roi , metric = metric ) for label in self . roi_list ]
self . clustered_carpet = np . vstack ( clusters )
except :
print ( 'unable to produce the clustered carpet - exception:' )
t... |
def create_namespaced_role_binding ( self , namespace , body , ** kwargs ) :
"""create a RoleBinding
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . create _ namespaced _ role _ binding ( namespace , body , as... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . create_namespaced_role_binding_with_http_info ( namespace , body , ** kwargs )
else :
( data ) = self . create_namespaced_role_binding_with_http_info ( namespace , body , ** kwargs )
return data |
def int ( self , * args ) :
"""Return the integer stored in the specified node .
Any type of integer will be decoded : byte , short , long , long long""" | data = self . bytes ( * args )
if data is not None :
if len ( data ) == 1 :
return struct . unpack ( "<B" , data ) [ 0 ]
if len ( data ) == 2 :
return struct . unpack ( "<H" , data ) [ 0 ]
if len ( data ) == 4 :
return struct . unpack ( "<L" , data ) [ 0 ]
if len ( data ) == 8 :
... |
def project_invite ( object_id , input_params = { } , always_retry = False , ** kwargs ) :
"""Invokes the / project - xxxx / invite API method .
For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Project - Permissions - and - Sharing # API - method % 3A - % 2Fproject - xxxx %... | return DXHTTPRequest ( '/%s/invite' % object_id , input_params , always_retry = always_retry , ** kwargs ) |
def efficiency_wei ( Gw , local = False ) :
'''The global efficiency is the average of inverse shortest path length ,
and is inversely related to the characteristic path length .
The local efficiency is the global efficiency computed on the
neighborhood of the node , and is related to the clustering coefficie... | def distance_inv_wei ( G ) :
n = len ( G )
D = np . zeros ( ( n , n ) )
# distance matrix
D [ np . logical_not ( np . eye ( n ) ) ] = np . inf
for u in range ( n ) : # distance permanence ( true is temporary )
S = np . ones ( ( n , ) , dtype = bool )
G1 = G . copy ( )
V = [ u... |
def pvz ( self , vz , R , z , gl = True , ngl = _DEFAULTNGL2 , nsigma = 4. , vTmax = 1.5 , _return_actions = False , _jr = None , _lz = None , _jz = None , _return_freqs = False , _rg = None , _kappa = None , _nu = None , _Omega = None , _sigmaR1 = None ) :
"""NAME :
pvz
PURPOSE :
calculate the marginalized v... | if _sigmaR1 is None :
sigmaR1 = self . _sr * numpy . exp ( ( self . _refr - R ) / self . _hsr )
else :
sigmaR1 = _sigmaR1
if gl :
if ngl % 2 == 1 :
raise ValueError ( "ngl must be even" )
# Use Gauss - Legendre integration for all
if ngl == _DEFAULTNGL :
glx , glw = self . _glxdef , ... |
def _memoize_cache_key ( args , kwargs ) :
"""Turn args tuple and kwargs dictionary into a hashable key .
Expects that all arguments to a memoized function are either hashable
or can be uniquely identified from type ( arg ) and repr ( arg ) .""" | cache_key_list = [ ]
# hack to get around the unhashability of lists ,
# add a special case to convert them to tuples
for arg in args :
if type ( arg ) is list :
cache_key_list . append ( tuple ( arg ) )
else :
cache_key_list . append ( arg )
for ( k , v ) in sorted ( kwargs . items ( ) ) :
... |
def police_priority_map_conform_map_pri4_conform ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
police_priority_map = ET . SubElement ( config , "police-priority-map" , xmlns = "urn:brocade.com:mgmt:brocade-policer" )
name_key = ET . SubElement ( police_priority_map , "name" )
name_key . text = kwargs . pop ( 'name' )
conform = ET . SubElement ( police_priority_map , "conform" )... |
async def dump_varint_t ( writer , type_or , pv ) :
"""Binary dump of the integer of given type
: param writer :
: param type _ or :
: param pv :
: return :""" | width = int_mark_to_size ( type_or )
n = ( pv << 2 ) | type_or
buffer = _UINT_BUFFER
for _ in range ( width ) :
buffer [ 0 ] = n & 0xff
await writer . awrite ( buffer )
n >>= 8
return width |
def node_as_tree ( self , node , visitor = lambda self , node : self . _default_node_visitor ( node ) , children = lambda self , node , visitor , children : self . _default_node_children ( node , visitor , children ) , ) :
"""Visits a : class : ` CTENode ` ` node ` and delegates to the ( optional )
` visitor ` ca... | tree = visitor ( self , node )
tree . update ( children ( self , node , visitor , children ) )
return tree |
def generate_fake_data ( f = '2*x-5' , x = _n . linspace ( - 5 , 5 , 11 ) , ey = 1 , ex = 0 , include_errors = False , ** kwargs ) :
"""Generates a set of fake data from the underlying " reality " ( or mean
behavior ) function f .
Parameters
Underlying " reality " function or mean behavior . This can be any
... | # Make a fitter object , which handily interprets string functions
# The " + 0 * x " is a trick to ensure the function takes x as an argument
# ( makes it a little more idiot proof ) .
fitty = _s . data . fitter ( ) . set_functions ( f + "+0*x" , '' )
# Make sure both errors are arrays of the right length
if not _s . f... |
def get_path_list ( args , nni_config , trial_content , temp_nni_path ) :
'''get path list according to different platform''' | path_list , host_list = parse_log_path ( args , trial_content )
platform = nni_config . get_config ( 'experimentConfig' ) . get ( 'trainingServicePlatform' )
if platform == 'local' :
print_normal ( 'Log path: %s' % ' ' . join ( path_list ) )
return path_list
elif platform == 'remote' :
path_list = copy_data... |
def calc_stream_lb ( self , vo = None , ro = None , R0 = None , Zsun = None , vsun = None ) :
"""NAME :
calc _ stream _ lb
PURPOSE :
convert the stream track to observational coordinates and store
INPUT :
Coordinate transformation inputs ( all default to the instance - wide
values ) :
vo = circular ve... | if vo is None :
vo = self . _vo
if ro is None :
ro = self . _ro
if R0 is None :
R0 = self . _R0
if Zsun is None :
Zsun = self . _Zsun
if vsun is None :
vsun = self . _vsun
self . _ObsTrackLB = numpy . empty_like ( self . _ObsTrack )
XYZ = bovy_coords . galcencyl_to_XYZ ( self . _ObsTrack [ : , 0 ] *... |
def update_null_primary ( hdu_in , hdu = None ) :
"""' Update ' a null primary HDU
This actually just checks hdu exists and creates it from hdu _ in if it does not .""" | if hdu is None :
hdu = fits . PrimaryHDU ( header = hdu_in . header )
else :
hdu = hdu_in
hdu . header . remove ( 'FILENAME' )
return hdu |
def times ( self , func , * args ) :
"""Run a function * * n * * times .""" | n = self . obj
i = 0
while n is not 0 :
n -= 1
func ( i )
i += 1
return self . _wrap ( func ) |
def doc_inherit ( parent , style = "parent" ) :
"""Returns a function / method decorator that , given ` parent ` , updates the docstring of the decorated
function / method based on the specified style and the corresponding attribute of ` parent ` .
Parameters
parent : Union [ str , Any ]
The docstring , or ... | merge_func = store [ style ]
decorator = _DocInheritDecorator
decorator . doc_merger = staticmethod ( merge_func )
return decorator ( parent ) |
def value_check ( arg_name , pos , allowed_values ) :
"""allows value checking at runtime for args or kwargs""" | def decorator ( fn ) : # brevity compromised in favour of readability
def logic ( * args , ** kwargs ) :
arg_count = len ( args )
if arg_count :
if pos < arg_count :
if args [ pos ] in allowed_values :
return fn ( * args , ** kwargs )
e... |
def generate_clk_from_csv ( input_f , # type : TextIO
keys , # type : Tuple [ AnyStr , AnyStr ]
schema , # type : Schema
validate = True , # type : bool
header = True , # type : Union [ bool , AnyStr ]
progress_bar = True # type : bool
) : # type : ( . . . ) - > List [ str ]
"""Generate Bloom filters from CSV file ... | if header not in { False , True , 'ignore' } :
raise ValueError ( "header must be False, True or 'ignore' but is {}." . format ( header ) )
log . info ( "Hashing data" )
# Read from CSV file
reader = unicode_reader ( input_f )
if header :
column_names = next ( reader )
if header != 'ignore' :
valida... |
def exp_files ( self ) :
"""A mapping from experiment to experiment configuration file
Note that this attribute only contains experiments whose configuration
has already dumped to the file !""" | ret = OrderedDict ( )
# restore the order of the experiments
exp_file = self . exp_file
if osp . exists ( exp_file ) :
for key , val in safe_load ( exp_file ) . items ( ) :
ret [ key ] = val
for project , d in self . projects . items ( ) :
project_path = d [ 'root' ]
config_path = osp . join ( proje... |
def _parse_data ( self , raw_data , var_filter , time_extents ) :
"""Transforms raw HADS observations into a dict :
station code - > [ ( variable , time , value ) , . . . ]
Takes into account the var filter ( if set ) .""" | retval = defaultdict ( list )
p = parser ( )
begin_time , end_time = time_extents
for line in raw_data . splitlines ( ) :
if len ( line ) == 0 :
continue
fields = line . split ( "|" ) [ 0 : - 1 ]
if var_filter is None or fields [ 2 ] in var_filter :
dt = p . parse ( fields [ 3 ] ) . replace ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.