repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/reader.py
read_variables
python
def read_variables(config_location: str) -> Dict[str, str]: with open(config_location, "r") as config_file: config_lines = config_file.readlines() try: return json.loads("".join(config_lines), parse_int=lambda num_str: str(num_str), parse_float=lambda float_str: str(flo...
Reads variables out of a config file. Variables can be in a ini file, a shell file used to source the variables (i.e. one that has just got "export *" like statements in it) or in JSON. :param config_location: the location of the config file :return: dictionary where the variable names are key and their val...
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/reader.py#L12-L27
[ "def _shell_to_ini(shell_file_contents: List[str]) -> List[str]:\n \"\"\"\n Converts a shell file, which just contains comments and \"export *\" statements into an ini file.\n :param shell_file_contents: the contents of the shell file\n :return: lines of an equivalent ini file\n \"\"\"\n line_numb...
import configparser import json from json import JSONDecodeError from typing import Dict, List _FAKE_SECTION_NAME = "all" _FAKE_SECTION = "[%s]\n" % _FAKE_SECTION_NAME _EXPORT_COMMAND = "export " def _read_ini_config(ini_file_contents: str) -> Dict[str, str]: """ Parses the given ini file contents and conv...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/reader.py
_read_ini_config
python
def _read_ini_config(ini_file_contents: str) -> Dict[str, str]: config = configparser.ConfigParser() config.optionxform = str config.read_string(_FAKE_SECTION + ini_file_contents) items = {} for section in config.sections(): items.update(dict(config[section].items())) return items
Parses the given ini file contents and converts to a dictionary of key/value pairs. :param ini_file_contents: the contents of the ini file :return: dictionary where the variable names are key and their values are the values
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/reader.py#L30-L44
null
import configparser import json from json import JSONDecodeError from typing import Dict, List _FAKE_SECTION_NAME = "all" _FAKE_SECTION = "[%s]\n" % _FAKE_SECTION_NAME _EXPORT_COMMAND = "export " def read_variables(config_location: str) -> Dict[str, str]: """ Reads variables out of a config file. Variables ...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/reader.py
_shell_to_ini
python
def _shell_to_ini(shell_file_contents: List[str]) -> List[str]: line_number = 0 while line_number < len(shell_file_contents): line = shell_file_contents[line_number].strip() if "=" not in line: del shell_file_contents[line_number] else: if line.strip().startswith(...
Converts a shell file, which just contains comments and "export *" statements into an ini file. :param shell_file_contents: the contents of the shell file :return: lines of an equivalent ini file
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/reader.py#L47-L62
null
import configparser import json from json import JSONDecodeError from typing import Dict, List _FAKE_SECTION_NAME = "all" _FAKE_SECTION = "[%s]\n" % _FAKE_SECTION_NAME _EXPORT_COMMAND = "export " def read_variables(config_location: str) -> Dict[str, str]: """ Reads variables out of a config file. Variables ...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/manager.py
ProjectVariablesManager.get
python
def get(self) -> Dict[str, str]: variables = self._project.variables.list(all=True) return {variable.key: variable.value for variable in variables}
Gets the build variables for the project. :return: the build variables
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/manager.py#L43-L49
null
class ProjectVariablesManager: """ Manages the build variables used by a project. """ def __init__(self, gitlab_config: GitLabConfig, project: str): """ Constructor. :param gitlab_config: configuration to access GitLab :param project: the project of interest (preferably n...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/manager.py
ProjectVariablesManager.clear
python
def clear(self): for variable in self._project.variables.list(all=True): variable.delete()
Clears all of the build variables.
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/manager.py#L51-L56
null
class ProjectVariablesManager: """ Manages the build variables used by a project. """ def __init__(self, gitlab_config: GitLabConfig, project: str): """ Constructor. :param gitlab_config: configuration to access GitLab :param project: the project of interest (preferably n...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/manager.py
ProjectVariablesManager.remove
python
def remove(self, variables: Union[Iterable[str], Dict[str, str]]=None): keys = list(variables.keys()) if isinstance(variables, Dict) else variables # type: Iterable[str] for key in keys: variable = self._project.variables.get(key) if isinstance(variables, Dict): ...
Removes the given variables. Will only remove a key if it has the given value if the value has been defined. :param variables: the variables to remove
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/manager.py#L58-L69
null
class ProjectVariablesManager: """ Manages the build variables used by a project. """ def __init__(self, gitlab_config: GitLabConfig, project: str): """ Constructor. :param gitlab_config: configuration to access GitLab :param project: the project of interest (preferably n...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/manager.py
ProjectVariablesManager.set
python
def set(self, variables: Dict[str, str]): current_variables = self.get() difference = DictDiffer(variables, current_variables) removed_keys = difference.removed() self.remove(removed_keys) changed_keys = difference.added() | difference.changed() changed = {key: variable...
Sets the build variables (i.e. removes old ones, adds new ones) :param variables: the build variables to set
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/manager.py#L71-L84
[ "def get(self) -> Dict[str, str]:\n \"\"\"\n Gets the build variables for the project.\n :return: the build variables\n \"\"\"\n variables = self._project.variables.list(all=True)\n return {variable.key: variable.value for variable in variables}\n", "def remove(self, variables: Union[Iterable[st...
class ProjectVariablesManager: """ Manages the build variables used by a project. """ def __init__(self, gitlab_config: GitLabConfig, project: str): """ Constructor. :param gitlab_config: configuration to access GitLab :param project: the project of interest (preferably n...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/manager.py
ProjectVariablesManager.add
python
def add(self, variables: Dict[str, str], overwrite: bool=False): preset_variables = self._project.variables.list() preset_variable_keys = [variable.key for variable in preset_variables] for key, value in variables.items(): if key in preset_variable_keys: if overwrite...
Adds the given build variables to those that already exist. :param variables: the build variables to add :param overwrite: whether the old variable should be overwritten in the case of a redefinition
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/manager.py#L86-L104
null
class ProjectVariablesManager: """ Manages the build variables used by a project. """ def __init__(self, gitlab_config: GitLabConfig, project: str): """ Constructor. :param gitlab_config: configuration to access GitLab :param project: the project of interest (preferably n...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/executables/gitlab_set_variables.py
_parse_args
python
def _parse_args(args: List[str]) -> _SetArgumentsRunConfig: parser = argparse.ArgumentParser( prog="gitlab-set-variables", description="Tool for setting a GitLab project's build variables") add_common_arguments(parser, project=True) parser.add_argument("source", nargs="+", type=str, ...
Parses the given CLI arguments to get a run configuration. :param args: CLI arguments :return: run configuration derived from the given CLI arguments
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/executables/gitlab_set_variables.py#L21-L35
[ "def add_common_arguments(parser: ArgumentParser, project: bool=False):\n \"\"\"\n Adds common arguments to the given argument parser.\n :param parser: argument parser\n :param url: whether the URL named argument should be added\n :param token: whether the access token named argument should be added\...
import argparse import sys from typing import List, Dict from gitlabbuildvariables.common import GitLabConfig from gitlabbuildvariables.executables._common import add_common_arguments, ProjectRunConfig from gitlabbuildvariables.manager import ProjectVariablesManager from gitlabbuildvariables.reader import read_variab...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/executables/gitlab_set_variables.py
main
python
def main(): run_config = _parse_args(sys.argv[1:]) gitlab_config = GitLabConfig(run_config.url, run_config.token) manager = ProjectVariablesManager(gitlab_config, run_config.project) variables = {} # type: Dict[str, str] for source in run_config.source: variables.update(read_variables(sourc...
Main method.
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/executables/gitlab_set_variables.py#L38-L49
[ "def read_variables(config_location: str) -> Dict[str, str]:\n \"\"\"\n Reads variables out of a config file. Variables can be in a ini file, a shell file used to source the variables\n (i.e. one that has just got \"export *\" like statements in it) or in JSON.\n :param config_location: the location of ...
import argparse import sys from typing import List, Dict from gitlabbuildvariables.common import GitLabConfig from gitlabbuildvariables.executables._common import add_common_arguments, ProjectRunConfig from gitlabbuildvariables.manager import ProjectVariablesManager from gitlabbuildvariables.reader import read_variab...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/update/_builders.py
ProjectVariablesUpdaterBuilder.build
python
def build(self, project: str, groups: Iterable[str], gitlab_config: GitLabConfig) \ -> ProjectVariablesUpdaterType: """ Builds a `ProjectVariablesUpdater` instance using the given arguments. :param project: the project that variables are to be updated for :param groups: the g...
Builds a `ProjectVariablesUpdater` instance using the given arguments. :param project: the project that variables are to be updated for :param groups: the groups of settings that should be set for the project :param gitlab_config: the configuration required to access GitLab :return: the ...
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/update/_builders.py#L16-L24
null
class ProjectVariablesUpdaterBuilder(Generic[ProjectVariablesUpdaterType], metaclass=ABCMeta): """ Builder of `ProjectVariablesUpdater` instances. """ @abstractmethod
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/update/_single_project_updaters.py
ProjectVariablesUpdater._get_variables
python
def _get_variables(self) -> Dict[str, str]: variables = {} # type: Dict[str, str] for group in self.groups: setting_variables = self._read_group_variables(group) variables.update(setting_variables) return variables
Gets the variables that should be set for this project. :return: the variables
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/update/_single_project_updaters.py#L46-L55
[ "def _read_group_variables(self, group: str) -> Dict[str, str]:\n \"\"\"\n Reads the setting variables associated to the given group identifier.\n :param group: the identifier of the group\n :return: the setting variables associated to the given group\n \"\"\"\n" ]
class ProjectVariablesUpdater(VariablesUpdater, metaclass=ABCMeta): """ Updates variables for a project in GitLab CI. """ @abstractmethod def _read_group_variables(self, group: str) -> Dict[str, str]: """ Reads the setting variables associated to the given group identifier. :...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/update/_single_project_updaters.py
FileBasedProjectVariablesUpdater._resolve_group_location
python
def _resolve_group_location(self, group: str) -> str: if os.path.isabs(group): possible_paths = [group] else: possible_paths = [] for repository in self.setting_repositories: possible_paths.append(os.path.join(repository, group)) for default_s...
Resolves the location of a setting file based on the given identifier. :param group: the identifier for the group's settings file (~its location) :return: the absolute path of the settings location
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/update/_single_project_updaters.py#L78-L100
null
class FileBasedProjectVariablesUpdater(ProjectVariablesUpdater): """ Updates variables for a project in GitLab CI based on the values stored within a file. """ def __init__(self, setting_repositories: List[str]=None, default_setting_extensions: List[str]=None, **kwargs): """ Constructor....
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/executables/_common.py
add_common_arguments
python
def add_common_arguments(parser: ArgumentParser, project: bool=False): parser.add_argument("--url", type=str, help="Location of GitLab") parser.add_argument("--token", type=str, help="GitLab access token") parser.add_argument("--debug", action="store_true", default=False, help="Turns on debugging") if p...
Adds common arguments to the given argument parser. :param parser: argument parser :param url: whether the URL named argument should be added :param token: whether the access token named argument should be added :param project: whether the project positional argument should be added
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/executables/_common.py#L23-L35
null
from argparse import ArgumentParser class RunConfig: """ Run configuration for use against GitLab. """ def __init__(self, url: str, token: str, debug: bool=False): self.url = url self.token = token self.debug = debug class ProjectRunConfig(RunConfig): """ Run configur...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/executables/gitlab_update_variables.py
_parse_args
python
def _parse_args(args: List[str]) -> _UpdateArgumentsRunConfig: parser = argparse.ArgumentParser( prog="gitlab-update-variables", description="Tool for setting a GitLab project's build variables") add_common_arguments(parser) parser.add_argument("config_location", type=str, help="Location of the conf...
Parses the given CLI arguments to get a run configuration. :param args: CLI arguments :return: run configuration derived from the given CLI arguments
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/executables/gitlab_update_variables.py#L24-L42
[ "def add_common_arguments(parser: ArgumentParser, project: bool=False):\n \"\"\"\n Adds common arguments to the given argument parser.\n :param parser: argument parser\n :param url: whether the URL named argument should be added\n :param token: whether the access token named argument should be added\...
import argparse import logging import sys from typing import List from gitlabbuildvariables.common import GitLabConfig from gitlabbuildvariables.executables._common import add_common_arguments, RunConfig from gitlabbuildvariables.update import logger, FileBasedProjectVariablesUpdaterBuilder, \ FileBasedProjectsVar...
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/executables/gitlab_update_variables.py
main
python
def main(): run_config = _parse_args(sys.argv[1:]) if run_config.debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) gitlab_config = GitLabConfig(run_config.url, run_config.token) project_updater_builder = FileBasedProjectVariablesUpdaterBuilder( settin...
Main method.
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/executables/gitlab_update_variables.py#L45-L62
[ "def _parse_args(args: List[str]) -> _UpdateArgumentsRunConfig:\n \"\"\"\n Parses the given CLI arguments to get a run configuration.\n :param args: CLI arguments\n :return: run configuration derived from the given CLI arguments\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"gitlab-u...
import argparse import logging import sys from typing import List from gitlabbuildvariables.common import GitLabConfig from gitlabbuildvariables.executables._common import add_common_arguments, RunConfig from gitlabbuildvariables.update import logger, FileBasedProjectVariablesUpdaterBuilder, \ FileBasedProjectsVar...
Vito2015/pyextend
pyextend/formula/lbstools.py
haversine
python
def haversine(lng1, lat1, lng2, lat2): # Convert coordinates to floats. lng1, lat1, lng2, lat2 = map(float, [lng1, lat1, lng2, lat2]) # Convert to radians from degrees lng1, lat1, lng2, lat2 = map(math.radians, [lng1, lat1, lng2, lat2]) # Compute distance dlng = lng2 - lng1 dlat = lat2 - l...
Compute km by geo-coordinates See also: haversine define https://en.wikipedia.org/wiki/Haversine_formula
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/formula/lbstools.py#L13-L29
null
# coding: utf-8 """ pyextend.formula ~~~~~~~~~~~~~~~~ pyextend formula package :copyright: (c) 2016 by Vito. :license: GNU, see LICENSE for more details. """ import math def calc_distance(lng1, lat1, lng2, lat2): """Calc distance (km) by geo-coordinates. @:param lng1: first coordinat...
Vito2015/pyextend
pyextend/formula/lbstools.py
calc_distance
python
def calc_distance(lng1, lat1, lng2, lat2): ra = 6378.140 # 赤道半径 (km) rb = 6356.755 # 极半径 (km) flatten = (ra - rb) / ra # 地球扁率 rad_lat_1 = math.radians(lat1) rad_lng_1 = math.radians(lng1) rad_lat_2 = math.radians(lat2) rad_lng_2 = math.radians(lng2) p1 = math.atan(rb / ra * math.tan(r...
Calc distance (km) by geo-coordinates. @:param lng1: first coordinate.lng @:param lat1: first coordinate.lat @:param lng2: second coordinate.lng @:param lat2: second coordinate.lat @:return distance: km
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/formula/lbstools.py#L32-L54
null
# coding: utf-8 """ pyextend.formula ~~~~~~~~~~~~~~~~ pyextend formula package :copyright: (c) 2016 by Vito. :license: GNU, see LICENSE for more details. """ import math def haversine(lng1, lat1, lng2, lat2): """Compute km by geo-coordinates See also: haversine define https://en.wikipedia...
Vito2015/pyextend
pyextend/core/math.py
isprime
python
def isprime(n): n = abs(int(n)) if n < 2: return False if n == 2: return True if not n & 1: return False # 在一般领域, 对正整数n, 如果用2 到 sqrt(n) 之间所有整数去除, 均无法整除, 则n为质数. for x in range(3, int(n ** 0.5)+1, 2): if n % x == 0: return False return True
Check the number is prime value. if prime value returns True, not False.
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/math.py#L12-L28
null
# coding: utf-8 """ pyextend.core.math ~~~~~~~~~~~~~~~~~~ pyextend core math tools. :copyright: (c) 2016 by Vito. :license: GNU, see LICENSE for more details. """
Vito2015/pyextend
pyextend/core/log.py
add_handler
python
def add_handler(cls, level, fmt, colorful, **kwargs): global g_logger if isinstance(level, str): level = getattr(logging, level.upper(), logging.DEBUG) handler = cls(**kwargs) handler.setLevel(level) if colorful: formatter = ColoredFormatter(fmt, datefmt='%Y-%m-%d %H:%M:%S') ...
Add a configured handler to the global logger.
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/log.py#L115-L133
null
# coding: utf-8 """ pyextend.core.log ~~~~~~~~~~~~~~~ Implements a simple log library. This module is a simple encapsulation of logging module to provide a more convenient interface to write log. The log will both print to stdout and write to log file. It provides a more flexible way to set the...
Vito2015/pyextend
pyextend/core/log.py
add_filehandler
python
def add_filehandler(level, fmt, filename, mode, backup_count, limit, when): kwargs = {} # If the filename is not set, use the default filename if filename is None: filename = getattr(sys.modules['__main__'], '__file__', 'log.py') filename = os.path.basename(filename.replace('.py', '.log'))...
Add a file handler to the global logger.
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/log.py#L141-L171
[ "def add_handler(cls, level, fmt, colorful, **kwargs):\n \"\"\"Add a configured handler to the global logger.\"\"\"\n global g_logger\n\n if isinstance(level, str):\n level = getattr(logging, level.upper(), logging.DEBUG)\n\n handler = cls(**kwargs)\n handler.setLevel(level)\n\n if colorful...
# coding: utf-8 """ pyextend.core.log ~~~~~~~~~~~~~~~ Implements a simple log library. This module is a simple encapsulation of logging module to provide a more convenient interface to write log. The log will both print to stdout and write to log file. It provides a more flexible way to set the...
Vito2015/pyextend
pyextend/core/log.py
init_logger
python
def init_logger(name=None): global g_logger if g_logger is None: g_logger = logging.getLogger(name=name) else: logging.shutdown() g_logger.handlers = [] g_logger.setLevel(logging.DEBUG)
Reload the global logger.
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/log.py#L174-L184
null
# coding: utf-8 """ pyextend.core.log ~~~~~~~~~~~~~~~ Implements a simple log library. This module is a simple encapsulation of logging module to provide a more convenient interface to write log. The log will both print to stdout and write to log file. It provides a more flexible way to set the...
Vito2015/pyextend
pyextend/core/log.py
set_logger
python
def set_logger(name=None, filename=None, mode='a', level='NOTSET:NOTSET', fmt= '%(asctime)s %(filename)s:%(lineno)d [PID:%(process)-5d THD:%(thread)-5d %(levelname)-7s] %(message)s', # fmt='[%(levelname)s] %(asctime)s %(message)s', backup_count=5, limit=20480,...
Configure the global logger.
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/log.py#L192-L212
[ "def add_streamhandler(level, fmt):\n \"\"\"Add a stream handler to the global logger.\"\"\"\n return add_handler(logging.StreamHandler, level, fmt, True)\n", "def add_filehandler(level, fmt, filename, mode, backup_count, limit, when):\n \"\"\"Add a file handler to the global logger.\"\"\"\n kwargs = ...
# coding: utf-8 """ pyextend.core.log ~~~~~~~~~~~~~~~ Implements a simple log library. This module is a simple encapsulation of logging module to provide a more convenient interface to write log. The log will both print to stdout and write to log file. It provides a more flexible way to set the...
Vito2015/pyextend
pyextend/core/log.py
import_log_funcs
python
def import_log_funcs(): global g_logger curr_mod = sys.modules[__name__] for func_name in _logging_funcs: func = getattr(g_logger, func_name) setattr(curr_mod, func_name, func)
Import the common log functions from the global logger to the module.
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/log.py#L215-L223
null
# coding: utf-8 """ pyextend.core.log ~~~~~~~~~~~~~~~ Implements a simple log library. This module is a simple encapsulation of logging module to provide a more convenient interface to write log. The log will both print to stdout and write to log file. It provides a more flexible way to set the...
Vito2015/pyextend
pyextend/network/regex.py
email_match
python
def email_match(string): m = re.match(email_pattern, string) if m: # print('Match success: %s' % m.string) return m.groups()[0], m.groups()[2] else: # print('Match failed: %s' % string) return None
邮箱地址匹配. 匹配成功返回(email_name, email_server), 否则返回None
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/network/regex.py#L23-L31
null
# coding: utf-8 """ pyextend.network.regex ~~~~~~~~~~~~~~~~~~~~ pyextend network regex :copyright: (c) 2016 by Vito. :license: GNU, see LICENSE for more details. """ __all__ = ['email_match', 'email_pattern'] import re # 表达式,如果匹配成功 这返回Match对象,否则返回None # bill.gates@microsoft.com # 当匹配成功时,在第1,3组中分...
Vito2015/pyextend
pyextend/formula/geo/geohash.py
decode
python
def decode(hashcode, delta=False): lat, lon, lat_length, lon_length = _decode_c2i(hashcode) if hasattr(float, "fromhex"): latitude_delta = 90.0/(1 << lat_length) longitude_delta = 180.0/(1 << lon_length) latitude = _int_to_float_hex(lat, lat_length) * 90.0 + latitude_delta long...
decode a hashcode and get center coordinate, and distance between center and outer border
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/formula/geo/geohash.py#L152-L180
[ "def _int_to_float_hex(i, l):\n if l == 0:\n return -1.0\n\n half = 1 << (l-1)\n s = int((l+3)/4)\n if i >= half:\n i -= half\n return float.fromhex((\"0x0.%0\"+str(s)+\"xp1\") % (i << (s*4-l),))\n else:\n i = half-i\n return float.fromhex((\"-0x0.%0\"+str(s)+\"xp1\...
#!/usr/bin/env python # coding: utf-8 __all__ = ['encode', 'decode', 'decode_exactly', 'bbox', 'neighbors', 'expand'] _base32 = '0123456789bcdefghjkmnpqrstuvwxyz' _base32_map = {} for i in range(len(_base32)): _base32_map[_base32[i]] = i del i LONG_ZERO = 0 import sys if sys.version_info[0] < 3: LONG_ZERO = ...
Vito2015/pyextend
pyextend/formula/geo/geohash.py
bbox
python
def bbox(hashcode): lat, lon, lat_length, lon_length = _decode_c2i(hashcode) if hasattr(float, "fromhex"): latitude_delta = 180.0/(1 << lat_length) longitude_delta = 360.0/(1 << lon_length) latitude = _int_to_float_hex(lat, lat_length) * 90.0 longitude = _int_to_float_hex(lon, l...
decode a hashcode and get north, south, east and west border.
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/formula/geo/geohash.py#L189-L217
[ "def _int_to_float_hex(i, l):\n if l == 0:\n return -1.0\n\n half = 1 << (l-1)\n s = int((l+3)/4)\n if i >= half:\n i -= half\n return float.fromhex((\"0x0.%0\"+str(s)+\"xp1\") % (i << (s*4-l),))\n else:\n i = half-i\n return float.fromhex((\"-0x0.%0\"+str(s)+\"xp1\...
#!/usr/bin/env python # coding: utf-8 __all__ = ['encode', 'decode', 'decode_exactly', 'bbox', 'neighbors', 'expand'] _base32 = '0123456789bcdefghjkmnpqrstuvwxyz' _base32_map = {} for i in range(len(_base32)): _base32_map[_base32[i]] = i del i LONG_ZERO = 0 import sys if sys.version_info[0] < 3: LONG_ZERO = ...
Vito2015/pyextend
pyextend/core/wrappers/timethis.py
timethis
python
def timethis(func): func_module, func_name = func.__module__, func.__name__ @functools.wraps(func) def wrapper(*args, **kwargs): start = _time_perf_counter() r = func(*args, **kwargs) end = _time_perf_counter() print('timethis : <{}.{}> : {}'.format(func_module, func_name, e...
A wrapper use for timeit.
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/wrappers/timethis.py#L23-L34
null
# coding: utf-8 """ pyextend.core.wrappers.timethis ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pyextend core wrappers timethis wrapper :copyright: (c) 2016 by Vito. :license: GNU, see LICENSE for more details. """ import sys import time import functools __all__ = ['timethis'] if sys.version_info < (3, 3): ...
Vito2015/pyextend
pyextend/core/wrappers/accepts.py
accepts
python
def accepts(exception=TypeError, **types): def check_param(v, type_or_funcname): if isinstance(type_or_funcname, tuple): results1 = [check_param(v, t) for t in type_or_funcname if t is not None] results2 = [v == t for t in type_or_funcname if t is None] return any(result...
A wrapper of function for checking function parameters type Example 1: @accepts(a=int, b='__iter__', c=str) def test(a, b=None, c=None): print('accepts OK') test(13, b=[], c='abc') -- OK test('aaa', b=(), c='abc') --Failed Example 2: @accepts(a=int, b=('__...
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/wrappers/accepts.py#L15-L77
null
# coding: utf-8 """ pyextend.core.wrappers.accepts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pyextend core wrappers accepts wrapper :copyright: (c) 2016 by Vito. :license: GNU, see LICENSE for more details. """ import functools from .system import version_info
Vito2015/pyextend
pyextend/core/wrappers/singleton.py
singleton
python
def singleton(cls, *args, **kwargs): instance = {} def _singleton(): if cls not in instance: instance[cls] = cls(*args, **kwargs) return instance[cls] return _singleton
类单例装饰器
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/wrappers/singleton.py#L12-L20
null
# coding: utf-8 """ pyextend.core.wrappers.singleton ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pyextend core wrappers singleton wrapper :copyright: (c) 2016 by Vito. :license: GNU, see LICENSE for more details. """
Vito2015/pyextend
pyextend/core/json2csv.py
json2csv
python
def json2csv(json_str, show_header=False, separator='\t'): json_obj = json.loads(json_str) cols = [col for col in json_obj.keys()] vals = [str(json_obj.get(col)) for col in cols] header = None if show_header: header = separator.join(cols) values = separator.join(vals) return (header...
Format a json string to csv like. :param json_str: json object string :param show_header: can returns csv header line :param separator: csv column format separator :return: if show_header=False: a string like csv formatting; if show_header=True: a tuple (header, csv string)
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/json2csv.py#L6-L23
null
#!/usr/bin/env python # coding: utf-8 import json # if __name__ == '__main__': # source = [ # '{"dbm": 0, "created": "2016-03-21 08:07:11", "registered": false, "lat": 30.303772000000002, "radio": "LTE", ' # '"key": "1cc0000000058b304cf3881", "provider": "network", "imei": "867323022973331", "lng...
Vito2015/pyextend
pyextend/core/wrappers/timeout.py
timeout
python
def timeout(seconds, error_message=None): def decorated(func): result = "" def _handle_timeout(signum, frame): errmsg = error_message or 'Timeout: The action <%s> is timeout!' % func.__name__ global result result = None import inspect sta...
Timeout checking just for Linux-like platform, not working in Windows platform.
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/wrappers/timeout.py#L25-L60
null
# coding: utf-8 """ pyextend.core.wrappers.timeout ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pyextend core wrappers timeout wrapper :copyright: (c) 2016 by Vito. :license: GNU, see LICENSE for more details. """ import os import sys import signal import functools from . import system as sysx if sysx.version_...
Vito2015/pyextend
pyextend/core/itertools.py
unpack
python
def unpack(iterable, count, fill=None): iterable = list(enumerate(iterable)) cnt = count if count <= len(iterable) else len(iterable) results = [iterable[i][1] for i in range(cnt)] # results[len(results):len(results)] = [fill for i in range(count-cnt)] results = merge(results, [fill for i in range(...
The iter data unpack function. Example 1: In[1]: source = 'abc' In[2]: a, b = safe_unpack(source, 2) In[3]: print(a, b) a b Example 2: In[1]: source = 'abc' In[2]: a, b, c, d = safe_unpack(source, 4) In[3]: print(a, b, c, d) a b None None
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/itertools.py#L19-L41
null
# coding: utf-8 """ pyextend.core.itertools ~~~~~~~~~~~~~~~~~~~~~ pyextend core string extension tools :copyright: (c) 2016 by Vito. :license: GNU, see LICENSE for more details. """ __all__ = ['unpack', 'merge'] # from pyextend.core.wrappers import accepts from .wrappers import accepts @accept...
Vito2015/pyextend
pyextend/core/itertools.py
merge
python
def merge(iterable1, *args): result_list = list(iterable1) if not isinstance(iterable1, dict) else eval('list(iterable1.items())') for i, other in enumerate(args, start=1): if not isinstance(other, type(iterable1)): raise TypeError('the parameter type of index {} not equals type of index 0...
Returns an type of iterable1 value, which merged after iterable1 used *args :exception TypeError: if any parameter type of args not equals type(iterable1) Example 1: source = ['a', 'b', 'c'] result = merge(source, [1, 2, 3]) self.assertEqual(result, ['a', 'b', 'c', 1, 2, 3]) r...
train
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/itertools.py#L45-L99
null
# coding: utf-8 """ pyextend.core.itertools ~~~~~~~~~~~~~~~~~~~~~ pyextend core string extension tools :copyright: (c) 2016 by Vito. :license: GNU, see LICENSE for more details. """ __all__ = ['unpack', 'merge'] # from pyextend.core.wrappers import accepts from .wrappers import accepts @accept...
datakortet/dkfileutils
dkfileutils/path.py
Path.touch
python
def touch(self, mode=0o666, exist_ok=True): if exist_ok: # First try to bump modification time # Implementation note: GNU touch uses the UTIME_NOW option of # the utimensat() / futimens() functions. try: os.utime(self, None) except OSEr...
Create this file with the given access mode, if it doesn't exist. Based on: https://github.com/python/cpython/blob/master/Lib/pathlib.py)
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/path.py#L99-L121
null
class Path(str): """Poor man's pathlib. """ def __new__(cls, *args, **kw): if isinstance(args[0], Path): return str.__new__(cls, str(args[0]), **kw) else: return str.__new__(cls, os.path.normcase(args[0]), **kw) def __div__(self, other): return Path( ...
datakortet/dkfileutils
dkfileutils/path.py
Path.glob
python
def glob(self, pat): r = "" negate = int(pat.startswith('!')) i = negate while i < len(pat): if pat[i:i + 3] == '**/': r += "(?:.*/)?" i += 3 elif pat[i] == "*": r += "[^/]*" i += 1 elif ...
`pat` can be an extended glob pattern, e.g. `'**/*.less'` This code handles negations similarly to node.js' minimatch, i.e. a leading `!` will negate the entire pattern.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/path.py#L123-L158
null
class Path(str): """Poor man's pathlib. """ def __new__(cls, *args, **kw): if isinstance(args[0], Path): return str.__new__(cls, str(args[0]), **kw) else: return str.__new__(cls, os.path.normcase(args[0]), **kw) def __div__(self, other): return Path( ...
datakortet/dkfileutils
dkfileutils/path.py
Path.list
python
def list(self, filterfn=lambda x: True): return [self / p for p in self.listdir() if filterfn(self / p)]
Return all direct descendands of directory `self` for which `filterfn` returns True.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/path.py#L329-L333
null
class Path(str): """Poor man's pathlib. """ def __new__(cls, *args, **kw): if isinstance(args[0], Path): return str.__new__(cls, str(args[0]), **kw) else: return str.__new__(cls, os.path.normcase(args[0]), **kw) def __div__(self, other): return Path( ...
datakortet/dkfileutils
dkfileutils/path.py
Path.rm
python
def rm(self, fname=None): if fname is not None: return (self / fname).rm() try: self.remove() except OSError: pass
Remove a file, don't raise exception if file does not exist.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/path.py#L372-L380
null
class Path(str): """Poor man's pathlib. """ def __new__(cls, *args, **kw): if isinstance(args[0], Path): return str.__new__(cls, str(args[0]), **kw) else: return str.__new__(cls, os.path.normcase(args[0]), **kw) def __div__(self, other): return Path( ...
datakortet/dkfileutils
dkfileutils/pfind.py
pfindall
python
def pfindall(path, *fnames): wd = os.path.abspath(path) assert os.path.isdir(wd) def parents(): """yield successive parent directories """ parent = wd yield parent while 1: parent, dirname = os.path.split(parent) if not dirname: ...
Find all fnames in the closest ancestor directory. For the purposes of this function, we are our own closest ancestor. I.e. given the structure:: . `-- a |-- b | |-- c | | `-- x.txt | `-- x.txt ...
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/pfind.py#L10-L56
[ "def parents():\n \"\"\"yield successive parent directories\n \"\"\"\n parent = wd\n yield parent\n while 1:\n parent, dirname = os.path.split(parent)\n if not dirname:\n return\n yield parent\n" ]
#!/usr/bin/python """CLI usage: ``pfind path filename`` will find the closest ancestor directory conataining filename (used for finding syncspec.txt and config files). """ from __future__ import print_function import os import sys def pfind(path, *fnames): """Find the first fname in the closest ancestor direc...
datakortet/dkfileutils
dkfileutils/listfiles.py
read_skipfile
python
def read_skipfile(dirname='.', defaults=None): if defaults is None: defaults = ['Makefile', 'make.bat', 'atlassian-ide-plugin.xml'] try: return defaults + open( os.path.join(dirname, SKIPFILE_NAME) ).read().splitlines() except IOError: return defaults
The .skipfile should contain one entry per line, listing files/directories that should be skipped by :func:`list_files`.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/listfiles.py#L13-L25
null
# -*- coding: utf-8 -*- """List interesting files. """ from __future__ import print_function import argparse import os from hashlib import md5 from .path import Path SKIPFILE_NAME = '.skipfile' def list_files(dirname='.', digest=True): """Yield (digest, fname) tuples for all interesting files in `dirname...
datakortet/dkfileutils
dkfileutils/listfiles.py
list_files
python
def list_files(dirname='.', digest=True): skipdirs = ['__pycache__', '.git', '.svn', 'htmlcov', 'dist', 'build', '.idea', 'tasks', 'static', 'media', 'data', 'migrations', '.doctrees', '_static', 'node_modules', 'external', 'jobs', 'tryout', 'tmp', '_coverage', ...
Yield (digest, fname) tuples for all interesting files in `dirname`.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/listfiles.py#L28-L82
[ "def read_skipfile(dirname='.', defaults=None):\n \"\"\"The .skipfile should contain one entry per line,\n listing files/directories that should be skipped by\n :func:`list_files`.\n \"\"\"\n if defaults is None:\n defaults = ['Makefile', 'make.bat', 'atlassian-ide-plugin.xml']\n try:...
# -*- coding: utf-8 -*- """List interesting files. """ from __future__ import print_function import argparse import os from hashlib import md5 from .path import Path SKIPFILE_NAME = '.skipfile' def read_skipfile(dirname='.', defaults=None): """The .skipfile should contain one entry per line, listing files...
datakortet/dkfileutils
dkfileutils/listfiles.py
main
python
def main(): # pragma: nocover p = argparse.ArgumentParser(add_help="Recursively list interesting files.") p.add_argument( 'directory', nargs="?", default="", help="The directory to process (current dir if omitted)." ) p.add_argument( '--verbose', '-v', action='store_true', ...
Print checksum and file name for all files in the directory.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/listfiles.py#L85-L106
[ "def list_files(dirname='.', digest=True):\n \"\"\"Yield (digest, fname) tuples for all interesting files\n in `dirname`.\n \"\"\"\n skipdirs = ['__pycache__', '.git', '.svn', 'htmlcov', 'dist', 'build',\n '.idea', 'tasks', 'static', 'media', 'data', 'migrations',\n '.do...
# -*- coding: utf-8 -*- """List interesting files. """ from __future__ import print_function import argparse import os from hashlib import md5 from .path import Path SKIPFILE_NAME = '.skipfile' def read_skipfile(dirname='.', defaults=None): """The .skipfile should contain one entry per line, listing files...
datakortet/dkfileutils
dkfileutils/which.py
get_path_directories
python
def get_path_directories(): pth = os.environ['PATH'] if sys.platform == 'win32' and os.environ.get("BASH"): # winbash has a bug.. if pth[1] == ';': # pragma: nocover pth = pth.replace(';', ':', 1) return [p.strip() for p in pth.split(os.pathsep) if p.strip()]
Return a list of all the directories on the path.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/which.py#L18-L26
null
# -*- coding: utf-8 -*- """Print where on the path an executable is located. """ from __future__ import print_function import sys import os from stat import ST_MODE, S_IXUSR, S_IXGRP, S_IXOTH def get_executable(name): """Return the first executable on the path that matches `name`. """ for result in which(...
datakortet/dkfileutils
dkfileutils/which.py
_listdir
python
def _listdir(pth, extensions): try: return [fname for fname in os.listdir(pth) if os.path.splitext(fname)[1] in extensions] except OSError: # pragma: nocover pass
Non-raising listdir.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/which.py#L35-L41
null
# -*- coding: utf-8 -*- """Print where on the path an executable is located. """ from __future__ import print_function import sys import os from stat import ST_MODE, S_IXUSR, S_IXGRP, S_IXOTH def get_executable(name): """Return the first executable on the path that matches `name`. """ for result in which(...
datakortet/dkfileutils
dkfileutils/which.py
which
python
def which(filename, interactive=False, verbose=False): exe = [e.lower() for e in os.environ.get('PATHEXT', '').split(';')] if sys.platform != 'win32': # pragma: nocover exe.append('') name, ext = os.path.splitext(filename) has_extension = bool(ext) if has_extension and ext.lower() not in e...
Yield all executable files on path that matches `filename`.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/which.py#L48-L93
[ "def _normalize(pth):\n return os.path.normcase(os.path.normpath(pth))\n", "def _listdir(pth, extensions):\n \"\"\"Non-raising listdir.\"\"\"\n try:\n return [fname for fname in os.listdir(pth)\n if os.path.splitext(fname)[1] in extensions]\n except OSError: # pragma: nocover\n ...
# -*- coding: utf-8 -*- """Print where on the path an executable is located. """ from __future__ import print_function import sys import os from stat import ST_MODE, S_IXUSR, S_IXGRP, S_IXOTH def get_executable(name): """Return the first executable on the path that matches `name`. """ for result in which(...
datakortet/dkfileutils
tasks.py
build_js
python
def build_js(ctx, force=False): for fname in JSX_FILENAMES: jstools.babel( ctx, '{pkg.source_js}/' + fname, '{pkg.django_static}/{pkg.name}/js/' + fname + '.js', force=force )
Build all javascript files.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/tasks.py#L79-L88
null
# -*- coding: utf-8 -*- """ Base version of package/tasks.py, created by package/root/dir> dk-tasklib install (it should reside in the root directory of your package) This file defines tasks for the Invoke tool: http://www.pyinvoke.org Basic usage:: inv -l # list all available tasks inv b...
datakortet/dkfileutils
tasks.py
build
python
def build(ctx, less=False, docs=False, js=False, force=False): specified = any([less, docs, js]) buildall = not specified if buildall or less: less_fname = ctx.pkg.source_less / ctx.pkg.name + '.less' if less_fname.exists(): lessc.LessRule( ctx, s...
Build everything and collectstatic.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/tasks.py#L92-L123
null
# -*- coding: utf-8 -*- """ Base version of package/tasks.py, created by package/root/dir> dk-tasklib install (it should reside in the root directory of your package) This file defines tasks for the Invoke tool: http://www.pyinvoke.org Basic usage:: inv -l # list all available tasks inv b...
datakortet/dkfileutils
tasks.py
watch
python
def watch(ctx): watcher = Watcher(ctx) watcher.watch_directory( path='{pkg.source_less}', ext='.less', action=lambda e: build(ctx, less=True) ) watcher.watch_directory( path='{pkg.source_js}', ext='.jsx', action=lambda e: build(ctx, js=True) ) watcher.watch_direct...
Automatically run build whenever a relevant file changes.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/tasks.py#L127-L143
null
# -*- coding: utf-8 -*- """ Base version of package/tasks.py, created by package/root/dir> dk-tasklib install (it should reside in the root directory of your package) This file defines tasks for the Invoke tool: http://www.pyinvoke.org Basic usage:: inv -l # list all available tasks inv b...
datakortet/dkfileutils
dkfileutils/changed.py
digest
python
def digest(dirname, glob=None): md5 = hashlib.md5() if glob is None: fnames = [fname for _, fname in list_files(Path(dirname))] for fname in sorted(fnames): fname = os.path.join(dirname, fname) md5.update(open(fname, 'rb').read()) else: fnames = Path(dirname)....
Returns the md5 digest of all interesting files (or glob) in `dirname`.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/changed.py#L12-L25
[ "def list_files(dirname='.', digest=True):\n \"\"\"Yield (digest, fname) tuples for all interesting files\n in `dirname`.\n \"\"\"\n skipdirs = ['__pycache__', '.git', '.svn', 'htmlcov', 'dist', 'build',\n '.idea', 'tasks', 'static', 'media', 'data', 'migrations',\n '.do...
# -*- coding: utf-8 -*- """Check if contents of directory has changed. """ from __future__ import print_function import argparse import os import hashlib from .listfiles import list_files from .path import Path def changed(dirname, filename='.md5', args=None, glob=None): """Has `glob` changed in `dirname` A...
datakortet/dkfileutils
dkfileutils/changed.py
changed
python
def changed(dirname, filename='.md5', args=None, glob=None): root = Path(dirname) if not root.exists(): # if dirname doesn't exist it is changed (by definition) return True cachefile = root / filename current_digest = cachefile.open().read() if cachefile.exists() else "" _diges...
Has `glob` changed in `dirname` Args: dirname: directory to measure filename: filename to store checksum
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/changed.py#L28-L52
[ "def digest(dirname, glob=None):\n \"\"\"Returns the md5 digest of all interesting files (or glob) in `dirname`.\n \"\"\"\n md5 = hashlib.md5()\n if glob is None:\n fnames = [fname for _, fname in list_files(Path(dirname))]\n for fname in sorted(fnames):\n fname = os.path.join(d...
# -*- coding: utf-8 -*- """Check if contents of directory has changed. """ from __future__ import print_function import argparse import os import hashlib from .listfiles import list_files from .path import Path def digest(dirname, glob=None): """Returns the md5 digest of all interesting files (or glob) in `dirnam...
datakortet/dkfileutils
dkfileutils/changed.py
main
python
def main(): # pragma: nocover p = argparse.ArgumentParser() p.add_argument( 'directory', help="Directory to check" ) p.add_argument( '--verbose', '-v', action='store_true', help="increase verbosity" ) args = p.parse_args() import sys _changed = changed(s...
Return exit code of zero iff directory is not changed.
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/changed.py#L67-L83
[ "def changed(dirname, filename='.md5', args=None, glob=None):\n \"\"\"Has `glob` changed in `dirname`\n\n Args:\n dirname: directory to measure\n filename: filename to store checksum\n \"\"\"\n root = Path(dirname)\n if not root.exists():\n # if dirname doesn't exist it is change...
# -*- coding: utf-8 -*- """Check if contents of directory has changed. """ from __future__ import print_function import argparse import os import hashlib from .listfiles import list_files from .path import Path def digest(dirname, glob=None): """Returns the md5 digest of all interesting files (or glob) in `dirnam...
datakortet/dkfileutils
dkfileutils/changed.py
Directory.changed
python
def changed(self, filename='.md5', glob=None): if glob is not None: filename += '.glob-' + ''.join(ch.lower() for ch in glob if ch.isalpha()) return changed(self, filename, glob=glob)
Are any of the files matched by ``glob`` changed?
train
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/changed.py#L58-L64
[ "def changed(dirname, filename='.md5', args=None, glob=None):\n \"\"\"Has `glob` changed in `dirname`\n\n Args:\n dirname: directory to measure\n filename: filename to store checksum\n \"\"\"\n root = Path(dirname)\n if not root.exists():\n # if dirname doesn't exist it is change...
class Directory(Path): """A path that is a directory. """
gear11/pypelogs
pypein/wikip.py
geo_filter
python
def geo_filter(d): page = d["page"] if not "revision" in page: return None title = page["title"] if skip_article(title): LOG.info("Skipping low-value article %s", title) return None text = page["revision"]["text"] if not utils.is_str_type(text): if "#text" in text...
Inspects the given Wikipedia article dict for geo-coordinates. If no coordinates are found, returns None. Otherwise, returns a new dict with the title and URL of the original article, along with coordinates.
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/wikip.py#L76-L111
[ "def wikip_url(s):\n return 'http://wikipedia.org/wiki/'+s.replace(' ', '_')\n", "def skip_article(title):\n \"\"\"Skips articles that have no value\"\"\"\n if title.find(\"Wikipedia:WikiProject National Register of Historic Places/\") == 0:\n return True\n return False\n", "def find_geo_coor...
import g11pyutils as utils import xml.etree.ElementTree as ET from xml.etree.ElementTree import XMLParser import logging import re import base64 import hashlib import codecs LOG = logging.getLogger("wikip") class WikipXMLParser(XMLParser): def init(self, html=0, target=None, encoding=None): super(WikipXML...
gear11/pypelogs
pypein/wikip.py
find_geo_coords
python
def find_geo_coords(s): coords = [] LOG.debug("Matching in text size %s", len(s)) for c in INFO_BOX_LAT_LON.findall(s): try: coord = (float(c[1]), float(c[2])) #, c[0]) coords.append(coord) LOG.debug("Found info box lat/lon: %s", coord) except Exception a...
Returns a list of lat/lons found by scanning the given text
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/wikip.py#L132-L177
[ "def skip_coords(c):\n \"\"\"Skip coordinate strings that are not valid\"\"\"\n if c == \"{{coord|LAT|LONG|display=inline,title}}\": # Unpopulated coord template\n return True\n if c.find(\"globe:\") >= 0 and c.find(\"globe:earth\") == -1: # Moon, venus, etc.\n return True\n return False\n...
import g11pyutils as utils import xml.etree.ElementTree as ET from xml.etree.ElementTree import XMLParser import logging import re import base64 import hashlib import codecs LOG = logging.getLogger("wikip") class WikipXMLParser(XMLParser): def init(self, html=0, target=None, encoding=None): super(WikipXML...
gear11/pypelogs
pypein/wikip.py
depipe
python
def depipe(s): n = 0 for i in reversed(s.split('|')): n = n / 60.0 + float(i) return n
Convert a string of the form DD or DD|MM or DD|MM|SS to decimal degrees
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/wikip.py#L179-L184
null
import g11pyutils as utils import xml.etree.ElementTree as ET from xml.etree.ElementTree import XMLParser import logging import re import base64 import hashlib import codecs LOG = logging.getLogger("wikip") class WikipXMLParser(XMLParser): def init(self, html=0, target=None, encoding=None): super(WikipXML...
gear11/pypelogs
pypein/wikip.py
skip_coords
python
def skip_coords(c): if c == "{{coord|LAT|LONG|display=inline,title}}": # Unpopulated coord template return True if c.find("globe:") >= 0 and c.find("globe:earth") == -1: # Moon, venus, etc. return True return False
Skip coordinate strings that are not valid
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/wikip.py#L186-L192
null
import g11pyutils as utils import xml.etree.ElementTree as ET from xml.etree.ElementTree import XMLParser import logging import re import base64 import hashlib import codecs LOG = logging.getLogger("wikip") class WikipXMLParser(XMLParser): def init(self, html=0, target=None, encoding=None): super(WikipXML...
gear11/pypelogs
pypein/flickr.py
Flickr.photo
python
def photo(self, args): rsp = self._load_rsp(self.flickr.photos_getInfo(photo_id=args[0])) p = rsp['photo'] yield self._prep(p)
Retrieves metadata for a specific photo. flickr:(credsfile),photo,(photo_id)
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L58-L66
[ "def _prep(e):\n \"\"\"\n Normalizes lastupdate to a timestamp, and constructs a URL from the embedded attributes.\n \"\"\"\n if 'lastupdate' in e:\n e['lastupdate'] = datetime.datetime.fromtimestamp(int(e['lastupdate']))\n for k in ['farm', 'server', 'id', 'secret']:\n if not k in e:\n...
class Flickr(object): """ Input from the Flickr API. Uses the flickrapi package from PIP ( http://stuvel.eu/flickrapi ) Usage: flickr:credsfile,command,args The credsfile is a JSON credentials file containing the Flickr API key and secret: { 'api_key': '....', 'api_secret': '....'...
gear11/pypelogs
pypein/flickr.py
Flickr.search
python
def search(self, args): kwargs = {} for a in args: k, v = a.split('=') kwargs[k] = v return self._paged_api_call(self.flickr.photos_search, kwargs)
Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)...
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L68-L78
[ "def _paged_api_call(self, func, kwargs, item_type='photo'):\n \"\"\"\n Takes a Flickr API function object and dict of keyword args and calls the\n API call repeatedly with an incrementing page value until all contents are exhausted.\n Flickr seems to limit to about 500 items.\n \"\"\"\n page = 1\...
class Flickr(object): """ Input from the Flickr API. Uses the flickrapi package from PIP ( http://stuvel.eu/flickrapi ) Usage: flickr:credsfile,command,args The credsfile is a JSON credentials file containing the Flickr API key and secret: { 'api_key': '....', 'api_secret': '....'...
gear11/pypelogs
pypein/flickr.py
Flickr.interesting
python
def interesting(self, args=None): kwargs = {'extras': ','.join(args) if args else 'last_update,geo,owner_name,url_sq'} return self._paged_api_call(self.flickr.interestingness_getList, kwargs)
Gets interesting photos. flickr:(credsfile),interesting
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L80-L88
[ "def _paged_api_call(self, func, kwargs, item_type='photo'):\n \"\"\"\n Takes a Flickr API function object and dict of keyword args and calls the\n API call repeatedly with an incrementing page value until all contents are exhausted.\n Flickr seems to limit to about 500 items.\n \"\"\"\n page = 1\...
class Flickr(object): """ Input from the Flickr API. Uses the flickrapi package from PIP ( http://stuvel.eu/flickrapi ) Usage: flickr:credsfile,command,args The credsfile is a JSON credentials file containing the Flickr API key and secret: { 'api_key': '....', 'api_secret': '....'...
gear11/pypelogs
pypein/flickr.py
Flickr.search_groups
python
def search_groups(self, args): kwargs = {'text': args[0]} return self._paged_api_call(self.flickr.groups_search, kwargs, 'group')
Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)...
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L90-L97
[ "def _paged_api_call(self, func, kwargs, item_type='photo'):\n \"\"\"\n Takes a Flickr API function object and dict of keyword args and calls the\n API call repeatedly with an incrementing page value until all contents are exhausted.\n Flickr seems to limit to about 500 items.\n \"\"\"\n page = 1\...
class Flickr(object): """ Input from the Flickr API. Uses the flickrapi package from PIP ( http://stuvel.eu/flickrapi ) Usage: flickr:credsfile,command,args The credsfile is a JSON credentials file containing the Flickr API key and secret: { 'api_key': '....', 'api_secret': '....'...
gear11/pypelogs
pypein/flickr.py
Flickr.group
python
def group(self, args): kwargs = {'group_id': args[0]} return self._paged_api_call(self.flickr.groups_pools_getPhotos, kwargs)
Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)...
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L99-L106
[ "def _paged_api_call(self, func, kwargs, item_type='photo'):\n \"\"\"\n Takes a Flickr API function object and dict of keyword args and calls the\n API call repeatedly with an incrementing page value until all contents are exhausted.\n Flickr seems to limit to about 500 items.\n \"\"\"\n page = 1\...
class Flickr(object): """ Input from the Flickr API. Uses the flickrapi package from PIP ( http://stuvel.eu/flickrapi ) Usage: flickr:credsfile,command,args The credsfile is a JSON credentials file containing the Flickr API key and secret: { 'api_key': '....', 'api_secret': '....'...
gear11/pypelogs
pypein/flickr.py
Flickr._paged_api_call
python
def _paged_api_call(self, func, kwargs, item_type='photo'): page = 1 while True: LOG.info("Fetching page %s" % page) kwargs['page'] = page rsp = self._load_rsp(func(**kwargs)) if rsp["stat"] == "ok": plural = item_type + 's' ...
Takes a Flickr API function object and dict of keyword args and calls the API call repeatedly with an incrementing page value until all contents are exhausted. Flickr seems to limit to about 500 items.
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L108-L133
[ "def _prep(e):\n \"\"\"\n Normalizes lastupdate to a timestamp, and constructs a URL from the embedded attributes.\n \"\"\"\n if 'lastupdate' in e:\n e['lastupdate'] = datetime.datetime.fromtimestamp(int(e['lastupdate']))\n for k in ['farm', 'server', 'id', 'secret']:\n if not k in e:\n...
class Flickr(object): """ Input from the Flickr API. Uses the flickrapi package from PIP ( http://stuvel.eu/flickrapi ) Usage: flickr:credsfile,command,args The credsfile is a JSON credentials file containing the Flickr API key and secret: { 'api_key': '....', 'api_secret': '....'...
gear11/pypelogs
pypein/flickr.py
Flickr._prep
python
def _prep(e): if 'lastupdate' in e: e['lastupdate'] = datetime.datetime.fromtimestamp(int(e['lastupdate'])) for k in ['farm', 'server', 'id', 'secret']: if not k in e: return e e["url"] = "https://farm%s.staticflickr.com/%s/%s_%s_b.jpg" % (e["farm"], e["se...
Normalizes lastupdate to a timestamp, and constructs a URL from the embedded attributes.
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L136-L146
null
class Flickr(object): """ Input from the Flickr API. Uses the flickrapi package from PIP ( http://stuvel.eu/flickrapi ) Usage: flickr:credsfile,command,args The credsfile is a JSON credentials file containing the Flickr API key and secret: { 'api_key': '....', 'api_secret': '....'...
gear11/pypelogs
pypein/flickr.py
Flickr._load_rsp
python
def _load_rsp(rsp): first = rsp.find('(') + 1 last = rsp.rfind(')') return json.loads(rsp[first:last])
Converts raw Flickr string response to Python dict
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L149-L155
null
class Flickr(object): """ Input from the Flickr API. Uses the flickrapi package from PIP ( http://stuvel.eu/flickrapi ) Usage: flickr:credsfile,command,args The credsfile is a JSON credentials file containing the Flickr API key and secret: { 'api_key': '....', 'api_secret': '....'...
gear11/pypelogs
pypein/nginx.py
Nginx.to_ts
python
def to_ts(s): # Strip TZ portion if present m = Nginx.DATE_FMT.match(s) if m: s = m.group(1) delta = timedelta(seconds=int(m.group(3)) * (-1 if m.group(2) == '-' else 1)) # Offset from GMT else: delta = timedelta(seconds=0) dt = datetime.strpt...
Parses an NGINX timestamp from "30/Apr/2014:07:32:09 +0000" and returns it as ISO 8601"
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/nginx.py#L65-L77
null
class Nginx(object): """ Parses an NGINX log with the following format: 10.208.128.193 - - [30/Apr/2014:07:32:09 +0000] "GET / HTTP/1.1" 200 2089 "-" "Mozilla/5.0 (Lin...37.36" 0.028 "149.254.219.174, 66.249.93.213, 10.183.252.20, ::ffff:127.0.0.1,::ffff:127.0.0.1" And assigns to event properties as f...
gear11/pypelogs
pypelogs.py
process
python
def process(specs): pout, pin = chain_specs(specs) LOG.info("Processing") sw = StopWatch().start() r = pout.process(pin) if r: print(r) LOG.info("Finished in %s", sw.read())
Executes the passed in list of specs
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypelogs.py#L33-L43
[ "def chain_specs(specs):\n \"\"\"\n Parses the incoming list of specs and produces a tuple (pout, pin) that can be invoked with:\n <pre>\n result = pout.process(pin)\n </pre>\n \"\"\"\n LOG.info(\"Parsing %s specs\", len(specs))\n # First spec is always an input\n pin = pypein...
import logging import argparse import sys import pypein import pypef import pypeout from g11pyutils import StopWatch LOG = logging.getLogger("pypelogs") def main(): parser = argparse.ArgumentParser() parser.add_argument('specs', metavar='S', nargs='*', help='A pype specification') parser.add_argument("-d...
gear11/pypelogs
pypelogs.py
chain_specs
python
def chain_specs(specs): LOG.info("Parsing %s specs", len(specs)) # First spec is always an input pin = pypein.input_for(specs[0]).__iter__() # If only an input spec was provided, then use json for output if len(specs) == 1: pout = pypeout.output_for("json") else: # Middle specs a...
Parses the incoming list of specs and produces a tuple (pout, pin) that can be invoked with: <pre> result = pout.process(pin) </pre>
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypelogs.py#L46-L70
[ "def input_for(s):\n spec_args = s.split(':', 1)\n clz = CLASSES.get(spec_args[0])\n if not clz:\n raise ValueError(\"No such input type: %s\", spec_args[0])\n return clz() if len(spec_args) == 1 else clz(spec_args[1])\n", "def filter_for(s):\n spec_args = s.split(':', 1)\n clz = CLASSES....
import logging import argparse import sys import pypein import pypef import pypeout from g11pyutils import StopWatch LOG = logging.getLogger("pypelogs") def main(): parser = argparse.ArgumentParser() parser.add_argument('specs', metavar='S', nargs='*', help='A pype specification') parser.add_argument("-d...
gear11/pypelogs
pypeout/mysql_out.py
MySQLOut.upsert
python
def upsert(self, events): existing = self.get_existing_keys(events) inserts = [e for e in events if not e[self.key] in existing] updates = [e for e in events if e[self.key] in existing] self.insert(inserts) self.update(updates)
Inserts/updates the given events into MySQL
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypeout/mysql_out.py#L35-L41
[ "def get_existing_keys(self, events):\n \"\"\"Returns the list of keys from the given event source that are already in the DB\"\"\"\n data = [e[self.key] for e in events]\n ss = ','.join(['%s' for _ in data])\n query = 'SELECT %s FROM %s WHERE %s IN (%s)' % (self.key, self.table, self.key, ss)\n curs...
class MySQLOut(MySQLIn): """ Supports upserting of data into MySQL. Unlike the SQL output, this does a non-standard 'upsert' operation that can update rows. Example usage: mysql:username:password@host:port/db,upsert,table,key The incoming events are expected to be compatible with the target tabl...
gear11/pypelogs
pypeout/mysql_out.py
MySQLOut.get_existing_keys
python
def get_existing_keys(self, events): data = [e[self.key] for e in events] ss = ','.join(['%s' for _ in data]) query = 'SELECT %s FROM %s WHERE %s IN (%s)' % (self.key, self.table, self.key, ss) cursor = self.conn.conn.cursor() cursor.execute(query, data) LOG.info("%s (dat...
Returns the list of keys from the given event source that are already in the DB
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypeout/mysql_out.py#L43-L53
null
class MySQLOut(MySQLIn): """ Supports upserting of data into MySQL. Unlike the SQL output, this does a non-standard 'upsert' operation that can update rows. Example usage: mysql:username:password@host:port/db,upsert,table,key The incoming events are expected to be compatible with the target tabl...
gear11/pypelogs
pypeout/mysql_out.py
MySQLOut.insert
python
def insert(self, events): if not len(events): return keys = sorted(events[0].keys()) ss = ','.join(['%s' for _ in keys]) query = 'INSERT INTO %s (%s) VALUES ' % (self.table, ','.join(keys)) data = [] for event in events: query += '(%s),' % ss ...
Constructs and executes a MySQL insert for the given events.
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypeout/mysql_out.py#L55-L71
null
class MySQLOut(MySQLIn): """ Supports upserting of data into MySQL. Unlike the SQL output, this does a non-standard 'upsert' operation that can update rows. Example usage: mysql:username:password@host:port/db,upsert,table,key The incoming events are expected to be compatible with the target tabl...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/driver.py
dumplist
python
def dumplist(args): from .query import Database db = Database() r = db.objects( protocol=args.protocol, purposes=args.purpose, model_ids=(args.client,), groups=args.group, classes=args.sclass ) output = sys.stdout if args.selftest: from bob.db.utils import null outpu...
Dumps lists of files based on your criteria
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/driver.py#L23-L45
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be usef...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/driver.py
checkfiles
python
def checkfiles(args): from .query import Database db = Database() r = db.objects() # go through all files, check if they are available on the filesystem good = [] bad = [] for f in r: if os.path.exists(f.make_path(args.directory, args.extension)): good.append(f) else: bad.append(f) ...
Checks existence of files based on your criteria
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/driver.py#L47-L76
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be usef...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/driver.py
reverse
python
def reverse(args): from .query import Database db = Database() output = sys.stdout if args.selftest: from bob.db.utils import null output = null() r = db.reverse(args.path) for f in r: output.write('%d\n' % f.id) if not r: return 1 return 0
Returns a list of file database identifiers given the path stems
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/driver.py#L78-L94
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be usef...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/driver.py
path
python
def path(args): from .query import Database db = Database() output = sys.stdout if args.selftest: from bob.db.utils import null output = null() r = db.paths(args.id, prefix=args.directory, suffix=args.extension) for path in r: output.write('%s\n' % path) if not r: return 1 return 0
Returns a list of fully formed paths or stems given some file id
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/driver.py#L96-L112
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be usef...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/query.py
Database.clients
python
def clients(self, protocol=None, groups=None): groups = self.__group_replace_eval_by_genuine__(groups) groups = self.check_parameters_for_validity(groups, "group", self.client_types()) # List of the clients q = self.query(Client) if groups: q = q.filter(Client.stype.in_(groups)) q = q.ord...
Returns a list of :py:class:`.Client` for the specific query by the user. Keyword Parameters: protocol Ignored. groups The groups (types) to which the clients belong either from ('Genuine', 'Impostor') Note that 'eval' is an alias for 'Genuine'. If no groups are specified, then bo...
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L68-L91
null
class Database(xbob.db.verification.utils.SQLiteDatabase,xbob.db.verification.utils.Database): """The dataset class opens and maintains a connection opened to the Database. It provides many different ways to probe for the characteristics of the data and for the data itself inside the database. """ def __ini...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/query.py
Database.model_ids
python
def model_ids(self, protocol=None, groups=None): return [client.subid for client in self.models(protocol, groups)]
Returns a list of model ids for the specific query by the user. Models correspond to Clients for the XM2VTS database (At most one model per identity). Keyword Parameters: protocol Ignored. groups The groups to which the subjects attached to the models belong ('dev', 'eval', 'world') ...
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L122-L140
null
class Database(xbob.db.verification.utils.SQLiteDatabase,xbob.db.verification.utils.Database): """The dataset class opens and maintains a connection opened to the Database. It provides many different ways to probe for the characteristics of the data and for the data itself inside the database. """ def __ini...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/query.py
Database.has_client_id
python
def has_client_id(self, id): return self.query(Client).filter(Client.id==id).count() != 0
Returns True if we have a client with a certain integer identifier
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L142-L145
null
class Database(xbob.db.verification.utils.SQLiteDatabase,xbob.db.verification.utils.Database): """The dataset class opens and maintains a connection opened to the Database. It provides many different ways to probe for the characteristics of the data and for the data itself inside the database. """ def __ini...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/query.py
Database.client
python
def client(self, id): return self.query(Client).filter(Client.id==id).one()
Returns the client object in the database given a certain id. Raises an error if that does not exist.
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L147-L151
null
class Database(xbob.db.verification.utils.SQLiteDatabase,xbob.db.verification.utils.Database): """The dataset class opens and maintains a connection opened to the Database. It provides many different ways to probe for the characteristics of the data and for the data itself inside the database. """ def __ini...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/query.py
Database.objects
python
def objects(self, protocol=None, purposes=None, model_ids=None, groups=None, classes=None): #groups = self.__group_replace_alias_clients__(groups) protocol = self.check_parameters_for_validity(protocol, "protocol", self.protocol_names()) purposes = self.check_parameters_for_validity(purposes,...
Returns a list of :py:class:`.File` for the specific query by the user. Keyword Parameters: protocol One of the Biosecurid protocols ('A'). purposes The purposes required to be retrieved ('enrol', 'probe') or a tuple with several of them. If 'None' is given (this is the default), it is ...
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L153-L230
null
class Database(xbob.db.verification.utils.SQLiteDatabase,xbob.db.verification.utils.Database): """The dataset class opens and maintains a connection opened to the Database. It provides many different ways to probe for the characteristics of the data and for the data itself inside the database. """ def __ini...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/query.py
Database.protocol_names
python
def protocol_names(self): l = self.protocols() retval = [str(k.name) for k in l] return retval
Returns all registered protocol names
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L232-L237
null
class Database(xbob.db.verification.utils.SQLiteDatabase,xbob.db.verification.utils.Database): """The dataset class opens and maintains a connection opened to the Database. It provides many different ways to probe for the characteristics of the data and for the data itself inside the database. """ def __ini...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/query.py
Database.has_protocol
python
def has_protocol(self, name): return self.query(Protocol).filter(Protocol.name==name).count() != 0
Tells if a certain protocol is available
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L244-L247
null
class Database(xbob.db.verification.utils.SQLiteDatabase,xbob.db.verification.utils.Database): """The dataset class opens and maintains a connection opened to the Database. It provides many different ways to probe for the characteristics of the data and for the data itself inside the database. """ def __ini...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/query.py
Database.protocol
python
def protocol(self, name): return self.query(Protocol).filter(Protocol.name==name).one()
Returns the protocol object in the database given a certain name. Raises an error if that does not exist.
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L249-L253
null
class Database(xbob.db.verification.utils.SQLiteDatabase,xbob.db.verification.utils.Database): """The dataset class opens and maintains a connection opened to the Database. It provides many different ways to probe for the characteristics of the data and for the data itself inside the database. """ def __ini...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/create.py
add_clients
python
def add_clients(session, verbose): for ctype in ['Genuine', 'Impostor']: for cdid in userid_clients: cid = ctype + '_%d' % cdid if verbose>1: print(" Adding user '%s' of type '%s'..." % (cid, ctype)) session.add(Client(cid, ctype, cdid))
Add clients to the ATVS Keystroke database.
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/create.py#L30-L36
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be usef...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/create.py
add_files
python
def add_files(session, imagedir, verbose): def add_file(session, basename, userid, shotid, sessionid): """Parse a single filename and add it to the list.""" session.add(File(userid, basename, sessionid, shotid)) filenames = os.listdir(imagedir) for filename in filenames: basename, extension = os.pat...
Add files to the ATVS Keystroke database.
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/create.py#L39-L62
[ "def add_file(session, basename, userid, shotid, sessionid):\n \"\"\"Parse a single filename and add it to the list.\"\"\"\n session.add(File(userid, basename, sessionid, shotid))\n" ]
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be usef...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/create.py
add_protocols
python
def add_protocols(session, verbose): # 1. DEFINITIONS enroll_session = [1] client_probe_session = [2] impostor_probe_session = [3] protocols = ['A'] # 2. ADDITIONS TO THE SQL DATABASE protocolPurpose_list = [('eval', 'enrol'), ('eval', 'probe')] for proto in protocols: p = Protocol(proto) # Ad...
Adds protocols
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/create.py#L65-L109
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be usef...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/create.py
create_tables
python
def create_tables(args): from bob.db.utils import create_engine_try_nolock engine = create_engine_try_nolock(args.type, args.files[0], echo=(args.verbose > 2)) Base.metadata.create_all(engine)
Creates all necessary tables (only to be used at the first time)
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/create.py#L112-L117
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be usef...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/create.py
create
python
def create(args): from bob.db.utils import session_try_nolock dbfile = args.files[0] if args.recreate: if args.verbose and os.path.exists(dbfile): print('unlinking %s...' % dbfile) if os.path.exists(dbfile): os.unlink(dbfile) if not os.path.exists(os.path.dirname(dbfile)): os.makedirs(os.p...
Creates or re-creates this database
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/create.py#L122-L144
[ "def add_clients(session, verbose):\n \"\"\"Add clients to the ATVS Keystroke database.\"\"\"\n for ctype in ['Genuine', 'Impostor']:\n for cdid in userid_clients:\n cid = ctype + '_%d' % cdid\n if verbose>1: print(\" Adding user '%s' of type '%s'...\" % (cid, ctype))\n session.add(Client(cid, ...
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be usef...
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/create.py
add_command
python
def add_command(subparsers): parser = subparsers.add_parser('create', help=create.__doc__) parser.add_argument('-R', '--recreate', action='store_true', help="If set, I'll first erase the current database") parser.add_argument('-v', '--verbose', action='count', help="Do SQL operations in a verbose way?") parse...
Add specific subcommands that the action "create" can use
train
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/create.py#L146-L155
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be usef...
RonenNess/Fileter
fileter/iterators/concat_files.py
ConcatFiles.process_file
python
def process_file(self, path, dryrun): # special case - skip output file so we won't include it in result if path == self._output_path: return None # if dryrun skip and return file if dryrun: return path # concat file with output file with open(pa...
Concat files and return filename.
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/iterators/concat_files.py#L41-L59
null
class ConcatFiles(files_iterator.FilesIterator): """ This files iterator concat all scanned files. """ def __init__(self, outfile): """ concat all source files into one output file. :param outfile: output file path. """ super(ConcatFiles, self).__init__() ...
RonenNess/Fileter
fileter/iterators/add_header.py
AddHeader.process_file
python
def process_file(self, path, dryrun): if dryrun: return path # get file's current header with open(path, "r") as infile: head = infile.read(len(self.__header)) # normalize line breaks if self.__normalize_br: head = head.replace("\r\n", "\n") ...
Add header to all files.
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/iterators/add_header.py#L40-L63
null
class AddHeader(files_iterator.FilesIterator): """ This iterator will add a constant header to all files, unless header already exist. For example, this can be used to add #!/usr/bin/python # -*- coding: utf-8 -*- To all python files. """ def __init__(self, header, normalize_br=False)...
RonenNess/Fileter
fileter/iterators/add_header.py
AddHeader.push_header
python
def push_header(self, filename): # open file and read it all with open(filename, "r") as infile: content = infile.read() # push header content = self.__header + content # re-write file with the header with open(filename, "w") as outfile: outfile....
Push the header to a given filename :param filename: the file path to push into.
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/iterators/add_header.py#L65-L79
null
class AddHeader(files_iterator.FilesIterator): """ This iterator will add a constant header to all files, unless header already exist. For example, this can be used to add #!/usr/bin/python # -*- coding: utf-8 -*- To all python files. """ def __init__(self, header, normalize_br=False)...
RonenNess/Fileter
fileter/iterators/grep.py
Grep.process_file
python
def process_file(self, path, dryrun): # if dryrun just return files if dryrun: return path # scan file and match lines ret = [] with open(path, "r") as infile: for line in infile: if re.search(self.__exp, line): ret.app...
Print files path.
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/iterators/grep.py#L39-L55
null
class Grep(files_iterator.FilesIterator): """ Iterate over files and return lines that match the grep condition. Return a list of lists: for every file return the list of occurances found in it. """ def __init__(self, expression): """ Init the grep iterator. :param expressio...
RonenNess/Fileter
fileter/files_iterator.py
FilesIterator.add_folder
python
def add_folder(self, path, depth=None, source_type=DefaultSourceType): self.add_source(FolderSource(path, depth, **source_type)) return self
Add a folder source to scan recursively from path (string). :param path: folder path. :param depth: if provided will be depth limit. 0 = first level only. :param source_type: what to return; files only, folders only, or both.
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/files_iterator.py#L87-L96
null
class FilesIterator(object): """ Base class to iterate over file sources and perform pre-defined actions on them. This class can be used in two ways: 1. as an iterator, if you want to iterate files and use them externally. 2. as an object that have pre-defined processing function and can iterate an...
RonenNess/Fileter
fileter/files_iterator.py
FilesIterator.add_pattern
python
def add_pattern(self, pattern, root=".", depth=None, source_type=DefaultSourceType): self.add_source(PatternSource(pattern, root, depth, **source_type)) return self
Add a recursive folder scan using a linux-style patterns. :param pattern: pattern or list of patterns to match. :param root: root to start from (default to '.') :param depth: if provided will be depth limit. 0 = first level only. :param source_type: what to return; files only, folders o...
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/files_iterator.py#L98-L108
null
class FilesIterator(object): """ Base class to iterate over file sources and perform pre-defined actions on them. This class can be used in two ways: 1. as an iterator, if you want to iterate files and use them externally. 2. as an object that have pre-defined processing function and can iterate an...
RonenNess/Fileter
fileter/files_iterator.py
FilesIterator.add_filtered_folder
python
def add_filtered_folder(self, path, regex, depth=None, source_type=DefaultSourceType): self.add_source(FilteredFolderSource(path, regex, depth, **source_type)) return self
Add a folder source to scan recursively, with a regex filter on directories. :param regex: regex string to filter folders by. :param depth: if provided will be depth limit. 0 = first level only. :param source_type: what to return; files only, folders only, or both.
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/files_iterator.py#L110-L119
null
class FilesIterator(object): """ Base class to iterate over file sources and perform pre-defined actions on them. This class can be used in two ways: 1. as an iterator, if you want to iterate files and use them externally. 2. as an object that have pre-defined processing function and can iterate an...
RonenNess/Fileter
fileter/files_iterator.py
FilesIterator.add_filter
python
def add_filter(self, files_filter, filter_type=DefaultFilterType): self.__filters.append((files_filter, filter_type)) return self
Add a files filter to this iterator. For a file to be processed, it must match ALL filters, eg they are added with ADD, not OR. :param files_filter: filter to apply, must be an object inheriting from filters.FilterAPI. :param filter_type: filter behavior, see FilterType for details.
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/files_iterator.py#L121-L130
null
class FilesIterator(object): """ Base class to iterate over file sources and perform pre-defined actions on them. This class can be used in two ways: 1. as an iterator, if you want to iterate files and use them externally. 2. as an object that have pre-defined processing function and can iterate an...
RonenNess/Fileter
fileter/files_iterator.py
FilesIterator.add_filter_by_pattern
python
def add_filter_by_pattern(self, pattern, filter_type=DefaultFilterType): self.add_filter(FilterPattern(pattern), filter_type) return self
Add a files filter by linux-style pattern to this iterator. :param pattern: linux-style files pattern (or list of patterns)
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/files_iterator.py#L132-L139
null
class FilesIterator(object): """ Base class to iterate over file sources and perform pre-defined actions on them. This class can be used in two ways: 1. as an iterator, if you want to iterate files and use them externally. 2. as an object that have pre-defined processing function and can iterate an...
RonenNess/Fileter
fileter/files_iterator.py
FilesIterator.add_filter_by_regex
python
def add_filter_by_regex(self, regex_expression, filter_type=DefaultFilterType): self.add_filter(FilterRegex(regex_expression), filter_type) return self
Add a files filter by regex to this iterator. :param regex_expression: regex string to apply.
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/files_iterator.py#L141-L148
null
class FilesIterator(object): """ Base class to iterate over file sources and perform pre-defined actions on them. This class can be used in two ways: 1. as an iterator, if you want to iterate files and use them externally. 2. as an object that have pre-defined processing function and can iterate an...
RonenNess/Fileter
fileter/files_iterator.py
FilesIterator.add_filter_by_extension
python
def add_filter_by_extension(self, extensions, filter_type=DefaultFilterType): self.add_filter(FilterExtension(extensions), filter_type) return self
Add a files filter by extensions to this iterator. :param extensions: single extension or list of extensions to filter by. for example: ["py", "js", "cpp", ...]
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/files_iterator.py#L150-L158
null
class FilesIterator(object): """ Base class to iterate over file sources and perform pre-defined actions on them. This class can be used in two ways: 1. as an iterator, if you want to iterate files and use them externally. 2. as an object that have pre-defined processing function and can iterate an...
RonenNess/Fileter
fileter/files_iterator.py
FilesIterator.next
python
def next(self, dryrun=False): # call the start hook self.on_start(dryrun) # store current dir curr_dir = "" # iterate over sources for src in self.__sources: # call the start_source hook self.on_start_source(src, dryrun) # iterate ...
Iterate over files in all sources. Use this if you want to iterate files externally. :param dryrun: if true, will only return all filenames instead of processing them, eg will not call "process_file" at all, and just show all the files it will scan.
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/files_iterator.py#L190-L236
null
class FilesIterator(object): """ Base class to iterate over file sources and perform pre-defined actions on them. This class can be used in two ways: 1. as an iterator, if you want to iterate files and use them externally. 2. as an object that have pre-defined processing function and can iterate an...