idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
52,000
def pending ( ) : signalbus = current_app . extensions [ 'signalbus' ] pending = [ ] total_pending = 0 for signal_model in signalbus . get_signal_models ( ) : count = signal_model . query . count ( ) if count > 0 : pending . append ( ( count , signal_model . __name__ ) ) total_pending += count if pending : pending . so...
Show the number of pending signals by signal type .
52,001
def create_thumbnail ( uuid , thumbnail_width ) : size = thumbnail_width + ',' thumbnail = IIIFImageAPI . get ( 'v2' , uuid , size , 0 , 'default' , 'jpg' )
Create the thumbnail for an image .
52,002
def price_str ( raw_price , default = _not_defined , dec_point = '.' ) : def _error_or_default ( err_msg ) : if default == _not_defined : raise ValueError ( err_msg ) return default if not isinstance ( raw_price , str ) : return _error_or_default ( 'Wrong raw price type "{price_type}" ' '(expected type "str")' . format...
Search and clean price value .
52,003
def price_dec ( raw_price , default = _not_defined ) : try : price = price_str ( raw_price ) return decimal . Decimal ( price ) except ValueError as err : if default == _not_defined : raise err return default
Price decimal value from raw string .
52,004
def metric ( self , measurement_name , values , tags = None , timestamp = None ) : if not measurement_name or values in ( None , { } ) : return tags = tags or { } all_tags = dict ( self . tags , ** tags ) line = Line ( measurement_name , values , all_tags , timestamp ) self . send ( line . to_line_protocol ( ) )
Append global tags configured for the client to the tags given then converts the data into InfluxDB Line protocol and sends to to socket
52,005
def send ( self , data ) : try : self . socket . sendto ( data . encode ( 'utf8' ) + b'\n' , ( self . host , self . port ) ) except ( socket . error , RuntimeError ) : pass
Sends the given data to the socket via UDP
52,006
def send ( self , data ) : self . future_session . post ( url = self . url , data = data )
Send the data in a separate thread via HTTP POST . HTTP introduces some overhead so to avoid blocking the main thread this issues the request in the background .
52,007
def to_line_protocol ( self ) : tags = self . get_output_tags ( ) return u"{0}{1} {2}{3}" . format ( self . get_output_measurement ( ) , "," + tags if tags else '' , self . get_output_values ( ) , self . get_output_timestamp ( ) )
Converts the given metrics as a single line of InfluxDB line protocol
52,008
def format_string ( key ) : if isinstance ( key , basestring ) : key = key . replace ( "," , "\," ) key = key . replace ( " " , "\ " ) key = key . replace ( "=" , "\=" ) return key
Formats either measurement names tag names or tag values .
52,009
def _process_equation ( value , fmt ) : global Nreferences global cursec attrs = value [ 0 ] eq = { 'is_unnumbered' : False , 'is_unreferenceable' : False , 'is_tagged' : False , 'attrs' : attrs } if not LABEL_PATTERN . match ( attrs [ 0 ] ) : eq [ 'is_unnumbered' ] = True eq [ 'is_unreferenceable' ] = True return eq i...
Processes the equation . Returns a dict containing eq properties .
52,010
def process_equations ( key , value , fmt , meta ) : if key == 'Math' and len ( value ) == 3 : eq = _process_equation ( value , fmt ) attrs = eq [ 'attrs' ] label = attrs [ 0 ] if eq [ 'is_unreferenceable' ] : attrs [ 0 ] = '' if eq [ 'is_unnumbered' ] : return None elif fmt in [ 'latex' , 'beamer' ] : return RawInline...
Processes the attributed equations .
52,011
def process ( meta ) : global capitalize global use_cleveref_default global plusname global starname global numbersections for name in [ 'eqnos-cleveref' , 'xnos-cleveref' , 'cleveref' ] : if name in meta : use_cleveref_default = check_bool ( get_meta ( meta , name ) ) break for name in [ 'eqnos-capitalize' , 'eqnos-ca...
Saves metadata fields in global variables and returns a few computed fields .
52,012
def check_debug ( ) : from django . conf import settings if not settings . configured : return False from django . apps import apps if not apps . ready : return False if not hasattr ( django . template , "backends" ) : return False if not hasattr ( django . template . backends , "django" ) : return False if not hasattr...
Check that Django s template debugging is enabled .
52,013
def read_template_source ( filename ) : from django . conf import settings if not settings . configured : settings . configure ( ) with open ( filename , "rb" ) as f : text = f . read ( ) . decode ( settings . FILE_CHARSET ) return text
Read the source of a Django template returning the Unicode text .
52,014
def get_line_number ( line_map , offset ) : for lineno , line_offset in enumerate ( line_map , start = 1 ) : if line_offset > offset : return lineno return - 1
Find a line number given a line map and a character offset .
52,015
def dump_frame ( frame , label = "" ) : locals = dict ( frame . f_locals ) self = locals . get ( 'self' , None ) context = locals . get ( 'context' , None ) if "__builtins__" in locals : del locals [ "__builtins__" ] if label : label = " ( %s ) " % label print ( "-- frame --%s---------------------" % label ) print ( "{...
Dump interesting information about this frame .
52,016
def get_line_map ( self , filename ) : if filename not in self . source_map : template_source = read_template_source ( filename ) if 0 : for i in range ( 0 , len ( template_source ) , 10 ) : print ( "%3d: %r" % ( i , template_source [ i : i + 10 ] ) ) self . source_map [ filename ] = make_line_map ( template_source ) r...
The line map for filename .
52,017
def init ( size = 250 ) : player = mpv . MPV ( start_event_thread = False ) player [ "force-window" ] = "immediate" player [ "keep-open" ] = "yes" player [ "geometry" ] = f"{size}x{size}" player [ "autofit" ] = f"{size}x{size}" player [ "title" ] = "bum" return player
Initialize mpv .
52,018
def bytes_to_file ( input_data , output_file ) : pathlib . Path ( output_file . parent ) . mkdir ( parents = True , exist_ok = True ) with open ( output_file , "wb" ) as file : file . write ( input_data )
Save bytes to a file .
52,019
def init ( port = 6600 , server = "localhost" ) : client = mpd . MPDClient ( ) try : client . connect ( server , port ) return client except ConnectionRefusedError : print ( "error: Connection refused to mpd/mopidy." ) os . _exit ( 1 )
Initialize mpd .
52,020
def get_art ( cache_dir , size , client ) : song = client . currentsong ( ) if len ( song ) < 2 : print ( "album: Nothing currently playing." ) return file_name = f"{song['artist']}_{song['album']}_{size}.jpg" . replace ( "/" , "" ) file_name = cache_dir / file_name if file_name . is_file ( ) : shutil . copy ( file_nam...
Get the album art .
52,021
def get_cover ( song , size = 250 ) : try : data = mus . search_releases ( artist = song [ "artist" ] , release = song [ "album" ] , limit = 1 ) release_id = data [ "release-list" ] [ 0 ] [ "release-group" ] [ "id" ] print ( f"album: Using release-id: {data['release-list'][0]['id']}" ) return mus . get_release_group_im...
Download the cover art .
52,022
def convertforinput ( self , filepath , metadata ) : assert isinstance ( metadata , CLAMMetaData ) if not metadata . __class__ in self . acceptforinput : raise Exception ( "Convertor " + self . __class__ . __name__ + " can not convert input files to " + metadata . __class__ . __name__ + "!" ) return False
Convert from target format into one of the source formats . Relevant if converters are used in InputTemplates . Metadata already is metadata for the to - be - generated file . filepath is both the source and the target file the source file will be erased and overwritten with the conversion result!
52,023
def convertforoutput ( self , outputfile ) : assert isinstance ( outputfile , CLAMOutputFile ) if not outputfile . metadata . __class__ in self . acceptforoutput : raise Exception ( "Convertor " + self . __class__ . __name__ + " can not convert input files to " + outputfile . metadata . __class__ . __name__ + "!" ) ret...
Convert from one of the source formats into target format . Relevant if converters are used in OutputTemplates . Sourcefile is a CLAMOutputFile instance .
52,024
def convertforinput ( self , filepath , metadata = None ) : super ( CharEncodingConverter , self ) . convertforinput ( filepath , metadata ) shutil . copy ( filepath , filepath + '.convertsource' ) try : fsource = io . open ( filepath + '.convertsource' , 'r' , encoding = self . charset ) ftarget = io . open ( filepath...
Convert from target format into one of the source formats . Relevant if converters are used in InputTemplates . Metadata already is metadata for the to - be - generated file .
52,025
def convertforoutput ( self , outputfile ) : super ( CharEncodingConverter , self ) . convertforoutput ( outputfile ) return withheaders ( flask . make_response ( ( line . encode ( self . charset ) for line in outputfile ) ) , 'text/plain; charset=' + self . charset )
Convert from one of the source formats into target format . Relevant if converters are used in OutputTemplates . Outputfile is a CLAMOutputFile instance .
52,026
def getclamdata ( filename , custom_formats = None ) : global CUSTOM_FORMATS f = io . open ( filename , 'r' , encoding = 'utf-8' ) xml = f . read ( os . path . getsize ( filename ) ) f . close ( ) if custom_formats : CUSTOM_FORMATS = custom_formats return CLAMData ( xml , None , True )
This function reads the CLAM Data from an XML file . Use this to read the clam . xml file from your system wrapper . It returns a CLAMData instance .
52,027
def sanitizeparameters ( parameters ) : if not isinstance ( parameters , dict ) : d = { } for x in parameters : if isinstance ( x , tuple ) and len ( x ) == 2 : for parameter in x [ 1 ] : d [ parameter . id ] = parameter elif isinstance ( x , clam . common . parameters . AbstractParameter ) : d [ x . id ] = x return d ...
Construct a dictionary of parameters for internal use only
52,028
def loadmetadata ( self ) : if not self . remote : metafile = self . projectpath + self . basedir + '/' + self . metafilename ( ) if os . path . exists ( metafile ) : f = io . open ( metafile , 'r' , encoding = 'utf-8' ) xml = "" . join ( f . readlines ( ) ) f . close ( ) else : raise IOError ( 2 , "No metadata found, ...
Load metadata for this file . This is usually called automatically upon instantiation except if explicitly disabled . Works both locally as well as for clients connecting to a CLAM service .
52,029
def delete ( self ) : if not self . remote : if not os . path . exists ( self . projectpath + self . basedir + '/' + self . filename ) : return False else : os . unlink ( self . projectpath + self . basedir + '/' + self . filename ) metafile = self . projectpath + self . basedir + '/' + self . metafilename ( ) if os . ...
Delete this file
52,030
def read ( self ) : lines = self . readlines ( ) if self . metadata and 'encoding' in self . metadata : encoding = self . metadata [ 'encoding' ] else : encoding = 'utf-8' if sys . version < '3' : return "\n" . join ( unicode ( line , 'utf-8' ) if isinstance ( line , str ) else line for line in lines ) else : return "\...
Loads all lines in memory
52,031
def copy ( self , target , timeout = 500 ) : if self . metadata and 'encoding' in self . metadata : with io . open ( target , 'w' , encoding = self . metadata [ 'encoding' ] ) as f : for line in self : f . write ( line ) else : with io . open ( target , 'wb' ) as f : for line in self : if sys . version < '3' and isinst...
Copy or download this file to a new local file
52,032
def outputtemplate ( self , template_id ) : for profile in self . profiles : for outputtemplate in profile . outputtemplates ( ) : if outputtemplate . id == template_id : return outputtemplate return KeyError ( "Outputtemplate " + template_id + " not found" )
Get an output template by ID
52,033
def commandlineargs ( self ) : commandlineargs = [ ] for parametergroup , parameters in self . parameters : for parameter in parameters : p = parameter . compilearg ( ) if p : commandlineargs . append ( p ) return " " . join ( commandlineargs )
Obtain a string of all parameters using the paramater flags they were defined with in order to pass to an external command . This is shell - safe by definition .
52,034
def parametererror ( self ) : for parametergroup , parameters in self . parameters : for parameter in parameters : if parameter . error : return parameter . error return False
Return the first parameter error or False if there is none
52,035
def inputtemplate ( self , template_id ) : for profile in self . profiles : for inputtemplate in profile . input : if inputtemplate . id == template_id : return inputtemplate raise Exception ( "No such input template: " + repr ( template_id ) )
Return the inputtemplate with the specified ID . This is used to resolve a inputtemplate ID to an InputTemplate object instance
52,036
def inputfiles ( self , inputtemplate = None ) : if isinstance ( inputtemplate , InputTemplate ) : inputtemplate = inputtemplate . id for inputfile in self . input : if not inputtemplate or inputfile . metadata . inputtemplate == inputtemplate : yield inputfile
Generator yielding all inputfiles for the specified inputtemplate if inputtemplate = None inputfiles are returned regardless of inputtemplate .
52,037
def outputtemplates ( self ) : outputtemplates = [ ] for o in self . output : if isinstance ( o , ParameterCondition ) : outputtemplates += o . allpossibilities ( ) else : assert isinstance ( o , OutputTemplate ) outputtemplates . append ( o ) return outputtemplates
Returns all outputtemplates resolving ParameterConditions to all possibilities
52,038
def generate ( self , projectpath , parameters , serviceid , servicename , serviceurl ) : parameters = sanitizeparameters ( parameters ) program = Program ( projectpath , [ self ] ) match , optional_absent = self . match ( projectpath , parameters ) if match : inputfiles = self . matchingfiles ( projectpath ) inputfile...
Generate output metadata on the basis of input files and parameters . Projectpath must be absolute . Returns a Program instance .
52,039
def xml ( self , indent = "" ) : xml = "\n" + indent + "<profile>\n" xml += indent + " <input>\n" for inputtemplate in self . input : xml += inputtemplate . xml ( indent + " " ) + "\n" xml += indent + " </input>\n" xml += indent + " <output>\n" for outputtemplate in self . output : xml += outputtemplate . xml ( inde...
Produce XML output for the profile
52,040
def fromxml ( node ) : if not isinstance ( node , ElementTree . _Element ) : node = parsexmlstring ( node ) args = [ ] if node . tag == 'profile' : for node in node : if node . tag == 'input' : for subnode in node : if subnode . tag . lower ( ) == 'inputtemplate' : args . append ( InputTemplate . fromxml ( subnode ) ) ...
Return a profile instance from the given XML description . Node can be a string or an etree . _Element .
52,041
def add ( self , outputfilename , outputtemplate , inputfilename = None , inputtemplate = None ) : if isinstance ( outputtemplate , OutputTemplate ) : outputtemplate = outputtemplate . id if isinstance ( inputtemplate , InputTemplate ) : inputtemplate = inputtemplate . id if outputfilename in self : outputtemplate , in...
Add a new path to the program
52,042
def xml ( self , indent = "" ) : xml = indent + "<provenance type=\"clam\" id=\"" + self . serviceid + "\" name=\"" + self . servicename + "\" url=\"" + self . serviceurl + "\" outputtemplate=\"" + self . outputtemplate_id + "\" outputtemplatelabel=\"" + self . outputtemplate_label + "\" timestamp=\"" + str ( self . ti...
Serialise provenance data to XML . This is included in CLAM Metadata files
52,043
def fromxml ( node ) : if not isinstance ( node , ElementTree . _Element ) : node = parsexmlstring ( node ) if node . tag == 'provenance' : if node . attrib [ 'type' ] == 'clam' : serviceid = node . attrib [ 'id' ] servicename = node . attrib [ 'name' ] serviceurl = node . attrib [ 'url' ] timestamp = node . attrib [ '...
Return a CLAMProvenanceData instance from the given XML description . Node can be a string or an lxml . etree . _Element .
52,044
def xml ( self , indent = "" ) : if not indent : xml = '<?xml version="1.0" encoding="UTF-8"?>\n' else : xml = "" xml += indent + "<CLAMMetaData format=\"" + self . __class__ . __name__ + "\"" if self . mimetype : xml += " mimetype=\"" + self . mimetype + "\"" if self . schema : xml += " schema=\"" + self . schema + "\...
Render an XML representation of the metadata
52,045
def save ( self , filename ) : with io . open ( filename , 'w' , encoding = 'utf-8' ) as f : f . write ( self . xml ( ) )
Save metadata to XML file
52,046
def json ( self ) : d = { 'id' : self . id , 'format' : self . formatclass . __name__ , 'label' : self . label , 'mimetype' : self . formatclass . mimetype , 'schema' : self . formatclass . schema } if self . unique : d [ 'unique' ] = True if self . filename : d [ 'filename' ] = self . filename if self . extension : d ...
Produce a JSON representation for the web interface
52,047
def validate ( self , postdata , user = None ) : clam . common . util . printdebug ( "Validating inputtemplate " + self . id + "..." ) errors , parameters , _ = processparameters ( postdata , self . parameters , user ) return errors , parameters
Validate posted data against the inputtemplate
52,048
def xml ( self , operator = 'set' , indent = "" ) : xml = indent + "<meta id=\"" + self . key + "\"" if operator != 'set' : xml += " operator=\"" + operator + "\"" if not self . value : xml += " />" else : xml += ">" + self . value + "</meta>" return xml
Serialize the metadata field to XML
52,049
def fromxml ( node ) : if not isinstance ( node , ElementTree . _Element ) : node = parsexmlstring ( node ) assert node . tag . lower ( ) == 'outputtemplate' template_id = node . attrib [ 'id' ] dataformat = node . attrib [ 'format' ] label = node . attrib [ 'label' ] kwargs = { } if 'filename' in node . attrib : kwarg...
Static method return an OutputTemplate instance from the given XML description . Node can be a string or an etree . _Element .
52,050
def getparent ( self , profile ) : assert self . parent for inputtemplate in profile . input : if inputtemplate == self . parent : return inputtemplate raise Exception ( "Parent InputTemplate '" + self . parent + "' not found!" )
Resolve a parent ID
52,051
def fromxml ( node ) : if not isinstance ( node , ElementTree . _Element ) : node = parsexmlstring ( node ) assert node . tag . lower ( ) == 'parametercondition' kwargs = { } found = False for node in node : if node . tag == 'if' : for subnode in node : operator = subnode . tag parameter = subnode . attrib [ 'parameter...
Static method returning a ParameterCondition instance from the given XML description . Node can be a string or an etree . _Element .
52,052
def fromxml ( node ) : if not isinstance ( node , ElementTree . _Element ) : node = parsexmlstring ( node ) assert node . tag . lower ( ) == 'action' kwargs = { } args = [ ] if 'id' in node . attrib : kwargs [ 'id' ] = node . attrib [ 'id' ] elif 'name' in node . attrib : kwargs [ 'name' ] = node . attrib [ 'name' ] el...
Static method returning an Action instance from the given XML description . Node can be a string or an etree . _Element .
52,053
def crude_tokenizer ( line ) : tokens = [ ] buffer = '' for c in line . strip ( ) : if c == ' ' or c in string . punctuation : if buffer : tokens . append ( buffer ) buffer = '' else : buffer += c if buffer : tokens . append ( buffer ) return tokens
This is a very crude tokenizer from pynlpl
52,054
def initauth ( self ) : headers = { 'User-agent' : 'CLAMClientAPI-' + clam . common . data . VERSION } if self . oauth : if not self . oauth_access_token : r = requests . get ( self . url , headers = headers , verify = self . verify ) if r . status_code == 404 : raise clam . common . data . NotFound ( "Authorization pr...
Initialise authentication for internal use
52,055
def request ( self , url = '' , method = 'GET' , data = None , parse = True , encoding = None ) : requestparams = self . initrequest ( data ) if method == 'POST' : request = requests . post elif method == 'DELETE' : request = requests . delete elif method == 'PUT' : request = requests . put else : request = requests . ...
Issue a HTTP request and parse CLAM XML response this is a low - level function called by all of the higher - level communication methods in this class use those instead
52,056
def _parse ( self , content ) : if content . find ( '<clam' ) != - 1 : data = clam . common . data . CLAMData ( content , self , loadmetadata = self . loadmetadata ) if data . errors : error = data . parametererror ( ) if error : raise clam . common . data . ParameterError ( error ) return data else : return True
Parses CLAM XML data and returns a CLAMData object . For internal use . Raises ParameterError exception on parameter errors .
52,057
def get ( self , project ) : try : data = self . request ( project + '/' ) except : raise if not isinstance ( data , clam . common . data . CLAMData ) : raise Exception ( "Unable to retrieve CLAM Data" ) else : return data
Query the project status . Returns a CLAMData instance or raises an exception according to the returned HTTP Status code
52,058
def getinputfilename ( self , inputtemplate , filename ) : if inputtemplate . filename : filename = inputtemplate . filename elif inputtemplate . extension : if filename . lower ( ) [ - 4 : ] == '.zip' or filename . lower ( ) [ - 7 : ] == '.tar.gz' or filename . lower ( ) [ - 8 : ] == '.tar.bz2' : return filename if fi...
Determine the final filename for an input file given an inputtemplate and a given filename .
52,059
def _parseupload ( self , node ) : if not isinstance ( node , ElementTree . _Element ) : try : node = clam . common . data . parsexmlstring ( node ) except : raise Exception ( node ) if node . tag != 'clamupload' : raise Exception ( "Not a valid CLAM upload response" ) for node2 in node : if node2 . tag == 'upload' : f...
Parse CLAM Upload XML Responses . For internal use
52,060
def download ( self , project , filename , targetfilename , loadmetadata = None ) : if loadmetadata is None : loadmetadata = self . loadmetadata f = clam . common . data . CLAMOutputFile ( self . url + project , filename , loadmetadata , self ) f . copy ( targetfilename )
Download an output file
52,061
def validate ( self , value ) : if self . validator is not None : try : valid = self . validator ( value ) except Exception as e : import pdb pdb . set_trace ( ) if isinstance ( valid , tuple ) and len ( valid ) == 2 : valid , errormsg = valid elif isinstance ( valid , bool ) : errormsg = "Invalid value" else : raise T...
Validate the parameter
52,062
def set ( self , value = True ) : value = value in ( True , 1 ) or ( ( isinstance ( value , str ) or ( sys . version < '3' and isinstance ( value , unicode ) ) ) and ( value . lower ( ) in ( "1" , "yes" , "true" , "enabled" ) ) ) return super ( BooleanParameter , self ) . set ( value )
Set the boolean parameter
52,063
def compilearg ( self ) : if isinstance ( self . value , list ) : value = self . delimiter . join ( self . value ) else : value = self . value if value . find ( " " ) >= 0 : value = '"' + value + '"' if self . paramflag and self . paramflag [ - 1 ] == '=' or self . nospace : sep = '' elif self . paramflag : sep = ' ' e...
This method compiles the parameter into syntax that can be used on the shell such as - paramflag = value
52,064
def index ( credentials = None ) : shortcutresponse = entryshortcut ( credentials ) if shortcutresponse is not None : return shortcutresponse projects = [ ] user , oauth_access_token = parsecredentials ( credentials ) totalsize = 0.0 if settings . LISTPROJECTS : projects , totalsize = getprojects ( user ) errors = "no"...
Get list of projects or shortcut to other functionality
52,065
def run_wsgi ( settings_module ) : global settingsmodule , DEBUG printdebug ( "Initialising WSGI service" ) globals ( ) [ 'settings' ] = settings_module settingsmodule = settings_module . __name__ try : if settings . DEBUG : DEBUG = True setdebug ( True ) except : pass test_version ( ) if DEBUG : setlog ( sys . stderr ...
Run CLAM in WSGI mode
52,066
def index ( credentials = None ) : user , oauth_access_token = parsecredentials ( credentials ) if not settings . ADMINS or user not in settings . ADMINS : return flask . make_response ( 'You shall not pass!!! You are not an administrator!' , 403 ) usersprojects = { } totalsize = { } for f in glob . glob ( settings . R...
Get list of projects
52,067
def exists ( project , credentials ) : user , oauth_access_token = parsecredentials ( credentials ) printdebug ( "Checking if project " + project + " exists for " + user ) return os . path . isdir ( Project . path ( project , user ) )
Check if the project exists
52,068
def new ( project , credentials = None ) : user , oauth_access_token = parsecredentials ( credentials ) response = Project . create ( project , user ) if response is not None : return response msg = "Project " + project + " has been created for user " + user if oauth_access_token : extraloc = '?oauth_access_token=' + o...
Create an empty project
52,069
def deleteoutputfile ( project , filename , credentials = None ) : user , oauth_access_token = parsecredentials ( credentials ) if filename : filename = filename . replace ( ".." , "" ) if not filename or len ( filename ) == 0 : Project . reset ( project , user ) msg = "Deleted" return withheaders ( flask . make_respon...
Delete an output file
52,070
def reset ( project , user ) : d = Project . path ( project , user ) + "output" if os . path . isdir ( d ) : shutil . rmtree ( d ) os . makedirs ( d ) else : raise flask . abort ( 404 ) if os . path . exists ( Project . path ( project , user ) + ".done" ) : os . unlink ( Project . path ( project , user ) + ".done" ) if...
Reset system delete all output files and prepare for a new run
52,071
def deleteinputfile ( project , filename , credentials = None ) : user , oauth_access_token = parsecredentials ( credentials ) filename = filename . replace ( ".." , "" ) if len ( filename ) == 0 : shutil . rmtree ( Project . path ( project , user ) + 'input' ) os . makedirs ( Project . path ( project , user ) + 'input...
Delete an input file
52,072
def corpusindex ( ) : corpora = [ ] for f in glob . glob ( settings . ROOT + "corpora/*" ) : if os . path . isdir ( f ) : corpora . append ( os . path . basename ( f ) ) return corpora
Get list of pre - installed corpora
52,073
def validate ( self , nonce ) : if self . debug : print ( "Checking nonce " + str ( nonce ) , file = sys . stderr ) try : opaque , ip , expiretime = self . get ( nonce ) if expiretime < time . time ( ) : if self . debug : print ( "Nonce expired" , file = sys . stderr ) self . remove ( nonce ) return False elif ip != fl...
Does the nonce exist and is it valid for the request?
52,074
def cleanup ( self ) : t = time . time ( ) for noncefile in glob ( self . path + '/*.nonce' ) : if os . path . getmtime ( noncefile ) + self . expiration > t : os . unlink ( noncefile )
Delete expired nonces
52,075
def json ( self ) : return { "id" : self . ID , "steps" : self . steps , "graph_source" : self . source , "errored" : self . errored }
Retrun JSON representation for this run
52,076
def new_run ( self ) : self . current_run += 1 self . runs . append ( RunData ( self . current_run + 1 ) )
Creates a new RunData object and increments pointers
52,077
def update_frontend ( self , info ) : headers = { 'Content-Type' : 'text/event-stream' } if info . get ( 'when' ) : info [ 'when' ] = info [ 'when' ] . isoformat ( ) requests . post ( self . base_url + '/publish' , data = json . dumps ( info ) , headers = headers )
Updates frontend with info from the log
52,078
def get_summary ( self ) : if not self . analysis_finished : return [ ] summary = { 'times_summary' : [ ] } for i in range ( len ( self . runs [ self . current_run ] . steps ) - 1 ) : step = self . runs [ self . current_run ] . steps [ i ] begin = parse ( step [ 'when' ] ) end = parse ( self . runs [ self . current_run...
Returns some summary data for a finished analysis
52,079
def _handle_rundebug_from_shell ( cmd_line ) : command , args = parse_shell_command ( cmd_line ) if len ( args ) >= 1 : get_workbench ( ) . get_editor_notebook ( ) . save_all_named_editors ( ) origcommand = command if command == "Ev3RemoteRun" : command = "Run" if command == "Ev3RemoteDebug" : command = "Debug" cmd = T...
Handles all commands that take a filename and 0 or more extra arguments . Passes the command to backend .
52,080
def download_log ( currentfile = None ) : if currentfile == None : return if not currentfile . endswith ( ".err.log" ) : currentfile = currentfile + ".err.log" list = get_base_ev3dev_cmd ( ) + [ 'download' , '--force' ] list . append ( currentfile ) env = os . environ . copy ( ) env [ "PYTHONUSERBASE" ] = THONNY_USER_B...
downloads log of given . py file from EV3 .
52,081
def download_log_of_current_script ( ) : try : src_file = get_workbench ( ) . get_current_editor ( ) . get_filename ( False ) if src_file is None : return download_log ( src_file ) except Exception : error_msg = traceback . format_exc ( 0 ) + '\n' showerror ( "Error" , error_msg )
download log of current python script from EV3
52,082
def cleanup_files_on_ev3 ( ) : list = get_base_ev3dev_cmd ( ) + [ 'cleanup' ] env = os . environ . copy ( ) env [ "PYTHONUSERBASE" ] = THONNY_USER_BASE proc = subprocess . Popen ( list , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , universal_newlines = True , env = env ) dlg = MySubprocessDialog ( get_wo...
cleanup files in homedir on EV3 .
52,083
def init ( base_url , username = None , password = None , verify = True ) : handler = RequestHandler ( base_url , username , password , verify ) set_default_request_handler ( handler ) return handler
Initialize ubersmith API module with HTTP request handler .
52,084
def getConfigPath ( configFileName = None ) : if configFileName != None : if sys . platform == 'win32' : return os . path . expanduser ( os . path . join ( '~\\' , 'Deepify' , configFileName ) ) else : return os . path . expanduser ( os . path . join ( '~/' , '.config' , 'Deepify' , configFileName ) ) else : if sys . p...
Auxiliar function to get the configuration path depending on the system .
52,085
def new_log_file ( logger , suffix , file_type = 'tcl' ) : file_handler = None for handler in logger . handlers : if isinstance ( handler , logging . FileHandler ) : file_handler = handler new_logger = logging . getLogger ( file_type + suffix ) if file_handler : logger_file_name = path . splitext ( file_handler . baseF...
Create new logger and log file from existing logger .
52,086
def process_request ( self , method , data = None ) : self . _validate_request_method ( method ) attempts = 3 for i in range ( attempts ) : response = self . _send_request ( method , data ) if self . _is_token_response ( response ) : if i < attempts - 1 : time . sleep ( 2 ) continue else : raise UpdatingTokenResponse b...
Process request over HTTP to ubersmith instance .
52,087
def _encode_data ( data ) : data = data if data is not None else { } data = to_nested_php_args ( data ) files = dict ( [ ( key , value ) for key , value in data . items ( ) if isinstance ( value , file_type ) ] ) for fname in files : del data [ fname ] return data , files or None , None
URL encode data .
52,088
def get_objects_or_children_by_type ( self , * types ) : objects = self . get_objects_by_type ( * types ) return objects if objects else self . get_children ( * types )
Get objects if children already been read or get children .
52,089
def get_object_or_child_by_type ( self , * types ) : objects = self . get_objects_or_children_by_type ( * types ) return objects [ 0 ] if any ( objects ) else None
Get object if child already been read or get child .
52,090
def del_object_from_parent ( self ) : if self . parent : self . parent . objects . pop ( self . ref )
Delete object from parent object .
52,091
def _idToStr ( self , x ) : if x < 0 : sign = - 1 elif x == 0 : return self . _idChars [ 0 ] else : sign = 1 x *= sign digits = [ ] while x : digits . append ( self . _idChars [ x % self . _idCharsCnt ] ) x //= self . _idCharsCnt if sign < 0 : digits . append ( '-' ) digits . reverse ( ) return '' . join ( digits )
Convert VCD id in int to string
52,092
def addVar ( self , sig : object , name : str , sigType : VCD_SIG_TYPE , width : int , valueFormatter : Callable [ [ "Value" ] , str ] ) : vInf = self . _writer . _idScope . registerVariable ( sig , name , self , width , sigType , valueFormatter ) self . children [ vInf . name ] = vInf self . _writer . _oFile . write (...
Add variable to scope
52,093
def varScope ( self , name ) : ch = VcdVarWritingScope ( name , self . _writer , parent = self ) assert name not in self . children , name self . children [ name ] = ch return ch
Create sub variable scope with defined name
52,094
def append_qs ( url , query_string ) : parsed_url = urlsplit ( url ) parsed_qs = parse_qsl ( parsed_url . query , True ) if isstr ( query_string ) : parsed_qs += parse_qsl ( query_string ) elif isdict ( query_string ) : for item in list ( query_string . items ( ) ) : if islist ( item [ 1 ] ) : for val in item [ 1 ] : p...
Append query_string values to an existing URL and return it as a string .
52,095
def urlencode_unicode ( data , doseq = 0 ) : data_iter = None if isdict ( data ) : data_iter = list ( data . items ( ) ) elif islist ( data ) : data_iter = data if data_iter : for i , ( key , value ) in enumerate ( data_iter ) : if isinstance ( value , text_type ) : try : safe_val = str ( value ) except UnicodeEncodeEr...
urllib . urlencode can t handle unicode this is a hack to fix it .
52,096
def to_nested_php_args ( data , prefix_key = None ) : is_root = prefix_key is None prefix_key = prefix_key if prefix_key else '' if islist ( data ) : data_iter = data if is_root else enumerate ( data ) new_data = [ ] if is_root else { } elif isdict ( data ) : data_iter = list ( data . items ( ) ) new_data = { } else : ...
This function will take either a dict or list and will recursively loop through the values converting it into a format similar to a PHP array which Ubersmith requires for the info portion of the API s order . create method .
52,097
def get_filename ( disposition ) : if disposition : params = [ param . strip ( ) for param in disposition . split ( ';' ) [ 1 : ] ] for param in params : if '=' in param : name , value = param . split ( '=' , 1 ) if name == 'filename' : return value . strip ( '"' )
Parse Content - Disposition header to pull out the filename bit .
52,098
def tcl_list_2_py_list ( tcl_list , within_tcl_str = False ) : if not within_tcl_str : tcl_list = tcl_str ( tcl_list ) return tcl_interp_g . eval ( 'join ' + tcl_list + ' LiStSeP' ) . split ( 'LiStSeP' ) if tcl_list else [ ]
Convert Tcl list to Python list using Tcl interpreter .
52,099
def py_list_to_tcl_list ( py_list ) : py_list_str = [ str ( s ) for s in py_list ] return tcl_str ( tcl_interp_g . eval ( 'split' + tcl_str ( '\t' . join ( py_list_str ) ) + '\\t' ) )
Convert Python list to Tcl list using Tcl interpreter .