repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
maximkulkin/hypothesis-regex | hypothesis_regex.py | CharactersBuilder.strategy | def strategy(self):
'Returns resulting strategy that generates configured char set'
max_codepoint = None if self._unicode else 127
strategies = []
if self._negate:
if self._categories or self._whitelist_chars:
strategies.append(
hs.charact... | python | def strategy(self):
'Returns resulting strategy that generates configured char set'
max_codepoint = None if self._unicode else 127
strategies = []
if self._negate:
if self._categories or self._whitelist_chars:
strategies.append(
hs.charact... | [
"def",
"strategy",
"(",
"self",
")",
":",
"'Returns resulting strategy that generates configured char set'",
"max_codepoint",
"=",
"None",
"if",
"self",
".",
"_unicode",
"else",
"127",
"strategies",
"=",
"[",
"]",
"if",
"self",
".",
"_negate",
":",
"if",
"self",
... | Returns resulting strategy that generates configured char set | [
"Returns",
"resulting",
"strategy",
"that",
"generates",
"configured",
"char",
"set"
] | dd139e97f5ef555dc61e9636bbe96558a5c7801f | https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L63-L99 | train |
maximkulkin/hypothesis-regex | hypothesis_regex.py | CharactersBuilder.add_category | def add_category(self, category):
'''
Add unicode category to set
Unicode categories are strings like 'Ll', 'Lu', 'Nd', etc.
See `unicodedata.category()`
'''
if category == sre.CATEGORY_DIGIT:
self._categories |= UNICODE_DIGIT_CATEGORIES
elif category... | python | def add_category(self, category):
'''
Add unicode category to set
Unicode categories are strings like 'Ll', 'Lu', 'Nd', etc.
See `unicodedata.category()`
'''
if category == sre.CATEGORY_DIGIT:
self._categories |= UNICODE_DIGIT_CATEGORIES
elif category... | [
"def",
"add_category",
"(",
"self",
",",
"category",
")",
":",
"if",
"category",
"==",
"sre",
".",
"CATEGORY_DIGIT",
":",
"self",
".",
"_categories",
"|=",
"UNICODE_DIGIT_CATEGORIES",
"elif",
"category",
"==",
"sre",
".",
"CATEGORY_NOT_DIGIT",
":",
"self",
"."... | Add unicode category to set
Unicode categories are strings like 'Ll', 'Lu', 'Nd', etc.
See `unicodedata.category()` | [
"Add",
"unicode",
"category",
"to",
"set"
] | dd139e97f5ef555dc61e9636bbe96558a5c7801f | https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L101-L131 | train |
maximkulkin/hypothesis-regex | hypothesis_regex.py | CharactersBuilder.add_chars | def add_chars(self, chars):
'Add given chars to char set'
for c in chars:
if self._ignorecase:
self._whitelist_chars.add(c.lower())
self._whitelist_chars.add(c.upper())
else:
self._whitelist_chars.add(c) | python | def add_chars(self, chars):
'Add given chars to char set'
for c in chars:
if self._ignorecase:
self._whitelist_chars.add(c.lower())
self._whitelist_chars.add(c.upper())
else:
self._whitelist_chars.add(c) | [
"def",
"add_chars",
"(",
"self",
",",
"chars",
")",
":",
"'Add given chars to char set'",
"for",
"c",
"in",
"chars",
":",
"if",
"self",
".",
"_ignorecase",
":",
"self",
".",
"_whitelist_chars",
".",
"add",
"(",
"c",
".",
"lower",
"(",
")",
")",
"self",
... | Add given chars to char set | [
"Add",
"given",
"chars",
"to",
"char",
"set"
] | dd139e97f5ef555dc61e9636bbe96558a5c7801f | https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L133-L140 | train |
jeffh/describe | describe/spec/utils.py | str_traceback | def str_traceback(error, tb):
"""Returns a string representation of the traceback.
"""
if not isinstance(tb, types.TracebackType):
return tb
return ''.join(traceback.format_exception(error.__class__, error, tb)) | python | def str_traceback(error, tb):
"""Returns a string representation of the traceback.
"""
if not isinstance(tb, types.TracebackType):
return tb
return ''.join(traceback.format_exception(error.__class__, error, tb)) | [
"def",
"str_traceback",
"(",
"error",
",",
"tb",
")",
":",
"if",
"not",
"isinstance",
"(",
"tb",
",",
"types",
".",
"TracebackType",
")",
":",
"return",
"tb",
"return",
"''",
".",
"join",
"(",
"traceback",
".",
"format_exception",
"(",
"error",
".",
"_... | Returns a string representation of the traceback. | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"traceback",
"."
] | 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/utils.py#L9-L15 | train |
jeffh/describe | describe/spec/utils.py | filter_traceback | def filter_traceback(error, tb, ignore_pkg=CURRENT_PACKAGE):
"""Filtered out all parent stacktraces starting with the given stacktrace that has
a given variable name in its globals.
"""
if not isinstance(tb, types.TracebackType):
return tb
def in_namespace(n):
return n and (n.starts... | python | def filter_traceback(error, tb, ignore_pkg=CURRENT_PACKAGE):
"""Filtered out all parent stacktraces starting with the given stacktrace that has
a given variable name in its globals.
"""
if not isinstance(tb, types.TracebackType):
return tb
def in_namespace(n):
return n and (n.starts... | [
"def",
"filter_traceback",
"(",
"error",
",",
"tb",
",",
"ignore_pkg",
"=",
"CURRENT_PACKAGE",
")",
":",
"if",
"not",
"isinstance",
"(",
"tb",
",",
"types",
".",
"TracebackType",
")",
":",
"return",
"tb",
"def",
"in_namespace",
"(",
"n",
")",
":",
"retur... | Filtered out all parent stacktraces starting with the given stacktrace that has
a given variable name in its globals. | [
"Filtered",
"out",
"all",
"parent",
"stacktraces",
"starting",
"with",
"the",
"given",
"stacktrace",
"that",
"has",
"a",
"given",
"variable",
"name",
"in",
"its",
"globals",
"."
] | 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/utils.py#L17-L35 | train |
jeffh/describe | describe/spec/utils.py | get_true_function | def get_true_function(obj):
"Returns the actual function and a boolean indicated if this is a method or not."
if not callable(obj):
raise TypeError("%r is not callable." % (obj,))
ismethod = inspect.ismethod(obj)
if inspect.isfunction(obj) or ismethod:
return obj, ismethod
if hasattr... | python | def get_true_function(obj):
"Returns the actual function and a boolean indicated if this is a method or not."
if not callable(obj):
raise TypeError("%r is not callable." % (obj,))
ismethod = inspect.ismethod(obj)
if inspect.isfunction(obj) or ismethod:
return obj, ismethod
if hasattr... | [
"def",
"get_true_function",
"(",
"obj",
")",
":",
"\"Returns the actual function and a boolean indicated if this is a method or not.\"",
"if",
"not",
"callable",
"(",
"obj",
")",
":",
"raise",
"TypeError",
"(",
"\"%r is not callable.\"",
"%",
"(",
"obj",
",",
")",
")",
... | Returns the actual function and a boolean indicated if this is a method or not. | [
"Returns",
"the",
"actual",
"function",
"and",
"a",
"boolean",
"indicated",
"if",
"this",
"is",
"a",
"method",
"or",
"not",
"."
] | 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/utils.py#L151-L166 | train |
adamziel/python_translate | python_translate/loaders.py | FileMixin.assert_valid_path | def assert_valid_path(self, path):
"""
Ensures that the path represents an existing file
@type path: str
@param path: path to check
"""
if not isinstance(path, str):
raise NotFoundResourceException(
"Resource passed to load() method must be a... | python | def assert_valid_path(self, path):
"""
Ensures that the path represents an existing file
@type path: str
@param path: path to check
"""
if not isinstance(path, str):
raise NotFoundResourceException(
"Resource passed to load() method must be a... | [
"def",
"assert_valid_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"raise",
"NotFoundResourceException",
"(",
"\"Resource passed to load() method must be a file path\"",
")",
"if",
"not",
"os",
".",
"path"... | Ensures that the path represents an existing file
@type path: str
@param path: path to check | [
"Ensures",
"that",
"the",
"path",
"represents",
"an",
"existing",
"file"
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L63-L77 | train |
adamziel/python_translate | python_translate/loaders.py | FileMixin.read_file | def read_file(self, path):
"""
Reads a file into memory and returns it's contents
@type path: str
@param path: path to load
"""
self.assert_valid_path(path)
with open(path, 'rb') as file:
contents = file.read().decode('UTF-8')
return conten... | python | def read_file(self, path):
"""
Reads a file into memory and returns it's contents
@type path: str
@param path: path to load
"""
self.assert_valid_path(path)
with open(path, 'rb') as file:
contents = file.read().decode('UTF-8')
return conten... | [
"def",
"read_file",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"assert_valid_path",
"(",
"path",
")",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"file",
":",
"contents",
"=",
"file",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'UTF-... | Reads a file into memory and returns it's contents
@type path: str
@param path: path to load | [
"Reads",
"a",
"file",
"into",
"memory",
"and",
"returns",
"it",
"s",
"contents"
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L79-L92 | train |
adamziel/python_translate | python_translate/loaders.py | DictLoader.flatten | def flatten(self, messages, parent_key=''):
"""
Flattens an nested array of translations.
The scheme used is:
'key' => array('key2' => array('key3' => 'value'))
Becomes:
'key.key2.key3' => 'value'
This function takes an array by reference and will modify it
... | python | def flatten(self, messages, parent_key=''):
"""
Flattens an nested array of translations.
The scheme used is:
'key' => array('key2' => array('key3' => 'value'))
Becomes:
'key.key2.key3' => 'value'
This function takes an array by reference and will modify it
... | [
"def",
"flatten",
"(",
"self",
",",
"messages",
",",
"parent_key",
"=",
"''",
")",
":",
"items",
"=",
"[",
"]",
"sep",
"=",
"'.'",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"messages",
".",
"items",
"(",
")",
")",
":",
"new_key",
"=",
"\"{0}{1}{2}... | Flattens an nested array of translations.
The scheme used is:
'key' => array('key2' => array('key3' => 'value'))
Becomes:
'key.key2.key3' => 'value'
This function takes an array by reference and will modify it
@type messages: dict
@param messages: The dict ... | [
"Flattens",
"an",
"nested",
"array",
"of",
"translations",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L127-L152 | train |
adamziel/python_translate | python_translate/loaders.py | PoFileLoader.parse | def parse(self, resource):
"""
Loads given resource into a dict using polib
@type resource: str
@param resource: resource
@rtype: list
"""
try:
import polib
except ImportError as e:
self.rethrow(
"You need to insta... | python | def parse(self, resource):
"""
Loads given resource into a dict using polib
@type resource: str
@param resource: resource
@rtype: list
"""
try:
import polib
except ImportError as e:
self.rethrow(
"You need to insta... | [
"def",
"parse",
"(",
"self",
",",
"resource",
")",
":",
"try",
":",
"import",
"polib",
"except",
"ImportError",
"as",
"e",
":",
"self",
".",
"rethrow",
"(",
"\"You need to install polib to use PoFileLoader or MoFileLoader\"",
",",
"ImportError",
")",
"self",
".",
... | Loads given resource into a dict using polib
@type resource: str
@param resource: resource
@rtype: list | [
"Loads",
"given",
"resource",
"into",
"a",
"dict",
"using",
"polib"
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L219-L250 | train |
ktdreyer/txkoji | txkoji/task.py | Task.arch | def arch(self):
"""
Return an architecture for this task.
:returns: an arch string (eg "noarch", or "ppc64le"), or None this task
has no architecture associated with it.
"""
if self.method in ('buildArch', 'createdistrepo', 'livecd'):
return self.pa... | python | def arch(self):
"""
Return an architecture for this task.
:returns: an arch string (eg "noarch", or "ppc64le"), or None this task
has no architecture associated with it.
"""
if self.method in ('buildArch', 'createdistrepo', 'livecd'):
return self.pa... | [
"def",
"arch",
"(",
"self",
")",
":",
"if",
"self",
".",
"method",
"in",
"(",
"'buildArch'",
",",
"'createdistrepo'",
",",
"'livecd'",
")",
":",
"return",
"self",
".",
"params",
"[",
"2",
"]",
"if",
"self",
".",
"method",
"in",
"(",
"'createrepo'",
"... | Return an architecture for this task.
:returns: an arch string (eg "noarch", or "ppc64le"), or None this task
has no architecture associated with it. | [
"Return",
"an",
"architecture",
"for",
"this",
"task",
"."
] | a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L28-L42 | train |
ktdreyer/txkoji | txkoji/task.py | Task.arches | def arches(self):
"""
Return a list of architectures for this task.
:returns: a list of arch strings (eg ["ppc64le", "x86_64"]). The list
is empty if this task has no arches associated with it.
"""
if self.method == 'image':
return self.params[2]
... | python | def arches(self):
"""
Return a list of architectures for this task.
:returns: a list of arch strings (eg ["ppc64le", "x86_64"]). The list
is empty if this task has no arches associated with it.
"""
if self.method == 'image':
return self.params[2]
... | [
"def",
"arches",
"(",
"self",
")",
":",
"if",
"self",
".",
"method",
"==",
"'image'",
":",
"return",
"self",
".",
"params",
"[",
"2",
"]",
"if",
"self",
".",
"arch",
":",
"return",
"[",
"self",
".",
"arch",
"]",
"return",
"[",
"]"
] | Return a list of architectures for this task.
:returns: a list of arch strings (eg ["ppc64le", "x86_64"]). The list
is empty if this task has no arches associated with it. | [
"Return",
"a",
"list",
"of",
"architectures",
"for",
"this",
"task",
"."
] | a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L45-L56 | train |
ktdreyer/txkoji | txkoji/task.py | Task.duration | def duration(self):
"""
Return a timedelta for this task.
Measure the time between this task's start and end time, or "now"
if the task has not yet finished.
:returns: timedelta object, or None if the task has not even started.
"""
if not self.started:
... | python | def duration(self):
"""
Return a timedelta for this task.
Measure the time between this task's start and end time, or "now"
if the task has not yet finished.
:returns: timedelta object, or None if the task has not even started.
"""
if not self.started:
... | [
"def",
"duration",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"started",
":",
"return",
"None",
"start",
"=",
"self",
".",
"started",
"end",
"=",
"self",
".",
"completed",
"if",
"not",
"end",
":",
"end",
"=",
"datetime",
".",
"utcnow",
"(",
"... | Return a timedelta for this task.
Measure the time between this task's start and end time, or "now"
if the task has not yet finished.
:returns: timedelta object, or None if the task has not even started. | [
"Return",
"a",
"timedelta",
"for",
"this",
"task",
"."
] | a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L127-L142 | train |
ktdreyer/txkoji | txkoji/task.py | Task.estimate_completion | def estimate_completion(self):
"""
Estimate completion time for a task.
:returns: deferred that when fired returns a datetime object for the
estimated, or the actual datetime, or None if we could not
estimate a time for this task method.
"""
i... | python | def estimate_completion(self):
"""
Estimate completion time for a task.
:returns: deferred that when fired returns a datetime object for the
estimated, or the actual datetime, or None if we could not
estimate a time for this task method.
"""
i... | [
"def",
"estimate_completion",
"(",
"self",
")",
":",
"if",
"self",
".",
"completion_ts",
":",
"defer",
".",
"returnValue",
"(",
"self",
".",
"completed",
")",
"if",
"self",
".",
"method",
"==",
"'build'",
"or",
"self",
".",
"method",
"==",
"'image'",
":"... | Estimate completion time for a task.
:returns: deferred that when fired returns a datetime object for the
estimated, or the actual datetime, or None if we could not
estimate a time for this task method. | [
"Estimate",
"completion",
"time",
"for",
"a",
"task",
"."
] | a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L145-L167 | train |
ktdreyer/txkoji | txkoji/task.py | Task._estimate_free | def _estimate_free(self):
"""
Estimate completion time for a free task.
:returns: deferred that when fired returns a datetime object for the
estimated, or the actual datetime, or None if we could not
estimate a time for this task method.
"""
#... | python | def _estimate_free(self):
"""
Estimate completion time for a free task.
:returns: deferred that when fired returns a datetime object for the
estimated, or the actual datetime, or None if we could not
estimate a time for this task method.
"""
#... | [
"def",
"_estimate_free",
"(",
"self",
")",
":",
"capacity_deferred",
"=",
"self",
".",
"channel",
".",
"total_capacity",
"(",
")",
"open_tasks_deferred",
"=",
"self",
".",
"channel",
".",
"tasks",
"(",
"state",
"=",
"[",
"task_states",
".",
"OPEN",
"]",
")... | Estimate completion time for a free task.
:returns: deferred that when fired returns a datetime object for the
estimated, or the actual datetime, or None if we could not
estimate a time for this task method. | [
"Estimate",
"completion",
"time",
"for",
"a",
"free",
"task",
"."
] | a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L197-L228 | train |
ktdreyer/txkoji | txkoji/task.py | Task.package | def package(self):
"""
Find a package name from a build task's parameters.
:returns: name of the package this build task is building.
:raises: ValueError if we could not parse this tasks's request params.
"""
if self.method == 'buildNotification':
return self... | python | def package(self):
"""
Find a package name from a build task's parameters.
:returns: name of the package this build task is building.
:raises: ValueError if we could not parse this tasks's request params.
"""
if self.method == 'buildNotification':
return self... | [
"def",
"package",
"(",
"self",
")",
":",
"if",
"self",
".",
"method",
"==",
"'buildNotification'",
":",
"return",
"self",
".",
"params",
"[",
"1",
"]",
"[",
"'name'",
"]",
"if",
"self",
".",
"method",
"in",
"(",
"'createImage'",
",",
"'image'",
",",
... | Find a package name from a build task's parameters.
:returns: name of the package this build task is building.
:raises: ValueError if we could not parse this tasks's request params. | [
"Find",
"a",
"package",
"name",
"from",
"a",
"build",
"task",
"s",
"parameters",
"."
] | a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L290-L325 | train |
ktdreyer/txkoji | txkoji/task.py | Task.params | def params(self):
"""
Return a list of parameters in this task's request.
If self.request is already a list, simply return it.
If self.request is a raw XML-RPC string, parse it and return the
params.
"""
if isinstance(self.request, list):
return unmu... | python | def params(self):
"""
Return a list of parameters in this task's request.
If self.request is already a list, simply return it.
If self.request is a raw XML-RPC string, parse it and return the
params.
"""
if isinstance(self.request, list):
return unmu... | [
"def",
"params",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"request",
",",
"list",
")",
":",
"return",
"unmunchify",
"(",
"self",
".",
"request",
")",
"(",
"params",
",",
"_",
")",
"=",
"xmlrpc",
".",
"loads",
"(",
"self",
".",
... | Return a list of parameters in this task's request.
If self.request is already a list, simply return it.
If self.request is a raw XML-RPC string, parse it and return the
params. | [
"Return",
"a",
"list",
"of",
"parameters",
"in",
"this",
"task",
"s",
"request",
"."
] | a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L328-L340 | train |
tjcsl/cslbot | cslbot/commands/pull.py | cmd | def cmd(send, _, args):
"""Pull changes.
Syntax: {command} <branch>
"""
try:
if exists(join(args['handler'].confdir, '.git')):
send(do_pull(srcdir=args['handler'].confdir))
else:
send(do_pull(repo=args['config']['api']['githubrepo']))
except subprocess.Calle... | python | def cmd(send, _, args):
"""Pull changes.
Syntax: {command} <branch>
"""
try:
if exists(join(args['handler'].confdir, '.git')):
send(do_pull(srcdir=args['handler'].confdir))
else:
send(do_pull(repo=args['config']['api']['githubrepo']))
except subprocess.Calle... | [
"def",
"cmd",
"(",
"send",
",",
"_",
",",
"args",
")",
":",
"try",
":",
"if",
"exists",
"(",
"join",
"(",
"args",
"[",
"'handler'",
"]",
".",
"confdir",
",",
"'.git'",
")",
")",
":",
"send",
"(",
"do_pull",
"(",
"srcdir",
"=",
"args",
"[",
"'ha... | Pull changes.
Syntax: {command} <branch> | [
"Pull",
"changes",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/pull.py#L27-L41 | train |
reichlab/pymmwr | pymmwr.py | _start_date_of_year | def _start_date_of_year(year: int) -> datetime.date:
"""
Return start date of the year using MMWR week rules
"""
jan_one = datetime.date(year, 1, 1)
diff = 7 * (jan_one.isoweekday() > 3) - jan_one.isoweekday()
return jan_one + datetime.timedelta(days=diff) | python | def _start_date_of_year(year: int) -> datetime.date:
"""
Return start date of the year using MMWR week rules
"""
jan_one = datetime.date(year, 1, 1)
diff = 7 * (jan_one.isoweekday() > 3) - jan_one.isoweekday()
return jan_one + datetime.timedelta(days=diff) | [
"def",
"_start_date_of_year",
"(",
"year",
":",
"int",
")",
"->",
"datetime",
".",
"date",
":",
"jan_one",
"=",
"datetime",
".",
"date",
"(",
"year",
",",
"1",
",",
"1",
")",
"diff",
"=",
"7",
"*",
"(",
"jan_one",
".",
"isoweekday",
"(",
")",
">",
... | Return start date of the year using MMWR week rules | [
"Return",
"start",
"date",
"of",
"the",
"year",
"using",
"MMWR",
"week",
"rules"
] | 98216bd5081998ca63db89003c4ef397fe905755 | https://github.com/reichlab/pymmwr/blob/98216bd5081998ca63db89003c4ef397fe905755/pymmwr.py#L40-L48 | train |
reichlab/pymmwr | pymmwr.py | date_to_epiweek | def date_to_epiweek(date=datetime.date.today()) -> Epiweek:
"""
Convert python date to Epiweek
"""
year = date.year
start_dates = list(map(_start_date_of_year, [year - 1, year, year + 1]))
start_date = start_dates[1]
if start_dates[1] > date:
start_date = start_dates[0]
elif da... | python | def date_to_epiweek(date=datetime.date.today()) -> Epiweek:
"""
Convert python date to Epiweek
"""
year = date.year
start_dates = list(map(_start_date_of_year, [year - 1, year, year + 1]))
start_date = start_dates[1]
if start_dates[1] > date:
start_date = start_dates[0]
elif da... | [
"def",
"date_to_epiweek",
"(",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
"->",
"Epiweek",
":",
"year",
"=",
"date",
".",
"year",
"start_dates",
"=",
"list",
"(",
"map",
"(",
"_start_date_of_year",
",",
"[",
"year",
"-",
"1",
... | Convert python date to Epiweek | [
"Convert",
"python",
"date",
"to",
"Epiweek"
] | 98216bd5081998ca63db89003c4ef397fe905755 | https://github.com/reichlab/pymmwr/blob/98216bd5081998ca63db89003c4ef397fe905755/pymmwr.py#L62-L80 | train |
reichlab/pymmwr | pymmwr.py | epiweeks_in_year | def epiweeks_in_year(year: int) -> int:
"""
Return number of epiweeks in a year
"""
if date_to_epiweek(epiweek_to_date(Epiweek(year, 53))).year == year:
return 53
else:
return 52 | python | def epiweeks_in_year(year: int) -> int:
"""
Return number of epiweeks in a year
"""
if date_to_epiweek(epiweek_to_date(Epiweek(year, 53))).year == year:
return 53
else:
return 52 | [
"def",
"epiweeks_in_year",
"(",
"year",
":",
"int",
")",
"->",
"int",
":",
"if",
"date_to_epiweek",
"(",
"epiweek_to_date",
"(",
"Epiweek",
"(",
"year",
",",
"53",
")",
")",
")",
".",
"year",
"==",
"year",
":",
"return",
"53",
"else",
":",
"return",
... | Return number of epiweeks in a year | [
"Return",
"number",
"of",
"epiweeks",
"in",
"a",
"year"
] | 98216bd5081998ca63db89003c4ef397fe905755 | https://github.com/reichlab/pymmwr/blob/98216bd5081998ca63db89003c4ef397fe905755/pymmwr.py#L83-L91 | train |
tylerbutler/engineer | engineer/commands/core.py | _ArgparseMixin.parser | def parser(self):
"""Returns the appropriate parser to use for adding arguments to your command."""
if self._command_parser is None:
parents = []
if self.need_verbose:
parents.append(_verbose_parser)
if self.need_settings:
parents.appen... | python | def parser(self):
"""Returns the appropriate parser to use for adding arguments to your command."""
if self._command_parser is None:
parents = []
if self.need_verbose:
parents.append(_verbose_parser)
if self.need_settings:
parents.appen... | [
"def",
"parser",
"(",
"self",
")",
":",
"if",
"self",
".",
"_command_parser",
"is",
"None",
":",
"parents",
"=",
"[",
"]",
"if",
"self",
".",
"need_verbose",
":",
"parents",
".",
"append",
"(",
"_verbose_parser",
")",
"if",
"self",
".",
"need_settings",
... | Returns the appropriate parser to use for adding arguments to your command. | [
"Returns",
"the",
"appropriate",
"parser",
"to",
"use",
"for",
"adding",
"arguments",
"to",
"your",
"command",
"."
] | 8884f587297f37646c40e5553174852b444a4024 | https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/commands/core.py#L165-L178 | train |
tjcsl/cslbot | cslbot/commands/admins.py | cmd | def cmd(send, _, args):
"""Returns a list of admins.
V = Verified (authed to NickServ), U = Unverified.
Syntax: {command}
"""
adminlist = []
for admin in args['db'].query(Permissions).order_by(Permissions.nick).all():
if admin.registered:
adminlist.append("%s (V)" % admin.n... | python | def cmd(send, _, args):
"""Returns a list of admins.
V = Verified (authed to NickServ), U = Unverified.
Syntax: {command}
"""
adminlist = []
for admin in args['db'].query(Permissions).order_by(Permissions.nick).all():
if admin.registered:
adminlist.append("%s (V)" % admin.n... | [
"def",
"cmd",
"(",
"send",
",",
"_",
",",
"args",
")",
":",
"adminlist",
"=",
"[",
"]",
"for",
"admin",
"in",
"args",
"[",
"'db'",
"]",
".",
"query",
"(",
"Permissions",
")",
".",
"order_by",
"(",
"Permissions",
".",
"nick",
")",
".",
"all",
"(",... | Returns a list of admins.
V = Verified (authed to NickServ), U = Unverified.
Syntax: {command} | [
"Returns",
"a",
"list",
"of",
"admins",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/admins.py#L23-L36 | train |
acutesoftware/virtual-AI-simulator | vais/AI_sample_game.py | ReallySimpleGameAI.run | def run(self):
"""
This AI simple moves the characters towards the opposite
edges of the grid for 3 steps or until event halts the
simulation
"""
x, y = 1,0 # set the direction
num_steps = 0
while self.s.get_state() != 'Halted':
self.s.comman... | python | def run(self):
"""
This AI simple moves the characters towards the opposite
edges of the grid for 3 steps or until event halts the
simulation
"""
x, y = 1,0 # set the direction
num_steps = 0
while self.s.get_state() != 'Halted':
self.s.comman... | [
"def",
"run",
"(",
"self",
")",
":",
"x",
",",
"y",
"=",
"1",
",",
"0",
"num_steps",
"=",
"0",
"while",
"self",
".",
"s",
".",
"get_state",
"(",
")",
"!=",
"'Halted'",
":",
"self",
".",
"s",
".",
"command",
"(",
"{",
"'name'",
":",
"'walk'",
... | This AI simple moves the characters towards the opposite
edges of the grid for 3 steps or until event halts the
simulation | [
"This",
"AI",
"simple",
"moves",
"the",
"characters",
"towards",
"the",
"opposite",
"edges",
"of",
"the",
"grid",
"for",
"3",
"steps",
"or",
"until",
"event",
"halts",
"the",
"simulation"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/AI_sample_game.py#L28-L43 | train |
louib/confirm | confirm/main.py | validate | def validate(schema_file, config_file, deprecation):
'''Validate a configuration file against a confirm schema.'''
result = validator_from_config_file(config_file, schema_file)
result.validate(error_on_deprecated=deprecation)
for error in result.errors():
click.secho('Error : %s' % error, er... | python | def validate(schema_file, config_file, deprecation):
'''Validate a configuration file against a confirm schema.'''
result = validator_from_config_file(config_file, schema_file)
result.validate(error_on_deprecated=deprecation)
for error in result.errors():
click.secho('Error : %s' % error, er... | [
"def",
"validate",
"(",
"schema_file",
",",
"config_file",
",",
"deprecation",
")",
":",
"result",
"=",
"validator_from_config_file",
"(",
"config_file",
",",
"schema_file",
")",
"result",
".",
"validate",
"(",
"error_on_deprecated",
"=",
"deprecation",
")",
"for"... | Validate a configuration file against a confirm schema. | [
"Validate",
"a",
"configuration",
"file",
"against",
"a",
"confirm",
"schema",
"."
] | 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L25-L35 | train |
louib/confirm | confirm/main.py | migrate | def migrate(schema_file, config_file):
'''Migrates a configuration file using a confirm schema.'''
schema = load_schema_file(open(schema_file, 'r'))
config = load_config_file(config_file, open(config_file, 'r').read())
config = append_existing_values(schema, config)
migrated_config = generate_con... | python | def migrate(schema_file, config_file):
'''Migrates a configuration file using a confirm schema.'''
schema = load_schema_file(open(schema_file, 'r'))
config = load_config_file(config_file, open(config_file, 'r').read())
config = append_existing_values(schema, config)
migrated_config = generate_con... | [
"def",
"migrate",
"(",
"schema_file",
",",
"config_file",
")",
":",
"schema",
"=",
"load_schema_file",
"(",
"open",
"(",
"schema_file",
",",
"'r'",
")",
")",
"config",
"=",
"load_config_file",
"(",
"config_file",
",",
"open",
"(",
"config_file",
",",
"'r'",
... | Migrates a configuration file using a confirm schema. | [
"Migrates",
"a",
"configuration",
"file",
"using",
"a",
"confirm",
"schema",
"."
] | 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L41-L50 | train |
louib/confirm | confirm/main.py | document | def document(schema_file):
'''Generate reStructuredText documentation from a confirm schema.'''
schema = load_schema_file(open(schema_file, 'r'))
documentation = generate_documentation(schema)
sys.stdout.write(documentation) | python | def document(schema_file):
'''Generate reStructuredText documentation from a confirm schema.'''
schema = load_schema_file(open(schema_file, 'r'))
documentation = generate_documentation(schema)
sys.stdout.write(documentation) | [
"def",
"document",
"(",
"schema_file",
")",
":",
"schema",
"=",
"load_schema_file",
"(",
"open",
"(",
"schema_file",
",",
"'r'",
")",
")",
"documentation",
"=",
"generate_documentation",
"(",
"schema",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"documenta... | Generate reStructuredText documentation from a confirm schema. | [
"Generate",
"reStructuredText",
"documentation",
"from",
"a",
"confirm",
"schema",
"."
] | 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L55-L59 | train |
louib/confirm | confirm/main.py | generate | def generate(schema_file, all_options):
'''Generates a template configuration file from a confirm schema.'''
schema = load_schema_file(open(schema_file, 'r'))
config_parser = generate_config_parser(schema, include_all=all_options)
config_parser.write(sys.stdout) | python | def generate(schema_file, all_options):
'''Generates a template configuration file from a confirm schema.'''
schema = load_schema_file(open(schema_file, 'r'))
config_parser = generate_config_parser(schema, include_all=all_options)
config_parser.write(sys.stdout) | [
"def",
"generate",
"(",
"schema_file",
",",
"all_options",
")",
":",
"schema",
"=",
"load_schema_file",
"(",
"open",
"(",
"schema_file",
",",
"'r'",
")",
")",
"config_parser",
"=",
"generate_config_parser",
"(",
"schema",
",",
"include_all",
"=",
"all_options",
... | Generates a template configuration file from a confirm schema. | [
"Generates",
"a",
"template",
"configuration",
"file",
"from",
"a",
"confirm",
"schema",
"."
] | 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L65-L69 | train |
louib/confirm | confirm/main.py | init | def init(config_file):
'''Initialize a confirm schema from an existing configuration file.'''
schema = generate_schema_file(open(config_file, 'r').read())
sys.stdout.write(schema) | python | def init(config_file):
'''Initialize a confirm schema from an existing configuration file.'''
schema = generate_schema_file(open(config_file, 'r').read())
sys.stdout.write(schema) | [
"def",
"init",
"(",
"config_file",
")",
":",
"schema",
"=",
"generate_schema_file",
"(",
"open",
"(",
"config_file",
",",
"'r'",
")",
".",
"read",
"(",
")",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"schema",
")"
] | Initialize a confirm schema from an existing configuration file. | [
"Initialize",
"a",
"confirm",
"schema",
"from",
"an",
"existing",
"configuration",
"file",
"."
] | 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L74-L77 | train |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | GaussianMixtureModel._init_random_gaussians | def _init_random_gaussians(self, X):
"""Initialize gaussian randomly"""
n_samples = np.shape(X)[0]
self.priors = (1 / self.k) * np.ones(self.k)
for _ in range(self.k):
params = {}
params["mean"] = X[np.random.choice(range(n_samples))]
params["cov"] = ... | python | def _init_random_gaussians(self, X):
"""Initialize gaussian randomly"""
n_samples = np.shape(X)[0]
self.priors = (1 / self.k) * np.ones(self.k)
for _ in range(self.k):
params = {}
params["mean"] = X[np.random.choice(range(n_samples))]
params["cov"] = ... | [
"def",
"_init_random_gaussians",
"(",
"self",
",",
"X",
")",
":",
"n_samples",
"=",
"np",
".",
"shape",
"(",
"X",
")",
"[",
"0",
"]",
"self",
".",
"priors",
"=",
"(",
"1",
"/",
"self",
".",
"k",
")",
"*",
"np",
".",
"ones",
"(",
"self",
".",
... | Initialize gaussian randomly | [
"Initialize",
"gaussian",
"randomly"
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L36-L45 | train |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | GaussianMixtureModel._get_likelihoods | def _get_likelihoods(self, X):
"""Calculate the likelihood over all samples"""
n_samples = np.shape(X)[0]
likelihoods = np.zeros((n_samples, self.k))
for i in range(self.k):
likelihoods[:, i] = self.multivariate_gaussian(X, self.parameters[i])
return likelihoods | python | def _get_likelihoods(self, X):
"""Calculate the likelihood over all samples"""
n_samples = np.shape(X)[0]
likelihoods = np.zeros((n_samples, self.k))
for i in range(self.k):
likelihoods[:, i] = self.multivariate_gaussian(X, self.parameters[i])
return likelihoods | [
"def",
"_get_likelihoods",
"(",
"self",
",",
"X",
")",
":",
"n_samples",
"=",
"np",
".",
"shape",
"(",
"X",
")",
"[",
"0",
"]",
"likelihoods",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_samples",
",",
"self",
".",
"k",
")",
")",
"for",
"i",
"in",
"r... | Calculate the likelihood over all samples | [
"Calculate",
"the",
"likelihood",
"over",
"all",
"samples"
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L63-L71 | train |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | GaussianMixtureModel._expectation | def _expectation(self, X):
"""Calculate the responsibility"""
# Calculate probabilities of X belonging to the different clusters
weighted_likelihoods = self._get_likelihoods(X) * self.priors
sum_likelihoods = np.expand_dims(np.sum(weighted_likelihoods, axis=1), axis=1)
# Determi... | python | def _expectation(self, X):
"""Calculate the responsibility"""
# Calculate probabilities of X belonging to the different clusters
weighted_likelihoods = self._get_likelihoods(X) * self.priors
sum_likelihoods = np.expand_dims(np.sum(weighted_likelihoods, axis=1), axis=1)
# Determi... | [
"def",
"_expectation",
"(",
"self",
",",
"X",
")",
":",
"weighted_likelihoods",
"=",
"self",
".",
"_get_likelihoods",
"(",
"X",
")",
"*",
"self",
".",
"priors",
"sum_likelihoods",
"=",
"np",
".",
"expand_dims",
"(",
"np",
".",
"sum",
"(",
"weighted_likelih... | Calculate the responsibility | [
"Calculate",
"the",
"responsibility"
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L73-L84 | train |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | GaussianMixtureModel._maximization | def _maximization(self, X):
"""Update the parameters and priors"""
# Iterate through clusters and recalculate mean and covariance
for i in range(self.k):
resp = np.expand_dims(self.responsibility[:, i], axis=1)
mean = (resp * X).sum(axis=0) / resp.sum()
covar... | python | def _maximization(self, X):
"""Update the parameters and priors"""
# Iterate through clusters and recalculate mean and covariance
for i in range(self.k):
resp = np.expand_dims(self.responsibility[:, i], axis=1)
mean = (resp * X).sum(axis=0) / resp.sum()
covar... | [
"def",
"_maximization",
"(",
"self",
",",
"X",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"k",
")",
":",
"resp",
"=",
"np",
".",
"expand_dims",
"(",
"self",
".",
"responsibility",
"[",
":",
",",
"i",
"]",
",",
"axis",
"=",
"1",
")",... | Update the parameters and priors | [
"Update",
"the",
"parameters",
"and",
"priors"
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L86-L98 | train |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | GaussianMixtureModel._converged | def _converged(self, X):
"""Covergence if || likehood - last_likelihood || < tolerance"""
if len(self.responsibilities) < 2:
return False
diff = np.linalg.norm(self.responsibilities[-1] - self.responsibilities[-2])
return diff <= self.tolerance | python | def _converged(self, X):
"""Covergence if || likehood - last_likelihood || < tolerance"""
if len(self.responsibilities) < 2:
return False
diff = np.linalg.norm(self.responsibilities[-1] - self.responsibilities[-2])
return diff <= self.tolerance | [
"def",
"_converged",
"(",
"self",
",",
"X",
")",
":",
"if",
"len",
"(",
"self",
".",
"responsibilities",
")",
"<",
"2",
":",
"return",
"False",
"diff",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"responsibilities",
"[",
"-",
"1",
"]",... | Covergence if || likehood - last_likelihood || < tolerance | [
"Covergence",
"if",
"||",
"likehood",
"-",
"last_likelihood",
"||",
"<",
"tolerance"
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L100-L107 | train |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | GaussianMixtureModel.cluster | def cluster(self, X):
"""Run GMM and return the cluster indices"""
# Initialize the gaussians randomly
self._init_random_gaussians(X)
# Run EM until convergence or for max iterations
for _ in range(self.max_iterations):
self._expectation(X) # E-step
s... | python | def cluster(self, X):
"""Run GMM and return the cluster indices"""
# Initialize the gaussians randomly
self._init_random_gaussians(X)
# Run EM until convergence or for max iterations
for _ in range(self.max_iterations):
self._expectation(X) # E-step
s... | [
"def",
"cluster",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"_init_random_gaussians",
"(",
"X",
")",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"max_iterations",
")",
":",
"self",
".",
"_expectation",
"(",
"X",
")",
"self",
".",
"_maximization",
... | Run GMM and return the cluster indices | [
"Run",
"GMM",
"and",
"return",
"the",
"cluster",
"indices"
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L109-L126 | train |
tjcsl/cslbot | cslbot/commands/translate.py | cmd | def cmd(send, msg, args):
"""Translate something.
Syntax: {command} [--from <language code>] [--to <language code>] <text>
See https://cloud.google.com/translate/v2/translate-reference#supported_languages for a list of valid language codes
"""
parser = arguments.ArgParser(args['config'])
parse... | python | def cmd(send, msg, args):
"""Translate something.
Syntax: {command} [--from <language code>] [--to <language code>] <text>
See https://cloud.google.com/translate/v2/translate-reference#supported_languages for a list of valid language codes
"""
parser = arguments.ArgParser(args['config'])
parse... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'--lang'",
",",
"'--from'",
",",
"default",
"=",
"None",
")",
"pa... | Translate something.
Syntax: {command} [--from <language code>] [--to <language code>] <text>
See https://cloud.google.com/translate/v2/translate-reference#supported_languages for a list of valid language codes | [
"Translate",
"something",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/translate.py#L24-L40 | train |
tjcsl/cslbot | cslbot/commands/coin.py | cmd | def cmd(send, msg, _):
"""Flips a coin a number of times.
Syntax: {command} [number]
"""
coin = ['heads', 'tails']
if not msg:
send('The coin lands on... %s' % choice(coin))
elif not msg.lstrip('-').isdigit():
send("Not A Valid Positive Integer.")
else:
msg = int(ms... | python | def cmd(send, msg, _):
"""Flips a coin a number of times.
Syntax: {command} [number]
"""
coin = ['heads', 'tails']
if not msg:
send('The coin lands on... %s' % choice(coin))
elif not msg.lstrip('-').isdigit():
send("Not A Valid Positive Integer.")
else:
msg = int(ms... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"_",
")",
":",
"coin",
"=",
"[",
"'heads'",
",",
"'tails'",
"]",
"if",
"not",
"msg",
":",
"send",
"(",
"'The coin lands on... %s'",
"%",
"choice",
"(",
"coin",
")",
")",
"elif",
"not",
"msg",
".",
"lstrip... | Flips a coin a number of times.
Syntax: {command} [number] | [
"Flips",
"a",
"coin",
"a",
"number",
"of",
"times",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/coin.py#L24-L42 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.is_admin | def is_admin(self, send, nick, required_role='admin'):
"""Checks if a nick is a admin.
If NickServ hasn't responded yet, then the admin is unverified,
so assume they aren't a admin.
"""
# If the required role is None, bypass checks.
if not required_role:
ret... | python | def is_admin(self, send, nick, required_role='admin'):
"""Checks if a nick is a admin.
If NickServ hasn't responded yet, then the admin is unverified,
so assume they aren't a admin.
"""
# If the required role is None, bypass checks.
if not required_role:
ret... | [
"def",
"is_admin",
"(",
"self",
",",
"send",
",",
"nick",
",",
"required_role",
"=",
"'admin'",
")",
":",
"if",
"not",
"required_role",
":",
"return",
"True",
"with",
"self",
".",
"db",
".",
"session_scope",
"(",
")",
"as",
"session",
":",
"admin",
"="... | Checks if a nick is a admin.
If NickServ hasn't responded yet, then the admin is unverified,
so assume they aren't a admin. | [
"Checks",
"if",
"a",
"nick",
"is",
"a",
"admin",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L106-L138 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.get_admins | def get_admins(self):
"""Check verification for all admins."""
# no nickserv support, assume people are who they say they are.
if not self.config['feature'].getboolean('nickserv'):
return
with self.db.session_scope() as session:
for a in session.query(orm.Permissi... | python | def get_admins(self):
"""Check verification for all admins."""
# no nickserv support, assume people are who they say they are.
if not self.config['feature'].getboolean('nickserv'):
return
with self.db.session_scope() as session:
for a in session.query(orm.Permissi... | [
"def",
"get_admins",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"config",
"[",
"'feature'",
"]",
".",
"getboolean",
"(",
"'nickserv'",
")",
":",
"return",
"with",
"self",
".",
"db",
".",
"session_scope",
"(",
")",
"as",
"session",
":",
"for",
"... | Check verification for all admins. | [
"Check",
"verification",
"for",
"all",
"admins",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L140-L148 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.abusecheck | def abusecheck(self, send, nick, target, limit, cmd):
""" Rate-limits commands.
| If a nick uses commands with the limit attr set, record the time
| at which they were used.
| If the command is used more than `limit` times in a
| minute, ignore the nick.
"""
if n... | python | def abusecheck(self, send, nick, target, limit, cmd):
""" Rate-limits commands.
| If a nick uses commands with the limit attr set, record the time
| at which they were used.
| If the command is used more than `limit` times in a
| minute, ignore the nick.
"""
if n... | [
"def",
"abusecheck",
"(",
"self",
",",
"send",
",",
"nick",
",",
"target",
",",
"limit",
",",
"cmd",
")",
":",
"if",
"nick",
"not",
"in",
"self",
".",
"abuselist",
":",
"self",
".",
"abuselist",
"[",
"nick",
"]",
"=",
"{",
"}",
"if",
"cmd",
"not"... | Rate-limits commands.
| If a nick uses commands with the limit attr set, record the time
| at which they were used.
| If the command is used more than `limit` times in a
| minute, ignore the nick. | [
"Rate",
"-",
"limits",
"commands",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L150-L174 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_log | def do_log(self, target, nick, msg, msgtype):
"""Handles logging.
| Logs to a sql db.
"""
if not isinstance(msg, str):
raise Exception("IRC doesn't like it when you send it a %s" % type(msg).__name__)
target = target.lower()
flags = 0
# Properly hand... | python | def do_log(self, target, nick, msg, msgtype):
"""Handles logging.
| Logs to a sql db.
"""
if not isinstance(msg, str):
raise Exception("IRC doesn't like it when you send it a %s" % type(msg).__name__)
target = target.lower()
flags = 0
# Properly hand... | [
"def",
"do_log",
"(",
"self",
",",
"target",
",",
"nick",
",",
"msg",
",",
"msgtype",
")",
":",
"if",
"not",
"isinstance",
"(",
"msg",
",",
"str",
")",
":",
"raise",
"Exception",
"(",
"\"IRC doesn't like it when you send it a %s\"",
"%",
"type",
"(",
"msg"... | Handles logging.
| Logs to a sql db. | [
"Handles",
"logging",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L226-L257 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_part | def do_part(self, cmdargs, nick, target, msgtype, send, c):
"""Leaves a channel.
Prevent user from leaving the primary channel.
"""
channel = self.config['core']['channel']
botnick = self.config['core']['nick']
if not cmdargs:
# don't leave the primary chann... | python | def do_part(self, cmdargs, nick, target, msgtype, send, c):
"""Leaves a channel.
Prevent user from leaving the primary channel.
"""
channel = self.config['core']['channel']
botnick = self.config['core']['nick']
if not cmdargs:
# don't leave the primary chann... | [
"def",
"do_part",
"(",
"self",
",",
"cmdargs",
",",
"nick",
",",
"target",
",",
"msgtype",
",",
"send",
",",
"c",
")",
":",
"channel",
"=",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'channel'",
"]",
"botnick",
"=",
"self",
".",
"config",
"["... | Leaves a channel.
Prevent user from leaving the primary channel. | [
"Leaves",
"a",
"channel",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L259-L285 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_join | def do_join(self, cmdargs, nick, msgtype, send, c):
"""Join a channel.
| Checks if bot is already joined to channel.
"""
if not cmdargs:
send("Join what?")
return
if cmdargs == '0':
send("I'm sorry, Dave. I'm afraid I can't do that.")
... | python | def do_join(self, cmdargs, nick, msgtype, send, c):
"""Join a channel.
| Checks if bot is already joined to channel.
"""
if not cmdargs:
send("Join what?")
return
if cmdargs == '0':
send("I'm sorry, Dave. I'm afraid I can't do that.")
... | [
"def",
"do_join",
"(",
"self",
",",
"cmdargs",
",",
"nick",
",",
"msgtype",
",",
"send",
",",
"c",
")",
":",
"if",
"not",
"cmdargs",
":",
"send",
"(",
"\"Join what?\"",
")",
"return",
"if",
"cmdargs",
"==",
"'0'",
":",
"send",
"(",
"\"I'm sorry, Dave. ... | Join a channel.
| Checks if bot is already joined to channel. | [
"Join",
"a",
"channel",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L287-L307 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_mode | def do_mode(self, target, msg, nick, send):
"""reop and handle guard violations."""
mode_changes = irc.modes.parse_channel_modes(msg)
with self.data_lock:
for change in mode_changes:
if change[1] == 'v':
self.voiced[target][change[2]] = True if cha... | python | def do_mode(self, target, msg, nick, send):
"""reop and handle guard violations."""
mode_changes = irc.modes.parse_channel_modes(msg)
with self.data_lock:
for change in mode_changes:
if change[1] == 'v':
self.voiced[target][change[2]] = True if cha... | [
"def",
"do_mode",
"(",
"self",
",",
"target",
",",
"msg",
",",
"nick",
",",
"send",
")",
":",
"mode_changes",
"=",
"irc",
".",
"modes",
".",
"parse_channel_modes",
"(",
"msg",
")",
"with",
"self",
".",
"data_lock",
":",
"for",
"change",
"in",
"mode_cha... | reop and handle guard violations. | [
"reop",
"and",
"handle",
"guard",
"violations",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L318-L343 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_kick | def do_kick(self, send, target, nick, msg, slogan=True):
"""Kick users.
- If kick is disabled, don't do anything.
- If the bot is not a op, rage at a op.
- Kick the user.
"""
if not self.kick_enabled:
return
if target not in self.channels:
... | python | def do_kick(self, send, target, nick, msg, slogan=True):
"""Kick users.
- If kick is disabled, don't do anything.
- If the bot is not a op, rage at a op.
- Kick the user.
"""
if not self.kick_enabled:
return
if target not in self.channels:
... | [
"def",
"do_kick",
"(",
"self",
",",
"send",
",",
"target",
",",
"nick",
",",
"msg",
",",
"slogan",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"kick_enabled",
":",
"return",
"if",
"target",
"not",
"in",
"self",
".",
"channels",
":",
"send",
"(... | Kick users.
- If kick is disabled, don't do anything.
- If the bot is not a op, rage at a op.
- Kick the user. | [
"Kick",
"users",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L345-L374 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_args | def do_args(self, modargs, send, nick, target, source, name, msgtype):
"""Handle the various args that modules need."""
realargs = {}
args = {
'nick': nick,
'handler': self,
'db': None,
'config': self.config,
'source': source,
... | python | def do_args(self, modargs, send, nick, target, source, name, msgtype):
"""Handle the various args that modules need."""
realargs = {}
args = {
'nick': nick,
'handler': self,
'db': None,
'config': self.config,
'source': source,
... | [
"def",
"do_args",
"(",
"self",
",",
"modargs",
",",
"send",
",",
"nick",
",",
"target",
",",
"source",
",",
"name",
",",
"msgtype",
")",
":",
"realargs",
"=",
"{",
"}",
"args",
"=",
"{",
"'nick'",
":",
"nick",
",",
"'handler'",
":",
"self",
",",
... | Handle the various args that modules need. | [
"Handle",
"the",
"various",
"args",
"that",
"modules",
"need",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L376-L398 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_welcome | def do_welcome(self):
"""Do setup when connected to server.
- Join the primary channel.
- Join the control channel.
"""
self.rate_limited_send('join', self.config['core']['channel'])
self.rate_limited_send('join', self.config['core']['ctrlchan'], self.config['auth']['ct... | python | def do_welcome(self):
"""Do setup when connected to server.
- Join the primary channel.
- Join the control channel.
"""
self.rate_limited_send('join', self.config['core']['channel'])
self.rate_limited_send('join', self.config['core']['ctrlchan'], self.config['auth']['ct... | [
"def",
"do_welcome",
"(",
"self",
")",
":",
"self",
".",
"rate_limited_send",
"(",
"'join'",
",",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'channel'",
"]",
")",
"self",
".",
"rate_limited_send",
"(",
"'join'",
",",
"self",
".",
"config",
"[",
"... | Do setup when connected to server.
- Join the primary channel.
- Join the control channel. | [
"Do",
"setup",
"when",
"connected",
"to",
"server",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L400-L414 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.get_filtered_send | def get_filtered_send(self, cmdargs, send, target):
"""Parse out any filters."""
parser = arguments.ArgParser(self.config)
parser.add_argument('--filter')
try:
filterargs, remainder = parser.parse_known_args(cmdargs)
except arguments.ArgumentException as ex:
... | python | def get_filtered_send(self, cmdargs, send, target):
"""Parse out any filters."""
parser = arguments.ArgParser(self.config)
parser.add_argument('--filter')
try:
filterargs, remainder = parser.parse_known_args(cmdargs)
except arguments.ArgumentException as ex:
... | [
"def",
"get_filtered_send",
"(",
"self",
",",
"cmdargs",
",",
"send",
",",
"target",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"self",
".",
"config",
")",
"parser",
".",
"add_argument",
"(",
"'--filter'",
")",
"try",
":",
"filterargs",
... | Parse out any filters. | [
"Parse",
"out",
"any",
"filters",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L420-L439 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.handle_msg | def handle_msg(self, c, e):
"""The Heart and Soul of IrcBot."""
if e.type not in ['authenticate', 'error', 'join', 'part', 'quit']:
nick = e.source.nick
else:
nick = e.source
if e.arguments is None:
msg = ""
else:
msg = " ".join(e... | python | def handle_msg(self, c, e):
"""The Heart and Soul of IrcBot."""
if e.type not in ['authenticate', 'error', 'join', 'part', 'quit']:
nick = e.source.nick
else:
nick = e.source
if e.arguments is None:
msg = ""
else:
msg = " ".join(e... | [
"def",
"handle_msg",
"(",
"self",
",",
"c",
",",
"e",
")",
":",
"if",
"e",
".",
"type",
"not",
"in",
"[",
"'authenticate'",
",",
"'error'",
",",
"'join'",
",",
"'part'",
",",
"'quit'",
"]",
":",
"nick",
"=",
"e",
".",
"source",
".",
"nick",
"else... | The Heart and Soul of IrcBot. | [
"The",
"Heart",
"and",
"Soul",
"of",
"IrcBot",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L605-L675 | train |
jmbeach/KEP.py | src/keppy/simulator_device.py | SimulatorDevice.process_tag | def process_tag(self, tag):
"""Processes tag and detects which function to use"""
try:
if not self._is_function(tag):
self._tag_type_processor[tag.data_type](tag)
except KeyError as ex:
raise Exception('Tag type {0} not recognized for tag {1}'
... | python | def process_tag(self, tag):
"""Processes tag and detects which function to use"""
try:
if not self._is_function(tag):
self._tag_type_processor[tag.data_type](tag)
except KeyError as ex:
raise Exception('Tag type {0} not recognized for tag {1}'
... | [
"def",
"process_tag",
"(",
"self",
",",
"tag",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"_is_function",
"(",
"tag",
")",
":",
"self",
".",
"_tag_type_processor",
"[",
"tag",
".",
"data_type",
"]",
"(",
"tag",
")",
"except",
"KeyError",
"as",
"... | Processes tag and detects which function to use | [
"Processes",
"tag",
"and",
"detects",
"which",
"function",
"to",
"use"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L48-L58 | train |
jmbeach/KEP.py | src/keppy/simulator_device.py | SimulatorDevice.process_boolean | def process_boolean(self, tag):
"""Process Boolean type tags"""
tag.set_address(self.normal_register.current_bit_address)
self.normal_register.move_to_next_bit_address() | python | def process_boolean(self, tag):
"""Process Boolean type tags"""
tag.set_address(self.normal_register.current_bit_address)
self.normal_register.move_to_next_bit_address() | [
"def",
"process_boolean",
"(",
"self",
",",
"tag",
")",
":",
"tag",
".",
"set_address",
"(",
"self",
".",
"normal_register",
".",
"current_bit_address",
")",
"self",
".",
"normal_register",
".",
"move_to_next_bit_address",
"(",
")"
] | Process Boolean type tags | [
"Process",
"Boolean",
"type",
"tags"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L61-L64 | train |
jmbeach/KEP.py | src/keppy/simulator_device.py | SimulatorDevice.process_boolean_array | def process_boolean_array(self, tag):
"""Process Boolean array type tags"""
array_size = tag.get_array_size()
tag.set_address(self.normal_register.get_array(array_size))
if self.is_sixteen_bit:
# each boolean address needs 1/16 byte
self.normal_register.move_to_ne... | python | def process_boolean_array(self, tag):
"""Process Boolean array type tags"""
array_size = tag.get_array_size()
tag.set_address(self.normal_register.get_array(array_size))
if self.is_sixteen_bit:
# each boolean address needs 1/16 byte
self.normal_register.move_to_ne... | [
"def",
"process_boolean_array",
"(",
"self",
",",
"tag",
")",
":",
"array_size",
"=",
"tag",
".",
"get_array_size",
"(",
")",
"tag",
".",
"set_address",
"(",
"self",
".",
"normal_register",
".",
"get_array",
"(",
"array_size",
")",
")",
"if",
"self",
".",
... | Process Boolean array type tags | [
"Process",
"Boolean",
"array",
"type",
"tags"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L66-L75 | train |
jmbeach/KEP.py | src/keppy/simulator_device.py | SimulatorDevice.process_byte | def process_byte(self, tag):
"""Process byte type tags"""
tag.set_address(self.normal_register.current_address)
# each address needs 1 byte
self.normal_register.move_to_next_address(1) | python | def process_byte(self, tag):
"""Process byte type tags"""
tag.set_address(self.normal_register.current_address)
# each address needs 1 byte
self.normal_register.move_to_next_address(1) | [
"def",
"process_byte",
"(",
"self",
",",
"tag",
")",
":",
"tag",
".",
"set_address",
"(",
"self",
".",
"normal_register",
".",
"current_address",
")",
"self",
".",
"normal_register",
".",
"move_to_next_address",
"(",
"1",
")"
] | Process byte type tags | [
"Process",
"byte",
"type",
"tags"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L77-L81 | train |
jmbeach/KEP.py | src/keppy/simulator_device.py | SimulatorDevice.process_string | def process_string(self, tag):
"""Process string type tags"""
tag.set_address(self.string_register.current_address)
if self.is_sixteen_bit:
# each string address needs 1 byte = 1/2 an address
self.string_register.move_to_next_address(1)
return
# each s... | python | def process_string(self, tag):
"""Process string type tags"""
tag.set_address(self.string_register.current_address)
if self.is_sixteen_bit:
# each string address needs 1 byte = 1/2 an address
self.string_register.move_to_next_address(1)
return
# each s... | [
"def",
"process_string",
"(",
"self",
",",
"tag",
")",
":",
"tag",
".",
"set_address",
"(",
"self",
".",
"string_register",
".",
"current_address",
")",
"if",
"self",
".",
"is_sixteen_bit",
":",
"self",
".",
"string_register",
".",
"move_to_next_address",
"(",... | Process string type tags | [
"Process",
"string",
"type",
"tags"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L166-L174 | train |
tjcsl/cslbot | cslbot/commands/microwave.py | cmd | def cmd(send, msg, args):
"""Microwaves something.
Syntax: {command} <level> <target>
"""
nick = args['nick']
channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel']
levels = {
1: 'Whirr...',
2: 'Vrrm...',
3: 'Zzzzhhhh...',
... | python | def cmd(send, msg, args):
"""Microwaves something.
Syntax: {command} <level> <target>
"""
nick = args['nick']
channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel']
levels = {
1: 'Whirr...',
2: 'Vrrm...',
3: 'Zzzzhhhh...',
... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"nick",
"=",
"args",
"[",
"'nick'",
"]",
"channel",
"=",
"args",
"[",
"'target'",
"]",
"if",
"args",
"[",
"'target'",
"]",
"!=",
"'private'",
"else",
"args",
"[",
"'config'",
"]",
"[",
... | Microwaves something.
Syntax: {command} <level> <target> | [
"Microwaves",
"something",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/microwave.py#L25-L83 | train |
fabaff/python-opensensemap-api | example.py | main | async def main():
"""Sample code to retrieve the data from an OpenSenseMap station."""
async with aiohttp.ClientSession() as session:
station = OpenSenseMap(SENSOR_ID, loop, session)
# Print details about the given station
await station.get_data()
print("Name:", station.name)
... | python | async def main():
"""Sample code to retrieve the data from an OpenSenseMap station."""
async with aiohttp.ClientSession() as session:
station = OpenSenseMap(SENSOR_ID, loop, session)
# Print details about the given station
await station.get_data()
print("Name:", station.name)
... | [
"async",
"def",
"main",
"(",
")",
":",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"station",
"=",
"OpenSenseMap",
"(",
"SENSOR_ID",
",",
"loop",
",",
"session",
")",
"await",
"station",
".",
"get_data",
"(",
")",
... | Sample code to retrieve the data from an OpenSenseMap station. | [
"Sample",
"code",
"to",
"retrieve",
"the",
"data",
"from",
"an",
"OpenSenseMap",
"station",
"."
] | 3c4f5473c514185087aae5d766ab4d5736ec1f30 | https://github.com/fabaff/python-opensensemap-api/blob/3c4f5473c514185087aae5d766ab4d5736ec1f30/example.py#L11-L26 | train |
adamheins/r12 | r12/shell.py | ShellStyle.theme | def theme(self, text):
''' Theme style. '''
return self.theme_color + self.BRIGHT + text + self.RESET | python | def theme(self, text):
''' Theme style. '''
return self.theme_color + self.BRIGHT + text + self.RESET | [
"def",
"theme",
"(",
"self",
",",
"text",
")",
":",
"return",
"self",
".",
"theme_color",
"+",
"self",
".",
"BRIGHT",
"+",
"text",
"+",
"self",
".",
"RESET"
] | Theme style. | [
"Theme",
"style",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L33-L35 | train |
adamheins/r12 | r12/shell.py | ShellStyle._label_desc | def _label_desc(self, label, desc, label_color=''):
''' Generic styler for a line consisting of a label and description. '''
return self.BRIGHT + label_color + label + self.RESET + desc | python | def _label_desc(self, label, desc, label_color=''):
''' Generic styler for a line consisting of a label and description. '''
return self.BRIGHT + label_color + label + self.RESET + desc | [
"def",
"_label_desc",
"(",
"self",
",",
"label",
",",
"desc",
",",
"label_color",
"=",
"''",
")",
":",
"return",
"self",
".",
"BRIGHT",
"+",
"label_color",
"+",
"label",
"+",
"self",
".",
"RESET",
"+",
"desc"
] | Generic styler for a line consisting of a label and description. | [
"Generic",
"styler",
"for",
"a",
"line",
"consisting",
"of",
"a",
"label",
"and",
"description",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L38-L40 | train |
adamheins/r12 | r12/shell.py | ShellStyle.error | def error(self, cmd, desc=''):
''' Style for an error message. '''
return self._label_desc(cmd, desc, self.error_color) | python | def error(self, cmd, desc=''):
''' Style for an error message. '''
return self._label_desc(cmd, desc, self.error_color) | [
"def",
"error",
"(",
"self",
",",
"cmd",
",",
"desc",
"=",
"''",
")",
":",
"return",
"self",
".",
"_label_desc",
"(",
"cmd",
",",
"desc",
",",
"self",
".",
"error_color",
")"
] | Style for an error message. | [
"Style",
"for",
"an",
"error",
"message",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L48-L50 | train |
adamheins/r12 | r12/shell.py | ShellStyle.warn | def warn(self, cmd, desc=''):
''' Style for warning message. '''
return self._label_desc(cmd, desc, self.warn_color) | python | def warn(self, cmd, desc=''):
''' Style for warning message. '''
return self._label_desc(cmd, desc, self.warn_color) | [
"def",
"warn",
"(",
"self",
",",
"cmd",
",",
"desc",
"=",
"''",
")",
":",
"return",
"self",
".",
"_label_desc",
"(",
"cmd",
",",
"desc",
",",
"self",
".",
"warn_color",
")"
] | Style for warning message. | [
"Style",
"for",
"warning",
"message",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L53-L55 | train |
adamheins/r12 | r12/shell.py | ShellStyle.success | def success(self, cmd, desc=''):
''' Style for a success message. '''
return self._label_desc(cmd, desc, self.success_color) | python | def success(self, cmd, desc=''):
''' Style for a success message. '''
return self._label_desc(cmd, desc, self.success_color) | [
"def",
"success",
"(",
"self",
",",
"cmd",
",",
"desc",
"=",
"''",
")",
":",
"return",
"self",
".",
"_label_desc",
"(",
"cmd",
",",
"desc",
",",
"self",
".",
"success_color",
")"
] | Style for a success message. | [
"Style",
"for",
"a",
"success",
"message",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L58-L60 | train |
adamheins/r12 | r12/shell.py | ArmShell.cmdloop | def cmdloop(self, intro=None):
''' Override the command loop to handle Ctrl-C. '''
self.preloop()
# Set up completion with readline.
if self.use_rawinput and self.completekey:
try:
import readline
self.old_completer = readline.get_completer()
... | python | def cmdloop(self, intro=None):
''' Override the command loop to handle Ctrl-C. '''
self.preloop()
# Set up completion with readline.
if self.use_rawinput and self.completekey:
try:
import readline
self.old_completer = readline.get_completer()
... | [
"def",
"cmdloop",
"(",
"self",
",",
"intro",
"=",
"None",
")",
":",
"self",
".",
"preloop",
"(",
")",
"if",
"self",
".",
"use_rawinput",
"and",
"self",
".",
"completekey",
":",
"try",
":",
"import",
"readline",
"self",
".",
"old_completer",
"=",
"readl... | Override the command loop to handle Ctrl-C. | [
"Override",
"the",
"command",
"loop",
"to",
"handle",
"Ctrl",
"-",
"C",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L95-L147 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_exit | def do_exit(self, arg):
''' Exit the shell. '''
if self.arm.is_connected():
self.arm.disconnect()
print('Bye!')
return True | python | def do_exit(self, arg):
''' Exit the shell. '''
if self.arm.is_connected():
self.arm.disconnect()
print('Bye!')
return True | [
"def",
"do_exit",
"(",
"self",
",",
"arg",
")",
":",
"if",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"self",
".",
"arm",
".",
"disconnect",
"(",
")",
"print",
"(",
"'Bye!'",
")",
"return",
"True"
] | Exit the shell. | [
"Exit",
"the",
"shell",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L150-L155 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_ctrlc | def do_ctrlc(self, arg):
''' Ctrl-C sends a STOP command to the arm. '''
print('STOP')
if self.arm.is_connected():
self.arm.write('STOP') | python | def do_ctrlc(self, arg):
''' Ctrl-C sends a STOP command to the arm. '''
print('STOP')
if self.arm.is_connected():
self.arm.write('STOP') | [
"def",
"do_ctrlc",
"(",
"self",
",",
"arg",
")",
":",
"print",
"(",
"'STOP'",
")",
"if",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"self",
".",
"arm",
".",
"write",
"(",
"'STOP'",
")"
] | Ctrl-C sends a STOP command to the arm. | [
"Ctrl",
"-",
"C",
"sends",
"a",
"STOP",
"command",
"to",
"the",
"arm",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L158-L162 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_status | def do_status(self, arg):
''' Print information about the arm. '''
info = self.arm.get_info()
max_len = len(max(info.keys(), key=len))
print(self.style.theme('\nArm Status'))
for key, value in info.items():
print(self.style.help(key.ljust(max_len + 2), str(value)))
... | python | def do_status(self, arg):
''' Print information about the arm. '''
info = self.arm.get_info()
max_len = len(max(info.keys(), key=len))
print(self.style.theme('\nArm Status'))
for key, value in info.items():
print(self.style.help(key.ljust(max_len + 2), str(value)))
... | [
"def",
"do_status",
"(",
"self",
",",
"arg",
")",
":",
"info",
"=",
"self",
".",
"arm",
".",
"get_info",
"(",
")",
"max_len",
"=",
"len",
"(",
"max",
"(",
"info",
".",
"keys",
"(",
")",
",",
"key",
"=",
"len",
")",
")",
"print",
"(",
"self",
... | Print information about the arm. | [
"Print",
"information",
"about",
"the",
"arm",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L180-L188 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_connect | def do_connect(self, arg):
''' Connect to the arm. '''
if self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is already connected.'))
else:
try:
port = self.arm.connect()
print(self.style.success('Success: ',
... | python | def do_connect(self, arg):
''' Connect to the arm. '''
if self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is already connected.'))
else:
try:
port = self.arm.connect()
print(self.style.success('Success: ',
... | [
"def",
"do_connect",
"(",
"self",
",",
"arg",
")",
":",
"if",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"print",
"(",
"self",
".",
"style",
".",
"error",
"(",
"'Error: '",
",",
"'Arm is already connected.'",
")",
")",
"else",
":",
"try",
... | Connect to the arm. | [
"Connect",
"to",
"the",
"arm",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L191-L201 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_disconnect | def do_disconnect(self, arg):
''' Disconnect from the arm. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is already disconnected.'))
else:
self.arm.disconnect()
print(self.style.success('Success: ', 'Disconnected.')) | python | def do_disconnect(self, arg):
''' Disconnect from the arm. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is already disconnected.'))
else:
self.arm.disconnect()
print(self.style.success('Success: ', 'Disconnected.')) | [
"def",
"do_disconnect",
"(",
"self",
",",
"arg",
")",
":",
"if",
"not",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"print",
"(",
"self",
".",
"style",
".",
"error",
"(",
"'Error: '",
",",
"'Arm is already disconnected.'",
")",
")",
"else",
... | Disconnect from the arm. | [
"Disconnect",
"from",
"the",
"arm",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L204-L210 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_run | def do_run(self, arg):
''' Load and run an external FORTH script. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is not connected.'))
return
# Load the script.
try:
with open(arg) as f:
lines = [line.strip()... | python | def do_run(self, arg):
''' Load and run an external FORTH script. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is not connected.'))
return
# Load the script.
try:
with open(arg) as f:
lines = [line.strip()... | [
"def",
"do_run",
"(",
"self",
",",
"arg",
")",
":",
"if",
"not",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"print",
"(",
"self",
".",
"style",
".",
"error",
"(",
"'Error: '",
",",
"'Arm is not connected.'",
")",
")",
"return",
"try",
":... | Load and run an external FORTH script. | [
"Load",
"and",
"run",
"an",
"external",
"FORTH",
"script",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L213-L235 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_dump | def do_dump(self, arg):
''' Output all bytes waiting in output queue. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is not connected.'))
return
print(self.arm.dump()) | python | def do_dump(self, arg):
''' Output all bytes waiting in output queue. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is not connected.'))
return
print(self.arm.dump()) | [
"def",
"do_dump",
"(",
"self",
",",
"arg",
")",
":",
"if",
"not",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"print",
"(",
"self",
".",
"style",
".",
"error",
"(",
"'Error: '",
",",
"'Arm is not connected.'",
")",
")",
"return",
"print",
... | Output all bytes waiting in output queue. | [
"Output",
"all",
"bytes",
"waiting",
"in",
"output",
"queue",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L238-L243 | train |
adamheins/r12 | r12/shell.py | ArmShell.complete_run | def complete_run(self, text, line, b, e):
''' Autocomplete file names with .forth ending. '''
# Don't break on path separators.
text = line.split()[-1]
# Try to find files with a forth file ending, .fs.
forth_files = glob.glob(text + '*.fs')
# Failing that, just try and... | python | def complete_run(self, text, line, b, e):
''' Autocomplete file names with .forth ending. '''
# Don't break on path separators.
text = line.split()[-1]
# Try to find files with a forth file ending, .fs.
forth_files = glob.glob(text + '*.fs')
# Failing that, just try and... | [
"def",
"complete_run",
"(",
"self",
",",
"text",
",",
"line",
",",
"b",
",",
"e",
")",
":",
"text",
"=",
"line",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
"forth_files",
"=",
"glob",
".",
"glob",
"(",
"text",
"+",
"'*.fs'",
")",
"if",
"len",
... | Autocomplete file names with .forth ending. | [
"Autocomplete",
"file",
"names",
"with",
".",
"forth",
"ending",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L251-L264 | train |
adamheins/r12 | r12/shell.py | ArmShell.get_names | def get_names(self):
''' Get names for autocompletion. '''
# Overridden to support autocompletion for the ROBOFORTH commands.
return (['do_' + x for x in self.commands['shell']]
+ ['do_' + x for x in self.commands['forth']]) | python | def get_names(self):
''' Get names for autocompletion. '''
# Overridden to support autocompletion for the ROBOFORTH commands.
return (['do_' + x for x in self.commands['shell']]
+ ['do_' + x for x in self.commands['forth']]) | [
"def",
"get_names",
"(",
"self",
")",
":",
"return",
"(",
"[",
"'do_'",
"+",
"x",
"for",
"x",
"in",
"self",
".",
"commands",
"[",
"'shell'",
"]",
"]",
"+",
"[",
"'do_'",
"+",
"x",
"for",
"x",
"in",
"self",
".",
"commands",
"[",
"'forth'",
"]",
... | Get names for autocompletion. | [
"Get",
"names",
"for",
"autocompletion",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L297-L301 | train |
adamheins/r12 | r12/shell.py | ArmShell.parse_help_text | def parse_help_text(self, file_path):
''' Load of list of commands and descriptions from a file. '''
with open(file_path) as f:
lines = f.readlines()
# Parse commands and descriptions, which are separated by a multi-space
# (any sequence of two or more space characters in a ... | python | def parse_help_text(self, file_path):
''' Load of list of commands and descriptions from a file. '''
with open(file_path) as f:
lines = f.readlines()
# Parse commands and descriptions, which are separated by a multi-space
# (any sequence of two or more space characters in a ... | [
"def",
"parse_help_text",
"(",
"self",
",",
"file_path",
")",
":",
"with",
"open",
"(",
"file_path",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"cmds",
"=",
"[",
"]",
"descs",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
... | Load of list of commands and descriptions from a file. | [
"Load",
"of",
"list",
"of",
"commands",
"and",
"descriptions",
"from",
"a",
"file",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L304-L333 | train |
adamheins/r12 | r12/shell.py | ArmShell.load_forth_commands | def load_forth_commands(self, help_dir):
''' Load completion list for ROBOFORTH commands. '''
try:
help_file_path = os.path.join(help_dir, 'roboforth.txt')
commands, help_text = self.parse_help_text(help_file_path)
except IOError:
print(self.style.warn('Warnin... | python | def load_forth_commands(self, help_dir):
''' Load completion list for ROBOFORTH commands. '''
try:
help_file_path = os.path.join(help_dir, 'roboforth.txt')
commands, help_text = self.parse_help_text(help_file_path)
except IOError:
print(self.style.warn('Warnin... | [
"def",
"load_forth_commands",
"(",
"self",
",",
"help_dir",
")",
":",
"try",
":",
"help_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"help_dir",
",",
"'roboforth.txt'",
")",
"commands",
",",
"help_text",
"=",
"self",
".",
"parse_help_text",
"(",
"... | Load completion list for ROBOFORTH commands. | [
"Load",
"completion",
"list",
"for",
"ROBOFORTH",
"commands",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L336-L347 | train |
adamheins/r12 | r12/shell.py | ArmShell.preloop | def preloop(self):
''' Executed before the command loop starts. '''
script_dir = os.path.dirname(os.path.realpath(__file__))
help_dir = os.path.join(script_dir, HELP_DIR_NAME)
self.load_forth_commands(help_dir)
self.load_shell_commands(help_dir) | python | def preloop(self):
''' Executed before the command loop starts. '''
script_dir = os.path.dirname(os.path.realpath(__file__))
help_dir = os.path.join(script_dir, HELP_DIR_NAME)
self.load_forth_commands(help_dir)
self.load_shell_commands(help_dir) | [
"def",
"preloop",
"(",
"self",
")",
":",
"script_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"help_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"script_dir",
",",
"HELP_DIR_NAME... | Executed before the command loop starts. | [
"Executed",
"before",
"the",
"command",
"loop",
"starts",
"."
] | ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L363-L368 | train |
The-Politico/politico-civic-election-night | electionnight/management/commands/methods/bootstrap/legislative_office.py | LegislativeOffice.bootstrap_legislative_office | def bootstrap_legislative_office(self, election):
"""
For legislative offices, create page content for the legislative
Body the Office belongs to AND the state-level Division.
E.g., for a Texas U.S. Senate seat, create page content for:
- U.S. Senate page
- Texas... | python | def bootstrap_legislative_office(self, election):
"""
For legislative offices, create page content for the legislative
Body the Office belongs to AND the state-level Division.
E.g., for a Texas U.S. Senate seat, create page content for:
- U.S. Senate page
- Texas... | [
"def",
"bootstrap_legislative_office",
"(",
"self",
",",
"election",
")",
":",
"body",
"=",
"election",
".",
"race",
".",
"office",
".",
"body",
"body_division",
"=",
"election",
".",
"race",
".",
"office",
".",
"body",
".",
"jurisdiction",
".",
"division",
... | For legislative offices, create page content for the legislative
Body the Office belongs to AND the state-level Division.
E.g., for a Texas U.S. Senate seat, create page content for:
- U.S. Senate page
- Texas state page | [
"For",
"legislative",
"offices",
"create",
"page",
"content",
"for",
"the",
"legislative",
"Body",
"the",
"Office",
"belongs",
"to",
"AND",
"the",
"state",
"-",
"level",
"Division",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/management/commands/methods/bootstrap/legislative_office.py#L40-L94 | train |
tjcsl/cslbot | cslbot/commands/xkcd.py | cmd | def cmd(send, msg, args):
"""Gets a xkcd comic.
Syntax: {command} [num|latest|term]
"""
latest = get_latest()
if not msg:
msg = randrange(1, latest)
elif msg == 'latest':
msg = latest
elif msg.isdigit():
msg = int(msg)
if msg > latest or msg < 1:
... | python | def cmd(send, msg, args):
"""Gets a xkcd comic.
Syntax: {command} [num|latest|term]
"""
latest = get_latest()
if not msg:
msg = randrange(1, latest)
elif msg == 'latest':
msg = latest
elif msg.isdigit():
msg = int(msg)
if msg > latest or msg < 1:
... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"latest",
"=",
"get_latest",
"(",
")",
"if",
"not",
"msg",
":",
"msg",
"=",
"randrange",
"(",
"1",
",",
"latest",
")",
"elif",
"msg",
"==",
"'latest'",
":",
"msg",
"=",
"latest",
"elif... | Gets a xkcd comic.
Syntax: {command} [num|latest|term] | [
"Gets",
"a",
"xkcd",
"comic",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/xkcd.py#L41-L63 | train |
louib/confirm | confirm/generator.py | generate_config_parser | def generate_config_parser(config, include_all=False):
"""
Generates a config parser from a configuration dictionary.
The dictionary contains the merged informations of the schema and,
optionally, of a source configuration file. Values of the source
configuration file will be stored in the *value* ... | python | def generate_config_parser(config, include_all=False):
"""
Generates a config parser from a configuration dictionary.
The dictionary contains the merged informations of the schema and,
optionally, of a source configuration file. Values of the source
configuration file will be stored in the *value* ... | [
"def",
"generate_config_parser",
"(",
"config",
",",
"include_all",
"=",
"False",
")",
":",
"config_parser",
"=",
"SafeConfigParser",
"(",
"allow_no_value",
"=",
"True",
")",
"for",
"section_name",
",",
"option_name",
"in",
"_get_included_schema_sections_options",
"("... | Generates a config parser from a configuration dictionary.
The dictionary contains the merged informations of the schema and,
optionally, of a source configuration file. Values of the source
configuration file will be stored in the *value* field of an option. | [
"Generates",
"a",
"config",
"parser",
"from",
"a",
"configuration",
"dictionary",
"."
] | 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/generator.py#L24-L55 | train |
louib/confirm | confirm/generator.py | generate_documentation | def generate_documentation(schema):
"""
Generates reStructuredText documentation from a Confirm file.
:param schema: Dictionary representing the Confirm schema.
:returns: String representing the reStructuredText documentation.
"""
documentation_title = "Configuration documentation"
docume... | python | def generate_documentation(schema):
"""
Generates reStructuredText documentation from a Confirm file.
:param schema: Dictionary representing the Confirm schema.
:returns: String representing the reStructuredText documentation.
"""
documentation_title = "Configuration documentation"
docume... | [
"def",
"generate_documentation",
"(",
"schema",
")",
":",
"documentation_title",
"=",
"\"Configuration documentation\"",
"documentation",
"=",
"documentation_title",
"+",
"\"\\n\"",
"documentation",
"+=",
"\"=\"",
"*",
"len",
"(",
"documentation_title",
")",
"+",
"'\\n'... | Generates reStructuredText documentation from a Confirm file.
:param schema: Dictionary representing the Confirm schema.
:returns: String representing the reStructuredText documentation. | [
"Generates",
"reStructuredText",
"documentation",
"from",
"a",
"Confirm",
"file",
"."
] | 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/generator.py#L73-L123 | train |
louib/confirm | confirm/generator.py | append_existing_values | def append_existing_values(schema, config):
"""
Adds the values of the existing config to the config dictionary.
"""
for section_name in config:
for option_name in config[section_name]:
option_value = config[section_name][option_name]
# Note that we must preserve existi... | python | def append_existing_values(schema, config):
"""
Adds the values of the existing config to the config dictionary.
"""
for section_name in config:
for option_name in config[section_name]:
option_value = config[section_name][option_name]
# Note that we must preserve existi... | [
"def",
"append_existing_values",
"(",
"schema",
",",
"config",
")",
":",
"for",
"section_name",
"in",
"config",
":",
"for",
"option_name",
"in",
"config",
"[",
"section_name",
"]",
":",
"option_value",
"=",
"config",
"[",
"section_name",
"]",
"[",
"option_name... | Adds the values of the existing config to the config dictionary. | [
"Adds",
"the",
"values",
"of",
"the",
"existing",
"config",
"to",
"the",
"config",
"dictionary",
"."
] | 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/generator.py#L126-L139 | train |
louib/confirm | confirm/generator.py | generate_schema_file | def generate_schema_file(config_file):
"""
Generates a basic confirm schema file from a configuration file.
"""
config = utils.load_config_from_ini_file(config_file)
schema = {}
for section_name in config:
for option_name in config[section_name]:
schema.setdefault(section_n... | python | def generate_schema_file(config_file):
"""
Generates a basic confirm schema file from a configuration file.
"""
config = utils.load_config_from_ini_file(config_file)
schema = {}
for section_name in config:
for option_name in config[section_name]:
schema.setdefault(section_n... | [
"def",
"generate_schema_file",
"(",
"config_file",
")",
":",
"config",
"=",
"utils",
".",
"load_config_from_ini_file",
"(",
"config_file",
")",
"schema",
"=",
"{",
"}",
"for",
"section_name",
"in",
"config",
":",
"for",
"option_name",
"in",
"config",
"[",
"sec... | Generates a basic confirm schema file from a configuration file. | [
"Generates",
"a",
"basic",
"confirm",
"schema",
"file",
"from",
"a",
"configuration",
"file",
"."
] | 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/generator.py#L142-L155 | train |
rraadd88/rohan | rohan/dandage/io_sets.py | rankwithlist | def rankwithlist(l,lwith,test=False):
"""
rank l wrt lwith
"""
if not (isinstance(l,list) and isinstance(lwith,list)):
l,lwith=list(l),list(lwith)
from scipy.stats import rankdata
if test:
print(l,lwith)
print(rankdata(l),rankdata(lwith))
print(rankdata(l+lwith))
... | python | def rankwithlist(l,lwith,test=False):
"""
rank l wrt lwith
"""
if not (isinstance(l,list) and isinstance(lwith,list)):
l,lwith=list(l),list(lwith)
from scipy.stats import rankdata
if test:
print(l,lwith)
print(rankdata(l),rankdata(lwith))
print(rankdata(l+lwith))
... | [
"def",
"rankwithlist",
"(",
"l",
",",
"lwith",
",",
"test",
"=",
"False",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"l",
",",
"list",
")",
"and",
"isinstance",
"(",
"lwith",
",",
"list",
")",
")",
":",
"l",
",",
"lwith",
"=",
"list",
"(",
... | rank l wrt lwith | [
"rank",
"l",
"wrt",
"lwith"
] | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_sets.py#L38-L49 | train |
rraadd88/rohan | rohan/dandage/io_sets.py | dfbool2intervals | def dfbool2intervals(df,colbool):
"""
ds contains bool values
"""
df.index=range(len(df))
intervals=bools2intervals(df[colbool])
for intervali,interval in enumerate(intervals):
df.loc[interval[0]:interval[1],f'{colbool} interval id']=intervali
df.loc[interval[0]:interval[1],f'{co... | python | def dfbool2intervals(df,colbool):
"""
ds contains bool values
"""
df.index=range(len(df))
intervals=bools2intervals(df[colbool])
for intervali,interval in enumerate(intervals):
df.loc[interval[0]:interval[1],f'{colbool} interval id']=intervali
df.loc[interval[0]:interval[1],f'{co... | [
"def",
"dfbool2intervals",
"(",
"df",
",",
"colbool",
")",
":",
"df",
".",
"index",
"=",
"range",
"(",
"len",
"(",
"df",
")",
")",
"intervals",
"=",
"bools2intervals",
"(",
"df",
"[",
"colbool",
"]",
")",
"for",
"intervali",
",",
"interval",
"in",
"e... | ds contains bool values | [
"ds",
"contains",
"bool",
"values"
] | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_sets.py#L54-L67 | train |
brandjon/simplestruct | simplestruct/type.py | TypeChecker.normalize_kind | def normalize_kind(self, kindlike):
"""Make a kind out of a possible shorthand. If the given
argument is a sequence of types or a singular type, it becomes
a kind that accepts exactly those types. If the given argument
is None, it becomes a type that accepts anything.
"""
... | python | def normalize_kind(self, kindlike):
"""Make a kind out of a possible shorthand. If the given
argument is a sequence of types or a singular type, it becomes
a kind that accepts exactly those types. If the given argument
is None, it becomes a type that accepts anything.
"""
... | [
"def",
"normalize_kind",
"(",
"self",
",",
"kindlike",
")",
":",
"if",
"kindlike",
"is",
"None",
":",
"return",
"(",
"object",
",",
")",
"elif",
"isinstance",
"(",
"kindlike",
",",
"type",
")",
":",
"return",
"(",
"kindlike",
",",
")",
"else",
":",
"... | Make a kind out of a possible shorthand. If the given
argument is a sequence of types or a singular type, it becomes
a kind that accepts exactly those types. If the given argument
is None, it becomes a type that accepts anything. | [
"Make",
"a",
"kind",
"out",
"of",
"a",
"possible",
"shorthand",
".",
"If",
"the",
"given",
"argument",
"is",
"a",
"sequence",
"of",
"types",
"or",
"a",
"singular",
"type",
"it",
"becomes",
"a",
"kind",
"that",
"accepts",
"exactly",
"those",
"types",
".",... | f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/type.py#L31-L42 | train |
brandjon/simplestruct | simplestruct/type.py | TypeChecker.str_kind | def str_kind(self, kind):
"""Get a string describing a kind."""
if len(kind) == 0:
return 'Nothing'
elif len(kind) == 1:
return kind[0].__name__
elif len(kind) == 2:
return kind[0].__name__ + ' or ' + kind[1].__name__
else:
return '... | python | def str_kind(self, kind):
"""Get a string describing a kind."""
if len(kind) == 0:
return 'Nothing'
elif len(kind) == 1:
return kind[0].__name__
elif len(kind) == 2:
return kind[0].__name__ + ' or ' + kind[1].__name__
else:
return '... | [
"def",
"str_kind",
"(",
"self",
",",
"kind",
")",
":",
"if",
"len",
"(",
"kind",
")",
"==",
"0",
":",
"return",
"'Nothing'",
"elif",
"len",
"(",
"kind",
")",
"==",
"1",
":",
"return",
"kind",
"[",
"0",
"]",
".",
"__name__",
"elif",
"len",
"(",
... | Get a string describing a kind. | [
"Get",
"a",
"string",
"describing",
"a",
"kind",
"."
] | f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/type.py#L44-L53 | train |
brandjon/simplestruct | simplestruct/type.py | TypeChecker.checktype | def checktype(self, val, kind, **kargs):
"""Raise TypeError if val does not satisfy kind."""
if not isinstance(val, kind):
raise TypeError('Expected {}; got {}'.format(
self.str_kind(kind), self.str_valtype(val))) | python | def checktype(self, val, kind, **kargs):
"""Raise TypeError if val does not satisfy kind."""
if not isinstance(val, kind):
raise TypeError('Expected {}; got {}'.format(
self.str_kind(kind), self.str_valtype(val))) | [
"def",
"checktype",
"(",
"self",
",",
"val",
",",
"kind",
",",
"**",
"kargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"kind",
")",
":",
"raise",
"TypeError",
"(",
"'Expected {}; got {}'",
".",
"format",
"(",
"self",
".",
"str_kind",
"(",
... | Raise TypeError if val does not satisfy kind. | [
"Raise",
"TypeError",
"if",
"val",
"does",
"not",
"satisfy",
"kind",
"."
] | f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/type.py#L55-L59 | train |
jeffh/describe | describe/mock/expectations.py | Expectation.raises | def raises(cls, sender, attrname, error, args=ANYTHING, kwargs=ANYTHING):
"An alternative constructor which raises the given error"
def raise_error():
raise error
return cls(sender, attrname, returns=Invoke(raise_error), args=ANYTHING, kwargs=ANYTHING) | python | def raises(cls, sender, attrname, error, args=ANYTHING, kwargs=ANYTHING):
"An alternative constructor which raises the given error"
def raise_error():
raise error
return cls(sender, attrname, returns=Invoke(raise_error), args=ANYTHING, kwargs=ANYTHING) | [
"def",
"raises",
"(",
"cls",
",",
"sender",
",",
"attrname",
",",
"error",
",",
"args",
"=",
"ANYTHING",
",",
"kwargs",
"=",
"ANYTHING",
")",
":",
"\"An alternative constructor which raises the given error\"",
"def",
"raise_error",
"(",
")",
":",
"raise",
"error... | An alternative constructor which raises the given error | [
"An",
"alternative",
"constructor",
"which",
"raises",
"the",
"given",
"error"
] | 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L24-L28 | train |
jeffh/describe | describe/mock/expectations.py | ExpectationBuilder.and_raises | def and_raises(self, *errors):
"Expects an error or more to be raised from the given expectation."
for error in errors:
self.__expect(Expectation.raises, error) | python | def and_raises(self, *errors):
"Expects an error or more to be raised from the given expectation."
for error in errors:
self.__expect(Expectation.raises, error) | [
"def",
"and_raises",
"(",
"self",
",",
"*",
"errors",
")",
":",
"\"Expects an error or more to be raised from the given expectation.\"",
"for",
"error",
"in",
"errors",
":",
"self",
".",
"__expect",
"(",
"Expectation",
".",
"raises",
",",
"error",
")"
] | Expects an error or more to be raised from the given expectation. | [
"Expects",
"an",
"error",
"or",
"more",
"to",
"be",
"raised",
"from",
"the",
"given",
"expectation",
"."
] | 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L204-L207 | train |
jeffh/describe | describe/mock/expectations.py | ExpectationBuilder.and_calls | def and_calls(self, *funcs):
"""Expects the return value from one or more functions to be raised
from the given expectation.
"""
for fn in funcs:
self.__expect(Expectation, Invoke(fn)) | python | def and_calls(self, *funcs):
"""Expects the return value from one or more functions to be raised
from the given expectation.
"""
for fn in funcs:
self.__expect(Expectation, Invoke(fn)) | [
"def",
"and_calls",
"(",
"self",
",",
"*",
"funcs",
")",
":",
"for",
"fn",
"in",
"funcs",
":",
"self",
".",
"__expect",
"(",
"Expectation",
",",
"Invoke",
"(",
"fn",
")",
")"
] | Expects the return value from one or more functions to be raised
from the given expectation. | [
"Expects",
"the",
"return",
"value",
"from",
"one",
"or",
"more",
"functions",
"to",
"be",
"raised",
"from",
"the",
"given",
"expectation",
"."
] | 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L214-L219 | train |
jeffh/describe | describe/mock/expectations.py | ExpectationBuilder.and_yields | def and_yields(self, *values):
"""Expects the return value of the expectation to be a generator of the
given values
"""
def generator():
for value in values:
yield value
self.__expect(Expectation, Invoke(generator)) | python | def and_yields(self, *values):
"""Expects the return value of the expectation to be a generator of the
given values
"""
def generator():
for value in values:
yield value
self.__expect(Expectation, Invoke(generator)) | [
"def",
"and_yields",
"(",
"self",
",",
"*",
"values",
")",
":",
"def",
"generator",
"(",
")",
":",
"for",
"value",
"in",
"values",
":",
"yield",
"value",
"self",
".",
"__expect",
"(",
"Expectation",
",",
"Invoke",
"(",
"generator",
")",
")"
] | Expects the return value of the expectation to be a generator of the
given values | [
"Expects",
"the",
"return",
"value",
"of",
"the",
"expectation",
"to",
"be",
"a",
"generator",
"of",
"the",
"given",
"values"
] | 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L221-L228 | train |
jeffh/describe | describe/mock/expectations.py | ExpectationBuilderFactory.attribute_invoked | def attribute_invoked(self, sender, name, args, kwargs):
"Handles the creation of ExpectationBuilder when an attribute is invoked."
return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, '__call__')(*args, **kwargs) | python | def attribute_invoked(self, sender, name, args, kwargs):
"Handles the creation of ExpectationBuilder when an attribute is invoked."
return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, '__call__')(*args, **kwargs) | [
"def",
"attribute_invoked",
"(",
"self",
",",
"sender",
",",
"name",
",",
"args",
",",
"kwargs",
")",
":",
"\"Handles the creation of ExpectationBuilder when an attribute is invoked.\"",
"return",
"ExpectationBuilder",
"(",
"self",
".",
"sender",
",",
"self",
".",
"de... | Handles the creation of ExpectationBuilder when an attribute is invoked. | [
"Handles",
"the",
"creation",
"of",
"ExpectationBuilder",
"when",
"an",
"attribute",
"is",
"invoked",
"."
] | 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L257-L259 | train |
jeffh/describe | describe/mock/expectations.py | ExpectationBuilderFactory.attribute_read | def attribute_read(self, sender, name):
"Handles the creation of ExpectationBuilder when an attribute is read."
return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, name) | python | def attribute_read(self, sender, name):
"Handles the creation of ExpectationBuilder when an attribute is read."
return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, name) | [
"def",
"attribute_read",
"(",
"self",
",",
"sender",
",",
"name",
")",
":",
"\"Handles the creation of ExpectationBuilder when an attribute is read.\"",
"return",
"ExpectationBuilder",
"(",
"self",
".",
"sender",
",",
"self",
".",
"delegate",
",",
"self",
".",
"add_in... | Handles the creation of ExpectationBuilder when an attribute is read. | [
"Handles",
"the",
"creation",
"of",
"ExpectationBuilder",
"when",
"an",
"attribute",
"is",
"read",
"."
] | 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L261-L263 | train |
jeffh/describe | describe/mock/expectations.py | ExpectationBuilderFactory.key_read | def key_read(self, sender, name):
"Handles the creation of ExpectationBuilder when a dictionary item access."
return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, '__getitem__')(name) | python | def key_read(self, sender, name):
"Handles the creation of ExpectationBuilder when a dictionary item access."
return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, '__getitem__')(name) | [
"def",
"key_read",
"(",
"self",
",",
"sender",
",",
"name",
")",
":",
"\"Handles the creation of ExpectationBuilder when a dictionary item access.\"",
"return",
"ExpectationBuilder",
"(",
"self",
".",
"sender",
",",
"self",
".",
"delegate",
",",
"self",
".",
"add_invo... | Handles the creation of ExpectationBuilder when a dictionary item access. | [
"Handles",
"the",
"creation",
"of",
"ExpectationBuilder",
"when",
"a",
"dictionary",
"item",
"access",
"."
] | 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L265-L267 | train |
ataylor32/django-friendly-tag-loader | src/friendlytagloader/templatetags/friendly_loader.py | friendly_load | def friendly_load(parser, token):
"""
Tries to load a custom template tag set. Non existing tag libraries
are ignored.
This means that, if used in conjunction with ``if_has_tag``, you can try to
load the comments template tag library to enable comments even if the
comments framework is not inst... | python | def friendly_load(parser, token):
"""
Tries to load a custom template tag set. Non existing tag libraries
are ignored.
This means that, if used in conjunction with ``if_has_tag``, you can try to
load the comments template tag library to enable comments even if the
comments framework is not inst... | [
"def",
"friendly_load",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"bits",
")",
">=",
"4",
"and",
"bits",
"[",
"-",
"2",
"]",
"==",
"\"from\"",
":",
"name",
"=",
"bits",... | Tries to load a custom template tag set. Non existing tag libraries
are ignored.
This means that, if used in conjunction with ``if_has_tag``, you can try to
load the comments template tag library to enable comments even if the
comments framework is not installed.
For example::
{% load fri... | [
"Tries",
"to",
"load",
"a",
"custom",
"template",
"tag",
"set",
".",
"Non",
"existing",
"tag",
"libraries",
"are",
"ignored",
"."
] | fe6037dbb1a4a97a64b57d0f2212ad77b832057a | https://github.com/ataylor32/django-friendly-tag-loader/blob/fe6037dbb1a4a97a64b57d0f2212ad77b832057a/src/friendlytagloader/templatetags/friendly_loader.py#L19-L59 | train |
jlesquembre/autopilot | src/autopilot/ui.py | CursesManager.off | def off(self):
"""Turn off curses"""
self.win.keypad(0)
curses.nocbreak()
curses.echo()
try:
curses.curs_set(1)
except:
pass
curses.endwin() | python | def off(self):
"""Turn off curses"""
self.win.keypad(0)
curses.nocbreak()
curses.echo()
try:
curses.curs_set(1)
except:
pass
curses.endwin() | [
"def",
"off",
"(",
"self",
")",
":",
"self",
".",
"win",
".",
"keypad",
"(",
"0",
")",
"curses",
".",
"nocbreak",
"(",
")",
"curses",
".",
"echo",
"(",
")",
"try",
":",
"curses",
".",
"curs_set",
"(",
"1",
")",
"except",
":",
"pass",
"curses",
... | Turn off curses | [
"Turn",
"off",
"curses"
] | ca5f36269ba0173bd29c39db6971dac57a58513d | https://github.com/jlesquembre/autopilot/blob/ca5f36269ba0173bd29c39db6971dac57a58513d/src/autopilot/ui.py#L36-L45 | train |
acutesoftware/virtual-AI-simulator | vais/simulator.py | Simulator._move_agent | def _move_agent(self, agent, direction, wrap_allowed=True):
"""
moves agent 'agent' in 'direction'
"""
x,y = agent.coords['x'], agent.coords['y']
print('moving agent ', agent.name, 'to x,y=', direction, 'wrap_allowed = ', wrap_allowed)
agent.coords['x'] = x + direction[0]... | python | def _move_agent(self, agent, direction, wrap_allowed=True):
"""
moves agent 'agent' in 'direction'
"""
x,y = agent.coords['x'], agent.coords['y']
print('moving agent ', agent.name, 'to x,y=', direction, 'wrap_allowed = ', wrap_allowed)
agent.coords['x'] = x + direction[0]... | [
"def",
"_move_agent",
"(",
"self",
",",
"agent",
",",
"direction",
",",
"wrap_allowed",
"=",
"True",
")",
":",
"x",
",",
"y",
"=",
"agent",
".",
"coords",
"[",
"'x'",
"]",
",",
"agent",
".",
"coords",
"[",
"'y'",
"]",
"print",
"(",
"'moving agent '",... | moves agent 'agent' in 'direction' | [
"moves",
"agent",
"agent",
"in",
"direction"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/simulator.py#L107-L114 | train |
Xion/taipan | taipan/functional/functions.py | key_func | def key_func(*keys, **kwargs):
"""Creates a "key function" based on given keys.
Resulting function will perform lookup using specified keys, in order,
on the object passed to it as an argument.
For example, ``key_func('a', 'b')(foo)`` is equivalent to ``foo['a']['b']``.
:param keys: Lookup keys
... | python | def key_func(*keys, **kwargs):
"""Creates a "key function" based on given keys.
Resulting function will perform lookup using specified keys, in order,
on the object passed to it as an argument.
For example, ``key_func('a', 'b')(foo)`` is equivalent to ``foo['a']['b']``.
:param keys: Lookup keys
... | [
"def",
"key_func",
"(",
"*",
"keys",
",",
"**",
"kwargs",
")",
":",
"ensure_argcount",
"(",
"keys",
",",
"min_",
"=",
"1",
")",
"ensure_keyword_args",
"(",
"kwargs",
",",
"optional",
"=",
"(",
"'default'",
",",
")",
")",
"keys",
"=",
"list",
"(",
"ma... | Creates a "key function" based on given keys.
Resulting function will perform lookup using specified keys, in order,
on the object passed to it as an argument.
For example, ``key_func('a', 'b')(foo)`` is equivalent to ``foo['a']['b']``.
:param keys: Lookup keys
:param default: Optional keyword arg... | [
"Creates",
"a",
"key",
"function",
"based",
"on",
"given",
"keys",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/functions.py#L134-L170 | train |
adamziel/python_translate | python_translate/utils.py | find_files | def find_files(path, patterns):
"""
Returns all files from a given path that matches the pattern or list
of patterns
@type path: str
@param path: A path to traverse
@typ patterns: str|list
@param patterns: A pattern or a list of patterns to match
@rtype: list[str]:
@return: A list... | python | def find_files(path, patterns):
"""
Returns all files from a given path that matches the pattern or list
of patterns
@type path: str
@param path: A path to traverse
@typ patterns: str|list
@param patterns: A pattern or a list of patterns to match
@rtype: list[str]:
@return: A list... | [
"def",
"find_files",
"(",
"path",
",",
"patterns",
")",
":",
"if",
"not",
"isinstance",
"(",
"patterns",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"patterns",
"=",
"[",
"patterns",
"]",
"matches",
"=",
"[",
"]",
"for",
"root",
",",
"dirnames",
... | Returns all files from a given path that matches the pattern or list
of patterns
@type path: str
@param path: A path to traverse
@typ patterns: str|list
@param patterns: A pattern or a list of patterns to match
@rtype: list[str]:
@return: A list of matched files | [
"Returns",
"all",
"files",
"from",
"a",
"given",
"path",
"that",
"matches",
"the",
"pattern",
"or",
"list",
"of",
"patterns"
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/utils.py#L18-L40 | train |
adamziel/python_translate | python_translate/utils.py | recursive_update | def recursive_update(_dict, _update):
"""
Same as dict.update, but updates also nested dicts instead of
overriding then
@type _dict: A
@param _dict: dict to apply update to
@type _update: A
@param _update: dict to pick update data from
@return:
"""
for k, v in _update.items():... | python | def recursive_update(_dict, _update):
"""
Same as dict.update, but updates also nested dicts instead of
overriding then
@type _dict: A
@param _dict: dict to apply update to
@type _update: A
@param _update: dict to pick update data from
@return:
"""
for k, v in _update.items():... | [
"def",
"recursive_update",
"(",
"_dict",
",",
"_update",
")",
":",
"for",
"k",
",",
"v",
"in",
"_update",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"collections",
".",
"Mapping",
")",
":",
"r",
"=",
"recursive_update",
"(",
"_di... | Same as dict.update, but updates also nested dicts instead of
overriding then
@type _dict: A
@param _dict: dict to apply update to
@type _update: A
@param _update: dict to pick update data from
@return: | [
"Same",
"as",
"dict",
".",
"update",
"but",
"updates",
"also",
"nested",
"dicts",
"instead",
"of",
"overriding",
"then"
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/utils.py#L43-L62 | train |
UMIACS/qav | qav/validators.py | Validator.validate | def validate(self, value):
'''The most basic validation'''
if not self.blank and value == '':
self.error_message = 'Can not be empty. Please provide a value.'
return False
self._choice = value
return True | python | def validate(self, value):
'''The most basic validation'''
if not self.blank and value == '':
self.error_message = 'Can not be empty. Please provide a value.'
return False
self._choice = value
return True | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"blank",
"and",
"value",
"==",
"''",
":",
"self",
".",
"error_message",
"=",
"'Can not be empty. Please provide a value.'",
"return",
"False",
"self",
".",
"_choice",
"=",
"va... | The most basic validation | [
"The",
"most",
"basic",
"validation"
] | f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/validators.py#L42-L48 | train |
UMIACS/qav | qav/validators.py | DomainNameValidator.validate | def validate(self, value):
"""Attempts a forward lookup via the socket library and if
successful will try to do a reverse lookup to verify DNS
is returning both lookups.
"""
if '.' not in value:
self.error_message = '%s is not a fully qualified domain name.' ... | python | def validate(self, value):
"""Attempts a forward lookup via the socket library and if
successful will try to do a reverse lookup to verify DNS
is returning both lookups.
"""
if '.' not in value:
self.error_message = '%s is not a fully qualified domain name.' ... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"'.'",
"not",
"in",
"value",
":",
"self",
".",
"error_message",
"=",
"'%s is not a fully qualified domain name.'",
"%",
"value",
"return",
"False",
"try",
":",
"ipaddress",
"=",
"socket",
".",
"ge... | Attempts a forward lookup via the socket library and if
successful will try to do a reverse lookup to verify DNS
is returning both lookups. | [
"Attempts",
"a",
"forward",
"lookup",
"via",
"the",
"socket",
"library",
"and",
"if",
"successful",
"will",
"try",
"to",
"do",
"a",
"reverse",
"lookup",
"to",
"verify",
"DNS",
"is",
"returning",
"both",
"lookups",
"."
] | f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/validators.py#L125-L147 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.