signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _make_bright_pixel_mask ( intensity_mean , mask_factor = 5.0 ) : """Make of mask of all the brightest pixels"""
mask = np . zeros ( ( intensity_mean . data . shape ) , bool ) nebins = len ( intensity_mean . data ) sum_intensity = intensity_mean . data . sum ( 0 ) mean_intensity = sum_intensity . mean ( ) for i in range ( nebins ) : mask [ i , 0 : ] = sum_intensity > ( mask_factor * mean_intensity ) return HpxMap ( mask , int...
def dinf_downslope_direction ( a ) : """Get the downslope directions of an dinf direction value Args : a : Dinf value Returns : downslope directions"""
taud , d = DinfUtil . check_orthogonal ( a ) if d != - 1 : down = [ d ] return down else : if a < FlowModelConst . ne : # 129 = 1 + 128 down = [ 1 , 2 ] elif a < FlowModelConst . n : # 192 = 128 + 64 down = [ 2 , 3 ] elif a < FlowModelConst . nw : # 96 = 64 + 32 down = [ 3 , ...
def dump_json_file ( json_data , pwd_dir_path , dump_file_name ) : """dump json data to file"""
class PythonObjectEncoder ( json . JSONEncoder ) : def default ( self , obj ) : try : return super ( ) . default ( self , obj ) except TypeError : return str ( obj ) logs_dir_path = os . path . join ( pwd_dir_path , "logs" ) if not os . path . isdir ( logs_dir_path ) : os...
def fetchnumpybatches ( self ) : """Returns an iterator over all rows in the active result set generated with ` ` execute ( ) ` ` or ` ` executemany ( ) ` ` . : return : An iterator you can use to iterate over batches of rows of the result set . Each batch consists of an ` ` OrderedDict ` ` of NumPy ` ` Maske...
batchgen = self . _numpy_batch_generator ( ) column_names = [ description [ 0 ] for description in self . description ] for next_batch in batchgen : yield OrderedDict ( zip ( column_names , next_batch ) )
def _parse_and_verify ( self , candidate , offset ) : """Parses a phone number from the candidate using phonenumberutil . parse and verifies it matches the requested leniency . If parsing and verification succeed , a corresponding PhoneNumberMatch is returned , otherwise this method returns None . Arguments :...
try : # Check the candidate doesn ' t contain any formatting which would # indicate that it really isn ' t a phone number . if ( not fullmatch ( _MATCHING_BRACKETS , candidate ) or _PUB_PAGES . search ( candidate ) ) : return None # If leniency is set to VALID or stricter , we also want to skip # nu...
def _is_balanced ( root ) : """Return the height if the binary tree is balanced , - 1 otherwise . : param root : Root node of the binary tree . : type root : binarytree . Node | None : return : Height if the binary tree is balanced , - 1 otherwise . : rtype : int"""
if root is None : return 0 left = _is_balanced ( root . left ) if left < 0 : return - 1 right = _is_balanced ( root . right ) if right < 0 : return - 1 return - 1 if abs ( left - right ) > 1 else max ( left , right ) + 1
def argmax_with_score ( logits , axis = None ) : """Argmax along with the value ."""
axis = axis or len ( logits . get_shape ( ) ) - 1 predictions = tf . argmax ( logits , axis = axis ) logits_shape = shape_list ( logits ) prefix_shape , vocab_size = logits_shape [ : - 1 ] , logits_shape [ - 1 ] prefix_size = 1 for d in prefix_shape : prefix_size *= d # Flatten to extract scores flat_logits = tf . ...
def _onMotion ( self , evt ) : """Start measuring on an axis ."""
x = evt . GetX ( ) y = self . figure . bbox . height - evt . GetY ( ) evt . Skip ( ) FigureCanvasBase . motion_notify_event ( self , x , y , guiEvent = evt )
def get_value ( self , label , takeable = False ) : """Retrieve single value at passed index label . . deprecated : : 0.21.0 Please use . at [ ] or . iat [ ] accessors . Parameters index : label takeable : interpret the index as indexers , default False Returns value : scalar value"""
warnings . warn ( "get_value is deprecated and will be removed " "in a future release. Please use " ".at[] or .iat[] accessors instead" , FutureWarning , stacklevel = 2 ) return self . _get_value ( label , takeable = takeable )
def with_metaclass ( meta , * bases ) : """copied from https : / / github . com / Byron / bcore / blob / master / src / python / butility / future . py # L15"""
class metaclass ( meta ) : __call__ = type . __call__ __init__ = type . __init__ def __new__ ( cls , name , nbases , d ) : if nbases is None : return type . __new__ ( cls , name , ( ) , d ) # There may be clients who rely on this attribute to be set to a reasonable value , which ...
def get_umbrella_sampling_data ( ntherm = 11 , us_fc = 20.0 , us_length = 500 , md_length = 1000 , nmd = 20 ) : """Continuous MCMC process in an asymmetric double well potential using umbrella sampling . Parameters ntherm : int , optional , default = 11 Number of umbrella states . us _ fc : double , optiona...
dws = _DWS ( ) us_data = dws . us_sample ( ntherm = ntherm , us_fc = us_fc , us_length = us_length , md_length = md_length , nmd = nmd ) us_data . update ( centers = dws . centers ) return us_data
def expand_ranges ( value ) : """: param str value : The value to be " expanded " . : return : A generator to yield the different resulting values from expanding the eventual ranges present in the input value . > > > tuple ( expand _ ranges ( " Item [ 1-3 ] - Bla " ) ) ( ' Item 1 - Bla ' , ' Item 2 - Bla ' ...
match_dict = RANGE_REGEX . match ( value ) . groupdict ( ) # the regex is supposed to always match . . before = match_dict [ 'before' ] after = match_dict [ 'after' ] from_value = match_dict [ 'from' ] if from_value is None : yield value else : # we have a [ x - y ] range from_value = int ( from_value ) to_...
def _remove_bound_conditions ( agent , keep_criterion ) : """Removes bound conditions of agent such that keep _ criterion is False . Parameters agent : Agent The agent whose bound conditions we evaluate keep _ criterion : function Evaluates removal _ criterion ( a ) for each agent a in a bound condition ...
new_bc = [ ] for ind in range ( len ( agent . bound_conditions ) ) : if keep_criterion ( agent . bound_conditions [ ind ] . agent ) : new_bc . append ( agent . bound_conditions [ ind ] ) agent . bound_conditions = new_bc
def set_measurements ( test ) : """Test phase that sets a measurement ."""
test . measurements . level_none = 0 time . sleep ( 1 ) test . measurements . level_some = 8 time . sleep ( 1 ) test . measurements . level_all = 9 time . sleep ( 1 ) level_all = test . get_measurement ( 'level_all' ) assert level_all . value == 9
def tag ( self , tokens ) : """Return a list of ( ( token , tag ) , label ) tuples for a given list of ( token , tag ) tuples ."""
# Lazy load model first time we tag if not self . _loaded_model : self . load ( self . model ) features = [ self . _get_features ( tokens , i ) for i in range ( len ( tokens ) ) ] labels = self . _tagger . tag ( features ) tagged_sent = list ( zip ( tokens , labels ) ) return tagged_sent
def replace_lines_in_files ( search_string , replacement_line ) : """Finds lines containing the search string and replaces the whole line with the specified replacement string ."""
# have the user select some files paths = _s . dialogs . MultipleFiles ( 'DIS AND DAT|*.*' ) if paths == [ ] : return for path in paths : _shutil . copy ( path , path + ".backup" ) lines = read_lines ( path ) for n in range ( 0 , len ( lines ) ) : if lines [ n ] . find ( search_string ) >= 0 : ...
def plot_mag ( fignum , datablock , s , num , units , norm ) : """plots magnetization against ( de ) magnetizing temperature or field Parameters _ _ _ _ _ fignum : matplotlib figure number for plotting datablock : nested list of [ step , 0 , 0 , magnetization , 1 , quality ] s : string for title num : m...
global globals , graphmenu Ints = [ ] for plotrec in datablock : Ints . append ( plotrec [ 3 ] ) Ints . sort ( ) plt . figure ( num = fignum ) T , M , Tv , recnum = [ ] , [ ] , [ ] , 0 Mex , Tex , Vdif = [ ] , [ ] , [ ] recbak = [ ] for rec in datablock : if rec [ 5 ] == 'g' : if units == "T" : ...
def can_create ( self , locator ) : """Checks if this factory is able to create component by given locator . This method searches for all registered components and returns a locator for component it is able to create that matches the given locator . If the factory is not able to create a requested component i...
if locator == None : raise Exception ( "Locator cannot be null" ) # Iterate from the latest factories for factory in reversed ( self . _factories ) : locator = factory . can_create ( locator ) if locator != None : return locator return None
def mouseMoveEvent ( self , event ) : """Handle the mouse move event for a drag operation ."""
# if event . buttons ( ) & Qt . LeftButton and self . _ drag _ origin is not None : # dist = ( event . pos ( ) - self . _ drag _ origin ) . manhattanLength ( ) # if dist > = QApplication . startDragDistance ( ) : # self . do _ drag ( event . widget ( ) ) # self . _ drag _ origin = None # return # Don ' t returns widget...
def get_storage ( clear = False ) : """helper function to get annotation storage on the portal : param clear : If true is passed in , annotations will be cleared : returns : portal annotations : rtype : IAnnotations"""
portal = getUtility ( ISiteRoot ) annotations = IAnnotations ( portal ) if ANNOTATION_KEY not in annotations or clear : annotations [ ANNOTATION_KEY ] = OOBTree ( ) return annotations [ ANNOTATION_KEY ]
def CreateClass ( self , * args , ** kwargs ) : """Override the CreateClass method in MOFWBEMConnection For a description of the parameters , see : meth : ` pywbem . WBEMConnection . CreateClass ` ."""
cc = args [ 0 ] if args else kwargs [ 'NewClass' ] namespace = self . getns ( ) try : self . compile_ordered_classnames . append ( cc . classname ) # The following generates an exception for each new ns self . classes [ self . default_namespace ] [ cc . classname ] = cc except KeyError : self . classes ...
def add_constraint ( self , * args , ** kwargs ) : """TODO : add documentation args can be string representation ( length 1) func and strings to pass to function"""
# TODO : be smart enough to take kwargs ( especially for undoing a # remove _ constraint ) for kind , value ( expression ) , redo_kwargs = deepcopy ( kwargs ) if len ( args ) == 1 and isinstance ( args [ 0 ] , str ) and not _get_add_func ( _constraint , args [ 0 ] , return_none_if_not_found = True ) : # then only the e...
def timeout ( timeout_time , default ) : '''Decorate a method so it is required to execute in a given time period , or return a default value .'''
def timeout_function ( f ) : def f2 ( * args ) : def timeout_handler ( signum , frame ) : raise MethodTimer . DecoratorTimeout ( ) old_handler = signal . signal ( signal . SIGALRM , timeout_handler ) # triger alarm in timeout _ time seconds signal . alarm ( timeout_time )...
def locate_intersection_ranges ( self , starts , stops ) : """Locate the intersection with a set of ranges . Parameters starts : array _ like , int Range start values . stops : array _ like , int Range stop values . Returns loc : ndarray , bool Boolean array with location of entries found . loc _ ...
# check inputs starts = asarray_ndim ( starts , 1 ) stops = asarray_ndim ( stops , 1 ) check_dim0_aligned ( starts , stops ) # find indices of start and stop values in idx start_indices = np . searchsorted ( self , starts ) stop_indices = np . searchsorted ( self , stops , side = 'right' ) # find intervals overlapping ...
def match ( line , keyword ) : """If the first part of line ( modulo blanks ) matches keyword , returns the end of that line . Otherwise checks if keyword is anywhere in the line and returns that section , else returns None"""
line = line . lstrip ( ) length = len ( keyword ) if line [ : length ] == keyword : return line [ length : ] else : if keyword in line : return line [ line . index ( keyword ) : ] else : return None
def answer ( self , c , details ) : """Answer will provide all necessary feedback for the caller Args : c ( int ) : HTTP Code details ( dict ) : Response payload Returns : dict : Response payload Raises : ErrAtlasBadRequest ErrAtlasUnauthorized ErrAtlasForbidden ErrAtlasNotFound ErrAtlasMethod...
if c in [ Settings . SUCCESS , Settings . CREATED , Settings . ACCEPTED ] : return details elif c == Settings . BAD_REQUEST : raise ErrAtlasBadRequest ( c , details ) elif c == Settings . UNAUTHORIZED : raise ErrAtlasUnauthorized ( c , details ) elif c == Settings . FORBIDDEN : raise ErrAtlasForbidden (...
def element_to_dict ( elem_to_parse , element_path = None , recurse = True ) : """: return : an element losslessly as a dictionary . If recurse is True , the element ' s children are included , otherwise they are omitted . The resulting Dictionary will have the following attributes : - name : the name of the ...
element = get_element ( elem_to_parse , element_path ) if element is not None : converted = { _ELEM_NAME : element . tag , _ELEM_TEXT : element . text , _ELEM_TAIL : element . tail , _ELEM_ATTRIBS : element . attrib , _ELEM_CHILDREN : [ ] } if recurse is True : for child in element : convert...
def getConfigDirectory ( ) : """Determines the platform - specific config directory location for ue4cli"""
if platform . system ( ) == 'Windows' : return os . path . join ( os . environ [ 'APPDATA' ] , 'ue4cli' ) else : return os . path . join ( os . environ [ 'HOME' ] , '.config' , 'ue4cli' )
def _change_secure_boot_settings ( self , property , value ) : """Change secure boot settings on the server ."""
system = self . _get_host_details ( ) # find the BIOS URI if ( 'links' not in system [ 'Oem' ] [ 'Hp' ] or 'SecureBoot' not in system [ 'Oem' ] [ 'Hp' ] [ 'links' ] ) : msg = ( ' "SecureBoot" resource or feature is not ' 'supported on this system' ) raise exception . IloCommandNotSupportedError ( msg ) secure_b...
def underscore ( name ) : '''Transform CamelCase - > snake _ case .'''
s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , name ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
def update_list_widget ( self ) : """Update list widget when radio button is clicked ."""
# Get selected radio button radio_button_checked_id = self . input_button_group . checkedId ( ) # No radio button checked , then default value = None if radio_button_checked_id > - 1 : selected_dict = list ( self . _parameter . options . values ( ) ) [ radio_button_checked_id ] if selected_dict . get ( 'type' )...
def process_docstring ( app , what , name , obj , options , lines ) : """Process the docstring for a given python object . Called when autodoc has read and processed a docstring . ` lines ` is a list of docstring lines that ` _ process _ docstring ` modifies in place to change what Sphinx outputs . The foll...
result_lines = lines if app . config . napoleon_numpy_docstring : docstring = ExtendedNumpyDocstring ( result_lines , app . config , app , what , name , obj , options ) result_lines = docstring . lines ( ) if app . config . napoleon_google_docstring : docstring = ExtendedGoogleDocstring ( result_lines , app...
def on_timer ( self , evt ) : """Keep watching the mouse displacement via timer Needed since EVT _ MOVE doesn ' t happen once the mouse gets outside the frame"""
ctrl_is_down = wx . GetKeyState ( wx . WXK_CONTROL ) ms = wx . GetMouseState ( ) # New initialization when keys pressed change if self . _key_state != ctrl_is_down : self . _key_state = ctrl_is_down # Keep state at click self . _click_ms_x , self . _click_ms_y = ms . x , ms . y self . _click_frame_x , s...
def update_value_map ( layer , exposure_key = None ) : """Assign inasafe values according to definitions for a vector layer . : param layer : The vector layer . : type layer : QgsVectorLayer : param exposure _ key : The exposure key . : type exposure _ key : str : return : The classified vector layer . ...
output_layer_name = assign_inasafe_values_steps [ 'output_layer_name' ] output_layer_name = output_layer_name % layer . keywords [ 'layer_purpose' ] keywords = layer . keywords inasafe_fields = keywords [ 'inasafe_fields' ] classification = None if keywords [ 'layer_purpose' ] == layer_purpose_hazard [ 'key' ] : if...
def prune_anomalies ( e_seq , smoothed_errors , max_error_below_e , anomaly_indices ) : """Helper method that removes anomalies which don ' t meet a minimum separation from next anomaly ."""
# min accepted perc decrease btwn max errors in anomalous sequences MIN_PERCENT_DECREASE = 0.05 e_seq_max , smoothed_errors_max = [ ] , [ ] for error_seq in e_seq : if len ( smoothed_errors [ error_seq [ 0 ] : error_seq [ 1 ] ] ) > 0 : sliced_errors = smoothed_errors [ error_seq [ 0 ] : error_seq [ 1 ] ] ...
def t_name ( self , s ) : r'[ A - Za - z _ ] [ A - Za - z _ 0-9 ] *'
if s in RESERVED_WORDS : self . add_token ( s . upper ( ) , s ) else : self . add_token ( 'NAME' , s )
def range_to_numeric ( ranges ) : """Converts a sequence of string ranges to a sequence of floats . E . g . : : > > > range _ to _ numeric ( [ ' 1 uV ' , ' 2 mV ' , ' 1 V ' ] ) [1E - 6 , 0.002 , 1.0]"""
values , units = zip ( * ( r . split ( ) for r in ranges ) ) # Detect common unit . unit = os . path . commonprefix ( [ u [ : : - 1 ] for u in units ] ) # Strip unit to get just the SI prefix . prefixes = ( u [ : - len ( unit ) ] for u in units ) # Convert string value and scale with prefix . values = [ float ( v ) * S...
def enumerate_local_modules ( tokens , path ) : """Returns a list of modules inside * tokens * that are local to * path * . * * Note : * * Will recursively look inside * path * for said modules ."""
# Have to get a list of all modules before we can do anything else modules = enumerate_imports ( tokens ) local_modules = [ ] parent = "" # Now check the local dir for matching modules for root , dirs , files in os . walk ( path ) : if not parent : parent = os . path . split ( root ) [ 1 ] for f in file...
def target_to_ipv6_cidr ( target ) : """Attempt to return a IPv6 CIDR list from a target string ."""
splitted = target . split ( '/' ) if len ( splitted ) != 2 : return None try : start_packed = inet_pton ( socket . AF_INET6 , splitted [ 0 ] ) block = int ( splitted [ 1 ] ) except ( socket . error , ValueError ) : return None if block <= 0 or block > 126 : return None start_value = int ( binascii ....
def stop_ppp_link ( self ) : '''stop the link'''
if self . ppp_fd == - 1 : return try : self . mpself . select_extra . pop ( self . ppp_fd ) os . close ( self . ppp_fd ) os . waitpid ( self . pid , 0 ) except Exception : pass self . pid = - 1 self . ppp_fd = - 1 print ( "stopped ppp link" )
def build_static ( self ) : """Build static files"""
if not os . path . isdir ( self . build_static_dir ) : os . makedirs ( self . build_static_dir ) copy_tree ( self . static_dir , self . build_static_dir ) if self . webassets_cmd : self . webassets_cmd . build ( )
def init_generic_serial_dut ( contextlist , conf , index , args ) : """Initializes a local hardware dut"""
port = conf [ 'serial_port' ] baudrate = ( args . baudrate if args . baudrate else conf . get ( "application" , { } ) . get ( "baudrate" , 115200 ) ) serial_config = { } if args . serial_rtscts : serial_config [ "serial_rtscts" ] = args . serial_rtscts elif args . serial_xonxoff : serial_config [ "serial_xonxof...
def check ( self , val ) : """Make sure given value is consistent with this ` Key ` specification . NOTE : if ` type ` is ' None ' , then ` listable ` also is * not * checked ."""
# If there is no ` type ` requirement , everything is allowed if self . type is None : return True is_list = isinstance ( val , list ) # If lists are not allowed , and this is a list - - > false if not self . listable and is_list : return False # ` is _ number ` already checks for either list or single value if...
def p_static_scalar_namespace_name ( p ) : '''static _ scalar : namespace _ name | NS _ SEPARATOR namespace _ name | NAMESPACE NS _ SEPARATOR namespace _ name'''
if len ( p ) == 2 : p [ 0 ] = ast . Constant ( p [ 1 ] , lineno = p . lineno ( 1 ) ) elif len ( p ) == 3 : p [ 0 ] = ast . Constant ( p [ 1 ] + p [ 2 ] , lineno = p . lineno ( 1 ) ) else : p [ 0 ] = ast . Constant ( p [ 1 ] + p [ 2 ] + p [ 3 ] , lineno = p . lineno ( 1 ) )
def reqHeadTimeStamp ( self , contract : Contract , whatToShow : str , useRTH : bool , formatDate : int = 1 ) -> datetime . datetime : """Get the datetime of earliest available historical data for the contract . Args : contract : Contract of interest . useRTH : If True then only show data from within Regula...
return self . _run ( self . reqHeadTimeStampAsync ( contract , whatToShow , useRTH , formatDate ) )
def fn_std ( self , a , axis = None ) : """Compute the standard deviation of an array , ignoring NaNs . : param a : The array . : return : The standard deviation of the array ."""
return numpy . nanstd ( self . _to_ndarray ( a ) , axis = axis )
def outputZip ( self , figtype = 'png' ) : """Outputs the report in a zip container . Figs and tabs as pngs and excells . Args : figtype ( str ) : Figure type of images in the zip folder ."""
from zipfile import ZipFile with ZipFile ( self . outfile + '.zip' , 'w' ) as zipcontainer : zipcontainer . writestr ( 'summary.txt' , '# {}\n\n{}\n{}' . format ( self . title , self . p , ( '\n## Conclusion\n' if self . conclusion else '' ) + self . conclusion ) . encode ( ) ) c = count ( 1 ) for section i...
def _find_header_flat ( self ) : """Find header elements in a table , if possible . This case handles situations where ' < th > ' elements are not within a row ( ' < tr > ' )"""
nodes = self . _node . contents . filter_tags ( matches = ftag ( 'th' ) , recursive = False ) if not nodes : return self . _log ( 'found header outside rows (%d <th> elements)' % len ( nodes ) ) return nodes
def resolution ( file_ , resolution_string ) : """A filter to return the URL for the provided resolution of the thumbnail ."""
if sorl_settings . THUMBNAIL_DUMMY : dummy_source = sorl_settings . THUMBNAIL_DUMMY_SOURCE source = dummy_source . replace ( '%(width)s' , '(?P<width>[0-9]+)' ) source = source . replace ( '%(height)s' , '(?P<height>[0-9]+)' ) source = re . compile ( source ) try : resolution = decimal . Dec...
def vote_count ( self ) : """Returns the total number of votes cast across all the poll ' s options ."""
return Vote . objects . filter ( content_type = ContentType . objects . get ( app_label = 'poll' , model = 'polloption' ) , object_id__in = [ o . id for o in self . polloption_set . all ( ) ] ) . aggregate ( Sum ( 'vote' ) ) [ 'vote__sum' ] or 0
async def FindTools ( self , arch , major , minor , number , series ) : '''arch : str major : int minor : int number : Number series : str Returns - > typing . Union [ _ ForwardRef ( ' Error ' ) , typing . Sequence [ ~ Tools ] ]'''
# map input types to rpc msg _params = dict ( ) msg = dict ( type = 'Client' , request = 'FindTools' , version = 1 , params = _params ) _params [ 'arch' ] = arch _params [ 'major' ] = major _params [ 'minor' ] = minor _params [ 'number' ] = number _params [ 'series' ] = series reply = await self . rpc ( msg ) return re...
def model ( x_train , y_train , x_test , y_test ) : """Model providing function : Create Keras model with double curly brackets dropped - in as needed . Return value has to be a valid python dictionary with two customary keys : - loss : Specify a numeric evaluation metric to be minimized - status : Just use...
from keras . models import Sequential from keras . layers . core import Dense , Dropout , Activation from keras . optimizers import RMSprop keras_model = Sequential ( ) keras_model . add ( Dense ( 512 , input_shape = ( 784 , ) ) ) keras_model . add ( Activation ( 'relu' ) ) keras_model . add ( Dropout ( { { uniform ( 0...
def gossip_connect_curve ( self , public_key , format , * args ) : """Set - up gossip discovery with CURVE enabled ."""
return lib . zyre_gossip_connect_curve ( self . _as_parameter_ , public_key , format , * args )
def run ( self ) : """Append version number to gvar / _ _ init _ _ . py"""
with open ( 'src/gvar/__init__.py' , 'a' ) as gvfile : gvfile . write ( "\n__version__ = '%s'\n" % GVAR_VERSION ) _build_py . run ( self )
def process_nxml_file ( fname , output_fmt = 'json' , outbuf = None , cleanup = True , ** kwargs ) : """Return processor with Statements extracted by reading an NXML file . Parameters fname : str The path to the NXML file to be read . output _ fmt : Optional [ str ] The output format to obtain from Sparse...
sp = None out_fname = None try : out_fname = run_sparser ( fname , output_fmt , outbuf , ** kwargs ) sp = process_sparser_output ( out_fname , output_fmt ) except Exception as e : logger . error ( "Sparser failed to run on %s." % fname ) logger . exception ( e ) finally : if out_fname is not None an...
def new ( cls , shapes , start_x , start_y , x_scale , y_scale ) : """Return a new | FreeformBuilder | object . The initial pen location is specified ( in local coordinates ) by ( * start _ x * , * start _ y * ) ."""
return cls ( shapes , int ( round ( start_x ) ) , int ( round ( start_y ) ) , x_scale , y_scale )
def setAllowedTypes ( self , allowed_types ) : """Set the allowed association types , checking to make sure each combination is valid ."""
for ( assoc_type , session_type ) in allowed_types : checkSessionType ( assoc_type , session_type ) self . allowed_types = allowed_types
def _clone_file_everywhere ( self , finfo ) : """Clone file ( * src _ editor * widget ) in all editorstacks Cloning from the first editorstack in which every single new editor is created ( when loading or creating a new file )"""
for editorstack in self . editorstacks [ 1 : ] : editor = editorstack . clone_editor_from ( finfo , set_current = False ) self . register_widget_shortcuts ( editor )
def kill_filler_process ( self ) : """terminates the process that fills this buffers : class : ` ~ alot . walker . PipeWalker ` ."""
if self . proc : if self . proc . is_alive ( ) : self . proc . terminate ( )
def translate ( self , exc ) : """Return whether or not to do translation ."""
from boto . exception import StorageResponseError if isinstance ( exc , StorageResponseError ) : if exc . status == 404 : return self . error_cls ( str ( exc ) ) return None
def V_vertical_spherical_concave ( D , a , h ) : r'''Calculates volume of a vertical tank with a concave spherical bottom , according to [ 1 ] _ . No provision for the top of the tank is made here . . . math : : V = \ frac { \ pi } { 12 } \ left [ 3D ^ 2h + \ frac { a } { 2 } ( 3D ^ 2 + 4a ^ 2 ) + ( a + h ) ^...
if h < abs ( a ) : Vf = pi / 12 * ( 3 * D ** 2 * h + a / 2. * ( 3 * D ** 2 + 4 * a ** 2 ) + ( a + h ) ** 3 * ( 4 - ( 3 * D ** 2 + 12 * a ** 2 ) / ( 2. * a * ( a + h ) ) ) ) else : Vf = pi / 12 * ( 3 * D ** 2 * h + a / 2. * ( 3 * D ** 2 + 4 * a ** 2 ) ) return Vf
def get_c_extension ( support_legacy = False , system_zstd = False , name = 'zstd' , warnings_as_errors = False , root = None ) : """Obtain a distutils . extension . Extension for the C extension . ` ` support _ legacy ` ` controls whether to compile in legacy zstd format support . ` ` system _ zstd ` ` control...
actual_root = os . path . abspath ( os . path . dirname ( __file__ ) ) root = root or actual_root sources = set ( [ os . path . join ( actual_root , p ) for p in ext_sources ] ) if not system_zstd : sources . update ( [ os . path . join ( actual_root , p ) for p in zstd_sources ] ) if support_legacy : s...
def getConf ( self , conftype ) : '''conftype must be a Zooborg constant'''
if conftype not in [ ZooConst . CLIENT , ZooConst . WORKER , ZooConst . BROKER ] : raise Exception ( 'Zooborg.getConf: invalid type' ) zooconf = { } # TODO : specialconf entries for the mock if conftype == ZooConst . CLIENT : zooconf [ 'broker' ] = { } zooconf [ 'broker' ] [ 'connectionstr' ] = b"tcp://loca...
def add_shadow ( img , vertices_list ) : """Add shadows to the image . From https : / / github . com / UjjwalSaxena / Automold - - Road - Augmentation - Library Args : img ( np . array ) : vertices _ list ( list ) : Returns :"""
non_rgb_warning ( img ) input_dtype = img . dtype needs_float = False if input_dtype == np . float32 : img = from_float ( img , dtype = np . dtype ( 'uint8' ) ) needs_float = True elif input_dtype not in ( np . uint8 , np . float32 ) : raise ValueError ( 'Unexpected dtype {} for RandomSnow augmentation' . f...
def validate_confusables_email ( value ) : """Validator which disallows ' dangerous ' email addresses likely to represent homograph attacks . An email address is ' dangerous ' if either the local - part or the domain , considered on their own , are mixed - script and contain one or more characters appearing...
if '@' not in value : return local_part , domain = value . split ( '@' ) if confusables . is_dangerous ( local_part ) or confusables . is_dangerous ( domain ) : raise ValidationError ( CONFUSABLE_EMAIL , code = 'invalid' )
def stable_cho_factor ( x , tiny = _TINY ) : """NAME : stable _ cho _ factor PURPOSE : Stable version of the cholesky decomposition INPUT : x - ( sc . array ) positive definite matrix tiny - ( double ) tiny number to add to the covariance matrix to make the decomposition stable ( has a default ) OUTPU...
return linalg . cho_factor ( x + numpy . sum ( numpy . diag ( x ) ) * tiny * numpy . eye ( x . shape [ 0 ] ) , lower = True )
def getdoc ( object ) : """Get the documentation string for an object . All tabs are expanded to spaces . To clean up docstrings that are indented to line up with blocks of code , any whitespace than can be uniformly removed from the second line onwards is removed ."""
try : doc = object . __doc__ except AttributeError : return None if not isinstance ( doc , ( str , unicode ) ) : return None try : lines = string . split ( string . expandtabs ( doc ) , '\n' ) except UnicodeError : return None else : margin = None for line in lines [ 1 : ] : content ...
def field_cache_to_index_pattern ( self , field_cache ) : """Return a . kibana index - pattern doc _ type"""
mapping_dict = { } mapping_dict [ 'customFormats' ] = "{}" mapping_dict [ 'title' ] = self . index_pattern # now post the data into . kibana mapping_dict [ 'fields' ] = json . dumps ( field_cache , separators = ( ',' , ':' ) ) # in order to post , we need to create the post string mapping_str = json . dumps ( mapping_d...
def set_resolution ( self , resolution = 1090 ) : """Set the resolution of the sensor The resolution value is the amount of steps recorded in a single Gauss . The possible options are : Recommended Gauss range Resolution Gauss per bit 0.88 Ga 1370 0.73 mGa 1.3 Ga 1090 0.92 mGa 1.9 Ga 820 1.22 mGa 2.5 Ga...
options = { 1370 : 0 , 1090 : 1 , 820 : 2 , 660 : 3 , 440 : 4 , 390 : 5 , 330 : 6 , 230 : 7 } if resolution not in options . keys ( ) : raise Exception ( 'Resolution of {} steps is not supported' . format ( resolution ) ) self . resolution = resolution config_b = 0 config_b &= options [ resolution ] << 5 self . i2c...
def recursive_cov ( self , cov , length , mean , chain , scaling = 1 , epsilon = 0 ) : r"""Compute the covariance recursively . Return the new covariance and the new mean . . . math : : C _ k & = \ frac { 1 } { k - 1 } ( \ sum _ { i = 1 } ^ k x _ i x _ i ^ T - k \ bar { x _ k } \ bar { x _ k } ^ T ) C _ n &...
n = length + len ( chain ) k = length new_mean = self . recursive_mean ( mean , length , chain ) t0 = k * np . outer ( mean , mean ) t1 = np . dot ( chain . T , chain ) t2 = n * np . outer ( new_mean , new_mean ) t3 = epsilon * np . eye ( cov . shape [ 0 ] ) new_cov = ( k - 1 ) / ( n - 1. ) * cov + scaling / ( n - 1. )...
def create_account_api_key ( self , account_id , body , ** kwargs ) : # noqa : E501 """Create a new API key . # noqa : E501 An endpoint for creating a new API key . There is no default value for the owner ID and it must be from the same account where the new API key is created . * * Example usage : * * ` curl - X...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . create_account_api_key_with_http_info ( account_id , body , ** kwargs ) # noqa : E501 else : ( data ) = self . create_account_api_key_with_http_info ( account_id , body , ** kwargs ) # noqa : E501 return da...
def T_i ( v_vars : List [ fl . Var ] , mass : np . ndarray , i : int ) : """Make Fluxion with the kinetic energy of body i"""
# Check that the lengths are consistent assert len ( v_vars ) == 3 * len ( mass ) # Mass of the body i m = mass [ i ] # kineteic energy = 1/2 * mass * speed ^ 2 T = ( 0.5 * m ) * flux_v2 ( v_vars , i ) return T
def add_slice_db ( self , fid , slice_end , md5 ) : '''在数据库中加入上传任务分片信息'''
sql = 'INSERT INTO slice VALUES(?, ?, ?)' self . cursor . execute ( sql , ( fid , slice_end , md5 ) ) self . check_commit ( )
def plot ( self , figure_list ) : """plots the data contained in self . data , which should be a dictionary or a deque of dictionaries for the latter use the last entry Args : figure _ list : list of figure objects that are passed to self . get _ axes _ layout to get axis objects for plotting"""
# if there is not data we do not plot anything if not self . data : return # if plot function is called when script is not running we request a plot refresh if not self . is_running : self . _plot_refresh = True axes_list = self . get_axes_layout ( figure_list ) if self . _plot_refresh is True : self . _plo...
def resolved_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 with Playbook variables automatically resolved ."""
if not self . _parsed_resolved : # only resolve once self . args ( ) # create new args Namespace for resolved args self . _default_args_resolved = Namespace ( ) # iterate over args and resolve any playbook variables for arg in vars ( self . _default_args ) : arg_val = getattr ( self . _defau...
def call ( ) : """Execute command line helper ."""
args = get_arguments ( ) # Set up logging if args . debug : log_level = logging . DEBUG elif args . quiet : log_level = logging . WARN else : log_level = logging . INFO setup_logging ( log_level ) abode = None if not args . cache : if not args . username or not args . password : raise Exception ...
def fd_solve ( self ) : """w = fd _ solve ( ) where coeff is the sparse coefficient matrix output from function coeff _ matrix and qs is the array of loads ( stresses ) Sparse solver for one - dimensional flexure of an elastic plate"""
if self . Debug : print ( "qs" , self . qs . shape ) print ( "Te" , self . Te . shape ) self . calc_max_flexural_wavelength ( ) print ( "maxFlexuralWavelength_ncells', self.maxFlexuralWavelength_ncells" ) if self . Solver == "iterative" or self . Solver == "Iterative" : if self . Debug : pri...
def insert ( self , xmltext ) : """Insert the LIGO _ LW metadata in the xmltext string into the database . @ return : message received ( may be empty ) from LDBD Server as a string"""
msg = "INSERT\0" + xmltext + "\0" self . sfile . write ( msg ) ret , output = self . __response__ ( ) reply = str ( output [ 0 ] ) if ret : msg = "Error executing insert on server %d:%s" % ( ret , reply ) raise LDBDClientException , msg return reply
def copyError ( self , to ) : """Save the original error to the new place ."""
if to is None : to__o = None else : to__o = to . _o ret = libxml2mod . xmlCopyError ( self . _o , to__o ) return ret
def set_widgets ( self ) : """Set widgets on the layer purpose tab ."""
self . clear_further_steps ( ) # Set widgets self . lstCategories . clear ( ) self . lblDescribeCategory . setText ( '' ) self . lblIconCategory . setPixmap ( QPixmap ( ) ) self . lblSelectCategory . setText ( category_question % self . parent . layer . name ( ) ) purposes = self . purposes_for_layer ( ) for purpose in...
def sky2px ( wcs , ra , dec , dra , ddec , cell , beam ) : """convert a sky region to pixel positions"""
dra = beam if dra < beam else dra # assume every source is at least as large as the psf ddec = beam if ddec < beam else ddec offsetDec = int ( ( ddec / 2. ) / cell ) offsetRA = int ( ( dra / 2. ) / cell ) if offsetDec % 2 == 1 : offsetDec += 1 if offsetRA % 2 == 1 : offsetRA += 1 raPix , decPix = map ( int , wc...
def load_dat ( self , delimiter = ',' ) : """Load the dat file into internal data structures , ` ` self . _ data ` `"""
try : data = np . loadtxt ( self . _dat_file , delimiter = ',' ) except ValueError : data = np . loadtxt ( self . _dat_file ) self . _data = data
def get_annotations ( df , annotations , kind = 'lines' , theme = None , ** kwargs ) : """Generates an annotations object Parameters : df : DataFrame Original DataFrame of values annotations : dict or list Dictionary of annotations { x _ point : text } or List of Plotly annotations"""
for key in list ( kwargs . keys ( ) ) : if key not in __ANN_KWARGS : raise Exception ( "Invalid keyword : '{0}'" . format ( key ) ) theme_data = getTheme ( theme ) kwargs [ 'fontcolor' ] = kwargs . pop ( 'fontcolor' , theme_data [ 'annotations' ] [ 'fontcolor' ] ) kwargs [ 'arrowcolor' ] = kwargs . pop ( 'a...
def _model ( self , beta ) : """Creates the structure of the model ( model matrices , etc ) Parameters beta : np . array Contains untransformed starting values for the latent variables Returns lambda : np . array Contains the values for the conditional volatility series Y : np . array Contains the l...
Y = np . array ( self . data [ self . max_lag : self . data . shape [ 0 ] ] ) X = np . ones ( Y . shape [ 0 ] ) scores = np . zeros ( Y . shape [ 0 ] ) # Transform latent variables parm = np . array ( [ self . latent_variables . z_list [ k ] . prior . transform ( beta [ k ] ) for k in range ( beta . shape [ 0 ] ) ] ) l...
def _covert_to_hashable ( data ) : r"""Args : data ( ? ) : Returns : CommandLine : python - m utool . util _ hash _ covert _ to _ hashable Example : > > > # DISABLE _ DOCTEST > > > from utool . util _ hash import * # NOQA > > > from utool . util _ hash import _ covert _ to _ hashable # NOQA > > > ...
if isinstance ( data , six . binary_type ) : hashable = data prefix = b'TXT' elif util_type . HAVE_NUMPY and isinstance ( data , np . ndarray ) : if data . dtype . kind == 'O' : msg = '[ut] hashing ndarrays with dtype=object is unstable' warnings . warn ( msg , RuntimeWarning ) hasha...
def __load_config ( self ) : '''Find and load . scuba . yml'''
# top _ path is where . scuba . yml is found , and becomes the top of our bind mount . # top _ rel is the relative path from top _ path to the current working directory , # and is where we ' ll set the working directory in the container ( relative to # the bind mount point ) . try : top_path , top_rel = find_config...
def tag_add ( package , tag , pkghash ) : """Add a new tag for a given package hash . Unlike versions , tags can have an arbitrary format , and can be modified and deleted . When a package is pushed , it gets the " latest " tag ."""
team , owner , pkg = parse_package ( package ) session = _get_session ( team ) session . put ( "{url}/api/tag/{owner}/{pkg}/{tag}" . format ( url = get_registry_url ( team ) , owner = owner , pkg = pkg , tag = tag ) , data = json . dumps ( dict ( hash = _match_hash ( package , pkghash ) ) ) )
def sphofs ( lat1 , lon1 , r , pa , tol = 1e-2 , rmax = None ) : """Offset from one location on the sphere to another . This function is given a start location , expressed as a latitude and longitude , a distance to offset , and a direction to offset ( expressed as a bearing , AKA position angle ) . It uses t...
if rmax is not None and np . abs ( r ) > rmax : raise ValueError ( 'sphofs radius value %f is too big for ' 'our approximation' % r ) lat2 = lat1 + r * np . cos ( pa ) lon2 = lon1 + r * np . sin ( pa ) / np . cos ( lat2 ) if tol is not None : s = sphdist ( lat1 , lon1 , lat2 , lon2 ) if np . any ( np . abs ...
def file_filter ( ifn : str , indir : str , opts : Namespace ) -> bool : """Determine whether to process ifn . We con ' t process : 1 ) Anything in a directory having a path element that begins with " _ " 2 ) Really , really big files 3 ) Temporary lists of know errors : param ifn : input file name : para...
# If it looks like we ' re processing a URL as an input file , skip the suffix check if '://' in ifn : return True if not ifn . endswith ( '.json' ) : return False if indir and ( indir . startswith ( "_" ) or "/_" in indir or any ( dn in indir for dn in opts . skipdirs ) ) : return False if opts . skipfns a...
def _union_copy ( dict1 , dict2 ) : """Internal wrapper to keep one level of copying out of play , for efficiency . Only copies data on dict2 , but will alter dict1."""
for key , value in dict2 . items ( ) : if key in dict1 and isinstance ( value , dict ) : dict1 [ key ] = _union_copy ( dict1 [ key ] , value ) else : dict1 [ key ] = copy . deepcopy ( value ) return dict1
def delete_episode ( db , aid , episode ) : """Delete an episode ."""
db . cursor ( ) . execute ( 'DELETE FROM episode WHERE aid=:aid AND type=:type AND number=:number' , { 'aid' : aid , 'type' : episode . type , 'number' : episode . number , } )
def keystroke_output ( self , settings , key , user_data ) : """If the gconf var scroll _ output be changed , this method will be called and will set the scroll _ on _ output in all terminals open ."""
for i in self . guake . notebook_manager . iter_terminals ( ) : i . set_scroll_on_output ( settings . get_boolean ( key ) )
def image_placeholder ( width : Union [ int , str ] = 1920 , height : Union [ int , str ] = 1080 ) -> str : """Generate a link to the image placeholder . : param width : Width of image . : param height : Height of image . : return : URL to image placeholder ."""
url = 'http://placehold.it/{width}x{height}' return url . format ( width = width , height = height )
def compress ( self , setup ) : """Returns the compressed graph according to the given experimental setup Parameters setup : : class : ` caspo . core . setup . Setup ` Experimental setup used to compress the graph Returns caspo . core . graph . Graph Compressed graph"""
designated = set ( setup . nodes ) zipped = self . copy ( ) marked = [ ( n , d ) for n , d in self . nodes ( data = True ) if n not in designated and not d . get ( 'compressed' , False ) ] while marked : for node , _ in sorted ( marked ) : backward = zipped . predecessors ( node ) forward = zipped ....
def show_schemas ( schemaname ) : """Show anchore document schemas ."""
ecode = 0 try : schemas = { } schema_dir = os . path . join ( contexts [ 'anchore_config' ] [ 'pkg_dir' ] , 'schemas' ) for f in os . listdir ( schema_dir ) : sdata = { } try : with open ( os . path . join ( schema_dir , f ) , 'r' ) as FH : sdata = json . loads ( ...
def _find_by_id ( self , resource , _id , parent = None ) : """Find the document by Id . If parent is not provided then on routing exception try to find using search ."""
def is_found ( hit ) : if 'exists' in hit : hit [ 'found' ] = hit [ 'exists' ] return hit . get ( 'found' , False ) args = self . _es_args ( resource ) try : # set the parent if available if parent : args [ 'parent' ] = parent hit = self . elastic ( resource ) . get ( id = _id , ** args ...
def simxSetObjectParent ( clientID , objectHandle , parentObject , keepInPlace , operationMode ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
return c_SetObjectParent ( clientID , objectHandle , parentObject , keepInPlace , operationMode )
def page_data_frame ( df , pager_argv = [ 'less' ] , ** kwargs ) : """Render a DataFrame as text and send it to a terminal pager program ( e . g . ` less ` ) , so that one can browse a full table conveniently . df The DataFrame to view pager _ argv : default ` ` [ ' less ' ] ` ` A list of strings passed t...
import codecs , subprocess , sys pager = subprocess . Popen ( pager_argv , shell = False , stdin = subprocess . PIPE , close_fds = True ) try : enc = codecs . getwriter ( sys . stdout . encoding or 'utf8' ) ( pager . stdin ) df . to_string ( enc , ** kwargs ) finally : enc . close ( ) pager . stdin . cl...
def update_gen_report ( self , role , file , original ) : """Update the role state and adjust the gen totals ."""
state = self . report [ "state" ] if not os . path . exists ( self . paths [ file ] ) : state [ "ok_role" ] += 1 self . report [ "roles" ] [ role ] [ "state" ] = "ok" elif ( self . report [ "roles" ] [ role ] [ file ] != original and self . report [ "roles" ] [ role ] [ "state" ] != "ok" ) : state [ "change...
def token_list_width ( tokenlist ) : """Return the character width of this token list . ( Take double width characters into account . ) : param tokenlist : List of ( token , text ) or ( token , text , mouse _ handler ) tuples ."""
ZeroWidthEscape = Token . ZeroWidthEscape return sum ( get_cwidth ( c ) for item in tokenlist for c in item [ 1 ] if item [ 0 ] != ZeroWidthEscape )