signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _clean_bindings ( self , bindings ) : """Remove all of the expressions from bindings : param bindings : The bindings to clean : type bindings : list : return : The cleaned bindings : rtype : list"""
return list ( filter ( lambda b : not isinstance ( b , QueryExpression ) , bindings ) )
def spherical_histogram ( data = None , radial_bins = "numpy" , theta_bins = 16 , phi_bins = 16 , transformed = False , * args , ** kwargs ) : """Facade construction function for the SphericalHistogram ."""
dropna = kwargs . pop ( "dropna" , True ) data = _prepare_data ( data , transformed = transformed , klass = SphericalHistogram , dropna = dropna ) if isinstance ( theta_bins , int ) : theta_range = ( 0 , np . pi ) if "theta_range" in "kwargs" : theta_range = kwargs [ "theta_range" ] elif "range" in ...
def feed_ssldata ( self , data ) : """Feed SSL record level data into the pipe . The data must be a bytes instance . It is OK to send an empty bytes instance . This can be used to get ssldata for a handshake initiated by this endpoint . Return a ( ssldata , appdata ) tuple . The ssldata element is a list of...
if self . _state == self . S_UNWRAPPED : # If unwrapped , pass plaintext data straight through . return ( [ ] , [ data ] if data else [ ] ) ssldata = [ ] ; appdata = [ ] self . _need_ssldata = False if data : self . _incoming . write ( data ) try : if self . _state == self . S_DO_HANDSHAKE : # Call do _ han...
def _register_endpoints ( self , providers ) : """Register methods to endpoints : type providers : list [ str ] : rtype : list [ ( str , ( ( satosa . context . Context , Any ) - > satosa . response . Response , Any ) ) ] : param providers : A list of backend providers : return : A list of endpoint / method ...
url_map = [ ] for endp_category in self . endpoints : for binding , endp in self . endpoints [ endp_category ] . items ( ) : valid_providers = "" for provider in providers : valid_providers = "{}|^{}" . format ( valid_providers , provider ) valid_providers = valid_providers . lst...
def _apply_scsi_controller ( adapter , adapter_type , bus_sharing , key , bus_number , operation ) : '''Returns a vim . vm . device . VirtualDeviceSpec object specifying to add / edit a SCSI controller adapter SCSI controller adapter name adapter _ type SCSI controller adapter type eg . paravirtual bus ...
log . trace ( 'Configuring scsi controller adapter=%s adapter_type=%s ' 'bus_sharing=%s key=%s bus_number=%s' , adapter , adapter_type , bus_sharing , key , bus_number ) scsi_spec = vim . vm . device . VirtualDeviceSpec ( ) if adapter_type == 'lsilogic' : summary = 'LSI Logic' scsi_spec . device = vim . vm . de...
def read_config_file ( filename ) : """Reads the configuration file . : param filename : the name of the file containing the configuration . : type filename : str : returns : A tuple where the first element is a list of sections , and the second element is a map containing the configuration ( options and ...
# Creating the config parser config = ConfigParser . RawConfigParser ( allow_no_value = True ) config . optionxform = str config . read ( filename ) # Checking the section names sections = None try : sections = sorted ( [ int ( i ) for i in config . sections ( ) ] ) except ValueError : # Section not integer msg...
def get_template ( template_name , using = None ) : """Loads and returns a template for the given name . Raises TemplateDoesNotExist if no such template exists ."""
engines = _engine_list ( using ) for engine in engines : try : return engine . get_template ( template_name ) except TemplateDoesNotExist as e : pass raise TemplateDoesNotExist ( template_name )
def ts_to_df ( metadata ) : """Create a data frame from one TimeSeries object : param dict metadata : Time Series dictionary : return dict : One data frame per table , organized in a dictionary by name"""
logger_dataframes . info ( "enter ts_to_df" ) dfs = { } # Plot the variable + values vs year , age , depth ( whichever are available ) dfs [ "paleoData" ] = pd . DataFrame ( _plot_ts_cols ( metadata ) ) # Plot the chronology variables + values in a data frame dfs [ "chronData" ] = _get_key_data ( metadata , "chronData_...
def find ( cls , searched_dir , pattern ) : """Find matched files . It does not include symbolic file in the result ."""
Log . debug ( 'find {0} with pattern: {1}' . format ( searched_dir , pattern ) ) matched_files = [ ] for root_dir , dir_names , file_names in os . walk ( searched_dir , followlinks = False ) : for file_name in file_names : if fnmatch . fnmatch ( file_name , pattern ) : file_path = os . path . jo...
def WriteClientCrashInfo ( self , client_id , crash_info , cursor = None ) : """Writes a new client crash record ."""
query = """ SET @now = NOW(6); INSERT INTO client_crash_history (client_id, timestamp, crash_info) VALUES (%(client_id)s, @now, %(crash_info)s); UPDATE clients SET last_crash_timestamp = @now WHERE client_id = %(client_id)s """ params = { "client_id" : db_utils . ClientIDToInt ( c...
def approve ( self , request , * args , ** kwargs ) : """Approves the considered post and retirects the user to the success URL ."""
self . object = self . get_object ( ) success_url = self . get_success_url ( ) self . object . approved = True self . object . save ( ) messages . success ( self . request , self . success_message ) return HttpResponseRedirect ( success_url )
def _represent_match_traversal ( match_traversal ) : """Emit MATCH query code for an entire MATCH traversal sequence ."""
output = [ ] output . append ( _first_step_to_match ( match_traversal [ 0 ] ) ) for step in match_traversal [ 1 : ] : output . append ( _subsequent_step_to_match ( step ) ) return u'' . join ( output )
def read_geojson ( filename ) : """Reads a geojson file containing an STObject and initializes a new STObject from the information in the file . Args : filename : Name of the geojson file Returns : an STObject"""
json_file = open ( filename ) data = json . load ( json_file ) json_file . close ( ) times = data [ "properties" ] [ "times" ] main_data = dict ( timesteps = [ ] , masks = [ ] , x = [ ] , y = [ ] , i = [ ] , j = [ ] ) attribute_data = dict ( ) for feature in data [ "features" ] : for main_name in main_data . keys (...
def _get_features ( self ) : """Decide which layers to render based on current zoom level and view type ."""
if self . _satellite : return [ ( "water" , [ ] , [ ] ) ] elif self . _zoom <= 2 : return [ ( "water" , [ ] , [ ] ) , ( "marine_label" , [ ] , [ 1 ] ) , ] elif self . _zoom <= 7 : return [ ( "admin" , [ ] , [ ] ) , ( "water" , [ ] , [ ] ) , ( "road" , [ "motorway" ] , [ ] ) , ( "country_label" , [ ] , [ ] )...
def mark_failed ( self , clsname , msg ) : '''Marks the tracer as failed with the given exception class name : code : ` clsname ` and message : code : ` msg ` . May only be called in the started state and only if the tracer is not already marked as failed . Note that this does not end the tracer ! Once a tr...
self . nsdk . tracer_error ( self . handle , clsname , msg )
def mach2tas ( M , h ) : """True airspeed ( tas ) to mach number conversion"""
a = vsound ( h ) tas = M * a return tas
def plot_pole ( map_axis , plon , plat , A95 , label = '' , color = 'k' , edgecolor = 'k' , marker = 'o' , markersize = 20 , legend = 'no' ) : """This function plots a paleomagnetic pole and A95 error ellipse on a cartopy map axis . Before this function is called , a plot needs to be initialized with code such ...
if not has_cartopy : print ( '-W- cartopy must be installed to run ipmag.plot_pole' ) return A95_km = A95 * 111.32 map_axis . scatter ( plon , plat , marker = marker , color = color , edgecolors = edgecolor , s = markersize , label = label , zorder = 101 , transform = ccrs . Geodetic ( ) ) equi ( map_axis , plo...
def last_entry ( self , data_revisar = None , key_revisar = None ) : """Obtiene el Timestamp del último valor de la base de datos seleecionada , junto con el no de entradas ( filas ) total de dicho paquete de datos . : param data _ revisar : ( OPC ) Se puede pasar un dataframe específico : param key _ revis...
key_revisar = key_revisar or self . masterkey data_revisar = self . data if data_revisar is None else data_revisar # return tmax , num _ entradas if key_revisar in data_revisar . keys ( ) : data_rev = data_revisar [ key_revisar ] return data_rev . index [ - 1 ] . to_pydatetime ( ) , len ( data_rev ) else : ...
def require_settings ( self , args , options ) : """Load the ZAPPA _ SETTINGS as we expect it ."""
if not options . has_key ( 'environment' ) : print ( "You must call deploy with an environment name. \n python manage.py deploy <environment>" ) raise ImproperlyConfigured from django . conf import settings if not 'ZAPPA_SETTINGS' in dir ( settings ) : print ( "Please define your ZAPPA_SETTINGS in your sett...
def leb128_decode ( data ) : """Decodes a LEB128 - encoded unsigned integer . : param BufferedIOBase data : The buffer containing the LEB128 - encoded integer to decode . : return : The decoded integer . : rtype : int"""
result = 0 shift = 0 while True : character = data . read ( 1 ) if len ( character ) == 0 : raise bitcoin . core . SerializationTruncationError ( 'Invalid LEB128 integer' ) b = ord ( character ) result |= ( b & 0x7f ) << shift if b & 0x80 == 0 : break shift += 7 return result
def createTargetOrder ( self , quantity , parentId = 0 , target = 0. , orderType = None , transmit = True , group = None , tif = "DAY" , rth = False , account = None ) : """Creates TARGET order"""
order = self . createOrder ( quantity , price = target , transmit = transmit , orderType = dataTypes [ "ORDER_TYPE_LIMIT" ] if orderType == None else orderType , ocaGroup = group , parentId = parentId , rth = rth , tif = tif , account = account ) return order
def set_stream ( self , stream_id ) : """Set group stream ."""
self . _group [ 'stream_id' ] = stream_id yield from self . _server . group_stream ( self . identifier , stream_id ) _LOGGER . info ( 'set stream to %s on %s' , stream_id , self . friendly_name )
def generate_page_toc ( soup ) : """Return page - level ( ~ list of headings ) TOC template data for soup"""
# Maybe we don ' t want to show all the headings . E . g . , it ' s common for a page # to have just one H1 , a title at the top . Our heuristic : if a page has just # one heading of some outline level , don ' t show it . found_depth_counts = collections . defaultdict ( int ) for tag in soup . find_all ( _heading_re ) ...
def catalog_to_cells ( catalog , radius , order , include_fallback = True , ** kwargs ) : """Convert a catalog to a set of cells . This function is intended to be used via ` catalog _ to _ moc ` but is available for separate usage . It takes the same arguments as that function . This function uses the Healp...
nside = 2 ** order # Ensure catalog is in ICRS coordinates . catalog = catalog . icrs # Ensure radius is in radians . if isinstance ( radius , Quantity ) : radius = radius . to ( radian ) . value else : radius = radius * pi / ( 180.0 * 3600.0 ) # Convert coordinates to position vectors . phi = catalog . ra . ra...
def batch ( args ) : """% prog batch all . cds * . anchors Compute Ks values for a set of anchors file . This will generate a bunch of work directories for each comparisons . The anchorsfile should be in the form of specie1 . species2 . anchors ."""
from jcvi . apps . grid import MakeManager p = OptionParser ( batch . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) cdsfile = args [ 0 ] anchors = args [ 1 : ] workdirs = [ "." . join ( op . basename ( x ) . split ( "." ) [ : 2 ] ) for x in anchors ] for...
def detect_FASST ( dat_orig , s_freq , time , opts , submethod = 'rms' ) : """Spindle detection based on FASST method , itself based on Moelle et al . (2002 ) . Parameters dat _ orig : ndarray ( dtype = ' float ' ) vector with the data for one channel s _ freq : float sampling frequency time : ndarray...
dat_det = transform_signal ( dat_orig , s_freq , 'butter' , opts . det_butter ) det_value = percentile ( dat_det , opts . det_thresh ) if submethod == 'abs' : dat_det = transform_signal ( dat_det , s_freq , 'abs' ) elif submethod == 'rms' : dat_det = transform_signal ( dat_det , s_freq , 'moving_rms' , opts . m...
def destroy_s3 ( app = '' , env = 'dev' , ** _ ) : """Destroy S3 Resources for _ app _ in _ env _ . Args : app ( str ) : Application name env ( str ) : Deployment environment / account name Returns : boolean : True if destroyed sucessfully"""
session = boto3 . Session ( profile_name = env ) client = session . resource ( 's3' ) generated = get_details ( app = app , env = env ) archaius = generated . archaius ( ) bucket = client . Bucket ( archaius [ 'bucket' ] ) for item in bucket . objects . filter ( Prefix = archaius [ 'path' ] ) : item . Object ( ) . ...
def _reduce_and_smooth ( obs_tidy , goal_size ) : """Uses interpolation to reduce the number of observations ( cells ) . This is useful for plotting functions that otherwise will ignore most of the cells ' values . The reduction and smoothing is only done per column Parameters obs _ tidy : Pandas DataFram...
if obs_tidy . shape [ 0 ] < goal_size : return obs_tidy else : # usually , a large number of cells can not be plotted , thus # it is useful to reduce the number of cells plotted while # smoothing the values . This should be similar to an interpolation # but done per row and not for the entire image . from scipy...
def max ( self , default = None ) : """Calculate the maximum value over the time series . : param default : Value to return as a default should the calculation not be possible . : return : Float representing the maximum value or ` None ` ."""
return numpy . asscalar ( numpy . max ( self . values ) ) if self . values else default
def get_package_manager ( self , target = None ) : """Returns package manager for target argument or global config ."""
package_manager = None if target : target_package_manager_field = target . payload . get_field ( 'package_manager' ) if target_package_manager_field : package_manager = target_package_manager_field . value return self . node_distribution . get_package_manager ( package_manager = package_manager )
def _run ( self , circuit : circuits . Circuit , param_resolver : study . ParamResolver , repetitions : int ) -> Dict [ str , np . ndarray ] : """Run a simulation , mimicking quantum hardware . Args : circuit : The circuit to simulate . param _ resolver : Parameters to run with the program . repetitions : N...
raise NotImplementedError ( )
def build_includes ( cls , include_packages ) : """The default include strategy is to add a star ( * ) wild card after all sub - packages ( but not the main package ) . This strategy is compatible with py2app and bbfreeze . Example ( From SaltStack 2014.7 ) : salt salt . fileserver . * salt . modules . * ...
includes , package_root_paths = cls . _split_packages ( include_packages ) for package_path , package_name in six . iteritems ( package_root_paths ) : if re . search ( r'__init__.py.*$' , package_path ) : # Looks like a package . Walk the directory and see if there are more . package_files = set ( [ os . pa...
def unpack ( cls , msg , client , server , request_id ) : """Parse message and return an ` OpMsg ` . Takes the client message as bytes , the client and server socket objects , and the client request id ."""
payload_document = OrderedDict ( ) flags , = _UNPACK_UINT ( msg [ : 4 ] ) pos = 4 if flags != 0 and flags != 2 : raise ValueError ( 'OP_MSG flag must be 0 or 2 not %r' % ( flags , ) ) while pos < len ( msg ) : payload_type , = _UNPACK_BYTE ( msg [ pos : pos + 1 ] ) pos += 1 payload_size , = _UNPACK_INT ...
def copy ( src , dst ) : """Handle the copying of a file or directory . The destination basedir _ must _ exist . : param src : A string containing the path of the source to copy . If the source ends with a ' / ' , will become a recursive directory copy of source . : param dst : A string containing the path ...
try : shutil . copytree ( src , dst ) except OSError as exc : if exc . errno == errno . ENOTDIR : shutil . copy ( src , dst ) else : raise
def _split_token_to_subtokens ( token , subtoken_dict , max_subtoken_length ) : """Splits a token into subtokens defined in the subtoken dict ."""
ret = [ ] start = 0 token_len = len ( token ) while start < token_len : # Find the longest subtoken , so iterate backwards . for end in xrange ( min ( token_len , start + max_subtoken_length ) , start , - 1 ) : subtoken = token [ start : end ] if subtoken in subtoken_dict : ret . append ...
def copy ( self , src , dst , other_system = None ) : """Copy object of the same storage . Args : src ( str ) : Path or URL . dst ( str ) : Path or URL . other _ system ( pycosio . storage . azure . _ AzureBaseSystem subclass ) : The source storage system ."""
with _handle_azure_exception ( ) : self . client . copy_file ( copy_source = ( other_system or self ) . _format_src_url ( src , self ) , ** self . get_client_kwargs ( dst ) )
def set_options ( pool_or_cursor , row_instance ) : "for connection - level options that need to be set on Row instances"
# todo : move around an Options object instead for option in ( 'JSON_READ' , ) : setattr ( row_instance , option , getattr ( pool_or_cursor , option , None ) ) return row_instance
def get_question_content ( self , number : str ) -> str : """取得課程中特定題目內容"""
try : # 操作所需資訊 params = { 'hwId' : number } # 取得資料 response = self . __session . get ( self . __url + '/showHomework' , params = params , timeout = 0.5 , verify = False ) soup = BeautifulSoup ( response . text , 'html.parser' ) # 處理題目內容的 \ r result = '' content = soup . find ( 'body' ) . get...
def destroy ( vm_ , call = None ) : '''Destroy a lxc container'''
destroy_opt = __opts__ . get ( 'destroy' , False ) profiles = __opts__ . get ( 'profiles' , { } ) profile = __opts__ . get ( 'profile' , __opts__ . get ( 'internal_lxc_profile' , [ ] ) ) path = None if profile and profile in profiles : path = profiles [ profile ] . get ( 'path' , None ) action = __opts__ . get ( 'a...
def OnMove ( self , event ) : """Main window move event"""
# Store window position in config position = self . main_window . GetScreenPositionTuple ( ) config [ "window_position" ] = repr ( position )
def GetArtifactDependencies ( rdf_artifact , recursive = False , depth = 1 ) : """Return a set of artifact dependencies . Args : rdf _ artifact : RDF object artifact . recursive : If True recurse into dependencies to find their dependencies . depth : Used for limiting recursion depth . Returns : A set o...
deps = set ( ) for source in rdf_artifact . sources : # ARTIFACT is the legacy name for ARTIFACT _ GROUP # per : https : / / github . com / ForensicArtifacts / artifacts / pull / 143 # TODO ( user ) : remove legacy support after migration . if source . type in ( rdf_artifacts . ArtifactSource . SourceType . ARTIFAC...
async def reset_webhook ( self , check = True ) -> bool : """Reset webhook : param check : check before deleting : return :"""
if check : wh = await self . bot . get_webhook_info ( ) if not wh . url : return False return await self . bot . delete_webhook ( )
def credential_delete ( self , * ids ) : """Delete one or more credentials . : param ids : one or more credential ids"""
return self . raw_query ( "credential" , "delete" , data = { "credentials" : [ { "id" : str ( id ) } for id in ids ] } )
def to_jsonf ( self , fpath : str , encoding : str = 'utf8' , indent : int = None , ignore_none : bool = True , ignore_empty : bool = False ) -> str : """From instance to json file : param fpath : Json file path : param encoding : Json file encoding : param indent : Number of indentation : param ignore _ no...
return util . save_jsonf ( traverse ( self , ignore_none , force_value = True , ignore_empty = ignore_empty ) , fpath , encoding , indent )
def get_import_lines ( self ) : """Take the stored imports and converts them to lines"""
if self . imports : return [ "from %s import %s" % ( value , key ) for key , value in self . imports . items ( ) ] else : return [ ]
def create_chart ( self , html_path = 'index.html' , data_path = 'data.json' , js_path = 'rickshaw.min.js' , css_path = 'rickshaw.min.css' , html_prefix = '' ) : '''Save bearcart output to HTML and JSON . Parameters html _ path : string , default ' index . html ' Path for html output data _ path : string , ...
self . template_vars . update ( { 'data_path' : str ( data_path ) , 'js_path' : js_path , 'css_path' : css_path , 'chart_id' : self . chart_id , 'y_axis_id' : self . y_axis_id , 'legend_id' : self . legend_id , 'slider_id' : self . slider_id } ) self . _build_graph ( ) html = self . env . get_template ( 'bcart_template...
def _set_attr ( self , attr ) : """Given some text attribute , set the current cursor attributes appropriately ."""
if attr in text : self . _text_attr ( attr ) elif attr in colors [ "foreground" ] : self . _color_attr ( "foreground" , attr ) elif attr in colors [ "background" ] : self . _color_attr ( "background" , attr )
def leaders ( self , current_page , ** options ) : '''Retrieve a page of leaders from the leaderboard . @ param current _ page [ int ] Page to retrieve from the leaderboard . @ param options [ Hash ] Options to be used when retrieving the page from the leaderboard . @ return a page of leaders from the leaderb...
return self . leaders_in ( self . leaderboard_name , current_page , ** options )
def gdal_translate ( src , dst , options ) : """a simple wrapper for ` gdal . Translate < https : / / gdal . org / python / osgeo . gdal - module . html # Translate > ` _ Parameters src : str , : osgeo : class : ` ogr . DataSource ` or : osgeo : class : ` gdal . Dataset ` the input data set dst : str the ...
out = gdal . Translate ( dst , src , options = gdal . TranslateOptions ( ** options ) ) out = None
def _is_unpacked_egg ( path ) : """Determine if given path appears to be an unpacked egg ."""
return ( _is_egg_path ( path ) and os . path . isfile ( os . path . join ( path , 'EGG-INFO' , 'PKG-INFO' ) ) )
def tds7_process_result ( self ) : """Reads and processes COLMETADATA stream This stream contains a list of returned columns . Stream format link : http : / / msdn . microsoft . com / en - us / library / dd357363 . aspx"""
self . log_response_message ( 'got COLMETADATA' ) r = self . _reader # read number of columns and allocate the columns structure num_cols = r . get_smallint ( ) # This can be a DUMMY results token from a cursor fetch if num_cols == - 1 : return self . param_info = None self . has_status = False self . ret_status = ...
def create_CTL ( fname , tbl_name , col_list , TRUNC_OR_APPEND , delim = ',' ) : """create _ CTL ( fname _ control _ file , tbl _ name , src _ file , cols , ' TRUNCATE ' )"""
with open ( fname , 'w' ) as ct : ct . write ( 'LOAD DATA\n' ) ct . write ( TRUNC_OR_APPEND + '\n' ) ct . write ( 'into table ' + tbl_name + '\n' ) ct . write ( "fields terminated by '" + delim + "'\n" ) ct . write ( 'optionally Enclosed by \'"\'\n' ) ct . write ( 'TRAILING NULLCOLS\n' ) ct...
def info_to_datatype_v4 ( signed , little_endian ) : """map CAN signal to MDF integer types Parameters signed : bool signal is flagged as signed in the CAN database little _ endian : bool signal is flagged as little endian ( Intel ) in the CAN database Returns datatype : int integer code for MDF cha...
if signed : if little_endian : datatype = v4c . DATA_TYPE_SIGNED_INTEL else : datatype = v4c . DATA_TYPE_SIGNED_MOTOROLA else : if little_endian : datatype = v4c . DATA_TYPE_UNSIGNED_INTEL else : datatype = v4c . DATA_TYPE_UNSIGNED_MOTOROLA return datatype
def pending_confirmations ( self ) : """Return all published messages that have yet to be acked , nacked , or returned . : return : [ ( int , Published ) ]"""
return sorted ( [ ( idx , msg ) for idx , msg in enumerate ( self . published_messages ) if not msg . future . done ( ) ] , key = lambda x : x [ 1 ] . delivery_tag )
def cmd_gimbal_point ( self , args ) : '''control gimbal pointing'''
if len ( args ) != 3 : print ( "usage: gimbal point ROLL PITCH YAW" ) return ( roll , pitch , yaw ) = ( float ( args [ 0 ] ) , float ( args [ 1 ] ) , float ( args [ 2 ] ) ) self . master . mav . mount_control_send ( self . target_system , self . target_component , pitch * 100 , roll * 100 , yaw * 100 , 0 )
def cli_plugin_add_help ( help ) : """Decorator generator that adds the cli help to the cli plugin based on the decorated function Args : help ( str ) : help string for the cli plugin Returns : function : Decorator that builds or extends the cliplugin for the decorated function , setting the given help ...
def decorator ( func ) : if not isinstance ( func , CLIPluginFuncWrapper ) : func = CLIPluginFuncWrapper ( do_run = func ) func . set_help ( help ) return func return decorator
def _draw_visible_area ( self , painter ) : """Draw the visible area . This method does not take folded blocks into account . : type painter : QtGui . QPainter"""
if self . editor . visible_blocks : start = self . editor . visible_blocks [ 0 ] [ - 1 ] end = self . editor . visible_blocks [ - 1 ] [ - 1 ] rect = QtCore . QRect ( ) rect . setX ( 0 ) rect . setY ( start . blockNumber ( ) * self . get_marker_height ( ) ) rect . setWidth ( self . sizeHint ( ) ....
def get_cover_image ( self , size = SIZE_EXTRA_LARGE ) : """Returns a URI to the cover image size can be one of : SIZE _ EXTRA _ LARGE SIZE _ LARGE SIZE _ MEDIUM SIZE _ SMALL"""
if "image" not in self . info : self . info [ "image" ] = _extract_all ( self . _request ( self . ws_prefix + ".getInfo" , cacheable = True ) , "image" ) return self . info [ "image" ] [ size ]
def rmod ( self , other , axis = "columns" , level = None , fill_value = None ) : """Mod this DataFrame against another DataFrame / Series / scalar . Args : other : The object to use to apply the div against this . axis : The axis to div over . level : The Multilevel index level to apply div over . fill _...
return self . _binary_op ( "rmod" , other , axis = axis , level = level , fill_value = fill_value )
def _log ( file_list , list_name , in_path ) : """Logs result at debug level"""
file_names = '\n' . join ( file_list ) LOG . debug ( "\nDiscovered %(size)d %(name)s file(s) in %(path)s:\n" "%(files)s\n" , { 'size' : len ( file_list ) , 'name' : list_name , 'path' : in_path , 'files' : file_names } )
def remove_service_listener ( self , listener ) : """Unregisters a service listener : param listener : The service listener : return : True if the listener has been unregistered"""
with self . __svc_lock : try : data = self . __listeners_data . pop ( listener ) spec_listeners = self . __svc_listeners [ data . specification ] spec_listeners . remove ( data ) if not spec_listeners : del self . __svc_listeners [ data . specification ] return Tr...
def _extract_comments ( self ) : """Retrieve all comments from the file"""
self . _det_file . seek ( 0 , 0 ) for line in self . _det_file . readlines ( ) : line = line . strip ( ) if line . startswith ( '#' ) : self . add_comment ( line [ 1 : ] )
def get_or_create_calendar_for_object ( self , obj , distinction = '' , name = None ) : """> > > user = User ( username = " jeremy " ) > > > user . save ( ) > > > calendar = Calendar . objects . get _ or _ create _ calendar _ for _ object ( user , name = " Jeremy ' s Calendar " ) > > > calendar . name " Jer...
try : return self . get_calendar_for_object ( obj , distinction ) except Calendar . DoesNotExist : if name is None : calendar = self . model ( name = str ( obj ) ) else : calendar = self . model ( name = name ) calendar . slug = slugify ( calendar . name ) calendar . save ( ) cal...
def max ( self , e , extra_constraints = ( ) , exact = None ) : """Return the maximum value of expression ` e ` . : param e : expression ( an AST ) to evaluate : param extra _ constraints : extra constraints ( as ASTs ) to add to the solver for this solve : param exact : if False , return approximate solution...
if exact is False and o . VALIDATE_APPROXIMATIONS in self . state . options : ar = self . _solver . max ( e , extra_constraints = self . _adjust_constraint_list ( extra_constraints ) , exact = False ) er = self . _solver . max ( e , extra_constraints = self . _adjust_constraint_list ( extra_constraints ) ) ...
def deploy ( self , version_name , path , runtime_version = None ) : """Deploy a model version to the cloud . Args : version _ name : the name of the version in short form , such as " v1 " . path : the Google Cloud Storage path ( gs : / / . . . ) which contains the model files . runtime _ version : the ML E...
if not path . startswith ( 'gs://' ) : raise Exception ( 'Invalid path. Only Google Cloud Storage path (gs://...) is accepted.' ) # If there is no " export . meta " or " saved _ model . pb " under path but there is # path / model / export . meta or path / model / saved _ model . pb , then append / model to the path...
def fit ( self , y ) : """Estimate censoring distribution from training data . Parameters y : structured array , shape = ( n _ samples , ) A structured array containing the binary event indicator as first field , and time of event or time of censoring as second field . Returns self"""
event , time = check_y_survival ( y ) if event . all ( ) : self . unique_time_ = numpy . unique ( time ) self . prob_ = numpy . ones ( self . unique_time_ . shape [ 0 ] ) else : unique_time , prob = kaplan_meier_estimator ( ~ event , time ) self . unique_time_ = numpy . concatenate ( ( [ - numpy . infty...
def __get_switch_arr ( work_sheet , row_num ) : '''if valud of the column of the row is ` 1 ` , it will be added to the array .'''
u_dic = [ ] for col_idx in FILTER_COLUMNS : cell_val = work_sheet [ '{0}{1}' . format ( col_idx , row_num ) ] . value if cell_val in [ 1 , '1' ] : # Appending the slug name of the switcher . u_dic . append ( work_sheet [ '{0}1' . format ( col_idx ) ] . value . strip ( ) . split ( ',' ) [ 0 ] ) return u_...
def p_funcvardecl ( self , p ) : """funcvardecl : decl | integerdecl"""
if isinstance ( p [ 1 ] , Decl ) : for r in p [ 1 ] . list : if ( not isinstance ( r , Input ) and not isinstance ( r , Reg ) and not isinstance ( r , Integer ) ) : raise ParseError ( "Syntax Error" ) p [ 0 ] = p [ 1 ] p . set_lineno ( 0 , p . lineno ( 1 ) )
def setpassword ( self , pwd ) : """Set default password for encrypted files ."""
if pwd and not isinstance ( pwd , bytes ) : raise TypeError ( "pwd: expected bytes, got %s" % type ( pwd ) ) if pwd : self . pwd = pwd else : self . pwd = None
def human_or_00 ( X , y , model_generator , method_name ) : """OR ( false / false ) This tests how well a feature attribution method agrees with human intuition for an OR operation combined with linear effects . This metric deals specifically with the question of credit allocation for the following function ...
return _human_or ( X , model_generator , method_name , False , False )
def unmerge ( self , unmerge_area , tab ) : """Unmerges all cells in unmerge _ area"""
top , left , bottom , right = unmerge_area selection = Selection ( [ ( top , left ) ] , [ ( bottom , right ) ] , [ ] , [ ] , [ ] ) attr = { "merge_area" : None , "locked" : False } self . _set_cell_attr ( selection , tab , attr )
def dfa_minimization ( dfa : dict ) -> dict : """Returns the minimization of the DFA in input through a greatest fix - point method . Given a completed DFA : math : ` A = ( Σ , S , s _ 0 , ρ , F ) ` there exists a single minimal DFA : math : ` A _ m ` which is equivalent to A , i . e . reads the same langua...
dfa = dfa_completion ( deepcopy ( dfa ) ) # # # Greatest - fixpoint z_current = set ( ) z_next = set ( ) # First bisimulation condition check ( can be done just once ) # s ∈ F iff t ∈ F for state_s in dfa [ 'states' ] : for state_t in dfa [ 'states' ] : if ( state_s in dfa [ 'accepting_states' ] and state_t...
def _cont_to_discrete_object ( cls , X , F , L , Qc , compute_derivatives = False , grad_params_no = None , P_inf = None , dP_inf = None , dF = None , dQc = None , dt0 = None ) : """Function return the object which is used in Kalman filter and / or smoother to obtain matrices A , Q and their derivatives for discr...
unique_round_decimals = 10 threshold_number_of_unique_time_steps = 20 # above which matrices are separately each time dt = np . empty ( ( X . shape [ 0 ] , ) ) dt [ 1 : ] = np . diff ( X [ : , 0 ] , axis = 0 ) if dt0 is None : dt [ 0 ] = 0 # dt [ 1] else : if isinstance ( dt0 , str ) : dt = dt [ 1 :...
async def read ( self , * _id ) : """Read data from database table . Accepts ids of entries . Returns list of results if success or string with error code and explanation . read ( * id ) = > [ ( result ) , ( result ) ] ( if success ) read ( * id ) = > [ ] ( if missed ) read ( ) = > { " error " : 400 , "...
if not _id : return { "error" : 400 , "reason" : "Missed required fields" } result = [ ] for i in _id : document = await self . collection . find_one ( { "id" : i } ) try : result . append ( { i : document [ i ] for i in document if i != "_id" } ) except : continue return result
def analyse_ligand_sasa ( self ) : """Analysis of ligand SASA ."""
i = 0 start = timer ( ) if self . trajectory == [ ] : self . trajectory = [ self . topology_data . universe . filename ] try : for traj in self . trajectory : new_traj = mdtraj . load ( traj , top = self . topology_data . universe . filename ) # Analyse only non - H ligand ligand_slice =...
def get_header ( message , name ) : """Gets an email . message . Message and a header name and returns the mail header decoded with the correct charset . Args : message ( email . message . Message ) : email message object name ( string ) : header to get Returns : decoded header"""
header = message . get ( name ) log . debug ( "Getting header {!r}: {!r}" . format ( name , header ) ) if header : return decode_header_part ( header ) return six . text_type ( )
def process_request ( self , request ) : """Setup the profiler for a profiling run and clear the SQL query log . If this is a resort of an existing profiling run , just return the resorted list ."""
def unpickle ( params ) : stats = unpickle_stats ( b64decode ( params . get ( 'stats' , '' ) ) ) queries = cPickle . loads ( b64decode ( params . get ( 'queries' , '' ) ) ) return stats , queries if request . method != 'GET' and not ( request . META . get ( 'HTTP_CONTENT_TYPE' , request . META . get ( 'CONT...
def _http_request ( url , method = 'GET' , headers = None , data = None ) : '''Make the HTTP request and return the body as python object .'''
req = requests . request ( method , url , headers = headers , data = data ) ret = _default_ret ( ) ok_status = METHOD_OK_STATUS . get ( method , 200 ) if req . status_code != ok_status : ret . update ( { 'comment' : req . json ( ) . get ( 'error' , '' ) } ) return ret ret . update ( { 'result' : True , 'out' : ...
def main ( args = sys . argv ) : """Run the work ( ) method from the class instance in the file " job - instance . pickle " ."""
try : # Set up logging . logging . basicConfig ( level = logging . WARN ) work_dir = args [ 1 ] assert os . path . exists ( work_dir ) , "First argument to lsf_runner.py must be a directory that exists" do_work_on_compute_node ( work_dir ) except Exception as exc : # Dump encoded data that we will try t...
def add_ip_scope ( name , description , auth , url , startip = None , endip = None , network_address = None ) : """Function takes input of four strings Start Ip , endIp , name , and description to add new Ip Scope to terminal access in the HPE IMC base platform : param name : str Name of the owner of this IP sc...
if network_address is not None : nw_address = ipaddress . IPv4Network ( network_address ) startip = nw_address [ 1 ] endip = nw_address [ - 2 ] f_url = url + "/imcrs/res/access/assignedIpScope" payload = ( '''{ "startIp": "%s", "endIp": "%s","name": "%s","description": "%s" }''' % ( str ( startip ) , str (...
def set_default_decoder_parameters ( dparams_p ) : """Wrapper for opj _ set _ default _ decoder _ parameters ."""
argtypes = [ ctypes . POINTER ( DecompressionParametersType ) ] OPENJPEG . opj_set_default_decoder_parameters . argtypes = argtypes OPENJPEG . opj_set_default_decoder_parameters ( dparams_p )
def _num_required_args ( func ) : """Number of args for func > > > def foo ( a , b , c = None ) : . . . return a + b + c > > > _ num _ required _ args ( foo ) > > > def bar ( * args ) : . . . return sum ( args ) > > > print ( _ num _ required _ args ( bar ) ) None borrowed from : https : / / github ...
try : spec = inspect . getargspec ( func ) if spec . varargs : return None num_defaults = len ( spec . defaults ) if spec . defaults else 0 return len ( spec . args ) - num_defaults except TypeError : return None
def equal ( obj1 , obj2 ) : """Calculate equality between two ( Comparable ) objects ."""
Comparable . log ( obj1 , obj2 , '==' ) equality = obj1 . equality ( obj2 ) Comparable . log ( obj1 , obj2 , '==' , result = equality ) return equality
def replace ( self , * args , ** kargs ) : """lst . replace ( < field > , [ < oldvalue > , ] < newvalue > ) lst . replace ( ( fld , [ ov ] , nv ) , ( fld , [ ov , ] nv ) , . . . ) if ov is None , all values are replaced ex : lst . replace ( IP . src , " 192.168.1.1 " , " 10.0.0.1 " ) lst . replace ( IP . ...
delete_checksums = kargs . get ( "delete_checksums" , False ) x = PacketList ( name = "Replaced %s" % self . listname ) if not isinstance ( args [ 0 ] , tuple ) : args = ( args , ) for p in self . res : p = self . _elt2pkt ( p ) copied = False for scheme in args : fld = scheme [ 0 ] old ...
def update ( self ) : """Update the processes stats ."""
# Reset the stats self . processlist = [ ] self . reset_processcount ( ) # Do not process if disable tag is set if self . disable_tag : return # Time since last update ( for disk _ io rate computation ) time_since_update = getTimeSinceLastUpdate ( 'process_disk' ) # Grab standard stats standard_attrs = [ 'cmdline' ...
def encrypt_file ( src , dest , csv_keys ) : """Encrypt a file with the specific GPG keys and write out to the specified path"""
keys = massage_keys ( csv_keys . split ( ',' ) ) cryptorito . encrypt ( src , dest , keys )
def _get_store_by_name ( self , name ) : """Return an instance of the correct DiskRepository based on the * first * file that matches the standard syntax for repository files"""
for cls in self . storage_type_map . values ( ) : cluster_files = glob . glob ( '%s/%s.%s' % ( self . storage_path , name , cls . file_ending ) ) if cluster_files : try : return cls ( self . storage_path ) except : continue raise ClusterNotFound ( "No cluster %s was found...
def save_df_state ( df_state : pd . DataFrame , site : str = '' , path_dir_save : Path = Path ( '.' ) , ) -> Path : '''save ` df _ state ` to a csv file Parameters df _ state : pd . DataFrame a dataframe of model states produced by a supy run site : str , optional site identifier ( the default is ' ' , wh...
file_state_save = 'df_state_{site}.csv' . format ( site = site ) # trim filename if site = = ' ' file_state_save = file_state_save . replace ( '_.csv' , '.csv' ) path_state_save = path_dir_save / file_state_save print ( 'writing out: {path_out}' . format ( path_out = path_state_save ) ) df_state . to_csv ( path_state_s...
def iter_query ( query ) : """Accept a filename , stream , or string . Returns an iterator over lines of the query ."""
try : itr = click . open_file ( query ) . readlines ( ) except IOError : itr = [ query ] return itr
async def deleteMessage ( self , msg_identifier ) : """See : https : / / core . telegram . org / bots / api # deletemessage : param msg _ identifier : Same as ` ` msg _ identifier ` ` in : meth : ` telepot . aio . Bot . editMessageText ` , except this method does not work on inline messages ."""
p = _strip ( locals ( ) , more = [ 'msg_identifier' ] ) p . update ( _dismantle_message_identifier ( msg_identifier ) ) return await self . _api_request ( 'deleteMessage' , _rectify ( p ) )
def start ( self ) : """This method must be called immediately after the class is instantiated . It instantiates the serial interface and then performs auto pin discovery . It is intended for use by pymata3 applications that do not use asyncio coroutines directly . : returns : No return value ."""
# check if user specified a socket transport if self . ip_address : self . socket = PymataSocket ( self . ip_address , self . ip_port , self . loop ) self . loop . run_until_complete ( ( self . socket . start ( ) ) ) # set the read and write handles self . read = self . socket . read self . write = ...
def __get_type_from_char ( self , c ) : """return a tuple of type information * type name * a flag to indicate if it ' s a collection"""
if c . isdigit ( ) or c == '-' : return ( "number" , False , None ) elif c == 't' or c == 'f' : # # true / false return ( "boolean" , False , None ) elif c == 'n' : # # nil return ( "nil" , False , None ) elif c == '\\' : return ( "char" , False , None ) elif c == ':' : return ( "keyword" , False , ...
def _build ( self , one_hot_input_sequence ) : """Builds the deep LSTM model sub - graph . Args : one _ hot _ input _ sequence : A Tensor with the input sequence encoded as a one - hot representation . Its dimensions should be ` [ truncation _ length , batch _ size , output _ size ] ` . Returns : Tuple ...
input_shape = one_hot_input_sequence . get_shape ( ) batch_size = input_shape [ 1 ] batch_embed_module = snt . BatchApply ( self . _embed_module ) input_sequence = batch_embed_module ( one_hot_input_sequence ) input_sequence = tf . nn . relu ( input_sequence ) initial_state = self . _core . initial_state ( batch_size )...
def generate_cache_key ( value ) : """Generates a cache key for the * args and * * kwargs"""
if is_bytes ( value ) : return hashlib . md5 ( value ) . hexdigest ( ) elif is_text ( value ) : return generate_cache_key ( to_bytes ( text = value ) ) elif is_boolean ( value ) or is_null ( value ) or is_number ( value ) : return generate_cache_key ( repr ( value ) ) elif is_dict ( value ) : return gen...
def remove_all_callbacks ( self ) : """Remove all callbacks registered to the shortcut manager : return :"""
for action in self . registered_shortcut_callbacks . keys ( ) : for callback in self . registered_shortcut_callbacks [ action ] : self . shortcut_manager . remove_callback_for_action ( action , callback ) # delete all registered shortcut callbacks self . registered_shortcut_callbacks = { }
def buffer_write ( self , data , dtype ) : """Write audio data from a buffer / bytes object to the file . Writes the contents of ` data ` to the file at the current read / write position . This also advances the read / write position by the number of frames that were written and enlarges the file if necessa...
ctype = self . _check_dtype ( dtype ) cdata , frames = self . _check_buffer ( data , ctype ) written = self . _cdata_io ( 'write' , cdata , ctype , frames ) assert written == frames self . _update_frames ( written )
def sg_lookup ( tensor , opt ) : r"""Looks up the ` tensor ` , which is the embedding matrix . Args : tensor : A tensor ( automatically given by chain ) opt : emb : A 2 - D ` Tensor ` . An embedding matrix . name : If provided , replace current tensor ' s name . Returns : A ` Tensor ` ."""
assert opt . emb is not None , 'emb is mandatory.' return tf . nn . embedding_lookup ( opt . emb , tensor , name = opt . name )
def smacof_mds ( C , dim , max_iter = 3000 , eps = 1e-9 ) : """Returns an interpolated point cloud following the dissimilarity matrix C using SMACOF multidimensional scaling ( MDS ) in specific dimensionned target space Parameters C : ndarray , shape ( ns , ns ) dissimilarity matrix dim : int dimensio...
rng = np . random . RandomState ( seed = 3 ) mds = manifold . MDS ( dim , max_iter = max_iter , eps = 1e-9 , dissimilarity = 'precomputed' , n_init = 1 ) pos = mds . fit ( C ) . embedding_ nmds = manifold . MDS ( 2 , max_iter = max_iter , eps = 1e-9 , dissimilarity = "precomputed" , random_state = rng , n_init = 1 ) np...
def coverage ( self , container : Container , tests : Optional [ Iterable [ TestCase ] ] = None , * , instrument : bool = True ) -> TestSuiteCoverage : """Computes line coverage information over a provided set of tests for the program inside a given container ."""
extractor = self . coverage_extractor ( container ) if tests is None : bugs = self . __installation . bugs bug = bugs [ container . bug ] tests = bug . tests return extractor . run ( tests , instrument = instrument )
def _set_offset_base1 ( self , v , load = False ) : """Setter method for offset _ base1 , mapped from YANG variable / uda _ key / profile / uda _ profile _ offsets / offset _ base1 ( uda - offset - base - type ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ offset _ b...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'first-header' : { 'value' : 1 } , u'packet-start' : { 'value' : 0 } , u'fourth-header' : { 'value' : 4 } , u'second-header' : {...