repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
krukas/Trionyx
trionyx/navigation.py
MenuItem.child_by_code
def child_by_code(self, code): """ Get child MenuItem by its last path code :param code: :return: MenuItem or None """ for child in self.childs: if child.path.split('/')[-1] == code: return child return None
python
def child_by_code(self, code): """ Get child MenuItem by its last path code :param code: :return: MenuItem or None """ for child in self.childs: if child.path.split('/')[-1] == code: return child return None
[ "def", "child_by_code", "(", "self", ",", "code", ")", ":", "for", "child", "in", "self", ".", "childs", ":", "if", "child", ".", "path", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "==", "code", ":", "return", "child", "return", "None" ]
Get child MenuItem by its last path code :param code: :return: MenuItem or None
[ "Get", "child", "MenuItem", "by", "its", "last", "path", "code" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L172-L182
krukas/Trionyx
trionyx/navigation.py
MenuItem.is_active
def is_active(self, path): """Check if given path is active for current item""" if self.url == '/' and self.url == path: return True elif self.url == '/': return False if self.url and path.startswith(self.url): return True if self.active_rege...
python
def is_active(self, path): """Check if given path is active for current item""" if self.url == '/' and self.url == path: return True elif self.url == '/': return False if self.url and path.startswith(self.url): return True if self.active_rege...
[ "def", "is_active", "(", "self", ",", "path", ")", ":", "if", "self", ".", "url", "==", "'/'", "and", "self", ".", "url", "==", "path", ":", "return", "True", "elif", "self", ".", "url", "==", "'/'", ":", "return", "False", "if", "self", ".", "ur...
Check if given path is active for current item
[ "Check", "if", "given", "path", "is", "active", "for", "current", "item" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L184-L200
krukas/Trionyx
trionyx/navigation.py
TabRegister.get_tabs
def get_tabs(self, model_alias, object): """ Get all active tabs for given model :param model_alias: :param object: Object used to filter tabs :return: """ model_alias = self.get_model_alias(model_alias) for item in self.tabs[model_alias]: if ...
python
def get_tabs(self, model_alias, object): """ Get all active tabs for given model :param model_alias: :param object: Object used to filter tabs :return: """ model_alias = self.get_model_alias(model_alias) for item in self.tabs[model_alias]: if ...
[ "def", "get_tabs", "(", "self", ",", "model_alias", ",", "object", ")", ":", "model_alias", "=", "self", ".", "get_model_alias", "(", "model_alias", ")", "for", "item", "in", "self", ".", "tabs", "[", "model_alias", "]", ":", "if", "item", ".", "display_...
Get all active tabs for given model :param model_alias: :param object: Object used to filter tabs :return:
[ "Get", "all", "active", "tabs", "for", "given", "model" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L210-L221
krukas/Trionyx
trionyx/navigation.py
TabRegister.get_tab
def get_tab(self, model_alias, object, tab_code): """ Get tab for given object and tab code :param model_alias: :param object: Object used to render tab :param tab_code: Tab code to use :return: """ model_alias = self.get_model_alias(model_alias) ...
python
def get_tab(self, model_alias, object, tab_code): """ Get tab for given object and tab code :param model_alias: :param object: Object used to render tab :param tab_code: Tab code to use :return: """ model_alias = self.get_model_alias(model_alias) ...
[ "def", "get_tab", "(", "self", ",", "model_alias", ",", "object", ",", "tab_code", ")", ":", "model_alias", "=", "self", ".", "get_model_alias", "(", "model_alias", ")", "for", "item", "in", "self", ".", "tabs", "[", "model_alias", "]", ":", "if", "item"...
Get tab for given object and tab code :param model_alias: :param object: Object used to render tab :param tab_code: Tab code to use :return:
[ "Get", "tab", "for", "given", "object", "and", "tab", "code" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L223-L236
krukas/Trionyx
trionyx/navigation.py
TabRegister.register
def register(self, model_alias, code='general', name=None, order=None, display_filter=None): """ Register new tab :param model_alias: :param code: :param name: :param order: :return: """ model_alias = self.get_model_alias(model_alias) def...
python
def register(self, model_alias, code='general', name=None, order=None, display_filter=None): """ Register new tab :param model_alias: :param code: :param name: :param order: :return: """ model_alias = self.get_model_alias(model_alias) def...
[ "def", "register", "(", "self", ",", "model_alias", ",", "code", "=", "'general'", ",", "name", "=", "None", ",", "order", "=", "None", ",", "display_filter", "=", "None", ")", ":", "model_alias", "=", "self", ".", "get_model_alias", "(", "model_alias", ...
Register new tab :param model_alias: :param code: :param name: :param order: :return:
[ "Register", "new", "tab" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L238-L266
krukas/Trionyx
trionyx/navigation.py
TabRegister.register_update
def register_update(self, model_alias, code): """ Register tab update function, function is being called with (layout, object) :param model_alias: :param code: :return: """ model_alias = self.get_model_alias(model_alias) def wrapper(update_layout): ...
python
def register_update(self, model_alias, code): """ Register tab update function, function is being called with (layout, object) :param model_alias: :param code: :return: """ model_alias = self.get_model_alias(model_alias) def wrapper(update_layout): ...
[ "def", "register_update", "(", "self", ",", "model_alias", ",", "code", ")", ":", "model_alias", "=", "self", ".", "get_model_alias", "(", "model_alias", ")", "def", "wrapper", "(", "update_layout", ")", ":", "for", "item", "in", "self", ".", "tabs", "[", ...
Register tab update function, function is being called with (layout, object) :param model_alias: :param code: :return:
[ "Register", "tab", "update", "function", "function", "is", "being", "called", "with", "(", "layout", "object", ")" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L268-L283
krukas/Trionyx
trionyx/navigation.py
TabRegister.update
def update(self, model_alias, code='general', name=None, order=None, display_filter=None): """ Update given tab :param model_alias: :param code: :param name: :param order: :param display_filter: :return: """ model_alias = self.get_model_al...
python
def update(self, model_alias, code='general', name=None, order=None, display_filter=None): """ Update given tab :param model_alias: :param code: :param name: :param order: :param display_filter: :return: """ model_alias = self.get_model_al...
[ "def", "update", "(", "self", ",", "model_alias", ",", "code", "=", "'general'", ",", "name", "=", "None", ",", "order", "=", "None", ",", "display_filter", "=", "None", ")", ":", "model_alias", "=", "self", ".", "get_model_alias", "(", "model_alias", ")...
Update given tab :param model_alias: :param code: :param name: :param order: :param display_filter: :return:
[ "Update", "given", "tab" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L285-L307
krukas/Trionyx
trionyx/navigation.py
TabRegister.get_model_alias
def get_model_alias(self, model_alias): """Get model alias if class then convert to alias string""" from trionyx.models import BaseModel if inspect.isclass(model_alias) and issubclass(model_alias, BaseModel): config = models_config.get_config(model_alias) return '{}.{}'.f...
python
def get_model_alias(self, model_alias): """Get model alias if class then convert to alias string""" from trionyx.models import BaseModel if inspect.isclass(model_alias) and issubclass(model_alias, BaseModel): config = models_config.get_config(model_alias) return '{}.{}'.f...
[ "def", "get_model_alias", "(", "self", ",", "model_alias", ")", ":", "from", "trionyx", ".", "models", "import", "BaseModel", "if", "inspect", ".", "isclass", "(", "model_alias", ")", "and", "issubclass", "(", "model_alias", ",", "BaseModel", ")", ":", "conf...
Get model alias if class then convert to alias string
[ "Get", "model", "alias", "if", "class", "then", "convert", "to", "alias", "string" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L309-L315
krukas/Trionyx
trionyx/navigation.py
TabRegister.auto_generate_missing_tabs
def auto_generate_missing_tabs(self): """Auto generate tabs for models with no tabs""" for config in models_config.get_all_configs(): model_alias = '{}.{}'.format(config.app_label, config.model_name) if model_alias not in self.tabs: @self.register(model_alias) ...
python
def auto_generate_missing_tabs(self): """Auto generate tabs for models with no tabs""" for config in models_config.get_all_configs(): model_alias = '{}.{}'.format(config.app_label, config.model_name) if model_alias not in self.tabs: @self.register(model_alias) ...
[ "def", "auto_generate_missing_tabs", "(", "self", ")", ":", "for", "config", "in", "models_config", ".", "get_all_configs", "(", ")", ":", "model_alias", "=", "'{}.{}'", ".", "format", "(", "config", ".", "app_label", ",", "config", ".", "model_name", ")", "...
Auto generate tabs for models with no tabs
[ "Auto", "generate", "tabs", "for", "models", "with", "no", "tabs" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L317-L331
krukas/Trionyx
trionyx/navigation.py
TabItem.name
def name(self): """Give back tab name if is set else generate name by code""" if self._name: return self._name return self.code.replace('_', ' ').capitalize()
python
def name(self): """Give back tab name if is set else generate name by code""" if self._name: return self._name return self.code.replace('_', ' ').capitalize()
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "_name", ":", "return", "self", ".", "_name", "return", "self", ".", "code", ".", "replace", "(", "'_'", ",", "' '", ")", ".", "capitalize", "(", ")" ]
Give back tab name if is set else generate name by code
[ "Give", "back", "tab", "name", "if", "is", "set", "else", "generate", "name", "by", "code" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L348-L352
krukas/Trionyx
trionyx/navigation.py
TabItem.get_layout
def get_layout(self, object): """Get complete layout for given object""" layout = self.create_layout(object) if isinstance(layout, Component): layout = Layout(layout) if isinstance(layout, list): layout = Layout(*layout) for update_layout in self.layout_...
python
def get_layout(self, object): """Get complete layout for given object""" layout = self.create_layout(object) if isinstance(layout, Component): layout = Layout(layout) if isinstance(layout, list): layout = Layout(*layout) for update_layout in self.layout_...
[ "def", "get_layout", "(", "self", ",", "object", ")", ":", "layout", "=", "self", ".", "create_layout", "(", "object", ")", "if", "isinstance", "(", "layout", ",", "Component", ")", ":", "layout", "=", "Layout", "(", "layout", ")", "if", "isinstance", ...
Get complete layout for given object
[ "Get", "complete", "layout", "for", "given", "object" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L359-L371
wbonnet/mnemonic-checker
mnemonic_checker/__main__.py
main
def main(): """ Main entry point for the script. Create a parser, process the command line, and run it """ parser = cli.Cli() parser.parse(sys.argv[1:]) return parser.run()
python
def main(): """ Main entry point for the script. Create a parser, process the command line, and run it """ parser = cli.Cli() parser.parse(sys.argv[1:]) return parser.run()
[ "def", "main", "(", ")", ":", "parser", "=", "cli", ".", "Cli", "(", ")", "parser", ".", "parse", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "return", "parser", ".", "run", "(", ")" ]
Main entry point for the script. Create a parser, process the command line, and run it
[ "Main", "entry", "point", "for", "the", "script", ".", "Create", "a", "parser", "process", "the", "command", "line", "and", "run", "it" ]
train
https://github.com/wbonnet/mnemonic-checker/blob/cec3f25b447c111f4d31fabcaee89af7977cafd8/mnemonic_checker/__main__.py#L26-L33
MacHu-GWU/angora-project
angora/gadget/backup.py
run_backup
def run_backup(filename, root_dir, ignore=[], ignore_ext=[], ignore_pattern=[]): """The backup utility method. :param root_dir: the directory you want to backup :param ignore: file or directory defined in this list will be ignored. :param ignore_ext: file with extensions defined in this list will be ig...
python
def run_backup(filename, root_dir, ignore=[], ignore_ext=[], ignore_pattern=[]): """The backup utility method. :param root_dir: the directory you want to backup :param ignore: file or directory defined in this list will be ignored. :param ignore_ext: file with extensions defined in this list will be ig...
[ "def", "run_backup", "(", "filename", ",", "root_dir", ",", "ignore", "=", "[", "]", ",", "ignore_ext", "=", "[", "]", ",", "ignore_pattern", "=", "[", "]", ")", ":", "tab", "=", "\" \"", "# Step 1, calculate files to backup", "print", "(", "\"Perform backu...
The backup utility method. :param root_dir: the directory you want to backup :param ignore: file or directory defined in this list will be ignored. :param ignore_ext: file with extensions defined in this list will be ignored. :param ignore_pattern: any file or directory that contains this pattern ...
[ "The", "backup", "utility", "method", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/backup.py#L75-L117
wtsi-hgi/python-baton-wrapper
baton/models.py
User.create_from_str
def create_from_str(name_and_zone: str): """ Factory method for creating a user from a string in the form `name#zone`. :param name_and_zone: the user's name followed by hash followed by the user's zone :return: the created user """ if _NAME_ZONE_SEGREGATOR not in name_and...
python
def create_from_str(name_and_zone: str): """ Factory method for creating a user from a string in the form `name#zone`. :param name_and_zone: the user's name followed by hash followed by the user's zone :return: the created user """ if _NAME_ZONE_SEGREGATOR not in name_and...
[ "def", "create_from_str", "(", "name_and_zone", ":", "str", ")", ":", "if", "_NAME_ZONE_SEGREGATOR", "not", "in", "name_and_zone", ":", "raise", "ValueError", "(", "\"User's zone not set\"", ")", "name", ",", "zone", "=", "name_and_zone", ".", "split", "(", "_NA...
Factory method for creating a user from a string in the form `name#zone`. :param name_and_zone: the user's name followed by hash followed by the user's zone :return: the created user
[ "Factory", "method", "for", "creating", "a", "user", "from", "a", "string", "in", "the", "form", "name#zone", ".", ":", "param", "name_and_zone", ":", "the", "user", "s", "name", "followed", "by", "hash", "followed", "by", "the", "user", "s", "zone", ":"...
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/models.py#L44-L57
wtsi-hgi/python-baton-wrapper
baton/models.py
IrodsEntity.access_controls
def access_controls(self, access_controls: Optional[Iterable[AccessControl]]): """ Sets the access controls associated to this entity. :param access_controls: the access controls (immutable) or `None` """ if access_controls is not None: access_controls = set(access_co...
python
def access_controls(self, access_controls: Optional[Iterable[AccessControl]]): """ Sets the access controls associated to this entity. :param access_controls: the access controls (immutable) or `None` """ if access_controls is not None: access_controls = set(access_co...
[ "def", "access_controls", "(", "self", ",", "access_controls", ":", "Optional", "[", "Iterable", "[", "AccessControl", "]", "]", ")", ":", "if", "access_controls", "is", "not", "None", ":", "access_controls", "=", "set", "(", "access_controls", ")", "self", ...
Sets the access controls associated to this entity. :param access_controls: the access controls (immutable) or `None`
[ "Sets", "the", "access", "controls", "associated", "to", "this", "entity", ".", ":", "param", "access_controls", ":", "the", "access", "controls", "(", "immutable", ")", "or", "None" ]
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/models.py#L141-L148
ddorn/pyconfiglib
configlib/prompting.py
prompt_file
def prompt_file(prompt, default=None): """Prompt a file name with autocompletion""" def complete(text: str, state): text = text.replace('~', HOME) sugg = (glob.glob(text + '*') + [None])[state] if sugg is None: return sugg = sugg.replace(HOME, '~') sugg = ...
python
def prompt_file(prompt, default=None): """Prompt a file name with autocompletion""" def complete(text: str, state): text = text.replace('~', HOME) sugg = (glob.glob(text + '*') + [None])[state] if sugg is None: return sugg = sugg.replace(HOME, '~') sugg = ...
[ "def", "prompt_file", "(", "prompt", ",", "default", "=", "None", ")", ":", "def", "complete", "(", "text", ":", "str", ",", "state", ")", ":", "text", "=", "text", ".", "replace", "(", "'~'", ",", "HOME", ")", "sugg", "=", "(", "glob", ".", "glo...
Prompt a file name with autocompletion
[ "Prompt", "a", "file", "name", "with", "autocompletion" ]
train
https://github.com/ddorn/pyconfiglib/blob/3ad01d0bb9344e18719d82a5928b4d8e5fe726ac/configlib/prompting.py#L9-L42
Vito2015/pyextend
pyextend/core/math.py
isprime
def isprime(n): """Check the number is prime value. if prime value returns True, not False.""" 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 ** ...
python
def isprime(n): """Check the number is prime value. if prime value returns True, not False.""" 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 ** ...
[ "def", "isprime", "(", "n", ")", ":", "n", "=", "abs", "(", "int", "(", "n", ")", ")", "if", "n", "<", "2", ":", "return", "False", "if", "n", "==", "2", ":", "return", "True", "if", "not", "n", "&", "1", ":", "return", "False", "# 在一般领域, 对正整...
Check the number is prime value. if prime value returns True, not False.
[ "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
mattupstate/cubric
cubric/contrib/servers/ubuntu/default/__init__.py
WsgiApplicationContext.create
def create(self): """Create an application context on the server""" self.before_create() puts(green('Creating app context')) tdir = os.path.dirname(__file__) # Ensure the app context user exists user_ensure(self.user, home='/home/' + self.user) dir_ensure('/hom...
python
def create(self): """Create an application context on the server""" self.before_create() puts(green('Creating app context')) tdir = os.path.dirname(__file__) # Ensure the app context user exists user_ensure(self.user, home='/home/' + self.user) dir_ensure('/hom...
[ "def", "create", "(", "self", ")", ":", "self", ".", "before_create", "(", ")", "puts", "(", "green", "(", "'Creating app context'", ")", ")", "tdir", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "# Ensure the app context user exists", "user...
Create an application context on the server
[ "Create", "an", "application", "context", "on", "the", "server" ]
train
https://github.com/mattupstate/cubric/blob/a648ce00e4467cd14d71e754240ef6c1f87a34b5/cubric/contrib/servers/ubuntu/default/__init__.py#L246-L291
mattupstate/cubric
cubric/contrib/servers/ubuntu/default/__init__.py
WsgiApplicationContext.upload_release
def upload_release(self): """Upload an application bundle to the server for a given context""" self.before_upload_release() with settings(user=self.user): with app_bundle(): local_bundle = env.local_bundle env.bundle = '/tmp/' + os.path.basename(local...
python
def upload_release(self): """Upload an application bundle to the server for a given context""" self.before_upload_release() with settings(user=self.user): with app_bundle(): local_bundle = env.local_bundle env.bundle = '/tmp/' + os.path.basename(local...
[ "def", "upload_release", "(", "self", ")", ":", "self", ".", "before_upload_release", "(", ")", "with", "settings", "(", "user", "=", "self", ".", "user", ")", ":", "with", "app_bundle", "(", ")", ":", "local_bundle", "=", "env", ".", "local_bundle", "en...
Upload an application bundle to the server for a given context
[ "Upload", "an", "application", "bundle", "to", "the", "server", "for", "a", "given", "context" ]
train
https://github.com/mattupstate/cubric/blob/a648ce00e4467cd14d71e754240ef6c1f87a34b5/cubric/contrib/servers/ubuntu/default/__init__.py#L299-L337
Rhathe/fixtureupper
fixtureupper/model.py
ModelFixtureUpper._print_breakdown
def _print_breakdown(cls, savedir, fname, data): """Function to print model fixtures into generated file""" if not os.path.exists(savedir): os.makedirs(savedir) with open(os.path.join(savedir, fname), 'w') as fout: fout.write(data)
python
def _print_breakdown(cls, savedir, fname, data): """Function to print model fixtures into generated file""" if not os.path.exists(savedir): os.makedirs(savedir) with open(os.path.join(savedir, fname), 'w') as fout: fout.write(data)
[ "def", "_print_breakdown", "(", "cls", ",", "savedir", ",", "fname", ",", "data", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "savedir", ")", ":", "os", ".", "makedirs", "(", "savedir", ")", "with", "open", "(", "os", ".", "path",...
Function to print model fixtures into generated file
[ "Function", "to", "print", "model", "fixtures", "into", "generated", "file" ]
train
https://github.com/Rhathe/fixtureupper/blob/f8d6f95b5f5f38963f2389f4183d1c9884184853/fixtureupper/model.py#L137-L143
Rhathe/fixtureupper
fixtureupper/model.py
ModelFixtureUpper.read_json_breakdown
def read_json_breakdown(cls, fname): """Read json file to get fixture data""" if not os.path.exists(fname): raise RuntimeError with open(fname, 'r') as data_file: return cls.fixup_from_json(data_file.read())
python
def read_json_breakdown(cls, fname): """Read json file to get fixture data""" if not os.path.exists(fname): raise RuntimeError with open(fname, 'r') as data_file: return cls.fixup_from_json(data_file.read())
[ "def", "read_json_breakdown", "(", "cls", ",", "fname", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "raise", "RuntimeError", "with", "open", "(", "fname", ",", "'r'", ")", "as", "data_file", ":", "return", "cls", ...
Read json file to get fixture data
[ "Read", "json", "file", "to", "get", "fixture", "data" ]
train
https://github.com/Rhathe/fixtureupper/blob/f8d6f95b5f5f38963f2389f4183d1c9884184853/fixtureupper/model.py#L226-L232
CitrineInformatics/dftparse
dftparse/wien2k/refract_parser.py
_parse_refraction
def _parse_refraction(line, lines): """Parse Energy [eV] ref_ind_xx ref_ind_zz extinct_xx extinct_zz""" split_line = line.split() energy = float(split_line[0]) ref_ind_xx = float(split_line[1]) ref_ind_zz = float(split_line[2]) extinct_xx = float(split_line[3]) extinct_zz = float(...
python
def _parse_refraction(line, lines): """Parse Energy [eV] ref_ind_xx ref_ind_zz extinct_xx extinct_zz""" split_line = line.split() energy = float(split_line[0]) ref_ind_xx = float(split_line[1]) ref_ind_zz = float(split_line[2]) extinct_xx = float(split_line[3]) extinct_zz = float(...
[ "def", "_parse_refraction", "(", "line", ",", "lines", ")", ":", "split_line", "=", "line", ".", "split", "(", ")", "energy", "=", "float", "(", "split_line", "[", "0", "]", ")", "ref_ind_xx", "=", "float", "(", "split_line", "[", "1", "]", ")", "ref...
Parse Energy [eV] ref_ind_xx ref_ind_zz extinct_xx extinct_zz
[ "Parse", "Energy", "[", "eV", "]", "ref_ind_xx", "ref_ind_zz", "extinct_xx", "extinct_zz" ]
train
https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/wien2k/refract_parser.py#L4-L15
phenicle/pgdbpy
pgdbpy/tools.py
PgDbPy.execute
def execute(self, fetchcommand, sql, params=None): """ where 'fetchcommand' is either 'fetchone' or 'fetchall' """ cur = self.conn.cursor() if params: if not type(params).__name__ == 'tuple': raise ValueError('the params argument needs to be a tuple') return None cur.execute(sql, params) else: ...
python
def execute(self, fetchcommand, sql, params=None): """ where 'fetchcommand' is either 'fetchone' or 'fetchall' """ cur = self.conn.cursor() if params: if not type(params).__name__ == 'tuple': raise ValueError('the params argument needs to be a tuple') return None cur.execute(sql, params) else: ...
[ "def", "execute", "(", "self", ",", "fetchcommand", ",", "sql", ",", "params", "=", "None", ")", ":", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "if", "params", ":", "if", "not", "type", "(", "params", ")", ".", "__name__", "==", "...
where 'fetchcommand' is either 'fetchone' or 'fetchall'
[ "where", "fetchcommand", "is", "either", "fetchone", "or", "fetchall" ]
train
https://github.com/phenicle/pgdbpy/blob/0b4cc8825006f8ce620f693c4bd9b8b74312d9e8/pgdbpy/tools.py#L136-L174
scivision/histutils
histutils/cp_parents.py
cp_parents
def cp_parents(files, target_dir: Union[str, Path]): """ This function requires Python >= 3.6. This acts like bash cp --parents in Python inspiration from http://stackoverflow.com/questions/15329223/copy-a-file-into-a-directory-with-its-original-leading-directories-appended example source:...
python
def cp_parents(files, target_dir: Union[str, Path]): """ This function requires Python >= 3.6. This acts like bash cp --parents in Python inspiration from http://stackoverflow.com/questions/15329223/copy-a-file-into-a-directory-with-its-original-leading-directories-appended example source:...
[ "def", "cp_parents", "(", "files", ",", "target_dir", ":", "Union", "[", "str", ",", "Path", "]", ")", ":", "# %% make list if it's a string", "if", "isinstance", "(", "files", ",", "(", "str", ",", "Path", ")", ")", ":", "files", "=", "[", "files", "]...
This function requires Python >= 3.6. This acts like bash cp --parents in Python inspiration from http://stackoverflow.com/questions/15329223/copy-a-file-into-a-directory-with-its-original-leading-directories-appended example source: /tmp/e/f dest: /tmp/a/b/c/d/ result: /tmp/a/b/c/d/tmp/e/...
[ "This", "function", "requires", "Python", ">", "=", "3", ".", "6", "." ]
train
https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/cp_parents.py#L7-L35
kevinsprong23/aperture
aperture/set_plot_params.py
set_plot_params
def set_plot_params(theme=None): """ set plot parameters for session, as an alternative to manipulating RC file """ # set solarized color progression no matter what mpl.rcParams['axes.color_cycle'] = ('268bd2, dc322f, 859900, ' + 'b58900, d33682, 2aa19...
python
def set_plot_params(theme=None): """ set plot parameters for session, as an alternative to manipulating RC file """ # set solarized color progression no matter what mpl.rcParams['axes.color_cycle'] = ('268bd2, dc322f, 859900, ' + 'b58900, d33682, 2aa19...
[ "def", "set_plot_params", "(", "theme", "=", "None", ")", ":", "# set solarized color progression no matter what", "mpl", ".", "rcParams", "[", "'axes.color_cycle'", "]", "=", "(", "'268bd2, dc322f, 859900, '", "+", "'b58900, d33682, 2aa198, '", "+", "'cb4b16, 002b36'", "...
set plot parameters for session, as an alternative to manipulating RC file
[ "set", "plot", "parameters", "for", "session", "as", "an", "alternative", "to", "manipulating", "RC", "file" ]
train
https://github.com/kevinsprong23/aperture/blob/d0420fef3b25d8afc0e5ddcfb6fe5f0ff42b9799/aperture/set_plot_params.py#L7-L64
Basic-Components/msgpack-rpc-protocol
python/pymprpc/errors.py
add_status_code
def add_status_code(code): """用于将mprpc的标准异常注册到`_mprpc_exceptions`的装饰器. Parameters: code (int): - 标准状态码 Return: (Callable): - 装饰函数 """ def class_decorator(cls): """内部装饰函数,用于将异常类注册到对应的状态码. Parameters: cls (Callable): - 要注册的异常类 Return: ...
python
def add_status_code(code): """用于将mprpc的标准异常注册到`_mprpc_exceptions`的装饰器. Parameters: code (int): - 标准状态码 Return: (Callable): - 装饰函数 """ def class_decorator(cls): """内部装饰函数,用于将异常类注册到对应的状态码. Parameters: cls (Callable): - 要注册的异常类 Return: ...
[ "def", "add_status_code", "(", "code", ")", ":", "def", "class_decorator", "(", "cls", ")", ":", "\"\"\"内部装饰函数,用于将异常类注册到对应的状态码.\n\n Parameters:\n cls (Callable): - 要注册的异常类\n Return:\n (Callable): - 注册的异常类\n\n \"\"\"", "cls", ".", "status_code"...
用于将mprpc的标准异常注册到`_mprpc_exceptions`的装饰器. Parameters: code (int): - 标准状态码 Return: (Callable): - 装饰函数
[ "用于将mprpc的标准异常注册到", "_mprpc_exceptions", "的装饰器", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/errors.py#L19-L41
Basic-Components/msgpack-rpc-protocol
python/pymprpc/errors.py
abort
def abort(status_code: int, ID: str=None, exception: str="", message: str=None): """根据状态码创建一个异常. Parameters: status_code (int): - 错误的状态码 ID (str): - 任务的ID号,通常是一个uuid,默认为None,服务错误不需要ID,方法调用错误需要ID exception (): - 错误的异常栈信息,默认为None,服务错误不需要,方法调用错误可以需要 me...
python
def abort(status_code: int, ID: str=None, exception: str="", message: str=None): """根据状态码创建一个异常. Parameters: status_code (int): - 错误的状态码 ID (str): - 任务的ID号,通常是一个uuid,默认为None,服务错误不需要ID,方法调用错误需要ID exception (): - 错误的异常栈信息,默认为None,服务错误不需要,方法调用错误可以需要 me...
[ "def", "abort", "(", "status_code", ":", "int", ",", "ID", ":", "str", "=", "None", ",", "exception", ":", "str", "=", "\"\"", ",", "message", ":", "str", "=", "None", ")", ":", "if", "message", "is", "None", ":", "message", "=", "STATUS_CODES", "....
根据状态码创建一个异常. Parameters: status_code (int): - 错误的状态码 ID (str): - 任务的ID号,通常是一个uuid,默认为None,服务错误不需要ID,方法调用错误需要ID exception (): - 错误的异常栈信息,默认为None,服务错误不需要,方法调用错误可以需要 message (str): - 错误信息 Return: (MprpcException): - 指定错误码对应的mprpc标准异常
[ "根据状态码创建一个异常", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/errors.py#L222-L252
rsalmaso/django-fluo
fluo/management/commands/load_admin_data.py
Command.handle
def handle(self, *args, **options): """Load a default admin user""" try: admin = User.objects.get(username='admin') except User.DoesNotExist: admin = User( username='admin', first_name='admin', last_name='admin', ...
python
def handle(self, *args, **options): """Load a default admin user""" try: admin = User.objects.get(username='admin') except User.DoesNotExist: admin = User( username='admin', first_name='admin', last_name='admin', ...
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "try", ":", "admin", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "'admin'", ")", "except", "User", ".", "DoesNotExist", ":", "admin", "=", "User"...
Load a default admin user
[ "Load", "a", "default", "admin", "user" ]
train
https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/management/commands/load_admin_data.py#L30-L45
ErikBjare/pyzenobase
examples/upload_battery_data_csv/main.py
upload_batterystats
def upload_batterystats(filename, username, password, bucket_name=BUCKET_NAME, bucket_desc=BUCKET_DESC): """ Works with CSVs generated by the Android app 'Battery Log' (https://play.google.com/store/apps/details?id=kr.hwangti.batterylog) """ zapi = pyzenobase.ZenobaseAPI(username, password) buc...
python
def upload_batterystats(filename, username, password, bucket_name=BUCKET_NAME, bucket_desc=BUCKET_DESC): """ Works with CSVs generated by the Android app 'Battery Log' (https://play.google.com/store/apps/details?id=kr.hwangti.batterylog) """ zapi = pyzenobase.ZenobaseAPI(username, password) buc...
[ "def", "upload_batterystats", "(", "filename", ",", "username", ",", "password", ",", "bucket_name", "=", "BUCKET_NAME", ",", "bucket_desc", "=", "BUCKET_DESC", ")", ":", "zapi", "=", "pyzenobase", ".", "ZenobaseAPI", "(", "username", ",", "password", ")", "bu...
Works with CSVs generated by the Android app 'Battery Log' (https://play.google.com/store/apps/details?id=kr.hwangti.batterylog)
[ "Works", "with", "CSVs", "generated", "by", "the", "Android", "app", "Battery", "Log", "(", "https", ":", "//", "play", ".", "google", ".", "com", "/", "store", "/", "apps", "/", "details?id", "=", "kr", ".", "hwangti", ".", "batterylog", ")" ]
train
https://github.com/ErikBjare/pyzenobase/blob/eb0572c7441a350bf5578bc5287f3be53d32ea19/examples/upload_battery_data_csv/main.py#L12-L42
EnigmaBridge/client.py
ebclient/crypto_util.py
to_bytes
def to_bytes(x, blocksize=0): """ Converts input to a byte string. Typically used in PyCrypto as an argument (e.g., key, iv) :param x: string (does nothing), bytearray, array with numbers :return: """ if isinstance(x, bytearray): return left_zero_pad(bytes(x), blocksize) elif is...
python
def to_bytes(x, blocksize=0): """ Converts input to a byte string. Typically used in PyCrypto as an argument (e.g., key, iv) :param x: string (does nothing), bytearray, array with numbers :return: """ if isinstance(x, bytearray): return left_zero_pad(bytes(x), blocksize) elif is...
[ "def", "to_bytes", "(", "x", ",", "blocksize", "=", "0", ")", ":", "if", "isinstance", "(", "x", ",", "bytearray", ")", ":", "return", "left_zero_pad", "(", "bytes", "(", "x", ")", ",", "blocksize", ")", "elif", "isinstance", "(", "x", ",", "basestri...
Converts input to a byte string. Typically used in PyCrypto as an argument (e.g., key, iv) :param x: string (does nothing), bytearray, array with numbers :return:
[ "Converts", "input", "to", "a", "byte", "string", ".", "Typically", "used", "in", "PyCrypto", "as", "an", "argument", "(", "e", ".", "g", ".", "key", "iv", ")" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L38-L55
EnigmaBridge/client.py
ebclient/crypto_util.py
to_long
def to_long(x): """ Converts input to a long number (arbitrary precision python long) :param x: :return: """ if isinstance(x, long): return x elif isinstance(x, int): return long(x) else: return bytes_to_long(to_bytes(x))
python
def to_long(x): """ Converts input to a long number (arbitrary precision python long) :param x: :return: """ if isinstance(x, long): return x elif isinstance(x, int): return long(x) else: return bytes_to_long(to_bytes(x))
[ "def", "to_long", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "long", ")", ":", "return", "x", "elif", "isinstance", "(", "x", ",", "int", ")", ":", "return", "long", "(", "x", ")", "else", ":", "return", "bytes_to_long", "(", "to_bytes"...
Converts input to a long number (arbitrary precision python long) :param x: :return:
[ "Converts", "input", "to", "a", "long", "number", "(", "arbitrary", "precision", "python", "long", ")", ":", "param", "x", ":", ":", "return", ":" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L58-L69
EnigmaBridge/client.py
ebclient/crypto_util.py
to_hex
def to_hex(x): """ Converts input to the hex string :param x: :return: """ if isinstance(x, bytearray): x = bytes(x) elif isinstance(x, (list, tuple)): x = bytes(bytearray(x)) if isinstance(x, basestring): return base64.b16encode(x).decode('ascii') else: ...
python
def to_hex(x): """ Converts input to the hex string :param x: :return: """ if isinstance(x, bytearray): x = bytes(x) elif isinstance(x, (list, tuple)): x = bytes(bytearray(x)) if isinstance(x, basestring): return base64.b16encode(x).decode('ascii') else: ...
[ "def", "to_hex", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "bytearray", ")", ":", "x", "=", "bytes", "(", "x", ")", "elif", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "x", "=", "bytes", "(", "bytearray",...
Converts input to the hex string :param x: :return:
[ "Converts", "input", "to", "the", "hex", "string", ":", "param", "x", ":", ":", "return", ":" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L86-L99
EnigmaBridge/client.py
ebclient/crypto_util.py
left_zero_pad
def left_zero_pad(s, blocksize): """ Left padding with zero bytes to a given block size :param s: :param blocksize: :return: """ if blocksize > 0 and len(s) % blocksize: s = (blocksize - len(s) % blocksize) * b('\000') + s return s
python
def left_zero_pad(s, blocksize): """ Left padding with zero bytes to a given block size :param s: :param blocksize: :return: """ if blocksize > 0 and len(s) % blocksize: s = (blocksize - len(s) % blocksize) * b('\000') + s return s
[ "def", "left_zero_pad", "(", "s", ",", "blocksize", ")", ":", "if", "blocksize", ">", "0", "and", "len", "(", "s", ")", "%", "blocksize", ":", "s", "=", "(", "blocksize", "-", "len", "(", "s", ")", "%", "blocksize", ")", "*", "b", "(", "'\\000'",...
Left padding with zero bytes to a given block size :param s: :param blocksize: :return:
[ "Left", "padding", "with", "zero", "bytes", "to", "a", "given", "block", "size" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L129-L139
EnigmaBridge/client.py
ebclient/crypto_util.py
str_equals
def str_equals(a, b): """ Constant time string equals method - no time leakage :param a: :param b: :return: """ al = len(a) bl = len(b) match = True for i in xrange(0, min(al, bl)): match &= a[i] == b[i] return match
python
def str_equals(a, b): """ Constant time string equals method - no time leakage :param a: :param b: :return: """ al = len(a) bl = len(b) match = True for i in xrange(0, min(al, bl)): match &= a[i] == b[i] return match
[ "def", "str_equals", "(", "a", ",", "b", ")", ":", "al", "=", "len", "(", "a", ")", "bl", "=", "len", "(", "b", ")", "match", "=", "True", "for", "i", "in", "xrange", "(", "0", ",", "min", "(", "al", ",", "bl", ")", ")", ":", "match", "&=...
Constant time string equals method - no time leakage :param a: :param b: :return:
[ "Constant", "time", "string", "equals", "method", "-", "no", "time", "leakage", ":", "param", "a", ":", ":", "param", "b", ":", ":", "return", ":" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L142-L154
EnigmaBridge/client.py
ebclient/crypto_util.py
bytes_replace
def bytes_replace(byte_str, start_idx, stop_idx, replacement): """ Replaces given portion of the byte string with the replacement, returns new array :param byte_str: :param start_idx: :param stop_idx: :param replacement: :return: """ return byte_str[:start_idx] + replacement + byte_s...
python
def bytes_replace(byte_str, start_idx, stop_idx, replacement): """ Replaces given portion of the byte string with the replacement, returns new array :param byte_str: :param start_idx: :param stop_idx: :param replacement: :return: """ return byte_str[:start_idx] + replacement + byte_s...
[ "def", "bytes_replace", "(", "byte_str", ",", "start_idx", ",", "stop_idx", ",", "replacement", ")", ":", "return", "byte_str", "[", ":", "start_idx", "]", "+", "replacement", "+", "byte_str", "[", "stop_idx", ":", "]" ]
Replaces given portion of the byte string with the replacement, returns new array :param byte_str: :param start_idx: :param stop_idx: :param replacement: :return:
[ "Replaces", "given", "portion", "of", "the", "byte", "string", "with", "the", "replacement", "returns", "new", "array", ":", "param", "byte_str", ":", ":", "param", "start_idx", ":", ":", "param", "stop_idx", ":", ":", "param", "replacement", ":", ":", "re...
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L157-L166
EnigmaBridge/client.py
ebclient/crypto_util.py
bytes_transform
def bytes_transform(byte_str, start_idx, stop_idx, fction): """ Takes portion of the byte array and passes it to the function for transformation. Result is replaced in the byte string, new one is created. :param byte_str: :param start_idx: :param stop_idx: :param fction: :return: """...
python
def bytes_transform(byte_str, start_idx, stop_idx, fction): """ Takes portion of the byte array and passes it to the function for transformation. Result is replaced in the byte string, new one is created. :param byte_str: :param start_idx: :param stop_idx: :param fction: :return: """...
[ "def", "bytes_transform", "(", "byte_str", ",", "start_idx", ",", "stop_idx", ",", "fction", ")", ":", "return", "bytes_replace", "(", "byte_str", ",", "start_idx", ",", "stop_idx", ",", "fction", "(", "byte_str", "[", "start_idx", ":", "stop_idx", "]", ")",...
Takes portion of the byte array and passes it to the function for transformation. Result is replaced in the byte string, new one is created. :param byte_str: :param start_idx: :param stop_idx: :param fction: :return:
[ "Takes", "portion", "of", "the", "byte", "array", "and", "passes", "it", "to", "the", "function", "for", "transformation", ".", "Result", "is", "replaced", "in", "the", "byte", "string", "new", "one", "is", "created", ".", ":", "param", "byte_str", ":", ...
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L169-L179
EnigmaBridge/client.py
ebclient/crypto_util.py
get_random_integer
def get_random_integer(N, randfunc=None): """getRandomInteger(N:int, randfunc:callable):long Return a random number with at most N bits. If randfunc is omitted, then Random.new().read is used. This function is for internal use only and may be renamed or removed in the future. """ if randfu...
python
def get_random_integer(N, randfunc=None): """getRandomInteger(N:int, randfunc:callable):long Return a random number with at most N bits. If randfunc is omitted, then Random.new().read is used. This function is for internal use only and may be renamed or removed in the future. """ if randfu...
[ "def", "get_random_integer", "(", "N", ",", "randfunc", "=", "None", ")", ":", "if", "randfunc", "is", "None", ":", "randfunc", "=", "Random", ".", "new", "(", ")", ".", "read", "S", "=", "randfunc", "(", "N", ">>", "3", ")", "odd_bits", "=", "N", ...
getRandomInteger(N:int, randfunc:callable):long Return a random number with at most N bits. If randfunc is omitted, then Random.new().read is used. This function is for internal use only and may be renamed or removed in the future.
[ "getRandomInteger", "(", "N", ":", "int", "randfunc", ":", "callable", ")", ":", "long", "Return", "a", "random", "number", "with", "at", "most", "N", "bits", "." ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L208-L226
EnigmaBridge/client.py
ebclient/crypto_util.py
get_random_range
def get_random_range(a, b, randfunc=None): """getRandomRange(a:int, b:int, randfunc:callable):long Return a random number n so that a <= n < b. If randfunc is omitted, then Random.new().read is used. This function is for internal use only and may be renamed or removed in the future. """ ra...
python
def get_random_range(a, b, randfunc=None): """getRandomRange(a:int, b:int, randfunc:callable):long Return a random number n so that a <= n < b. If randfunc is omitted, then Random.new().read is used. This function is for internal use only and may be renamed or removed in the future. """ ra...
[ "def", "get_random_range", "(", "a", ",", "b", ",", "randfunc", "=", "None", ")", ":", "range_", "=", "b", "-", "a", "-", "1", "bits", "=", "size", "(", "range_", ")", "value", "=", "get_random_integer", "(", "bits", ",", "randfunc", ")", "while", ...
getRandomRange(a:int, b:int, randfunc:callable):long Return a random number n so that a <= n < b. If randfunc is omitted, then Random.new().read is used. This function is for internal use only and may be renamed or removed in the future.
[ "getRandomRange", "(", "a", ":", "int", "b", ":", "int", "randfunc", ":", "callable", ")", ":", "long", "Return", "a", "random", "number", "n", "so", "that", "a", "<", "=", "n", "<", "b", "." ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L229-L243
EnigmaBridge/client.py
ebclient/crypto_util.py
aes
def aes(encrypt, key, data): """ One-pass AES-256-CBC used in ProcessData. Zero IV (don't panic, IV-like random nonce is included in plaintext in the first block in ProcessData). Does not use padding (data has to be already padded). :param encrypt: :param key: :param data: :return: ...
python
def aes(encrypt, key, data): """ One-pass AES-256-CBC used in ProcessData. Zero IV (don't panic, IV-like random nonce is included in plaintext in the first block in ProcessData). Does not use padding (data has to be already padded). :param encrypt: :param key: :param data: :return: ...
[ "def", "aes", "(", "encrypt", ",", "key", ",", "data", ")", ":", "cipher", "=", "AES", ".", "new", "(", "key", ",", "AES", ".", "MODE_CBC", ",", "get_zero_vector", "(", "16", ")", ")", "if", "encrypt", ":", "return", "cipher", ".", "encrypt", "(", ...
One-pass AES-256-CBC used in ProcessData. Zero IV (don't panic, IV-like random nonce is included in plaintext in the first block in ProcessData). Does not use padding (data has to be already padded). :param encrypt: :param key: :param data: :return:
[ "One", "-", "pass", "AES", "-", "256", "-", "CBC", "used", "in", "ProcessData", ".", "Zero", "IV", "(", "don", "t", "panic", "IV", "-", "like", "random", "nonce", "is", "included", "in", "plaintext", "in", "the", "first", "block", "in", "ProcessData", ...
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L350-L366
EnigmaBridge/client.py
ebclient/crypto_util.py
cbc_mac
def cbc_mac(key, data): """ AES-265-CBC-MAC on the data used in ProcessData. Does not use padding (data has to be already padded). :param key: :param data: :return: """ engine = AES.new(key, AES.MODE_CBC, get_zero_vector(16)) return engine.encrypt(data)[-16:]
python
def cbc_mac(key, data): """ AES-265-CBC-MAC on the data used in ProcessData. Does not use padding (data has to be already padded). :param key: :param data: :return: """ engine = AES.new(key, AES.MODE_CBC, get_zero_vector(16)) return engine.encrypt(data)[-16:]
[ "def", "cbc_mac", "(", "key", ",", "data", ")", ":", "engine", "=", "AES", ".", "new", "(", "key", ",", "AES", ".", "MODE_CBC", ",", "get_zero_vector", "(", "16", ")", ")", "return", "engine", ".", "encrypt", "(", "data", ")", "[", "-", "16", ":"...
AES-265-CBC-MAC on the data used in ProcessData. Does not use padding (data has to be already padded). :param key: :param data: :return:
[ "AES", "-", "265", "-", "CBC", "-", "MAC", "on", "the", "data", "used", "in", "ProcessData", ".", "Does", "not", "use", "padding", "(", "data", "has", "to", "be", "already", "padded", ")", "." ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L377-L387
EnigmaBridge/client.py
ebclient/crypto_util.py
rsa_enc
def rsa_enc(data, modulus, exponent): """ Simple RAW RSA encryption method, returns byte string. Returns byte string of the same size as the modulus (left padded with 0) :param data: :param modulus: :param exponent: :return: """ modulus = to_long(modulus) exponent = to_long(expo...
python
def rsa_enc(data, modulus, exponent): """ Simple RAW RSA encryption method, returns byte string. Returns byte string of the same size as the modulus (left padded with 0) :param data: :param modulus: :param exponent: :return: """ modulus = to_long(modulus) exponent = to_long(expo...
[ "def", "rsa_enc", "(", "data", ",", "modulus", ",", "exponent", ")", ":", "modulus", "=", "to_long", "(", "modulus", ")", "exponent", "=", "to_long", "(", "exponent", ")", "data", "=", "to_long", "(", "data", ")", "return", "long_to_bytes", "(", "pow", ...
Simple RAW RSA encryption method, returns byte string. Returns byte string of the same size as the modulus (left padded with 0) :param data: :param modulus: :param exponent: :return:
[ "Simple", "RAW", "RSA", "encryption", "method", "returns", "byte", "string", ".", "Returns", "byte", "string", "of", "the", "same", "size", "as", "the", "modulus", "(", "left", "padded", "with", "0", ")" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L390-L404
inveniosoftware-contrib/record-recommender
record_recommender/fetcher.py
_is_bot
def _is_bot(user_agent): """Check if user_agent is a known bot.""" bot_list = [ 'http://www.baidu.com/search/spider.html', 'python-requests', 'http://ltx71.com/', 'http://drupal.org/', 'www.sogou.com', 'http://search...
python
def _is_bot(user_agent): """Check if user_agent is a known bot.""" bot_list = [ 'http://www.baidu.com/search/spider.html', 'python-requests', 'http://ltx71.com/', 'http://drupal.org/', 'www.sogou.com', 'http://search...
[ "def", "_is_bot", "(", "user_agent", ")", ":", "bot_list", "=", "[", "'http://www.baidu.com/search/spider.html'", ",", "'python-requests'", ",", "'http://ltx71.com/'", ",", "'http://drupal.org/'", ",", "'www.sogou.com'", ",", "'http://search.msn.com/msnbot.htm'", ",", "'sem...
Check if user_agent is a known bot.
[ "Check", "if", "user_agent", "is", "a", "known", "bot", "." ]
train
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/fetcher.py#L316-L330
inveniosoftware-contrib/record-recommender
record_recommender/fetcher.py
_is_download
def _is_download(ending): """Check if file ending is considered as download.""" list = [ 'PDF', 'DOC', 'TXT', 'PPT', 'XLSX', 'MP3', 'SVG', '7Z', 'HTML', 'TEX', 'MPP', '...
python
def _is_download(ending): """Check if file ending is considered as download.""" list = [ 'PDF', 'DOC', 'TXT', 'PPT', 'XLSX', 'MP3', 'SVG', '7Z', 'HTML', 'TEX', 'MPP', '...
[ "def", "_is_download", "(", "ending", ")", ":", "list", "=", "[", "'PDF'", ",", "'DOC'", ",", "'TXT'", ",", "'PPT'", ",", "'XLSX'", ",", "'MP3'", ",", "'SVG'", ",", "'7Z'", ",", "'HTML'", ",", "'TEX'", ",", "'MPP'", ",", "'ODT'", ",", "'RAR'", ",",...
Check if file ending is considered as download.
[ "Check", "if", "file", "ending", "is", "considered", "as", "download", "." ]
train
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/fetcher.py#L333-L361
inveniosoftware-contrib/record-recommender
record_recommender/fetcher.py
ElasticsearchFetcher.fetch
def fetch(self, year, week, overwrite=False): """Fetch PageViews and Downloads from Elasticsearch.""" self.config['overwrite_files'] = overwrite time_start = time.time() self._fetch_pageviews(self.storage, year, week, ip_users=False) self._fetch_downloads(self.storage, year, week...
python
def fetch(self, year, week, overwrite=False): """Fetch PageViews and Downloads from Elasticsearch.""" self.config['overwrite_files'] = overwrite time_start = time.time() self._fetch_pageviews(self.storage, year, week, ip_users=False) self._fetch_downloads(self.storage, year, week...
[ "def", "fetch", "(", "self", ",", "year", ",", "week", ",", "overwrite", "=", "False", ")", ":", "self", ".", "config", "[", "'overwrite_files'", "]", "=", "overwrite", "time_start", "=", "time", ".", "time", "(", ")", "self", ".", "_fetch_pageviews", ...
Fetch PageViews and Downloads from Elasticsearch.
[ "Fetch", "PageViews", "and", "Downloads", "from", "Elasticsearch", "." ]
train
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/fetcher.py#L93-L103
inveniosoftware-contrib/record-recommender
record_recommender/fetcher.py
ElasticsearchFetcher._fetch_pageviews
def _fetch_pageviews(self, storage, year, week, ip_users=False): """ Fetch PageViews from Elasticsearch. :param time_from: Staring at timestamp. :param time_to: To timestamp """ prefix = 'Pageviews' if ip_users: query_add = "AND !(bot:True) AND (id_us...
python
def _fetch_pageviews(self, storage, year, week, ip_users=False): """ Fetch PageViews from Elasticsearch. :param time_from: Staring at timestamp. :param time_to: To timestamp """ prefix = 'Pageviews' if ip_users: query_add = "AND !(bot:True) AND (id_us...
[ "def", "_fetch_pageviews", "(", "self", ",", "storage", ",", "year", ",", "week", ",", "ip_users", "=", "False", ")", ":", "prefix", "=", "'Pageviews'", "if", "ip_users", ":", "query_add", "=", "\"AND !(bot:True) AND (id_user:0)\"", "prefix", "+=", "'_IP'", "e...
Fetch PageViews from Elasticsearch. :param time_from: Staring at timestamp. :param time_to: To timestamp
[ "Fetch", "PageViews", "from", "Elasticsearch", "." ]
train
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/fetcher.py#L105-L165
inveniosoftware-contrib/record-recommender
record_recommender/fetcher.py
ElasticsearchFetcher._fetch_elasticsearch
def _fetch_elasticsearch(self, es_query): """ Load data from Elasticsearch. :param query: TODO :param time_from: TODO :param time_to: TODO :returns: TODO """ # TODO: Show error if index is not found. scanResp = self._esd.search(index=self.config['...
python
def _fetch_elasticsearch(self, es_query): """ Load data from Elasticsearch. :param query: TODO :param time_from: TODO :param time_to: TODO :returns: TODO """ # TODO: Show error if index is not found. scanResp = self._esd.search(index=self.config['...
[ "def", "_fetch_elasticsearch", "(", "self", ",", "es_query", ")", ":", "# TODO: Show error if index is not found.", "scanResp", "=", "self", ".", "_esd", ".", "search", "(", "index", "=", "self", ".", "config", "[", "'es_index'", "]", ",", "body", "=", "es_que...
Load data from Elasticsearch. :param query: TODO :param time_from: TODO :param time_to: TODO :returns: TODO
[ "Load", "data", "from", "Elasticsearch", "." ]
train
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/fetcher.py#L247-L313
diffeo/rejester
rejester/_queue.py
RejesterQueue.dump_queue
def dump_queue(self, *names): """Debug-log some of the queues. ``names`` may include any of "worker", "available", "priorities", "expiration", "workers", or "reservations_ITEM" filling in some specific item. """ conn = redis.StrictRedis(connection_pool=self.pool) ...
python
def dump_queue(self, *names): """Debug-log some of the queues. ``names`` may include any of "worker", "available", "priorities", "expiration", "workers", or "reservations_ITEM" filling in some specific item. """ conn = redis.StrictRedis(connection_pool=self.pool) ...
[ "def", "dump_queue", "(", "self", ",", "*", "names", ")", ":", "conn", "=", "redis", ".", "StrictRedis", "(", "connection_pool", "=", "self", ".", "pool", ")", "for", "name", "in", "names", ":", "if", "name", "==", "'worker'", ":", "logger", ".", "de...
Debug-log some of the queues. ``names`` may include any of "worker", "available", "priorities", "expiration", "workers", or "reservations_ITEM" filling in some specific item.
[ "Debug", "-", "log", "some", "of", "the", "queues", "." ]
train
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L91-L120
diffeo/rejester
rejester/_queue.py
RejesterQueue.worker_id
def worker_id(self): """A unique identifier for this queue instance and the items it owns.""" if self._worker_id is not None: return self._worker_id return self._get_worker_id(self._conn())
python
def worker_id(self): """A unique identifier for this queue instance and the items it owns.""" if self._worker_id is not None: return self._worker_id return self._get_worker_id(self._conn())
[ "def", "worker_id", "(", "self", ")", ":", "if", "self", ".", "_worker_id", "is", "not", "None", ":", "return", "self", ".", "_worker_id", "return", "self", ".", "_get_worker_id", "(", "self", ".", "_conn", "(", ")", ")" ]
A unique identifier for this queue instance and the items it owns.
[ "A", "unique", "identifier", "for", "this", "queue", "instance", "and", "the", "items", "it", "owns", "." ]
train
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L123-L126
diffeo/rejester
rejester/_queue.py
RejesterQueue._get_worker_id
def _get_worker_id(self, conn): """Get the worker ID, using a preestablished connection.""" if self._worker_id is None: self._worker_id = conn.incr(self._key_worker()) return self._worker_id
python
def _get_worker_id(self, conn): """Get the worker ID, using a preestablished connection.""" if self._worker_id is None: self._worker_id = conn.incr(self._key_worker()) return self._worker_id
[ "def", "_get_worker_id", "(", "self", ",", "conn", ")", ":", "if", "self", ".", "_worker_id", "is", "None", ":", "self", ".", "_worker_id", "=", "conn", ".", "incr", "(", "self", ".", "_key_worker", "(", ")", ")", "return", "self", ".", "_worker_id" ]
Get the worker ID, using a preestablished connection.
[ "Get", "the", "worker", "ID", "using", "a", "preestablished", "connection", "." ]
train
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L137-L141
diffeo/rejester
rejester/_queue.py
RejesterQueue.add_item
def add_item(self, item, priority): """Add ``item`` to this queue. It will have the specified ``priority`` (highest priority runs first). If it is already in the queue, fail if it is checked out or reserved, or change its priority to ``priority`` otherwise. """ ...
python
def add_item(self, item, priority): """Add ``item`` to this queue. It will have the specified ``priority`` (highest priority runs first). If it is already in the queue, fail if it is checked out or reserved, or change its priority to ``priority`` otherwise. """ ...
[ "def", "add_item", "(", "self", ",", "item", ",", "priority", ")", ":", "conn", "=", "self", ".", "_conn", "(", ")", "self", ".", "_run_expiration", "(", "conn", ")", "script", "=", "conn", ".", "register_script", "(", "\"\"\"\n if (redis.call(\"hexis...
Add ``item`` to this queue. It will have the specified ``priority`` (highest priority runs first). If it is already in the queue, fail if it is checked out or reserved, or change its priority to ``priority`` otherwise.
[ "Add", "item", "to", "this", "queue", "." ]
train
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L143-L168
diffeo/rejester
rejester/_queue.py
RejesterQueue.check_out_item
def check_out_item(self, expiration): """Get the highest-priority item out of this queue. Returns the item, or None if no items are available. The item must be either ``return_item()`` or ``renew_item()`` before ``expiration`` seconds pass, or it will become available to future...
python
def check_out_item(self, expiration): """Get the highest-priority item out of this queue. Returns the item, or None if no items are available. The item must be either ``return_item()`` or ``renew_item()`` before ``expiration`` seconds pass, or it will become available to future...
[ "def", "check_out_item", "(", "self", ",", "expiration", ")", ":", "conn", "=", "redis", ".", "StrictRedis", "(", "connection_pool", "=", "self", ".", "pool", ")", "self", ".", "_run_expiration", "(", "conn", ")", "expiration", "+=", "time", ".", "time", ...
Get the highest-priority item out of this queue. Returns the item, or None if no items are available. The item must be either ``return_item()`` or ``renew_item()`` before ``expiration`` seconds pass, or it will become available to future callers. The item will be marked as being owned...
[ "Get", "the", "highest", "-", "priority", "item", "out", "of", "this", "queue", "." ]
train
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L170-L196
diffeo/rejester
rejester/_queue.py
RejesterQueue.renew_item
def renew_item(self, item, expiration): """Update the expiration time for ``item``. The item will remain checked out for ``expiration`` seconds beyond the current time. This queue instance must have already checked out ``item``, and this method can fail if ``item`` is already o...
python
def renew_item(self, item, expiration): """Update the expiration time for ``item``. The item will remain checked out for ``expiration`` seconds beyond the current time. This queue instance must have already checked out ``item``, and this method can fail if ``item`` is already o...
[ "def", "renew_item", "(", "self", ",", "item", ",", "expiration", ")", ":", "conn", "=", "self", ".", "_conn", "(", ")", "self", ".", "_run_expiration", "(", "conn", ")", "expiration", "+=", "time", ".", "time", "(", ")", "script", "=", "conn", ".", ...
Update the expiration time for ``item``. The item will remain checked out for ``expiration`` seconds beyond the current time. This queue instance must have already checked out ``item``, and this method can fail if ``item`` is already overdue.
[ "Update", "the", "expiration", "time", "for", "item", "." ]
train
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L198-L223
diffeo/rejester
rejester/_queue.py
RejesterQueue.return_item
def return_item(self, item, priority): """Complete work on an item from ``check_out_item()``. If this instance no longer owns ``item``, raise ``LostLease``. If ``priority`` is None, the item is removed from the queue; otherwise it is re-added with the specified priority. Any lo...
python
def return_item(self, item, priority): """Complete work on an item from ``check_out_item()``. If this instance no longer owns ``item``, raise ``LostLease``. If ``priority`` is None, the item is removed from the queue; otherwise it is re-added with the specified priority. Any lo...
[ "def", "return_item", "(", "self", ",", "item", ",", "priority", ")", ":", "conn", "=", "redis", ".", "StrictRedis", "(", "connection_pool", "=", "self", ".", "pool", ")", "self", ".", "_run_expiration", "(", "conn", ")", "script", "=", "conn", ".", "r...
Complete work on an item from ``check_out_item()``. If this instance no longer owns ``item``, raise ``LostLease``. If ``priority`` is None, the item is removed from the queue; otherwise it is re-added with the specified priority. Any locked items associated with this item are unlocked.
[ "Complete", "work", "on", "an", "item", "from", "check_out_item", "()", "." ]
train
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L225-L271
diffeo/rejester
rejester/_queue.py
RejesterQueue.reserve_items
def reserve_items(self, parent_item, *items): """Reserve a set of items until a parent item is returned. Prevent ``check_out_item()`` from returning any of ``items`` until ``parent_item`` is completed or times out. For each item, if it is not already checked out or reserved by some ...
python
def reserve_items(self, parent_item, *items): """Reserve a set of items until a parent item is returned. Prevent ``check_out_item()`` from returning any of ``items`` until ``parent_item`` is completed or times out. For each item, if it is not already checked out or reserved by some ...
[ "def", "reserve_items", "(", "self", ",", "parent_item", ",", "*", "items", ")", ":", "conn", "=", "redis", ".", "StrictRedis", "(", "connection_pool", "=", "self", ".", "pool", ")", "self", ".", "_run_expiration", "(", "conn", ")", "script", "=", "conn"...
Reserve a set of items until a parent item is returned. Prevent ``check_out_item()`` from returning any of ``items`` until ``parent_item`` is completed or times out. For each item, if it is not already checked out or reserved by some other parent item, it is associated with ``parent_it...
[ "Reserve", "a", "set", "of", "items", "until", "a", "parent", "item", "is", "returned", "." ]
train
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L273-L315
diffeo/rejester
rejester/_queue.py
RejesterQueue._run_expiration
def _run_expiration(self, conn): """Return any items that have expired.""" # The logic here is sufficiently complicated, and we need # enough random keys (Redis documentation strongly encourages # not constructing key names in scripts) that we'll need to # do this in multiple ste...
python
def _run_expiration(self, conn): """Return any items that have expired.""" # The logic here is sufficiently complicated, and we need # enough random keys (Redis documentation strongly encourages # not constructing key names in scripts) that we'll need to # do this in multiple ste...
[ "def", "_run_expiration", "(", "self", ",", "conn", ")", ":", "# The logic here is sufficiently complicated, and we need", "# enough random keys (Redis documentation strongly encourages", "# not constructing key names in scripts) that we'll need to", "# do this in multiple steps. This means t...
Return any items that have expired.
[ "Return", "any", "items", "that", "have", "expired", "." ]
train
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L317-L357
mayfield/shellish
shellish/paging.py
pager_redirect
def pager_redirect(desc, *, pagercmd=None, istty=None, file=None, substitutions=None): """ Redirect output to file/stdout to a pager process. Care is taken to restore the controlling tty stdio files to their original state. """ global _pager_active if file is None: file = sys...
python
def pager_redirect(desc, *, pagercmd=None, istty=None, file=None, substitutions=None): """ Redirect output to file/stdout to a pager process. Care is taken to restore the controlling tty stdio files to their original state. """ global _pager_active if file is None: file = sys...
[ "def", "pager_redirect", "(", "desc", ",", "*", ",", "pagercmd", "=", "None", ",", "istty", "=", "None", ",", "file", "=", "None", ",", "substitutions", "=", "None", ")", ":", "global", "_pager_active", "if", "file", "is", "None", ":", "file", "=", "...
Redirect output to file/stdout to a pager process. Care is taken to restore the controlling tty stdio files to their original state.
[ "Redirect", "output", "to", "file", "/", "stdout", "to", "a", "pager", "process", ".", "Care", "is", "taken", "to", "restore", "the", "controlling", "tty", "stdio", "files", "to", "their", "original", "state", "." ]
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/paging.py#L53-L89
zacernst/timed_dict
timed_dict/timed_dict.py
cleanup_sweep_threads
def cleanup_sweep_threads(): ''' Not used. Keeping this function in case we decide not to use daemonized threads and it becomes necessary to clean up the running threads upon exit. ''' for dict_name, obj in globals().items(): if isinstance(obj, (TimedDict,)): logging.info( ...
python
def cleanup_sweep_threads(): ''' Not used. Keeping this function in case we decide not to use daemonized threads and it becomes necessary to clean up the running threads upon exit. ''' for dict_name, obj in globals().items(): if isinstance(obj, (TimedDict,)): logging.info( ...
[ "def", "cleanup_sweep_threads", "(", ")", ":", "for", "dict_name", ",", "obj", "in", "globals", "(", ")", ".", "items", "(", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "TimedDict", ",", ")", ")", ":", "logging", ".", "info", "(", "'Stopping ...
Not used. Keeping this function in case we decide not to use daemonized threads and it becomes necessary to clean up the running threads upon exit.
[ "Not", "used", ".", "Keeping", "this", "function", "in", "case", "we", "decide", "not", "to", "use", "daemonized", "threads", "and", "it", "becomes", "necessary", "to", "clean", "up", "the", "running", "threads", "upon", "exit", "." ]
train
https://github.com/zacernst/timed_dict/blob/01a1d145d246832e63c2e92e11d91cac5c3f2d1e/timed_dict/timed_dict.py#L343-L355
zacernst/timed_dict
timed_dict/timed_dict.py
TimedDict.set_expiration
def set_expiration(self, key, ignore_missing=False, additional_seconds=None, seconds=None): ''' Alters the expiration time for a key. If the key is not present, then raise an Exception unless `ignore_missing` is set to `True`. Args: key: The key whose exp...
python
def set_expiration(self, key, ignore_missing=False, additional_seconds=None, seconds=None): ''' Alters the expiration time for a key. If the key is not present, then raise an Exception unless `ignore_missing` is set to `True`. Args: key: The key whose exp...
[ "def", "set_expiration", "(", "self", ",", "key", ",", "ignore_missing", "=", "False", ",", "additional_seconds", "=", "None", ",", "seconds", "=", "None", ")", ":", "if", "key", "not", "in", "self", ".", "time_dict", "and", "ignore_missing", ":", "return"...
Alters the expiration time for a key. If the key is not present, then raise an Exception unless `ignore_missing` is set to `True`. Args: key: The key whose expiration we are changing. ignore_missing (bool): If set, then return silently if the key does not...
[ "Alters", "the", "expiration", "time", "for", "a", "key", ".", "If", "the", "key", "is", "not", "present", "then", "raise", "an", "Exception", "unless", "ignore_missing", "is", "set", "to", "True", "." ]
train
https://github.com/zacernst/timed_dict/blob/01a1d145d246832e63c2e92e11d91cac5c3f2d1e/timed_dict/timed_dict.py#L198-L221
zacernst/timed_dict
timed_dict/timed_dict.py
TimedDict.sweep
def sweep(self): ''' This methods runs in a separate thread. So long as `self.sweep_flag` is set, it expires keys according to the process explained in the docstring for the `TimedDict` class. The thread is halted by calling `self.stop_sweep()`, which sets the `self.sweep...
python
def sweep(self): ''' This methods runs in a separate thread. So long as `self.sweep_flag` is set, it expires keys according to the process explained in the docstring for the `TimedDict` class. The thread is halted by calling `self.stop_sweep()`, which sets the `self.sweep...
[ "def", "sweep", "(", "self", ")", ":", "while", "self", ".", "sweep_flag", ":", "current_time", "=", "time", ".", "time", "(", ")", "expire_keys", "=", "set", "(", ")", "keys_checked", "=", "0.", "items", "=", "list", "(", "self", ".", "time_dict", "...
This methods runs in a separate thread. So long as `self.sweep_flag` is set, it expires keys according to the process explained in the docstring for the `TimedDict` class. The thread is halted by calling `self.stop_sweep()`, which sets the `self.sweep_flag` to `False`.
[ "This", "methods", "runs", "in", "a", "separate", "thread", ".", "So", "long", "as", "self", ".", "sweep_flag", "is", "set", "it", "expires", "keys", "according", "to", "the", "process", "explained", "in", "the", "docstring", "for", "the", "TimedDict", "cl...
train
https://github.com/zacernst/timed_dict/blob/01a1d145d246832e63c2e92e11d91cac5c3f2d1e/timed_dict/timed_dict.py#L287-L316
zacernst/timed_dict
timed_dict/timed_dict.py
TimedDict.expire_key
def expire_key(self, key): ''' Expire the key, delete the value, and call the callback function if one is specified. Args: key: The ``TimedDict`` key ''' value = self.base_dict[key] del self[key] if self.callback is not None: self....
python
def expire_key(self, key): ''' Expire the key, delete the value, and call the callback function if one is specified. Args: key: The ``TimedDict`` key ''' value = self.base_dict[key] del self[key] if self.callback is not None: self....
[ "def", "expire_key", "(", "self", ",", "key", ")", ":", "value", "=", "self", ".", "base_dict", "[", "key", "]", "del", "self", "[", "key", "]", "if", "self", ".", "callback", "is", "not", "None", ":", "self", ".", "callback", "(", "key", ",", "v...
Expire the key, delete the value, and call the callback function if one is specified. Args: key: The ``TimedDict`` key
[ "Expire", "the", "key", "delete", "the", "value", "and", "call", "the", "callback", "function", "if", "one", "is", "specified", "." ]
train
https://github.com/zacernst/timed_dict/blob/01a1d145d246832e63c2e92e11d91cac5c3f2d1e/timed_dict/timed_dict.py#L318-L330
pavelsof/ipalint
ipalint/read.py
Reader._save_stdin
def _save_stdin(self, stdin): """ Creates a temporary dir (self.temp_dir) and saves the given input stream to a file within that dir. Returns the path to the file. The dir is removed in the __del__ method. """ self.temp_dir = TemporaryDirectory() file_path = os.path.join(self.temp_dir.name, 'dataset') ...
python
def _save_stdin(self, stdin): """ Creates a temporary dir (self.temp_dir) and saves the given input stream to a file within that dir. Returns the path to the file. The dir is removed in the __del__ method. """ self.temp_dir = TemporaryDirectory() file_path = os.path.join(self.temp_dir.name, 'dataset') ...
[ "def", "_save_stdin", "(", "self", ",", "stdin", ")", ":", "self", ".", "temp_dir", "=", "TemporaryDirectory", "(", ")", "file_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "temp_dir", ".", "name", ",", "'dataset'", ")", "try", ":", "...
Creates a temporary dir (self.temp_dir) and saves the given input stream to a file within that dir. Returns the path to the file. The dir is removed in the __del__ method.
[ "Creates", "a", "temporary", "dir", "(", "self", ".", "temp_dir", ")", "and", "saves", "the", "given", "input", "stream", "to", "a", "file", "within", "that", "dir", ".", "Returns", "the", "path", "to", "the", "file", ".", "The", "dir", "is", "removed"...
train
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/read.py#L96-L113
pavelsof/ipalint
ipalint/read.py
Reader._open
def _open(self, file_path=None): """ Opens the file specified by the given path. Raises ValueError if there is a problem with opening or reading the file. """ if file_path is None: file_path = self.file_path if not os.path.exists(file_path): raise ValueError('Could not find file: {}'.format(file_path...
python
def _open(self, file_path=None): """ Opens the file specified by the given path. Raises ValueError if there is a problem with opening or reading the file. """ if file_path is None: file_path = self.file_path if not os.path.exists(file_path): raise ValueError('Could not find file: {}'.format(file_path...
[ "def", "_open", "(", "self", ",", "file_path", "=", "None", ")", ":", "if", "file_path", "is", "None", ":", "file_path", "=", "self", ".", "file_path", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "raise", "ValueError", ...
Opens the file specified by the given path. Raises ValueError if there is a problem with opening or reading the file.
[ "Opens", "the", "file", "specified", "by", "the", "given", "path", ".", "Raises", "ValueError", "if", "there", "is", "a", "problem", "with", "opening", "or", "reading", "the", "file", "." ]
train
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/read.py#L116-L133
pavelsof/ipalint
ipalint/read.py
Reader.get_dialect
def get_dialect(self): """ Returns a Dialect named tuple or None if the dataset file comprises a single column of data. If the dialect is not already known, then tries to determine it. Raises ValueError if it fails in the latter case. """ if self.is_single_col: return None if self.delimiter and self.q...
python
def get_dialect(self): """ Returns a Dialect named tuple or None if the dataset file comprises a single column of data. If the dialect is not already known, then tries to determine it. Raises ValueError if it fails in the latter case. """ if self.is_single_col: return None if self.delimiter and self.q...
[ "def", "get_dialect", "(", "self", ")", ":", "if", "self", ".", "is_single_col", ":", "return", "None", "if", "self", ".", "delimiter", "and", "self", ".", "quotechar", ":", "return", "Dialect", "(", "self", ".", "delimiter", ",", "self", ".", "quotechar...
Returns a Dialect named tuple or None if the dataset file comprises a single column of data. If the dialect is not already known, then tries to determine it. Raises ValueError if it fails in the latter case.
[ "Returns", "a", "Dialect", "named", "tuple", "or", "None", "if", "the", "dataset", "file", "comprises", "a", "single", "column", "of", "data", ".", "If", "the", "dialect", "is", "not", "already", "known", "then", "tries", "to", "determine", "it", ".", "R...
train
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/read.py#L136-L174
pavelsof/ipalint
ipalint/read.py
Reader._determine_dialect
def _determine_dialect(self, lines): """ Expects a non-empty [] of strings; these would normally be the first few lines of a csv file. Returns the most likely Dialect named tuple or None if the data seems to form a single column. Ensures that using the returned dialect, all the lines given will have the sa...
python
def _determine_dialect(self, lines): """ Expects a non-empty [] of strings; these would normally be the first few lines of a csv file. Returns the most likely Dialect named tuple or None if the data seems to form a single column. Ensures that using the returned dialect, all the lines given will have the sa...
[ "def", "_determine_dialect", "(", "self", ",", "lines", ")", ":", "permuts", "=", "[", "(", "quotechar", ",", "escapechar", ")", "for", "quotechar", "in", "CSV_QUOTECHARS", "for", "escapechar", "in", "CSV_ESCAPECHARS", "]", "for", "delim", "in", "CSV_DELIMITER...
Expects a non-empty [] of strings; these would normally be the first few lines of a csv file. Returns the most likely Dialect named tuple or None if the data seems to form a single column. Ensures that using the returned dialect, all the lines given will have the same number of columns. Helper for the get_d...
[ "Expects", "a", "non", "-", "empty", "[]", "of", "strings", ";", "these", "would", "normally", "be", "the", "first", "few", "lines", "of", "a", "csv", "file", ".", "Returns", "the", "most", "likely", "Dialect", "named", "tuple", "or", "None", "if", "th...
train
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/read.py#L177-L218
pavelsof/ipalint
ipalint/read.py
Reader._get_csv_reader
def _get_csv_reader(self, f, dialect): """ Returns a csv.reader for the given file handler and csv Dialect named tuple. If the file has a header, it already will be gone through. Also, if self.ipa_col is not set, an attempt will be made to infer which the IPA column is. ValueError would be raised otherwise. ...
python
def _get_csv_reader(self, f, dialect): """ Returns a csv.reader for the given file handler and csv Dialect named tuple. If the file has a header, it already will be gone through. Also, if self.ipa_col is not set, an attempt will be made to infer which the IPA column is. ValueError would be raised otherwise. ...
[ "def", "_get_csv_reader", "(", "self", ",", "f", ",", "dialect", ")", ":", "reader", "=", "csv", ".", "reader", "(", "f", ",", "delimiter", "=", "dialect", ".", "delimiter", ",", "quotechar", "=", "dialect", ".", "quotechar", ",", "doublequote", "=", "...
Returns a csv.reader for the given file handler and csv Dialect named tuple. If the file has a header, it already will be gone through. Also, if self.ipa_col is not set, an attempt will be made to infer which the IPA column is. ValueError would be raised otherwise.
[ "Returns", "a", "csv", ".", "reader", "for", "the", "given", "file", "handler", "and", "csv", "Dialect", "named", "tuple", ".", "If", "the", "file", "has", "a", "header", "it", "already", "will", "be", "gone", "through", "." ]
train
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/read.py#L221-L250
pavelsof/ipalint
ipalint/read.py
Reader._infer_ipa_col
def _infer_ipa_col(self, header): """ Returns the column (as index) containing the IPA data based on the header (the first line of the data file). Raises ValueError otherwise. If self.ipa_col is a string, it is assumed to be the column's name or index. Otherwise, several common IPA column names are tried. ...
python
def _infer_ipa_col(self, header): """ Returns the column (as index) containing the IPA data based on the header (the first line of the data file). Raises ValueError otherwise. If self.ipa_col is a string, it is assumed to be the column's name or index. Otherwise, several common IPA column names are tried. ...
[ "def", "_infer_ipa_col", "(", "self", ",", "header", ")", ":", "if", "self", ".", "ipa_col", "and", "isinstance", "(", "self", ".", "ipa_col", ",", "str", ")", ":", "if", "self", ".", "ipa_col", "in", "header", ":", "return", "header", ".", "index", ...
Returns the column (as index) containing the IPA data based on the header (the first line of the data file). Raises ValueError otherwise. If self.ipa_col is a string, it is assumed to be the column's name or index. Otherwise, several common IPA column names are tried.
[ "Returns", "the", "column", "(", "as", "index", ")", "containing", "the", "IPA", "data", "based", "on", "the", "header", "(", "the", "first", "line", "of", "the", "data", "file", ")", ".", "Raises", "ValueError", "otherwise", "." ]
train
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/read.py#L253-L286
pavelsof/ipalint
ipalint/read.py
Reader.gen_ipa_data
def gen_ipa_data(self): """ Generator for iterating over the IPA strings found in the dataset file. Yields the IPA data string paired with the respective line number. """ dialect = self.get_dialect() f = self._open() try: if dialect: for res in self._gen_csv_data(f, dialect): yield res els...
python
def gen_ipa_data(self): """ Generator for iterating over the IPA strings found in the dataset file. Yields the IPA data string paired with the respective line number. """ dialect = self.get_dialect() f = self._open() try: if dialect: for res in self._gen_csv_data(f, dialect): yield res els...
[ "def", "gen_ipa_data", "(", "self", ")", ":", "dialect", "=", "self", ".", "get_dialect", "(", ")", "f", "=", "self", ".", "_open", "(", ")", "try", ":", "if", "dialect", ":", "for", "res", "in", "self", ".", "_gen_csv_data", "(", "f", ",", "dialec...
Generator for iterating over the IPA strings found in the dataset file. Yields the IPA data string paired with the respective line number.
[ "Generator", "for", "iterating", "over", "the", "IPA", "strings", "found", "in", "the", "dataset", "file", ".", "Yields", "the", "IPA", "data", "string", "paired", "with", "the", "respective", "line", "number", "." ]
train
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/read.py#L289-L306
pavelsof/ipalint
ipalint/read.py
Reader._gen_csv_data
def _gen_csv_data(self, f, dialect): """ Yields (column data, row number) tuples from the given csv file handler, using the given Dialect named tuple instance. Depends on self.ipa_col being correctly set. Helper for the gen_ipa_data method. """ reader = self._get_csv_reader(f, dialect) for line in rea...
python
def _gen_csv_data(self, f, dialect): """ Yields (column data, row number) tuples from the given csv file handler, using the given Dialect named tuple instance. Depends on self.ipa_col being correctly set. Helper for the gen_ipa_data method. """ reader = self._get_csv_reader(f, dialect) for line in rea...
[ "def", "_gen_csv_data", "(", "self", ",", "f", ",", "dialect", ")", ":", "reader", "=", "self", ".", "_get_csv_reader", "(", "f", ",", "dialect", ")", "for", "line", "in", "reader", ":", "try", ":", "datum", "=", "line", "[", "self", ".", "ipa_col", ...
Yields (column data, row number) tuples from the given csv file handler, using the given Dialect named tuple instance. Depends on self.ipa_col being correctly set. Helper for the gen_ipa_data method.
[ "Yields", "(", "column", "data", "row", "number", ")", "tuples", "from", "the", "given", "csv", "file", "handler", "using", "the", "given", "Dialect", "named", "tuple", "instance", ".", "Depends", "on", "self", ".", "ipa_col", "being", "correctly", "set", ...
train
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/read.py#L309-L326
pavelsof/ipalint
ipalint/read.py
Reader._gen_txt_data
def _gen_txt_data(self, f): """ Yields (line, line number) tuples from the given file handler. Skips the first line if the self.has_header flag is set. Helper for the gen_ipa_data method. """ reader = iter(f) for line_num, line in enumerate(reader): if line_num == 0 and self.has_header: continue ...
python
def _gen_txt_data(self, f): """ Yields (line, line number) tuples from the given file handler. Skips the first line if the self.has_header flag is set. Helper for the gen_ipa_data method. """ reader = iter(f) for line_num, line in enumerate(reader): if line_num == 0 and self.has_header: continue ...
[ "def", "_gen_txt_data", "(", "self", ",", "f", ")", ":", "reader", "=", "iter", "(", "f", ")", "for", "line_num", ",", "line", "in", "enumerate", "(", "reader", ")", ":", "if", "line_num", "==", "0", "and", "self", ".", "has_header", ":", "continue",...
Yields (line, line number) tuples from the given file handler. Skips the first line if the self.has_header flag is set. Helper for the gen_ipa_data method.
[ "Yields", "(", "line", "line", "number", ")", "tuples", "from", "the", "given", "file", "handler", ".", "Skips", "the", "first", "line", "if", "the", "self", ".", "has_header", "flag", "is", "set", "." ]
train
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/read.py#L329-L344
pyros-dev/pyros-common
pyros_interfaces_common/basenode.py
PyrosBase.start
def start(self, timeout=None): """ Startup of the node. :param join: optionally wait for the process to end (default : True) :return: None """ assert super(PyrosBase, self).start(timeout=timeout) # Because we currently use this to setup connection return ...
python
def start(self, timeout=None): """ Startup of the node. :param join: optionally wait for the process to end (default : True) :return: None """ assert super(PyrosBase, self).start(timeout=timeout) # Because we currently use this to setup connection return ...
[ "def", "start", "(", "self", ",", "timeout", "=", "None", ")", ":", "assert", "super", "(", "PyrosBase", ",", "self", ")", ".", "start", "(", "timeout", "=", "timeout", ")", "# Because we currently use this to setup connection", "return", "self", ".", "name" ]
Startup of the node. :param join: optionally wait for the process to end (default : True) :return: None
[ "Startup", "of", "the", "node", ".", ":", "param", "join", ":", "optionally", "wait", "for", "the", "process", "to", "end", "(", "default", ":", "True", ")", ":", "return", ":", "None" ]
train
https://github.com/pyros-dev/pyros-common/blob/0709538b8777ec055ea31f59cdca5bebaaabb04e/pyros_interfaces_common/basenode.py#L174-L183
pyros-dev/pyros-common
pyros_interfaces_common/basenode.py
PyrosBase.setup
def setup(self, *args, **kwargs): """ Dynamically reset the interface to expose the services / topics / params whose names are passed as args The interface class can be specified with a module to be dynamically imported :param publishers: :param subscribers: :param servic...
python
def setup(self, *args, **kwargs): """ Dynamically reset the interface to expose the services / topics / params whose names are passed as args The interface class can be specified with a module to be dynamically imported :param publishers: :param subscribers: :param servic...
[ "def", "setup", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#BWCOMPAT", "if", "kwargs", ".", "get", "(", "'topics'", ")", ":", "if", "kwargs", ".", "get", "(", "'publishers'", ")", ":", "kwargs", "[", "'publishers'", "]", "="...
Dynamically reset the interface to expose the services / topics / params whose names are passed as args The interface class can be specified with a module to be dynamically imported :param publishers: :param subscribers: :param services: :param topics: BW COMPAT ONLY ! :p...
[ "Dynamically", "reset", "the", "interface", "to", "expose", "the", "services", "/", "topics", "/", "params", "whose", "names", "are", "passed", "as", "args", "The", "interface", "class", "can", "be", "specified", "with", "a", "module", "to", "be", "dynamical...
train
https://github.com/pyros-dev/pyros-common/blob/0709538b8777ec055ea31f59cdca5bebaaabb04e/pyros_interfaces_common/basenode.py#L186-L232
pyros-dev/pyros-common
pyros_interfaces_common/basenode.py
PyrosBase.child_context
def child_context(self, *args, **kwargs): """ Context setup first in child process, before returning from start() call in parent. Result is passed in as argument of update :return: """ # Now we can extract config values expected_args = { 'services': [...
python
def child_context(self, *args, **kwargs): """ Context setup first in child process, before returning from start() call in parent. Result is passed in as argument of update :return: """ # Now we can extract config values expected_args = { 'services': [...
[ "def", "child_context", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Now we can extract config values", "expected_args", "=", "{", "'services'", ":", "[", "]", ",", "'topics'", ":", "[", "]", ",", "# bwcompat", "'subscribers'", ":", ...
Context setup first in child process, before returning from start() call in parent. Result is passed in as argument of update :return:
[ "Context", "setup", "first", "in", "child", "process", "before", "returning", "from", "start", "()", "call", "in", "parent", ".", "Result", "is", "passed", "in", "as", "argument", "of", "update", ":", "return", ":" ]
train
https://github.com/pyros-dev/pyros-common/blob/0709538b8777ec055ea31f59cdca5bebaaabb04e/pyros_interfaces_common/basenode.py#L235-L268
pyros-dev/pyros-common
pyros_interfaces_common/basenode.py
PyrosBase.shutdown
def shutdown(self, join=True, timeout=None): """ Clean shutdown of the node. :param join: optionally wait for the process to end (default : True) :return: last exitcode from update method """ if self.interface is not None: self.interface.stop() return...
python
def shutdown(self, join=True, timeout=None): """ Clean shutdown of the node. :param join: optionally wait for the process to end (default : True) :return: last exitcode from update method """ if self.interface is not None: self.interface.stop() return...
[ "def", "shutdown", "(", "self", ",", "join", "=", "True", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "interface", "is", "not", "None", ":", "self", ".", "interface", ".", "stop", "(", ")", "return", "super", "(", "PyrosBase", ",", "s...
Clean shutdown of the node. :param join: optionally wait for the process to end (default : True) :return: last exitcode from update method
[ "Clean", "shutdown", "of", "the", "node", ".", ":", "param", "join", ":", "optionally", "wait", "for", "the", "process", "to", "end", "(", "default", ":", "True", ")", ":", "return", ":", "last", "exitcode", "from", "update", "method" ]
train
https://github.com/pyros-dev/pyros-common/blob/0709538b8777ec055ea31f59cdca5bebaaabb04e/pyros_interfaces_common/basenode.py#L270-L279
pyros-dev/pyros-common
pyros_interfaces_common/basenode.py
PyrosBase.update
def update(self, timedelta, *args, **kwargs): """ Update function to call from a looping thread. Note : the interface is lazily constructed here :param timedelta: the time past since the last update call """ # TODO move time management somewhere else... self.last...
python
def update(self, timedelta, *args, **kwargs): """ Update function to call from a looping thread. Note : the interface is lazily constructed here :param timedelta: the time past since the last update call """ # TODO move time management somewhere else... self.last...
[ "def", "update", "(", "self", ",", "timedelta", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# TODO move time management somewhere else...", "self", ".", "last_update", "+=", "timedelta", "# if shutdown we want to bypass the update_interval check", "# if shutting...
Update function to call from a looping thread. Note : the interface is lazily constructed here :param timedelta: the time past since the last update call
[ "Update", "function", "to", "call", "from", "a", "looping", "thread", ".", "Note", ":", "the", "interface", "is", "lazily", "constructed", "here", ":", "param", "timedelta", ":", "the", "time", "past", "since", "the", "last", "update", "call" ]
train
https://github.com/pyros-dev/pyros-common/blob/0709538b8777ec055ea31f59cdca5bebaaabb04e/pyros_interfaces_common/basenode.py#L281-L297
fdb/aufmachen
aufmachen/BeautifulSoup.py
PageElement._findAll
def _findAll(self, name, attrs, text, limit, generator, **kwargs): "Iterates over a generator looking for things that match." if isinstance(name, SoupStrainer): strainer = name # (Possibly) special case some findAll*(...) searches elif text is None and not limit and not attr...
python
def _findAll(self, name, attrs, text, limit, generator, **kwargs): "Iterates over a generator looking for things that match." if isinstance(name, SoupStrainer): strainer = name # (Possibly) special case some findAll*(...) searches elif text is None and not limit and not attr...
[ "def", "_findAll", "(", "self", ",", "name", ",", "attrs", ",", "text", ",", "limit", ",", "generator", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "name", ",", "SoupStrainer", ")", ":", "strainer", "=", "name", "# (Possibly) special case...
Iterates over a generator looking for things that match.
[ "Iterates", "over", "a", "generator", "looking", "for", "things", "that", "match", "." ]
train
https://github.com/fdb/aufmachen/blob/f2986a0cf087ac53969f82b84d872e3f1c6986f4/aufmachen/BeautifulSoup.py#L333-L367
fdb/aufmachen
aufmachen/BeautifulSoup.py
Tag.decompose
def decompose(self): """Recursively destroys the contents of this tree.""" self.extract() if len(self.contents) == 0: return current = self.contents[0] while current is not None: next = current.next if isinstance(current, Tag): ...
python
def decompose(self): """Recursively destroys the contents of this tree.""" self.extract() if len(self.contents) == 0: return current = self.contents[0] while current is not None: next = current.next if isinstance(current, Tag): ...
[ "def", "decompose", "(", "self", ")", ":", "self", ".", "extract", "(", ")", "if", "len", "(", "self", ".", "contents", ")", "==", "0", ":", "return", "current", "=", "self", ".", "contents", "[", "0", "]", "while", "current", "is", "not", "None", ...
Recursively destroys the contents of this tree.
[ "Recursively", "destroys", "the", "contents", "of", "this", "tree", "." ]
train
https://github.com/fdb/aufmachen/blob/f2986a0cf087ac53969f82b84d872e3f1c6986f4/aufmachen/BeautifulSoup.py#L778-L793
fdb/aufmachen
aufmachen/BeautifulSoup.py
BeautifulStoneSoup._smartPop
def _smartPop(self, name): """We need to pop up to the previous tag of this type, unless one of this tag's nesting reset triggers comes between this tag and the previous tag of this type, OR unless this tag is a generic nesting trigger and another generic nesting trigger comes b...
python
def _smartPop(self, name): """We need to pop up to the previous tag of this type, unless one of this tag's nesting reset triggers comes between this tag and the previous tag of this type, OR unless this tag is a generic nesting trigger and another generic nesting trigger comes b...
[ "def", "_smartPop", "(", "self", ",", "name", ")", ":", "nestingResetTriggers", "=", "self", ".", "NESTABLE_TAGS", ".", "get", "(", "name", ")", "isNestable", "=", "nestingResetTriggers", "!=", "None", "isResetNesting", "=", "self", ".", "RESET_NESTING_TAGS", ...
We need to pop up to the previous tag of this type, unless one of this tag's nesting reset triggers comes between this tag and the previous tag of this type, OR unless this tag is a generic nesting trigger and another generic nesting trigger comes between this tag and the previous tag of...
[ "We", "need", "to", "pop", "up", "to", "the", "previous", "tag", "of", "this", "type", "unless", "one", "of", "this", "tag", "s", "nesting", "reset", "triggers", "comes", "between", "this", "tag", "and", "the", "previous", "tag", "of", "this", "type", ...
train
https://github.com/fdb/aufmachen/blob/f2986a0cf087ac53969f82b84d872e3f1c6986f4/aufmachen/BeautifulSoup.py#L1281-L1325
fdb/aufmachen
aufmachen/BeautifulSoup.py
UnicodeDammit._subMSChar
def _subMSChar(self, orig): """Changes a MS smart quote character to an XML or HTML entity.""" sub = self.MS_CHARS.get(orig) if isinstance(sub, tuple): if self.smartQuotesTo == 'xml': sub = '&#x%s;' % sub[1] else: sub = '&%s;' % sub...
python
def _subMSChar(self, orig): """Changes a MS smart quote character to an XML or HTML entity.""" sub = self.MS_CHARS.get(orig) if isinstance(sub, tuple): if self.smartQuotesTo == 'xml': sub = '&#x%s;' % sub[1] else: sub = '&%s;' % sub...
[ "def", "_subMSChar", "(", "self", ",", "orig", ")", ":", "sub", "=", "self", ".", "MS_CHARS", ".", "get", "(", "orig", ")", "if", "isinstance", "(", "sub", ",", "tuple", ")", ":", "if", "self", ".", "smartQuotesTo", "==", "'xml'", ":", "sub", "=", ...
Changes a MS smart quote character to an XML or HTML entity.
[ "Changes", "a", "MS", "smart", "quote", "character", "to", "an", "XML", "or", "HTML", "entity", "." ]
train
https://github.com/fdb/aufmachen/blob/f2986a0cf087ac53969f82b84d872e3f1c6986f4/aufmachen/BeautifulSoup.py#L1800-L1809
mkurnikov/typed-env
typed_env/read_dot_env.py
read_file_values
def read_file_values(env_file, fail_silently=True): """ Borrowed from Honcho. """ env_data = {} try: with open(env_file) as f: content = f.read() except IOError: if fail_silently: logging.error("Could not read file '{0}'".format(env_file)) retu...
python
def read_file_values(env_file, fail_silently=True): """ Borrowed from Honcho. """ env_data = {} try: with open(env_file) as f: content = f.read() except IOError: if fail_silently: logging.error("Could not read file '{0}'".format(env_file)) retu...
[ "def", "read_file_values", "(", "env_file", ",", "fail_silently", "=", "True", ")", ":", "env_data", "=", "{", "}", "try", ":", "with", "open", "(", "env_file", ")", "as", "f", ":", "content", "=", "f", ".", "read", "(", ")", "except", "IOError", ":"...
Borrowed from Honcho.
[ "Borrowed", "from", "Honcho", "." ]
train
https://github.com/mkurnikov/typed-env/blob/d0f3e947f0d5561c9fd1679d6faa9830de24d870/typed_env/read_dot_env.py#L8-L37
edeposit/edeposit.amqp.ltp
src/edeposit/amqp/ltp/fn_composers.py
_get_suffix
def _get_suffix(path): """ Return suffix from `path`. ``/home/xex/somefile.txt`` --> ``txt``. Args: path (str): Full file path. Returns: str: Suffix. Raises: UserWarning: When ``/`` is detected in suffix. """ suffix = os.path.basename(path).split(".")[-1] ...
python
def _get_suffix(path): """ Return suffix from `path`. ``/home/xex/somefile.txt`` --> ``txt``. Args: path (str): Full file path. Returns: str: Suffix. Raises: UserWarning: When ``/`` is detected in suffix. """ suffix = os.path.basename(path).split(".")[-1] ...
[ "def", "_get_suffix", "(", "path", ")", ":", "suffix", "=", "os", ".", "path", ".", "basename", "(", "path", ")", ".", "split", "(", "\".\"", ")", "[", "-", "1", "]", "if", "\"/\"", "in", "suffix", ":", "raise", "UserWarning", "(", "\"Filename can't ...
Return suffix from `path`. ``/home/xex/somefile.txt`` --> ``txt``. Args: path (str): Full file path. Returns: str: Suffix. Raises: UserWarning: When ``/`` is detected in suffix.
[ "Return", "suffix", "from", "path", "." ]
train
https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/fn_composers.py#L14-L34
biocore/mustached-octo-ironman
moi/websocket.py
MOIMessageHandler.on_message
def on_message(self, msg): """Accept a message that was published, process and forward Parameters ---------- msg : str The message sent over the line Notes ----- This method only handles messages where `message_type` is "message". """ ...
python
def on_message(self, msg): """Accept a message that was published, process and forward Parameters ---------- msg : str The message sent over the line Notes ----- This method only handles messages where `message_type` is "message". """ ...
[ "def", "on_message", "(", "self", ",", "msg", ")", ":", "if", "self", "not", "in", "clients", ":", "return", "try", ":", "payload", "=", "json_decode", "(", "msg", ")", "except", "ValueError", ":", "# unable to decode so we cannot handle the message", "return", ...
Accept a message that was published, process and forward Parameters ---------- msg : str The message sent over the line Notes ----- This method only handles messages where `message_type` is "message".
[ "Accept", "a", "message", "that", "was", "published", "process", "and", "forward" ]
train
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/websocket.py#L40-L66
metagriffin/pxml
pxml/__init__.py
prettify
def prettify(input, output, strict=True, indentString=' ', color=False, encoding=DEFAULT_ENCODING): ''' Converts the input data stream `input` (which must be a file input like object) to `output` (which must be a file output like object) by parsing the stream as XML and outputting "prettified" X...
python
def prettify(input, output, strict=True, indentString=' ', color=False, encoding=DEFAULT_ENCODING): ''' Converts the input data stream `input` (which must be a file input like object) to `output` (which must be a file output like object) by parsing the stream as XML and outputting "prettified" X...
[ "def", "prettify", "(", "input", ",", "output", ",", "strict", "=", "True", ",", "indentString", "=", "' '", ",", "color", "=", "False", ",", "encoding", "=", "DEFAULT_ENCODING", ")", ":", "data", "=", "input", ".", "read", "(", ")", "try", ":", "do...
Converts the input data stream `input` (which must be a file input like object) to `output` (which must be a file output like object) by parsing the stream as XML and outputting "prettified" XML. Prettification involves the following aspects: * Collapsing ignorable whitespace. * Indenting nodes by `indentStr...
[ "Converts", "the", "input", "data", "stream", "input", "(", "which", "must", "be", "a", "file", "input", "like", "object", ")", "to", "output", "(", "which", "must", "be", "a", "file", "output", "like", "object", ")", "by", "parsing", "the", "stream", ...
train
https://github.com/metagriffin/pxml/blob/f340e26a6febbd06bf4c246d7668d0e89a2efecf/pxml/__init__.py#L187-L249
wtsi-hgi/xiongxiong
decoders/python/xiongxiong/xiongxiong.py
_tokenFactory
def _tokenFactory(authenticated): ''' Build a Token class, based upon the function arguments in the closure, and return an instantiation of it. This allows us return an object with truly read-only properties :) These 'hoops' suggest that this is probably 'unpythonic', but what can you do?! n.b., This shoul...
python
def _tokenFactory(authenticated): ''' Build a Token class, based upon the function arguments in the closure, and return an instantiation of it. This allows us return an object with truly read-only properties :) These 'hoops' suggest that this is probably 'unpythonic', but what can you do?! n.b., This shoul...
[ "def", "_tokenFactory", "(", "authenticated", ")", ":", "if", "not", "authenticated", ":", "weAreGood", "=", "False", "authenticated", "=", "{", "'data'", ":", "None", ",", "'expiration'", ":", "None", "}", "else", ":", "weAreGood", "=", "True", "class", "...
Build a Token class, based upon the function arguments in the closure, and return an instantiation of it. This allows us return an object with truly read-only properties :) These 'hoops' suggest that this is probably 'unpythonic', but what can you do?! n.b., This shouldn't be invoked directly.
[ "Build", "a", "Token", "class", "based", "upon", "the", "function", "arguments", "in", "the", "closure", "and", "return", "an", "instantiation", "of", "it", ".", "This", "allows", "us", "return", "an", "object", "with", "truly", "read", "-", "only", "prope...
train
https://github.com/wtsi-hgi/xiongxiong/blob/d177aa88bd5c290ddbc8ff123f8fd7a95e4e3ec7/decoders/python/xiongxiong/xiongxiong.py#L44-L86
chamrc/to
to/layers/sru.py
SRU_Compute_CPU
def SRU_Compute_CPU(activation_type, d, bidirectional=False, scale_x=1): """CPU version of the core SRU computation. Has the same interface as SRU_Compute_GPU() but is a regular Python function instead of a torch.autograd.Function because we don't implement backward() explicitly. """ def sru_c...
python
def SRU_Compute_CPU(activation_type, d, bidirectional=False, scale_x=1): """CPU version of the core SRU computation. Has the same interface as SRU_Compute_GPU() but is a regular Python function instead of a torch.autograd.Function because we don't implement backward() explicitly. """ def sru_c...
[ "def", "SRU_Compute_CPU", "(", "activation_type", ",", "d", ",", "bidirectional", "=", "False", ",", "scale_x", "=", "1", ")", ":", "def", "sru_compute_cpu", "(", "u", ",", "x", ",", "bias", ",", "init", "=", "None", ",", "mask_h", "=", "None", ")", ...
CPU version of the core SRU computation. Has the same interface as SRU_Compute_GPU() but is a regular Python function instead of a torch.autograd.Function because we don't implement backward() explicitly.
[ "CPU", "version", "of", "the", "core", "SRU", "computation", "." ]
train
https://github.com/chamrc/to/blob/ea1122bef08615b6c19904dadf2608e10c20c960/to/layers/sru.py#L502-L567
brbsix/subnuker
subnuker.py
get_encoding
def get_encoding(binary): """Return the encoding type.""" try: from chardet import detect except ImportError: LOGGER.error("Please install the 'chardet' module") sys.exit(1) encoding = detect(binary).get('encoding') return 'iso-8859-1' if encoding == 'CP949' else encoding
python
def get_encoding(binary): """Return the encoding type.""" try: from chardet import detect except ImportError: LOGGER.error("Please install the 'chardet' module") sys.exit(1) encoding = detect(binary).get('encoding') return 'iso-8859-1' if encoding == 'CP949' else encoding
[ "def", "get_encoding", "(", "binary", ")", ":", "try", ":", "from", "chardet", "import", "detect", "except", "ImportError", ":", "LOGGER", ".", "error", "(", "\"Please install the 'chardet' module\"", ")", "sys", ".", "exit", "(", "1", ")", "encoding", "=", ...
Return the encoding type.
[ "Return", "the", "encoding", "type", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L334-L345
brbsix/subnuker
subnuker.py
getch
def getch(): """Request a single character input from the user.""" if sys.platform in ['darwin', 'linux']: import termios import tty file_descriptor = sys.stdin.fileno() settings = termios.tcgetattr(file_descriptor) try: tty.setraw(file_descriptor) ...
python
def getch(): """Request a single character input from the user.""" if sys.platform in ['darwin', 'linux']: import termios import tty file_descriptor = sys.stdin.fileno() settings = termios.tcgetattr(file_descriptor) try: tty.setraw(file_descriptor) ...
[ "def", "getch", "(", ")", ":", "if", "sys", ".", "platform", "in", "[", "'darwin'", ",", "'linux'", "]", ":", "import", "termios", "import", "tty", "file_descriptor", "=", "sys", ".", "stdin", ".", "fileno", "(", ")", "settings", "=", "termios", ".", ...
Request a single character input from the user.
[ "Request", "a", "single", "character", "input", "from", "the", "user", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L348-L363
brbsix/subnuker
subnuker.py
ismatch
def ismatch(text, pattern): """Test whether text contains string or matches regex.""" if hasattr(pattern, 'search'): return pattern.search(text) is not None else: return pattern in text if Config.options.case_sensitive \ else pattern.lower() in text.lower()
python
def ismatch(text, pattern): """Test whether text contains string or matches regex.""" if hasattr(pattern, 'search'): return pattern.search(text) is not None else: return pattern in text if Config.options.case_sensitive \ else pattern.lower() in text.lower()
[ "def", "ismatch", "(", "text", ",", "pattern", ")", ":", "if", "hasattr", "(", "pattern", ",", "'search'", ")", ":", "return", "pattern", ".", "search", "(", "text", ")", "is", "not", "None", "else", ":", "return", "pattern", "in", "text", "if", "Con...
Test whether text contains string or matches regex.
[ "Test", "whether", "text", "contains", "string", "or", "matches", "regex", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L366-L373
brbsix/subnuker
subnuker.py
logger
def logger(): """Configure program logger.""" scriptlogger = logging.getLogger(__program__) # ensure logger is not reconfigured if not scriptlogger.hasHandlers(): # set log level scriptlogger.setLevel(logging.INFO) fmt = '%(name)s:%(levelname)s: %(message)s' # config...
python
def logger(): """Configure program logger.""" scriptlogger = logging.getLogger(__program__) # ensure logger is not reconfigured if not scriptlogger.hasHandlers(): # set log level scriptlogger.setLevel(logging.INFO) fmt = '%(name)s:%(levelname)s: %(message)s' # config...
[ "def", "logger", "(", ")", ":", "scriptlogger", "=", "logging", ".", "getLogger", "(", "__program__", ")", "# ensure logger is not reconfigured", "if", "not", "scriptlogger", ".", "hasHandlers", "(", ")", ":", "# set log level", "scriptlogger", ".", "setLevel", "(...
Configure program logger.
[ "Configure", "program", "logger", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L376-L392
brbsix/subnuker
subnuker.py
main
def main(args=None): """Start application.""" Config.options, Config.args = parse(args) logger() if Config.options.aeidon or Config.options.fix: start_aeidon() else: start_srt() if Config.options.fix: sys.exit(0) if not Config.results: basenames = [os.pat...
python
def main(args=None): """Start application.""" Config.options, Config.args = parse(args) logger() if Config.options.aeidon or Config.options.fix: start_aeidon() else: start_srt() if Config.options.fix: sys.exit(0) if not Config.results: basenames = [os.pat...
[ "def", "main", "(", "args", "=", "None", ")", ":", "Config", ".", "options", ",", "Config", ".", "args", "=", "parse", "(", "args", ")", "logger", "(", ")", "if", "Config", ".", "options", ".", "aeidon", "or", "Config", ".", "options", ".", "fix", ...
Start application.
[ "Start", "application", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L395-L417
brbsix/subnuker
subnuker.py
parse
def parse(args): """Parse command-line arguments. Arguments may consist of any combination of directories, files, and options.""" import argparse parser = argparse.ArgumentParser( add_help=False, description="Remove spam and advertising from subtitle files.", usage="%(prog)s [O...
python
def parse(args): """Parse command-line arguments. Arguments may consist of any combination of directories, files, and options.""" import argparse parser = argparse.ArgumentParser( add_help=False, description="Remove spam and advertising from subtitle files.", usage="%(prog)s [O...
[ "def", "parse", "(", "args", ")", ":", "import", "argparse", "parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ",", "description", "=", "\"Remove spam and advertising from subtitle files.\"", ",", "usage", "=", "\"%(prog)s [OPTION]... TA...
Parse command-line arguments. Arguments may consist of any combination of directories, files, and options.
[ "Parse", "command", "-", "line", "arguments", ".", "Arguments", "may", "consist", "of", "any", "combination", "of", "directories", "files", "and", "options", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L426-L488
brbsix/subnuker
subnuker.py
pattern_logic_aeidon
def pattern_logic_aeidon(): """Return patterns to be used for searching subtitles via aeidon.""" if Config.options.pattern_files: return prep_patterns(Config.options.pattern_files) elif Config.options.regex: return Config.REGEX else: return Config.TERMS
python
def pattern_logic_aeidon(): """Return patterns to be used for searching subtitles via aeidon.""" if Config.options.pattern_files: return prep_patterns(Config.options.pattern_files) elif Config.options.regex: return Config.REGEX else: return Config.TERMS
[ "def", "pattern_logic_aeidon", "(", ")", ":", "if", "Config", ".", "options", ".", "pattern_files", ":", "return", "prep_patterns", "(", "Config", ".", "options", ".", "pattern_files", ")", "elif", "Config", ".", "options", ".", "regex", ":", "return", "Conf...
Return patterns to be used for searching subtitles via aeidon.
[ "Return", "patterns", "to", "be", "used", "for", "searching", "subtitles", "via", "aeidon", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L491-L499
brbsix/subnuker
subnuker.py
pattern_logic_srt
def pattern_logic_srt(): """Return patterns to be used for searching srt subtitles.""" if Config.options.pattern_files and Config.options.regex: return prep_regex(prep_patterns(Config.options.pattern_files)) elif Config.options.pattern_files: return prep_patterns(Config.options.pattern_file...
python
def pattern_logic_srt(): """Return patterns to be used for searching srt subtitles.""" if Config.options.pattern_files and Config.options.regex: return prep_regex(prep_patterns(Config.options.pattern_files)) elif Config.options.pattern_files: return prep_patterns(Config.options.pattern_file...
[ "def", "pattern_logic_srt", "(", ")", ":", "if", "Config", ".", "options", ".", "pattern_files", "and", "Config", ".", "options", ".", "regex", ":", "return", "prep_regex", "(", "prep_patterns", "(", "Config", ".", "options", ".", "pattern_files", ")", ")", ...
Return patterns to be used for searching srt subtitles.
[ "Return", "patterns", "to", "be", "used", "for", "searching", "srt", "subtitles", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L502-L512
brbsix/subnuker
subnuker.py
prep_files
def prep_files(paths, extensions): """Parses `paths` (which may consist of files and/or directories). Removes duplicates, sorts, and returns verified srt files.""" from batchpath import GeneratePaths filenames = GeneratePaths().files(paths, os.W_OK, extensions, 0, True) if filenames: retu...
python
def prep_files(paths, extensions): """Parses `paths` (which may consist of files and/or directories). Removes duplicates, sorts, and returns verified srt files.""" from batchpath import GeneratePaths filenames = GeneratePaths().files(paths, os.W_OK, extensions, 0, True) if filenames: retu...
[ "def", "prep_files", "(", "paths", ",", "extensions", ")", ":", "from", "batchpath", "import", "GeneratePaths", "filenames", "=", "GeneratePaths", "(", ")", ".", "files", "(", "paths", ",", "os", ".", "W_OK", ",", "extensions", ",", "0", ",", "True", ")"...
Parses `paths` (which may consist of files and/or directories). Removes duplicates, sorts, and returns verified srt files.
[ "Parses", "paths", "(", "which", "may", "consist", "of", "files", "and", "/", "or", "directories", ")", ".", "Removes", "duplicates", "sorts", "and", "returns", "verified", "srt", "files", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L515-L527
brbsix/subnuker
subnuker.py
prep_patterns
def prep_patterns(filenames): """Load pattern files passed via options and return list of patterns.""" patterns = [] for filename in filenames: try: with open(filename) as file: patterns += [l.rstrip('\n') for l in file] except: # pylint: disable=W0702 ...
python
def prep_patterns(filenames): """Load pattern files passed via options and return list of patterns.""" patterns = [] for filename in filenames: try: with open(filename) as file: patterns += [l.rstrip('\n') for l in file] except: # pylint: disable=W0702 ...
[ "def", "prep_patterns", "(", "filenames", ")", ":", "patterns", "=", "[", "]", "for", "filename", "in", "filenames", ":", "try", ":", "with", "open", "(", "filename", ")", "as", "file", ":", "patterns", "+=", "[", "l", ".", "rstrip", "(", "'\\n'", ")...
Load pattern files passed via options and return list of patterns.
[ "Load", "pattern", "files", "passed", "via", "options", "and", "return", "list", "of", "patterns", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L530-L548
brbsix/subnuker
subnuker.py
prep_regex
def prep_regex(patterns): """Compile regex patterns.""" flags = 0 if Config.options.case_sensitive else re.I return [re.compile(pattern, flags) for pattern in patterns]
python
def prep_regex(patterns): """Compile regex patterns.""" flags = 0 if Config.options.case_sensitive else re.I return [re.compile(pattern, flags) for pattern in patterns]
[ "def", "prep_regex", "(", "patterns", ")", ":", "flags", "=", "0", "if", "Config", ".", "options", ".", "case_sensitive", "else", "re", ".", "I", "return", "[", "re", ".", "compile", "(", "pattern", ",", "flags", ")", "for", "pattern", "in", "patterns"...
Compile regex patterns.
[ "Compile", "regex", "patterns", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L551-L556
brbsix/subnuker
subnuker.py
prerequisites
def prerequisites(): """Display information about obtaining the aeidon module.""" url = "http://home.gna.org/gaupol/download.html" debian = "sudo apt-get install python3-aeidon" other = "python3 setup.py --user --without-gaupol clean install" LOGGER.error( "The aeidon module is missing!\n\...
python
def prerequisites(): """Display information about obtaining the aeidon module.""" url = "http://home.gna.org/gaupol/download.html" debian = "sudo apt-get install python3-aeidon" other = "python3 setup.py --user --without-gaupol clean install" LOGGER.error( "The aeidon module is missing!\n\...
[ "def", "prerequisites", "(", ")", ":", "url", "=", "\"http://home.gna.org/gaupol/download.html\"", "debian", "=", "\"sudo apt-get install python3-aeidon\"", "other", "=", "\"python3 setup.py --user --without-gaupol clean install\"", "LOGGER", ".", "error", "(", "\"The aeidon modu...
Display information about obtaining the aeidon module.
[ "Display", "information", "about", "obtaining", "the", "aeidon", "module", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L559-L571
brbsix/subnuker
subnuker.py
remove_elements
def remove_elements(target, indices): """Remove multiple elements from a list and return result. This implementation is faster than the alternative below. Also note the creation of a new list to avoid altering the original. We don't have any current use for the original intact list, but may in the f...
python
def remove_elements(target, indices): """Remove multiple elements from a list and return result. This implementation is faster than the alternative below. Also note the creation of a new list to avoid altering the original. We don't have any current use for the original intact list, but may in the f...
[ "def", "remove_elements", "(", "target", ",", "indices", ")", ":", "copied", "=", "list", "(", "target", ")", "for", "index", "in", "reversed", "(", "indices", ")", ":", "del", "copied", "[", "index", "]", "return", "copied" ]
Remove multiple elements from a list and return result. This implementation is faster than the alternative below. Also note the creation of a new list to avoid altering the original. We don't have any current use for the original intact list, but may in the future...
[ "Remove", "multiple", "elements", "from", "a", "list", "and", "return", "result", ".", "This", "implementation", "is", "faster", "than", "the", "alternative", "below", ".", "Also", "note", "the", "creation", "of", "a", "new", "list", "to", "avoid", "altering...
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L574-L585
brbsix/subnuker
subnuker.py
start_aeidon
def start_aeidon(): """Prepare filenames and patterns then process subtitles with aeidon.""" extensions = ['ass', 'srt', 'ssa', 'sub'] Config.filenames = prep_files(Config.args, extensions) Config.patterns = pattern_logic_aeidon() for filename in Config.filenames: AeidonProject(filename)
python
def start_aeidon(): """Prepare filenames and patterns then process subtitles with aeidon.""" extensions = ['ass', 'srt', 'ssa', 'sub'] Config.filenames = prep_files(Config.args, extensions) Config.patterns = pattern_logic_aeidon() for filename in Config.filenames: AeidonProject(filename)
[ "def", "start_aeidon", "(", ")", ":", "extensions", "=", "[", "'ass'", ",", "'srt'", ",", "'ssa'", ",", "'sub'", "]", "Config", ".", "filenames", "=", "prep_files", "(", "Config", ".", "args", ",", "extensions", ")", "Config", ".", "patterns", "=", "pa...
Prepare filenames and patterns then process subtitles with aeidon.
[ "Prepare", "filenames", "and", "patterns", "then", "process", "subtitles", "with", "aeidon", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L593-L602
brbsix/subnuker
subnuker.py
start_srt
def start_srt(): """Prepare filenames and patterns then process srt subtitles.""" extensions = ['srt'] Config.filenames = prep_files(Config.args, extensions) Config.patterns = pattern_logic_srt() for filename in Config.filenames: SrtProject(filename)
python
def start_srt(): """Prepare filenames and patterns then process srt subtitles.""" extensions = ['srt'] Config.filenames = prep_files(Config.args, extensions) Config.patterns = pattern_logic_srt() for filename in Config.filenames: SrtProject(filename)
[ "def", "start_srt", "(", ")", ":", "extensions", "=", "[", "'srt'", "]", "Config", ".", "filenames", "=", "prep_files", "(", "Config", ".", "args", ",", "extensions", ")", "Config", ".", "patterns", "=", "pattern_logic_srt", "(", ")", "for", "filename", ...
Prepare filenames and patterns then process srt subtitles.
[ "Prepare", "filenames", "and", "patterns", "then", "process", "srt", "subtitles", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L605-L614
brbsix/subnuker
subnuker.py
AeidonProject.fixchars
def fixchars(self): """Replace characters or strings within subtitle file.""" for key in Config.CHARFIXES: self.project.set_search_string(key) self.project.set_search_replacement(Config.CHARFIXES[key]) self.project.replace_all()
python
def fixchars(self): """Replace characters or strings within subtitle file.""" for key in Config.CHARFIXES: self.project.set_search_string(key) self.project.set_search_replacement(Config.CHARFIXES[key]) self.project.replace_all()
[ "def", "fixchars", "(", "self", ")", ":", "for", "key", "in", "Config", ".", "CHARFIXES", ":", "self", ".", "project", ".", "set_search_string", "(", "key", ")", "self", ".", "project", ".", "set_search_replacement", "(", "Config", ".", "CHARFIXES", "[", ...
Replace characters or strings within subtitle file.
[ "Replace", "characters", "or", "strings", "within", "subtitle", "file", "." ]
train
https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L87-L92