text
stringlengths
81
112k
Processes the equation. Returns a dict containing eq properties. def _process_equation(value, fmt): """Processes the equation. Returns a dict containing eq properties.""" # pylint: disable=global-statement global Nreferences # Global references counter global cursec # Current section # P...
Processes the attributed equations. def process_equations(key, value, fmt, meta): """Processes the attributed equations.""" if key == 'Math' and len(value) == 3: # Process the equation eq = _process_equation(value, fmt) # Get the attributes and label attrs = eq['attrs'] ...
Saves metadata fields in global variables and returns a few computed fields. def process(meta): """Saves metadata fields in global variables and returns a few computed fields.""" # pylint: disable=global-statement global capitalize global use_cleveref_default global plusname global sta...
Filters the document AST. def main(): """Filters the document AST.""" # pylint: disable=global-statement global PANDOCVERSION global AttrMath # Get the output format and document fmt = args.fmt doc = json.loads(STDIN.read()) # Initialize pandocxnos # pylint: disable=too-many-func...
Check that Django's template debugging is enabled. Django's built-in "template debugging" records information the plugin needs to do its work. Check that the setting is correct, and raise an exception if it is not. Returns True if the debug check was performed, False otherwise def check_debug(): ...
Read the source of a Django template, returning the Unicode text. def read_template_source(filename): """Read the source of a Django template, returning the Unicode text.""" # Import this late to be sure we don't trigger settings machinery too # early. from django.conf import settings if not setti...
Find a line number, given a line map and a character offset. def get_line_number(line_map, offset): """Find a line number, given a line map and a character offset.""" for lineno, line_offset in enumerate(line_map, start=1): if line_offset > offset: return lineno return -1
Dump interesting information about this frame. def dump_frame(frame, label=""): """Dump interesting information about this frame.""" locals = dict(frame.f_locals) self = locals.get('self', None) context = locals.get('context', None) if "__builtins__" in locals: del locals["__builtins__"] ...
The line map for `filename`. A line map is a list of character offsets, indicating where each line in the text begins. For example, a line map like this:: [13, 19, 30] means that line 2 starts at character 13, line 3 starts at 19, etc. Line 1 always starts at character 0....
Initialize mpv. def init(size=250): """Initialize mpv.""" 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
Save bytes to a file. def bytes_to_file(input_data, output_file): """Save bytes to a file.""" pathlib.Path(output_file.parent).mkdir(parents=True, exist_ok=True) with open(output_file, "wb") as file: file.write(input_data)
Initialize mpd. def init(port=6600, server="localhost"): """Initialize mpd.""" client = mpd.MPDClient() try: client.connect(server, port) return client except ConnectionRefusedError: print("error: Connection refused to mpd/mopidy.") os._exit(1)
Get the album art. def get_art(cache_dir, size, client): """Get the album art.""" 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 / fil...
Download the cover art. def get_cover(song, size=250): """Download the cover art.""" try: data = mus.search_releases(artist=song["artist"], release=song["album"], limit=1) release_id = data["release-list"][0]["release-group"]...
Get the script arguments. def get_args(): """Get the script arguments.""" description = "bum - Download and display album art \ for mpd tracks." arg = argparse.ArgumentParser(description=description) arg.add_argument("--size", metavar="\"px\"", help="what size t...
Main script function. def main(): """Main script function.""" args = get_args() process_args(args) if not args.no_display: disp = display.init(args.size) client = song.init(args.port, args.server) while True: song.get_art(args.cache_dir, args.size, client) if not args...
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! def convertforinput(self...
Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Sourcefile is a CLAMOutputFile instance. def convertforoutput(self,outputfile): """Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Source...
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. def convertforinput(self,filepath, metadata=None): """Convert from target format into one of the source formats. Relevant if converters are us...
Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Outputfile is a CLAMOutputFile instance. def convertforoutput(self,outputfile): """Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Output...
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. If you make use of CUSTOM_FORMATS, you need to pass the CUSTOM_FORMATS list as 2nd argument. def getclamdata(filename, custom_formats=None): global CUSTOM_FORMAT...
Construct a dictionary of parameters, for internal use only def sanitizeparameters(parameters): """Construct a dictionary of parameters, for internal use only""" if not isinstance(parameters,dict): d = {} for x in parameters: if isinstance(x,tuple) and len(x) == 2: f...
Given input files and parameters, produce metadata for outputfiles. Returns a list of matched profiles (empty if none match), and a program. def profiler(profiles, projectpath,parameters,serviceid,servicename,serviceurl,printdebug=None): """Given input files and parameters, produce metadata for outputfiles. Return...
Returns the value string, wrapped in the specified quotes (if not empty), but checks and raises an Exception if the string is at risk of causing code injection def shellsafe(s, quote='', doescape=True): """Returns the value string, wrapped in the specified quotes (if not empty), but checks and raises an Exception ...
Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate def attachviewers(self, profiles): """Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate""" if self.metadata: template = Non...
Returns the filename for the metadata file (not full path). Only used for local files. def metafilename(self): """Returns the filename for the metadata file (not full path). Only used for local files.""" metafilename = os.path.dirname(self.filename) if metafilename: metafilename += '/' ...
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. def loadmetadata(self): """Load metadata for this file. This is usually called automatically upon instantiation, except if...
Delete this file def delete(self): """Delete this file""" 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) ...
Loads all lines in memory def read(self): """Loads all lines in memory""" 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...
Copy or download this file to a new local file def copy(self, target, timeout=500): """Copy or download this file to a new local file""" if self.metadata and 'encoding' in self.metadata: with io.open(target,'w', encoding=self.metadata['encoding']) as f: for line in self: ...
Parses CLAM XML, there's usually no need to call this directly def parseresponse(self, xml, localroot = False): """Parses CLAM XML, there's usually no need to call this directly""" root = parsexmlstring(xml) if root.tag != 'clam': raise FormatError("CLAM root tag not found") ...
Get an output template by ID def outputtemplate(self, template_id): """Get an output template by ID""" for profile in self.profiles: for outputtemplate in profile.outputtemplates(): if outputtemplate.id == template_id: return outputtemplate return...
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. def commandlineargs(self): """Obtain a string of all parameters, using the paramater flags they were defined with, in order to pass to an external comm...
Return the specified global parameter (the entire object, not just the value) def parameter(self, parameter_id): """Return the specified global parameter (the entire object, not just the value)""" for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable for parame...
Return the first parameter error, or False if there is none def parametererror(self): """Return the first parameter error, or False if there is none""" for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable for parameter in parameters: if paramet...
Return all parameters as {id: value} dictionary def passparameters(self): """Return all parameters as {id: value} dictionary""" paramdict = {} for parametergroup, params in self.parameters: #pylint: disable=unused-variable for parameter in params: if parameter.value:...
Return all input templates as a list (of InputTemplate instances) def inputtemplates(self): """Return all input templates as a list (of InputTemplate instances)""" l = [] for profile in self.profiles: l += profile.input return l
Return the inputtemplate with the specified ID. This is used to resolve a inputtemplate ID to an InputTemplate object instance def inputtemplate(self,template_id): """Return the inputtemplate with the specified ID. This is used to resolve a inputtemplate ID to an InputTemplate object instance""" for pr...
Return the inputfile for the specified inputtemplate, if ``inputtemplate=None``, inputfile is returned regardless of inputtemplate. This function may only return 1 and returns an error when multiple input files can be returned, use ``inputfiles()`` instead. def inputfile(self, inputtemplate=None): """Return th...
Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate. def inputfiles(self, inputtemplate=None): """Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned r...
Check if the profile matches all inputdata *and* produces output given the set parameters. Returns a boolean def match(self, projectpath, parameters): """Check if the profile matches all inputdata *and* produces output given the set parameters. Returns a boolean""" parameters = sanitizeparameters(param...
Return a list of all inputfiles matching the profile (filenames) def matchingfiles(self, projectpath): """Return a list of all inputfiles matching the profile (filenames)""" l = [] for inputtemplate in self.input: l += inputtemplate.matchingfiles(projectpath) return l
Returns all outputtemplates, resolving ParameterConditions to all possibilities def outputtemplates(self): """Returns all outputtemplates, resolving ParameterConditions to all possibilities""" outputtemplates = [] for o in self.output: if isinstance(o, ParameterCondition): ...
Generate output metadata on the basis of input files and parameters. Projectpath must be absolute. Returns a Program instance. def generate(self, projectpath, parameters, serviceid, servicename,serviceurl): """Generate output metadata on the basis of input files and parameters. Projectpath must be absolute. Re...
Produce XML output for the profile def xml(self, indent = ""): """Produce XML output for the profile""" xml = "\n" + indent + "<profile>\n" xml += indent + " <input>\n" for inputtemplate in self.input: xml += inputtemplate.xml(indent +" ") + "\n" xml += indent + "...
Return a profile instance from the given XML description. Node can be a string or an etree._Element. def fromxml(node): """Return a profile instance from the given XML description. Node can be a string or an etree._Element.""" if not isinstance(node,ElementTree._Element): #pylint: disable=protected-acc...
Add a new path to the program def add(self, outputfilename, outputtemplate, inputfilename=None, inputtemplate=None): """Add a new path to the program""" if isinstance(outputtemplate,OutputTemplate): outputtemplate = outputtemplate.id if isinstance(inputtemplate,InputTemplate): ...
Iterates over all output files and their output template. Yields (CLAMOutputFile, str:outputtemplate_id) tuples. The last three arguments are passed to its constructor. def getoutputfiles(self, loadmetadata=True, client=None,requiremetadata=False): """Iterates over all output files and their output template. Y...
Iterates over all input files for the specified outputfile (you may pass a CLAMOutputFile instance or a filename string). Yields (CLAMInputFile,str:inputtemplate_id) tuples. The last three arguments are passed to its constructor. def getinputfiles(self, outputfile, loadmetadata=True, client=None,requiremetadata=False)...
Grabs one input file for the specified output filename (raises a KeyError exception if there is no such output, StopIteration if there are no input files for it). Shortcut for getinputfiles() def getinputfile(self, outputfile, loadmetadata=True, client=None,requiremetadata=False): """Grabs one input file for t...
Grabs one output file (raises a StopIteration exception if there is none). Shortcut for getoutputfiles() def getoutputfile(self, loadmetadata=True, client=None,requiremetadata=False): """Grabs one output file (raises a StopIteration exception if there is none). Shortcut for getoutputfiles()""" return n...
Serialise provenance data to XML. This is included in CLAM Metadata files def xml(self, indent = ""): """Serialise provenance data to XML. This is included in CLAM Metadata files""" xml = indent + "<provenance type=\"clam\" id=\""+self.serviceid+"\" name=\"" +self.servicename+"\" url=\"" + self.service...
Return a CLAMProvenanceData instance from the given XML description. Node can be a string or an lxml.etree._Element. def fromxml(node): """Return a CLAMProvenanceData instance from the given XML description. Node can be a string or an lxml.etree._Element.""" if not isinstance(node,ElementTree._Element)...
Render an XML representation of the metadata def xml(self, indent = ""): """Render an XML representation of the metadata""" #(independent of web.py for support in CLAM API) if not indent: xml = '<?xml version="1.0" encoding="UTF-8"?>\n' else: xml = "" xml += inde...
Save metadata to XML file def save(self, filename): """Save metadata to XML file""" with io.open(filename,'w',encoding='utf-8') as f: f.write(self.xml())
Read metadata from XML. Static method returning an CLAMMetaData instance (or rather; the appropriate subclass of CLAMMetaData) from the given XML description. Node can be a string or an etree._Element. def fromxml(node, file=None): """Read metadata from XML. Static method returning an CLAMMetaData instance (or...
Produce Template XML def xml(self, indent = ""): """Produce Template XML""" xml = indent + "<InputTemplate id=\""+self.id+"\" format=\"" + self.formatclass.__name__ + "\"" + " label=\"" + self.label + "\"" if self.formatclass.mimetype: xml +=" mimetype=\""+self.formatclass.mimetype+...
Produce a JSON representation for the web interface def json(self): """Produce a JSON representation for the web interface""" d = { 'id': self.id, 'format': self.formatclass.__name__,'label': self.label, 'mimetype': self.formatclass.mimetype, 'schema': self.formatclass.schema } if self.unique:...
Does the specified metadata match this template? returns (success,metadata,parameters) def match(self, metadata, user = None): """Does the specified metadata match this template? returns (success,metadata,parameters)""" assert isinstance(metadata, self.formatclass) return self.generate(metadata...
Checks if the input conditions are satisfied, i.e the required input files are present. We use the symbolic links .*.INPUTTEMPLATE.id.seqnr to determine this. Returns a list of matching results (seqnr, filename, inputtemplate). def matchingfiles(self, projectpath): """Checks if the input conditions are satisfi...
Validate posted data against the inputtemplate def validate(self, postdata, user = None): """Validate posted data against the inputtemplate""" clam.common.util.printdebug("Validating inputtemplate " + self.id + "...") errors, parameters, _ = processparameters(postdata, self.parameters, user)...
Convert the template into instantiated metadata, validating the data in the process and returning errors otherwise. inputdata is a dictionary-compatible structure, such as the relevant postdata. Return (success, metadata, parameters), error messages can be extracted from parameters[].error. Validatedata is a (errors,pa...
Serialize the metadata field to XML def xml(self, operator='set', indent = ""): """Serialize the metadata field to XML""" xml = indent + "<meta id=\"" + self.key + "\"" if operator != 'set': xml += " operator=\"" + operator + "\"" if not self.value: xml += " />" ...
Static method returning an MetaField instance (any subclass of AbstractMetaField) from the given XML description. Node can be a string or an etree._Element. def fromxml(node): """Static method returning an MetaField instance (any subclass of AbstractMetaField) from the given XML description. Node can be a stri...
Produce Template XML def xml(self, indent = ""): """Produce Template XML""" xml = indent + "<OutputTemplate id=\"" + self.id + "\" format=\"" + self.formatclass.__name__ + "\"" + " label=\"" + self.label + "\"" if self.formatclass.mimetype: xml +=" mimetype=\""+self.formatclass.mime...
Static method return an OutputTemplate instance from the given XML description. Node can be a string or an etree._Element. def fromxml(node): """Static method return an OutputTemplate instance from the given XML description. Node can be a string or an etree._Element.""" if not isinstance(node,ElementTr...
Find the most suitable parent, that is: the first matching unique/multi inputtemplate def findparent(self, inputtemplates): """Find the most suitable parent, that is: the first matching unique/multi inputtemplate""" for inputtemplate in inputtemplates: if self.unique == inputtemplate.unique...
Resolve a parent ID def getparent(self, profile): """Resolve a parent ID""" assert self.parent for inputtemplate in profile.input: if inputtemplate == self.parent: return inputtemplate raise Exception("Parent InputTemplate '"+self.parent+"' not found!")
Yields (inputtemplate, inputfilename, outputfilename, metadata) tuples def generate(self, profile, parameters, projectpath, inputfiles, provenancedata=None): """Yields (inputtemplate, inputfilename, outputfilename, metadata) tuples""" project = os.path.basename(projectpath) if self.parent: #p...
Generate metadata, given a filename, parameters and a dictionary of inputdata (necessary in case we copy from it) def generatemetadata(self, parameters, parentfile, relevantinputfiles, provenancedata = None): """Generate metadata, given a filename, parameters and a dictionary of inputdata (necessary in case we...
Returns all possible outputtemplates that may occur (recusrively applied) def allpossibilities(self): """Returns all possible outputtemplates that may occur (recusrively applied)""" l = [] if isinstance(self.then, ParameterCondition): #recursive parametercondition l += s...
Returns False if there's no match, or whatever the ParameterCondition evaluates to (recursively applied!) def evaluate(self, parameters): """Returns False if there's no match, or whatever the ParameterCondition evaluates to (recursively applied!)""" if self.match(parameters): if isinstance(...
Static method returning a ParameterCondition instance from the given XML description. Node can be a string or an etree._Element. def fromxml(node): """Static method returning a ParameterCondition instance from the given XML description. Node can be a string or an etree._Element.""" if not isinstance(no...
Static method returning an Action instance from the given XML description. Node can be a string or an etree._Element. def fromxml(node): """Static method returning an Action instance from the given XML description. Node can be a string or an etree._Element.""" if not isinstance(node,ElementTree._Elemen...
This is a very crude tokenizer from pynlpl def crude_tokenizer(line): """This is a very crude tokenizer from pynlpl""" tokens = [] buffer = '' for c in line.strip(): if c == ' ' or c in string.punctuation: if buffer: tokens.append(buffer) buffer = '' ...
Function for converting dictionary to plaintext output, optionally with some (reverse) sorting def dicttotext(d, sort=False, max = 0): """Function for converting dictionary to plaintext output, optionally with some (reverse) sorting""" if sort: f = lambda x: sorted(x, key=lambda y: -1 * y[1]) else:...
Initialise authentication, for internal use def initauth(self): """Initialise authentication, for internal use""" headers = {'User-agent': 'CLAMClientAPI-' + clam.common.data.VERSION} if self.oauth: if not self.oauth_access_token: r = requests.get(self.url,headers=he...
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 def request(self, url='', method = 'GET', data = None, parse=True, encoding=None): """Issue a HTTP request and parse CLAM XML response, this is...
Parses CLAM XML data and returns a ``CLAMData`` object. For internal use. Raises `ParameterError` exception on parameter errors. def _parse(self, content): """Parses CLAM XML data and returns a ``CLAMData`` object. For internal use. Raises `ParameterError` exception on parameter errors.""" if content.f...
Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code def get(self, project): """Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code""" try: data = s...
Query an action, specify the parameters for the action as keyword parameters. An optional keyword parameter method='GET' (default) or method='POST' can be set. The character set encoding of the response can be configured using the encoding keyword parameter (defaults to utf-8 by default) def action(self, action_id, **...
Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for the global parameters. Returns a ``CLAMData`` object or raises exceptions. Note that no exceptions are raised on parameter errors, you have to check for those manually! (Use startsafe instead if want Exceptions on pa...
Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for the global parameters. Returns a ``CLAMData`` object or raises exceptions. This version, unlike ``start()``, raises Exceptions (``ParameterError``) on parameter errors. response = client.startsafe("mypro...
Download all output files as a single archive: * *targetfile* - path for the new local file to be written * *archiveformat* - the format of the archive, can be 'zip','gz','bz2' Example:: client.downloadarchive("myproject","allresults.zip","zip") def downloadarchive(self, project,...
Determine the final filename for an input file given an inputtemplate and a given filename. Example:: filenameonserver = client.getinputfilename("someinputtemplate","/path/to/local/file") def getinputfilename(self, inputtemplate, filename): """Determine the final filename for an input fil...
Parse CLAM Upload XML Responses. For internal use def _parseupload(self, node): """Parse CLAM Upload XML Responses. For internal use""" if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access try: node = clam.common.data.parsexmlstring(node) ...
Add/upload an input file to the CLAM service. Supports proper file upload streaming. project - the ID of the project you want to add the file to. inputtemplate - The input template you want to use to add this file (InputTemplate instance) sourcefile - The file you want to add: string containing...
Add an input file to the CLAM service. Explictly providing the contents as a string. This is not suitable for large files as the contents are kept in memory! Use ``addinputfile()`` instead for large files. project - the ID of the project you want to add the file to. inputtemplate - The input template y...
Alias for ``addinputfile()`` def upload(self,project, inputtemplate, sourcefile, **kwargs): """Alias for ``addinputfile()``""" return self.addinputfile(project, inputtemplate,sourcefile, **kwargs)
Download an output file def download(self, project, filename, targetfilename, loadmetadata=None): """Download an output file""" if loadmetadata is None: loadmetadata = self.loadmetadata f = clam.common.data.CLAMOutputFile(self.url + project, filename, loadmetadata, self) f.copy(targetf...
Validate the parameter def validate(self,value): """Validate the parameter""" 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(vali...
This method compiles the parameter into syntax that can be used on the shell, such as for example: --paramflag=value def compilearg(self): """This method compiles the parameter into syntax that can be used on the shell, such as for example: --paramflag=value""" if self.paramflag and self.paramflag[-1] ...
This methods renders an XML representation of this parameter, along with its selected value, and feedback on validation errors def xml(self, indent = ""): """This methods renders an XML representation of this parameter, along with its selected value, and feedback on validation errors""" ...
This parameter method attempts to set a specific value for this parameter. The value will be validated first, and if it can not be set. An error message will be set in the error property of this parameter def set(self, value): """This parameter method attempts to set a specific value for this parameter. The va...
This method checks if the given user has access to see/set this parameter, based on the denyusers and/or allowusers option. def access(self, user): """This method checks if the given user has access to see/set this parameter, based on the denyusers and/or allowusers option.""" if self.denyusers: ...
Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element def fromxml(node): """Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containi...
Set the boolean parameter def set(self, value = True): """Set the boolean parameter""" 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"))) #pylint: disable=undefined-variable return su...
This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set(). It typically returns the default None when something is left unset (but that default can be overridden) def valuefrompostdata(se...
This method compiles the parameter into syntax that can be used on the shell, such as -paramflag=value def compilearg(self): """This method compiles the parameter into syntax that can be used on the shell, such as -paramflag=value""" if isinstance(self.value,list): value = self.delimiter.jo...
This methods renders an XML representation of this parameter, along with its selected value, and feedback on validation errors def xml(self, indent = ""): """This methods renders an XML representation of this parameter, along with its selected value, and feedback on validation errors""" ...