text
stringlengths
81
112k
find all matching data files in search_path search_path: path of directories to load from codecs: allow to override from list of installed returns array of tuples (codec_object, filename) def find_datafile(name, search_path, codecs=get_codecs()): """ find all matching data files in search_path ...
find datafile and load them from codec TODO only does the first one kwargs: default = if passed will return that on failure instead of throwing def load_datafile(name, search_path, codecs=get_codecs(), **kwargs): """ find datafile and load them from codec TODO only does the first one kwargs...
Initialize what requires credentials/secret files. :param secrets_dir: dir to expect credentials in and store logs/history in. :param log: logger to use for log output. :param bot_name: name of this bot, used for various kinds of labelling. :returns: none. def cred_init( ...
Send birdsite message. :param text: text to send in post. :returns: list of output records, each corresponding to either a single post, or an error. def send( self, *, text: str, ) -> List[OutputRecord]: """ Send birdsite ...
Upload media to birdsite, and send status and media, and captions if present. :param text: tweet text. :param files: list of files to upload with post. :param captions: list of captions to include as alt-text with files. :returns: list of output records, each...
Performs batch reply on target account. Looks up the recent messages of the target user, applies the callback, and replies with what the callback generates. :param callback: a callback taking a message id, message contents, and optional extra keys, ...
Send DM to owner if something happens. :param message: message to send to owner. :returns: None. def send_dm_sos(self, message: str) -> None: """ Send DM to owner if something happens. :param message: message to send to owner. :returns: None. """ if sel...
Handle error while trying to do something. :param message: message to send in DM regarding error. :param e: tweepy error object. :returns: OutputRecord containing an error. def handle_error( self, *, message: str, error: tweepy.TweepError, ) ...
Handle uploading all captions. :param media_ids: media ids of uploads to attach captions to. :param captions: captions to be attached to those media ids. :returns: None. def _handle_caption_upload( self, *, media_ids: List[str], captions: Optiona...
:reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event.html def _send_direct_message_new(self, messageobject: Dict[str, Dict]) -> Any: """ :reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-e...
Takes crash data via stdin and generates a Socorro signature def main(): """Takes crash data via stdin and generates a Socorro signature""" parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument( '-v', '--verbose', help='increase output verbosity', action='store_true' ) ...
Update internel configuration dict with config and recheck def add_config(self, config): """ Update internel configuration dict with config and recheck """ for attr in self.__fixed_attrs: if attr in config: raise Exception("cannot set '%s' outside of init", a...
called after config was modified to sanity check raises on error def check_config(self): """ called after config was modified to sanity check raises on error """ # sanity checks - no config access past here if not getattr(self, 'stages', None): raise...
called after Defintion was loaded to sanity check raises on error def check_definition(self): """ called after Defintion was loaded to sanity check raises on error """ if not self.write_codec: self.__write_codec = self.defined.data_ext # TODO need to...
find all matching data files in search_path returns array of tuples (codec_object, filename) def find_datafile(self, name, search_path=None): """ find all matching data files in search_path returns array of tuples (codec_object, filename) """ if not search_path: ...
find datafile and load them from codec def load_datafile(self, name, search_path=None, **kwargs): """ find datafile and load them from codec """ if not search_path: search_path = self.define_dir self.debug_msg('loading datafile %s from %s' % (name, str(search_path))...
run all configured stages def run(self): """ run all configured stages """ self.sanity_check() # TODO - check for devel # if not self.version: # raise Exception("no version") # XXX check attr exist if not self.release_environment: raise Exception("no instance nam...
Return POSIX timestamp as float. >>> timestamp(datetime.datetime.now()) > 1494638812 True >>> timestamp(datetime.datetime.now()) % 1 > 0 True def timestamp(dt): """ Return POSIX timestamp as float. >>> timestamp(datetime.datetime.now()) > 1494638812 True >>> timestamp(datetime.datetime.now()) % 1 > 0 Tru...
Rate limit a function. def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]: """Rate limit a function.""" return util.rate_limited(max_per_hour, *args)
Repair a corrupted IterationRecord with a specific known issue. def _repair(record: Dict[str, Any]) -> Dict[str, Any]: """Repair a corrupted IterationRecord with a specific known issue.""" output_records = record.get("output_records") if record.get("_type", None) == "IterationRecord" and output_records is ...
Get object back from dict. def from_dict(cls, obj_dict: Dict[str, Any]) -> "IterationRecord": """Get object back from dict.""" obj = cls() for key, item in obj_dict.items(): obj.__dict__[key] = item return obj
Post text-only to all outputs. :param args: positional arguments. expected: text to send as message in post. keyword text argument is preferred over this. :param text: text to send as message in post. :returns: new record of iteration def send( self, ...
Post with one media item to all outputs. Provide filename so outputs can handle their own uploads. :param args: positional arguments. expected: text to send as message in post. file to be uploaded. caption to be paired with file. k...
Post with several media. Provide filenames so outputs can handle their own uploads. :param args: positional arguments. expected: text to send as message in post. files to be uploaded. captions to be paired with files. keyword argum...
Performs batch reply on target accounts. Looks up the recent messages of the target user, applies the callback, and replies with what the callback generates. :param callback: a callback taking a message id, message contents, and optional extra keys, ...
Go to sleep for the duration of self.delay. :returns: None def nap(self) -> None: """ Go to sleep for the duration of self.delay. :returns: None """ self.log.info(f"Sleeping for {self.delay} seconds.") for _ in progress.bar(range(self.delay)): time....
Store some extra value in the messaging storage. :param key: key of dictionary entry to add. :param value: value of dictionary entry to add. :returns: None def store_extra_info(self, key: str, value: Any) -> None: """ Store some extra value in the messaging storage. :p...
Store several extra values in the messaging storage. :param d: dictionary entry to merge with current self.extra_keys. :returns: None def store_extra_keys(self, d: Dict[str, Any]) -> None: """ Store several extra values in the messaging storage. :param d: dictionary entry to m...
Update messaging history on disk. :returns: None def update_history(self) -> None: """ Update messaging history on disk. :returns: None """ self.log.debug(f"Saving history. History is: \n{self.history}") jsons = [] for item in self.history: ...
Load messaging history from disk to self. :returns: List of iteration records comprising history. def load_history(self) -> List["IterationRecord"]: """ Load messaging history from disk to self. :returns: List of iteration records comprising history. """ if path.isfile...
Set up all output methods. Provide them credentials and anything else they need. def _setup_all_outputs(self) -> None: """Set up all output methods. Provide them credentials and anything else they need.""" # The way this is gonna work is that we assume an output should be set up iff it has a #...
Parse output records into dicts ready for JSON. def _parse_output_records(self, item: IterationRecord) -> Dict[str, Any]: """Parse output records into dicts ready for JSON.""" output_records = {} for key, sub_item in item.output_records.items(): if isinstance(sub_item, dict) or isin...
Create the directory of a fully qualified file name if it does not exist. :param fname: File name :type fname: string Equivalent to these Bash shell commands: .. code-block:: bash $ fname="${HOME}/mydir/myfile.txt" $ dir=$(dirname "${fname}") $ mkdir -p "${dir}" :param ...
r""" Fix potential problems with a Microsoft Windows file name. Superfluous backslashes are removed and unintended escape sequences are converted to their equivalent (presumably correct and intended) representation, for example :code:`r'\\\\x07pps'` is transformed to :code:`r'\\\\\\\\apps'`. A file...
Enforce line separators to be the right one depending on platform. def _homogenize_linesep(line): """Enforce line separators to be the right one depending on platform.""" token = str(uuid.uuid4()) line = line.replace(os.linesep, token).replace("\n", "").replace("\r", "") return line.replace(token, os.l...
Process line range tokens. def _proc_token(spec, mlines): """Process line range tokens.""" spec = spec.strip().replace(" ", "") regexp = re.compile(r".*[^0123456789\-,]+.*") tokens = spec.split(",") cond = any([not item for item in tokens]) if ("--" in spec) or ("-," in spec) or (",-" in spec) ...
r""" Return a Python source file formatted in reStructuredText. .. role:: bash(code) :language: bash :param fname: File name, relative to environment variable :bash:`PKG_DOC_DIR` :type fname: string :param fpointer: Output function pointer. Normally is :code:`cog.out` b...
Print STDOUT of a shell command formatted in reStructuredText. This is a simplified version of :py:func:`pmisc.term_echo`. :param command: Shell command (relative to **mdir** if **env** is not given) :type command: string :param nindent: Indentation level :type nindent: integer :param mdir...
Print STDOUT of a shell command formatted in reStructuredText. .. role:: bash(code) :language: bash :param command: Shell command :type command: string :param nindent: Indentation level :type nindent: integer :param env: Environment variable replacement dictionary. The ...
Return the string given by param formatted with the callers locals. def flo(string): '''Return the string given by param formatted with the callers locals.''' callers_locals = {} frame = inspect.currentframe() try: outerframe = frame.f_back callers_locals = outerframe.f_locals final...
Color wrapper. Example: >>> blue = _wrap_with('34') >>> print(blue('text')) \033[34mtext\033[0m def _wrap_with(color_code): '''Color wrapper. Example: >>> blue = _wrap_with('34') >>> print(blue('text')) \033[34mtext\033[0m ''' def inner(text, bold=F...
Delete temporary files not under version control. Args: deltox: If True, delete virtual environments used by tox def clean(deltox=False): '''Delete temporary files not under version control. Args: deltox: If True, delete virtual environments used by tox ''' basedir = dirname(__fi...
Install latest pythons with pyenv. The python version will be activated in the projects base dir. Will skip already installed latest python versions. def pythons(): '''Install latest pythons with pyenv. The python version will be activated in the projects base dir. Will skip already installed l...
Run tox. Build package and run unit tests against several pythons. Args: args: Optional arguments passed to tox. Example: fab tox:'-e py36 -r' def tox(args=''): '''Run tox. Build package and run unit tests against several pythons. Args: args: Optional argume...
Build package and upload to pypi. def pypi(): '''Build package and upload to pypi.''' if query_yes_no('version updated in setup.py?'): print(cyan('\n## clean-up\n')) execute(clean) basedir = dirname(__file__) latest_pythons = _determine_latest_pythons() # e.g. highest...
Check that none of the input column numbers is out of range. (Instead of defining this function, we could depend on Python's built-in IndexError exception for this issue, but the IndexError exception wouldn't include line number information, which is helpful for users to find exactly which line is the c...
Read input gene history file into the database. Note that the arguments tax_id_col, id_col and symbol_col have been converted into 0-based column indexes. def import_gene_history(file_handle, tax_id, tax_id_col, id_col, symbol_col): """ Read input gene history file into the database. Note that the ...
Initialize what requires credentials/secret files. def cred_init( self, *, secrets_dir: str, log: Logger, bot_name: str="", ) -> None: """Initialize what requires credentials/secret files.""" super().__init__(secrets_dir=secrets_dir, log=l...
Send mastodon message. :param text: text to send in post. :returns: list of output records, each corresponding to either a single post, or an error. def send( self, *, text: str, ) -> List[OutputRecord]: """ Send mastodon ...
Upload media to mastodon, and send status and media, and captions if present. :param text: post text. :param files: list of files to upload with post. :param captions: list of captions to include as alt-text with files. :returns: list of output records, each ...
Performs batch reply on target account. Looks up the recent messages of the target user, applies the callback, and replies with what the callback generates. :param callback: a callback taking a message id, message contents, and optional extra keys, ...
Handle error while trying to do something. def handle_error(self, message: str, e: mastodon.MastodonError) -> OutputRecord: """Handle error while trying to do something.""" self.lerror(f"Got an error! {e}") # Handle errors if we know how. try: code = e[0]["code"] ...
Little-endian |... 4 bytes unsigned int ...|... 4 bytes unsigned int ...| | frames count | dimensions count | def _read_header(self): ''' Little-endian |... 4 bytes unsigned int ...|... 4 bytes unsigned int ...| | frames count | ...
Request a callback for value modification. Parameters ---------- you : object An instance having ``__call__`` attribute. def listen(self, you): """ Request a callback for value modification. Parameters ---------- you : object An ...
Simple utility function to load a term. def _get_term_by_id(self, id): '''Simple utility function to load a term. ''' url = (self.url + '/%s.json') % id r = self.session.get(url) return r.json()
Returns all concepts or collections that form the top-level of a display hierarchy. As opposed to the :meth:`get_top_concepts`, this method can possibly return both concepts and collections. :rtype: Returns a list of concepts and collections. For each an id is present and a...
Return a list of concepts or collections that should be displayed under this concept or collection. :param id: A concept or collection id. :rtype: A list of concepts and collections. For each an id is present and a label. The label is determined by looking at the `**kwar...
Pass a list of identifiers (id_list), the name of the database ('Entrez', 'Symbol', 'Standard name', 'Systematic name' or a loaded crossreference database) that you wish to translate from, and the name of the database that you wish to translate to. def translate_genes(id_list=None, from_id=None, to_id=None...
must be applied to all inner functions that return contexts. Wraps all instances of pygame.Surface in the input in Surface def _inner_func_anot(func): """must be applied to all inner functions that return contexts. Wraps all instances of pygame.Surface in the input in Surface""" @wraps(func) ...
Draws a cross centered in the target area :param width: width of the lines of the cross in pixels :type width: int :param color: color of the lines of the cross :type color: pygame.Color def Cross(width=3, color=0): """Draws a cross centered in the target area :param width: width of the lines...
Top level function to create a surface. :param target: the pygame.Surface to blit on. Or a (width, height) tuple in which case a new surface will be created :type target: - def compose(target, root=None): """Top level function to create a surface. :param target: the pygame.Surface to...
Unifies loading of fonts. :param name: name of system-font or filepath, if None is passed the default system-font is loaded :type name: str :param source: "sys" for system font, or "file" to load a file :type source: str def Font(name=None, source="sys", italic=False, bold=False, size=20): ...
Renders a text. Supports multiline text, the background will be transparent. :param align: text-alignment must be "center", "left", or "righ" :type align: str :return: the input text :rtype: pygame.Surface def Text(text, font, color=pygame.Color(0, 0, 0), antialias=False, align="center"): """R...
Creates a padding by the remaining space after scaling the content. E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0) because the content would not be scaled (since scale_h=1) and therefore t...
:param levels string: An optional argument of declaring a single or comma-delimited list of levels is available, as seen in the example as 1. An example of a comma-delimited list of levels is 1,2,5,9. http://www.wanikani.com/api/v1.2#radicals-list def radicals(self, levels=None): ...
:param levels: An optional argument of declaring a single or comma-delimited list of levels is available, as seen in the example as 1. An example of a comma-delimited list of levels is 1,2,5,9. :type levels: str or None http://www.wanikani.com/api/v1.2#kanji-list def kanji(self...
:param levels: An optional argument of declaring a single or comma-delimited list of levels is available, as seen in the example as 1. An example of a comma-delimited list of levels is 1,2,5,9. :type levels: str or None http://www.wanikani.com/api/v1.2#vocabulary-list def vocab...
Test if the argument is a string representing a valid hexadecimal digit. :param obj: Object :type obj: any :rtype: boolean def ishex(obj): """ Test if the argument is a string representing a valid hexadecimal digit. :param obj: Object :type obj: any :rtype: boolean """ ret...
Test if the argument is a number (complex, float or integer). :param obj: Object :type obj: any :rtype: boolean def isnumber(obj): """ Test if the argument is a number (complex, float or integer). :param obj: Object :type obj: any :rtype: boolean """ return ( (obj ...
Test if the argument is a real number (float or integer). :param obj: Object :type obj: any :rtype: boolean def isreal(obj): """ Test if the argument is a real number (float or integer). :param obj: Object :type obj: any :rtype: boolean """ return ( (obj is not Non...
Create and return an API context def create_api_context(self, cls): """Create and return an API context""" return self.api_context_schema().load({ "name": cls.name, "cls": cls, "inst": [], "conf": self.conf.get_api_service(cls.name), "calls": ...
Pass an API result down the pipeline def receive(self, data, api_context): """Pass an API result down the pipeline""" self.log.debug(f"Putting data on the pipeline: {data}") result = { "api_contexts": self.api_contexts, "api_context": api_context, "strategy":...
Shut it down def shutdown(self, signum, frame): # pylint: disable=unused-argument """Shut it down""" if not self.exit: self.exit = True self.log.debug(f"SIGTRAP!{signum};{frame}") self.api.shutdown() self.strat.shutdown()
Course this node belongs to def course(self): """ Course this node belongs to """ course = self.parent while course.parent: course = course.parent return course
Path of this node on Studip. Looks like Coures/folder/folder/document. Respects the renaming policies defined in the namemap def path(self): """ Path of this node on Studip. Looks like Coures/folder/folder/document. Respects the renaming policies defined in the namemap """ if self.paren...
get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the default value from stud.ip is used. def title(self): """ get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the defaul...
list of all documents find in subtrees of this node def deep_documents(self): """ list of all documents find in subtrees of this node """ tree = [] for entry in self.contents: if isinstance(entry, Document): tree.append(entry) else: ...
The title of the course. If no entry in the namemap of the configuration is found a new entry is created with name=$STUD.IP_NAME + $SEMESTER_NAME def title(self): """ The title of the course. If no entry in the namemap of the configuration is found a new entry is created with name=$STUD.IP_NAME + $SEME...
run a get request against an url. Returns the response which can optionally be streamed def _get(self, route, stream=False): """ run a get request against an url. Returns the response which can optionally be streamed """ log.debug("Running GET request against %s" % route) return...
List all contents of a folder. Returns a list of all Documents and Folders (in this order) in the folder. def get_contents(self, folder: Folder): """ List all contents of a folder. Returns a list of all Documents and Folders (in this order) in the folder. """ log.debug("Listing Contents...
Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename. If overwrite is set the local version will be overwritten if the file was changed on studip since the last check def download_document(self, document: Document, overwrite=True, pa...
get the semester of a node def get_semester_title(self, node: BaseNode): """ get the semester of a node """ log.debug("Getting Semester Title for %s" % node.course.id) return self._get_semester_from_id(node.course.semester)
use the base_url and auth data from the configuration to list all courses the user is subscribed to def get_courses(self): """ use the base_url and auth data from the configuration to list all courses the user is subscribed to """ log.info("Listing Courses...") courses = json.lo...
Minimize a scalar function using Brent's method. Parameters ---------- verbose : bool ``True`` for verbose output; ``False`` otherwise. def _minimize_scalar( self, desc="Progress", rtol=1.4902e-08, atol=1.4902e-08, verbose=True ): """ Minimize a scalar f...
return a url-safe hash of the string, optionally (and by default) base64-encoded alg='sha256' = the hash algorithm, must be in hashlib b64=True = whether to base64-encode the output strip=True = whether to strip trailing '=' from the base64 output Using the...
turn a string to CamelCase, omitting non-word characters def camelify(self): """turn a string to CamelCase, omitting non-word characters""" outstring = self.titleify(allwords=True) outstring = re.sub(r"&[^;]+;", " ", outstring) outstring = re.sub(r"\W+", "", outstring) retu...
takes a string and makes a title from it def titleify(self, lang='en', allwords=False, lastword=True): """takes a string and makes a title from it""" if lang in LOWERCASE_WORDS: lc_words = LOWERCASE_WORDS[lang] else: lc_words = [] s = str(self).strip() ...
return a python identifier from the string (underscore separators) def identifier(self, camelsplit=False, ascii=True): """return a python identifier from the string (underscore separators)""" return self.nameify(camelsplit=camelsplit, ascii=ascii, sep='_')
return an XML name (hyphen-separated by default, initial underscore if non-letter) def nameify(self, camelsplit=False, ascii=True, sep='-'): """return an XML name (hyphen-separated by default, initial underscore if non-letter)""" s = String(str(self)) # immutable if camelsplit == True: ...
Turn non-word characters (incl. underscore) into single hyphens. If ascii=True, return ASCII-only. If also lossless=True, use the UTF-8 codes for the non-ASCII characters. def hyphenify(self, ascii=False): """Turn non-word characters (incl. underscore) into single hyphens. If ascii=...
Turn a CamelCase string into a string with spaces def camelsplit(self): """Turn a CamelCase string into a string with spaces""" s = str(self) for i in range(len(s) - 1, -1, -1): if i != 0 and ( (s[i].isupper() and s[i - 1].isalnum() and not s[i - 1].isupper()) ...
Pyramid pluggable and discoverable function. def includeme(config): """Pyramid pluggable and discoverable function.""" global_settings = config.registry.settings settings = local_settings(global_settings, PREFIX) try: file = settings['file'] except KeyError: raise KeyError("Must su...
Executed on startup of application def run(self): """Executed on startup of application""" self.api = self.context.get("cls")(self.context) self.context["inst"].append(self) # Adapters used by strategies for call, calldata in self.context.get("calls", {}).items(): def loop...
Executed on each scheduled iteration def call(self, callname, arguments=None): """Executed on each scheduled iteration""" # See if a method override exists action = getattr(self.api, callname, None) if action is None: try: action = self.api.ENDPOINT_OVERRIDES...
Generate a request object for delivery to the API def _generate_request(self, callname, request): """Generate a request object for delivery to the API""" # Retrieve path from API class schema = self.api.request_schema() schema.context['callname'] = callname return schema.dump(re...
Generate a results object for delivery to the context object def _generate_result(self, callname, result): """Generate a results object for delivery to the context object""" # Retrieve path from API class schema = self.api.result_schema() schema.context['callname'] = callname se...
create a key for index by converting index into a base-26 number, using A-Z as the characters. def excel_key(index): """create a key for index by converting index into a base-26 number, using A-Z as the characters.""" X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or '' return X(int(index))
Takes a raw crash and a processed crash (these are Socorro-centric data structures) and converts them to a crash data structure used by signature generation. :arg raw_crash: raw crash data from Socorro :arg processed_crash: processed crash data from Socorro :returns: crash data structure that conf...
Takes a text and drops all non-printable and non-ascii characters and also any whitespace characters that aren't space. :arg str text: the text to fix :returns: text with all bad characters dropped def drop_bad_characters(text): """Takes a text and drops all non-printable and non-ascii characters and...
Parses a source file thing and returns the file name Example: >>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06') 'js/src/jit/MIR.h' :arg str source_file: the source file ("file") from a stack frame :returns: the filename or ``None`` if it couldn't determine ...