signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _sendline ( self , line ) :
"""Send exactly one line to the device
Args :
line str : data send to device""" | logging . info ( '%s: sending line' , self . port )
# clear buffer
self . _lines = [ ]
try :
self . _read ( )
except socket . error :
logging . debug ( '%s: Nothing cleared' , self . port )
print 'sending [%s]' % line
self . _write ( line + '\r\n' )
# wait for write to complete
time . sleep ( 0.1 ) |
def _write_to_uaa_cache ( self , new_item ) :
"""Cache the client details into a cached file on disk .""" | data = self . _read_uaa_cache ( )
# Initialize client list if first time
if self . uri not in data :
data [ self . uri ] = [ ]
# Remove existing client record and any expired tokens
for client in data [ self . uri ] :
if new_item [ 'id' ] == client [ 'id' ] :
data [ self . uri ] . remove ( client )
... |
def in_base ( self , unit_system = None ) :
"""Creates a copy of this array with the data in the specified unit
system , and returns it in that system ' s base units .
Parameters
unit _ system : string , optional
The unit system to be used in the conversion . If not specified ,
the configured default base... | us = _sanitize_unit_system ( unit_system , self )
try :
conv_data = _check_em_conversion ( self . units , unit_system = us , registry = self . units . registry )
except MKSCGSConversionError :
raise UnitsNotReducible ( self . units , us )
if any ( conv_data ) :
to_units , ( conv , offset ) = _em_conversion ... |
def modify_pool_member ( hostname , username , password , name , member , connection_limit = None , description = None , dynamic_ratio = None , inherit_profile = None , logging = None , monitor = None , priority_group = None , profiles = None , rate_limit = None , ratio = None , session = None , member_state = None ) :... | ret = { 'name' : name , 'changes' : { } , 'result' : False , 'comment' : '' }
if __opts__ [ 'test' ] :
return _test_output ( ret , 'modify' , params = { 'hostname' : hostname , 'username' : username , 'password' : password , 'name' : name , 'members' : member } )
# is this pool member currently configured ?
existin... |
async def leave ( self ) :
"""You can use ' await self . _ client . leave ( ) ' to surrender midst game .""" | is_resign = self . _game_result is None
if is_resign : # For all clients that can leave , result of leaving the game either
# loss , or the client will ignore the result
self . _game_result = { self . _player_id : Result . Defeat }
try :
await self . _execute ( leave_game = sc_pb . RequestLeaveGame ( ) )
except... |
def _before_request ( self ) :
"""A function to be run before each request .
See : http : / / flask . pocoo . org / docs / 0.12 / api / # flask . Flask . before _ request""" | # Do not trace if the url is blacklisted
if utils . disable_tracing_url ( flask . request . url , self . blacklist_paths ) :
return
try :
span_context = self . propagator . from_headers ( flask . request . headers )
tracer = tracer_module . Tracer ( span_context = span_context , sampler = self . sampler , e... |
def _get_contigs_to_use ( self , contigs_to_use ) :
'''If contigs _ to _ use is a set , returns that set . If it ' s None , returns an empty set .
Otherwise , assumes it ' s a file name , and gets names from the file''' | if type ( contigs_to_use ) == set :
return contigs_to_use
elif contigs_to_use is None :
return set ( )
else :
f = pyfastaq . utils . open_file_read ( contigs_to_use )
contigs_to_use = set ( [ line . rstrip ( ) for line in f ] )
pyfastaq . utils . close ( f )
return contigs_to_use |
def open_archive ( stream , filename ) :
"""Open an archive ( tarball or zip ) and return the object .""" | name , ext = os . path . splitext ( os . path . basename ( filename ) )
def targz_handler ( stream ) :
return TarGZAdapter ( tarfile . open ( fileobj = stream , mode = 'r:gz' ) )
cls = [ zipfile . ZipFile , targz_handler ] [ 'gz' in ext ]
archive = cls ( stream )
return archive |
def corrgroups60 ( display = False ) :
"""Correlated Groups 60
A simulated dataset with tight correlations among distinct groups of features .""" | # set a constant seed
old_seed = np . random . seed ( )
np . random . seed ( 0 )
# generate dataset with known correlation
N = 1000
M = 60
# set one coefficent from each group of 3 to 1
beta = np . zeros ( M )
beta [ 0 : 30 : 3 ] = 1
# build a correlation matrix with groups of 3 tightly correlated features
C = np . eye... |
def discard ( self , val ) :
"""Remove the first occurrence of * val * .
If * val * is not a member , does nothing .""" | _maxes = self . _maxes
if not _maxes :
return
pos = bisect_left ( _maxes , val )
if pos == len ( _maxes ) :
return
_lists = self . _lists
idx = bisect_left ( _lists [ pos ] , val )
if _lists [ pos ] [ idx ] == val :
self . _delete ( pos , idx ) |
def serve ( info , host , port , reload , debugger , eager_loading , with_threads ) :
'''Runs a local udata development server .
This local server is recommended for development purposes only but it
can also be used for simple intranet deployments .
By default it will not support any sort of concurrency at al... | # Werkzeug logger is special and is required
# with this configuration for development server
logger = logging . getLogger ( 'werkzeug' )
logger . setLevel ( logging . INFO )
logger . handlers = [ ]
debug = current_app . config [ 'DEBUG' ]
if reload is None :
reload = bool ( debug )
if debugger is None :
debugg... |
def to_dict ( self , flat = True ) :
"""Return the contents as regular dict . If ` flat ` is ` True ` the
returned dict will only have the first item present , if ` flat ` is
` False ` all values will be returned as lists .
: param flat : If set to ` False ` the dict returned will have lists
with all the va... | if flat :
return dict ( self . iteritems ( ) )
return dict ( self . lists ( ) ) |
def _le_ropenarrow ( self , annot , p1 , p2 , lr ) :
"""Make stream commands for right open arrow line end symbol . " lr " denotes left ( False ) or right point .""" | m , im , L , R , w , scol , fcol , opacity = self . _le_annot_parms ( annot , p1 , p2 )
shift = 2.5
d = shift * max ( 1 , w )
p2 = R - ( d / 3. , 0 ) if lr else L + ( d / 3. , 0 )
p1 = p2 + ( 2 * d , - d ) if lr else p2 + ( - 2 * d , - d )
p3 = p2 + ( 2 * d , d ) if lr else p2 + ( - 2 * d , d )
p1 *= im
p2 *= im
p3 *= ... |
def add_config_option ( self , default = None ) :
"""Add a - - config option to the argument parser .""" | self . argparser . add_argument ( '--config' , default = default , help = 'Config file to read. Defaults to: %(default)s' )
self . should_parse_config = True |
def field_subset ( f , inds , rank = 0 ) :
"""Return the value of a field at a subset of points .
Parameters
f : array , shape ( a1 , a2 , . . . , ad , r1 , r2 , . . . , rrank )
Rank - r field in d dimensions
inds : integer array , shape ( n , d )
Index vectors
rank : integer
The rank of the field ( 0... | f_dim_space = f . ndim - rank
if inds . ndim > 2 :
raise Exception ( 'Too many dimensions in indices array' )
if inds . ndim == 1 :
if f_dim_space == 1 :
return f [ inds ]
else :
raise Exception ( 'Indices array is 1d but field is not' )
if inds . shape [ 1 ] != f_dim_space :
raise Excep... |
def core_q_to_ros_q ( q_core ) :
"""Converts a ROS quaternion vector to an autolab _ core quaternion vector .""" | q_ros = np . array ( [ q_core [ 1 ] , q_core [ 2 ] , q_core [ 3 ] , q_core [ 0 ] ] )
return q_ros |
def stop ( self , timeout = 10.0 ) :
"""Send all pending messages , close connection .
Returns True if no message left to sent . False if dirty .
- timeout : seconds to wait for sending remaining messages . disconnect
immedately if None .""" | if ( self . _send_greenlet is not None ) and ( self . _send_queue . qsize ( ) > 0 ) :
self . wait_send ( timeout = timeout )
if self . _send_greenlet is not None :
gevent . kill ( self . _send_greenlet )
self . _send_greenlet = None
if self . _error_greenlet is not None :
gevent . kill ( self . _error_g... |
def block ( bdaddr ) :
'''Block a specific bluetooth device by BD Address
CLI Example :
. . code - block : : bash
salt ' * ' bluetooth . block DE : AD : BE : EF : CA : FE''' | if not salt . utils . validate . net . mac ( bdaddr ) :
raise CommandExecutionError ( 'Invalid BD address passed to bluetooth.block' )
cmd = 'hciconfig {0} block' . format ( bdaddr )
__salt__ [ 'cmd.run' ] ( cmd ) . splitlines ( ) |
def _update ( self , sock_info , criteria , document , upsert = False , check_keys = True , multi = False , manipulate = False , write_concern = None , op_id = None , ordered = True , bypass_doc_val = False , collation = None , array_filters = None , session = None , retryable_write = False ) :
"""Internal update /... | common . validate_boolean ( "upsert" , upsert )
if manipulate :
document = self . __database . _fix_incoming ( document , self )
collation = validate_collation_or_none ( collation )
write_concern = write_concern or self . write_concern
acknowledged = write_concern . acknowledged
update_doc = SON ( [ ( 'q' , criteri... |
def cli ( env , sortby , datacenter ) :
"""List number of file storage volumes per datacenter .""" | file_manager = SoftLayer . FileStorageManager ( env . client )
mask = "mask[serviceResource[datacenter[name]]," "replicationPartners[serviceResource[datacenter[name]]]]"
file_volumes = file_manager . list_file_volumes ( datacenter = datacenter , mask = mask )
datacenters = dict ( )
for volume in file_volumes :
serv... |
def set_alias ( index_name , delete = True ) :
'''Properly end an indexation by creating an alias .
Previous alias is deleted if needed .''' | log . info ( 'Creating alias "{0}" on index "{1}"' . format ( es . index_name , index_name ) )
if es . indices . exists_alias ( name = es . index_name ) :
alias = es . indices . get_alias ( name = es . index_name )
previous_indices = alias . keys ( )
if index_name not in previous_indices :
es . indi... |
def rotate ( p , rad , o = ( 0 , 0 ) ) :
"""rotate vector
Args :
p : point ( x , y )
rad : angle ( radian )
o : origin ( x , y )""" | v = vector ( o , p )
fx = lambda x , y , d : x * cos ( d ) - y * sin ( d )
fy = lambda x , y , d : x * sin ( d ) + y * cos ( d )
rv = fx ( v [ 0 ] , v [ 1 ] , rad ) , fy ( v [ 0 ] , v [ 1 ] , rad )
return translate ( rv , o ) |
def train ( self , sentences , save_loc = None , nr_iter = 5 ) :
'''Train a model from sentences , and save it at ` ` save _ loc ` ` . ` ` nr _ iter ` `
controls the number of Perceptron training iterations .
: param sentences : A list of ( words , tags ) tuples .
: param save _ loc : If not ` ` None ` ` , sa... | self . _make_tagdict ( sentences )
self . model . classes = self . classes
for iter_ in range ( nr_iter ) :
c = 0
n = 0
for words , tags in sentences :
prev , prev2 = self . START
context = self . START + [ self . _normalize ( w ) for w in words ] + self . END
for i , word in enumera... |
def lazy_reverse_binmap ( f , xs ) :
"""Same as lazy _ binmap , except the parameters are flipped for the binary function""" | return ( f ( y , x ) for x , y in zip ( xs , xs [ 1 : ] ) ) |
def increment_time_by ( self , secs ) :
"""This is called when wpilib . Timer . delay ( ) occurs""" | self . slept = [ True ] * 3
was_paused = False
with self . lock :
self . _increment_tm ( secs )
while self . paused and secs > 0 :
if self . pause_secs is not None : # if pause _ secs is set , this means it was a step operation ,
# so we adjust the wait accordingly
if secs > self . p... |
def _get_event_records ( self , limit : int = None , offset : int = None , filters : List [ Tuple [ str , Any ] ] = None , logical_and : bool = True , ) -> List [ EventRecord ] :
"""Return a batch of event records
The batch size can be tweaked with the ` limit ` and ` offset ` arguments .
Additionally the retur... | cursor = self . _form_and_execute_json_query ( query = 'SELECT identifier, source_statechange_id, data FROM state_events ' , limit = limit , offset = offset , filters = filters , logical_and = logical_and , )
result = [ EventRecord ( event_identifier = row [ 0 ] , state_change_identifier = row [ 1 ] , data = row [ 2 ] ... |
async def mount ( self , device ) :
"""Mount the device if not already mounted .
: param device : device object , block device path or mount path
: returns : whether the device is mounted .""" | device = self . _find_device ( device )
if not self . is_handleable ( device ) or not device . is_filesystem :
self . _log . warn ( _ ( 'not mounting {0}: unhandled device' , device ) )
return False
if device . is_mounted :
self . _log . info ( _ ( 'not mounting {0}: already mounted' , device ) )
return... |
def get_all_specs ( self ) :
"""Returns a dict mapping kernel names and resource directories .""" | # This is new in 4.1 - > https : / / github . com / jupyter / jupyter _ client / pull / 93
specs = self . get_all_kernel_specs_for_envs ( )
specs . update ( super ( EnvironmentKernelSpecManager , self ) . get_all_specs ( ) )
return specs |
def send ( self , topic , value = None , timeout = 60 , key = None , partition = None , timestamp_ms = None ) :
"""Publish a message to a topic .
- ` ` topic ` ` ( str ) : topic where the message will be published
- ` ` value ` ` : message value . Must be type bytes , or be serializable to bytes via configured ... | future = self . producer . send ( topic , value = value , key = key , partition = partition , timestamp_ms = timestamp_ms )
future . get ( timeout = timeout ) |
def _write ( self , item , labels , features ) :
"""Writes the given item to the owned file .""" | data = Data ( [ item ] , [ labels ] , [ features ] )
self . _writer . write ( data , self . groupname , append = True ) |
def clean_build ( self , arch = None ) :
'''Deletes all the build information of the recipe .
If arch is not None , only this arch dir is deleted . Otherwise
( the default ) all builds for all archs are deleted .
By default , this just deletes the main build dir . If the
recipe has e . g . object files bigl... | if arch is None :
base_dir = join ( self . ctx . build_dir , 'other_builds' , self . name )
else :
base_dir = self . get_build_container_dir ( arch )
dirs = glob . glob ( base_dir + '-*' )
if exists ( base_dir ) :
dirs . append ( base_dir )
if not dirs :
warning ( 'Attempted to clean build for {} but fo... |
def pic_inflow_v1 ( self ) :
"""Update the inlet link sequence .
Required inlet sequence :
| dam _ inlets . Q |
Calculated flux sequence :
| Inflow |
Basic equation :
: math : ` Inflow = Q `""" | flu = self . sequences . fluxes . fastaccess
inl = self . sequences . inlets . fastaccess
flu . inflow = inl . q [ 0 ] |
def _supported_rule ( protocol , ethertype ) :
"""Checks that the rule is an IPv4 rule of a supported protocol""" | if not protocol or protocol not in utils . SUPPORTED_SG_PROTOCOLS :
return False
if ethertype != n_const . IPv4 :
return False
return True |
def get_collection_in_tower ( self , key ) :
"""Get items from this collection that are added in the current tower .""" | new = tf . get_collection ( key )
old = set ( self . original . get ( key , [ ] ) )
# persist the order in new
return [ x for x in new if x not in old ] |
def decoded_output_boxes_class_agnostic ( self ) :
"""Returns : Nx4""" | assert self . _bbox_class_agnostic
box_logits = tf . reshape ( self . box_logits , [ - 1 , 4 ] )
decoded = decode_bbox_target ( box_logits / self . bbox_regression_weights , self . proposals . boxes )
return decoded |
def from_geom ( geom ) :
"""Return an instantiated stat object
stats should not override this method .
Parameters
geom : geom
` geom `
Returns
out : stat
A stat object
Raises
: class : ` PlotnineError ` if unable to create a ` stat ` .""" | name = geom . params [ 'stat' ]
kwargs = geom . _kwargs
# More stable when reloading modules than
# using issubclass
if ( not isinstance ( name , type ) and hasattr ( name , 'compute_layer' ) ) :
return name
if isinstance ( name , stat ) :
return name
elif isinstance ( name , type ) and issubclass ( name , stat... |
def get_all_in_collection ( self , collection_paths : Union [ str , Iterable [ str ] ] , load_metadata : bool = True ) -> Sequence [ EntityType ] :
"""Gets entities contained within the given iRODS collections .
If one or more of the collection _ paths does not exist , a ` FileNotFound ` exception will be raised ... | |
def download_schema ( uri , path , comment = None ) :
"""Download a schema from a specified URI and save it locally .
: param uri : url where the schema should be downloaded
: param path : local file path where the schema should be saved
: param comment : optional comment ; if specified , will be added to
t... | # if requests isn ' t available , warn and bail out
if requests is None :
sys . stderr . write ( req_requests_msg )
return
# short - hand name of the schema , based on uri
schema = os . path . basename ( uri )
try :
req = requests . get ( uri , stream = True )
req . raise_for_status ( )
with open ( ... |
def retry ( method ) :
"""Allows to retry method execution few times .""" | def inner ( self , * args , ** kwargs ) :
attempt_number = 1
while attempt_number < self . retries :
try :
return method ( self , * args , ** kwargs )
except HasOffersException as exc :
if 'API usage exceeded rate limit' not in str ( exc ) :
raise exc
... |
def display ( self , buffer = None ) :
"""\~english
Write buffer to physical display .
@ param buffer : Data to display , If < b > None < / b > mean will use self . _ buffer data to display
\~chinese
将缓冲区写入物理显示屏 。
@ param buffer : 要显示的数据 , 如果是 < b > None < / b > ( 默认 ) 将把 self . _ buffer 数据写入物理显示屏""" | if buffer != None :
self . _display_buffer ( buffer )
else :
self . _display_buffer ( self . _buffer ) |
def sort_files_by_size ( filenames , verbose = False , reverse = False ) :
"""Return a list of the filenames sorted in order from smallest file
to largest file ( or largest to smallest if reverse is set to True ) .
If a filename in the list is None ( used by many pycbc _ glue . ligolw based
codes to indicate ... | if verbose :
if reverse :
print >> sys . stderr , "sorting files from largest to smallest ..."
else :
print >> sys . stderr , "sorting files from smallest to largest ..."
return sorted ( filenames , key = ( lambda filename : os . stat ( filename ) [ stat . ST_SIZE ] if filename is not None else ... |
def p_commands_list ( p ) :
"""commands : commands command""" | p [ 0 ] = p [ 1 ]
# section 3.2 : REQUIRE command must come before any other commands
if p [ 2 ] . RULE_IDENTIFIER == 'REQUIRE' :
if any ( command . RULE_IDENTIFIER != 'REQUIRE' for command in p [ 0 ] . commands ) :
print ( "REQUIRE command on line %d must come before any " "other non-REQUIRE commands" % p ... |
def demo ( ctx , reset = False ) :
'''Set up the demo environment and run the server''' | if reset :
rmdb ( ctx )
ctx . run ( 'demo check' , pty = True )
ctx . run ( 'demo loaddemo' , pty = True )
ctx . run ( 'demo runserver' , pty = True ) |
def _get_response_ms ( self ) :
"""Get the duration of the request response cycle is milliseconds .
In case of negative duration 0 is returned .""" | response_timedelta = now ( ) - self . log [ 'requested_at' ]
response_ms = int ( response_timedelta . total_seconds ( ) * 1000 )
return max ( response_ms , 0 ) |
def _register_jobs ( self ) :
"""This method extracts only the " ConcreteJob " class
from modules that were collected by ConfigReader . _ get _ modules ( ) .
And , this method called Subject . notify ( ) ,
append " ConcreteJob " classes to JobObserver . jobs .""" | # job _ name is hard - corded
job_name = 'ConcreteJob'
modules = self . _get_modules ( )
for section , options in self . config . items ( ) :
if section == 'global' :
continue
try :
name = options [ 'module' ]
except KeyError :
raise ConfigMissingValue ( section , 'module' )
try ... |
def peak_templates ( self ) :
"""Create a list of concrete peak templates from a list of general peak descriptions .
: return : List of peak templates .
: rtype : : py : class : ` list `""" | peak_templates = [ ]
for peak_descr in self :
expanded_dims = [ dim_group . dimensions for dim_group in peak_descr ]
templates = product ( * expanded_dims )
for template in templates :
peak_templates . append ( PeakTemplate ( template ) )
return peak_templates |
def is_locked ( self , key ) :
"""Returns the status of the lock of a global variable
: param key : the unique key of the global variable
: return :""" | key = str ( key )
if key in self . __variable_locks :
return self . __variable_locks [ key ] . locked ( )
return False |
def is_schema_of_common_names ( schema : GraphQLSchema ) -> bool :
"""Check whether this schema uses the common naming convention .
GraphQL schema define root types for each type of operation . These types are the
same as any other type and can be named in any manner , however there is a common
naming convent... | query_type = schema . query_type
if query_type and query_type . name != "Query" :
return False
mutation_type = schema . mutation_type
if mutation_type and mutation_type . name != "Mutation" :
return False
subscription_type = schema . subscription_type
if subscription_type and subscription_type . name != "Subscr... |
def str_dateStrip ( astr_datestr , astr_sep = '/' ) :
"""Simple date strip method . Checks if the < astr _ datestr >
contains < astr _ sep > . If so , strips these from the string
and returns result .
The actual stripping entails falling through two layers
of exception handling . . . so it is something of a... | try :
index = astr_datestr . index ( astr_sep )
except :
return astr_datestr . encode ( 'ascii' )
try :
tm = time . strptime ( astr_datestr , '%d/%M/%Y' )
except :
try :
tm = time . strptime ( astr_datestr , '%d/%M/%y' )
except :
error_exit ( 'str_dateStrip' , 'parsing date string' ,... |
def rectToArray ( self , swapWH = False ) :
"""\~english
Rectangles converted to array of coordinates
@ return : an array of rect points . eg . ( x1 , y1 , x2 , y2)
\~chinese
矩形数据转换为矩形坐标数组
@ return : 矩形座标数组 , 例如 : ( x1 , y1 , x2 , y2 )""" | if swapWH == False :
return [ self . x , self . y , self . x + self . width , self . y + self . height ]
else :
return [ self . x , self . y , self . x + self . height , self . y + self . width ] |
def get_type_properties ( self , property_obj , name , additional_prop = False ) :
"""Extend parents ' Get internal properties of property ' - method""" | property_type , property_format , property_dict = super ( Schema , self ) . get_type_properties ( property_obj , name , additional_prop = additional_prop )
_schema = self . storage . get ( property_type )
if _schema and ( 'additionalProperties' in property_obj ) :
_property_type , _property_format , _property_dict ... |
def SaturationFlux ( EPIC , campaign = None , ** kwargs ) :
'''Returns the well depth for the target . If any of the target ' s pixels
have flux larger than this value , they are likely to be saturated and
cause charge bleeding . The well depths were obtained from Table 13
of the Kepler instrument handbook . ... | channel , well_depth = np . loadtxt ( os . path . join ( EVEREST_SRC , 'missions' , 'k2' , 'tables' , 'well_depth.tsv' ) , unpack = True )
satflx = well_depth [ channel == Channel ( EPIC , campaign = campaign ) ] [ 0 ] / 6.02
return satflx |
def get_season_player_stats ( self , season_key , player_key ) :
"""Calling Season Player Stats API .
Arg :
season _ key : key of the season
player _ key : key of the player
Return :
json data""" | season_player_stats_url = self . api_path + "season/" + season_key + "/player/" + player_key + "/stats/"
response = self . get_response ( season_player_stats_url )
return response |
def load ( self , * args , ** kwargs ) :
"""Clear all existing key : value items and import all key : value items from
< mapping > . If multiple values exist for the same key in < mapping > , they
are all be imported .
Example :
omd = omdict ( [ ( 1,1 ) , ( 1,11 ) , ( 1,111 ) , ( 2,2 ) , ( 3,3 ) ] )
omd .... | self . clear ( )
self . updateall ( * args , ** kwargs )
return self |
def update_thing_shadow ( self , ** kwargs ) :
r"""Updates the thing shadow for the specified thing .
: Keyword Arguments :
* * thingName * ( ` ` string ` ` ) - -
[ REQUIRED ]
The name of the thing .
* * payload * ( ` ` bytes or seekable file - like object ` ` ) - -
[ REQUIRED ]
The state information ... | thing_name = self . _get_required_parameter ( 'thingName' , ** kwargs )
payload = self . _get_required_parameter ( 'payload' , ** kwargs )
return self . _shadow_op ( 'update' , thing_name , payload ) |
def _pack_images ( images , rows , cols ) :
"""Helper utility to make a tiled field of images from numpy arrays .
Args :
images : Image tensor in shape [ N , W , H , C ] .
rows : Number of images per row in tiled image .
cols : Number of images per column in tiled image .
Returns :
A tiled image of shap... | shape = onp . shape ( images )
width , height , depth = shape [ - 3 : ]
images = onp . reshape ( images , ( - 1 , width , height , depth ) )
batch = onp . shape ( images ) [ 0 ]
rows = onp . minimum ( rows , batch )
cols = onp . minimum ( batch // rows , cols )
images = images [ : rows * cols ]
images = onp . reshape (... |
def size ( self ) :
'''Return the area of the patch .
The area can be computed using the standard polygon area formula + signed segment areas of each arc .''' | polygon_area = 0
for a in self . arcs :
polygon_area += box_product ( a . start_point ( ) , a . end_point ( ) )
polygon_area /= 2.0
return polygon_area + sum ( [ a . sign * a . segment_area ( ) for a in self . arcs ] ) |
def contains ( self , key ) :
'''Returns whether the object named by ` key ` exists .
First checks ` ` cache _ datastore ` ` .''' | return self . cache_datastore . contains ( key ) or self . child_datastore . contains ( key ) |
def to_dataset_files ( self , local_path = None , remote_path = None ) :
"""Save the GDataframe to a local or remote location
: param local _ path : a local path to the folder in which the data must be saved
: param remote _ path : a remote dataset name that wants to be used for these data
: return : None""" | return FrameToGMQL . to_dataset_files ( self , path_local = local_path , path_remote = remote_path ) |
def upsert_entities ( self , entities , sync = False ) :
"""Upsert a list of entities to the database
: param entities : The entities to sync
: param sync : Do a sync instead of an upsert""" | # Select the entities we are upserting for update to reduce deadlocks
if entities : # Default select for update query when syncing all
select_for_update_query = ( 'SELECT FROM {table_name} FOR NO KEY UPDATE' ) . format ( table_name = Entity . _meta . db_table )
select_for_update_query_params = [ ]
# If we a... |
def scale_0to1 ( image_in , exclude_outliers_below = False , exclude_outliers_above = False ) :
"""Scale the two images to [ 0 , 1 ] based on min / max from both .
Parameters
image _ in : ndarray
Input image
exclude _ outliers _ { below , above } : float
Lower / upper limit , a value between 0 and 100.
... | min_value = image_in . min ( )
max_value = image_in . max ( )
# making a copy to ensure no side - effects
image = image_in . copy ( )
if exclude_outliers_below :
perctl = float ( exclude_outliers_below )
image [ image < np . percentile ( image , perctl ) ] = min_value
if exclude_outliers_above :
perctl = fl... |
def add_scaled_residues_highlight_to_nglview ( self , view , structure_resnums , chain = None , color = 'red' , unique_colors = False , opacity_range = ( 0.5 , 1 ) , scale_range = ( .7 , 10 ) , multiplier = None ) :
"""Add a list of residue numbers ( which may contain repeating residues ) to a view , or add a dicti... | # TODO : likely to move these functions to a separate nglview / utils folder since they are not coupled to the structure
# TODO : add color by letter _ annotations !
if not chain :
chain = self . mapped_chains
if not chain :
raise ValueError ( 'Please input chain ID to display residue on' )
else :
c... |
def _to_dict ( self , serialize = False ) :
"""This method works by copying self . _ _ dict _ _ , and removing everything that should not be serialized .""" | copy_dict = self . __dict__ . copy ( )
for key , value in vars ( self ) . items ( ) : # We want to send all ids to Zendesk always
if serialize and key == 'id' :
continue
# If this is a Zenpy object , convert it to a dict .
if not serialize and isinstance ( value , BaseObject ) :
copy_dict [ ... |
def open ( cls , blob , username , password ) :
"""Creates a vault from a blob object""" | return cls ( blob , blob . encryption_key ( username , password ) ) |
def axis ( self ) -> Callable [ [ Any ] , Any ] :
"""Determine the axis to return based on the hist type .""" | axis_func = hist_axis_func ( axis_type = self . axis_type )
return axis_func |
def init ( self , app_id = None ) :
"""Initializes Steam API library .
: param str | int app _ id : Application ID .
: raises : SteamApiStartupError""" | self . set_app_id ( app_id )
err_msg = ( 'Unable to initialize. Check Steam client is running ' 'and Steam application ID is defined in steam_appid.txt or passed to Api.' )
if self . _lib . steam_init ( ) :
try :
_set_client ( self . _lib . Client ( ) )
self . utils = Utils ( )
self . curren... |
def get_or_set_hash ( name , length = 8 , chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' ) :
'''Perform a one - time generation of a hash and write it to the local grains .
If that grain has already been set return the value instead .
This is useful for generating passwords or keys that are specif... | ret = get ( name , None )
if ret is None :
val = '' . join ( [ random . SystemRandom ( ) . choice ( chars ) for _ in range ( length ) ] )
if DEFAULT_TARGET_DELIM in name :
root , rest = name . split ( DEFAULT_TARGET_DELIM , 1 )
curr = get ( root , _infinitedict ( ) )
val = _dict_from_pat... |
def image_clone ( call = None , kwargs = None ) :
'''Clones an existing image .
. . versionadded : : 2016.3.0
name
The name of the new image .
image _ id
The ID of the image to be cloned . Can be used instead of ` ` image _ name ` ` .
image _ name
The name of the image to be cloned . Can be used inste... | if call != 'function' :
raise SaltCloudSystemExit ( 'The image_clone function must be called with -f or --function.' )
if kwargs is None :
kwargs = { }
name = kwargs . get ( 'name' , None )
image_id = kwargs . get ( 'image_id' , None )
image_name = kwargs . get ( 'image_name' , None )
if name is None :
rais... |
def iter ( self , keyed = False , extended = False , cast = True , relations = False ) :
"""https : / / github . com / frictionlessdata / tableschema - py # schema""" | # Prepare unique checks
if cast :
unique_fields_cache = { }
if self . schema :
unique_fields_cache = _create_unique_fields_cache ( self . schema )
# Open / iterate stream
self . __stream . open ( )
iterator = self . __stream . iter ( extended = True )
iterator = self . __apply_processors ( iterator , ca... |
def setImageMode ( self ) :
"""Extracts color ordering and 24 vs . 32 bpp info out of the pixel format information""" | if self . _version_server == 3.889 :
self . setPixelFormat ( bpp = 16 , depth = 16 , bigendian = 0 , truecolor = 1 , redmax = 31 , greenmax = 63 , bluemax = 31 , redshift = 11 , greenshift = 5 , blueshift = 0 )
self . image_mode = "BGR;16"
elif ( self . truecolor and ( not self . bigendian ) and self . depth ==... |
def awaitTermination ( self , timeout = None ) :
"""Wait for the execution to stop .
@ param timeout : time to wait in seconds""" | if timeout is None :
self . _jssc . awaitTermination ( )
else :
self . _jssc . awaitTerminationOrTimeout ( int ( timeout * 1000 ) ) |
def getKeySequenceCounter ( self ) :
"""get current Thread Network key sequence""" | print '%s call getKeySequenceCounter' % self . port
keySequence = ''
keySequence = self . __sendCommand ( WPANCTL_CMD + 'getprop -v Network:KeyIndex' ) [ 0 ]
return keySequence |
def get_cache ( app ) :
"""Attempt to find a valid cache from the Celery configuration
If the setting is a valid cache , just use it .
Otherwise , if Django is installed , then :
If the setting is a valid Django cache entry , then use that .
If the setting is empty use the default cache
Otherwise , if Wer... | jobtastic_cache_setting = app . conf . get ( 'JOBTASTIC_CACHE' )
if isinstance ( jobtastic_cache_setting , BaseCache ) :
return jobtastic_cache_setting
if 'Django' in CACHES :
if jobtastic_cache_setting :
try :
return WrappedCache ( get_django_cache ( jobtastic_cache_setting ) )
exce... |
def topological_order ( self ) :
"""Return the topological order of the node IDs from the input node to the output node .""" | q = Queue ( )
in_degree = { }
for i in range ( self . n_nodes ) :
in_degree [ i ] = 0
for u in range ( self . n_nodes ) :
for v , _ in self . adj_list [ u ] :
in_degree [ v ] += 1
for i in range ( self . n_nodes ) :
if in_degree [ i ] == 0 :
q . put ( i )
order_list = [ ]
while not q . empty... |
def number ( self ) : # type : ( ) - > int
"""Return this commits number .
This is the same as the total number of commits in history up until
this commit .
This value can be useful in some CI scenarios as it allows to track
progress on any given branch ( although there can be two commits with the
same nu... | cmd = 'git log --oneline {}' . format ( self . sha1 )
out = shell . run ( cmd , capture = True , never_pretend = True ) . stdout . strip ( )
return len ( out . splitlines ( ) ) |
def get_list_of_concatenated_objects ( obj , dot_separated_name , lst = None ) :
"""get a list of the objects consisting of
- obj
- obj + " . " + dot _ separated _ name
- ( obj + " . " + dot _ separated _ name ) + " . " + dot _ separated _ name ( called recursively )
Note : lists are expanded
Args :
obj... | from textx . scoping import Postponed
if lst is None :
lst = [ ]
if not obj :
return lst
if obj in lst :
return lst
lst . append ( obj )
if type ( obj ) is Postponed :
return lst
ret = get_referenced_object ( None , obj , dot_separated_name )
if type ( ret ) is list :
for r in ret :
lst = ge... |
def _read_header ( self ) :
'''Little - endian
| . . . 4 bytes unsigned int . . . | . . . 4 bytes unsigned int . . . |
| frames count | dimensions count |''' | self . _fh . seek ( 0 )
buf = self . _fh . read ( 4 * 2 )
fc , dc = struct . unpack ( "<II" , buf )
return fc , dc |
def create ( cls , statement_format , date_start , date_end , monetary_account_id = None , regional_format = None , custom_headers = None ) :
""": type user _ id : int
: type monetary _ account _ id : int
: param statement _ format : The format type of statement . Allowed values :
MT940 , CSV , PDF .
: type... | if custom_headers is None :
custom_headers = { }
request_map = { cls . FIELD_STATEMENT_FORMAT : statement_format , cls . FIELD_DATE_START : date_start , cls . FIELD_DATE_END : date_end , cls . FIELD_REGIONAL_FORMAT : regional_format }
request_map_string = converter . class_to_json ( request_map )
request_map_string... |
def min_zoom ( self ) :
"""Get the minimal zoom level of all layers .
Returns :
int : the minimum of all zoom levels of all layers
Raises :
ValueError : if no layers exist""" | zoom_levels = [ map_layer . min_zoom for map_layer in self . layers ]
return min ( zoom_levels ) |
def read ( self , client ) :
"""Read from Vault while handling non surprising errors .""" | val = None
if self . no_resource :
return val
LOG . debug ( "Reading from %s" , self )
try :
val = client . read ( self . path )
except hvac . exceptions . InvalidRequest as vault_exception :
if str ( vault_exception ) . startswith ( 'no handler for route' ) :
val = None
return val |
def preconnect ( self , size = - 1 ) :
"""( pre ) Connects some or all redis clients inside the pool .
Args :
size ( int ) : number of redis clients to build and to connect
( - 1 means all clients if pool max _ size > - 1)
Raises :
ClientError : when size = = - 1 and pool max _ size = = - 1""" | if size == - 1 and self . max_size == - 1 :
raise ClientError ( "size=-1 not allowed with pool max_size=-1" )
limit = min ( size , self . max_size ) if size != - 1 else self . max_size
clients = yield [ self . get_connected_client ( ) for _ in range ( 0 , limit ) ]
for client in clients :
self . release_client ... |
def generate_mtime_map ( opts , path_map ) :
'''Generate a dict of filename - > mtime''' | file_map = { }
for saltenv , path_list in six . iteritems ( path_map ) :
for path in path_list :
for directory , _ , filenames in salt . utils . path . os_walk ( path ) :
for item in filenames :
try :
file_path = os . path . join ( directory , item )
... |
def transform_field ( instance , source_field_name , destination_field_name , transformation ) :
'''Does an image transformation on a instance . It will get the image
from the source field attribute of the instnace , then call
the transformation function with that instance , and finally
save that transformed ... | source_field = getattr ( instance , source_field_name )
destination_field = getattr ( instance , destination_field_name )
update_fields = [ destination_field_name ]
transformed_image = get_transformed_image ( source_field , transformation )
if transformed_image :
destination_name = os . path . basename ( source_fie... |
def _validate_features ( self , data ) :
"""Validate Booster and data ' s feature _ names are identical .
Set feature _ names and feature _ types from DMatrix""" | if self . feature_names is None :
self . feature_names = data . feature_names
self . feature_types = data . feature_types
else : # Booster can ' t accept data with different feature names
if self . feature_names != data . feature_names :
msg = 'feature_names mismatch: {0} {1}'
raise ValueErr... |
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) :
"""See : meth : ` superclass method
< . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > `
for spec of input and result values .""" | # extracting dictionary of coefficients specific to required
# intensity measure type .
C = self . COEFFS [ imt ]
mean = ( self . _get_magnitude_term ( C , rup . mag ) + self . _get_distance_term ( C , dists . rjb , rup . mag ) + self . _get_site_term ( C , sites . vs30 ) )
# Units of GMPE are in terms of m / s ( corre... |
def bytes_to_unicode ( s , encoding = 'utf-8' , errors = 'replace' ) :
"""Helper to convert byte string to unicode string for user based input
: param str s : string to decode
: param str encoding : utf - 8 by default
: param str errors : what to do when decoding fails
: return : unicode utf - 8 string""" | if compat . PY3 :
return str ( s , 'utf-8' ) if isinstance ( s , bytes ) else s
return s if isinstance ( s , unicode ) else s . decode ( encoding , errors ) |
def get_mpl_patches_texts ( self , properties_func = None , text_offset = 5.0 , origin = 1 ) :
"""Often , the regions files implicitly assume the lower - left
corner of the image as a coordinate ( 1,1 ) . However , the python
convetion is that the array index starts from 0 . By default
( ` ` origin = 1 ` ` ) ... | from . mpl_helper import as_mpl_artists
patches , txts = as_mpl_artists ( self , properties_func , text_offset , origin = origin )
return patches , txts |
def fonts ( self ) :
"""Generator yielding all fonts of this typeface
Yields :
Font : the next font in this typeface""" | for width in ( w for w in FontWidth if w in self ) :
for slant in ( s for s in FontSlant if s in self [ width ] ) :
for weight in ( w for w in FontWeight if w in self [ width ] [ slant ] ) :
yield self [ width ] [ slant ] [ weight ] |
def _login_dockerhub ( ) :
"""Login to the Docker Hub account
: return : None""" | dockerhub_credentials = _get_dockerhub_credentials ( )
logging . info ( 'Logging in to DockerHub' )
# We use password - stdin instead of - - password to avoid leaking passwords in case of an error .
# This method will produce the following output :
# > WARNING ! Your password will be stored unencrypted in / home / jenk... |
def in6_ptoc ( addr ) :
"""Converts an IPv6 address in printable representation to RFC
1924 Compact Representation ; - )
Returns None on error .""" | try :
d = struct . unpack ( "!IIII" , inet_pton ( socket . AF_INET6 , addr ) )
except Exception :
return None
res = 0
m = [ 2 ** 96 , 2 ** 64 , 2 ** 32 , 1 ]
for i in range ( 4 ) :
res += d [ i ] * m [ i ]
rem = res
res = [ ]
while rem :
res . append ( _rfc1924map [ rem % 85 ] )
rem = rem // 85
res ... |
def get_all_instance_profiles ( path_prefix = '/' , region = None , key = None , keyid = None , profile = None ) :
'''Get and return all IAM instance profiles , starting at the optional path .
. . versionadded : : 2016.11.0
CLI Example :
salt - call boto _ iam . get _ all _ instance _ profiles''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
marker = False
profiles = [ ]
while marker is not None :
marker = marker if marker else None
p = conn . list_instance_profiles ( path_prefix = path_prefix , marker = marker )
res = p . list_instance_profiles_response . list... |
def _verify_part_number ( self ) :
"""Verifies that the total number of parts is smaller then 10 ^ 5 which
is the maximum number of parts .""" | total = int ( math . ceil ( self . _file_size / self . _part_size ) )
if total > PartSize . MAXIMUM_TOTAL_PARTS :
self . _status = TransferState . FAILED
raise SbgError ( 'Total parts = {}. Maximum number of parts is {}' . format ( total , PartSize . MAXIMUM_TOTAL_PARTS ) ) |
def serialize_bytes ( data ) :
"""Write bytes by using Telegram guidelines""" | if not isinstance ( data , bytes ) :
if isinstance ( data , str ) :
data = data . encode ( 'utf-8' )
else :
raise TypeError ( 'bytes or str expected, not {}' . format ( type ( data ) ) )
r = [ ]
if len ( data ) < 254 :
padding = ( len ( data ) + 1 ) % 4
if padding != 0 :
padding ... |
def set_duration ( self , duration ) :
"""Sets the assessment duration .
arg : duration ( osid . calendaring . Duration ) : assessment
duration
raise : InvalidArgument - ` ` duration ` ` is invalid
raise : NoAccess - ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` `
* compliance : mandatory - - This metho... | # Implemented from template for osid . assessment . AssessmentOfferedForm . set _ duration _ template
if self . get_duration_metadata ( ) . is_read_only ( ) :
raise errors . NoAccess ( )
if not self . _is_valid_duration ( duration , self . get_duration_metadata ( ) ) :
raise errors . InvalidArgument ( )
map = d... |
def __reverse ( self , ** kwargs ) :
"""If we hit the bathymetry , set the location to where we came from .""" | start_point = kwargs . pop ( 'start_point' )
return Location4D ( latitude = start_point . latitude , longitude = start_point . longitude , depth = start_point . depth ) |
def _nextJob ( self , job , nextRound = True ) :
"""Given a completed job , start the next job in the round , or return None
: param nextRound : whether to start jobs from the next round if the current round is completed .
: return : the newly started Job , or None if no job was started""" | jobInfo = job . info ( )
assert jobInfo [ 'state' ] == 'FINISHED'
roundEnd = False
if jobInfo [ 'type' ] == 'INJECT' :
nextCommand = 'GENERATE'
elif jobInfo [ 'type' ] == 'GENERATE' :
nextCommand = 'FETCH'
elif jobInfo [ 'type' ] == 'FETCH' :
nextCommand = 'PARSE'
elif jobInfo [ 'type' ] == 'PARSE' :
ne... |
def import_obj ( cls , i_datasource , import_time = None ) :
"""Imports the datasource from the object to the database .
Metrics and columns and datasource will be overridden if exists .
This function can be used to import / export dashboards between multiple
superset instances . Audit metadata isn ' t copies... | def lookup_datasource ( d ) :
return db . session . query ( DruidDatasource ) . filter ( DruidDatasource . datasource_name == d . datasource_name , DruidCluster . cluster_name == d . cluster_name , ) . first ( )
def lookup_cluster ( d ) :
return db . session . query ( DruidCluster ) . filter_by ( cluster_name =... |
def _calculate_credit_charge ( self , message ) :
"""Calculates the credit charge for a request based on the command . If
connection . supports _ multi _ credit is not True then the credit charge
isn ' t valid so it returns 0.
The credit charge is the number of credits that are required for
sending / receiv... | credit_size = 65536
if not self . supports_multi_credit :
credit_charge = 0
elif message . COMMAND == Commands . SMB2_READ :
max_size = message [ 'length' ] . get_value ( ) + message [ 'read_channel_info_length' ] . get_value ( ) - 1
credit_charge = math . ceil ( max_size / credit_size )
elif message . COMM... |
def asTuple ( self ) :
"""Return the location as a tuple .
Sort the dimension names alphabetically .
> > > l = Location ( pop = 1 , snap = - 100)
> > > l . asTuple ( )
( ( ' pop ' , 1 ) , ( ' snap ' , - 100 ) )""" | t = [ ]
k = sorted ( self . keys ( ) )
for key in k :
t . append ( ( key , self [ key ] ) )
return tuple ( t ) |
def Morton ( rhol , rhog , mul , sigma , g = g ) :
r'''Calculates Morton number or ` Mo ` for a liquid and vapor with the
specified properties , under the influence of gravitational force ` g ` .
. . math : :
Mo = \ frac { g \ mu _ l ^ 4 ( \ rho _ l - \ rho _ g ) } { \ rho _ l ^ 2 \ sigma ^ 3}
Parameters
... | mul2 = mul * mul
return g * mul2 * mul2 * ( rhol - rhog ) / ( rhol * rhol * sigma * sigma * sigma ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.