signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def init_kernel ( self ) :
'''Initializes the covariance matrix with a guess at
the GP kernel parameters .''' | if self . kernel_params is None :
X = self . apply_mask ( self . fpix / self . flux . reshape ( - 1 , 1 ) )
y = self . apply_mask ( self . flux ) - np . dot ( X , np . linalg . solve ( np . dot ( X . T , X ) , np . dot ( X . T , self . apply_mask ( self . flux ) ) ) )
white = np . nanmedian ( [ np . nanstd ... |
def normalize ( self , bias_range = 1 , quadratic_range = None , ignored_variables = None , ignored_interactions = None , ignore_offset = False ) :
"""Normalizes the biases of the binary quadratic model such that they
fall in the provided range ( s ) , and adjusts the offset appropriately .
If ` quadratic _ ran... | def parse_range ( r ) :
if isinstance ( r , Number ) :
return - abs ( r ) , abs ( r )
return r
def min_and_max ( iterable ) :
if not iterable :
return 0 , 0
return min ( iterable ) , max ( iterable )
if ignored_variables is None :
ignored_variables = set ( )
elif not isinstance ( ign... |
def format ( self , format_str ) :
"""Returns a formatted version of format _ str .
The only named replacement fields supported by this method and
their corresponding API calls are :
* { num } group _ num
* { name } group _ name
* { symbol } group _ symbol
* { variant } group _ variant
* { current _ d... | return format_str . format ( ** { "num" : self . group_num , "name" : self . group_name , "symbol" : self . group_symbol , "variant" : self . group_variant , "current_data" : self . group_data , "count" : self . groups_count , "names" : self . groups_names , "symbols" : self . groups_symbols , "variants" : self . group... |
def build_network_settings ( ** settings ) :
'''Build the global network script .
CLI Example :
. . code - block : : bash
salt ' * ' ip . build _ network _ settings < settings >''' | # Read current configuration and store default values
current_network_settings = _parse_rh_config ( _RH_NETWORK_FILE )
# Build settings
opts = _parse_network_settings ( settings , current_network_settings )
try :
template = JINJA . get_template ( 'network.jinja' )
except jinja2 . exceptions . TemplateNotFound :
... |
def element ( self , inp = None ) :
"""Return a complex number from ` ` inp ` ` or from scratch .""" | if inp is not None : # Workaround for missing _ _ complex _ _ of numpy . ndarray
# for Numpy version < 1.12
# TODO : remove when Numpy > = 1.12 is required
if isinstance ( inp , np . ndarray ) :
return complex ( inp . reshape ( [ 1 ] ) [ 0 ] )
else :
return complex ( inp )
else :
return comp... |
def friendly_number ( self , value : int ) -> str :
"""Returns a comma - separated number for the given integer .""" | if self . code not in ( "en" , "en_US" ) :
return str ( value )
s = str ( value )
parts = [ ]
while s :
parts . append ( s [ - 3 : ] )
s = s [ : - 3 ]
return "," . join ( reversed ( parts ) ) |
def write_compounds ( self , stream , compounds , properties = None ) :
"""Write iterable of compounds as YAML object to stream .
Args :
stream : File - like object .
compounds : Iterable of compound entries .
properties : Set of compound properties to output ( or None to output
all ) .""" | self . _write_entries ( stream , compounds , self . convert_compound_entry , properties ) |
def get_model ( app_dot_model ) :
"""Returns Django model class corresponding to passed - in ` app _ dot _ model `
string . This is helpful for preventing circular - import errors in a Django
project .
Positional Arguments :
- ` app _ dot _ model ` : Django ' s ` < app _ name > . < model _ name > ` syntax .... | try :
app , model = app_dot_model . split ( '.' )
except ValueError :
msg = ( f'Passed in value \'{app_dot_model}\' was not in the format ' '`<app_name>.<model_name>`.' )
raise ValueError ( msg )
return apps . get_app_config ( app ) . get_model ( model ) |
def cmd_servo ( self , args ) :
'''set servos''' | if len ( args ) == 0 or args [ 0 ] not in [ 'set' , 'repeat' ] :
print ( "Usage: servo <set|repeat>" )
return
if args [ 0 ] == "set" :
if len ( args ) < 3 :
print ( "Usage: servo set <SERVO_NUM> <PWM>" )
return
self . master . mav . command_long_send ( self . target_system , self . targe... |
def eta_bar ( msg , max_value ) :
"""Display an adaptive ETA / countdown bar with a message .
Parameters
msg : str
Message to prefix countdown bar line with
max _ value : max _ value
The max number of progress bar steps / updates""" | widgets = [ "{msg}:" . format ( msg = msg ) , progressbar . Bar ( ) , ' ' , progressbar . AdaptiveETA ( ) , ]
return progressbar . ProgressBar ( widgets = widgets , max_value = max_value ) |
def _terminate_procs ( procs ) :
"""Terminate all processes in the process dictionary""" | logging . warn ( "Stopping all remaining processes" )
for proc , g in procs . values ( ) :
logging . debug ( "[%s] SIGTERM" , proc . pid )
try :
proc . terminate ( )
except OSError as e : # we don ' t care if the process we tried to kill didn ' t exist .
if e . errno != errno . ESRCH :
... |
def _publisher_callback ( self , publish_ack ) :
"""publisher callback that grpc and web socket can pass messages to
address the received message onto the queue
: param publish _ ack : EventHub _ pb2 . Ack the ack received from either wss or grpc
: return : None""" | logging . debug ( "ack received: " + str ( publish_ack ) . replace ( '\n' , ' ' ) )
self . _rx_queue . append ( publish_ack ) |
def iter_tiles ( image , tile_size ) :
"""Yields ( x , y ) coordinate pairs for the top left corner of each tile in
the given image , based on the given tile size .""" | w , h = image . size
for y in xrange ( 0 , h , tile_size ) :
for x in xrange ( 0 , w , tile_size ) :
yield x , y |
def _input_valid ( input_ , operation , message , output_condition_uri = None ) :
"""Validates a single Input against a single Output .
Note :
In case of a ` CREATE ` Transaction , this method
does not validate against ` output _ condition _ uri ` .
Args :
input _ ( : class : ` ~ bigchaindb . common . tra... | ccffill = input_ . fulfillment
try :
parsed_ffill = Fulfillment . from_uri ( ccffill . serialize_uri ( ) )
except ( TypeError , ValueError , ParsingError , ASN1DecodeError , ASN1EncodeError ) :
return False
if operation == Transaction . CREATE : # NOTE : In the case of a ` CREATE ` transaction , the
# output is... |
def store_pulse_pushes ( body , exchange , routing_key ) :
"""Fetches the pushes pending from pulse exchanges and loads them .""" | newrelic . agent . add_custom_parameter ( "exchange" , exchange )
newrelic . agent . add_custom_parameter ( "routing_key" , routing_key )
PushLoader ( ) . process ( body , exchange ) |
def reductions ( fn , seq , acc = None ) :
"""Return the intermediate values of a reduction
: param fn : a function
: param seq : a sequence
: param acc : the accumulator
: returns : a list
> > > reductions ( lambda x , y : x + y , [ 1 , 2 , 3 ] )
[1 , 3 , 6]
> > > reductions ( lambda x , y : x + y , ... | indexes = xrange ( len ( seq ) )
if acc :
return map ( lambda i : reduce ( lambda x , y : fn ( x , y ) , seq [ : i + 1 ] , acc ) , indexes )
else :
return map ( lambda i : reduce ( lambda x , y : fn ( x , y ) , seq [ : i + 1 ] ) , indexes ) |
def zscore_df ( df , axis = 'row' , keep_orig = False ) :
'''take the zscore of a dataframe dictionary , does not write to net ( self )''' | df_z = { }
for mat_type in df :
if keep_orig and mat_type == 'mat' :
mat_orig = deepcopy ( df [ mat_type ] )
inst_df = df [ mat_type ]
if axis == 'row' :
inst_df = inst_df . transpose ( )
df_z [ mat_type ] = ( inst_df - inst_df . mean ( ) ) / inst_df . std ( )
if axis == 'row' :
... |
def stop ( self ) :
"""Stop session .""" | if self . transport :
self . transport . write ( self . method . TEARDOWN ( ) . encode ( ) )
self . transport . close ( )
self . rtp . stop ( ) |
def onMessageDelivered ( self , msg_ids = None , delivered_for = None , thread_id = None , thread_type = ThreadType . USER , ts = None , metadata = None , msg = None , ) :
"""Called when the client is listening , and somebody marks messages as delivered
: param msg _ ids : The messages that are marked as delivere... | log . info ( "Messages {} delivered to {} in {} ({}) at {}s" . format ( msg_ids , delivered_for , thread_id , thread_type . name , ts / 1000 ) ) |
def _serializer ( obj ) :
'''helper function to serialize some objects for prettier return''' | import datetime
if isinstance ( obj , datetime . datetime ) :
if obj . utcoffset ( ) is not None :
obj = obj - obj . utcoffset ( )
return obj . __str__ ( )
return obj |
def commit_author ( sha1 = '' ) : # type : ( str ) - > Author
"""Return the author of the given commit .
Args :
sha1 ( str ) :
The sha1 of the commit to query . If not given , it will return the
sha1 for the current commit .
Returns :
Author : A named tuple ` ` ( name , email ) ` ` with the commit autho... | with conf . within_proj_dir ( ) :
cmd = 'git show -s --format="%an||%ae" {}' . format ( sha1 )
result = shell . run ( cmd , capture = True , never_pretend = True ) . stdout
name , email = result . split ( '||' )
return Author ( name , email ) |
def _init_attr ( self , bitstring_map : Dict [ str , str ] ) :
"""Acts instead of _ _ init _ _ method to instantiate the necessary Deutsch - Jozsa state .
: param Dict [ String , String ] bitstring _ map : truth - table of the input bitstring map in
dictionary format , used to construct the oracle in the Deutsc... | self . bit_map = bitstring_map
self . n_qubits = len ( list ( bitstring_map . keys ( ) ) [ 0 ] )
# We use one extra qubit for making the oracle ,
# and one for storing the answer of the oracle .
self . n_ancillas = 2
self . _qubits = list ( range ( self . n_qubits + self . n_ancillas ) )
self . computational_qubits = s... |
def do_alarm_definition_list ( mc , args ) :
'''List alarm definitions for this tenant .''' | fields = { }
if args . name :
fields [ 'name' ] = args . name
if args . dimensions :
fields [ 'dimensions' ] = utils . format_dimensions_query ( args . dimensions )
if args . severity :
if not _validate_severity ( args . severity ) :
return
fields [ 'severity' ] = args . severity
if args . sort_... |
def get_penalty_model ( specification ) :
"""Retrieve a PenaltyModel from one of the available factories .
Args :
specification ( : class : ` . Specification ` ) : The specification
for the desired PenaltyModel .
Returns :
: class : ` . PenaltyModel ` / None : A PenaltyModel as returned by
the highest p... | # Iterate through the available factories until one gives a penalty model
for factory in iter_factories ( ) :
try :
pm = factory ( specification )
except ImpossiblePenaltyModel as e : # information about impossible models should be propagated
raise e
except FactoryException : # any other typ... |
def most_seen_creators_by_works ( work_kind = None , role_name = None , num = 10 ) :
"""Returns a QuerySet of the Creators that are associated with the most Works .""" | return Creator . objects . by_works ( kind = work_kind , role_name = role_name ) [ : num ] |
def removeSubscribers ( self , emails_list ) :
"""Remove subscribers from this workitem
If the subscribers have not been added , no more actions will be
performed .
: param emails _ list : a : class : ` list ` / : class : ` tuple ` / : class : ` set `
contains the the subscribers ' emails""" | if not hasattr ( emails_list , "__iter__" ) :
error_msg = "Input parameter 'emails_list' is not iterable"
self . log . error ( error_msg )
raise exception . BadValue ( error_msg )
# overall flag
missing_flags = True
headers , raw_data = self . _perform_subscribe ( )
for email in emails_list :
missing_fl... |
def open_application ( self , remote_url , alias = None , ** kwargs ) :
"""Opens a new application to given Appium server .
Capabilities of appium server , Android and iOS ,
Please check https : / / github . com / appium / appium / blob / master / docs / en / writing - running - appium / server - args . md
| ... | desired_caps = kwargs
application = webdriver . Remote ( str ( remote_url ) , desired_caps )
self . _debug ( 'Opened application with session id %s' % application . session_id )
return self . _cache . register ( application , alias ) |
def config ( key , value , local = True ) :
"""Set that config key to that value
Unless local is set to False : only change local config""" | option = local and '--local' or ''
run ( 'config %s "%s" "%s"' % ( option , key , value ) ) |
def detect_possible_scope_visibility ( node , context_scope ) : # type : ( Dict [ str , Any ] , Scope ) - > ScopeVisibilityHint
"""Returns a * possible * variable visibility by the specified node .
The " possible " means that we can not determine a scope visibility of lambda arguments until reachability check .""... | node_type = NodeType ( node [ 'type' ] )
if not is_analyzable_identifier ( node ) :
return ScopeVisibilityHint ( ScopeVisibility . UNANALYZABLE , ExplicityOfScopeVisibility . UNANALYZABLE )
if node_type is NodeType . IDENTIFIER :
return _detect_possible_identifier_scope_visibility ( node , context_scope )
if no... |
def plot_i2 ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) :
"""Plot the third invariant I2 ( the determinant ) of the tensor :
I2 = vxx * ( vyy * vzz - vyz * * 2 ) + vxy * ( vyz * vxz - vxy * vzz )
+ vxz * ( vxy * vyz - vxz * vyy ... | if cb_label is None :
cb_label = self . _i2_label
if self . i2 is None :
self . compute_invar ( )
if ax is None :
fig , axes = self . i2 . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs )
if show :
fig . show ( )
if fname is not ... |
def match_blocks ( hash_func , old_children , new_children ) :
"""Use difflib to find matching blocks .""" | sm = difflib . SequenceMatcher ( _is_junk , a = [ hash_func ( c ) for c in old_children ] , b = [ hash_func ( c ) for c in new_children ] , )
return sm |
def get_api_gateway_resource ( name ) :
"""Get the resource associated with our gateway .""" | client = boto3 . client ( 'apigateway' , region_name = PRIMARY_REGION )
matches = [ x for x in client . get_rest_apis ( ) . get ( 'items' , list ( ) ) if x [ 'name' ] == API_GATEWAY ]
match = matches . pop ( )
resources = client . get_resources ( restApiId = match . get ( 'id' ) )
resource_id = None
for item in resourc... |
def pc_anova ( self , covariates , num_pc = 5 ) :
"""Calculate one - way ANOVA between the first num _ pc prinicipal components
and known covariates . The size and index of covariates determines
whether u or v is used .
Parameters
covariates : pandas . DataFrame
Dataframe of covariates whose index corresp... | from scipy . stats import f_oneway
if ( covariates . shape [ 0 ] == self . u . shape [ 0 ] and len ( set ( covariates . index ) & set ( self . u . index ) ) == self . u . shape [ 0 ] ) :
mat = self . u
elif ( covariates . shape [ 0 ] == self . v . shape [ 0 ] and len ( set ( covariates . index ) & set ( self . v . ... |
def GetKey ( self , path , cycle = 9999 , rootpy = True , ** kwargs ) :
"""Override TDirectory ' s GetKey and also handle accessing keys nested
arbitrarily deep in subdirectories .""" | key = super ( _DirectoryBase , self ) . GetKey ( path , cycle )
if not key :
raise DoesNotExist
if rootpy :
return asrootpy ( key , ** kwargs )
return key |
def __write_columns ( self , pc , table ) :
"""Read numeric data from csv and write to the bottom section of the txt file .
: param dict table : Paleodata dictionary
: return none :""" | logger_lpd_noaa . info ( "writing section: data, csv values from file" )
# get filename for this table ' s csv data
# filename = self . _ _ get _ filename ( table )
# logger _ lpd _ noaa . info ( " processing csv file : { } " . format ( filename ) )
# # get missing value for this table
# # mv = self . _ _ get _ mv ( ta... |
def to_string ( self , limit = None ) :
"""Create a string representation of this collection , showing up to
` limit ` items .""" | header = self . short_string ( )
if len ( self ) == 0 :
return header
contents = ""
element_lines = [ " -- %s" % ( element , ) for element in self . elements [ : limit ] ]
contents = "\n" . join ( element_lines )
if limit is not None and len ( self . elements ) > limit :
contents += "\n ... and %d more" % ( l... |
def do_execute ( self ) :
"""The actual execution of the actor .
: return : None if successful , otherwise error message
: rtype : str""" | result = None
teeoff = True
cond = self . storagehandler . expand ( str ( self . resolve_option ( "condition" ) ) )
if len ( cond ) > 0 :
teeoff = bool ( eval ( cond ) )
if teeoff :
self . first_active . input = self . input
result = self . _director . execute ( )
if result is None :
self . _output . ap... |
def setEditable ( self , editable ) :
"""setter to _ editable . apply changes while changing dtype .
Raises :
TypeError : if editable is not of type bool .
Args :
editable ( bool ) : apply changes while changing dtype .""" | if not isinstance ( editable , bool ) :
raise TypeError ( 'Argument is not of type bool' )
self . _editable = editable |
def persist ( name , value , config = '/etc/sysctl.conf' ) :
'''Assign and persist a simple sysctl parameter for this minion
CLI Example :
. . code - block : : bash
salt ' * ' sysctl . persist net . inet . icmp . icmplim 50
salt ' * ' sysctl . persist coretemp _ load NO config = / boot / loader . conf''' | nlines = [ ]
edited = False
value = six . text_type ( value )
with salt . utils . files . fopen ( config , 'r' ) as ifile :
for line in ifile :
line = salt . utils . stringutils . to_unicode ( line ) . rstrip ( '\n' )
if not line . startswith ( '{0}=' . format ( name ) ) :
nlines . appen... |
def submesh ( self , faces_sequence , ** kwargs ) :
"""Return a subset of the mesh .
Parameters
faces _ sequence : sequence ( m , ) int
Face indices of mesh
only _ watertight : bool
Only return submeshes which are watertight
append : bool
Return a single mesh which has the faces appended .
if this f... | return util . submesh ( mesh = self , faces_sequence = faces_sequence , ** kwargs ) |
def set_field ( obj , field_name , value ) :
"""Fancy setattr with debugging .""" | old = getattr ( obj , field_name )
field = obj . _meta . get_field ( field_name )
# is _ relation is Django 1.8 only
if field . is_relation : # If field _ name is the ` _ id ` field , then there is no ' pk ' attr and
# old / value * is * the pk
old_repr = None if old is None else getattr ( old , 'pk' , old )
ne... |
def work ( ) :
"""Start an rq worker on the connection provided by create _ connection .""" | with rq . Connection ( create_connection ( ) ) :
worker = rq . Worker ( list ( map ( rq . Queue , listen ) ) )
worker . work ( ) |
def _update_data ( self , data ) : # type : ( Any ) - > Dict [ str , List ]
"""Set our data and notify any subscribers of children what has changed
Args :
data ( object ) : The new data
Returns :
dict : { child _ name : [ path _ list , optional child _ data ] } of the change
that needs to be passed to a c... | self . data = data
child_change_dict = { }
# Reflect change of data to children
for name in self . children :
child_data = getattr ( data , name , None )
if child_data is None : # Deletion
child_change_dict [ name ] = [ [ ] ]
else : # Change
child_change_dict [ name ] = [ [ ] , child_data ]
... |
def convert_cifar10 ( directory , output_directory , output_filename = 'cifar10.hdf5' ) :
"""Converts the CIFAR - 10 dataset to HDF5.
Converts the CIFAR - 10 dataset to an HDF5 dataset compatible with
: class : ` fuel . datasets . CIFAR10 ` . The converted dataset is saved as
' cifar10 . hdf5 ' .
It assumes... | output_path = os . path . join ( output_directory , output_filename )
h5file = h5py . File ( output_path , mode = 'w' )
input_file = os . path . join ( directory , DISTRIBUTION_FILE )
tar_file = tarfile . open ( input_file , 'r:gz' )
train_batches = [ ]
for batch in range ( 1 , 6 ) :
file = tar_file . extractfile (... |
def change_object_content_type ( self , container , obj , new_ctype , guess = False , extra_info = None ) :
"""Copies object to itself , but applies a new content - type . The guess
feature requires the container to be CDN - enabled . If not then the
content - type must be supplied . If using guess with a CDN -... | return self . _manager . change_object_content_type ( container , obj , new_ctype , guess = guess ) |
def simulate_measurement ( self , index : int ) -> bool :
"""Simulates a single qubit measurement in the computational basis .
Args :
index : Which qubit is measured .
Returns :
True iff the measurement result corresponds to the | 1 > state .""" | args = self . _shard_num_args ( { 'index' : index } )
prob_one = np . sum ( self . _pool . map ( _one_prob_per_shard , args ) )
result = bool ( np . random . random ( ) <= prob_one )
args = self . _shard_num_args ( { 'index' : index , 'result' : result , 'prob_one' : prob_one } )
self . _pool . map ( _collapse_state , ... |
def sndread ( path : str ) -> Tuple [ np . ndarray , int ] :
"""Read a soundfile as a numpy array . This is a float array defined
between - 1 and 1 , independently of the format of the soundfile
Returns ( data : ndarray , sr : int )""" | backend = _getBackend ( path )
logger . debug ( f"sndread: using backend {backend.name}" )
return backend . read ( path ) |
def submodules ( self ) :
"""Returns all documented sub - modules in the module sorted
alphabetically as a list of ` pydoc . Module ` .""" | p = lambda o : isinstance ( o , Module ) and self . _docfilter ( o )
return sorted ( filter ( p , self . doc . values ( ) ) ) |
def gendicts ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Dict [ str , Any ] , None , None ] :
"""Generate all rows from a cursor as : class : ` OrderedDict ` objects .
Args :
cursor : the cursor
arraysize : split fetches into chunks of this many records
Yields :
each row , as an : class : ... | columns = get_fieldnames_from_cursor ( cursor )
return ( OrderedDict ( zip ( columns , row ) ) for row in genrows ( cursor , arraysize ) ) |
def _get_value ( self , value , default ) :
"""calls appropriate gconf function by the default value""" | vtype = type ( default )
if vtype is bool :
return value . get_bool ( )
elif vtype is str :
return value . get_string ( )
elif vtype is int :
return value . get_int ( )
elif vtype in ( list , tuple ) :
l = [ ]
for i in value . get_list ( ) :
l . append ( i . get_string ( ) )
return l
ret... |
def add ( self , interval ) :
"""Adds an interval to the tree , if not already present .
Completes in O ( log n ) time .""" | if interval in self :
return
if interval . is_null ( ) :
raise ValueError ( "IntervalTree: Null Interval objects not allowed in IntervalTree:" " {0}" . format ( interval ) )
if not self . top_node :
self . top_node = Node . from_interval ( interval )
else :
self . top_node = self . top_node . add ( inte... |
def insert_arguments_into_match_query ( compilation_result , arguments ) :
"""Insert the arguments into the compiled MATCH query to form a complete query .
Args :
compilation _ result : a CompilationResult object derived from the GraphQL compiler
arguments : dict , mapping argument name to its value , for eve... | if compilation_result . language != MATCH_LANGUAGE :
raise AssertionError ( u'Unexpected query output language: {}' . format ( compilation_result ) )
base_query = compilation_result . query
argument_types = compilation_result . input_metadata
# The arguments are assumed to have already been validated against the qu... |
def overlap ( self , x , ctrs , kdtree = None ) :
"""Check how many balls ` x ` falls within . Uses a K - D Tree to
perform the search if provided .""" | q = len ( self . within ( x , ctrs , kdtree = kdtree ) )
return q |
def save_to_files ( self , directory : str ) -> None :
"""Persist this Vocabulary to files so it can be reloaded later .
Each namespace corresponds to one file .
Parameters
directory : ` ` str ` `
The directory where we save the serialized vocabulary .""" | os . makedirs ( directory , exist_ok = True )
if os . listdir ( directory ) :
logging . warning ( "vocabulary serialization directory %s is not empty" , directory )
with codecs . open ( os . path . join ( directory , NAMESPACE_PADDING_FILE ) , 'w' , 'utf-8' ) as namespace_file :
for namespace_str in self . _non... |
def init_versioning ( self , app , database , versioning_manager = None ) :
"""Initialize the versioning support using SQLAlchemy - Continuum .""" | try :
pkg_resources . get_distribution ( 'sqlalchemy_continuum' )
except pkg_resources . DistributionNotFound : # pragma : no cover
default_versioning = False
else :
default_versioning = True
app . config . setdefault ( 'DB_VERSIONING' , default_versioning )
if not app . config [ 'DB_VERSIONING' ] :
ret... |
def _HandleLegacy ( self , args , token = None ) :
"""Creates a new hunt .""" | # We only create generic hunts with / hunts / create requests .
generic_hunt_args = rdf_hunts . GenericHuntArgs ( )
generic_hunt_args . flow_runner_args . flow_name = args . flow_name
generic_hunt_args . flow_args = args . flow_args
# Clear all fields marked with HIDDEN , except for output _ plugins - they are
# marked... |
def logs ( self , ** kwargs ) :
"""Get logs from this container . Similar to the ` ` docker logs ` ` command .
The ` ` stream ` ` parameter makes the ` ` logs ` ` function return a blocking
generator you can iterate over to retrieve log output as it happens .
Args :
stdout ( bool ) : Get ` ` STDOUT ` ` . De... | return self . client . api . logs ( self . id , ** kwargs ) |
def _remove_blacklisted ( self , filepaths ) :
"""internal helper method to remove the blacklisted filepaths
from ` filepaths ` .""" | filepaths = util . remove_from_set ( filepaths , self . blacklisted_filepaths )
return filepaths |
def populate_host_templates ( host_templates , hardware_ids = None , virtual_guest_ids = None , ip_address_ids = None , subnet_ids = None ) :
"""Populate the given host _ templates array with the IDs provided
: param host _ templates : The array to which host templates will be added
: param hardware _ ids : A L... | if hardware_ids is not None :
for hardware_id in hardware_ids :
host_templates . append ( { 'objectType' : 'SoftLayer_Hardware' , 'id' : hardware_id } )
if virtual_guest_ids is not None :
for virtual_guest_id in virtual_guest_ids :
host_templates . append ( { 'objectType' : 'SoftLayer_Virtual_Gu... |
def close ( self , request , * args , ** kwargs ) :
"""To close alert - run * * POST * * against * / api / alerts / < alert _ uuid > / close / * . No data is required .
Only users with staff privileges can close alerts .""" | if not request . user . is_staff :
raise PermissionDenied ( )
alert = self . get_object ( )
alert . close ( )
return response . Response ( status = status . HTTP_204_NO_CONTENT ) |
def get_object_by_uid ( uid , default = _marker ) :
"""Find an object by a given UID
: param uid : The UID of the object to find
: type uid : string
: returns : Found Object or None""" | # nothing to do here
if not uid :
if default is not _marker :
return default
fail ( "get_object_by_uid requires UID as first argument; got {} instead" . format ( uid ) )
# we defined the portal object UID to be ' 0 ' : :
if uid == '0' :
return get_portal ( )
brain = get_brain_by_uid ( uid )
if brain... |
def get ( self , key , ** kw ) :
"""Retrieve a value from the cache .
: param key : the value ' s key .
: param \ * * kw : cache configuration arguments . The
backend is configured using these arguments upon first request .
Subsequent requests that use the same series of configuration
values will use that... | return self . impl . get ( key , ** self . _get_cache_kw ( kw , None ) ) |
def make_request_from_data ( self , data ) :
"""Returns a Request instance from data coming from Redis .
By default , ` ` data ` ` is an encoded URL . You can override this method to
provide your own message decoding .
Parameters
data : bytes
Message from redis .""" | url = bytes_to_str ( data , self . redis_encoding )
return self . make_requests_from_url ( url ) |
def detect_from_pkgconfig ( self ) :
"""Detects the igraph include directory , library directory and the
list of libraries to link to using ` ` pkg - config ` ` .""" | if not buildcfg . has_pkgconfig :
print ( "Cannot find the C core of igraph on this system using pkg-config." )
return False
cmd = "pkg-config igraph --cflags --libs"
if self . static_extension :
cmd += " --static"
line , exit_code = get_output ( cmd )
if exit_code > 0 or len ( line ) == 0 :
return Fals... |
def update ( self ) :
"""Updates the dictionary of the device""" | if "tag_groups" not in self . _device_dict :
return
for group in self . tag_groups :
group . update ( )
for i in range ( len ( self . _device_dict [ "tag_groups" ] ) ) :
tag_group_dict = self . _device_dict [ "tag_groups" ] [ i ]
for group in self . tag_groups :
if group . name == tag_group_dict... |
def load_mo ( self , state , page_idx ) :
"""Loads a memory object from memory .
: param page _ idx : the index into the page
: returns : a tuple of the object""" | try :
key = next ( self . _storage . irange ( maximum = page_idx , reverse = True ) )
except StopIteration :
return None
else :
return self . _storage [ key ] |
def handle ( self , t_input : inference . TranslatorInput , t_output : inference . TranslatorOutput , t_walltime : float = 0. ) :
""": param t _ input : Translator input .
: param t _ output : Translator output .
: param t _ walltime : Total wall - clock time for translation .""" | line = "{sent_id} ||| {target} ||| {score:f} ||| {source} ||| {source_len:d} ||| {target_len:d}\n"
self . stream . write ( line . format ( sent_id = t_input . sentence_id , target = " " . join ( t_output . tokens ) , score = t_output . score , source = " " . join ( t_input . tokens ) , source_len = len ( t_input . toke... |
def manual_uniprot_mapping ( self , gene_to_uniprot_dict , outdir = None , set_as_representative = True ) :
"""Read a manual dictionary of model gene IDs - - > UniProt IDs . By default sets them as representative .
This allows for mapping of the missing genes , or overriding of automatic mappings .
Input a dict... | for g , u in tqdm ( gene_to_uniprot_dict . items ( ) ) :
g = str ( g )
gene = self . genes . get_by_id ( g )
try :
uniprot_prop = gene . protein . load_uniprot ( uniprot_id = u , outdir = outdir , download = True , set_as_representative = set_as_representative )
except HTTPError as e :
l... |
def iter ( self , headers_only = False , page_size = None ) :
"""Yield all time series objects selected by the query .
The generator returned iterates over
: class : ` ~ google . cloud . monitoring _ v3 . types . TimeSeries ` objects
containing points ordered from oldest to newest .
Note that the : class : ... | if self . _end_time is None :
raise ValueError ( "Query time interval not specified." )
params = self . _build_query_params ( headers_only , page_size )
for ts in self . _client . list_time_series ( ** params ) :
yield ts |
def run ( addr , * commands , ** kwargs ) :
"""Non - threaded batch command runner returning output results""" | results = [ ]
handler = VarnishHandler ( addr , ** kwargs )
for cmd in commands :
if isinstance ( cmd , tuple ) and len ( cmd ) > 1 :
results . extend ( [ getattr ( handler , c [ 0 ] . replace ( '.' , '_' ) ) ( * c [ 1 : ] ) for c in cmd ] )
else :
results . append ( getattr ( handler , cmd . re... |
def process ( self , request , queryset , period ) :
"""Will process the request and return an appropriate Response object .
: param request : The request being processed .
: param model : The model class being processed .
: param period : The model being processed .
: return : The response with the report ... | response = HttpResponse ( content = self . get_attachment_content ( request , queryset ) or '' , content_type = self . get_attachment_content_type ( request ) or 'text/plain' )
response [ 'Content-Disposition' ] = 'attachment; filename=' + ( self . get_attachment_filename ( request , period ) or 'report.txt' )
return r... |
def class_to_json ( obj ) :
""": type obj : int | str | bool | float | bytes | unicode | list | dict | object
: rtype : int | str | bool | list | dict""" | obj_raw = serialize ( obj )
return json . dumps ( obj_raw , indent = _JSON_INDENT , sort_keys = True ) |
def binary_n ( total_N , min_n = 50 ) :
"""Creates a list of values by successively halving the total length total _ N
until the resulting value is less than min _ n .
Non - integer results are rounded down .
Args :
total _ N ( int ) :
total length
Kwargs :
min _ n ( int ) :
minimal length after div... | max_exp = np . log2 ( 1.0 * total_N / min_n )
max_exp = int ( np . floor ( max_exp ) )
return [ int ( np . floor ( 1.0 * total_N / ( 2 ** i ) ) ) for i in range ( 1 , max_exp + 1 ) ] |
def add_context_menu_items ( self , items , replace_items = False ) :
'''Adds context menu items . If replace _ items is True all
previous context menu items will be removed .''' | for label , action in items :
assert isinstance ( label , basestring )
assert isinstance ( action , basestring )
if replace_items :
self . _context_menu_items = [ ]
self . _context_menu_items . extend ( items )
self . _listitem . addContextMenuItems ( items , replace_items ) |
def flags ( self , index ) :
"""Returns the item flags for the given index .""" | if not index . isValid ( ) :
return 0
cti = self . getItem ( index )
result = Qt . ItemIsSelectable
if cti . enabled :
result |= Qt . ItemIsEnabled
if index . column ( ) == self . COL_VALUE :
result |= cti . valueColumnItemFlags
return result |
def _timeoutDeferred ( deferred , timeout ) :
"""Cancels the given deferred after the given time , if it has not yet callbacked / errbacked it .""" | delayedCall = reactor . callLater ( timeout , deferred . cancel )
def gotResult ( result ) :
if delayedCall . active ( ) :
delayedCall . cancel ( )
return result
deferred . addBoth ( gotResult ) |
def define_frequencies ( Ne , explicitly_antisymmetric = False ) :
u"""Define all frequencies omega _ level , omega , gamma .
> > > from sympy import pprint
> > > pprint ( define _ frequencies ( 2 ) , use _ unicode = True )
⎛ ⎡ 0 ω12 ⎤ ⎡ 0 γ12 ⎤ ⎞
⎜ [ ω1 , ω2 ] , ⎢ ⎥ , ⎢ ⎥ ⎟
⎝ ⎣ ω21 0 ⎦ ⎣ γ21 0 ⎦ ⎠
We c... | omega_level = [ Symbol ( 'omega_' + str ( i + 1 ) , real = True ) for i in range ( Ne ) ]
if Ne > 9 :
opening = "\\"
comma = ","
open_brace = "{"
close_brace = "}"
else :
opening = r""
comma = ""
open_brace = ""
close_brace = ""
omega = [ ] ;
gamma = [ ]
for i in range ( Ne ) :
row_o... |
def get_context ( name , doc ) :
"""Generate a command with given name .
The command can be run immediately after generation .
For example :
dj generate command bar
dj run manage . py bar""" | name = inflection . underscore ( name )
return { 'name' : name , 'doc' : doc or name } |
def cublasDtrsm ( handle , side , uplo , trans , diag , m , n , alpha , A , lda , B , ldb ) :
"""Solve a real triangular system with multiple right - hand sides .""" | status = _libcublas . cublasDtrsm_v2 ( handle , _CUBLAS_SIDE_MODE [ side ] , _CUBLAS_FILL_MODE [ uplo ] , _CUBLAS_OP [ trans ] , _CUBLAS_DIAG [ diag ] , m , n , ctypes . byref ( ctypes . c_double ( alpha ) ) , int ( A ) , lda , int ( B ) , ldb )
cublasCheckStatus ( status ) |
def crossspec ( data , tbin , Df = None , units = False , pointProcess = False ) :
"""Calculate ( smoothed ) cross spectra of data .
If ` units ` = True , cross spectra are averaged across units .
Note that averaging is done on cross spectra rather than data .
Cross spectra are normalized by the length T of t... | N = len ( data )
if units is True : # smoothing and normalization take place in powerspec
# and compound _ powerspec
freq , POW = powerspec ( data , tbin , Df = Df , units = True )
freq_com , CPOW = compound_powerspec ( data , tbin , Df = Df )
assert ( len ( freq ) == len ( freq_com ) )
assert ( np . mi... |
def extractall ( self , directory , auto_create_dir = False , patool_path = None ) :
''': param directory : directory to extract to
: param auto _ create _ dir : auto create directory
: param patool _ path : the path to the patool backend''' | log . debug ( 'extracting %s into %s (backend=%s)' , self . filename , directory , self . backend )
is_zipfile = zipfile . is_zipfile ( self . filename )
directory = _fullpath ( directory )
if not os . path . exists ( self . filename ) :
raise ValueError ( 'archive file does not exist:' + str ( self . filename ) )
... |
def _timeout ( seconds ) :
"""Context manager that runs code block until timeout is reached .
Example usage : :
try :
with _ timeout ( 10 ) :
do _ stuff ( )
except Timeout :
print ( " do _ stuff timed out " )""" | def _handle_timeout ( * args ) :
raise Timeout ( seconds )
signal . signal ( signal . SIGALRM , _handle_timeout )
signal . alarm ( seconds )
try :
yield
finally :
signal . alarm ( 0 )
signal . signal ( signal . SIGALRM , signal . SIG_DFL ) |
def _print ( * args ) :
"""Print txt by coding GBK .
* args
list , list of printing contents""" | if not CFG . debug :
return
if not args :
return
encoding = 'gbk'
args = [ _cs ( a , encoding ) for a in args ]
f_back = None
try :
raise Exception
except :
f_back = sys . exc_traceback . tb_frame . f_back
f_name = f_back . f_code . co_name
filename = os . path . basename ( f_back . f_code . co_filename... |
def MapItemsIterator ( function , items ) :
"""Maps ItemsIterator via given function .""" | return ItemsIterator ( items = map ( function , items ) , total_count = items . total_count ) |
def history_view ( self , request , object_id , extra_context = None ) :
"""The ' history ' admin view for this model .""" | request . current_app = self . admin_site . name
model = self . model
opts = model . _meta
app_label = opts . app_label
pk_name = opts . pk . attname
history = getattr ( model , model . _meta . simple_history_manager_attribute )
object_id = unquote ( object_id )
action_list = history . filter ( ** { pk_name : object_id... |
def insert_relation_information ( germanet_db , gn_rels_file ) :
'''Reads in the given GermaNet relation file and inserts its contents
into the given MongoDB database .
Arguments :
- ` germanet _ db ` : a pymongo . database . Database object
- ` gn _ rels _ file ` :''' | lex_rels , con_rels = read_relation_file ( gn_rels_file )
# cache the lexunits while we work on them
lexunits = { }
for lex_rel in lex_rels :
if lex_rel [ 'from' ] not in lexunits :
lexunits [ lex_rel [ 'from' ] ] = germanet_db . lexunits . find_one ( { 'id' : lex_rel [ 'from' ] } )
from_lexunit = lexun... |
def get_conn ( profile ) :
'''Return a client object for accessing consul''' | params = { }
for key in ( 'host' , 'port' , 'token' , 'scheme' , 'consistency' , 'dc' , 'verify' ) :
if key in profile :
params [ key ] = profile [ key ]
if HAS_CONSUL :
return consul . Consul ( ** params )
else :
raise CommandExecutionError ( '(unable to import consul, ' 'module most likely not ins... |
def runlist_add_app ( name , app , profile , force , ** kwargs ) :
"""Add specified application with profile to the specified runlist .
Existence of application or profile is not checked .""" | ctx = Context ( ** kwargs )
ctx . execute_action ( 'runlist:add-app' , ** { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , 'app' : app , 'profile' : profile , 'force' : force } ) |
def deploy ( Class , name = None , uid = None , gid = None , ** kw ) :
"""Create an application with the give name , uid , and gid .
The application has one child service , an instance of Class
configured based on the additional keyword arguments passed .
The application is not persistable .
@ param Class :... | svc = Class ( ** kw )
if name is None :
name = Class . __name__
# Make it easier ( possible ) to find this service by name later on
svc . setName ( name )
app = service . Application ( name , uid = uid , gid = gid )
app . addComponent ( NotPersistable ( app ) , ignoreClass = True )
svc . setServiceParent ( app )
re... |
def _freq_parser ( self , freq ) :
"""day , hour , min , sec ,""" | freq = freq . lower ( ) . strip ( )
try :
if "day" in freq :
freq = freq . replace ( "day" , "" )
return timedelta ( days = int ( freq ) )
elif "hour" in freq :
freq = freq . replace ( "hour" , "" )
return timedelta ( hours = int ( freq ) )
elif "min" in freq :
freq =... |
def crc_srec ( hexstr ) :
"""Calculate the CRC for given Motorola S - Record hexstring .""" | crc = sum ( bytearray ( binascii . unhexlify ( hexstr ) ) )
crc &= 0xff
crc ^= 0xff
return crc |
def _server_response_handler ( self , response : Dict [ str , Any ] ) :
"""处理100 ~ 199段状态码 , 针对不同的服务响应进行操作 .
Parameters :
( response ) : - 响应的python字典形式数据
Return :
( bool ) : - 准确地说没有错误就会返回True""" | code = response . get ( "CODE" )
if code == 100 :
if self . debug :
print ( "auth succeed" )
self . _login_fut . set_result ( response )
if code == 101 :
if self . debug :
print ( 'pong' )
return True |
def _store_expansion_state ( self ) :
"""Iter recursively all tree items and store expansion state""" | def store_tree_expansion ( child_tree_iter , expansion_state ) :
tree_item_path = self . history_tree_store . get_path ( child_tree_iter )
history_item = self . get_history_item_for_tree_iter ( child_tree_iter )
# store expansion state if tree item path is valid and expansion state was not stored already
... |
def matching_tokens ( self , text , start = 0 ) :
"""Retrieve all token definitions matching the beginning of a text .
Args :
text ( str ) : the text to test
start ( int ) : the position where matches should be searched in the
string ( see re . match ( rx , txt , pos ) )
Yields :
( token _ class , re . ... | for token_class , regexp in self . _tokens :
match = regexp . match ( text , pos = start )
if match :
yield token_class , match |
def ngrok_url ( ) :
"""If ngrok is running , it exposes an API on port 4040 . We can use that
to figure out what URL it has assigned , and suggest that to the user .
https : / / ngrok . com / docs # list - tunnels""" | try :
ngrok_resp = requests . get ( "http://localhost:4040/api/tunnels" )
except requests . ConnectionError : # I guess ngrok isn ' t running .
return None
ngrok_data = ngrok_resp . json ( )
secure_urls = [ tunnel [ "public_url" ] for tunnel in ngrok_data [ "tunnels" ] if tunnel [ "proto" ] == "https" ]
return ... |
def this_and_prev ( iterable ) :
"""Walk an iterable , returning the current and previous items
as a two - tuple .""" | try :
item = next ( iterable )
while True :
next_item = next ( iterable )
yield item , next_item
item = next_item
except StopIteration :
return |
def run ( macro , output_files = [ ] , force_close = True ) :
"""Runs Fiji with the suplied macro . Output of Fiji can be viewed by
setting environment variable ` DEBUG = fijibin ` .
Parameters
macro : string or list of strings
IJM - macro ( s ) to run . If list of strings , it will be joined with
a space... | if type ( macro ) == list :
macro = ' ' . join ( macro )
if len ( macro ) == 0 :
print ( 'fijibin.macro.run got empty macro, not starting fiji' )
return _exists ( output_files )
if force_close : # make sure fiji halts immediately when done
# hack : use error code 42 to check if macro has run sucessfully
... |
def get_opcode_from_name ( operation_name : str ) -> int :
"""Get an op code based on its name .
: param operation _ name :
: return :""" | for op_code , value in opcodes . items ( ) :
if operation_name == value [ 0 ] :
return op_code
raise RuntimeError ( "Unknown opcode" ) |
def update_pypsa_generator_import ( network ) :
"""Translate graph based grid representation to PyPSA Network
For details from a user perspective see API documentation of
: meth : ` ~ . grid . network . EDisGo . analyze ` of the API class
: class : ` ~ . grid . network . EDisGo ` .
Translating eDisGo ' s gr... | # get topology and time series data
if network . pypsa . edisgo_mode is None :
mv_components = mv_to_pypsa ( network )
lv_components = lv_to_pypsa ( network )
components = combine_mv_and_lv ( mv_components , lv_components )
elif network . pypsa . edisgo_mode is 'mv' :
raise NotImplementedError
elif netw... |
def is_valid_assignment ( self , mtf_dimension_name , mesh_dimension_name ) :
"""Whether this MTF dimension may be assigned to this mesh dimension .
Args :
mtf _ dimension _ name : string , the name of a Mesh TensorFlow dimension .
mesh _ dimension _ name : string , the name of a mesh dimension .
Returns : ... | return ( ( mtf_dimension_name in self . _splittable_mtf_dimension_names ) and ( self . _mtf_dimension_name_to_size_gcd [ mtf_dimension_name ] % self . _mesh_dimension_name_to_size [ mesh_dimension_name ] == 0 ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.