signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def commit ( self , raise_on_error = True ) : '''Send commands to redis .'''
cmds = list ( chain ( [ ( ( 'multi' , ) , { } ) ] , self . command_stack , [ ( ( 'exec' , ) , { } ) ] ) ) self . reset ( ) return self . store . execute_pipeline ( cmds , raise_on_error )
def calc_mean_and_variance_of_variances ( self , NumberOfOscillations ) : """Calculates the mean and variance of a set of varainces . This set is obtained by splitting the timetrace into chunks of points with a length of NumberOfOscillations oscillations . Parameters NumberOfOscillations : int The number ...
SplittedArraySize = int ( self . SampleFreq / self . FTrap . n ) * NumberOfOscillations VoltageArraySize = len ( self . voltage ) SnippetsVariances = _np . var ( self . voltage [ : VoltageArraySize - _np . mod ( VoltageArraySize , SplittedArraySize ) ] . reshape ( - 1 , SplittedArraySize ) , axis = 1 ) return _np . mea...
def keys ( self ) : "Returns a list of ConfigMap keys ."
return ( list ( self . _pb . IntMap . keys ( ) ) + list ( self . _pb . StringMap . keys ( ) ) + list ( self . _pb . FloatMap . keys ( ) ) + list ( self . _pb . BoolMap . keys ( ) ) )
def options ( self , url : StrOrURL , * , allow_redirects : bool = True , ** kwargs : Any ) -> '_RequestContextManager' : """Perform HTTP OPTIONS request ."""
return _RequestContextManager ( self . _request ( hdrs . METH_OPTIONS , url , allow_redirects = allow_redirects , ** kwargs ) )
def _set_level_1 ( self , v , load = False ) : """Setter method for level _ 1 , mapped from YANG variable / routing _ system / router / isis / router _ isis _ cmds _ holder / address _ family / ipv6 / af _ ipv6 _ unicast / af _ ipv6 _ attributes / af _ common _ attributes / redistribute / isis / level _ 1 ( contain...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = level_1 . level_1 , is_container = 'container' , presence = False , yang_name = "level-1" , rest_name = "level-1" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True ,...
def associate_azure_publisher ( self , publisher_name , azure_publisher_id ) : """AssociateAzurePublisher . [ Preview API ] : param str publisher _ name : : param str azure _ publisher _ id : : rtype : : class : ` < AzurePublisher > < azure . devops . v5_0 . gallery . models . AzurePublisher > `"""
route_values = { } if publisher_name is not None : route_values [ 'publisherName' ] = self . _serialize . url ( 'publisher_name' , publisher_name , 'str' ) query_parameters = { } if azure_publisher_id is not None : query_parameters [ 'azurePublisherId' ] = self . _serialize . query ( 'azure_publisher_id' , azur...
def downsample ( time_series : DataFrame , freq : str ) -> DataFrame : """Downsample the given route , stop , or feed time series , ( outputs of : func : ` . routes . compute _ route _ time _ series ` , : func : ` . stops . compute _ stop _ time _ series ` , or : func : ` . miscellany . compute _ feed _ time ...
f = time_series . copy ( ) # Can ' t downsample to a shorter frequency if f . empty or pd . tseries . frequencies . to_offset ( freq ) < f . index . freq : return f result = None if "stop_id" in time_series . columns . names : # It ' s a stops time series result = f . resample ( freq ) . sum ( ) else : # It ' s...
def query_snl ( self , criteria ) : """Query for submitted SNLs . . . note : : As of now , this MP REST feature is open only to a select group of users . Opening up submissions to all users is being planned for the future . Args : criteria ( dict ) : Query criteria . Returns : A dict , with a list o...
try : payload = { "criteria" : json . dumps ( criteria ) } response = self . session . post ( "{}/snl/query" . format ( self . preamble ) , data = payload ) if response . status_code in [ 200 , 400 ] : resp = json . loads ( response . text ) if resp [ "valid_response" ] : if resp...
def get_cmd_output_from_stdin ( stdint_content_binary : bytes , * args , encoding : str = SYS_ENCODING ) -> str : """Returns text output of a command , passing binary data in via stdin ."""
p = subprocess . Popen ( args , stdin = subprocess . PIPE , stdout = subprocess . PIPE ) stdout , stderr = p . communicate ( input = stdint_content_binary ) return stdout . decode ( encoding , errors = 'ignore' )
def attachable ( name , path = None ) : '''Return True if the named container can be attached to via the lxc - attach command path path to the container parent default : / var / lib / lxc ( system default ) . . versionadded : : 2015.8.0 CLI Example : . . code - block : : bash salt ' minion ' lxc . a...
cachekey = 'lxc.attachable{0}{1}' . format ( name , path ) try : return __context__ [ cachekey ] except KeyError : _ensure_exists ( name , path = path ) # Can ' t use run ( ) here because it uses attachable ( ) and would # endlessly recurse , resulting in a traceback log . debug ( 'Checking if LXC c...
def run ( self , * args ) : """Export data from the registry . By default , it writes the data to the standard output . If a positional argument is given , it will write the data on that file ."""
params = self . parser . parse_args ( args ) with params . outfile as outfile : if params . identities : code = self . export_identities ( outfile , params . source ) elif params . orgs : code = self . export_organizations ( outfile ) else : # The running proccess never should reach this sec...
def _branch ( self , live_defs , node , path = "" ) : """Recursive function , it branches in every possible path in the VFG . @ live _ defs : a dict { addr : stmt } of live definitions at the start point @ node : the starting vfg node Returns : the address of the block where the execution stops"""
irsb = self . _irsb ( node . state ) path = path + " -> " + hex ( irsb . addr ) if isinstance ( irsb , SimProcedure ) : self . _simproc_map [ irsb . addr ] = repr ( irsb ) l . debug ( "--> Branch: running block 0x%x" % irsb . addr ) block = self . _make_block ( irsb , live_defs ) self . _imarks . update ( block . _...
def Run ( self , request ) : """Runs the Find action ."""
self . request = request filters = self . BuildChecks ( request ) files_checked = 0 for f in self . ListDirectory ( request . pathspec ) : self . Progress ( ) # Ignore this file if any of the checks fail . if not any ( ( check ( f ) for check in filters ) ) : self . SendReply ( f ) files_checked...
def copy ( self , deep = True , data = None ) : """Returns a copy of this object . If ` deep = True ` , the data array is loaded into memory and copied onto the new object . Dimensions , attributes and encodings are always copied . Use ` data ` to create a new object with the same structure as original but ...
if data is None : data = self . _data if isinstance ( data , indexing . MemoryCachedArray ) : # don ' t share caching between copies data = indexing . MemoryCachedArray ( data . array ) if deep : if isinstance ( data , dask_array_type ) : data = data . copy ( ) elif not i...
def stats ( path , hash_type = None , follow_symlinks = True ) : '''Return a dict containing the stats for a given file CLI Example : . . code - block : : bash salt ' * ' file . stats / etc / passwd'''
path = os . path . expanduser ( path ) ret = { } if not os . path . exists ( path ) : try : # Broken symlinks will return False for os . path . exists ( ) , but still # have a uid and gid pstat = os . lstat ( path ) except OSError : # Not a broken symlink , just a nonexistent path # NOTE : The f...
def reset ( self ) : """Reset the calibration to it initial state"""
simulation = self . survey_scenario . simulation holder = simulation . get_holder ( self . weight_name ) holder . array = numpy . array ( self . initial_weight , dtype = holder . variable . dtype )
def enter_linking_mode ( self , group = 0x01 ) : """Tell a device to enter All - Linking Mode . Same as holding down the Set button for 10 sec . Default group is 0x01. Not supported by i1 devices ."""
msg = ExtendedSend ( self . _address , COMMAND_ENTER_LINKING_MODE_0X09_NONE , cmd2 = group , userdata = Userdata ( ) ) msg . set_checksum ( ) self . _send_msg ( msg )
def filterstr_to_filterfunc ( filter_str : str , item_type : type ) : """Takes an - - post - filter = . . . or - - storyitem - filter = . . . filter specification and makes a filter _ func Callable out of it ."""
# The filter _ str is parsed , then all names occurring in its AST are replaced by loads to post . < name > . A # function Post - > bool is returned which evaluates the filter with the post as ' post ' in its namespace . class TransformFilterAst ( ast . NodeTransformer ) : def visit_Name ( self , node : ast . Name ...
def build_specfile_filesection ( spec , files ) : """builds the % file section of the specfile"""
str = '%files\n' if 'X_RPM_DEFATTR' not in spec : spec [ 'X_RPM_DEFATTR' ] = '(-,root,root)' str = str + '%%defattr %s\n' % spec [ 'X_RPM_DEFATTR' ] supported_tags = { 'PACKAGING_CONFIG' : '%%config %s' , 'PACKAGING_CONFIG_NOREPLACE' : '%%config(noreplace) %s' , 'PACKAGING_DOC' : '%%doc %s' , 'PACKAGING_UNIX_ATTR' ...
def query_configuration ( parser_args ) : """Queries process state"""
from synergy . system import process_helper from synergy . conf import context process_names = [ parser_args . process_name ] if parser_args . process_name else list ( context . process_context ) for process_name in process_names : process_helper . poll_process ( process_name ) sys . stdout . write ( '\n' )
def create_all ( graph ) : """Create all database tables ."""
head = get_current_head ( graph ) if head is None : Model . metadata . create_all ( graph . postgres ) stamp_head ( graph )
def max_pulse_sp ( self ) : """Used to set the pulse size in milliseconds for the signal that tells the servo to drive to the maximum ( clockwise ) position _ sp . Default value is 2400. Valid values are 2300 to 2700 . You must write to the position _ sp attribute for changes to this attribute to take effect ...
self . _max_pulse_sp , value = self . get_attr_int ( self . _max_pulse_sp , 'max_pulse_sp' ) return value
def _remove_unexpected_query_parameters ( schema , req ) : """Remove unexpected properties from the req . GET ."""
additional_properties = schema . get ( 'addtionalProperties' , True ) if additional_properties : pattern_regexes = [ ] patterns = schema . get ( 'patternProperties' , None ) if patterns : for regex in patterns : pattern_regexes . append ( re . compile ( regex ) ) for param in set ( r...
def _get_section_start_index ( self , section ) : '''Get start of a section ' s content . : param section : string name of section : return : integer index of section ' s beginning : raises : NonextantSectionException'''
sec_start_re = r'%s\s*\{' % section found = re . search ( sec_start_re , self . template_str ) if found : return found . end ( ) - 1 raise NonextantSectionException ( 'Section %s not found in template' % section )
def prefix ( self , sign : Optional [ PrefixSign ] = None , symbol : bool = False ) -> str : """Get a random prefix for the International System of Units . : param sign : Sing of number . : param symbol : Return symbol of prefix . : return : Prefix for SI . : raises NonEnumerableError : if sign is not suppo...
prefixes = SI_PREFIXES_SYM if symbol else SI_PREFIXES key = self . _validate_enum ( item = sign , enum = PrefixSign ) return self . random . choice ( prefixes [ key ] )
def LoadElement ( href , only_etag = False ) : """Return an instance of a element as a ElementCache dict used as a cache . : rtype ElementCache"""
request = SMCRequest ( href = href ) request . exception = FetchElementFailed result = request . read ( ) if only_etag : return result . etag return ElementCache ( result . json , etag = result . etag )
def mesh_surface_area ( mesh = None , verts = None , faces = None ) : r"""Calculates the surface area of a meshed region Parameters mesh : tuple The tuple returned from the ` ` mesh _ region ` ` function verts : array An N - by - ND array containing the coordinates of each mesh vertex faces : array An...
if mesh : verts = mesh . verts faces = mesh . faces else : if ( verts is None ) or ( faces is None ) : raise Exception ( 'Either mesh or verts and faces must be given' ) surface_area = measure . mesh_surface_area ( verts , faces ) return surface_area
def find_cell_content ( self , lines ) : """Parse cell till its end and set content , lines _ to _ next _ cell . Return the position of next cell start"""
cell_end_marker , next_cell_start , self . explicit_eoc = self . find_cell_end ( lines ) # Metadata to dict if self . metadata is None : cell_start = 0 self . metadata = { } else : cell_start = 1 # Cell content source = lines [ cell_start : cell_end_marker ] self . org_content = [ line for line in source ] ...
def create_from_format_name ( self , format_name ) : """Create a file loader from a format name . Supported file formats are as follows : Format name Loader ` ` " csv " ` ` : py : class : ` ~ . CsvTableFileLoader ` ` ` " excel " ` ` : py : class : ` ~ . ExcelTableFileLoader ` ` ` " html " ` ` : py : class...
loader = self . _create_from_format_name ( format_name ) logger . debug ( "TableFileLoaderFactory.create_from_format_name: name={}, loader={}" . format ( format_name , loader . format_name ) ) return loader
def run_evaluate ( self , block : TimeAggregate ) -> bool : """Evaluates the anchor condition against the specified block . : param block : Block to run the anchor condition against . : return : True , if the anchor condition is met , otherwise , False ."""
if self . _anchor . evaluate_anchor ( block , self . _evaluation_context ) : try : self . run_reset ( ) self . _evaluation_context . global_add ( 'anchor' , block ) self . _evaluate ( ) self . _anchor . add_condition_met ( ) return True finally : self . _evaluatio...
def stratify_by_scores ( scores , goal_n_strata = 'auto' , method = 'cum_sqrt_F' , n_bins = 'auto' ) : """Stratify by binning the items based on their scores Parameters scores : array - like , shape = ( n _ items , ) ordered array of scores which quantify the classifier confidence for the items in the pool ...
available_methods = [ 'equal_size' , 'cum_sqrt_F' ] if method not in available_methods : raise ValueError ( "method argument is invalid" ) if ( method == 'cum_sqrt_F' ) or ( goal_n_strata == 'auto' ) : # computation below is needed for cum _ sqrt _ F method OR if we need to # determine the number of strata for equa...
def get_steamids_from_ips ( self , server_ips , timeout = 30 ) : """Resolve SteamIDs from IPs : param steam _ ids : a list of ips ( e . g . ` ` [ ' 1.2.3.4:27015 ' , . . . ] ` ` ) : type steam _ ids : list : param timeout : ( optional ) timeout for request in seconds : type timeout : int : return : map of...
resp , error = self . _um . send_and_wait ( "GameServers.GetServerSteamIDsByIP#1" , { "server_ips" : server_ips } , timeout = timeout , ) if error : raise error if resp is None : return None return { server . addr : SteamID ( server . steamid ) for server in resp . servers }
def __regions_russian ( self , word ) : """Return the regions RV and R2 which are used by the Russian stemmer . In any word , RV is the region after the first vowel , or the end of the word if it contains no vowel . R2 is the region after the first non - vowel following a vowel in R1 , or the end of the wor...
r1 = "" r2 = "" rv = "" vowels = ( "A" , "U" , "E" , "a" , "e" , "i" , "o" , "u" , "y" ) word = ( word . replace ( "i^a" , "A" ) . replace ( "i^u" , "U" ) . replace ( "e`" , "E" ) ) for i in range ( 1 , len ( word ) ) : if word [ i ] not in vowels and word [ i - 1 ] in vowels : r1 = word [ i + 1 : ] ...
def controlParameters ( self , module , status ) : """Returns control parameters as XML . : type module : str : type status : str : param module : The module number / ID : param status : The state to set ( i . e . true ( on ) or false ( off ) ) : return XML string to join with payload"""
if self . use_legacy_protocol : return '''{}<NickName>Socket 1</NickName><Description>Socket 1</Description> <OPStatus>{}</OPStatus><Controller>1</Controller>''' . format ( self . moduleParameters ( module ) , status ) else : return '''{}<NickName>Socket 1</NickName><Description>Socket 1</...
def apply_mask ( data : bytes , mask : bytes ) -> bytes : """Apply masking to the data of a WebSocket message . ` ` data ` ` and ` ` mask ` ` are bytes - like objects . Return : class : ` bytes ` ."""
if len ( mask ) != 4 : raise ValueError ( "mask must contain 4 bytes" ) return bytes ( b ^ m for b , m in zip ( data , itertools . cycle ( mask ) ) )
def floatify_latlng ( input_value ) : """Work around a JSON dict with string , not float , lat / lngs . Given anything ( list / dict / etc ) it will return that thing again , * but * any dict ( at any level ) that has only 2 elements lat & lng , will be replaced with the lat & lng turned into floats . If th...
if isinstance ( input_value , collections . Mapping ) : if len ( input_value ) == 2 and sorted ( input_value . keys ( ) ) == [ 'lat' , 'lng' ] : # This dict has only 2 keys ' lat ' & ' lon ' return { 'lat' : float_if_float ( input_value [ "lat" ] ) , 'lng' : float_if_float ( input_value [ "lng" ] ) } el...
def match ( self , filename ) : """Searches for a pattern that matches the given filename . : return A matching pattern or None if there is no matching pattern ."""
try : for regex , patterns in self . _regex_patterns : match = regex . match ( filename ) debug_template = "%s against %s: %%s" % ( filename , regex . _real_regex . pattern ) if match : if self . debug : logger . info ( debug_template % "hit" ) return ...
def check_image_positions ( self , kwargs_ps , kwargs_lens , tolerance = 0.001 ) : """checks whether the point sources in kwargs _ ps satisfy the lens equation with a tolerance ( computed by ray - tracing in the source plane ) : param kwargs _ ps : : param kwargs _ lens : : param tolerance : : return : bo...
x_image_list , y_image_list = self . image_position ( kwargs_ps , kwargs_lens ) for i , model in enumerate ( self . _point_source_list ) : if model in [ 'LENSED_POSITION' , 'SOURCE_POSITION' ] : x_pos = x_image_list [ i ] y_pos = y_image_list [ i ] x_source , y_source = self . _lensModel . r...
def has_changed ( self , initial , data ) : "Detects if the data was changed . This is added in 1.6."
if initial is None and data is None : return False if data and not hasattr ( data , '__iter__' ) : data = self . widget . decompress ( data ) initial = self . to_python ( initial ) data = self . to_python ( data ) if hasattr ( self , '_coerce' ) : data = self . _coerce ( data ) if isinstance ( data , Model ...
def set_inputhook ( self , callback ) : """Set PyOS _ InputHook to callback and return the previous one ."""
# On platforms with ' readline ' support , it ' s all too likely to # have a KeyboardInterrupt signal delivered * even before * an # initial ` ` try : ` ` clause in the callback can be executed , so # we need to disable CTRL + C in this situation . ignore_CTRL_C ( ) self . _callback = callback self . _callback_pyfuncty...
def inject ( self , * args ) : """Decorator to mark a class , method , or function as needing dependencies injected . Example usage : : from flask _ unchained import unchained , injectable # automatically figure out which params to inject @ unchained . inject ( ) def my _ function ( not _ injected , some ...
used_without_parenthesis = len ( args ) and callable ( args [ 0 ] ) has_explicit_args = len ( args ) and all ( isinstance ( x , str ) for x in args ) def wrapper ( fn ) : cls = None if isinstance ( fn , type ) : cls = fn fn = cls . __init__ # check if the fn has already been wrapped with inj...
def to_toml ( value , pretty = False ) : # noqa : unused - argument """Serializes the given value to TOML . : param value : the value to serialize : param pretty : this argument is ignored , as no TOML libraries support this type of operation : type pretty : bool : rtype : str"""
if not toml : raise NotImplementedError ( 'No supported TOML library available' ) return toml . dumps ( make_toml_friendly ( value ) ) . rstrip ( )
def MessageToString ( message , as_utf8 = False , as_one_line = False , pointy_brackets = False , use_index_order = False , float_format = None , use_field_number = False , descriptor_pool = None , indent = 0 ) : """Convert protobuf message to text format . Floating point values can be formatted compactly with 15...
out = TextWriter ( as_utf8 ) printer = _Printer ( out , indent , as_utf8 , as_one_line , pointy_brackets , use_index_order , float_format , use_field_number , descriptor_pool ) printer . PrintMessage ( message ) result = out . getvalue ( ) out . close ( ) if as_one_line : return result . rstrip ( ) return result
def admin_state ( self , ** kwargs ) : """Set interface administrative state . Args : int _ type ( str ) : Type of interface . ( gigabitethernet , tengigabitethernet , etc ) . name ( str ) : Name of interface . ( 1/0/5 , 1/0/10 , etc ) . enabled ( bool ) : Is the interface enabled ? ( True , False ) rbr...
int_type = kwargs . pop ( 'int_type' ) . lower ( ) name = kwargs . pop ( 'name' ) get = kwargs . pop ( 'get' , False ) if get : enabled = None else : enabled = kwargs . pop ( 'enabled' ) rbridge_id = kwargs . pop ( 'rbridge_id' , '1' ) callback = kwargs . pop ( 'callback' , self . _callback ) valid_int_types = ...
def convert_clip ( node , ** kwargs ) : """Map MXNet ' s Clip operator attributes to onnx ' s Clip operator and return the created node ."""
name , input_nodes , attrs = get_inputs ( node , kwargs ) a_min = np . float ( attrs . get ( 'a_min' , - np . inf ) ) a_max = np . float ( attrs . get ( 'a_max' , np . inf ) ) clip_node = onnx . helper . make_node ( "Clip" , input_nodes , [ name ] , name = name , min = a_min , max = a_max ) return [ clip_node ]
def init_logging ( ) : """Initialize logging ( set up forwarding to Go backend and sane defaults )"""
# Forward to Go backend logging . addLevelName ( TRACE_LEVEL , 'TRACE' ) logging . setLoggerClass ( AgentLogger ) rootLogger = logging . getLogger ( ) rootLogger . addHandler ( AgentLogHandler ( ) ) rootLogger . setLevel ( _get_py_loglevel ( datadog_agent . get_config ( 'log_level' ) ) ) # ` requests ` ( used in a lot ...
def send_keysequence_window_up ( self , window , keysequence , delay = 12000 ) : """Send key release ( up ) events for the given key sequence"""
_libxdo . xdo_send_keysequence_window_up ( self . _xdo , window , keysequence , ctypes . c_ulong ( delay ) )
def find_contours_level ( density , x , y , level , closed = False ) : """Find iso - valued density contours for a given level value Parameters density : 2d ndarray of shape ( M , N ) Kernel density estimate for which to compute the contours x : 2d ndarray of shape ( M , N ) or 1d ndarray of size M X - va...
if level >= 1 or level <= 0 : raise ValueError ( "`level` must be in (0,1), got '{}'!" . format ( level ) ) # level relative to maximum level = level * density . max ( ) # xy coordinates if len ( x . shape ) == 2 : assert np . all ( x [ : , 0 ] == x [ : , 1 ] ) x = x [ : , 0 ] if len ( y . shape ) == 2 : ...
def lvm_info ( self , name = None ) : """Call a program : param name : if specified - program will return information for that lvm - entity only . otherwise - all available entries are returned : return : tuple of str ( fields )"""
cmd = [ ] if self . sudo ( ) is False else [ 'sudo' ] cmd . extend ( [ self . command ( ) , '-c' ] ) if name is not None : cmd . append ( name ) output = subprocess . check_output ( cmd , timeout = self . cmd_timeout ( ) ) output = output . decode ( ) result = [ ] fields_count = self . fields_count ( ) for line in ...
def _default_value_cell_data_func ( self , tree_view_column , cell , model , iter , data = None ) : """Function set renderer properties for every single cell independently The function controls the editable and color scheme for every cell in the default value column according the use _ runtime _ value flag and ...
if isinstance ( self . model . state , LibraryState ) : use_runtime_value = model . get_value ( iter , self . USE_RUNTIME_VALUE_STORAGE_ID ) if use_runtime_value : cell . set_property ( "editable" , True ) cell . set_property ( 'text' , model . get_value ( iter , self . RUNTIME_VALUE_STORAGE_ID ...
def _write_frames ( self , handle ) : '''Write our frame data to the given file handle . Parameters handle : file Write metadata and C3D motion frames to the given file handle . The writer does not close the handle .'''
assert handle . tell ( ) == 512 * ( self . header . data_block - 1 ) scale = abs ( self . point_scale ) is_float = self . point_scale < 0 point_dtype = [ np . int16 , np . float32 ] [ is_float ] point_scale = [ scale , 1 ] [ is_float ] point_format = 'if' [ is_float ] raw = np . empty ( ( self . point_used , 4 ) , poin...
def Dirname ( self ) : """Get a new copied object with only the directory path ."""
result = self . Copy ( ) while 1 : last_directory = posixpath . dirname ( result . last . path ) if last_directory != "/" or len ( result ) <= 1 : result . last . path = last_directory # Make sure to clear the inode information . result . last . inode = None break result . Po...
def has_permissions ( self , object , group , operations ) : '''Check if this : class : ` Subject ` has permissions for ` ` operations ` ` on an ` ` object ` ` . It returns the number of valid permissions .'''
if self . is_superuser : return 1 else : models = self . session . router # valid permissions query = models . permission . for_object ( object , operation = operations ) objects = models [ models . role . permissions . model ] return objects . filter ( role = self . role . query ( ) , permissio...
def cli ( env , volume_id , schedule_type ) : """Disables snapshots on the specified schedule for a given volume"""
if ( schedule_type not in [ 'INTERVAL' , 'HOURLY' , 'DAILY' , 'WEEKLY' ] ) : raise exceptions . CLIAbort ( '--schedule-type must be INTERVAL, HOURLY, DAILY, or WEEKLY' ) block_manager = SoftLayer . BlockStorageManager ( env . client ) disabled = block_manager . disable_snapshots ( volume_id , schedule_type ) if dis...
def get ( self , pk , ** kwargs ) : """Get item from Model get : parameters : - in : path schema : type : integer name : pk - $ ref : ' # / components / parameters / get _ item _ schema ' responses : 200: description : Item from Model content : application / json : schema : type : object...
item = self . datamodel . get ( pk , self . _base_filters ) if not item : return self . response_404 ( ) _response = dict ( ) _args = kwargs . get ( "rison" , { } ) select_cols = _args . get ( API_SELECT_COLUMNS_RIS_KEY , [ ] ) _pruned_select_cols = [ col for col in select_cols if col in self . show_columns ] self ...
def metadata ( self , exportFormat = "default" , output = None , saveFolder = None , fileName = None ) : """exports metadata to the various supported formats Inputs : exportFormats - export metadata to the following formats : fgdc , inspire , iso19139 , iso19139-3.2 , iso19115 , arcgis , and default . defau...
url = "%s/info/metadata/metadata.xml" % self . root allowedFormats = [ "fgdc" , "inspire" , "iso19139" , "iso19139-3.2" , "iso19115" , "arcgis" , "default" ] if not exportFormat . lower ( ) in allowedFormats : raise Exception ( "Invalid exportFormat" ) if exportFormat . lower ( ) == "arcgis" : params = { } else...
def reflection_matrix_pow ( reflection_matrix : np . ndarray , exponent : float ) : """Raises a matrix with two opposing eigenvalues to a power . Args : reflection _ matrix : The matrix to raise to a power . exponent : The power to raise the matrix to . Returns : The given matrix raised to the given power...
# The eigenvalues are x and - x for some complex unit x . Determine x . squared_phase = np . dot ( reflection_matrix [ : , 0 ] , reflection_matrix [ 0 , : ] ) phase = complex ( np . sqrt ( squared_phase ) ) # Extract + x and - x eigencomponents of the matrix . i = np . eye ( reflection_matrix . shape [ 0 ] ) * phase po...
def traverse_ruffus_exception ( exceptions , options , log ) : """Traverse a RethrownJobError and output the exceptions Ruffus presents exceptions as 5 element tuples . The RethrownJobException has a list of exceptions like e . job _ exceptions = [ ( 5 - tuple ) , ( 5 - tuple ) , . . . ] ruffus < 2.7.0 had ...
exit_codes = [ ] for exc in exceptions : exit_code = do_ruffus_exception ( exc , options , log ) exit_codes . append ( exit_code ) return exit_codes [ 0 ]
def _parsed_items ( items , sep = _SEP , ** options ) : """: param items : List of pairs , [ ( key , value ) ] , or generator yields pairs : param sep : Seprator string : return : Generator to yield ( key , value ) pair of ' dic '"""
parse = _parse if options . get ( "ac_parse_value" ) else anyconfig . utils . noop for key , val in items : yield ( key , parse ( val , sep ) )
def send_message_tracked ( self , msg ) : """Send a message to the MUC with tracking . : param msg : The message to send . : type msg : : class : ` aioxmpp . Message ` . . warning : : Please read : ref : ` api - tracking - memory ` . This is especially relevant for MUCs because tracking is not guaranteed ...
msg . type_ = aioxmpp . MessageType . GROUPCHAT msg . to = self . _mucjid # see https : / / mail . jabber . org / pipermail / standards / 2017 - January / 032048 . html # NOQA # for a full discussion on the rationale for this . # TL ; DR : we want to help entities to discover that a message is related # to a MUC . msg ...
def hpsample ( self , data : [ 'SASdata' , str ] = None , cls : [ str , list ] = None , performance : str = None , target : [ str , list , dict ] = None , var : str = None , procopts : [ str , list , dict ] = None , stmtpassthrough : [ str , list , dict ] = None , ** kwargs : dict ) -> 'SASresults' : """Python meth...
async def on_isupport_chanlimit ( self , value ) : """Simultaneous channel limits for user ."""
self . _channel_limits = { } for entry in value . split ( ',' ) : types , limit = entry . split ( ':' ) # Assign limit to channel type group and add lookup entry for type . self . _channel_limits [ frozenset ( types ) ] = int ( limit ) for prefix in types : self . _channel_limit_groups [ prefix ...
def get_image_url ( self , selector , by = By . CSS_SELECTOR , timeout = settings . SMALL_TIMEOUT ) : """Extracts the URL from an image element on the page ."""
if self . timeout_multiplier and timeout == settings . SMALL_TIMEOUT : timeout = self . __get_new_timeout ( timeout ) return self . get_attribute ( selector , attribute = 'src' , by = by , timeout = timeout )
def transform_data ( self , data , request = None , response = None , context = None ) : transform = self . transform if hasattr ( transform , 'context' ) : self . transform . context = context """Runs the transforms specified on this endpoint with the provided data , returning the data modified"""
if transform and not ( isinstance ( transform , type ) and isinstance ( data , transform ) ) : if self . _params_for_transform : return transform ( data , ** self . _arguments ( self . _params_for_transform , request , response ) ) else : return transform ( data ) return data
def nvmlSystemGetProcessName ( pid ) : r"""* Gets name of the process with provided process id * For all products . * Returned process name is cropped to provided length . * name string is encoded in ANSI . * @ param pid The identifier of the process * @ param name Reference in which to return the process...
c_name = create_string_buffer ( 1024 ) fn = _nvmlGetFunctionPointer ( "nvmlSystemGetProcessName" ) ret = fn ( c_uint ( pid ) , c_name , c_uint ( 1024 ) ) _nvmlCheckReturn ( ret ) return bytes_to_str ( c_name . value )
def find_omega_min ( omega_levelu , Neu , Nl , xiu ) : r"""Find the smallest transition frequency for each field . > > > Ne = 6 > > > Nl = 2 > > > omega _ level = [ 0.0 , 100.0 , 100.0 , 200.0 , 200.0 , 300.0] > > > xi = np . zeros ( ( Nl , Ne , Ne ) ) > > > coup = [ [ ( 1 , 0 ) , ( 2 , 0 ) ] , [ ( 3 , 0 ...
omega_min = [ ] ; iu0 = [ ] ; ju0 = [ ] for l in range ( Nl ) : omegasl = [ ] for iu in range ( Neu ) : for ju in range ( iu ) : if xiu [ l , iu , ju ] == 1 : omegasl += [ ( omega_levelu [ iu ] - omega_levelu [ ju ] , iu , ju ) ] omegasl = list ( sorted ( omegasl ) ) ...
def _attempt_resumable_download ( self , key , fp , headers , cb , num_cb , torrent , version_id ) : """Attempts a resumable download . Raises ResumableDownloadException if any problems occur ."""
cur_file_size = get_cur_file_size ( fp , position_to_eof = True ) if ( cur_file_size and self . etag_value_for_current_download and self . etag_value_for_current_download == key . etag . strip ( '"\'' ) ) : # Try to resume existing transfer . if cur_file_size > key . size : raise ResumableDownloadException ...
def config_dir ( self ) : """Get the path to the user configuration directory . The directory is guaranteed to exist as a postcondition ( one may be created if none exist ) . If the application ' s ` ` . . . DIR ` ` environment variable is set , it is used as the configuration directory . Otherwise , plat...
# If environment variable is set , use it . if self . _env_var in os . environ : appdir = os . environ [ self . _env_var ] appdir = os . path . abspath ( os . path . expanduser ( appdir ) ) if os . path . isfile ( appdir ) : raise ConfigError ( u'{0} must be a directory' . format ( self . _env_var )...
def completed_stage ( self , stage ) : """Determine whether the pipeline ' s completed the stage indicated . : param pypiper . Stage stage : Stage to check for completion status . : return bool : Whether this pipeline ' s completed the indicated stage . : raises UnknownStageException : If the stage name given...
check_path = checkpoint_filepath ( stage , self . manager ) return os . path . exists ( check_path )
def pivot_wavelength ( self ) : """Get the bandpass ' pivot wavelength . Unlike calc _ pivot _ wavelength ( ) , this function will use a cached value if available ."""
wl = self . registry . _pivot_wavelengths . get ( ( self . telescope , self . band ) ) if wl is not None : return wl wl = self . calc_pivot_wavelength ( ) self . registry . register_pivot_wavelength ( self . telescope , self . band , wl ) return wl
def sc_imap ( self , viewer , event , msg = True ) : """Interactively change the intensity map by scrolling ."""
direction = self . get_direction ( event . direction ) self . _cycle_imap ( viewer , msg , direction = direction ) return True
def _legacy_init ( self , name , arr ) : """Legacy initialization method . Parameters name : str Name of corresponding NDArray . arr : NDArray NDArray to be initialized ."""
warnings . warn ( "\033[91mCalling initializer with init(str, NDArray) has been deprecated." "please use init(mx.init.InitDesc(...), NDArray) instead.\033[0m" , DeprecationWarning , stacklevel = 3 ) if not isinstance ( name , string_types ) : raise TypeError ( 'name must be string' ) if not isinstance ( arr , NDArr...
def build_tree_from_alignment ( aln , moltype = DNA , best_tree = False , params = None ) : """Returns a tree from alignment Will check MolType of aln object"""
if params is None : params = { } if moltype == DNA or moltype == RNA : params [ '-nt' ] = True elif moltype == PROTEIN : params [ '-nt' ] = False else : raise ValueError , "FastTree does not support moltype: %s" % moltype . label app = FastTree ( params = params ) if best_tree : raise NotImplemented...
def count_words ( text , to_lower = True , delimiters = DEFAULT_DELIMITERS ) : """If ` text ` is an SArray of strings or an SArray of lists of strings , the occurances of word are counted for each row in the SArray . If ` text ` is an SArray of dictionaries , the keys are tokenized and the values are the coun...
_raise_error_if_not_sarray ( text , "text" ) # # Compute word counts sf = _turicreate . SFrame ( { 'docs' : text } ) fe = _feature_engineering . WordCounter ( features = 'docs' , to_lower = to_lower , delimiters = delimiters , output_column_prefix = None ) output_sf = fe . fit_transform ( sf ) return output_sf [ 'docs'...
def _new_java_obj ( sc , java_class , * args ) : """Construct a new Java object ."""
java_obj = _jvm ( ) for name in java_class . split ( "." ) : java_obj = getattr ( java_obj , name ) java_args = [ _py2java ( sc , arg ) for arg in args ] return java_obj ( * java_args )
def send ( self , to , message ) : """Send a message to another process . Same as ` ` Process . send ` ` except that ` ` message ` ` is a protocol buffer . Returns immediately . : param to : The pid of the process to send a message . : type to : : class : ` PID ` : param message : The message to send : ...
super ( ProtobufProcess , self ) . send ( to , message . DESCRIPTOR . full_name , message . SerializeToString ( ) )
def tags ( ) : # type : ( ) - > List [ str ] """Returns all tags in the repo . Returns : list [ str ] : List of all tags in the repo , sorted as versions . All tags returned by this function will be parsed as if the contained versions ( using ` ` v : refname ` ` sorting ) ."""
return shell . run ( 'git tag --sort=v:refname' , capture = True , never_pretend = True ) . stdout . strip ( ) . splitlines ( )
def rmon_alarm_entry_alarm_rising_threshold ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) rmon = ET . SubElement ( config , "rmon" , xmlns = "urn:brocade.com:mgmt:brocade-rmon" ) alarm_entry = ET . SubElement ( rmon , "alarm-entry" ) alarm_index_key = ET . SubElement ( alarm_entry , "alarm-index" ) alarm_index_key . text = kwargs . pop ( 'alarm_index' ) alarm_rising_thresh...
def onPlanDeleted ( self , mid = None , plan = None , author_id = None , thread_id = None , thread_type = None , ts = None , metadata = None , msg = None , ) : """Called when the client is listening , and somebody deletes a plan : param mid : The action ID : param plan : Deleted plan : param author _ id : The...
log . info ( "{} deleted plan {} in {} ({})" . format ( author_id , plan , thread_id , thread_type . name ) )
def clean_text ( self , country , guess = False , ** kwargs ) : """Determine a two - letter country code based on an input . The input may be a country code , a country name , etc ."""
code = country . lower ( ) . strip ( ) if code in self . names : return code country = countrynames . to_code ( country , fuzzy = guess ) if country is not None : return country . lower ( )
def default_value ( self ) : """Get the default value of the field ."""
if self . name in tsdb_coded_attributes : return tsdb_coded_attributes [ self . name ] elif self . datatype == ':integer' : return - 1 else : return ''
def run ( ) : '''Dump on stdout the config flags required to compile pythran - generated code .'''
import argparse import distutils . sysconfig import pythran import numpy parser = argparse . ArgumentParser ( prog = 'pythran-config' , description = 'output build options for pythran-generated code' , epilog = "It's a megablast!" ) parser . add_argument ( '--compiler' , action = 'store_true' , help = 'print default co...
def _generate ( cls , strategy , params ) : """generate the object . Args : params ( dict ) : attributes to use for generating the object strategy : the strategy to use"""
if cls . _meta . abstract : raise errors . FactoryError ( "Cannot generate instances of abstract factory %(f)s; " "Ensure %(f)s.Meta.model is set and %(f)s.Meta.abstract " "is either not set or False." % dict ( f = cls . __name__ ) ) step = builder . StepBuilder ( cls . _meta , params , strategy ) return step . bui...
def project_list_folder ( object_id , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / project - xxxx / listFolder API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Folders - and - Deletion # API - method % 3A - % 2Fclass - xxxx % 2Flist...
return DXHTTPRequest ( '/%s/listFolder' % object_id , input_params , always_retry = always_retry , ** kwargs )
def compress ( x , y ) : """Given a x , y coordinate , encode in " compressed format " Returned is always 33 bytes ."""
polarity = "02" if y % 2 == 0 else "03" wrap = lambda x : x if not is_py2 : wrap = lambda x : bytes ( x , 'ascii' ) return unhexlify ( wrap ( "%s%0.64x" % ( polarity , x ) ) )
def p_document_shorthand_with_fragments ( self , p ) : """document : selection _ set fragment _ list"""
p [ 0 ] = Document ( definitions = [ Query ( selections = p [ 1 ] ) ] + p [ 2 ] )
def connect ( self ) : """Connects to the database server ."""
with warnings . catch_warnings ( ) : warnings . filterwarnings ( 'ignore' , '.*deprecated.*' ) self . _conn = client . connect ( init_command = self . init_fun , sql_mode = "NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO," "STRICT_ALL_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" , charset = confi...
def _indirect_jump_resolved ( self , jump , jump_addr , resolved_by , targets ) : """Called when an indirect jump is successfully resolved . : param IndirectJump jump : The resolved indirect jump , or None if an IndirectJump instance is not available . : param int jump _ addr : Address of the resolved indirec...
addr = jump . addr if jump is not None else jump_addr l . debug ( 'The indirect jump at %#x is successfully resolved by %s. It has %d targets.' , addr , resolved_by , len ( targets ) ) self . kb . resolved_indirect_jumps . add ( addr )
def phenotypesGenerator ( self , request ) : """Returns a generator over the ( phenotypes , nextPageToken ) pairs defined by the ( JSON string ) request"""
# TODO make paging work using SPARQL ? compoundId = datamodel . PhenotypeAssociationSetCompoundId . parse ( request . phenotype_association_set_id ) dataset = self . getDataRepository ( ) . getDataset ( compoundId . dataset_id ) phenotypeAssociationSet = dataset . getPhenotypeAssociationSet ( compoundId . phenotypeAsso...
def map_field ( field , func , dict_sequence ) : """Apply given function to value of given key in every dictionary in sequence and set the result as new value for that key ."""
for item in dict_sequence : try : item [ field ] = func ( item . get ( field , None ) ) yield item except ValueError : pass
def scheduled_function ( f , hints = None ) : """The Noodles schedule function decorator . The decorated function will return a workflow in stead of being applied immediately . This workflow can then be passed to a job scheduler in order to be run on any architecture supporting the current python environmen...
if hints is None : hints = { } if 'version' not in hints : try : source_bytes = inspect . getsource ( f ) . encode ( ) except Exception : pass else : m = hashlib . md5 ( ) m . update ( source_bytes ) hints [ 'version' ] = m . hexdigest ( ) @ wraps ( f ) def wrappe...
def _refresh_stats ( self ) : """Loads up the stats sheet created for this pipeline run and reads those stats into memory"""
# regex identifies all possible stats files . # regex = self . outfolder + " * _ stats . tsv " # stats _ files = glob . glob ( regex ) # stats _ files . insert ( self . pipeline _ stats _ file ) # last one is the current pipeline # for stats _ file in stats _ files : stats_file = self . pipeline_stats_file if os . path...
def loadLabeledPoints ( sc , path , minPartitions = None ) : """Load labeled points saved using RDD . saveAsTextFile . : param sc : Spark context : param path : file or directory path in any Hadoop - supported file system URI : param minPartitions : min number of partitions @ return : labeled data stored ...
minPartitions = minPartitions or min ( sc . defaultParallelism , 2 ) return callMLlibFunc ( "loadLabeledPoints" , sc , path , minPartitions )
def highlight ( self , selector , by = By . CSS_SELECTOR , loops = settings . HIGHLIGHTS , scroll = True ) : """This method uses fancy JavaScript to highlight an element . Used during demo _ mode . @ Params selector - the selector of the element to find by - the type of selector to search by ( Default : CSS...
selector , by = self . __recalculate_selector ( selector , by ) element = self . find_element ( selector , by = by , timeout = settings . SMALL_TIMEOUT ) if scroll : self . __slow_scroll_to_element ( element ) try : selector = self . convert_to_css_selector ( selector , by = by ) except Exception : # Don ' t hi...
def do_resolved ( self , subcmd , opts , * args ) : """Remove ' conflicted ' state on working copy files or directories . usage : resolved PATH . . . Note : this subcommand does not semantically resolve conflicts or remove conflict markers ; it merely removes the conflict - related artifact files and allo...
print "'svn %s' opts: %s" % ( subcmd , opts ) print "'svn %s' args: %s" % ( subcmd , args )
def honeycomb_lattice ( a , b , spacing , alternating_sites = False ) : """Generate a honeycomb lattice . Args : a ( Int ) : Number of lattice repeat units along x . b ( Int ) : Number of lattice repeat units along y . spacing ( Float ) : Distance between lattice sites . alternating _ sites ( Bool , optio...
if alternating_sites : site_labels = [ 'A' , 'B' , 'A' , 'B' ] else : site_labels = [ 'L' , 'L' , 'L' , 'L' ] unit_cell_lengths = np . array ( [ sqrt ( 3 ) , 3.0 , 0.0 ] ) * spacing cell_lengths = unit_cell_lengths * np . array ( [ a , b , 1.0 ] ) grid = np . array ( list ( range ( 1 , int ( a * b * 4 + 1 ) ) )...
def pkg_contents ( self ) : """Print packages contents"""
packages = self . args [ 1 : ] options = [ "-d" , "--display" ] if len ( self . args ) > 1 and self . args [ 0 ] in options : PackageManager ( packages ) . display ( ) else : usage ( "" )
def viewbox ( self ) : """Return bounding box of the viewport . : return : ( left , top , right , bottom ) ` tuple ` ."""
return self . left , self . top , self . right , self . bottom
def item_wegobject_adapter ( obj , request ) : """Adapter for rendering a list of : class : ` crabpy . gateway . Wegobject ` to json ."""
return { 'id' : obj . id , 'aard' : { 'id' : obj . aard . id , 'naam' : obj . aard . naam , 'definitie' : obj . aard . definitie } , 'centroid' : obj . centroid , 'bounding_box' : obj . bounding_box , 'metadata' : { 'begin_tijd' : obj . metadata . begin_tijd , 'begin_datum' : obj . metadata . begin_datum , 'begin_bewer...
def get_choice_selected_value ( self ) : """Returns the default selection from a choice menu Throws an error if this is not a choice parameter ."""
if 'choiceInfo' not in self . dto [ self . name ] : raise GPException ( 'not a choice parameter' ) choice_info_dto = self . dto [ self . name ] [ 'choiceInfo' ] if 'selectedValue' in choice_info_dto : return self . dto [ self . name ] [ 'choiceInfo' ] [ 'selectedValue' ] else : return None