code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def get_git_remote_url(path='.', remote='origin'): return dulwich.repo.Repo.discover(path).get_config()\ .get((b'remote', remote.encode('utf-8')), b'url').decode('utf-8')
Get git remote url :param path: path to repo :param remote: :return: remote url or exception
def plantuml(desc): classes, relations, inherits = desc result = [ '@startuml', 'skinparam defaultFontName Courier', ] for cls in classes: # issue #11 - tabular output of class members (attrs) # http://stackoverflow.com/a/8356620/258194 # build table ...
Generate plantuml class diagram :param desc: result of sadisplay.describe function Return plantuml class diagram string
def is_reference_target(resource, rtype, label): prop = resource.props.references.get(rtype, False) if prop: return label in prop
Return true if the resource has this rtype with this label
def get_sources(self, resources): rtype = self.rtype # E.g. category label = self.props.label # E.g. category1 result = [ resource for resource in resources.values() if is_reference_target(resource, rtype, label) ] return result
Filter resources based on which have this reference
def icon(self): path = self._icon if not path: return '' path = os.path.expandvars(os.path.expanduser(path)) if path.startswith('.'): base_path = os.path.dirname(self.filepath()) path = os.path.abspath(os.path.join(base_path, path)) ...
Returns the icon filepath for this plugin. :return <str>
def addPluginPath(cls, pluginpath): prop_key = '_%s__pluginpath' % cls.__name__ curr_path = getattr(cls, prop_key, None) if not curr_path: curr_path = [] setattr(cls, prop_key, curr_path) if isinstance(pluginpath, basestring): pluginpath = pl...
Adds the plugin path for this class to the given path. The inputted pluginpath value can either be a list of strings, or a string containing paths separated by the OS specific path separator (':' on Mac & Linux, ';' on Windows) :param pluginpath | [<str>, ..] || <str>
def pluginRegisterType(cls): default = Plugin.Type.Module default |= Plugin.Type.Package default |= Plugin.Type.RegistryFile return getattr(cls, '_%s__pluginRegisterType', default)
Returns the register type for this plugin class. :return <Plugin.RegisterType>
def plugin(cls, name): cls.loadPlugins() plugs = getattr(cls, '_%s__plugins' % cls.__name__, {}) return plugs.get(nstr(name))
Retrieves the plugin based on the inputted name. :param name | <str> :return <Plugin>
def pluginNames(cls, enabled=True): return map(lambda x: x.name(), cls.plugins(enabled))
Returns the names of the plugins for a given class. :param enabled | <bool> || None :return [<str>, ..]
def plugins(cls, enabled=True): cls.loadPlugins() plugs = getattr(cls, '_%s__plugins' % cls.__name__, {}).values() if enabled is None: return plugs return filter(lambda x: x.isEnabled() == enabled, plugs)
Returns the plugins for the given class. :param enabled | <bool> || None :return [<Plugin>, ..]
def register(cls, plugin): plugs = getattr(cls, '_%s__plugins' % cls.__name__, None) if plugs is None: cls.loadPlugins() plugs = getattr(cls, '_%s__plugins' % cls.__name__, {}) if plugin.name() in plugs: inst = plugs[plugin.name()] # assign...
Registers the given plugin instance to this system. If a plugin with the same name is already registered, then this plugin will not take effect. The first registered plugin is the one that is used. :param plugin | <Plugin> :return <bool>
def setPluginPath(cls, pluginpath): setattr(cls, '_%s__pluginpath' % cls.__name__, None) cls.addPluginPath(pluginpath)
Sets the plugin path for this class to the given path. The inputted pluginpath value can either be a list of strings, or a string containing paths separated by the OS specific path separator (':' on Mac & Linux, ';' on Windows) :param pluginpath | [<str>, ..] || <str>
def unregister(cls, plugin): plugs = getattr(cls, '_%s__plugins' % cls.__name__, {}) try: plugs.pop(plugin.name()) except AttributeError: pass except ValueError: pass
Unregisters the given plugin from the system based on its name. :param plugin | <Plugin>
def loadInstance(self): if self._loaded: return self._loaded = True module_path = self.modulePath() package = projex.packageFromPath(module_path) path = os.path.normpath(projex.packageRootPath(module_path)) if path in sys.path: sys.path...
Loads the plugin from the proxy information that was created from the registry file.
def modulePath(self): base_path = os.path.dirname(self.filepath()) module_path = self.importPath() module_path = os.path.expanduser(os.path.expandvars(module_path)) if module_path.startswith('.'): module_path = os.path.abspath(os.path.join(base_path, module_path)) ...
Returns the module path information for this proxy plugin. This path will represent the root module that will be imported when the instance is first created of this plugin. :return <str>
def fromFile(cls, filepath): xdata = ElementTree.parse(nstr(filepath)) xroot = xdata.getroot() # collect variable information name = xroot.get('name') ver = float(xroot.get('version', '1.0')) if not name: name = os.path.basename(filepath).split('.')...
Creates a proxy instance from the inputted registry file. :param filepath | <str> :return <PluginProxy> || None
def clean_resource_json(resource_json): for a in ('parent_docname', 'parent', 'template', 'repr', 'series'): if a in resource_json: del resource_json[a] props = resource_json['props'] for prop in ( 'acquireds', 'style', 'in_nav', 'nav_title', 'weight', 'aut...
The catalog wants to be smaller, let's drop some stuff
def resources_to_json(resources): return { docname: clean_resource_json(resource.__json__(resources)) for (docname, resource) in resources.items() }
Make a JSON/catalog representation of the resources db
def references_to_json(resources, references): dump_references = {} for reftype, refvalue in references.items(): dump_references[reftype] = {} for label, reference_resource in refvalue.items(): target_count = len(reference_resource.get_sources(resources)) dump_refer...
Make a JSON/catalog representation of the references db, including the count for each
def get(self, url, params=None, cache_cb=None, **kwargs): if self.use_random_user_agent: headers = kwargs.get("headers", dict()) headers.update({Headers.UserAgent.KEY: Headers.UserAgent.random()}) kwargs["headers"] = he...
Make http get request. :param url: :param params: :param cache_cb: (optional) a function that taking requests.Response as input, and returns a bool flag, indicate whether should update the cache. :param cache_expire: (optional). :param kwargs: optional arguments.
def get_html(self, url, params=None, cache_cb=None, decoder_encoding=None, decoder_errors=url_specified_decoder.ErrorsHandle.strict, **kwargs): response = self.get( url=url, par...
Get html of an url.
def download(self, url, dst, params=None, cache_cb=None, overwrite=False, stream=False, minimal_size=-1, maximum_size=1024 ** 6, **kwargs): response =...
Download binary content to destination. :param url: binary content url :param dst: path to the 'save_as' file :param cache_cb: (optional) a function that taking requests.Response as input, and returns a bool flag, indicate whether should update the cache. :param overwrite: b...
def option(*args, **kwargs): def decorate_sub_command(method): """create and add sub-command options""" if not hasattr(method, "optparser"): method.optparser = SubCmdOptionParser() method.optparser.add_option(*args, **kwargs) return method def decorate_class(klas...
Decorator to add an option to the optparser argument of a Cmdln subcommand To add a toplevel option, apply the decorator on the class itself. (see p4.py for an example) Example: @cmdln.option("-E", dest="environment_path") class MyShell(cmdln.Cmdln): @cmdln.option("-f",...
def _inherit_attr(klass, attr, default, cp): if attr not in klass.__dict__: if hasattr(klass, attr): value = cp(getattr(klass, attr)) else: value = default setattr(klass, attr, value)
Inherit the attribute from the base class Copy `attr` from base class (otherwise use `default`). Copying is done using the passed `cp` function. The motivation behind writing this function is to allow inheritance among Cmdln classes where base classes set 'common' options using the `@cmdln.option`...
def _forgiving_issubclass(derived_class, base_class): return (type(derived_class) is ClassType and \ type(base_class) is ClassType and \ issubclass(derived_class, base_class))
Forgiving version of ``issubclass`` Does not throw any exception when arguments are not of class type
def applyTimeCalMs1(msrunContainer, specfile, correctionData, **kwargs): toleranceMode = kwargs.get('toleranceMode', 'relative') if toleranceMode == 'relative': for siId in correctionData: calibValue = correctionData[siId]['calibValue'] msrunContainer.saic[specfile][siId].a...
Applies correction values to the MS1 ion m/z arrays in order to correct for a time dependent m/z error. :param msrunContainer: intance of :class:`maspy.core.MsrunContainer`, containing the :class:`maspy.core.Sai` items of the "specfile". :param specfile: filename of an ms-run file to which the m/z ...
def applyMassCalMs1(msrunContainer, specfile, dataFit, **kwargs): toleranceMode = kwargs.get('toleranceMode', 'relative') if toleranceMode == 'relative': for si in msrunContainer.getItems(specfile, selector=lambda si: si.msLevel==1): mzArr = ms...
Applies a correction function to the MS1 ion m/z arrays in order to correct for a m/z dependent m/z error. :param msrunContainer: intance of :class:`maspy.core.MsrunContainer`, containing the :class:`maspy.core.Sai` items of the "specfile". :param specfile: filename of an ms-run file to which the m...
def _make(self, key, content): pass self.say('make a new key>>>' + key + '>>>with>>>:' + str(content)) if key.isdigit(): i = int(key) # list index [p] self.say('extending parent list to contain index:' + key) # make a list with size retur...
clean
def set_path(self, data, path, value): self.say('set_path:value:' + str(value) + ' at:' + str(path) + ' in:' + str(data)) if isinstance(path, str): path = path.split('.') if len(path) > 1: self.set_path(data.setdefault(path[0], {}), path[1:], va...
Sets the given key in the given dict object to the given value. If the given path is nested, child dicts are created as appropriate. Accepts either a dot-delimited path or an array of path elements as the `path` variable.
def get_genericpage(cls, kb_app): # Presumes the registry has been committed q = dectate.Query('genericpage') klasses = sorted(q(kb_app), key=lambda args: args[0].order) if not klasses: # The site doesn't configure a genericpage, return Genericpage ...
Return the one class if configured, otherwise default
def buy_product(self, product_pk): if self.invoice_sales.filter(lines_sales__product_final__pk=product_pk).exists() \ or self.ticket_sales.filter(lines_sales__product_final__pk=product_pk).exists(): return True else: return False
determina si el customer ha comprado un producto
def create_ticket_from_albaran(pk, list_lines): MODEL_SOURCE = SalesAlbaran MODEL_FINAL = SalesTicket url_reverse = 'CDNX_invoicing_ticketsaless_list' # type_doc msg_error_relation = _("Hay lineas asignadas a ticket") msg_error_not_found = _('Sales albaran not found') ...
context = {} if list_lines: new_list_lines = SalesLines.objects.filter( pk__in=[int(x) for x in list_lines] ).exclude( invoice__isnull=True ).values_list('pk') if new_list_lines: new_pk = SalesLines.objects.values_l...
def create_invoice_from_albaran(pk, list_lines): MODEL_SOURCE = SalesAlbaran MODEL_FINAL = SalesInvoice url_reverse = 'CDNX_invoicing_invoicesaless_list' # type_doc msg_error_relation = _("Hay lineas asignadas a facturas") msg_error_not_found = _('Sales albaran not found'...
context = {} if list_lines: new_list_lines = SalesLines.objects.filter( pk__in=[int(x) for x in list_lines] ).exclude( invoice__isnull=False ) if new_list_lines: new_pk = new_list_lines.first() if ne...
def create_invoice_from_ticket(pk, list_lines): MODEL_SOURCE = SalesTicket MODEL_FINAL = SalesInvoice url_reverse = 'CDNX_invoicing_invoicesaless_list' # type_doc msg_error_relation = _("Hay lineas asignadas a facturas") msg_error_not_found = _('Sales ticket not found') ...
context = {} if list_lines: new_list_lines = SalesLines.objects.filter( pk__in=[int(x) for x in list_lines] ).exclude( invoice__isnull=T...
def cli(ctx): manfile = bubble_lib_dir+os.sep+'extras'+os.sep+'Bubble.1.gz' mancmd = ["/usr/bin/man", manfile] try: return subprocess.call(mancmd) except Exception as e: print('cannot run man with bubble man page') print('you can always have a look at: '+manfile)
Shows the man page packed inside the bubble tool this is mainly too overcome limitations on installing manual pages in a distribution agnostic and simple way and the way bubble has been developed, in virtual python environments, installing a man page into a system location makes no sense, the system ma...
def _fetch_dimensions(self, dataset): for dimension in super(SCB, self)._fetch_dimensions(dataset): if dimension.id == "Region": yield Dimension(dimension.id, datatype="region", dialect="skatteverket", ...
We override this method just to set the correct datatype and dialect for regions.
def call(self, func, key, timeout=None): '''Wraps a function call with cache. Args: func (function): the function to call. key (str): the cache key for this call. timeout (int): the cache timeout for the key (the unit of this parameter depe...
Wraps a function call with cache. Args: func (function): the function to call. key (str): the cache key for this call. timeout (int): the cache timeout for the key (the unit of this parameter depends on the cache class yo...
def default_ssl_context() -> ssl.SSLContext: ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH) # OP_NO_SSLv2, OP_NO_SSLv3, and OP_NO_COMPRESSION are already set by default # so we just need to disable the old versions of TLS. ctx.options |= (ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1) ...
Creates an SSL context suitable for use with HTTP/2. See https://tools.ietf.org/html/rfc7540#section-9.2 for what this entails. Specifically, we are interested in these points: § 9.2: Implementations of HTTP/2 MUST use TLS version 1.2 or higher. § 9.2.1: A deployment of HTTP/2 over TLS 1.2 MUST...
async def _window_open(self, stream_id: int): stream = self._get_stream(stream_id) return await stream.window_open.wait()
Wait until the identified stream's flow control window is open.
async def send_data( self, stream_id: int, data: bytes, end_stream: bool = False, ): if self.closed: raise ConnectionClosedError stream = self._get_stream(stream_id) if stream.closed: raise StreamClosedError(stream_id) ...
Send data, respecting the receiver's flow control instructions. If the provided data is larger than the connection's maximum outbound frame size, it will be broken into several frames as appropriate.
async def read_data(self, stream_id: int) -> bytes: frames = [f async for f in self.stream_frames(stream_id)] return b''.join(frames)
Read data from the specified stream until it is closed by the remote peer. If the stream is never ended, this never returns.
async def read_frame(self, stream_id: int) -> bytes: stream = self._get_stream(stream_id) frame = await stream.read_frame() if frame.flow_controlled_length > 0: self._acknowledge_data(frame.flow_controlled_length, stream_id) return frame.data
Read a single frame of data from the specified stream, waiting until frames are available if none are present in the local buffer. If the stream is closed and all buffered frames have been consumed, raises a StreamConsumedError.
async def get_pushed_stream_ids(self, parent_stream_id: int) -> List[int]: if parent_stream_id not in self._streams: logger.error( f'Parent stream {parent_stream_id} unknown to this connection' ) raise NoSuchStreamError(parent_stream_id) paren...
Return a list of all streams pushed by the remote peer that are children of the specified stream. If no streams have been pushed when this method is called, waits until at least one stream has been pushed.
def populate(self, obj): # query if type(obj) is AtlasServiceInstance.Instance: query = { "instance_id" : obj.instance_id, "binding_id" : { "$exists" : False } } elif type(obj) is AtlasServiceBinding.Binding: query = { "binding_id" : obj.binding_id, "ins...
Populate Query mongo to get information about the obj if it exists Args: obj (AtlasServiceBinding.Binding or AtlasServiceInstance.Instance): instance or binding Raises: ErrStorageTypeUnsupported: Type unsupported. ErrStorageMongoConn...
def store(self, obj): # query if type(obj) is AtlasServiceInstance.Instance: query = { "instance_id" : obj.instance_id, "database" : obj.get_dbname(), "cluster": obj.get_cluster(), "parameters" : obj.parameters } elif type(obj) is AtlasServiceBinding.Binding: ...
Store Store an object into the MongoDB storage for caching Args: obj (AtlasServiceBinding.Binding or AtlasServiceInstance.Instance): instance or binding Returns: ObjectId: MongoDB _id Raises: ErrStorageMongoConn...
def remove(self, obj): if type(obj) is AtlasServiceInstance.Instance: self.remove_instance(obj) elif type(obj) is AtlasServiceBinding.Binding: self.remove_binding(obj) else: raise ErrStorageTypeUnsupported(type(obj))
Remove Remove an object from the MongoDB storage for caching Args: obj (AtlasServiceBinding.Binding or AtlasServiceInstance.Instance): instance or binding Raises: ErrStorageTypeUnsupported: Type unsupported.
def remove_instance(self, instance): # query query = { "instance_id" : instance.instance_id, "binding_id" : { "$exists" : False } } # delete the instance try: result = self.broker.delete_one(query) except: raise ErrStorageMongoCo...
Remove an instance Remove an object from the MongoDB storage for caching Args: instance (AtlasServiceInstance.Instance): instance Raises: ErrStorageMongoConnection: Error during MongoDB communication. ErrStorageRemoveInstance: Failed...
def remove_binding(self, binding): # query query = { "binding_id" : binding.binding_id, "instance_id" : binding.instance.instance_id } # delete the binding try: result = self.broker.delete_one(query) except: raise ErrStorageMongo...
Remove a binding Remove an object from the MongoDB storage for caching Args: binding (AtlasServiceBinding.Binding): binding Raises: ErrStorageMongoConnection: Error during MongoDB communication. ErrStorageRemoveBinding: Failed to...
def handle(self, request, buffer_size): if self.component_type == StreamComponent.SOURCE: msg = self.handler_function() return self.__send(request, msg) logger = self.logger data = self.__receive(request, buffer_size) if data is None: retur...
Handle a message :param request: the request socket. :param buffer_size: the buffer size. :return: True if success, False otherwise
def handle(self, request, buffer_size): logger = self.logger data = self.__receive(request, buffer_size) if data is None: return False else: arr = array('B',data) for message in split_array(arr,StxEtxHandler.ETX): if message[0...
Handle a message :param request: the request socket. :param buffer_size: the buffer size. :return: True if success, False otherwise
def handle(self, request, buffer_size): logger = self.logger msg = self.__receive(request, buffer_size) if msg is None: return False result = self.handler_function(msg) if self.component_type == StreamComponent.PROCESSOR: return self.__send(requ...
Handle a message :param request: the request socket. :param buffer_size: the buffer size. :return: True if success, False otherwise
def defaultFetchSiAttrFromSmi(smi, si): for key, value in viewitems(fetchSpectrumInfo(smi)): setattr(si, key, value) for key, value in viewitems(fetchScanInfo(smi)): setattr(si, key, value) if si.msLevel > 1: for key, value in viewitems(fetchParentIon(smi)): setattr(...
Default method to extract attributes from a spectrum metadata item (sai) and adding them to a spectrum item (si).
def convertMzml(mzmlPath, outputDirectory=None): outputDirectory = outputDirectory if outputDirectory is not None else os.path.dirname(mzmlPath) msrunContainer = importMzml(mzmlPath) msrunContainer.setPath(outputDirectory) msrunContainer.save()
Imports an mzml file and converts it to a MsrunContainer file :param mzmlPath: path of the mzml file :param outputDirectory: directory where the MsrunContainer file should be written if it is not specified, the output directory is set to the mzml files directory.
def prepareSiiImport(siiContainer, specfile, path, qcAttr, qcLargerBetter, qcCutoff, rankAttr, rankLargerBetter): if specfile not in siiContainer.info: siiContainer.addSpecfile(specfile, path) else: raise Exception('...') siiContainer.info[specfile]['qcAttr'] = qcA...
Prepares the ``siiContainer`` for the import of peptide spectrum matching results. Adds entries to ``siiContainer.container`` and to ``siiContainer.info``. :param siiContainer: instance of :class:`maspy.core.SiiContainer` :param specfile: unambiguous identifier of a ms-run file. Is also used as ...
def addSiiToContainer(siiContainer, specfile, siiList): for sii in siiList: if sii.id not in siiContainer.container[specfile]: siiContainer.container[specfile][sii.id] = list() siiContainer.container[specfile][sii.id].append(sii)
Adds the ``Sii`` elements contained in the siiList to the appropriate list in ``siiContainer.container[specfile]``. :param siiContainer: instance of :class:`maspy.core.SiiContainer` :param specfile: unambiguous identifier of a ms-run file. Is also used as a reference to other MasPy file containers....
def applySiiRanking(siiContainer, specfile): attr = siiContainer.info[specfile]['rankAttr'] reverse = siiContainer.info[specfile]['rankLargerBetter'] for itemList in listvalues(siiContainer.container[specfile]): sortList = [(getattr(sii, attr), sii) for sii in itemList] itemList = [sii ...
Iterates over all Sii entries of a specfile in siiContainer and sorts Sii elements of the same spectrum according to the score attribute specified in ``siiContainer.info[specfile]['rankAttr']``. Sorted Sii elements are then ranked according to their sorted position, if multiple Sii have the same score,...
def applySiiQcValidation(siiContainer, specfile): attr = siiContainer.info[specfile]['qcAttr'] cutOff = siiContainer.info[specfile]['qcCutoff'] if siiContainer.info[specfile]['qcLargerBetter']: evaluator = lambda sii: getattr(sii, attr) >= cutOff and sii.rank == 1 else: evaluator = ...
Iterates over all Sii entries of a specfile in siiContainer and validates if they surpass a user defined quality threshold. The parameters for validation are defined in ``siiContainer.info[specfile]``: - ``qcAttr``, ``qcCutoff`` and ``qcLargerBetter`` In addition to passing this validation a ``Sii...
def _importDinosaurTsv(filelocation): with io.open(filelocation, 'r', encoding='utf-8') as openFile: #NOTE: this is pretty similar to importing percolator results, maybe unify in a common function lines = openFile.readlines() headerDict = dict([[y,x] for (x,y) in enumerate(lines[0].stri...
Reads a Dinosaur tsv file. :returns: {featureKey1: {attribute1:value1, attribute2:value2, ...}, ...} See also :func:`importPeptideFeatures`
def rst_to_html(input_string: str) -> str: overrides = dict(input_encoding='unicode', doctitle_xform=True, initial_header_level=1) parts = publish_parts( writer_name='html', source=input_string, settings_overrides=overrides ) return parts['html_body']
Given a string of RST, use docutils to generate html
def get_rst_title(rst_doc: Node) -> Optional[Any]: for title in rst_doc.traverse(nodes.title): return title.astext() return None
Given some RST, extract what docutils thinks is the title
def get_rst_excerpt(rst_doc: document, paragraphs: int = 1) -> str: texts = [] for count, p in enumerate(rst_doc.traverse(paragraph)): texts.append(p.astext()) if count + 1 == paragraphs: break return ' '.join(texts)
Given rst, parse and return a portion
def requires_password_auth(fn): def wrapper(self, *args, **kwargs): self.auth_context = HAPI.auth_context_password return fn(self, *args, **kwargs) return wrapper
Decorator for HAPI methods that requires the instance to be authenticated with a password
def requires_api_auth(fn): def wrapper(self, *args, **kwargs): self.auth_context = HAPI.auth_context_hapi return fn(self, *args, **kwargs) return wrapper
Decorator for HAPI methods that requires the instance to be authenticated with a HAPI token
def parse(response): """Split a a=1b=2c=3 string into a dictionary of pairs""" tokens = {r[0]: r[1] for r in [r.split('=') for r in response.split("&")]} # The odd dummy parameter is of no use to us if 'dummy' in tokens: del tokens['dummy'] """ If ...
Parse a postdata-style response format from the API into usable data
def init_chain(self): if not self._hasinit: self._hasinit = True self._devices = [] self.jtag_enable() while True: # pylint: disable=no-member idcode = self.rw_dr(bitcount=32, read=True, ...
Autodetect the devices attached to the Controller, and initialize a JTAGDevice for each. This is a required call before device specific Primitives can be used.
def get_fitted_lv1_prim(self, reqef, bitcount): res = self._fitted_lv1_prim_cache.get(reqef) if res: return res prim = self.get_best_lv1_prim(reqef, bitcount) dispatcher = PrimitiveLv1Dispatcher(self, prim, reqef) self._fitted_lv1_prim_cache[reqef] = dispatch...
request r - A C 0 1 e -|? ! ! ! ! s A|? ✓ ✓ 0 1 Check this logic u C|? m ✓ 0 1 l 0|? M M 0 ! t 1|? M M ! 1 - = No Care A = arbitrary C = Constant 0 = ZERO 1 = ONE ! = ERROR ? = NO CARE RESULT ✓ = Pass dat...
def _UserUpdateConfigValue(self, configKey, strDescriptor, isDir = True, dbConfigValue = None): newConfigValue = None if dbConfigValue is None: prompt = "Enter new {0} or 'x' to exit: ".format(strDescriptor) else: prompt = "Enter 'y' to use existing {0}, enter a new {0} or 'x' to exit: ".f...
Allow user to set or update config values in the database table. This is always called if no valid entry exists in the table already. Parameters ---------- configKey : string Name of config field. strDescriptor : string Description of config field. isDir : boolean [optio...
def _GetConfigValue(self, configKey, strDescriptor, isDir = True): goodlogging.Log.Info("CLEAR", "Loading {0} from database:".format(strDescriptor)) goodlogging.Log.IncreaseIndent() configValue = self._db.GetConfigValue(configKey) if configValue is None: goodlogging.Log.Info("CLEAR", "No {0}...
Get configuration value from database table. If no value found user will be prompted to enter one. Parameters ---------- configKey : string Name of config field. strDescriptor : string Description of config field. isDir : boolean [optional : default = True] Set t...
def _UserUpdateSupportedFormats(self, origFormatList = []): formatList = list(origFormatList) inputDone = None while inputDone is None: prompt = "Enter new format (e.g. .mp4, .avi), " \ "'r' to reset format list, " \ "'f' to finish or " \...
Add supported formats to database table. Always called if the database table is empty. User can build a list of entries to add to the database table (one entry at a time). Once finished they select the finish option and all entries will be added to the table. They can reset the list at any time bef...
def _GetSupportedFormats(self): goodlogging.Log.Info("CLEAR", "Loading supported formats from database:") goodlogging.Log.IncreaseIndent() formatList = self._db.GetSupportedFormats() if formatList is None: goodlogging.Log.Info("CLEAR", "No supported formats exist in database") formatLi...
Get supported format values from database table. If no values found user will be prompted to enter values for this table. Returns ---------- string List of supported formats from database table.
def _UserUpdateIgnoredDirs(self, origIgnoredDirs = []): ignoredDirs = list(origIgnoredDirs) inputDone = None while inputDone is None: prompt = "Enter new directory to ignore (e.g. DONE), " \ "'r' to reset directory list, " \ "'f' to finish or...
Add ignored directories to database table. Always called if the database table is empty. User can build a list of entries to add to the database table (one entry at a time). Once finished they select the finish option and all entries will be added to the table. They can reset the list at any time b...
def _GetIgnoredDirs(self): goodlogging.Log.Info("CLEAR", "Loading ignored directories from database:") goodlogging.Log.IncreaseIndent() ignoredDirs = self._db.GetIgnoredDirs() if ignoredDirs is None: goodlogging.Log.Info("CLEAR", "No ignored directories exist in database") ignoredDirs ...
Get ignored directories values from database table. If no values found user will be prompted to enter values for this table. Returns ---------- string List of ignored directories from database table.
def _GetDatabaseConfig(self): goodlogging.Log.Seperator() goodlogging.Log.Info("CLEAR", "Getting configuration variables...") goodlogging.Log.IncreaseIndent() # SOURCE DIRECTORY if self._sourceDir is None: self._sourceDir = self._GetConfigValue('SourceDir', 'source directory') # TV ...
Get all configuration from database. This includes values from the Config table as well as populating lists for supported formats and ignored directories from their respective database tables.
def _GetSupportedFilesInDir(self, fileDir, fileList, supportedFormatList, ignoreDirList): goodlogging.Log.Info("CLEAR", "Parsing file directory: {0}".format(fileDir)) if os.path.isdir(fileDir) is True: for globPath in glob.glob(os.path.join(fileDir, '*')): if util.FileExtensionMatch(globPath,...
Recursively get all supported files given a root search directory. Supported file extensions are given as a list, as are any directories which should be ignored. The result will be appended to the given file list argument. Parameters ---------- fileDir : string Path to root of direc...
def Run(self): self._GetArgs() goodlogging.Log.Info("CLEAR", "Using database: {0}".format(self._databasePath)) self._db = database.RenamerDB(self._databasePath) if self._dbPrint or self._dbUpdate: goodlogging.Log.Seperator() self._db.PrintAllTables() if self._dbUpdate: ...
Main entry point for ClearManager class. Does the following steps: - Parse script arguments. - Optionally print or update database tables. - Get all configuration settings from database. - Optionally parse directory for file extraction. - Recursively parse source directory for files matching ...
def _merge_prims(prims, *, debug=False, stagenames=None, stages=None): if isinstance(prims, FrameSequence): merged_prims = FrameSequence(prims._chain) else: merged_prims = [] working_prim = prims[0] i = 1 logging_tmp = [] while i < len(prims): tmp = prims[i] ...
Helper method to greedily combine Frames (of Primitives) or Primitives based on the rules defined in the Primitive's class. Used by a CommandQueue during compilation and optimization of Primitives. Args: prims: A list or FrameSequence of Primitives or Frames (respectively) to try to merge together...
def flush(self): self.stages = [] self.stagenames = [] if not self.queue: return if self.print_statistics:#pragma: no cover print("LEN OF QUENE", len(self)) t = time() if self._chain._collect_compiler_artifacts: self._co...
Force the queue of Primitives to compile, execute on the Controller, and fulfill promises with the data returned.
def Ping(self, request, context): status = processor_pb2.Status() status.message='alive' return status
Invoke the Server health endpoint :param request: Empty :param context: the request context :return: Status message 'alive'
def Process(self, request, context): logger.debug(request) message = Message.__from_protobuf_message__(request) sig = getfullargspec(self.handler_function) if len(sig.args) == 2: result = self.handler_function(message.payload, message.headers) elif len(sig.ar...
Invoke the Grpc Processor, delegating to the handler_function. If the handler_function has a single argument, pass the Message payload. If two arguments, pass the payload and headers as positional arguments: handler_function(payload, headers). If the handler function return is not of type(Message), crea...
def step_impl(context): expected_lines = context.text.split('\n') assert len(expected_lines) == len(context.output) for expected, actual in zip(expected_lines, context.output): print('--\n\texpected: {}\n\tactual: {}'.format(expected, actual)) assert expected == actual
Compares text as written to the log output
def _ParseShowList(self, checkOnly=False): showTitleList = [] showIDList = [] csvReader = csv.reader(self._allShowList.splitlines()) for rowCnt, row in enumerate(csvReader): if rowCnt == 0: # Get header column index for colCnt, column in enumerate(row): if column ==...
Read self._allShowList as csv file and make list of titles and IDs. Parameters ---------- checkOnly : boolean [optional : default = False] If checkOnly is True this will only check to ensure the column headers can be extracted correctly.
def _GetAllShowList(self): today = datetime.date.today().strftime("%Y%m%d") saveFile = '_epguides_' + today + '.csv' saveFilePath = os.path.join(self._saveDir, saveFile) if os.path.exists(saveFilePath): # Load data previous saved to file with open(saveFilePath, 'r') as allShowsFile: ...
Populates self._allShowList with the epguides all show info. On the first lookup for a day the information will be loaded from the epguides url. This will be saved to local file _epguides_YYYYMMDD.csv and any old files will be removed. Subsequent accesses for the same day will read this file.
def _GetShowID(self, showName): self._GetTitleList() self._GetIDList() for index, showTitle in enumerate(self._showTitleList): if showName == showTitle: return self._showIDList[index] return None
Get epguides show id for a given show name. Attempts to match the given show name against a show title in self._showTitleList and, if found, returns the corresponding index in self._showIDList. Parameters ---------- showName : string Show name to get show ID for. Returns ---...
def _ExtractDataFromShowHtml(self, html): htmlLines = html.splitlines() for count, line in enumerate(htmlLines): if line.strip() == r'<pre>': startLine = count+1 if line.strip() == r'</pre>': endLine = count try: dataList = htmlLines[startLine:endLine] dataStrin...
Extracts csv show data from epguides html source. Parameters ---------- html : string Block of html text Returns ---------- string Show data extracted from html text in csv format.
def _GetEpisodeName(self, showID, season, episode): # Load data for showID from dictionary showInfo = csv.reader(self._showInfoDict[showID].splitlines()) for rowCnt, row in enumerate(showInfo): if rowCnt == 0: # Get header column index for colCnt, column in enumerate(row): ...
Get episode name from epguides show info. Parameters ---------- showID : string Identifier matching show in epguides. season : int Season number. epiosde : int Epiosde number. Returns ---------- int or None If an episode name is found this is r...
def ShowNameLookUp(self, string): goodlogging.Log.Info("EPGUIDES", "Looking up show name match for string '{0}' in guide".format(string), verbosity=self.logVerbosity) self._GetTitleList() showName = util.GetBestMatch(string, self._showTitleList) return(showName)
Attempts to find the best match for the given string in the list of epguides show titles. If this list has not previous been generated it will be generated first. Parameters ---------- string : string String to find show name match against. Returns ---------- string ...
def EpisodeNameLookUp(self, showName, season, episode): goodlogging.Log.Info("EPGUIDE", "Looking up episode name for {0} S{1}E{2}".format(showName, season, episode), verbosity=self.logVerbosity) goodlogging.Log.IncreaseIndent() showID = self._GetShowID(showName) if showID is not None: try: ...
Get the episode name correspondng to the given show name, season number and episode number. Parameters ---------- showName : string Name of TV show. This must match an entry in the epguides title list (this can be achieved by calling ShowNameLookUp first). season : int ...
def clone(cls, srcpath, destpath): # Mercurial will not create intermediate directories for clones. try: os.makedirs(destpath) except OSError as e: if not e.errno == errno.EEXIST: raise cmd = [HG, 'clone', '--quiet', '--noupdate', srcpath,...
Clone an existing repository to a new bare repository.
def create(cls, path): cmd = [HG, 'init', path] subprocess.check_call(cmd) return cls(path)
Create a new repository
def private_path(self): path = os.path.join(self.path, '.hg', '.private') try: os.mkdir(path) except OSError as e: if e.errno != errno.EEXIST: raise return path
Get the path to a directory which can be used to store arbitrary data This directory should not conflict with any of the repository internals. The directory should be created if it does not already exist.
def bookmarks(self): cmd = [HG, 'bookmarks'] output = self._command(cmd).decode(self.encoding, 'replace') if output.startswith('no bookmarks set'): return [] results = [] for line in output.splitlines(): m = bookmarks_rx.match(line) as...
Get list of bookmarks
def content(self): if not self._content: self._content = self._read() return self._content
Get the file contents. This property is cached. The file is only read once.
def config(self): conf = config.Configuration() for namespace in self.namespaces: if not hasattr(conf, namespace): if not self._strict: continue raise exc.NamespaceNotRegistered( "The namespace {0} is not re...
Get a Configuration object from the file contents.
def _read(self): with open(self.path, 'r') as file_handle: content = file_handle.read() # Py27 INI config parser chokes if the content provided is not unicode. # All other versions seems to work appropriately. Forcing the value to # unicode here in order to resolve...
Open the file and return its contents.
async def ask(self, body, quick_replies=None, options=None, user=None): await self.send_text_message_to_all_interfaces( recipient=user, text=body, quick_replies=quick_replies, options=options, ) return any.Any()
simple ask with predefined quick replies :param body: :param quick_replies: (optional) in form of {'title': <message>, 'payload': <any json>} :param options: :param user: :return:
async def say(self, body, user, options): return await self.send_text_message_to_all_interfaces( recipient=user, text=body, options=options)
say something to user :param body: :param user: :return:
async def send_audio(self, url, user, options=None): tasks = [interface.send_audio(user, url, options) for _, interface in self.interfaces.items()] return [body for body in await asyncio.gather(*tasks)]
send audio message :param url: link to the audio file :param user: target user :param options: :return:
async def send_text_message_to_all_interfaces(self, *args, **kwargs): logger.debug('async_send_text_message_to_all_interfaces') tasks = [interface.send_text_message(*args, **kwargs) for _, interface in self.interfaces.items()] logger.debug(' tasks') logger.deb...
TODO: we should know from where user has come and use right interface as well right interface can be chosen :param args: :param kwargs: :return:
def connect(self, protocolFactory): deferred = self._startProcess() deferred.addCallback(self._connectRelay, protocolFactory) deferred.addCallback(self._startRelay) return deferred
Starts a process and connect a protocol to it.
def _startProcess(self): connectedDeferred = defer.Deferred() processProtocol = RelayProcessProtocol(connectedDeferred) self.inductor.execute(processProtocol, *self.inductorArgs) return connectedDeferred
Use the inductor to start the process we want to relay data from.