signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def init_from_wave_file ( wavpath ) : """Init a sonic visualiser environment structure based the analysis of the main audio file . The audio file have to be encoded in wave Args : wavpath ( str ) : the full path to the wavfile"""
try : samplerate , data = SW . read ( wavpath ) nframes = data . shape [ 0 ] except : # scipy cannot handle 24 bit wav files # and wave cannot handle 32 bit wav files try : w = wave . open ( wavpath ) samplerate = w . getframerate ( ) nframes = w . getnframes ( ) except : ...
def _format_exception_message ( e ) : """Formats the specified exception ."""
# Prevent duplication of " AppError " in places that print " AppError " # and then this formatted string if isinstance ( e , dxpy . AppError ) : return _safe_unicode ( e ) if USING_PYTHON2 : return unicode ( e . __class__ . __name__ , 'utf-8' ) + ": " + _safe_unicode ( e ) else : return e . __class__ . __na...
def clean_scope ( self ) : """The scope is assembled by combining all the set flags into a single integer value which we can later check again for set bits . If * no * scope is set , we return the default scope which is the first defined scope in : attr : ` provider . constants . SCOPES ` ."""
default = SCOPES [ 0 ] [ 0 ] flags = self . cleaned_data . get ( 'scope' , [ ] ) return scope . to_int ( default = default , * flags )
def chmod_native ( path , mode_expression , recursive = False ) : """This is ugly and will only work on POSIX , but the built - in Python os . chmod support is very minimal , and neither supports fast recursive chmod nor " + X " type expressions , both of which are slow for large trees . So just shell out ."""
popenargs = [ "chmod" ] if recursive : popenargs . append ( "-R" ) popenargs . append ( mode_expression ) popenargs . append ( path ) subprocess . check_call ( popenargs )
def get_content_type ( self ) : """Returns the Content Type to serve from either the extension or the Accept headers . Uses the : attr : ` EXTENSION _ MAP ` list for all the configured MIME types ."""
extension = self . path_params . get ( '_extension' ) for ext , mime in self . EXTENSION_MAP : if ext == extension : return mime # Else : use the Accept headers if self . response . vary is None : self . response . vary = [ 'Accept' ] else : self . response . vary . append ( 'Accept' ) types = [ mim...
def install_os_snaps ( snaps , refresh = False ) : """Install OpenStack snaps from channel and with mode @ param snaps : Dictionary of snaps with channels and modes of the form : { ' snap _ name ' : { ' channel ' : ' snap _ channel ' , ' mode ' : ' snap _ mode ' } } Where channel is a snapstore channel and ...
def _ensure_flag ( flag ) : if flag . startswith ( '--' ) : return flag return '--{}' . format ( flag ) if refresh : for snap in snaps . keys ( ) : snap_refresh ( snap , _ensure_flag ( snaps [ snap ] [ 'channel' ] ) , _ensure_flag ( snaps [ snap ] [ 'mode' ] ) ) else : for snap in snaps ...
def to_dict ( self ) : """Get a dictionary of the attributes of this Language object , which can be useful for constructing a similar object ."""
if self . _dict is not None : return self . _dict result = { } for key in self . ATTRIBUTES : value = getattr ( self , key ) if value : result [ key ] = value self . _dict = result return result
def wet_records_from_file_obj ( f , take_ownership = False ) : """Iterate through records in WET file object ."""
while True : record = WETRecord . read ( f ) if record is None : break if not record . url : continue yield record if take_ownership : f . close ( )
def get_object ( self , * args , ** kwargs ) : """Should memoize the object to avoid multiple query if get _ object is used many times in the view"""
self . category_instance = get_object_or_404 ( Category , slug = self . kwargs [ 'category_slug' ] ) return get_object_or_404 ( Post , thread__id = self . kwargs [ 'thread_id' ] , thread__category = self . category_instance , pk = self . kwargs [ 'post_id' ] )
def predict ( self , timeseriesX , n , m ) : """Calculates the dependent timeseries Y for the given parameters and independent timeseries . ( y = m * x + n ) : param TimeSeries timeseriesX : the independent Timeseries . : param float n : The interception with the x access that has been calculated during reg...
new_entries = [ ] for entry in timeseriesX : predicted_value = m * entry [ 1 ] + n new_entries . append ( [ entry [ 0 ] , predicted_value ] ) return TimeSeries . from_twodim_list ( new_entries )
def update_translation ( self , context_id , translation_id , static_ip = None , remote_ip = None , notes = None ) : """Updates an address translation entry using the given values . : param int context _ id : The id - value representing the context instance . : param dict template : A key - value mapping of tra...
translation = self . get_translation ( context_id , translation_id ) if static_ip is not None : translation [ 'internalIpAddress' ] = static_ip translation . pop ( 'internalIpAddressId' , None ) if remote_ip is not None : translation [ 'customerIpAddress' ] = remote_ip translation . pop ( 'customerIpAdd...
def repack_archive ( archive , archive_new , verbosity = 0 , interactive = True ) : """Repack archive to different file and / or format ."""
util . check_existing_filename ( archive ) util . check_new_filename ( archive_new ) if verbosity >= 0 : util . log_info ( "Repacking %s to %s ..." % ( archive , archive_new ) ) res = _repack_archive ( archive , archive_new , verbosity = verbosity , interactive = interactive ) if verbosity >= 0 : util . log_inf...
def get_extended_summaryf ( self , * args , ** kwargs ) : """Extract the extended summary from a function docstring This function can be used as a decorator to extract the extended summary of a function docstring ( similar to : meth : ` get _ sectionsf ` ) . Parameters ` ` * args ` ` and ` ` * * kwargs ` ` ...
def func ( f ) : doc = f . __doc__ self . get_extended_summary ( doc or '' , * args , ** kwargs ) return f return func
def get_user_home ( self , user ) : """Returns the default URL for a particular user . This method can be used to customize where a user is sent when they log in , etc . By default it returns the value of : meth : ` get _ absolute _ url ` . An alternative function can be supplied to customize this behavior ...
user_home = self . _conf [ 'user_home' ] if user_home : if callable ( user_home ) : return user_home ( user ) elif isinstance ( user_home , six . string_types ) : # Assume we ' ve got a URL if there ' s a slash in it if '/' in user_home : return user_home else : m...
def docgen ( ) : """Build documentation ."""
hitchpylibrarytoolkit . docgen ( _storybook ( { } ) , DIR . project , DIR . key / "story" , DIR . gen )
def status ( self ) : """Collects the instances state and returns a list . . . important : : Molecule assumes all instances were created successfully by Ansible , otherwise Ansible would return an error on create . This may prove to be a bad assumption . However , configuring Molecule ' s driver to match ...
status_list = [ ] for platform in self . _config . platforms . instances : instance_name = platform [ 'name' ] driver_name = self . name provisioner_name = self . _config . provisioner . name scenario_name = self . _config . scenario . name status_list . append ( Status ( instance_name = instance_na...
def outbound_message_filter ( f ) : """Register the decorated function as a service - level outbound message filter . : raise TypeError : if the decorated object is a coroutine function . . seealso : : : class : ` StanzaStream ` for important remarks regarding the use of stanza filters ."""
if asyncio . iscoroutinefunction ( f ) : raise TypeError ( "outbound_message_filter must not be a coroutine function" ) add_handler_spec ( f , HandlerSpec ( ( _apply_outbound_message_filter , ( ) ) ) , ) return f
def _from_dict ( cls , _dict ) : """Initialize a ToneCategory object from a json dictionary ."""
args = { } if 'tones' in _dict : args [ 'tones' ] = [ ToneScore . _from_dict ( x ) for x in ( _dict . get ( 'tones' ) ) ] else : raise ValueError ( 'Required property \'tones\' not present in ToneCategory JSON' ) if 'category_id' in _dict : args [ 'category_id' ] = _dict . get ( 'category_id' ) else : r...
def ResolveHostnameToIP ( host , port ) : """Resolves a hostname to an IP address ."""
ip_addrs = socket . getaddrinfo ( host , port , socket . AF_UNSPEC , 0 , socket . IPPROTO_TCP ) # getaddrinfo returns tuples ( family , socktype , proto , canonname , sockaddr ) . # We are interested in sockaddr which is in turn a tuple # ( address , port ) for IPv4 or ( address , port , flow info , scope id ) # for IP...
def scalar ( name , data , step = None , description = None ) : """Write a scalar summary . Arguments : name : A name for this summary . The summary tag used for TensorBoard will be this name prefixed by any active name scopes . data : A real numeric scalar value , convertible to a ` float32 ` Tensor . st...
summary_metadata = metadata . create_summary_metadata ( display_name = None , description = description ) # TODO ( https : / / github . com / tensorflow / tensorboard / issues / 2109 ) : remove fallback summary_scope = ( getattr ( tf . summary . experimental , 'summary_scope' , None ) or tf . summary . summary_scope ) ...
def _open_sheet ( self ) : """Read the sheet , get value the header , get number columns and rows : return :"""
if self . sheet_name and not self . header : self . _sheet = self . _file . worksheet ( self . sheet_name . title ) self . ncols = self . _sheet . col_count self . nrows = self . _sheet . row_count for i in range ( 1 , self . ncols + 1 ) : self . header = self . header + [ self . _sheet . cell (...
def deploy ( self , environment , target_name , stream_output = None ) : """Return True if deployment was successful"""
try : remote_server_command ( [ "rsync" , "-lrv" , "--safe-links" , "--munge-links" , "--delete" , "--inplace" , "--chmod=ugo=rwX" , "--exclude=.datacats-environment" , "--exclude=.git" , "/project/." , environment . deploy_target + ':' + target_name ] , environment , self , include_project_dir = True , stream_outp...
def _agg_bake ( cls , vertices , color , closed = False ) : """Bake a list of 2D vertices for rendering them as thick line . Each line segment must have its own vertices because of antialias ( this means no vertex sharing between two adjacent line segments ) ."""
n = len ( vertices ) P = np . array ( vertices ) . reshape ( n , 2 ) . astype ( float ) idx = np . arange ( n ) # used to eventually tile the color array dx , dy = P [ 0 ] - P [ - 1 ] d = np . sqrt ( dx * dx + dy * dy ) # If closed , make sure first vertex = last vertex ( + / - epsilon = 1e - 10) if closed and d > 1e-1...
def get_filenames ( root , prefix = u'' , suffix = u'' ) : """Function for listing filenames with given prefix and suffix in the root directory . Parameters prefix : str The prefix of the required files . suffix : str The suffix of the required files Returns list of str List of filenames matching th...
return [ fnm for fnm in os . listdir ( root ) if fnm . startswith ( prefix ) and fnm . endswith ( suffix ) ]
def _init_structures ( self , data , subjects ) : """Initializes data structures for SRM and preprocess the data . Parameters data : list of 2D arrays , element i has shape = [ voxels _ i , samples ] Each element in the list contains the fMRI data of one subject . subjects : int The total number of subjec...
x = [ ] mu = [ ] rho2 = np . zeros ( subjects ) trace_xtx = np . zeros ( subjects ) for subject in range ( subjects ) : mu . append ( np . mean ( data [ subject ] , 1 ) ) rho2 [ subject ] = 1 trace_xtx [ subject ] = np . sum ( data [ subject ] ** 2 ) x . append ( data [ subject ] - mu [ subject ] [ : , ...
def nan_empty ( self , col : str ) : """Fill empty values with NaN values : param col : name of the colum : type col : str : example : ` ` ds . nan _ empty ( " mycol " ) ` `"""
try : self . df [ col ] = self . df [ col ] . replace ( '' , nan ) self . ok ( "Filled empty values with nan in column " + col ) except Exception as e : self . err ( e , "Can not fill empty values with nan" )
def args ( self ) : """Parse args if they have not already been parsed and return the Namespace for args . . . Note : : Accessing args should only be done directly in the App . Returns : ( namespace ) : ArgParser parsed arguments ."""
if not self . _parsed : # only resolve once self . _default_args , unknown = self . parser . parse_known_args ( ) # when running locally retrieve any args from the results . tc file . when running in # platform this is done automatically . self . _results_tc_args ( ) # log unknown arguments only onc...
def _mean_image_subtraction ( image , means , num_channels ) : """Subtracts the given means from each image channel . For example : means = [ 123.68 , 116.779 , 103.939] image = _ mean _ image _ subtraction ( image , means ) Note that the rank of ` image ` must be known . Args : image : a tensor of size...
if image . get_shape ( ) . ndims != 3 : raise ValueError ( 'Input must be of size [height, width, C>0]' ) if len ( means ) != num_channels : raise ValueError ( 'len(means) must match the number of channels' ) mlperf_log . resnet_print ( key = mlperf_log . INPUT_MEAN_SUBTRACTION , value = means ) # We have a 1 -...
def lF_oneway ( * lists ) : """Performs a 1 - way ANOVA , returning an F - value and probability given any number of groups . From Heiman , pp . 394-7. Usage : F _ oneway ( * lists ) where * lists is any number of lists , one per treatment group Returns : F value , one - tailed p - value"""
a = len ( lists ) # ANOVA on ' a ' groups , each in it ' s own list means = [ 0 ] * a vars = [ 0 ] * a ns = [ 0 ] * a alldata = [ ] tmp = [ N . array ( _ ) for _ in lists ] means = [ amean ( _ ) for _ in tmp ] vars = [ avar ( _ ) for _ in tmp ] ns = [ len ( _ ) for _ in lists ] for i in range ( len ( lists ) ) : al...
def parameter_distribution ( self , parameter , bp , bins = 30 , merge = False , merge_method = 'mean' , masked = False ) : """To get the parameter distribution of either a specific base - pair / step or a DNA segment over the MD simulation . parameters parameter : str Name of a base - pair or base - step or ...
if not ( isinstance ( bp , list ) or isinstance ( bp , np . ndarray ) ) : raise AssertionError ( "type %s is not list or np.ndarray" % type ( bp ) ) if ( len ( bp ) > 1 ) and ( merge == False ) : raise AssertionError ( "bp %s contains more than two values, whereas merge=False. Use either one value in bp or merg...
async def find_movie ( self , query ) : """Retrieve movie data by search query . Arguments : query ( : py : class : ` str ` ) : Query to search for . Returns : : py : class : ` list ` : Possible matches ."""
params = OrderedDict ( [ ( 'query' , query ) , ( 'include_adult' , False ) , ] ) url = self . url_builder ( 'search/movie' , { } , params ) data = await self . get_data ( url ) if data is None : return return [ Movie . from_json ( item , self . config [ 'data' ] . get ( 'images' ) ) for item in data . get ( 'result...
def purview_state ( self , direction ) : """The state of the purview when we are computing coefficients in ` ` direction ` ` . For example , if we are computing the cause coefficient of a mechanism in ` ` after _ state ` ` , the direction is ` ` CAUSE ` ` and the ` ` purview _ state ` ` is ` ` before _ stat...
return { Direction . CAUSE : self . before_state , Direction . EFFECT : self . after_state } [ direction ]
def _get_instance_repo ( self , namespace ) : """Returns the instance repository for the specified CIM namespace within the mock repository . This is the original instance variable , so any modifications will change the mock repository . Validates that the namespace exists in the mock repository . If the in...
self . _validate_namespace ( namespace ) if namespace not in self . instances : self . instances [ namespace ] = [ ] return self . instances [ namespace ]
def mul ( x , y , context = None ) : """Return ` ` x ` ` times ` ` y ` ` ."""
return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_mul , ( BigFloat . _implicit_convert ( x ) , BigFloat . _implicit_convert ( y ) , ) , context , )
def checkArgs ( args ) : """Checks the arguments and options . : param args : a object containing the options of the program . : type args : argparse . Namespace : returns : ` ` True ` ` if everything was OK . If there is a problem with an option , an exception is raised using the : py : class : ` Program...
# Check if we have the tped and the tfam files required_file_extensions = { ".tfam" , ".tped" } if args . is_bfile : required_file_extensions = { ".bed" , ".bim" , ".fam" } for fileName in [ args . ifile + i for i in required_file_extensions ] : if not os . path . isfile ( fileName ) : msg = "{}: no suc...
def disable_component ( self , component ) : """Force a component to be disabled . : param component : can be a class or an instance ."""
if not isinstance ( component , type ) : component = component . __class__ self . enabled [ component ] = False self . components [ component ] = None
def get_ancestors ( self , limit : int , header : BlockHeader ) -> Tuple [ BaseBlock , ... ] : """Return ` limit ` number of ancestor blocks from the current canonical head ."""
ancestor_count = min ( header . block_number , limit ) # We construct a temporary block object vm_class = self . get_vm_class_for_block_number ( header . block_number ) block_class = vm_class . get_block_class ( ) block = block_class ( header = header , uncles = [ ] ) ancestor_generator = iterate ( compose ( self . get...
def read ( self , size = - 1 ) : """Read up to size uncompressed bytes from the file . If size is negative or omitted , read until EOF is reached . Returns b " " if the file is already at EOF ."""
self . _check_can_read ( ) if size is None : # This is not needed on Python 3 where the comparison to zeo # will fail with a TypeError . raise TypeError ( "Read size should be an integer, not None" ) if self . _mode == _MODE_READ_EOF or size == 0 : return b"" elif size < 0 : return self . _read_all ( ) else...
def hyperparameters ( self ) : """Return hyperparameters used by your custom TensorFlow code during model training ."""
hyperparameters = super ( RLEstimator , self ) . hyperparameters ( ) additional_hyperparameters = { SAGEMAKER_OUTPUT_LOCATION : self . output_path , # TODO : can be applied to all other estimators SAGEMAKER_ESTIMATOR : SAGEMAKER_ESTIMATOR_VALUE } hyperparameters . update ( Framework . _json_encode_hyperparameters ( add...
def wrap_udf ( hdfs_file , inputs , output , so_symbol , name = None ) : """Creates a callable scalar function object . Must be created in Impala to be used Parameters hdfs _ file : . so file that contains relevant UDF inputs : list of strings or sig . TypeSignature Input types to UDF output : string ...
func = ImpalaUDF ( inputs , output , so_symbol , name = name , lib_path = hdfs_file ) return func
def set_tag ( self , tag ) : '''Sets the tag . If the Entity belongs to the world it will check for tag conflicts .'''
if self . _world : if self . _world . get_entity_by_tag ( tag ) : raise NonUniqueTagError ( tag ) self . _tag = tag
def pov ( self , color : chess . Color ) -> "Score" : """Get the score from the point of view of the given * color * ."""
return self . relative if self . turn == color else - self . relative
def availability_sets_list_available_sizes ( name , resource_group , ** kwargs ) : # pylint : disable = invalid - name '''. . versionadded : : 2019.2.0 List all available virtual machine sizes that can be used to to create a new virtual machine in an existing availability set . : param name : The availability...
result = { } compconn = __utils__ [ 'azurearm.get_client' ] ( 'compute' , ** kwargs ) try : sizes = __utils__ [ 'azurearm.paged_object_to_list' ] ( compconn . availability_sets . list_available_sizes ( resource_group_name = resource_group , availability_set_name = name ) ) for size in sizes : result [ s...
def exists_orm ( session : Session , ormclass : DeclarativeMeta , * criteria : Any ) -> bool : """Detects whether a database record exists for the specified ` ` ormclass ` ` and ` ` criteria ` ` . Example usage : . . code - block : : python bool _ exists = exists _ orm ( session , MyClass , MyClass . myfiel...
# http : / / docs . sqlalchemy . org / en / latest / orm / query . html q = session . query ( ormclass ) for criterion in criteria : q = q . filter ( criterion ) exists_clause = q . exists ( ) return bool_from_exists_clause ( session = session , exists_clause = exists_clause )
def add_user_invitation ( self , ** kwargs ) : """Add a UserInvitation object , with properties specified in ` ` * * kwargs ` ` ."""
user_invitation = self . UserInvitationClass ( ** kwargs ) self . db_adapter . add_object ( user_invitation ) return user_invitation
async def close ( self ) -> None : """Complete queued queries / cursors and close the connection ."""
await self . _execute ( self . _conn . close ) self . _running = False self . _connection = None
def _convert ( self , value ) : """Returns a PasswordHash from the given string . PasswordHash instances or None values will return unchanged . Strings will be hashed and the resulting PasswordHash returned . Any other input will result in a TypeError ."""
if isinstance ( value , PasswordHash ) : return value elif isinstance ( value , str ) : value = value . encode ( 'utf-8' ) return PasswordHash . new ( value , self . rounds ) elif value is not None : raise TypeError ( 'Cannot convert {} to a PasswordHash' . format ( type ( value ) ) )
def takeexactly ( iterable , size ) : """Yield blocks from ` iterable ` until exactly len ( size ) have been returned . Args : iterable ( iterable ) : Any iterable that yields sliceable objects that have length . size ( int ) : How much data to consume Yields : blocks from ` iterable ` such that sum (...
total = 0 for block in iterable : n = min ( len ( block ) , size - total ) block = block [ : n ] if block : yield block total += len ( block ) if total >= size : break if total < size : raise ValueError ( 'not enough data (yielded {} of {})' ) # sanity check ; this should never h...
def tree ( ) : """Return a tree of tuples representing the logger layout . Each tuple looks like ` ` ( ' logger - name ' , < Logger > , [ . . . ] ) ` ` where the third element is a list of zero or more child tuples that share the same layout ."""
root = ( '' , logging . root , [ ] ) nodes = { } items = list ( logging . root . manager . loggerDict . items ( ) ) # for Python 2 and 3 items . sort ( ) for name , logger in items : nodes [ name ] = node = ( name , logger , [ ] ) i = name . rfind ( '.' , 0 , len ( name ) - 1 ) # same formula used in ` logg...
def update_remote_ids ( self , remote_folder ) : """Set remote id based on remote _ folder and check children against this folder ' s children . : param remote _ folder : RemoteFolder to compare against"""
self . remote_id = remote_folder . id _update_remote_children ( remote_folder , self . children )
def begin_span ( self , name , span_type , context = None , leaf = False , tags = None ) : """Begin a new span : param name : name of the span : param span _ type : type of the span : param context : a context dict : param leaf : True if this is a leaf span : param tags : a flat string / string dict of ta...
return self . _begin_span ( name , span_type , context = context , leaf = leaf , tags = tags , parent_span_id = None )
def do_create ( marfile , files , compress , productversion = None , channel = None , signing_key = None , signing_algorithm = None ) : """Create a new MAR file ."""
with open ( marfile , 'w+b' ) as f : with MarWriter ( f , productversion = productversion , channel = channel , signing_key = signing_key , signing_algorithm = signing_algorithm , ) as m : for f in files : m . add ( f , compress = compress )
def evaluate_service_changes ( services , envs , repo_root , func ) : """Given a dict of services , and a list of environments , apply the diff function to evaluate the differences between the target environments and the rendered templates . Sub - services ( names with ' . ' in them ) are skipped ."""
for service_name , service in services . iteritems ( ) : for env_category in service [ 'environments' ] : if env_category not in get_env_categories ( envs ) : logger . debug ( 'Skipping not-included environment `%s` for service `%s`' , env_category , service_name ) continue e...
def compile ( self , node , * args , ** kwargs ) : """Parse a WhereNode to a LDAP filter string ."""
if isinstance ( node , WhereNode ) : return where_node_as_ldap ( node , self , self . connection ) return super ( SQLCompiler , self ) . compile ( node , * args , ** kwargs )
def parse_on_event ( self , node ) : """Parses < OnEvent > @ param node : Node containing the < OnEvent > element @ type node : xml . etree . Element"""
try : port = node . lattrib [ 'port' ] except : self . raise_error ( '<OnEvent> must specify a port.' ) event_handler = OnEvent ( port ) self . current_regime . add_event_handler ( event_handler ) self . current_event_handler = event_handler self . process_nested_tags ( node ) self . current_event_handler = Non...
def _action_remove ( self , ids ) : """Remove IDs from the group Parameters ids : { list , set , tuple , generator } of str The IDs to remove Returns list of dict The details of the removed jobs"""
return self . _action_get ( ( self . unlisten_to_node ( id_ ) for id_ in ids ) )
def get_qr ( self , filename = None ) : """Get pairing QR code from client"""
if "Click to reload QR code" in self . driver . page_source : self . reload_qr ( ) qr = self . driver . find_element_by_css_selector ( self . _SELECTORS [ 'qrCode' ] ) if filename is None : fd , fn_png = tempfile . mkstemp ( prefix = self . username , suffix = '.png' ) else : fd = os . open ( filename , os ...
def send_email_message ( self , recipient , subject , html_message , text_message , sender_email , sender_name ) : """Send email message via Flask - Mail . Args : recipient : Email address or tuple of ( Name , Email - address ) . subject : Subject line . html _ message : The message body in HTML . text _ ...
# Construct sender from sender _ name and sender _ email sender = '"%s" <%s>' % ( sender_name , sender_email ) if sender_name else sender_email # Send email via SMTP except when we ' re testing if not current_app . testing : # pragma : no cover try : # Prepare email message from flask_mail import Message ...
def pack ( self , value = None ) : """Pack the struct in a binary representation . Merge some fields to ensure correct packing . Returns : bytes : Binary representation of this instance ."""
# Set the correct IHL based on options size if self . options : self . ihl += int ( len ( self . options ) / 4 ) # Set the correct packet length based on header length and data self . length = int ( self . ihl * 4 + len ( self . data ) ) self . _version_ihl = self . version << 4 | self . ihl self . _dscp_ecn = self...
def DbPutClassProperty ( self , argin ) : """Create / Update class property ( ies ) : param argin : Str [ 0 ] = Tango class name Str [ 1 ] = Property number Str [ 2 ] = Property name Str [ 3 ] = Property value number Str [ 4 ] = Property value 1 Str [ n ] = Property value n : type : tango . DevVarStri...
self . _log . debug ( "In DbPutClassProperty()" ) class_name = argin [ 0 ] nb_properties = int ( argin [ 1 ] ) self . db . put_class_property ( class_name , nb_properties , argin [ 2 : ] )
def right_click ( self , x , y , n = 1 , pre_dl = None , post_dl = None ) : """Right click at ` ` ( x , y ) ` ` on screen for ` ` n ` ` times . at begin . * * 中文文档 * * 在屏幕的 ` ` ( x , y ) ` ` 坐标处右键单击 ` ` n ` ` 次 。"""
self . delay ( pre_dl ) self . m . click ( x , y , 2 , n ) self . delay ( post_dl )
async def exit_rescue_mode ( self , wait : bool = False , wait_interval : int = 5 ) : """Exit rescue mode . : param wait : If specified , wait until the deploy is complete . : param wait _ interval : How often to poll , defaults to 5 seconds"""
try : self . _data = await self . _handler . exit_rescue_mode ( system_id = self . system_id ) except CallError as error : if error . status == HTTPStatus . FORBIDDEN : message = "Not allowed to exit rescue mode." raise OperationNotAllowed ( message ) from error else : raise if not w...
def get_cands_uri ( field , ccd , version = 'p' , ext = 'measure3.cands.astrom' , prefix = None , block = None ) : """return the nominal URI for a candidate file . @ param field : the OSSOS field name @ param ccd : which CCD are the candidates on @ param version : either the ' p ' , or ' s ' ( scrambled ) can...
if prefix is None : prefix = "" if len ( prefix ) > 0 : prefix += "_" if len ( field ) > 0 : field += "_" if ext is None : ext = "" if len ( ext ) > 0 and ext [ 0 ] != "." : ext = ".{}" . format ( ext ) measure3_dir = MEASURE3 if block is not None : measure3_dir + "/{}" . format ( block ) return...
def accept ( self ) : """accept ( ) - > ( socket object , address info ) Wait for an incoming connection . Return a new socket representing the connection , and the address of the client . For IP sockets , the address info is a pair ( hostaddr , port ) ."""
fd , addr = self . _accept ( ) sock = socket ( self . family , self . type , self . proto , fileno = fd ) # Issue # 7995 : if no default timeout is set and the listening # socket had a ( non - zero ) timeout , force the new socket in blocking # mode to override platform - specific socket flags inheritance . if getdefau...
def version ( self ) : """Returns the node ' s RPC version : raises : : py : exc : ` nano . rpc . RPCException ` > > > rpc . version ( ) " rpc _ version " : 1, " store _ version " : 10, " node _ vendor " : " RaiBlocks 9.0" """
resp = self . call ( 'version' ) for key in ( 'rpc_version' , 'store_version' ) : resp [ key ] = int ( resp [ key ] ) return resp
def _find_relations ( self ) : """Find all relevant relation elements and return them in a list ."""
# Get all extractions extractions = list ( self . tree . execute ( "$.extractions[(@.@type is 'Extraction')]" ) ) # Get relations from extractions relations = [ ] for e in extractions : label_set = set ( e . get ( 'labels' , [ ] ) ) # If this is a DirectedRelation if 'DirectedRelation' in label_set : ...
def read_packet ( self , size = MTU ) : """return a single packet read from the file bytes , ( sec , # timestamp seconds usec , # timestamp microseconds wirelen ) # actual length of packet returns None when no more packets are available"""
hdr = self . f . read ( 16 ) if len ( hdr ) < 16 : return None sec , usec , caplen , wirelen = struct . unpack ( self . endian + "IIII" , hdr ) s = self . f . read ( caplen ) [ : MTU ] return s , 0 , ( sec , usec , wirelen )
def IntraField ( config = { } ) : """Intra field interlace to sequential converter . This uses a vertical filter with an aperture of 8 lines , generated by : py : class : ` ~ pyctools . components . interp . filtergenerator . FilterGenerator ` . The aperture ( and other parameters ) can be adjusted after th...
return Compound ( config = config , deint = SimpleDeinterlace ( ) , interp = Resize ( ) , filgen = FilterGenerator ( yaperture = 8 , ycut = 50 ) , gain = Arithmetic ( func = 'data * pt_float(2)' ) , linkages = { ( 'self' , 'input' ) : [ ( 'deint' , 'input' ) ] , ( 'deint' , 'output' ) : [ ( 'interp' , 'input' ) ] , ( '...
def copy_root_log_to_file ( filename : str , fmt : str = LOG_FORMAT , datefmt : str = LOG_DATEFMT ) -> None : """Copy all currently configured logs to the specified file . Should ONLY be called from the ` ` if _ _ name _ _ = = ' main ' ` ` script ; see https : / / docs . python . org / 3.4 / howto / logging . h...
fh = logging . FileHandler ( filename ) # default file mode is ' a ' for append formatter = logging . Formatter ( fmt = fmt , datefmt = datefmt ) fh . setFormatter ( formatter ) apply_handler_to_root_log ( fh )
def delete_forwarding_address ( payment_id , coin_symbol = 'btc' , api_key = None ) : '''Delete a forwarding address on a specific blockchain , using its payment id'''
assert payment_id , 'payment_id required' assert is_valid_coin_symbol ( coin_symbol ) assert api_key , 'api_key required' params = { 'token' : api_key } url = make_url ( ** dict ( payments = payment_id ) ) r = requests . delete ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) return get_valid_js...
def _move_bee ( self , bee , new_values ) : '''Moves a bee to a new position if new fitness score is better than the bee ' s current fitness score Args : bee ( EmployerBee ) : bee to move new _ values ( tuple ) : ( new score , new values , new fitness function return value )'''
score = np . nan_to_num ( new_values [ 0 ] ) if bee . score > score : bee . failed_trials += 1 else : bee . values = new_values [ 1 ] bee . score = score bee . error = new_values [ 2 ] bee . failed_trials = 0 self . _logger . log ( 'debug' , 'Bee assigned to new merged position' )
def plot_eval_results ( eval_results , metric = None , xaxislabel = None , yaxislabel = None , title = None , title_fontsize = 'x-large' , axes_title_fontsize = 'large' , show_metric_direction = True , metric_direction_font_size = 'large' , subplots_opts = None , subplots_adjust_opts = None , figsize = 'auto' , ** fig_...
if type ( eval_results ) not in ( list , tuple ) or not eval_results : raise ValueError ( '`eval_results` must be a list or tuple with at least one element' ) if type ( eval_results [ 0 ] ) not in ( list , tuple ) or len ( eval_results [ 0 ] ) != 2 : raise ValueError ( '`eval_results` must be a list or tuple co...
def _get_call_names_helper ( node ) : """Recursively finds all function names ."""
if isinstance ( node , ast . Name ) : if node . id not in BLACK_LISTED_CALL_NAMES : yield node . id elif isinstance ( node , ast . Subscript ) : yield from _get_call_names_helper ( node . value ) elif isinstance ( node , ast . Str ) : yield node . s elif isinstance ( node , ast . Attribute ) : y...
def specimens_results_magic ( infile = 'pmag_specimens.txt' , measfile = 'magic_measurements.txt' , sampfile = 'er_samples.txt' , sitefile = 'er_sites.txt' , agefile = 'er_ages.txt' , specout = 'er_specimens.txt' , sampout = 'pmag_samples.txt' , siteout = 'pmag_sites.txt' , resout = 'pmag_results.txt' , critout = 'pmag...
# initialize some variables plotsites = False # cannot use draw _ figs from within ipmag Comps = [ ] # list of components version_num = pmag . get_version ( ) args = sys . argv model_lat_file = "" Dcrit , Icrit , nocrit = 0 , 0 , 0 corrections = [ ] nocorrection = [ 'DA-NL' , 'DA-AC' , 'DA-CR' ] # do some data adjustme...
def _from_signer_and_info ( cls , signer , info , ** kwargs ) : """Creates a Credentials instance from a signer and service account info . Args : signer ( google . auth . crypt . Signer ) : The signer used to sign JWTs . info ( Mapping [ str , str ] ) : The service account info . kwargs : Additional argum...
return cls ( signer , service_account_email = info [ 'client_email' ] , token_uri = info [ 'token_uri' ] , project_id = info . get ( 'project_id' ) , ** kwargs )
def handle_django_settings ( filename ) : '''Attempts to load a Django project and get package dependencies from settings . Tested using Django 1.4 and 1.8 . Not sure if some nuances are missed in the other versions .'''
old_sys_path = sys . path [ : ] dirpath = os . path . dirname ( filename ) project = os . path . basename ( dirpath ) cwd = os . getcwd ( ) project_path = os . path . normpath ( os . path . join ( dirpath , '..' ) ) if project_path not in sys . path : sys . path . insert ( 0 , project_path ) os . chdir ( project_pa...
def url_tibiadata ( self ) : """: class : ` str ` : The URL to the TibiaData . com page of the house ."""
return self . get_url_tibiadata ( self . id , self . world ) if self . id and self . world else None
def find_usedby ( self , depslock_file_path , property_validate = True ) : """Find all dependencies by package : param depslock _ file _ path : : param property _ validate : for ` root ` packages we need check property , bad if we find packages from ` lock ` file , we can skip validate part : return :"""
if depslock_file_path is None : self . _raw = [ self . _params ] self . _raw [ 0 ] [ 'repo' ] = None self . _raw [ 0 ] [ 'server' ] = None else : self . _raw = [ x for x in self . _downloader . common_parser . iter_packages_params ( depslock_file_path ) ] self . packages = self . _downloader . get_usedb...
def rms ( signal , fs ) : """Returns the root mean square ( RMS ) of the given * signal * : param signal : a vector of electric potential : type signal : numpy . ndarray : param fs : samplerate of the signal ( Hz ) : type fs : int : returns : float - - the RMS value of the signal"""
# if a signal contains a some silence , taking the RMS of the whole # signal will be calculated as less loud as a signal without a silent # period . I don ' t like this , so I am going to chunk the signals , and # take the value of the most intense chunk chunk_time = 0.001 # 1 ms chunk chunk_samps = int ( chunk_time * ...
def get_decorated_names ( path , decorator_module , decorator_name ) : '''Get the name of fumctions or methods decorated with the specified decorator . If a method , the name will be as class _ name . method _ name . Args : path : The path to the module . decorator _ module : The name of the module defining...
# Read the source with open ( path ) as f : module_source = f . read ( ) expression = '\s*@(?:{}\.)?{}[\s\S]+?(?:instance_creator\s*=\s*([\w.]+)[\s\S]+?)?\s*def\s+(\w+)\s*\(\s*(self)?' . format ( decorator_module , decorator_name ) methods = re . compile ( expression ) . findall ( module_source ) decorateds = [ x [...
def del_password ( name , root = None ) : '''. . versionadded : : 2014.7.0 Delete the password from name user name User to delete root Directory to chroot into CLI Example : . . code - block : : bash salt ' * ' shadow . del _ password username'''
cmd = [ 'passwd' ] if root is not None : cmd . extend ( ( '-R' , root ) ) cmd . extend ( ( '-d' , name ) ) __salt__ [ 'cmd.run' ] ( cmd , python_shell = False , output_loglevel = 'quiet' ) uinfo = info ( name , root = root ) return not uinfo [ 'passwd' ] and uinfo [ 'name' ] == name
def scencd ( sc , sclkch , MXPART = None ) : """Encode character representation of spacecraft clock time into a double precision number . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / scencd _ c . html : param sc : NAIF spacecraft identification code . : type sc : int : p...
sc = ctypes . c_int ( sc ) sclkch = stypes . stringToCharP ( sclkch ) sclkdp = ctypes . c_double ( ) libspice . scencd_c ( sc , sclkch , ctypes . byref ( sclkdp ) ) return sclkdp . value
def init_db ( drop_all = False , bind = engine ) : """Initialize the database , optionally dropping existing tables ."""
try : if drop_all : Base . metadata . drop_all ( bind = bind ) Base . metadata . create_all ( bind = bind ) except OperationalError as err : msg = 'password authentication failed for user "dallinger"' if msg in err . message : sys . stderr . write ( db_user_warning ) raise return ses...
def submit_error ( self , description , extra = None , default_message = None ) : """Send an error to bugzscout . Sends a request to the fogbugz URL for this instance . If a case exists with the * * same * * description , a new occurrence will be added to that case . It is advisable to remove personal info fr...
req_data = { 'ScoutUserName' : self . user , 'ScoutProject' : self . project , 'ScoutArea' : self . area , # When this matches , cases are grouped together . 'Description' : description , 'Extra' : extra , # 1 forces a new bug to be created . 'ForceNewBug' : 0 , 'ScoutDefaultMessage' : default_message , # 0 sends XML r...
def get_osid_object_mdata ( ) : """Return default mdata map for OsidObject"""
return { 'display_name' : { 'element_label' : { 'text' : 'Display Name' , 'languageTypeId' : str ( DEFAULT_LANGUAGE_TYPE ) , 'scriptTypeId' : str ( DEFAULT_SCRIPT_TYPE ) , 'formatTypeId' : str ( DEFAULT_FORMAT_TYPE ) , } , 'instructions' : { 'text' : 'Required, 255 character maximum' , 'languageTypeId' : str ( DEFAULT_...
def _safe_exit ( start , output ) : """exit without breaking pipes"""
try : sys . stdout . write ( output ) sys . stdout . flush ( ) except TypeError : # python3 sys . stdout . write ( str ( output , 'utf-8' ) ) sys . stdout . flush ( ) except IOError : pass seconds = time . time ( ) - start print ( "\n\n%5.3f seconds" % ( seconds ) , file = sys . stderr )
def circ_corrcl ( x , y , tail = 'two-sided' ) : """Correlation coefficient between one circular and one linear variable random variables . Parameters x : np . array First circular variable ( expressed in radians ) y : np . array Second circular variable ( linear ) tail : string Specify whether to r...
from scipy . stats import pearsonr , chi2 x = np . asarray ( x ) y = np . asarray ( y ) # Check size if x . size != y . size : raise ValueError ( 'x and y must have the same length.' ) # Remove NA x , y = remove_na ( x , y , paired = True ) n = x . size # Compute correlation coefficent for sin and cos independently...
def default ( self , value ) : """Convert mongo . ObjectId ."""
if isinstance ( value , ObjectId ) : return str ( value ) return super ( ElasticJSONSerializer , self ) . default ( value )
def fprime ( self , w , * args ) : """Return the derivatives of the cost function for predictions . Args : w ( array of float ) : weight vectors such that : w [ : - h1 ] - - weights between the input and h layers w [ - h1 : ] - - weights between the h and output layers args : features ( args [ 0 ] ) and t...
x0 = args [ 0 ] x1 = args [ 1 ] n0 = x0 . shape [ 0 ] n1 = x1 . shape [ 0 ] # n - - number of pairs to evaluate n = max ( n0 , n1 ) * 10 idx0 = np . random . choice ( range ( n0 ) , size = n ) idx1 = np . random . choice ( range ( n1 ) , size = n ) # b - - bias for the input and h layers b = np . ones ( ( n , 1 ) ) i1 ...
def validate ( self , value , add_comments = False , schema_name = "map" ) : """verbose - also return the jsonschema error details"""
validator = self . get_schema_validator ( schema_name ) error_messages = [ ] if isinstance ( value , list ) : for d in value : error_messages += self . _validate ( d , validator , add_comments , schema_name ) else : error_messages = self . _validate ( value , validator , add_comments , schema_name ) ret...
def AttachUserList ( client , ad_group_id , user_list_id ) : """Links the provided ad group and user list . Args : client : an AdWordsClient instance . ad _ group _ id : an int ad group ID . user _ list _ id : an int user list ID . Returns : The ad group criterion that was successfully created ."""
ad_group_criterion_service = client . GetService ( 'AdGroupCriterionService' , 'v201809' ) user_list = { 'xsi_type' : 'CriterionUserList' , 'userListId' : user_list_id } ad_group_criterion = { 'xsi_type' : 'BiddableAdGroupCriterion' , 'criterion' : user_list , 'adGroupId' : ad_group_id } operations = [ { 'operator' : '...
def read_data ( self , size ) : """Receive data from the device . If the read fails for any reason , an : obj : ` IOError ` exception is raised . : param size : the number of bytes to read . : type size : int : return : the data received . : rtype : list ( int )"""
result = self . dev . bulkRead ( 0x81 , size , timeout = 1200 ) if not result or len ( result ) < size : raise IOError ( 'pywws.device_libusb1.USBDevice.read_data failed' ) # Python2 libusb1 version 1.5 and earlier returns a string if not isinstance ( result [ 0 ] , int ) : result = map ( ord , result ) return ...
def database_rename ( object_id , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / database - xxxx / rename API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Name # API - method % 3A - % 2Fclass - xxxx % 2Frename"""
return DXHTTPRequest ( '/%s/rename' % object_id , input_params , always_retry = always_retry , ** kwargs )
def computeStrongestPaths ( self , profile , pairwisePreferences ) : """Returns a two - dimensional dictionary that associates every pair of candidates , cand1 and cand2 , with the strongest path from cand1 to cand2. : ivar Profile profile : A Profile object that represents an election profile . : ivar dict <...
cands = profile . candMap . keys ( ) numCands = len ( cands ) # Initialize the two - dimensional dictionary that will hold our strongest paths . strongestPaths = dict ( ) for cand in cands : strongestPaths [ cand ] = dict ( ) for i in range ( 1 , numCands + 1 ) : for j in range ( 1 , numCands + 1 ) : if...
def initialize_plugin ( self ) : """Initialize the plugin"""
# Generate a list of blacklisted packages from the configuration and # store it into self . blacklist _ package _ names attribute so this # operation doesn ' t end up in the fastpath . if not self . whitelist_package_names : self . whitelist_package_names = self . _determine_unfiltered_package_names ( ) logger ...
def get ( self ) : """Constructs a ExecutionContextContext : returns : twilio . rest . studio . v1 . flow . execution . execution _ context . ExecutionContextContext : rtype : twilio . rest . studio . v1 . flow . execution . execution _ context . ExecutionContextContext"""
return ExecutionContextContext ( self . _version , flow_sid = self . _solution [ 'flow_sid' ] , execution_sid = self . _solution [ 'execution_sid' ] , )
def gc3 ( args ) : """% prog gc3 ksfile cdsfile [ cdsfile2 ] - o newksfile Filter the Ks results to remove high GC3 genes . High GC3 genes are problematic in Ks calculation - see Tang et al . 2010 PNAS . Specifically , the two calculation methods produce drastically different results for these pairs . There...
p = OptionParser ( gc3 . __doc__ ) p . add_option ( "--plot" , default = False , action = "store_true" , help = "Also plot the GC3 histogram [default: %default]" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) outfile = opts . outfile plot = opts . plot if not 1 < len ( args ) < 4 : sys . exit ( not p ....
def convert_to_categorical ( df ) : """Run a heuristic on the columns of the dataframe to determine whether it contains categorical values if the heuristic decides it ' s categorical then the type of the column is changed Args : df ( dataframe ) : The dataframe to check for categorical data"""
might_be_categorical = df . select_dtypes ( include = [ object ] ) . columns . tolist ( ) for column in might_be_categorical : if df [ column ] . nunique ( ) < 20 : # Convert the column print ( 'Changing column {:s} to category...' . format ( column ) ) df [ column ] = pd . Categorical ( df [ column...
def remove_connection ( self , interface1 , interface2 ) : """Remove a connection between two interfaces"""
uri = "api/interface/disconnect/%s/%s/" % ( interface1 , interface2 ) return self . delete ( uri )
def match_non_rule_patterns ( fixed_text , cur = 0 ) : """Matches given text at cursor position with non rule patterns Returns a dictionary of three elements : - " matched " - Bool : depending on if match found - " found " - string / None : Value of matched pattern ' s ' find ' key or none - " replaced " : ...
pattern = exact_find_in_pattern ( fixed_text , cur , NON_RULE_PATTERNS ) if len ( pattern ) > 0 : return { "matched" : True , "found" : pattern [ 0 ] [ 'find' ] , "replaced" : pattern [ 0 ] [ 'replace' ] } else : return { "matched" : False , "found" : None , "replaced" : fixed_text [ cur ] }