signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def sweHouses ( jd , lat , lon , hsys ) : """Returns lists of houses and angles ."""
hsys = SWE_HOUSESYS [ hsys ] hlist , ascmc = swisseph . houses ( jd , lat , lon , hsys ) # Add first house to the end of ' hlist ' so that we # can compute house sizes with an iterator hlist += ( hlist [ 0 ] , ) houses = [ { 'id' : const . LIST_HOUSES [ i ] , 'lon' : hlist [ i ] , 'size' : angle . distance ( hlist [ i ...
def query ( self , coords , ** kwargs ) : """Returns E ( B - V ) , in mags , at the specified location ( s ) on the sky . Args : coords ( : obj : ` astropy . coordinates . SkyCoord ` ) : The coordinates to query . Returns : A float array of the reddening , in magnitudes of E ( B - V ) , at the selected co...
return super ( Lenz2017Query , self ) . query ( coords , ** kwargs )
def start ( ** kwargs ) : """Starts new context using provided configuration . Raises RuntimeConfigError if a context is already active ."""
if CORE_MANAGER . started : raise RuntimeConfigError ( 'Current context has to be stopped to start ' 'a new context.' ) try : waiter = kwargs . pop ( 'waiter' ) except KeyError : waiter = hub . Event ( ) common_config = CommonConf ( ** kwargs ) hub . spawn ( CORE_MANAGER . start , * [ ] , ** { 'common_conf'...
def GenerateDateTripsDeparturesList ( self , date_start , date_end ) : """Return a list of ( date object , number of trips , number of departures ) . The list is generated for dates in the range [ date _ start , date _ end ) . Args : date _ start : The first date in the list , a date object date _ end : The...
service_id_to_trips = defaultdict ( lambda : 0 ) service_id_to_departures = defaultdict ( lambda : 0 ) for trip in self . GetTripList ( ) : headway_start_times = trip . GetFrequencyStartTimes ( ) if headway_start_times : trip_runs = len ( headway_start_times ) else : trip_runs = 1 servic...
def generate_matching_datasets ( self , data_slug ) : """Return datasets that match data _ slug ( tag ) ."""
tag = Tag . objects . filter ( slug = data_slug ) try : return tag [ 0 ] . dataset_set . all ( ) . order_by ( '-uploaded_by' ) except IndexError : return None
def _init_values ( self , context = None ) : """Retrieve field values from the server . May be used to restore the original values in the purpose to cancel all changes made ."""
if context is None : context = self . env . context # Get basic fields ( no relational ones ) basic_fields = [ ] for field_name in self . _columns : field = self . _columns [ field_name ] if not getattr ( field , 'relation' , False ) : basic_fields . append ( field_name ) # Fetch values from the ser...
def config_mode ( self , config_command = "config term" , pattern = "" ) : """Enter into configuration mode on remote device . Cisco IOS devices abbreviate the prompt at 20 chars in config mode"""
if not pattern : pattern = re . escape ( self . base_prompt [ : 16 ] ) return super ( CiscoBaseConnection , self ) . config_mode ( config_command = config_command , pattern = pattern )
def cutR_seq ( seq , cutR , max_palindrome ) : """Cut genomic sequence from the right . Parameters seq : str Nucleotide sequence to be cut from the right cutR : int cutR - max _ palindrome = how many nucleotides to cut from the right . Negative cutR implies complementary palindromic insertions . max _...
complement_dict = { 'A' : 'T' , 'C' : 'G' , 'G' : 'C' , 'T' : 'A' } # can include lower case if wanted if cutR < max_palindrome : seq = seq + '' . join ( [ complement_dict [ nt ] for nt in seq [ cutR - max_palindrome : ] ] [ : : - 1 ] ) # reverse complement palindrome insertions else : seq = seq [ : len ( s...
def parser_set ( self , args ) : """Set config from an : py : class : ` argparse . Namespace ` object . Call this method with the return value from : py : meth : ` ~ argparse . ArgumentParser . parse _ args ` . : param argparse . Namespace args : The populated : py : class : ` argparse . Namespace ` object ...
for key , value in vars ( args ) . items ( ) : self . _parser_update ( key , value )
def getLocalParameters ( self ) : """Retrieve the ICE parameters of the ICE gatherer . : rtype : RTCIceParameters"""
return RTCIceParameters ( usernameFragment = self . _connection . local_username , password = self . _connection . local_password )
def possible_moves ( self , position ) : """Returns all possible rook moves . : type : position : Board : rtype : list"""
for move in itertools . chain ( * [ self . moves_in_direction ( fn , position ) for fn in self . cross_fn ] ) : yield move
def from_other ( cls , ori , ** kwargs ) : """Creates a new instance with an existing one as a template . Parameters ori : SymbolicSys instance \\ * \\ * kwargs : Keyword arguments used to create the new instance . Returns A new instance of the class ."""
for k in cls . _attrs_to_copy + ( 'params' , 'roots' , 'init_indep' , 'init_dep' ) : if k not in kwargs : val = getattr ( ori , k ) if val is not None : kwargs [ k ] = val if 'lower_bounds' not in kwargs and getattr ( ori , 'lower_bounds' ) is not None : kwargs [ 'lower_bounds' ] = o...
def getPeerStats ( self ) : """Get NTP Peer Stats for localhost by querying local NTP Server . @ return : Dictionary of NTP stats converted to seconds ."""
info_dict = { } output = util . exec_command ( [ ntpqCmd , '-n' , '-c' , 'peers' ] ) for line in output . splitlines ( ) : mobj = re . match ( '\*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+' , line ) if mobj : info_dict [ 'ip' ] = mobj . group ( 1 ) cols = line . split ( ) info_dict [ 'strat...
def filter ( self , data ) : """Filters the dataset ( s ) . When providing a list , this can be used to create compatible train / test sets , since the filter only gets initialized with the first dataset and all subsequent datasets get transformed using the same setup . NB : inputformat ( Instances ) must hav...
if isinstance ( data , list ) : result = [ ] for d in data : result . append ( Instances ( javabridge . static_call ( "Lweka/filters/Filter;" , "useFilter" , "(Lweka/core/Instances;Lweka/filters/Filter;)Lweka/core/Instances;" , d . jobject , self . jobject ) ) ) return result else : return Insta...
def _set_version ( ) : """Set check50 _ _ version _ _"""
global __version__ from pkg_resources import get_distribution , DistributionNotFound import os # https : / / stackoverflow . com / questions / 17583443 / what - is - the - correct - way - to - share - package - version - with - setup - py - and - the - package try : dist = get_distribution ( "check50" ) # Norma...
def visit_BoolOp ( self , node ) : """Merge BoolOp operand type . BoolOp are " and " and " or " and may return any of these results so all operands should have the combinable type ."""
# Visit subnodes self . generic_visit ( node ) # Merge all operands types . [ self . combine ( node , value ) for value in node . values ]
def set_monitor_callback ( self , callback , monitor_all = False ) : """Install callback for monitor . Parameters callback : function Takes a string and an NDArrayHandle . monitor _ all : bool , default False If true , monitor both input and output , otherwise monitor output only . Examples > > > def ...
cb_type = ctypes . CFUNCTYPE ( None , ctypes . c_char_p , NDArrayHandle , ctypes . c_void_p ) self . _monitor_callback = cb_type ( _monitor_callback_wrapper ( callback ) ) check_call ( _LIB . MXExecutorSetMonitorCallbackEX ( self . handle , self . _monitor_callback , None , ctypes . c_int ( monitor_all ) ) )
def coords ( obj ) : """Yields the coordinates from a Feature or Geometry . : param obj : A geometry or feature to extract the coordinates from . : type obj : Feature , Geometry : return : A generator with coordinate tuples from the geometry or feature . : rtype : generator"""
# Handle recursive case first if 'features' in obj : for f in obj [ 'features' ] : # For Python 2 compatibility # See https : / / www . reddit . com / r / learnpython / comments / 4rc15s / yield _ from _ and _ python _ 27 / # noqa : E501 for c in coords ( f ) : yield c else : if isinstan...
def forgotten_pw ( new_user = False ) : """Reset password for users who have already activated their accounts ."""
email = request . form . get ( "email" , "" ) . lower ( ) action = request . form . get ( "action" ) if action == "cancel" : return redirect ( url_for ( "login.login_form" ) ) if not email : flash ( _ ( "You must provide your email address." ) , "error" ) return render_template ( "login/forgotten_password.h...
def scale_atoms ( fac ) : '''Scale the currently selected atoms atoms by a certain factor * fac * . Use the value * fac = 1.0 * to reset the scale .'''
rep = current_representation ( ) atms = selected_atoms ( ) rep . scale_factors [ atms ] = fac rep . update_scale_factors ( rep . scale_factors ) viewer . update ( )
def at ( self , for_time , counter_offset = 0 ) : """Accepts either a Unix timestamp integer or a Time object . Time objects will be adjusted to UTC automatically @ param [ Time / Integer ] time the time to generate an OTP for @ param [ Integer ] counter _ offset an amount of ticks to add to the time counter"...
if not isinstance ( for_time , datetime . datetime ) : for_time = datetime . datetime . fromtimestamp ( int ( for_time ) ) return self . generate_otp ( self . timecode ( for_time ) + counter_offset )
def plot_power_factor_dop ( self , temps = 'all' , output = 'average' , relaxation_time = 1e-14 ) : """Plot the Power Factor in function of doping levels for different temperatures . Args : temps : the default ' all ' plots all the temperatures in the analyzer . Specify a list of temperatures if you want to p...
import matplotlib . pyplot as plt if output == 'average' : pf = self . _bz . get_power_factor ( relaxation_time = relaxation_time , output = 'average' ) elif output == 'eigs' : pf = self . _bz . get_power_factor ( relaxation_time = relaxation_time , output = 'eigs' ) tlist = sorted ( pf [ 'n' ] . keys ( ) ) if ...
def un ( byts ) : '''Use msgpack to de - serialize a python object . Args : byts ( bytes ) : The bytes to de - serialize Notes : String objects are decoded using utf8 encoding . In order to handle potentially malformed input , ` ` unicode _ errors = ' surrogatepass ' ` ` is set to allow decoding bad inp...
# This uses a subset of unpacker _ kwargs return msgpack . loads ( byts , use_list = False , raw = False , unicode_errors = 'surrogatepass' )
def fromcolumns ( cols , header = None , missing = None ) : """View a sequence of columns as a table , e . g . : : > > > import petl as etl > > > cols = [ [ 0 , 1 , 2 ] , [ ' a ' , ' b ' , ' c ' ] ] > > > tbl = etl . fromcolumns ( cols ) > > > tbl | f0 | f1 | | 0 | ' a ' | | 1 | ' b ' | | 2 | ' c ' ...
return ColumnsView ( cols , header = header , missing = missing )
def _save_table ( self , raw = False , cls = None , force_insert = None , force_update = None , using = None , update_fields = None ) : """Saves the current instance ."""
# Connection aliasing connection = connections [ using ] create = bool ( force_insert or not self . dn ) # Prepare fields if update_fields : target_fields = [ self . _meta . get_field ( name ) for name in update_fields ] else : target_fields = [ field for field in cls . _meta . get_fields ( include_hidden = Tru...
def find_matches ( self , text ) : """Return candidates matching the text ."""
if self . use_main_ns : self . namespace = __main__ . __dict__ if "." in text : return self . attr_matches ( text ) else : return self . global_matches ( text )
def _configure_nve_member ( self , vni , device_id , mcast_group , host_id ) : """Add " member vni " configuration to the NVE interface . Called during update postcommit port event ."""
host_nve_connections = self . _get_switch_nve_info ( host_id ) for switch_ip in host_nve_connections : # If configured to set global VXLAN values then # If this is the first database entry for this switch _ ip # then configure the " interface nve " entry on the switch . if cfg . CONF . ml2_cisco . vxlan_global_conf...
def run ( local_file , no_output ) : """Run a script and print its output . Run will send the specified file to the board and execute it immediately . Any output from the board will be printed to the console ( note that this is not a ' shell ' and you can ' t send input to the program ) . Note that if your ...
# Run the provided file and print its output . board_files = files . Files ( _board ) try : output = board_files . run ( local_file , not no_output ) if output is not None : print ( output . decode ( "utf-8" ) , end = "" ) except IOError : click . echo ( "Failed to find or read input file: {0}" . fo...
def symmetric_elliot_function ( signal , derivative = False ) : """A fast approximation of tanh"""
s = 1.0 # steepness abs_signal = ( 1 + np . abs ( signal * s ) ) if derivative : return s / abs_signal ** 2 else : # Return the activation signal return ( signal * s ) / abs_signal
def train ( config_path : str , cl_arguments : Iterable [ str ] , output_root : str ) -> None : """Load config and start the training . : param config _ path : path to configuration file : param cl _ arguments : additional command line arguments which will update the configuration : param output _ root : outp...
config = None try : config_path = find_config ( config_path ) config = load_config ( config_file = config_path , additional_args = cl_arguments ) validate_config ( config ) logging . debug ( '\tLoaded config: %s' , config ) except Exception as ex : # pylint : disable = broad - except fallback ( 'Loa...
def mget ( self , keys , * args ) : """Returns a list of values ordered identically to ` ` keys ` `"""
keys = [ self . redis_key ( k ) for k in self . _parse_values ( keys , args ) ] with self . pipe as pipe : f = Future ( ) res = pipe . mget ( keys ) def cb ( ) : decode = self . valueparse . decode f . set ( [ None if r is None else decode ( r ) for r in res . result ] ) pipe . on_execut...
def _getEventsOnDay ( self , request , day ) : """Return my child events for a given day ."""
return getAllEventsByDay ( request , day , day , home = self ) [ 0 ]
def _get_all_packages ( mirror = DEFAULT_MIRROR , cyg_arch = 'x86_64' ) : '''Return the list of packages based on the mirror provided .'''
if 'cyg.all_packages' not in __context__ : __context__ [ 'cyg.all_packages' ] = { } if mirror not in __context__ [ 'cyg.all_packages' ] : __context__ [ 'cyg.all_packages' ] [ mirror ] = [ ] if not __context__ [ 'cyg.all_packages' ] [ mirror ] : pkg_source = '/' . join ( [ mirror , cyg_arch , 'setup.bz2' ] )...
def set_ordered ( self , value , inplace = False ) : """Set the ordered attribute to the boolean value . Parameters value : bool Set whether this categorical is ordered ( True ) or not ( False ) . inplace : bool , default False Whether or not to set the ordered attribute in - place or return a copy of t...
inplace = validate_bool_kwarg ( inplace , 'inplace' ) new_dtype = CategoricalDtype ( self . categories , ordered = value ) cat = self if inplace else self . copy ( ) cat . _dtype = new_dtype if not inplace : return cat
def get_advanced_params ( ) : """Get ` Parameters ` struct with parameters that most users do not want to think about ."""
p = Parameters ( ) # Internal format used during the registration process p . FixedInternalImagePixelType = "float" p . MovingInternalImagePixelType = "float" # Image direction p . UseDirectionCosines = True # In almost all cases you ' d want multi resolution p . Registration = 'MultiResolutionRegistration' # Pyramid o...
def parameterEntity ( self , name ) : """Do an entity lookup in the internal and external subsets and"""
ret = libxml2mod . xmlGetParameterEntity ( self . _o , name ) if ret is None : raise treeError ( 'xmlGetParameterEntity() failed' ) __tmp = xmlEntity ( _obj = ret ) return __tmp
def projective_measurement_constraints ( * parties ) : """Return a set of constraints that define projective measurements . : param parties : Measurements of different parties . : type A : list or tuple of list of list of : class : ` sympy . physics . quantum . operator . HermitianOperator ` . : returns : s...
substitutions = { } # Idempotency and orthogonality of projectors if isinstance ( parties [ 0 ] [ 0 ] [ 0 ] , list ) : parties = parties [ 0 ] for party in parties : for measurement in party : for projector1 in measurement : for projector2 in measurement : if projector1 == pr...
def parse_smarttag ( document , container , tag_elem ) : "Parse the endnote element ."
tag = doc . SmartTag ( ) tag . element = tag_elem . attrib [ _name ( '{{{w}}}element' ) ] for elem in tag_elem : if elem . tag == _name ( '{{{w}}}r' ) : parse_text ( document , tag , elem ) if elem . tag == _name ( '{{{w}}}smartTag' ) : parse_smarttag ( document , tag , elem ) container . elemen...
def get_result ( self ) : """Build compiled SQL expression from the bottom up and return as a string"""
translated = self . translate ( self . expr ) if self . _needs_name ( self . expr ) : # TODO : this could fail in various ways name = self . expr . get_name ( ) translated = self . name ( translated , name ) return translated
async def handle_forever ( self ) : """Handle data forever ."""
while self . connected : data = await self . connection . recv ( ) if not data : if self . connected : await self . disconnect ( expected = False ) break await self . on_data ( data )
def get_needs_parameters ( self ) : """Get the minimum needs resources in parameter format : returns : The minimum needs resources wrapped in parameters . : rtype : list"""
parameters = [ ] for resource in self . minimum_needs [ 'resources' ] : parameter = ResourceParameter ( ) parameter . name = resource [ 'Resource name' ] parameter . help_text = resource [ 'Resource description' ] # Adding in the frequency property . This is not in the # FloatParameter by default , ...
def update_next_block ( self ) : """If the last instruction of this block is a JP , JR or RET ( with no conditions ) then the next and goes _ to sets just contains a single block"""
last = self . mem [ - 1 ] if last . inst not in ( 'ret' , 'jp' , 'jr' ) or last . condition_flag is not None : return if last . inst == 'ret' : if self . next is not None : self . next . delete_from ( self ) self . delete_goes ( self . next ) return if last . opers [ 0 ] not in LABELS . keys...
def _generate_hash ( self ) : """Generates a hash based on the specific fields for the method ."""
self . hash = None str_hash = '' for key , val in self . _get_params ( ) . iteritems ( ) : str_hash += smart_str ( val ) # Append the encryption string str_hash += self . _service . encryption_key # Set md5 hash on the object self . hash = hashlib . md5 ( str_hash ) . hexdigest ( )
def findAllSingle ( self , selfValue ) : '''Looks for all the single values and subclasses * recursively * and returns a list of them Args : selfValue : A list of single , str , int . Normally just ` ` self . value ` ` Returns : list : A list contains only singles and subclasses .'''
resultList = [ ] for element in selfValue : if isinstance ( element , Single ) : resultList . append ( element ) resultList += element . findAllSingle ( ) return resultList
def system_commands ( self , action ) : """Perform system commands"""
if action == 'backup' : status = self . api_action . backup ( ) if status [ 0 ] : notify_confirm ( 'Vent backup successful' ) else : notify_confirm ( 'Vent backup could not be completed' ) elif action == 'start' : status = self . api_action . start ( ) if status [ 0 ] : notif...
def parse_doc ( f , ctx = None , overwrite = False ) : """Accepts an open file or a list of lines ."""
lg = LineGetter ( f , comment_marker = ( "#" , ";" ) , strip = False ) cfg = ConfigParser ( ctx ) . parse_doc ( lg ) set_defaults ( cfg ) if overwrite : squash ( cfg ) return cfg
def lab ( self ) : """Return colors in Lab color space"""
RGB = [ 0 , 0 , 0 ] XYZ = [ 0 , 0 , 0 ] for ( num , value ) in enumerate ( self . rgb ) : if value > 0.04045 : value = pow ( ( ( value + 0.055 ) / 1.055 ) , 2.4 ) else : value = value / 12.92 RGB [ num ] = value * 100.0 # http : / / www . brucelindbloom . com / index . html ? Eqn _ RGB _ XYZ...
def configurations ( self ) : """Property for accessing : class : ` ConfigurationManager ` instance , which is used to manage configurations . : rtype : yagocd . resources . configuration . ConfigurationManager"""
if self . _configuration_manager is None : self . _configuration_manager = ConfigurationManager ( session = self . _session ) return self . _configuration_manager
def createProgBuilder ( env ) : """This is a utility function that creates the Program Builder in an Environment if it is not there already . If it is already there , we return the existing one ."""
try : program = env [ 'BUILDERS' ] [ 'Program' ] except KeyError : import SCons . Defaults program = SCons . Builder . Builder ( action = SCons . Defaults . LinkAction , emitter = '$PROGEMITTER' , prefix = '$PROGPREFIX' , suffix = '$PROGSUFFIX' , src_suffix = '$OBJSUFFIX' , src_builder = 'Object' , target_s...
def dropout ( x , keep_prob , noise_shape = None , name = None ) : """Dropout layer . Args : x : a Tensor keep _ prob : a float between 0.0 and 1.0 noise _ shape : an optional Shape ( a subset of x . shape ) name : an optional string Returns : a Tensor"""
noise_shape = convert_to_shape ( noise_shape ) if noise_shape is None : noise_shape = x . shape with tf . variable_scope ( name , default_name = "dropout" ) : if keep_prob == 1.0 : return x noise = cast ( less ( random_uniform ( x . mesh , noise_shape , dtype = x . dtype ) , keep_prob ) , x . dtype ...
def change_dir ( directory ) : """Wraps a function to run in a given directory ."""
def cd_decorator ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : org_path = os . getcwd ( ) os . chdir ( directory ) func ( * args , ** kwargs ) os . chdir ( org_path ) return wrapper return cd_decorator
def switch_to_aux_top_layer ( self ) : """Context that construct cnn in the auxiliary arm ."""
if self . aux_top_layer is None : raise RuntimeError ( "Empty auxiliary top layer in the network." ) saved_top_layer = self . top_layer saved_top_size = self . top_size self . top_layer = self . aux_top_layer self . top_size = self . aux_top_size yield self . aux_top_layer = self . top_layer self . aux_top_size = s...
def has_dynamic_getattr ( self , context = None ) : """Check if the class has a custom _ _ getattr _ _ or _ _ getattribute _ _ . If any such method is found and it is not from builtins , nor from an extension module , then the function will return True . : returns : True if the class has a custom _ _ geta...
def _valid_getattr ( node ) : root = node . root ( ) return root . name != BUILTINS and getattr ( root , "pure_python" , None ) try : return _valid_getattr ( self . getattr ( "__getattr__" , context ) [ 0 ] ) except exceptions . AttributeInferenceError : # if self . newstyle : XXX cause an infinite recursio...
def where_ends_with ( self , field_name , value ) : """To get all the document that ends with the value in the giving field _ name @ param str field _ name : The field name in the index you want to query . @ param str value : The value will be the fields value you want to query"""
if field_name is None : raise ValueError ( "None field_name is invalid" ) field_name = Query . escape_if_needed ( field_name ) self . _add_operator_if_needed ( ) self . negate_if_needed ( field_name ) self . last_equality = { field_name : value } token = _Token ( field_name = field_name , token = "endsWith" , value...
def check_environment_presets ( ) : """Checks for environment variables that can cause problems with supernova"""
presets = [ x for x in os . environ . copy ( ) . keys ( ) if x . startswith ( 'NOVA_' ) or x . startswith ( 'OS_' ) ] if len ( presets ) < 1 : return True else : click . echo ( "_" * 80 ) click . echo ( "*WARNING* Found existing environment variables that may " "cause conflicts:" ) for preset in presets...
def create_python_bundle ( self , dirn , arch ) : """Create a packaged python bundle in the target directory , by copying all the modules and standard library to the right place ."""
# Todo : find a better way to find the build libs folder modules_build_dir = join ( self . get_build_dir ( arch . arch ) , 'android-build' , 'build' , 'lib.linux{}-{}-{}' . format ( '2' if self . version [ 0 ] == '2' else '' , arch . command_prefix . split ( '-' ) [ 0 ] , self . major_minor_version_string ) ) # Compile...
def squish ( incs , f ) : """returns ' flattened ' inclination , assuming factor , f and King ( 1955 ) formula : tan ( I _ o ) = f tan ( I _ f ) Parameters _ _ _ _ _ incs : array of inclination ( I _ f ) data to flatten f : flattening factor Returns _ _ _ _ _ I _ o : inclinations after flattening"""
incs = np . radians ( incs ) I_o = f * np . tan ( incs ) # multiply tangent by flattening factor return np . degrees ( np . arctan ( I_o ) )
def get_children_for ( self , parent_alias = None , only_with_aliases = False ) : """Returns a list with with categories under the given parent . : param str | None parent _ alias : Parent category alias or None for categories under root : param bool only _ with _ aliases : Flag to return only children with ali...
self . _cache_init ( ) child_ids = self . get_child_ids ( parent_alias ) if only_with_aliases : children = [ ] for cid in child_ids : category = self . get_category_by_id ( cid ) if category . alias : children . append ( category ) return children return [ self . get_category_by_...
def flushdb ( host = None , port = None , db = None , password = None ) : '''Remove all keys from the selected database CLI Example : . . code - block : : bash salt ' * ' redis . flushdb'''
server = _connect ( host , port , db , password ) return server . flushdb ( )
def FDMT_params ( f_min , f_max , maxDT , inttime ) : """Summarize DM grid and other parameters ."""
maxDM = inttime * maxDT / ( 4.1488e-3 * ( 1 / f_min ** 2 - 1 / f_max ** 2 ) ) logger . info ( 'Freqs from {0}-{1}, MaxDT {2}, Int time {3} => maxDM {4}' . format ( f_min , f_max , maxDT , inttime , maxDM ) )
def decode_step ( self , step : int , target_embed_prev : mx . sym . Symbol , source_encoded_max_length : int , * states : mx . sym . Symbol ) -> Tuple [ mx . sym . Symbol , mx . sym . Symbol , List [ mx . sym . Symbol ] ] : """Decodes a single time step given the current step , the previous embedded target word , ...
pass
def ReadItems ( self , collection_link , feed_options = None ) : """Reads all documents in a collection . : param str collection _ link : The link to the document collection . : param dict feed _ options : : return : Query Iterable of Documents . : rtype : query _ iterable . QueryIterable"""
if feed_options is None : feed_options = { } return self . QueryItems ( collection_link , None , feed_options )
def RunPlaybookOnHost ( playbook_path , host , private_key , extra_vars = None ) : """Runs the playbook and returns True if it completes successfully on a single host ."""
return RunPlaybookOnHosts ( playbook_path , [ host ] , private_key , extra_vars )
def addMenuLabel ( menu , text ) : """Adds a QLabel contaning text to the given menu"""
qaw = QWidgetAction ( menu ) lab = QLabel ( text , menu ) qaw . setDefaultWidget ( lab ) lab . setAlignment ( Qt . AlignCenter ) lab . setFrameShape ( QFrame . StyledPanel ) lab . setFrameShadow ( QFrame . Sunken ) menu . addAction ( qaw ) return lab
def from_url ( url , db = None , ** kwargs ) : """Returns an active Redis client generated from the given database URL . Will attempt to extract the database id from the path url fragment , if none is provided ."""
from redis . client import Redis return Redis . from_url ( url , db , ** kwargs )
def element_conforms ( element , etype ) -> bool : """Determine whether element conforms to etype"""
from pyjsg . jsglib import Empty if isinstance ( element , etype ) : return True # This catches the Optional [ ] idiom if ( element is None or element is Empty ) and issubclass ( etype , type ( None ) ) : return True elif element is Empty : return False elif isinstance ( etype , type ( type ) ) and ( issubc...
def all ( A , ax = None ) : """Test if all values in A evaluate to True"""
if isinstance ( A , Poly ) : out = numpy . zeros ( A . shape , dtype = bool ) B = A . A for key in A . keys : out += all ( B [ key ] , ax ) return out return numpy . all ( A , ax )
def _get_history_id ( self , connection , agent_id , instance_id ) : '''Checks own cache for history _ id for agent _ id and instance _ id . If information is missing fetch it from database . If it is not there create the new record . BEWARE : This method runs in a thread .'''
cache_key = ( agent_id , instance_id , ) if cache_key in self . _history_id_cache : history_id = self . _history_id_cache [ cache_key ] return history_id else : command = text_helper . format_block ( """ SELECT id FROM histories WHERE agent_id = ? AND instance_id = ? """ ) cursor...
def _validate_bagittxt ( self ) : """Verify that bagit . txt conforms to specification"""
bagit_file_path = os . path . join ( self . path , "bagit.txt" ) with open ( bagit_file_path , 'r' ) as bagit_file : first_line = bagit_file . readline ( ) if first_line . startswith ( BOM ) : raise BagValidationError ( "bagit.txt must not contain a byte-order mark" )
def publish ( self , metrics , config ) : """Publishes metrics to a file in JSON format . This method is called by the Snap deamon during the collection phase of the execution of a Snap workflow . In this example we are writing the metrics to a file in json format . We obtain the path to the file through th...
if len ( metrics ) > 0 : with open ( config [ "file" ] , 'a' ) as outfile : for metric in metrics : outfile . write ( json_format . MessageToJson ( metric . _pb , including_default_value_fields = True ) )
def coord ( self , offset = ( 0 , 0 ) ) : '''return lat , lon within a tile given ( offsetx , offsety )'''
( tilex , tiley ) = self . tile ( offsetx , offsety ) = offset world_tiles = 1 << self . zoom x = ( tilex + 1.0 * offsetx / TILES_WIDTH ) / ( world_tiles / 2. ) - 1 y = ( tiley + 1.0 * offsety / TILES_HEIGHT ) / ( world_tiles / 2. ) - 1 lon = x * 180.0 y = math . exp ( - y * 2 * math . pi ) e = ( y - 1 ) / ( y + 1 ) la...
def add_feature ( self , label , value = None ) : """label : A VW label ( not containing characters from escape _ dict . keys ( ) , unless ' escape ' mode is on ) value : float giving the weight or magnitude of this feature"""
if self . escape : label = escape_vw_string ( label ) elif self . validate : validate_vw_string ( label ) feature = ( label , value ) self . features . append ( feature )
def median ( lst ) : """Calcuates the median value in a @ lst"""
# : http : / / stackoverflow . com / a / 24101534 sortedLst = sorted ( lst ) lstLen = len ( lst ) index = ( lstLen - 1 ) // 2 if ( lstLen % 2 ) : return sortedLst [ index ] else : return ( sortedLst [ index ] + sortedLst [ index + 1 ] ) / 2.0
def repr ( self , changed_widgets = None ) : """It is used to automatically represent the object to HTML format packs all the attributes , children and so on . Args : changed _ widgets ( dict ) : A dictionary containing a collection of tags that have to be updated . The tag that have to be updated is the ke...
if changed_widgets is None : changed_widgets = { } local_changed_widgets = { } _innerHTML = self . innerHTML ( local_changed_widgets ) if self . _ischanged ( ) or ( len ( local_changed_widgets ) > 0 ) : self . _backup_repr = '' . join ( ( '<' , self . type , ' ' , self . _repr_attributes , '>' , _innerHTML , '<...
def delvlan ( self , vlanid ) : """Function operates on the IMCDev object . Takes input of vlanid ( 1-4094 ) , auth and url to execute the delete _ dev _ vlans method on the IMCDev object . Device must be supported in the HPE IMC Platform VLAN Manager module . : param vlanid : str of VLANId ( valid 1-4094 ) ...
delete_dev_vlans ( vlanid , self . auth , self . url , devid = self . devid )
def p_duration_number_duration_unit_duration ( self , p ) : 'duration : NUMBER DURATION _ UNIT duration'
logger . debug ( 'duration = number %s, duration unit %s, duration %s' , p [ 1 ] , p [ 2 ] , p [ 3 ] ) duration = Duration . from_quantity_unit ( p [ 1 ] , p [ 2 ] ) p [ 0 ] = duration + p [ 3 ]
def load_cover ( self ) : """Load the cover out of the config , options and conventions . Priority goes this way : 1 . if a - - cover option is set , use it . 2 . if there ' s a " cover " key in the config file , use it . 3 . if a cover . ( png | jpg | jpeg | svg ) exists in the directory , use it . Once ...
if not self . args : return False filename = self . args . get ( '--cover' , None ) or self . config . get ( 'cover' , None ) or None if not filename : for extension in ( 'png' , 'jpg' , 'jpeg' , 'svg' ) : temp_filename = 'cover.%s' % extension if exists ( temp_filename ) : filename ...
def create ( self , * args , ** kwargs ) : """Adds created http status response and location link ."""
resource = super ( JsonServerResource , self ) . create ( * args , ** kwargs ) return ResourceResult ( body = resource , status = get_http_status_code_value ( http . client . CREATED ) , location = "{}/{}" . format ( request . url , resource . get_id ( ) ) )
def apply_cut ( self , cut ) : """Return a cut version of this transition ."""
return Transition ( self . network , self . before_state , self . after_state , self . cause_indices , self . effect_indices , cut )
def stop_capture ( self , port_number ) : """Stops a packet capture . : param port _ number : allocated port number"""
if not [ port [ "port_number" ] for port in self . _ports_mapping if port_number == port [ "port_number" ] ] : raise NodeError ( "Port {port_number} doesn't exist on cloud '{name}'" . format ( name = self . name , port_number = port_number ) ) if port_number not in self . _nios : raise NodeError ( "Port {} is n...
def predict_variant_coding_effect_on_transcript ( variant , transcript , trimmed_cdna_ref , trimmed_cdna_alt , transcript_offset ) : """Given a minimal cDNA ref / alt nucleotide string pair and an offset into a given transcript , determine the coding effect of this nucleotide substitution onto the translated pr...
if not transcript . complete : raise ValueError ( ( "Can't annotate coding effect for %s" " on incomplete transcript %s" % ( variant , transcript ) ) ) sequence = transcript . sequence n_ref = len ( trimmed_cdna_ref ) n_alt = len ( trimmed_cdna_alt ) # reference nucleotides found on the transcript , if these don ' ...
def write ( p , line ) : """Send and flush a single line to the subprocess ' stdin ."""
log . debug ( '%s <- %r' , p . args , line ) p . stdin . write ( line ) p . stdin . flush ( )
def calculate_bv_sum_unordered ( site , nn_list , scale_factor = 1 ) : """Calculates the BV sum of a site for unordered structures . Args : site : The site nn _ list : List of nearest neighbors in the format [ ( nn _ site , dist ) , . . . ] . scale _ factor : A scale factor to be applied . This is use...
# If the site " site " has N partial occupations as : f _ { site } _ 0, # f _ { site } _ 1 , . . . f _ { site } _ N of elements # X _ { site } _ 0 , X _ { site } _ 1 , . . . X _ { site } _ N , and each neighbors nn _ i in nn # has N _ { nn _ i } partial occupations as : # f _ { nn _ i } _ 0 , f _ { nn _ i } _ 1 , . . ....
def is_valid ( self , model , validator = None ) : """Returns true if the model passes the validation , and false if not . Validator must be present _ optional if validation is not ' simple ' ."""
if self . property_name and self . is_property_specific : arg0 = getattr ( model , self . property_name ) else : arg0 = model if self . is_simple : is_valid = self . callback ( arg0 ) else : is_valid = self . callback ( arg0 , validator ) return ( is_valid , None if is_valid else ( self . message or "is...
def _calcCTRBUF ( self ) : """Calculates one block of CTR keystream"""
self . ctr_cks = self . encrypt ( struct . pack ( "Q" , self . ctr_iv ) ) # keystream block self . ctr_iv += 1 self . ctr_pos = 0
def values_for_enum ( gtype ) : """Get all values for a enum ( gtype ) ."""
g_type_class = gobject_lib . g_type_class_ref ( gtype ) g_enum_class = ffi . cast ( 'GEnumClass *' , g_type_class ) values = [ ] # -1 since we always have a " last " member . for i in range ( 0 , g_enum_class . n_values - 1 ) : value = _to_string ( g_enum_class . values [ i ] . value_nick ) values . append ( va...
def _cla_adder_unit ( a , b , cin ) : """Carry generation and propogation signals will be calculated only using the inputs ; their values don ' t rely on the sum . Every unit generates a cout signal which is used as cin for the next unit ."""
gen = a & b prop = a ^ b assert ( len ( prop ) == len ( gen ) ) carry = [ gen [ 0 ] | prop [ 0 ] & cin ] sum_bit = prop [ 0 ] ^ cin cur_gen = gen [ 0 ] cur_prop = prop [ 0 ] for i in range ( 1 , len ( prop ) ) : cur_gen = gen [ i ] | ( prop [ i ] & cur_gen ) cur_prop = cur_prop & prop [ i ] sum_bit = pyrtl ...
def remove_file_data ( file_id , silent = True ) : """Remove file instance and associated data . : param file _ id : The : class : ` invenio _ files _ rest . models . FileInstance ` ID . : param silent : It stops propagation of a possible arised IntegrityError exception . ( Default : ` ` True ` ` ) : raises...
try : # First remove FileInstance from database and commit transaction to # ensure integrity constraints are checked and enforced . f = FileInstance . get ( file_id ) if not f . writable : return f . delete ( ) db . session . commit ( ) # Next , remove the file on disk . This leaves the poss...
def load ( self ) : """Loads this stream by calling River View for data ."""
print "Loading data for %s..." % self . getName ( ) self . _dataHandle = self . _stream . data ( since = self . _since , until = self . _until , limit = self . _limit , aggregate = self . _aggregate ) self . _data = self . _dataHandle . data ( ) self . _headers = self . _dataHandle . headers ( ) print "Loaded %i rows."...
def universal_transformer_base ( ) : """Base parameters for Universal Transformer ."""
hparams = transformer . transformer_base ( ) # To have a similar capacity to the transformer _ base with 6 layers , # we need to increase the size of the UT ' s layer # since , in fact , UT has a single layer repeating multiple times . hparams . hidden_size = 1024 hparams . filter_size = 4096 hparams . num_heads = 16 h...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'voices' ) and self . voices is not None : _dict [ 'voices' ] = [ x . _to_dict ( ) for x in self . voices ] return _dict
def get_configs ( self ) : """Return an iterable of models ."""
self . bots . check_models_ready ( ) for config in self . configs . values ( ) : yield config
def disconnect ( self ) : """Disconnect from a TWS or IB gateway application . This will clear all session state ."""
if not self . client . isConnected ( ) : return stats = self . client . connectionStats ( ) self . _logger . info ( f'Disconnecting from {self.client.host}:{self.client.port}, ' f'{util.formatSI(stats.numBytesSent)}B sent ' f'in {stats.numMsgSent} messages, ' f'{util.formatSI(stats.numBytesRecv)}B received ' f'in {...
def pre_message ( self ) : '''read timestamp if needed'''
# read the timestamp if self . filesize != 0 : self . percent = ( 100.0 * self . f . tell ( ) ) / self . filesize if self . notimestamps : return if self . planner_format : tbuf = self . f . read ( 21 ) if len ( tbuf ) != 21 or tbuf [ 0 ] != '-' or tbuf [ 20 ] != ':' : raise RuntimeError ( 'bad ...
def _get_data ( self , read_size ) : """Get data from the character device ."""
if NIX : return super ( Mouse , self ) . _get_data ( read_size ) return self . _pipe . recv_bytes ( )
def compile_assets ( self ) : """Compile the front end assets"""
try : # Move into client dir curdir = os . path . abspath ( os . curdir ) client_path = os . path . join ( os . path . dirname ( __file__ ) , 'longclaw' , 'client' ) os . chdir ( client_path ) subprocess . check_call ( [ 'npm' , 'install' ] ) subprocess . check_call ( [ 'npm' , 'run' , 'build' ] ) ...
def format_explanation ( explanation , indent = ' ' , indent_level = 0 ) : """Return explanation in an easier to read format Easier to read for me , at least ."""
if not explanation : return '' # Note : This is probably a crap implementation , but it ' s an # interesting starting point for a better formatter . line = ( '%s%s %2.4f' % ( ( indent * indent_level ) , explanation [ 'description' ] , explanation [ 'value' ] ) ) if 'details' in explanation : details = '\n' . jo...
def write_toml ( self , data , path = None ) : """Writes the given data structure out as TOML ."""
if path is None : path = self . pipfile_location data = convert_toml_outline_tables ( data ) try : formatted_data = tomlkit . dumps ( data ) . rstrip ( ) except Exception : document = tomlkit . document ( ) for section in ( "packages" , "dev-packages" ) : document [ section ] = tomlkit . contain...
def get_network ( network_id ) : """Get the network with the given id ."""
try : net = models . Network . query . filter_by ( id = network_id ) . one ( ) except NoResultFound : return error_response ( error_type = "/network GET: no network found" , status = 403 ) # return the data return success_response ( network = net . __json__ ( ) )
def strframe ( obj , extended = False ) : """Return a string with a frame record pretty - formatted . The record is typically an item in a list generated by ` inspect . stack ( ) < https : / / docs . python . org / 3 / library / inspect . html # inspect . stack > ` _ ) . : param obj : Frame record : type ob...
# Stack frame - > ( frame object [ 0 ] , filename [ 1 ] , line number of current # line [ 2 ] , function name [ 3 ] , list of lines of context from source # code [ 4 ] , index of current line within list [ 5 ] ) fname = normalize_windows_fname ( obj [ 1 ] ) ret = list ( ) ret . append ( pcolor ( "Frame object ID: {0}" ...