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
The-Politico/politico-civic-election-night
electionnight/viewsets/office.py
OfficeMixin.get_queryset
def get_queryset(self): """ Returns a queryset of all executive offices holding an election on a date. """ try: date = ElectionDay.objects.get(date=self.kwargs['date']) except Exception: raise APIException( 'No elections on {}.'.for...
python
def get_queryset(self): """ Returns a queryset of all executive offices holding an election on a date. """ try: date = ElectionDay.objects.get(date=self.kwargs['date']) except Exception: raise APIException( 'No elections on {}.'.for...
[ "def", "get_queryset", "(", "self", ")", ":", "try", ":", "date", "=", "ElectionDay", ".", "objects", ".", "get", "(", "date", "=", "self", ".", "kwargs", "[", "'date'", "]", ")", "except", "Exception", ":", "raise", "APIException", "(", "'No elections o...
Returns a queryset of all executive offices holding an election on a date.
[ "Returns", "a", "queryset", "of", "all", "executive", "offices", "holding", "an", "election", "on", "a", "date", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/viewsets/office.py#L9-L25
train
tjcsl/cslbot
cslbot/commands/slap.py
cmd
def cmd(send, msg, args): """Slap somebody. Syntax: {command} <nick> [for <reason>] """ implements = ['the golden gate bridge', 'a large trout', 'a clue-by-four', 'a fresh haddock', 'moon', 'an Itanium', 'fwilson', 'a wombat'] methods = ['around a bit', 'upside the head'] if not msg: c...
python
def cmd(send, msg, args): """Slap somebody. Syntax: {command} <nick> [for <reason>] """ implements = ['the golden gate bridge', 'a large trout', 'a clue-by-four', 'a fresh haddock', 'moon', 'an Itanium', 'fwilson', 'a wombat'] methods = ['around a bit', 'upside the head'] if not msg: c...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "implements", "=", "[", "'the golden gate bridge'", ",", "'a large trout'", ",", "'a clue-by-four'", ",", "'a fresh haddock'", ",", "'moon'", ",", "'an Itanium'", ",", "'fwilson'", ",", "'a wombat'", ...
Slap somebody. Syntax: {command} <nick> [for <reason>]
[ "Slap", "somebody", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/slap.py#L24-L84
train
tjcsl/cslbot
cslbot/commands/nicks.py
cmd
def cmd(send, msg, args): """Gets previous nicks. Syntax: {command} <nick> """ if not msg: with args['handler'].data_lock: users = list(args['handler'].channels[args['target']].users()) if args['target'] != 'private' else [args['nick']] msg = choice(users) chain = get_c...
python
def cmd(send, msg, args): """Gets previous nicks. Syntax: {command} <nick> """ if not msg: with args['handler'].data_lock: users = list(args['handler'].channels[args['target']].users()) if args['target'] != 'private' else [args['nick']] msg = choice(users) chain = get_c...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "with", "args", "[", "'handler'", "]", ".", "data_lock", ":", "users", "=", "list", "(", "args", "[", "'handler'", "]", ".", "channels", "[", "args", "[", "'ta...
Gets previous nicks. Syntax: {command} <nick>
[ "Gets", "previous", "nicks", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/nicks.py#L25-L39
train
asphalt-framework/asphalt-sqlalchemy
asphalt/sqlalchemy/utils.py
clear_database
def clear_database(engine: Connectable, schemas: Iterable[str] = ()) -> None: """ Clear any tables from an existing database. :param engine: the engine or connection to use :param schemas: full list of schema names to expect (ignored for SQLite) """ assert check_argument_types() metadatas ...
python
def clear_database(engine: Connectable, schemas: Iterable[str] = ()) -> None: """ Clear any tables from an existing database. :param engine: the engine or connection to use :param schemas: full list of schema names to expect (ignored for SQLite) """ assert check_argument_types() metadatas ...
[ "def", "clear_database", "(", "engine", ":", "Connectable", ",", "schemas", ":", "Iterable", "[", "str", "]", "=", "(", ")", ")", "->", "None", ":", "assert", "check_argument_types", "(", ")", "metadatas", "=", "[", "]", "all_schemas", "=", "(", "None", ...
Clear any tables from an existing database. :param engine: the engine or connection to use :param schemas: full list of schema names to expect (ignored for SQLite)
[ "Clear", "any", "tables", "from", "an", "existing", "database", "." ]
5abb7d9977ee92299359b76496ff34624421de05
https://github.com/asphalt-framework/asphalt-sqlalchemy/blob/5abb7d9977ee92299359b76496ff34624421de05/asphalt/sqlalchemy/utils.py#L8-L27
train
tjcsl/cslbot
cslbot/commands/inspect.py
cmd
def cmd(send, msg, args): """'Inspects a bot attribute. Syntax: {command} <attr> """ if not hasattr(args['handler'], msg): send("That attribute was not found in the handler.") return send(str(getattr(args['handler'], msg)))
python
def cmd(send, msg, args): """'Inspects a bot attribute. Syntax: {command} <attr> """ if not hasattr(args['handler'], msg): send("That attribute was not found in the handler.") return send(str(getattr(args['handler'], msg)))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "hasattr", "(", "args", "[", "'handler'", "]", ",", "msg", ")", ":", "send", "(", "\"That attribute was not found in the handler.\"", ")", "return", "send", "(", "str", "(", "geta...
Inspects a bot attribute. Syntax: {command} <attr>
[ "Inspects", "a", "bot", "attribute", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/inspect.py#L22-L31
train
tjcsl/cslbot
cslbot/commands/s.py
cmd
def cmd(send, msg, args): """Corrects a previous message. Syntax: {command}/<msg>/<replacement>/<ig|nick> """ if not msg: send("Invalid Syntax.") return char = msg[0] msg = [x.replace(r'\/', '/') for x in re.split(r'(?<!\\)\%s' % char, msg[1:], maxsplit=2)] # fix for people...
python
def cmd(send, msg, args): """Corrects a previous message. Syntax: {command}/<msg>/<replacement>/<ig|nick> """ if not msg: send("Invalid Syntax.") return char = msg[0] msg = [x.replace(r'\/', '/') for x in re.split(r'(?<!\\)\%s' % char, msg[1:], maxsplit=2)] # fix for people...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "send", "(", "\"Invalid Syntax.\"", ")", "return", "char", "=", "msg", "[", "0", "]", "msg", "=", "[", "x", ".", "replace", "(", "r'\\/'", ",", "'/'", ")", "...
Corrects a previous message. Syntax: {command}/<msg>/<replacement>/<ig|nick>
[ "Corrects", "a", "previous", "message", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/s.py#L80-L124
train
JoeVirtual/KonFoo
konfoo/core.py
Stream.resize
def resize(self, size): """ Re-sizes the `Stream` field by appending zero bytes or removing bytes from the end. :param int size: `Stream` size in number of bytes. """ count = max(int(size), 0) - len(self) if count == 0: pass elif -count == len(self):...
python
def resize(self, size): """ Re-sizes the `Stream` field by appending zero bytes or removing bytes from the end. :param int size: `Stream` size in number of bytes. """ count = max(int(size), 0) - len(self) if count == 0: pass elif -count == len(self):...
[ "def", "resize", "(", "self", ",", "size", ")", ":", "count", "=", "max", "(", "int", "(", "size", ")", ",", "0", ")", "-", "len", "(", "self", ")", "if", "count", "==", "0", ":", "pass", "elif", "-", "count", "==", "len", "(", "self", ")", ...
Re-sizes the `Stream` field by appending zero bytes or removing bytes from the end. :param int size: `Stream` size in number of bytes.
[ "Re", "-", "sizes", "the", "Stream", "field", "by", "appending", "zero", "bytes", "or", "removing", "bytes", "from", "the", "end", "." ]
0c62ef5c2bed4deaf908b34082e4de2544532fdc
https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L2064-L2082
train
JoeVirtual/KonFoo
konfoo/core.py
String.value
def value(self): """ Field value as an ascii encoded string.""" length = self._value.find(b'\x00') if length >= 0: return self._value[:length].decode('ascii') else: return self._value.decode('ascii')
python
def value(self): """ Field value as an ascii encoded string.""" length = self._value.find(b'\x00') if length >= 0: return self._value[:length].decode('ascii') else: return self._value.decode('ascii')
[ "def", "value", "(", "self", ")", ":", "length", "=", "self", ".", "_value", ".", "find", "(", "b'\\x00'", ")", "if", "length", ">=", "0", ":", "return", "self", ".", "_value", "[", ":", "length", "]", ".", "decode", "(", "'ascii'", ")", "else", ...
Field value as an ascii encoded string.
[ "Field", "value", "as", "an", "ascii", "encoded", "string", "." ]
0c62ef5c2bed4deaf908b34082e4de2544532fdc
https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L2188-L2194
train
JoeVirtual/KonFoo
konfoo/core.py
Decimal._set_alignment
def _set_alignment(self, group_size, bit_offset=0, auto_align=False): """ Sets the alignment of the ``Decimal`` field. :param int group_size: size of the aligned `Field` group in bytes, can be between ``1`` and ``8``. :param int bit_offset: bit offset of the `Decimal` field within t...
python
def _set_alignment(self, group_size, bit_offset=0, auto_align=False): """ Sets the alignment of the ``Decimal`` field. :param int group_size: size of the aligned `Field` group in bytes, can be between ``1`` and ``8``. :param int bit_offset: bit offset of the `Decimal` field within t...
[ "def", "_set_alignment", "(", "self", ",", "group_size", ",", "bit_offset", "=", "0", ",", "auto_align", "=", "False", ")", ":", "field_offset", "=", "int", "(", "bit_offset", ")", "if", "auto_align", ":", "field_size", ",", "bit_offset", "=", "divmod", "(...
Sets the alignment of the ``Decimal`` field. :param int group_size: size of the aligned `Field` group in bytes, can be between ``1`` and ``8``. :param int bit_offset: bit offset of the `Decimal` field within the aligned `Field` group, can be between ``0`` and ``63``. :pa...
[ "Sets", "the", "alignment", "of", "the", "Decimal", "field", "." ]
0c62ef5c2bed4deaf908b34082e4de2544532fdc
https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L2647-L2690
train
JoeVirtual/KonFoo
konfoo/core.py
Enum.value
def value(self): """ Field value as an enum name string. Fall back is an unsigned integer number.""" if self._enum and issubclass(self._enum, Enumeration): name = self._enum.get_name(self._value) if name: return name return self._value
python
def value(self): """ Field value as an enum name string. Fall back is an unsigned integer number.""" if self._enum and issubclass(self._enum, Enumeration): name = self._enum.get_name(self._value) if name: return name return self._value
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "_enum", "and", "issubclass", "(", "self", ".", "_enum", ",", "Enumeration", ")", ":", "name", "=", "self", ".", "_enum", ".", "get_name", "(", "self", ".", "_value", ")", "if", "name", ":",...
Field value as an enum name string. Fall back is an unsigned integer number.
[ "Field", "value", "as", "an", "enum", "name", "string", ".", "Fall", "back", "is", "an", "unsigned", "integer", "number", "." ]
0c62ef5c2bed4deaf908b34082e4de2544532fdc
https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L3761-L3767
train
shapiromatron/bmds
bmds/datasets.py
DichotomousDataset.to_dict
def to_dict(self): """ Returns a dictionary representation of the dataset. """ d = dict(doses=self.doses, ns=self.ns, incidences=self.incidences) d.update(self.kwargs) return d
python
def to_dict(self): """ Returns a dictionary representation of the dataset. """ d = dict(doses=self.doses, ns=self.ns, incidences=self.incidences) d.update(self.kwargs) return d
[ "def", "to_dict", "(", "self", ")", ":", "d", "=", "dict", "(", "doses", "=", "self", ".", "doses", ",", "ns", "=", "self", ".", "ns", ",", "incidences", "=", "self", ".", "incidences", ")", "d", ".", "update", "(", "self", ".", "kwargs", ")", ...
Returns a dictionary representation of the dataset.
[ "Returns", "a", "dictionary", "representation", "of", "the", "dataset", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L136-L142
train
shapiromatron/bmds
bmds/datasets.py
DichotomousDataset._calculate_plotting
def _calculate_plotting(n, incidence): """ Add confidence intervals to dichotomous datasets. From bmds231_manual.pdf, pg 124-5. LL = {(2np + z2 - 1) - z*sqrt[z2 - (2+1/n) + 4p(nq+1)]}/[2*(n+z2)] UL = {(2np + z2 + 1) + z*sqrt[z2 + (2-1/n) + 4p(nq-1)]}/[2*(n+z2)] - p = the observ...
python
def _calculate_plotting(n, incidence): """ Add confidence intervals to dichotomous datasets. From bmds231_manual.pdf, pg 124-5. LL = {(2np + z2 - 1) - z*sqrt[z2 - (2+1/n) + 4p(nq+1)]}/[2*(n+z2)] UL = {(2np + z2 + 1) + z*sqrt[z2 + (2-1/n) + 4p(nq-1)]}/[2*(n+z2)] - p = the observ...
[ "def", "_calculate_plotting", "(", "n", ",", "incidence", ")", ":", "p", "=", "incidence", "/", "float", "(", "n", ")", "z", "=", "stats", ".", "norm", ".", "ppf", "(", "0.975", ")", "q", "=", "1.", "-", "p", "ll", "=", "(", "(", "2", "*", "n...
Add confidence intervals to dichotomous datasets. From bmds231_manual.pdf, pg 124-5. LL = {(2np + z2 - 1) - z*sqrt[z2 - (2+1/n) + 4p(nq+1)]}/[2*(n+z2)] UL = {(2np + z2 + 1) + z*sqrt[z2 + (2-1/n) + 4p(nq-1)]}/[2*(n+z2)] - p = the observed proportion - n = the total number in the group i...
[ "Add", "confidence", "intervals", "to", "dichotomous", "datasets", ".", "From", "bmds231_manual", ".", "pdf", "pg", "124", "-", "5", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L145-L171
train
marrow/util
marrow/util/context/__init__.py
cd
def cd(path, on=os): """Change the current working directory within this context. Preserves the previous working directory and can be applied to remote connections that offer @getcwd@ and @chdir@ methods using the @on@ argument. """ original = on.getcwd() on.chdir(path) yi...
python
def cd(path, on=os): """Change the current working directory within this context. Preserves the previous working directory and can be applied to remote connections that offer @getcwd@ and @chdir@ methods using the @on@ argument. """ original = on.getcwd() on.chdir(path) yi...
[ "def", "cd", "(", "path", ",", "on", "=", "os", ")", ":", "original", "=", "on", ".", "getcwd", "(", ")", "on", ".", "chdir", "(", "path", ")", "yield", "on", ".", "chdir", "(", "original", ")" ]
Change the current working directory within this context. Preserves the previous working directory and can be applied to remote connections that offer @getcwd@ and @chdir@ methods using the @on@ argument.
[ "Change", "the", "current", "working", "directory", "within", "this", "context", ".", "Preserves", "the", "previous", "working", "directory", "and", "can", "be", "applied", "to", "remote", "connections", "that", "offer" ]
abb8163dbd1fa0692d42a44d129b12ae2b39cdf2
https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/context/__init__.py#L13-L26
train
textbook/atmdb
atmdb/core.py
Service.url_builder
def url_builder(self, endpoint, *, root=None, params=None, url_params=None): """Create a URL for the specified endpoint. Arguments: endpoint (:py:class:`str`): The API endpoint to access. root: (:py:class:`str`, optional): The root URL for the service API. para...
python
def url_builder(self, endpoint, *, root=None, params=None, url_params=None): """Create a URL for the specified endpoint. Arguments: endpoint (:py:class:`str`): The API endpoint to access. root: (:py:class:`str`, optional): The root URL for the service API. para...
[ "def", "url_builder", "(", "self", ",", "endpoint", ",", "*", ",", "root", "=", "None", ",", "params", "=", "None", ",", "url_params", "=", "None", ")", ":", "if", "root", "is", "None", ":", "root", "=", "self", ".", "ROOT", "return", "''", ".", ...
Create a URL for the specified endpoint. Arguments: endpoint (:py:class:`str`): The API endpoint to access. root: (:py:class:`str`, optional): The root URL for the service API. params: (:py:class:`dict`, optional): The values for format into the created URL...
[ "Create", "a", "URL", "for", "the", "specified", "endpoint", "." ]
cab14547d2e777a1e26c2560266365c484855789
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L40-L62
train
textbook/atmdb
atmdb/core.py
TokenAuthMixin.from_env
def from_env(cls): """Create a service instance from an environment variable.""" token = getenv(cls.TOKEN_ENV_VAR) if token is None: msg = 'missing environment variable: {!r}'.format(cls.TOKEN_ENV_VAR) raise ValueError(msg) return cls(api_token=token)
python
def from_env(cls): """Create a service instance from an environment variable.""" token = getenv(cls.TOKEN_ENV_VAR) if token is None: msg = 'missing environment variable: {!r}'.format(cls.TOKEN_ENV_VAR) raise ValueError(msg) return cls(api_token=token)
[ "def", "from_env", "(", "cls", ")", ":", "token", "=", "getenv", "(", "cls", ".", "TOKEN_ENV_VAR", ")", "if", "token", "is", "None", ":", "msg", "=", "'missing environment variable: {!r}'", ".", "format", "(", "cls", ".", "TOKEN_ENV_VAR", ")", "raise", "Va...
Create a service instance from an environment variable.
[ "Create", "a", "service", "instance", "from", "an", "environment", "variable", "." ]
cab14547d2e777a1e26c2560266365c484855789
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L104-L110
train
textbook/atmdb
atmdb/core.py
UrlParamMixin.url_builder
def url_builder(self, endpoint, params=None, url_params=None): """Add authentication URL parameter.""" if url_params is None: url_params = OrderedDict() url_params[self.AUTH_PARAM] = self.api_token return super().url_builder( endpoint, params=params, ...
python
def url_builder(self, endpoint, params=None, url_params=None): """Add authentication URL parameter.""" if url_params is None: url_params = OrderedDict() url_params[self.AUTH_PARAM] = self.api_token return super().url_builder( endpoint, params=params, ...
[ "def", "url_builder", "(", "self", ",", "endpoint", ",", "params", "=", "None", ",", "url_params", "=", "None", ")", ":", "if", "url_params", "is", "None", ":", "url_params", "=", "OrderedDict", "(", ")", "url_params", "[", "self", ".", "AUTH_PARAM", "]"...
Add authentication URL parameter.
[ "Add", "authentication", "URL", "parameter", "." ]
cab14547d2e777a1e26c2560266365c484855789
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L119-L128
train
tjcsl/cslbot
cslbot/commands/reddit.py
cmd
def cmd(send, msg, args): """Gets a random Reddit post. Syntax: {command} [subreddit] """ if msg and not check_exists(msg): send("Non-existant subreddit.") return subreddit = msg if msg else None send(random_post(subreddit, args['config']['api']['bitlykey']))
python
def cmd(send, msg, args): """Gets a random Reddit post. Syntax: {command} [subreddit] """ if msg and not check_exists(msg): send("Non-existant subreddit.") return subreddit = msg if msg else None send(random_post(subreddit, args['config']['api']['bitlykey']))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "msg", "and", "not", "check_exists", "(", "msg", ")", ":", "send", "(", "\"Non-existant subreddit.\"", ")", "return", "subreddit", "=", "msg", "if", "msg", "else", "None", "send", "(",...
Gets a random Reddit post. Syntax: {command} [subreddit]
[ "Gets", "a", "random", "Reddit", "post", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/reddit.py#L23-L33
train
tjcsl/cslbot
cslbot/commands/choose.py
cmd
def cmd(send, msg, args): """Chooses between multiple choices. Syntax: {command} <object> or <object> (or <object>...) """ if not msg: send("Choose what?") return choices = msg.split(' or ') action = [ 'draws a slip of paper from a hat and gets...', 'says eenie, menie, ...
python
def cmd(send, msg, args): """Chooses between multiple choices. Syntax: {command} <object> or <object> (or <object>...) """ if not msg: send("Choose what?") return choices = msg.split(' or ') action = [ 'draws a slip of paper from a hat and gets...', 'says eenie, menie, ...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "send", "(", "\"Choose what?\"", ")", "return", "choices", "=", "msg", ".", "split", "(", "' or '", ")", "action", "=", "[", "'draws a slip of paper from a hat and gets....
Chooses between multiple choices. Syntax: {command} <object> or <object> (or <object>...)
[ "Chooses", "between", "multiple", "choices", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/choose.py#L24-L38
train
tjcsl/cslbot
cslbot/commands/pester.py
cmd
def cmd(send, msg, args): """Pesters somebody. Syntax: {command} <nick> <message> """ if not msg or len(msg.split()) < 2: send("Pester needs at least two arguments.") return match = re.match('(%s+) (.*)' % args['config']['core']['nickregex'], msg) if match: message = ma...
python
def cmd(send, msg, args): """Pesters somebody. Syntax: {command} <nick> <message> """ if not msg or len(msg.split()) < 2: send("Pester needs at least two arguments.") return match = re.match('(%s+) (.*)' % args['config']['core']['nickregex'], msg) if match: message = ma...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", "or", "len", "(", "msg", ".", "split", "(", ")", ")", "<", "2", ":", "send", "(", "\"Pester needs at least two arguments.\"", ")", "return", "match", "=", "re", ".", ...
Pesters somebody. Syntax: {command} <nick> <message>
[ "Pesters", "somebody", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/pester.py#L24-L38
train
shapiromatron/bmds
bmds/session.py
BMDS.get_model
def get_model(cls, version, model_name): """ Return BMDS model class given BMDS version and model-name. """ models = cls.versions[version].model_options for keystore in models.values(): if model_name in keystore: return keystore[model_name] rai...
python
def get_model(cls, version, model_name): """ Return BMDS model class given BMDS version and model-name. """ models = cls.versions[version].model_options for keystore in models.values(): if model_name in keystore: return keystore[model_name] rai...
[ "def", "get_model", "(", "cls", ",", "version", ",", "model_name", ")", ":", "models", "=", "cls", ".", "versions", "[", "version", "]", ".", "model_options", "for", "keystore", "in", "models", ".", "values", "(", ")", ":", "if", "model_name", "in", "k...
Return BMDS model class given BMDS version and model-name.
[ "Return", "BMDS", "model", "class", "given", "BMDS", "version", "and", "model", "-", "name", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/session.py#L37-L45
train
shapiromatron/bmds
bmds/session.py
BMDS._add_to_to_ordered_dict
def _add_to_to_ordered_dict(self, d, dataset_index, recommended_only=False): """ Save a session to an ordered dictionary. In some cases, a single session may include a final session, as well as other BMDS executions where doses were dropped. This will include all sessions. """ ...
python
def _add_to_to_ordered_dict(self, d, dataset_index, recommended_only=False): """ Save a session to an ordered dictionary. In some cases, a single session may include a final session, as well as other BMDS executions where doses were dropped. This will include all sessions. """ ...
[ "def", "_add_to_to_ordered_dict", "(", "self", ",", "d", ",", "dataset_index", ",", "recommended_only", "=", "False", ")", ":", "if", "self", ".", "doses_dropped_sessions", ":", "for", "key", "in", "sorted", "(", "list", "(", "self", ".", "doses_dropped_sessio...
Save a session to an ordered dictionary. In some cases, a single session may include a final session, as well as other BMDS executions where doses were dropped. This will include all sessions.
[ "Save", "a", "session", "to", "an", "ordered", "dictionary", ".", "In", "some", "cases", "a", "single", "session", "may", "include", "a", "final", "session", "as", "well", "as", "other", "BMDS", "executions", "where", "doses", "were", "dropped", ".", "This...
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/session.py#L226-L236
train
shapiromatron/bmds
bmds/session.py
BMDS._add_single_session_to_to_ordered_dict
def _add_single_session_to_to_ordered_dict(self, d, dataset_index, recommended_only): """ Save a single session to an ordered dictionary. """ for model_index, model in enumerate(self.models): # determine if model should be presented, or if a null-model should # be...
python
def _add_single_session_to_to_ordered_dict(self, d, dataset_index, recommended_only): """ Save a single session to an ordered dictionary. """ for model_index, model in enumerate(self.models): # determine if model should be presented, or if a null-model should # be...
[ "def", "_add_single_session_to_to_ordered_dict", "(", "self", ",", "d", ",", "dataset_index", ",", "recommended_only", ")", ":", "for", "model_index", ",", "model", "in", "enumerate", "(", "self", ".", "models", ")", ":", "show_null", "=", "False", "if", "reco...
Save a single session to an ordered dictionary.
[ "Save", "a", "single", "session", "to", "an", "ordered", "dictionary", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/session.py#L238-L265
train
shapiromatron/bmds
bmds/session.py
BMDS._group_models
def _group_models(self): """ If AIC and BMD are numeric and identical, then treat models as identical. Returns a list of lists. The outer list is a list of related models, the inner list contains each individual model, sorted by the number of parameters in ascending order. ...
python
def _group_models(self): """ If AIC and BMD are numeric and identical, then treat models as identical. Returns a list of lists. The outer list is a list of related models, the inner list contains each individual model, sorted by the number of parameters in ascending order. ...
[ "def", "_group_models", "(", "self", ")", ":", "od", "=", "OrderedDict", "(", ")", "for", "i", ",", "model", "in", "enumerate", "(", "self", ".", "models", ")", ":", "output", "=", "getattr", "(", "model", ",", "\"output\"", ",", "{", "}", ")", "if...
If AIC and BMD are numeric and identical, then treat models as identical. Returns a list of lists. The outer list is a list of related models, the inner list contains each individual model, sorted by the number of parameters in ascending order. This is required because in some cases, a ...
[ "If", "AIC", "and", "BMD", "are", "numeric", "and", "identical", "then", "treat", "models", "as", "identical", ".", "Returns", "a", "list", "of", "lists", ".", "The", "outer", "list", "is", "a", "list", "of", "related", "models", "the", "inner", "list", ...
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/session.py#L355-L394
train
rraadd88/rohan
rohan/dandage/io_nums.py
is_numeric
def is_numeric(obj): """ This detects whether an input object is numeric or not. :param obj: object to be tested. """ try: obj+obj, obj-obj, obj*obj, obj**obj, obj/obj except ZeroDivisionError: return True except Exception: return False else: return True
python
def is_numeric(obj): """ This detects whether an input object is numeric or not. :param obj: object to be tested. """ try: obj+obj, obj-obj, obj*obj, obj**obj, obj/obj except ZeroDivisionError: return True except Exception: return False else: return True
[ "def", "is_numeric", "(", "obj", ")", ":", "try", ":", "obj", "+", "obj", ",", "obj", "-", "obj", ",", "obj", "*", "obj", ",", "obj", "**", "obj", ",", "obj", "/", "obj", "except", "ZeroDivisionError", ":", "return", "True", "except", "Exception", ...
This detects whether an input object is numeric or not. :param obj: object to be tested.
[ "This", "detects", "whether", "an", "input", "object", "is", "numeric", "or", "not", "." ]
b0643a3582a2fffc0165ace69fb80880d92bfb10
https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_nums.py#L14-L27
train
tjcsl/cslbot
cslbot/hooks/scores.py
handle
def handle(send, msg, args): """Handles scores. If it's a ++ add one point unless the user is trying to promote themselves. Otherwise substract one point. """ session = args['db'] matches = re.findall(r"\b(?<!-)(%s{2,16})(\+\+|--)" % args['config']['core']['nickregex'], msg) if not matches...
python
def handle(send, msg, args): """Handles scores. If it's a ++ add one point unless the user is trying to promote themselves. Otherwise substract one point. """ session = args['db'] matches = re.findall(r"\b(?<!-)(%s{2,16})(\+\+|--)" % args['config']['core']['nickregex'], msg) if not matches...
[ "def", "handle", "(", "send", ",", "msg", ",", "args", ")", ":", "session", "=", "args", "[", "'db'", "]", "matches", "=", "re", ".", "findall", "(", "r\"\\b(?<!-)(%s{2,16})(\\+\\+|--)\"", "%", "args", "[", "'config'", "]", "[", "'core'", "]", "[", "'n...
Handles scores. If it's a ++ add one point unless the user is trying to promote themselves. Otherwise substract one point.
[ "Handles", "scores", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/hooks/scores.py#L25-L57
train
tjcsl/cslbot
cslbot/hooks/xkcd.py
handle
def handle(send, msg, args): """Implements several XKCD comics.""" output = textutils.gen_xkcd_sub(msg, True) if output is None: return if args['type'] == 'action': send("correction: * %s %s" % (args['nick'], output)) else: send("%s actually meant: %s" % (args['nick'], output...
python
def handle(send, msg, args): """Implements several XKCD comics.""" output = textutils.gen_xkcd_sub(msg, True) if output is None: return if args['type'] == 'action': send("correction: * %s %s" % (args['nick'], output)) else: send("%s actually meant: %s" % (args['nick'], output...
[ "def", "handle", "(", "send", ",", "msg", ",", "args", ")", ":", "output", "=", "textutils", ".", "gen_xkcd_sub", "(", "msg", ",", "True", ")", "if", "output", "is", "None", ":", "return", "if", "args", "[", "'type'", "]", "==", "'action'", ":", "s...
Implements several XKCD comics.
[ "Implements", "several", "XKCD", "comics", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/hooks/xkcd.py#L23-L31
train
tjcsl/cslbot
cslbot/commands/nuke.py
cmd
def cmd(send, msg, args): """Nukes somebody. Syntax: {command} <target> """ c, nick = args['handler'].connection, args['nick'] channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel'] if not msg: send("Nuke who?") return with args['hand...
python
def cmd(send, msg, args): """Nukes somebody. Syntax: {command} <target> """ c, nick = args['handler'].connection, args['nick'] channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel'] if not msg: send("Nuke who?") return with args['hand...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "c", ",", "nick", "=", "args", "[", "'handler'", "]", ".", "connection", ",", "args", "[", "'nick'", "]", "channel", "=", "args", "[", "'target'", "]", "if", "args", "[", "'target'", "...
Nukes somebody. Syntax: {command} <target>
[ "Nukes", "somebody", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/nuke.py#L23-L41
train
Xion/taipan
taipan/strings.py
trim
def trim(s, prefix=None, suffix=None, strict=False): """Trim a string, removing given prefix or suffix. :param s: String to trim :param prefix: Prefix to remove from ``s`` :param suffix: Suffix to remove from ``s`` :param strict: Whether the prefix or suffix must be present in ``s``. ...
python
def trim(s, prefix=None, suffix=None, strict=False): """Trim a string, removing given prefix or suffix. :param s: String to trim :param prefix: Prefix to remove from ``s`` :param suffix: Suffix to remove from ``s`` :param strict: Whether the prefix or suffix must be present in ``s``. ...
[ "def", "trim", "(", "s", ",", "prefix", "=", "None", ",", "suffix", "=", "None", ",", "strict", "=", "False", ")", ":", "ensure_string", "(", "s", ")", "has_prefix", "=", "prefix", "is", "not", "None", "has_suffix", "=", "suffix", "is", "not", "None"...
Trim a string, removing given prefix or suffix. :param s: String to trim :param prefix: Prefix to remove from ``s`` :param suffix: Suffix to remove from ``s`` :param strict: Whether the prefix or suffix must be present in ``s``. By default, if the infix is not found, function will si...
[ "Trim", "a", "string", "removing", "given", "prefix", "or", "suffix", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L82-L132
train
Xion/taipan
taipan/strings.py
join
def join(delimiter, iterable, **kwargs): """Returns a string which is a concatenation of strings in ``iterable``, separated by given ``delimiter``. :param delimiter: Delimiter to put between strings :param iterable: Iterable to join Optional keyword arguments control the exact joining strategy: ...
python
def join(delimiter, iterable, **kwargs): """Returns a string which is a concatenation of strings in ``iterable``, separated by given ``delimiter``. :param delimiter: Delimiter to put between strings :param iterable: Iterable to join Optional keyword arguments control the exact joining strategy: ...
[ "def", "join", "(", "delimiter", ",", "iterable", ",", "**", "kwargs", ")", ":", "ensure_string", "(", "delimiter", ")", "ensure_iterable", "(", "iterable", ")", "ensure_keyword_args", "(", "kwargs", ",", "optional", "=", "(", "'errors'", ",", "'with_'", ")"...
Returns a string which is a concatenation of strings in ``iterable``, separated by given ``delimiter``. :param delimiter: Delimiter to put between strings :param iterable: Iterable to join Optional keyword arguments control the exact joining strategy: :param errors: What to do with errone...
[ "Returns", "a", "string", "which", "is", "a", "concatenation", "of", "strings", "in", "iterable", "separated", "by", "given", "delimiter", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L188-L245
train
Xion/taipan
taipan/strings.py
camel_case
def camel_case(arg, capitalize=None): """Converts given text with whitespaces between words into equivalent camel-cased one. :param capitalize: Whether result will have first letter upper case (True), lower case (False), or left as is (None, default). :return: String turned into...
python
def camel_case(arg, capitalize=None): """Converts given text with whitespaces between words into equivalent camel-cased one. :param capitalize: Whether result will have first letter upper case (True), lower case (False), or left as is (None, default). :return: String turned into...
[ "def", "camel_case", "(", "arg", ",", "capitalize", "=", "None", ")", ":", "ensure_string", "(", "arg", ")", "if", "not", "arg", ":", "return", "arg", "words", "=", "split", "(", "arg", ")", "first_word", "=", "words", "[", "0", "]", "if", "len", "...
Converts given text with whitespaces between words into equivalent camel-cased one. :param capitalize: Whether result will have first letter upper case (True), lower case (False), or left as is (None, default). :return: String turned into camel-case "equivalent"
[ "Converts", "given", "text", "with", "whitespaces", "between", "words", "into", "equivalent", "camel", "-", "cased", "one", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L254-L278
train
Xion/taipan
taipan/strings.py
random
def random(length, chars=None): """Generates a random string. :param length: Length of the string to generate. This can be a numbe or a pair: ``(min_length, max_length)`` :param chars: String of characters to choose from """ if chars is None: chars = string.ascii_letters ...
python
def random(length, chars=None): """Generates a random string. :param length: Length of the string to generate. This can be a numbe or a pair: ``(min_length, max_length)`` :param chars: String of characters to choose from """ if chars is None: chars = string.ascii_letters ...
[ "def", "random", "(", "length", ",", "chars", "=", "None", ")", ":", "if", "chars", "is", "None", ":", "chars", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "else", ":", "ensure_string", "(", "chars", ")", "if", "not", "chars", ...
Generates a random string. :param length: Length of the string to generate. This can be a numbe or a pair: ``(min_length, max_length)`` :param chars: String of characters to choose from
[ "Generates", "a", "random", "string", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L418-L442
train
Xion/taipan
taipan/strings.py
Replacer.with_
def with_(self, replacement): """Provide replacement for string "needles". :param replacement: Target replacement for needles given in constructor :return: The :class:`Replacement` object :raise TypeError: If ``replacement`` is not a string :raise ReplacementError: If replaceme...
python
def with_(self, replacement): """Provide replacement for string "needles". :param replacement: Target replacement for needles given in constructor :return: The :class:`Replacement` object :raise TypeError: If ``replacement`` is not a string :raise ReplacementError: If replaceme...
[ "def", "with_", "(", "self", ",", "replacement", ")", ":", "ensure_string", "(", "replacement", ")", "if", "is_mapping", "(", "self", ".", "_replacements", ")", ":", "raise", "ReplacementError", "(", "\"string replacements already provided\"", ")", "self", ".", ...
Provide replacement for string "needles". :param replacement: Target replacement for needles given in constructor :return: The :class:`Replacement` object :raise TypeError: If ``replacement`` is not a string :raise ReplacementError: If replacement has been already given
[ "Provide", "replacement", "for", "string", "needles", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L367-L381
train
Xion/taipan
taipan/strings.py
Replacer.in_
def in_(self, haystack): """Perform replacement in given string. :param haystack: String to perform replacements in :return: ``haystack`` after the replacements :raise TypeError: If ``haystack`` if not a string :raise ReplacementError: If no replacement(s) have been provided y...
python
def in_(self, haystack): """Perform replacement in given string. :param haystack: String to perform replacements in :return: ``haystack`` after the replacements :raise TypeError: If ``haystack`` if not a string :raise ReplacementError: If no replacement(s) have been provided y...
[ "def", "in_", "(", "self", ",", "haystack", ")", ":", "from", "taipan", ".", "collections", "import", "dicts", "ensure_string", "(", "haystack", ")", "if", "not", "is_mapping", "(", "self", ".", "_replacements", ")", ":", "raise", "ReplacementError", "(", ...
Perform replacement in given string. :param haystack: String to perform replacements in :return: ``haystack`` after the replacements :raise TypeError: If ``haystack`` if not a string :raise ReplacementError: If no replacement(s) have been provided yet
[ "Perform", "replacement", "in", "given", "string", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L383-L413
train
tylerbutler/engineer
engineer/util.py
wrap_list
def wrap_list(item): """ Returns an object as a list. If the object is a list, it is returned directly. If it is a tuple or set, it is returned as a list. If it is another object, it is wrapped in a list and returned. """ if item is None: return [] elif isinstance(item, list): ...
python
def wrap_list(item): """ Returns an object as a list. If the object is a list, it is returned directly. If it is a tuple or set, it is returned as a list. If it is another object, it is wrapped in a list and returned. """ if item is None: return [] elif isinstance(item, list): ...
[ "def", "wrap_list", "(", "item", ")", ":", "if", "item", "is", "None", ":", "return", "[", "]", "elif", "isinstance", "(", "item", ",", "list", ")", ":", "return", "item", "elif", "isinstance", "(", "item", ",", "(", "tuple", ",", "set", ")", ")", ...
Returns an object as a list. If the object is a list, it is returned directly. If it is a tuple or set, it is returned as a list. If it is another object, it is wrapped in a list and returned.
[ "Returns", "an", "object", "as", "a", "list", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/util.py#L228-L243
train
tylerbutler/engineer
engineer/util.py
update_additive
def update_additive(dict1, dict2): """ A utility method to update a dict or other mapping type with the contents of another dict. This method updates the contents of ``dict1``, overwriting any existing key/value pairs in ``dict1`` with the corresponding key/value pair in ``dict2``. If the value in ``di...
python
def update_additive(dict1, dict2): """ A utility method to update a dict or other mapping type with the contents of another dict. This method updates the contents of ``dict1``, overwriting any existing key/value pairs in ``dict1`` with the corresponding key/value pair in ``dict2``. If the value in ``di...
[ "def", "update_additive", "(", "dict1", ",", "dict2", ")", ":", "for", "key", ",", "value", "in", "dict2", ".", "items", "(", ")", ":", "if", "key", "not", "in", "dict1", ":", "dict1", "[", "key", "]", "=", "value", "else", ":", "if", "isinstance",...
A utility method to update a dict or other mapping type with the contents of another dict. This method updates the contents of ``dict1``, overwriting any existing key/value pairs in ``dict1`` with the corresponding key/value pair in ``dict2``. If the value in ``dict2`` is a mapping type itself, then ``upda...
[ "A", "utility", "method", "to", "update", "a", "dict", "or", "other", "mapping", "type", "with", "the", "contents", "of", "another", "dict", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/util.py#L366-L388
train
tylerbutler/engineer
engineer/util.py
diff_dir
def diff_dir(dir_cmp, left_path=True): """ A generator that, given a ``filecmp.dircmp`` object, yields the paths to all files that are different. Works recursively. :param dir_cmp: A ``filecmp.dircmp`` object representing the comparison. :param left_path: If ``True``, paths will be relative to dirc...
python
def diff_dir(dir_cmp, left_path=True): """ A generator that, given a ``filecmp.dircmp`` object, yields the paths to all files that are different. Works recursively. :param dir_cmp: A ``filecmp.dircmp`` object representing the comparison. :param left_path: If ``True``, paths will be relative to dirc...
[ "def", "diff_dir", "(", "dir_cmp", ",", "left_path", "=", "True", ")", ":", "for", "name", "in", "dir_cmp", ".", "diff_files", ":", "if", "left_path", ":", "path_root", "=", "dir_cmp", ".", "left", "else", ":", "path_root", "=", "dir_cmp", ".", "right", ...
A generator that, given a ``filecmp.dircmp`` object, yields the paths to all files that are different. Works recursively. :param dir_cmp: A ``filecmp.dircmp`` object representing the comparison. :param left_path: If ``True``, paths will be relative to dircmp.left. Else paths will be relative to dircmp.righ...
[ "A", "generator", "that", "given", "a", "filecmp", ".", "dircmp", "object", "yields", "the", "paths", "to", "all", "files", "that", "are", "different", ".", "Works", "recursively", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/util.py#L446-L463
train
VIVelev/PyDojoML
dojo/base/preprocessor.py
Preprocessor.get_params
def get_params(self, *keys): """Returns the specified parameters for the current preprocessor. Parameters: ----------- keys : variable sized list, containing the names of the requested parameters Returns: -------- values : list or dictionary, if any `keys` are s...
python
def get_params(self, *keys): """Returns the specified parameters for the current preprocessor. Parameters: ----------- keys : variable sized list, containing the names of the requested parameters Returns: -------- values : list or dictionary, if any `keys` are s...
[ "def", "get_params", "(", "self", ",", "*", "keys", ")", ":", "if", "len", "(", "keys", ")", "==", "0", ":", "return", "vars", "(", "self", ")", "else", ":", "return", "[", "vars", "(", "self", ")", "[", "k", "]", "for", "k", "in", "keys", "]...
Returns the specified parameters for the current preprocessor. Parameters: ----------- keys : variable sized list, containing the names of the requested parameters Returns: -------- values : list or dictionary, if any `keys` are specified those named parameters'...
[ "Returns", "the", "specified", "parameters", "for", "the", "current", "preprocessor", "." ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/base/preprocessor.py#L32-L50
train
shapiromatron/bmds
bmds/parser.py
OutputParser._import_single_searches
def _import_single_searches(self): """ Look for simple one-line regex searches common across dataset types. If failed, then return -999. AIC is only handled in this method for dichotomous continuous and exponential and handled via separate methods. """ searches ...
python
def _import_single_searches(self): """ Look for simple one-line regex searches common across dataset types. If failed, then return -999. AIC is only handled in this method for dichotomous continuous and exponential and handled via separate methods. """ searches ...
[ "def", "_import_single_searches", "(", "self", ")", ":", "searches", "=", "{", "\"BMD\"", ":", "r\"(?<!Setting )BMD = +(%s)\"", "%", "self", ".", "re_num", ",", "\"BMDL\"", ":", "r\"BMDL = +(%s)\"", "%", "self", ".", "re_num", ",", "\"BMDU\"", ":", "r\"BMDU = +(...
Look for simple one-line regex searches common across dataset types. If failed, then return -999. AIC is only handled in this method for dichotomous continuous and exponential and handled via separate methods.
[ "Look", "for", "simple", "one", "-", "line", "regex", "searches", "common", "across", "dataset", "types", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/parser.py#L175-L203
train
shapiromatron/bmds
bmds/parser.py
OutputParser._import_warnings
def _import_warnings(self): """ Add custom warnings found in output files. Warnings in output files are searched for using this method; if a warning is found then it will be appended to the warnings list. """ warnings = ( r"Warning: BMDL computation is at bes...
python
def _import_warnings(self): """ Add custom warnings found in output files. Warnings in output files are searched for using this method; if a warning is found then it will be appended to the warnings list. """ warnings = ( r"Warning: BMDL computation is at bes...
[ "def", "_import_warnings", "(", "self", ")", ":", "warnings", "=", "(", "r\"Warning: BMDL computation is at best imprecise for these data\"", ",", "r\"THE MODEL HAS PROBABLY NOT CONVERGED!!!\"", ",", "\"THIS USUALLY MEANS THE MODEL HAS NOT CONVERGED!\"", ",", "r\"BMR value is not in th...
Add custom warnings found in output files. Warnings in output files are searched for using this method; if a warning is found then it will be appended to the warnings list.
[ "Add", "custom", "warnings", "found", "in", "output", "files", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/parser.py#L205-L226
train
shapiromatron/bmds
bmds/parser.py
OutputParser._import_dich_vals
def _import_dich_vals(self): """ Import simple dichotomous values. Dichotomous values are found on one line, therefore one regex will return up to three possible matches for the Chi^2, degrees of freedom, and p-value. """ m = re.search( r"Chi\^2 = ({0...
python
def _import_dich_vals(self): """ Import simple dichotomous values. Dichotomous values are found on one line, therefore one regex will return up to three possible matches for the Chi^2, degrees of freedom, and p-value. """ m = re.search( r"Chi\^2 = ({0...
[ "def", "_import_dich_vals", "(", "self", ")", ":", "m", "=", "re", ".", "search", "(", "r\"Chi\\^2 = ({0}|\\w+) +d.f. = +({0}|\\w+) +P-value = +({0}|\\w+)\"", ".", "format", "(", "self", ".", "re_num", ")", ",", "self", ".", "output_text", ",", ")", "cw", "=", ...
Import simple dichotomous values. Dichotomous values are found on one line, therefore one regex will return up to three possible matches for the Chi^2, degrees of freedom, and p-value.
[ "Import", "simple", "dichotomous", "values", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/parser.py#L228-L247
train
JIC-CSB/jicimagelib
jicimagelib/transform.py
transformation
def transformation(func): """Function decorator to turn another function into a transformation.""" @wraps(func) def func_as_transformation(*args, **kwargs): # When using transforms that return new ndarrays we lose the # jicimagelib.image.Image type and the history of the image. ...
python
def transformation(func): """Function decorator to turn another function into a transformation.""" @wraps(func) def func_as_transformation(*args, **kwargs): # When using transforms that return new ndarrays we lose the # jicimagelib.image.Image type and the history of the image. ...
[ "def", "transformation", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "func_as_transformation", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "hasattr", "(", "args", "[", "0", "]", ",", "'history'", ")", ":", "history", "=",...
Function decorator to turn another function into a transformation.
[ "Function", "decorator", "to", "turn", "another", "function", "into", "a", "transformation", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/transform.py#L46-L83
train
JIC-CSB/jicimagelib
jicimagelib/transform.py
smooth_gaussian
def smooth_gaussian(image, sigma=1): """Returns Gaussian smoothed image. :param image: numpy array or :class:`jicimagelib.image.Image` :param sigma: standard deviation :returns: :class:`jicimagelib.image.Image` """ return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode="nearest")
python
def smooth_gaussian(image, sigma=1): """Returns Gaussian smoothed image. :param image: numpy array or :class:`jicimagelib.image.Image` :param sigma: standard deviation :returns: :class:`jicimagelib.image.Image` """ return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode="nearest")
[ "def", "smooth_gaussian", "(", "image", ",", "sigma", "=", "1", ")", ":", "return", "scipy", ".", "ndimage", ".", "filters", ".", "gaussian_filter", "(", "image", ",", "sigma", "=", "sigma", ",", "mode", "=", "\"nearest\"", ")" ]
Returns Gaussian smoothed image. :param image: numpy array or :class:`jicimagelib.image.Image` :param sigma: standard deviation :returns: :class:`jicimagelib.image.Image`
[ "Returns", "Gaussian", "smoothed", "image", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/transform.py#L109-L116
train
JIC-CSB/jicimagelib
jicimagelib/transform.py
equalize_adaptive_clahe
def equalize_adaptive_clahe(image, ntiles=8, clip_limit=0.01): """Return contrast limited adaptive histogram equalized image. The return value is normalised to the range 0 to 1. :param image: numpy array or :class:`jicimagelib.image.Image` of dtype float :param ntiles: number of tile regions :...
python
def equalize_adaptive_clahe(image, ntiles=8, clip_limit=0.01): """Return contrast limited adaptive histogram equalized image. The return value is normalised to the range 0 to 1. :param image: numpy array or :class:`jicimagelib.image.Image` of dtype float :param ntiles: number of tile regions :...
[ "def", "equalize_adaptive_clahe", "(", "image", ",", "ntiles", "=", "8", ",", "clip_limit", "=", "0.01", ")", ":", "skimage_float_im", "=", "normalise", "(", "image", ")", "if", "np", ".", "all", "(", "skimage_float_im", ")", ":", "raise", "(", "RuntimeErr...
Return contrast limited adaptive histogram equalized image. The return value is normalised to the range 0 to 1. :param image: numpy array or :class:`jicimagelib.image.Image` of dtype float :param ntiles: number of tile regions :param clip_limit: clipping limit in range 0 to 1, ...
[ "Return", "contrast", "limited", "adaptive", "histogram", "equalized", "image", ".", "The", "return", "value", "is", "normalised", "to", "the", "range", "0", "to", "1", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/transform.py#L120-L142
train
JIC-CSB/jicimagelib
jicimagelib/transform.py
threshold_otsu
def threshold_otsu(image, multiplier=1.0): """Return image thresholded using Otsu's method. """ otsu_value = skimage.filters.threshold_otsu(image) return image > otsu_value * multiplier
python
def threshold_otsu(image, multiplier=1.0): """Return image thresholded using Otsu's method. """ otsu_value = skimage.filters.threshold_otsu(image) return image > otsu_value * multiplier
[ "def", "threshold_otsu", "(", "image", ",", "multiplier", "=", "1.0", ")", ":", "otsu_value", "=", "skimage", ".", "filters", ".", "threshold_otsu", "(", "image", ")", "return", "image", ">", "otsu_value", "*", "multiplier" ]
Return image thresholded using Otsu's method.
[ "Return", "image", "thresholded", "using", "Otsu", "s", "method", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/transform.py#L146-L150
train
tjcsl/cslbot
cslbot/commands/version.py
cmd
def cmd(send, msg, args): """Check the git revison. Syntax: {command} [check|master] """ parser = arguments.ArgParser(args['config']) parser.add_argument('action', choices=['check', 'master', 'commit'], nargs='?') try: cmdargs = parser.parse_args(msg) except arguments.ArgumentExce...
python
def cmd(send, msg, args): """Check the git revison. Syntax: {command} [check|master] """ parser = arguments.ArgParser(args['config']) parser.add_argument('action', choices=['check', 'master', 'commit'], nargs='?') try: cmdargs = parser.parse_args(msg) except arguments.ArgumentExce...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "parser", "=", "arguments", ".", "ArgParser", "(", "args", "[", "'config'", "]", ")", "parser", ".", "add_argument", "(", "'action'", ",", "choices", "=", "[", "'check'", ",", "'master'", ...
Check the git revison. Syntax: {command} [check|master]
[ "Check", "the", "git", "revison", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/version.py#L25-L56
train
tjcsl/cslbot
cslbot/commands/next.py
cmd
def cmd(send, _, args): """Ships a product. Syntax: {command} """ send("%s! %s" % (args['name'].upper(), random.choice(squirrels)))
python
def cmd(send, _, args): """Ships a product. Syntax: {command} """ send("%s! %s" % (args['name'].upper(), random.choice(squirrels)))
[ "def", "cmd", "(", "send", ",", "_", ",", "args", ")", ":", "send", "(", "\"%s! %s\"", "%", "(", "args", "[", "'name'", "]", ".", "upper", "(", ")", ",", "random", ".", "choice", "(", "squirrels", ")", ")", ")" ]
Ships a product. Syntax: {command}
[ "Ships", "a", "product", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/next.py#L38-L44
train
CI-WATER/mapkit
mapkit/RasterConverter.py
RasterConverter.getAsGrassAsciiRaster
def getAsGrassAsciiRaster(self, tableName, rasterId=1, rasterIdFieldName='id', rasterFieldName='raster', newSRID=None): """ Returns a string representation of the raster in GRASS ASCII raster format. """ # Get raster in ArcInfo Grid format arcInfoGrid = self.getAsGdalRaster(raste...
python
def getAsGrassAsciiRaster(self, tableName, rasterId=1, rasterIdFieldName='id', rasterFieldName='raster', newSRID=None): """ Returns a string representation of the raster in GRASS ASCII raster format. """ # Get raster in ArcInfo Grid format arcInfoGrid = self.getAsGdalRaster(raste...
[ "def", "getAsGrassAsciiRaster", "(", "self", ",", "tableName", ",", "rasterId", "=", "1", ",", "rasterIdFieldName", "=", "'id'", ",", "rasterFieldName", "=", "'raster'", ",", "newSRID", "=", "None", ")", ":", "arcInfoGrid", "=", "self", ".", "getAsGdalRaster",...
Returns a string representation of the raster in GRASS ASCII raster format.
[ "Returns", "a", "string", "representation", "of", "the", "raster", "in", "GRASS", "ASCII", "raster", "format", "." ]
ce5fbded6af7adabdf1eec85631c6811ef8ecc34
https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L871-L930
train
CI-WATER/mapkit
mapkit/RasterConverter.py
RasterConverter.supportedGdalRasterFormats
def supportedGdalRasterFormats(cls, sqlAlchemyEngineOrSession): """ Return a list of the supported GDAL raster formats. """ if isinstance(sqlAlchemyEngineOrSession, Engine): # Create sqlalchemy session sessionMaker = sessionmaker(bind=sqlAlchemyEngineOrSession) ...
python
def supportedGdalRasterFormats(cls, sqlAlchemyEngineOrSession): """ Return a list of the supported GDAL raster formats. """ if isinstance(sqlAlchemyEngineOrSession, Engine): # Create sqlalchemy session sessionMaker = sessionmaker(bind=sqlAlchemyEngineOrSession) ...
[ "def", "supportedGdalRasterFormats", "(", "cls", ",", "sqlAlchemyEngineOrSession", ")", ":", "if", "isinstance", "(", "sqlAlchemyEngineOrSession", ",", "Engine", ")", ":", "sessionMaker", "=", "sessionmaker", "(", "bind", "=", "sqlAlchemyEngineOrSession", ")", "sessio...
Return a list of the supported GDAL raster formats.
[ "Return", "a", "list", "of", "the", "supported", "GDAL", "raster", "formats", "." ]
ce5fbded6af7adabdf1eec85631c6811ef8ecc34
https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L974-L995
train
CI-WATER/mapkit
mapkit/RasterConverter.py
RasterConverter.setColorRamp
def setColorRamp(self, colorRamp=None): """ Set the color ramp of the raster converter instance """ if not colorRamp: self._colorRamp = RasterConverter.setDefaultColorRamp(ColorRampEnum.COLOR_RAMP_HUE) else: self._colorRamp = colorRamp
python
def setColorRamp(self, colorRamp=None): """ Set the color ramp of the raster converter instance """ if not colorRamp: self._colorRamp = RasterConverter.setDefaultColorRamp(ColorRampEnum.COLOR_RAMP_HUE) else: self._colorRamp = colorRamp
[ "def", "setColorRamp", "(", "self", ",", "colorRamp", "=", "None", ")", ":", "if", "not", "colorRamp", ":", "self", ".", "_colorRamp", "=", "RasterConverter", ".", "setDefaultColorRamp", "(", "ColorRampEnum", ".", "COLOR_RAMP_HUE", ")", "else", ":", "self", ...
Set the color ramp of the raster converter instance
[ "Set", "the", "color", "ramp", "of", "the", "raster", "converter", "instance" ]
ce5fbded6af7adabdf1eec85631c6811ef8ecc34
https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L997-L1004
train
CI-WATER/mapkit
mapkit/RasterConverter.py
RasterConverter.setDefaultColorRamp
def setDefaultColorRamp(self, colorRampEnum=ColorRampEnum.COLOR_RAMP_HUE): """ Returns the color ramp as a list of RGB tuples """ self._colorRamp = ColorRampGenerator.generateDefaultColorRamp(colorRampEnum)
python
def setDefaultColorRamp(self, colorRampEnum=ColorRampEnum.COLOR_RAMP_HUE): """ Returns the color ramp as a list of RGB tuples """ self._colorRamp = ColorRampGenerator.generateDefaultColorRamp(colorRampEnum)
[ "def", "setDefaultColorRamp", "(", "self", ",", "colorRampEnum", "=", "ColorRampEnum", ".", "COLOR_RAMP_HUE", ")", ":", "self", ".", "_colorRamp", "=", "ColorRampGenerator", ".", "generateDefaultColorRamp", "(", "colorRampEnum", ")" ]
Returns the color ramp as a list of RGB tuples
[ "Returns", "the", "color", "ramp", "as", "a", "list", "of", "RGB", "tuples" ]
ce5fbded6af7adabdf1eec85631c6811ef8ecc34
https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L1006-L1010
train
CI-WATER/mapkit
mapkit/RasterConverter.py
RasterConverter.isNumber
def isNumber(self, value): """ Validate whether a value is a number or not """ try: str(value) float(value) return True except ValueError: return False
python
def isNumber(self, value): """ Validate whether a value is a number or not """ try: str(value) float(value) return True except ValueError: return False
[ "def", "isNumber", "(", "self", ",", "value", ")", ":", "try", ":", "str", "(", "value", ")", "float", "(", "value", ")", "return", "True", "except", "ValueError", ":", "return", "False" ]
Validate whether a value is a number or not
[ "Validate", "whether", "a", "value", "is", "a", "number", "or", "not" ]
ce5fbded6af7adabdf1eec85631c6811ef8ecc34
https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L1097-L1107
train
tjcsl/cslbot
cslbot/helpers/reddit.py
check_exists
def check_exists(subreddit): """Make sure that a subreddit actually exists.""" req = get('http://www.reddit.com/r/%s/about.json' % subreddit, headers={'User-Agent': 'CslBot/1.0'}) if req.json().get('kind') == 'Listing': # no subreddit exists, search results page is shown return False ret...
python
def check_exists(subreddit): """Make sure that a subreddit actually exists.""" req = get('http://www.reddit.com/r/%s/about.json' % subreddit, headers={'User-Agent': 'CslBot/1.0'}) if req.json().get('kind') == 'Listing': # no subreddit exists, search results page is shown return False ret...
[ "def", "check_exists", "(", "subreddit", ")", ":", "req", "=", "get", "(", "'http://www.reddit.com/r/%s/about.json'", "%", "subreddit", ",", "headers", "=", "{", "'User-Agent'", ":", "'CslBot/1.0'", "}", ")", "if", "req", ".", "json", "(", ")", ".", "get", ...
Make sure that a subreddit actually exists.
[ "Make", "sure", "that", "a", "subreddit", "actually", "exists", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/reddit.py#L25-L31
train
tjcsl/cslbot
cslbot/helpers/reddit.py
random_post
def random_post(subreddit, apikey): """Gets a random post from a subreddit and returns a title and shortlink to it.""" subreddit = '/r/random' if subreddit is None else '/r/%s' % subreddit urlstr = 'http://reddit.com%s/random?%s' % (subreddit, time.time()) url = get(urlstr, headers={'User-Agent': 'CslBo...
python
def random_post(subreddit, apikey): """Gets a random post from a subreddit and returns a title and shortlink to it.""" subreddit = '/r/random' if subreddit is None else '/r/%s' % subreddit urlstr = 'http://reddit.com%s/random?%s' % (subreddit, time.time()) url = get(urlstr, headers={'User-Agent': 'CslBo...
[ "def", "random_post", "(", "subreddit", ",", "apikey", ")", ":", "subreddit", "=", "'/r/random'", "if", "subreddit", "is", "None", "else", "'/r/%s'", "%", "subreddit", "urlstr", "=", "'http://reddit.com%s/random?%s'", "%", "(", "subreddit", ",", "time", ".", "...
Gets a random post from a subreddit and returns a title and shortlink to it.
[ "Gets", "a", "random", "post", "from", "a", "subreddit", "and", "returns", "a", "title", "and", "shortlink", "to", "it", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/reddit.py#L34-L39
train
acutesoftware/virtual-AI-simulator
vais/character.py
RefFile.parse_to_dict
def parse_to_dict(self): """ parse raw CSV into dictionary """ lst = [] with open(self.fname, 'r') as f: hdr = f.readline() self.hdrs = hdr.split(',') #print("self.hdrs = ", self.hdrs) for line in f: cols = line.spli...
python
def parse_to_dict(self): """ parse raw CSV into dictionary """ lst = [] with open(self.fname, 'r') as f: hdr = f.readline() self.hdrs = hdr.split(',') #print("self.hdrs = ", self.hdrs) for line in f: cols = line.spli...
[ "def", "parse_to_dict", "(", "self", ")", ":", "lst", "=", "[", "]", "with", "open", "(", "self", ".", "fname", ",", "'r'", ")", "as", "f", ":", "hdr", "=", "f", ".", "readline", "(", ")", "self", ".", "hdrs", "=", "hdr", ".", "split", "(", "...
parse raw CSV into dictionary
[ "parse", "raw", "CSV", "into", "dictionary" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L36-L57
train
acutesoftware/virtual-AI-simulator
vais/character.py
RefFile.get_random_choice
def get_random_choice(self): """ returns a random name from the class """ i = random.randint(0,len(self.dat)-1) return self.dat[i]['name']
python
def get_random_choice(self): """ returns a random name from the class """ i = random.randint(0,len(self.dat)-1) return self.dat[i]['name']
[ "def", "get_random_choice", "(", "self", ")", ":", "i", "=", "random", ".", "randint", "(", "0", ",", "len", "(", "self", ".", "dat", ")", "-", "1", ")", "return", "self", ".", "dat", "[", "i", "]", "[", "'name'", "]" ]
returns a random name from the class
[ "returns", "a", "random", "name", "from", "the", "class" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L59-L64
train
acutesoftware/virtual-AI-simulator
vais/character.py
CharacterCollection.random_stats
def random_stats(self, all_stats, race, ch_class): """ create random stats based on the characters class and race This looks up the tables from CharacterCollection to get base stats and applies a close random fit """ # create blank list of stats to be generated ...
python
def random_stats(self, all_stats, race, ch_class): """ create random stats based on the characters class and race This looks up the tables from CharacterCollection to get base stats and applies a close random fit """ # create blank list of stats to be generated ...
[ "def", "random_stats", "(", "self", ",", "all_stats", ",", "race", ",", "ch_class", ")", ":", "stats", "=", "[", "]", "res", "=", "{", "}", "for", "s", "in", "all_stats", ":", "stats", ".", "append", "(", "s", "[", "'stat'", "]", ")", "res", "[",...
create random stats based on the characters class and race This looks up the tables from CharacterCollection to get base stats and applies a close random fit
[ "create", "random", "stats", "based", "on", "the", "characters", "class", "and", "race", "This", "looks", "up", "the", "tables", "from", "CharacterCollection", "to", "get", "base", "stats", "and", "applies", "a", "close", "random", "fit" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L122-L153
train
acutesoftware/virtual-AI-simulator
vais/character.py
Character.load_from_file
def load_from_file(self, fname): """ OVERWRITES the current character object from stats in file """ with open(fname, 'r') as f: for line in f: k,v = line.split(' = ') self._parse_char_line_to_self(k,v)
python
def load_from_file(self, fname): """ OVERWRITES the current character object from stats in file """ with open(fname, 'r') as f: for line in f: k,v = line.split(' = ') self._parse_char_line_to_self(k,v)
[ "def", "load_from_file", "(", "self", ",", "fname", ")", ":", "with", "open", "(", "fname", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "k", ",", "v", "=", "line", ".", "split", "(", "' = '", ")", "self", ".", "_parse_char_lin...
OVERWRITES the current character object from stats in file
[ "OVERWRITES", "the", "current", "character", "object", "from", "stats", "in", "file" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L189-L196
train
acutesoftware/virtual-AI-simulator
vais/character.py
Character._parse_char_line_to_self
def _parse_char_line_to_self(self, k,v): """ takes a line from a saved file split into key and values and updates the appropriate self parameters of character. """ k = k.strip(' ').strip('\n') v = v.strip(' ').strip('\n') # print('_parse_char_line_to_self(self, k,v...
python
def _parse_char_line_to_self(self, k,v): """ takes a line from a saved file split into key and values and updates the appropriate self parameters of character. """ k = k.strip(' ').strip('\n') v = v.strip(' ').strip('\n') # print('_parse_char_line_to_self(self, k,v...
[ "def", "_parse_char_line_to_self", "(", "self", ",", "k", ",", "v", ")", ":", "k", "=", "k", ".", "strip", "(", "' '", ")", ".", "strip", "(", "'\\n'", ")", "v", "=", "v", ".", "strip", "(", "' '", ")", ".", "strip", "(", "'\\n'", ")", "if", ...
takes a line from a saved file split into key and values and updates the appropriate self parameters of character.
[ "takes", "a", "line", "from", "a", "saved", "file", "split", "into", "key", "and", "values", "and", "updates", "the", "appropriate", "self", "parameters", "of", "character", "." ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L198-L219
train
acutesoftware/virtual-AI-simulator
vais/character.py
Character.save_to_file
def save_to_file(self, fname): """ saves a characters data to file """ with open(fname, 'w') as f: f.write(str(self))
python
def save_to_file(self, fname): """ saves a characters data to file """ with open(fname, 'w') as f: f.write(str(self))
[ "def", "save_to_file", "(", "self", ",", "fname", ")", ":", "with", "open", "(", "fname", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "str", "(", "self", ")", ")" ]
saves a characters data to file
[ "saves", "a", "characters", "data", "to", "file" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L236-L241
train
acutesoftware/virtual-AI-simulator
vais/character.py
Character.copy
def copy(self): """ make an identical copy of the character """ return Character(self.name, self.race,self.ch_class, self.stats, self.skills, self.story, self.inventory)
python
def copy(self): """ make an identical copy of the character """ return Character(self.name, self.race,self.ch_class, self.stats, self.skills, self.story, self.inventory)
[ "def", "copy", "(", "self", ")", ":", "return", "Character", "(", "self", ".", "name", ",", "self", ".", "race", ",", "self", ".", "ch_class", ",", "self", ".", "stats", ",", "self", ".", "skills", ",", "self", ".", "story", ",", "self", ".", "in...
make an identical copy of the character
[ "make", "an", "identical", "copy", "of", "the", "character" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L243-L247
train
LukeB42/Window
window.py
palette
def palette(fg, bg=-1): """ Since curses only supports a finite amount of initialised colour pairs we memoise any selections you've made as an attribute on this function """ if not hasattr(palette, "counter"): palette.counter = 1 if not hasattr(palette, "selections"): palette.s...
python
def palette(fg, bg=-1): """ Since curses only supports a finite amount of initialised colour pairs we memoise any selections you've made as an attribute on this function """ if not hasattr(palette, "counter"): palette.counter = 1 if not hasattr(palette, "selections"): palette.s...
[ "def", "palette", "(", "fg", ",", "bg", "=", "-", "1", ")", ":", "if", "not", "hasattr", "(", "palette", ",", "\"counter\"", ")", ":", "palette", ".", "counter", "=", "1", "if", "not", "hasattr", "(", "palette", ",", "\"selections\"", ")", ":", "pa...
Since curses only supports a finite amount of initialised colour pairs we memoise any selections you've made as an attribute on this function
[ "Since", "curses", "only", "supports", "a", "finite", "amount", "of", "initialised", "colour", "pairs", "we", "memoise", "any", "selections", "you", "ve", "made", "as", "an", "attribute", "on", "this", "function" ]
6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62
https://github.com/LukeB42/Window/blob/6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62/window.py#L719-L750
train
LukeB42/Window
window.py
Window.start
def start(self): """ Window event loop """ self.window = _curses.initscr() _curses.savetty() _curses.start_color() _curses.use_default_colors() self.window.leaveok(1) _curses.raw() self.window.keypad(1) _curses.noecho() _cur...
python
def start(self): """ Window event loop """ self.window = _curses.initscr() _curses.savetty() _curses.start_color() _curses.use_default_colors() self.window.leaveok(1) _curses.raw() self.window.keypad(1) _curses.noecho() _cur...
[ "def", "start", "(", "self", ")", ":", "self", ".", "window", "=", "_curses", ".", "initscr", "(", ")", "_curses", ".", "savetty", "(", ")", "_curses", ".", "start_color", "(", ")", "_curses", ".", "use_default_colors", "(", ")", "self", ".", "window",...
Window event loop
[ "Window", "event", "loop" ]
6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62
https://github.com/LukeB42/Window/blob/6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62/window.py#L63-L87
train
LukeB42/Window
window.py
Window.stop
def stop(self): """ Restore the TTY to its original state. """ _curses.nocbreak() self.window.keypad(0) _curses.echo() _curses.resetty() _curses.endwin() self.running = False
python
def stop(self): """ Restore the TTY to its original state. """ _curses.nocbreak() self.window.keypad(0) _curses.echo() _curses.resetty() _curses.endwin() self.running = False
[ "def", "stop", "(", "self", ")", ":", "_curses", ".", "nocbreak", "(", ")", "self", ".", "window", ".", "keypad", "(", "0", ")", "_curses", ".", "echo", "(", ")", "_curses", ".", "resetty", "(", ")", "_curses", ".", "endwin", "(", ")", "self", "....
Restore the TTY to its original state.
[ "Restore", "the", "TTY", "to", "its", "original", "state", "." ]
6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62
https://github.com/LukeB42/Window/blob/6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62/window.py#L101-L110
train
LukeB42/Window
window.py
Window.coordinate
def coordinate(self, panes=[], index=0): """ Update pane coordinate tuples based on their height and width relative to other panes within the dimensions of the current window. We account for panes with a height of 1 where the bottom coordinates are the same as the top. Account f...
python
def coordinate(self, panes=[], index=0): """ Update pane coordinate tuples based on their height and width relative to other panes within the dimensions of the current window. We account for panes with a height of 1 where the bottom coordinates are the same as the top. Account f...
[ "def", "coordinate", "(", "self", ",", "panes", "=", "[", "]", ",", "index", "=", "0", ")", ":", "y", "=", "0", "for", "i", ",", "element", "in", "enumerate", "(", "self", ".", "panes", ")", ":", "x", "=", "0", "if", "isinstance", "(", "element...
Update pane coordinate tuples based on their height and width relative to other panes within the dimensions of the current window. We account for panes with a height of 1 where the bottom coordinates are the same as the top. Account for floating panes and self-coordinating panes adjacent to pan...
[ "Update", "pane", "coordinate", "tuples", "based", "on", "their", "height", "and", "width", "relative", "to", "other", "panes", "within", "the", "dimensions", "of", "the", "current", "window", "." ]
6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62
https://github.com/LukeB42/Window/blob/6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62/window.py#L565-L616
train
LukeB42/Window
window.py
Window.addstr
def addstr(self, h, w, text, attrs=0): """ A safe addstr wrapper """ self.update_window_size() if h > self.height or w > self.width: return try: # Python curses addstr doesn't deal with non-ascii characters #self.window.addstr(h, w, tex...
python
def addstr(self, h, w, text, attrs=0): """ A safe addstr wrapper """ self.update_window_size() if h > self.height or w > self.width: return try: # Python curses addstr doesn't deal with non-ascii characters #self.window.addstr(h, w, tex...
[ "def", "addstr", "(", "self", ",", "h", ",", "w", ",", "text", ",", "attrs", "=", "0", ")", ":", "self", ".", "update_window_size", "(", ")", "if", "h", ">", "self", ".", "height", "or", "w", ">", "self", ".", "width", ":", "return", "try", ":"...
A safe addstr wrapper
[ "A", "safe", "addstr", "wrapper" ]
6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62
https://github.com/LukeB42/Window/blob/6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62/window.py#L618-L630
train
LukeB42/Window
window.py
Window.update_window_size
def update_window_size(self): """ Update the current window object with its current height and width and clear the screen if they've changed. """ height, width = self.window.getmaxyx() if self.height != height or self.width != width: self.height, self.width = ...
python
def update_window_size(self): """ Update the current window object with its current height and width and clear the screen if they've changed. """ height, width = self.window.getmaxyx() if self.height != height or self.width != width: self.height, self.width = ...
[ "def", "update_window_size", "(", "self", ")", ":", "height", ",", "width", "=", "self", ".", "window", ".", "getmaxyx", "(", ")", "if", "self", ".", "height", "!=", "height", "or", "self", ".", "width", "!=", "width", ":", "self", ".", "height", ","...
Update the current window object with its current height and width and clear the screen if they've changed.
[ "Update", "the", "current", "window", "object", "with", "its", "current", "height", "and", "width", "and", "clear", "the", "screen", "if", "they", "ve", "changed", "." ]
6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62
https://github.com/LukeB42/Window/blob/6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62/window.py#L632-L640
train
LukeB42/Window
window.py
Window.add
def add(self, pane): """ Adds new panes to the window """ if isinstance(pane, list): initialised_panes = [] for p in pane: initialised_panes.append(self.init_pane(p)) self.panes.append(initialised_panes) else: pa...
python
def add(self, pane): """ Adds new panes to the window """ if isinstance(pane, list): initialised_panes = [] for p in pane: initialised_panes.append(self.init_pane(p)) self.panes.append(initialised_panes) else: pa...
[ "def", "add", "(", "self", ",", "pane", ")", ":", "if", "isinstance", "(", "pane", ",", "list", ")", ":", "initialised_panes", "=", "[", "]", "for", "p", "in", "pane", ":", "initialised_panes", ".", "append", "(", "self", ".", "init_pane", "(", "p", ...
Adds new panes to the window
[ "Adds", "new", "panes", "to", "the", "window" ]
6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62
https://github.com/LukeB42/Window/blob/6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62/window.py#L642-L653
train
LukeB42/Window
window.py
Window.get
def get(self, name, default=None, cache=False): """ Get a pane by name, possibly from the cache. Return None if not found. """ if cache == True: for pane in self.cache: if pane.name == name: return pane return default fo...
python
def get(self, name, default=None, cache=False): """ Get a pane by name, possibly from the cache. Return None if not found. """ if cache == True: for pane in self.cache: if pane.name == name: return pane return default fo...
[ "def", "get", "(", "self", ",", "name", ",", "default", "=", "None", ",", "cache", "=", "False", ")", ":", "if", "cache", "==", "True", ":", "for", "pane", "in", "self", ".", "cache", ":", "if", "pane", ".", "name", "==", "name", ":", "return", ...
Get a pane by name, possibly from the cache. Return None if not found.
[ "Get", "a", "pane", "by", "name", "possibly", "from", "the", "cache", ".", "Return", "None", "if", "not", "found", "." ]
6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62
https://github.com/LukeB42/Window/blob/6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62/window.py#L673-L685
train
LukeB42/Window
window.py
Pane.process_input
def process_input(self, character): """ A subclassable method for dealing with input characters. """ func = None try: func = getattr(self, "handle_%s" % chr(character), None) except: pass if func: func()
python
def process_input(self, character): """ A subclassable method for dealing with input characters. """ func = None try: func = getattr(self, "handle_%s" % chr(character), None) except: pass if func: func()
[ "def", "process_input", "(", "self", ",", "character", ")", ":", "func", "=", "None", "try", ":", "func", "=", "getattr", "(", "self", ",", "\"handle_%s\"", "%", "chr", "(", "character", ")", ",", "None", ")", "except", ":", "pass", "if", "func", ":"...
A subclassable method for dealing with input characters.
[ "A", "subclassable", "method", "for", "dealing", "with", "input", "characters", "." ]
6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62
https://github.com/LukeB42/Window/blob/6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62/window.py#L790-L800
train
tjcsl/cslbot
cslbot/commands/gcc.py
cmd
def cmd(send, msg, args): """Compiles stuff. Syntax: {command} <code> """ if args['type'] == 'privmsg': send('GCC is a group exercise!') return if 'include' in msg: send("We're not a terribly inclusive community around here.") return if 'import' in msg: ...
python
def cmd(send, msg, args): """Compiles stuff. Syntax: {command} <code> """ if args['type'] == 'privmsg': send('GCC is a group exercise!') return if 'include' in msg: send("We're not a terribly inclusive community around here.") return if 'import' in msg: ...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "args", "[", "'type'", "]", "==", "'privmsg'", ":", "send", "(", "'GCC is a group exercise!'", ")", "return", "if", "'include'", "in", "msg", ":", "send", "(", "\"We're not a terribly incl...
Compiles stuff. Syntax: {command} <code>
[ "Compiles", "stuff", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/gcc.py#L26-L59
train
ymyzk/python-gyazo
gyazo/api.py
Api.get_image_list
def get_image_list(self, page=1, per_page=20): """Return a list of user's saved images :param page: (optional) Page number (default: 1) :param per_page: (optional) Number of images per page (default: 20, min: 1, max: 100) """ url = self.api_url + '/api/i...
python
def get_image_list(self, page=1, per_page=20): """Return a list of user's saved images :param page: (optional) Page number (default: 1) :param per_page: (optional) Number of images per page (default: 20, min: 1, max: 100) """ url = self.api_url + '/api/i...
[ "def", "get_image_list", "(", "self", ",", "page", "=", "1", ",", "per_page", "=", "20", ")", ":", "url", "=", "self", ".", "api_url", "+", "'/api/images'", "params", "=", "{", "'page'", ":", "page", ",", "'per_page'", ":", "per_page", "}", "response",...
Return a list of user's saved images :param page: (optional) Page number (default: 1) :param per_page: (optional) Number of images per page (default: 20, min: 1, max: 100)
[ "Return", "a", "list", "of", "user", "s", "saved", "images" ]
52893118899ed308ff75245b55f73d745c98ed1d
https://github.com/ymyzk/python-gyazo/blob/52893118899ed308ff75245b55f73d745c98ed1d/gyazo/api.py#L33-L50
train
ymyzk/python-gyazo
gyazo/api.py
Api.upload_image
def upload_image(self, image_file, referer_url=None, title=None, desc=None, created_at=None, collection_id=None): """Upload an image :param image_file: File-like object of an im...
python
def upload_image(self, image_file, referer_url=None, title=None, desc=None, created_at=None, collection_id=None): """Upload an image :param image_file: File-like object of an im...
[ "def", "upload_image", "(", "self", ",", "image_file", ",", "referer_url", "=", "None", ",", "title", "=", "None", ",", "desc", "=", "None", ",", "created_at", "=", "None", ",", "collection_id", "=", "None", ")", ":", "url", "=", "self", ".", "upload_u...
Upload an image :param image_file: File-like object of an image file :param referer_url: Referer site URL :param title: Site title :param desc: Comment :param created_at: Image's created time in unix time :param collection_id: Collection ID
[ "Upload", "an", "image" ]
52893118899ed308ff75245b55f73d745c98ed1d
https://github.com/ymyzk/python-gyazo/blob/52893118899ed308ff75245b55f73d745c98ed1d/gyazo/api.py#L52-L86
train
ymyzk/python-gyazo
gyazo/api.py
Api.get_oembed
def get_oembed(self, url): """Return an oEmbed format json dictionary :param url: Image page URL (ex. http://gyazo.com/xxxxx) """ api_url = self.api_url + '/api/oembed' parameters = { 'url': url } response = self._request_url(api_url, 'get', params=pa...
python
def get_oembed(self, url): """Return an oEmbed format json dictionary :param url: Image page URL (ex. http://gyazo.com/xxxxx) """ api_url = self.api_url + '/api/oembed' parameters = { 'url': url } response = self._request_url(api_url, 'get', params=pa...
[ "def", "get_oembed", "(", "self", ",", "url", ")", ":", "api_url", "=", "self", ".", "api_url", "+", "'/api/oembed'", "parameters", "=", "{", "'url'", ":", "url", "}", "response", "=", "self", ".", "_request_url", "(", "api_url", ",", "'get'", ",", "pa...
Return an oEmbed format json dictionary :param url: Image page URL (ex. http://gyazo.com/xxxxx)
[ "Return", "an", "oEmbed", "format", "json", "dictionary" ]
52893118899ed308ff75245b55f73d745c98ed1d
https://github.com/ymyzk/python-gyazo/blob/52893118899ed308ff75245b55f73d745c98ed1d/gyazo/api.py#L98-L109
train
ymyzk/python-gyazo
gyazo/api.py
Api._request_url
def _request_url(self, url, method, params=None, data=None, files=None, with_client_id=False, with_access_token=False): """Send HTTP request :param url: URL...
python
def _request_url(self, url, method, params=None, data=None, files=None, with_client_id=False, with_access_token=False): """Send HTTP request :param url: URL...
[ "def", "_request_url", "(", "self", ",", "url", ",", "method", ",", "params", "=", "None", ",", "data", "=", "None", ",", "files", "=", "None", ",", "with_client_id", "=", "False", ",", "with_access_token", "=", "False", ")", ":", "headers", "=", "{", ...
Send HTTP request :param url: URL :param method: HTTP method (get, post or delete) :param with_client_id: send request with client_id (default: false) :param with_access_token: send request with with_access_token (default: false) :raise GyazoErr...
[ "Send", "HTTP", "request" ]
52893118899ed308ff75245b55f73d745c98ed1d
https://github.com/ymyzk/python-gyazo/blob/52893118899ed308ff75245b55f73d745c98ed1d/gyazo/api.py#L111-L147
train
Genida/archan
src/archan/dsm.py
validate_rows_length
def validate_rows_length(data, length, message=None, exception=MatrixError): """Validate that all rows have the same length.""" if message is None: message = 'All rows must have the same length (same number of columns)' for row in data: if len(row) != length: raise exception(mess...
python
def validate_rows_length(data, length, message=None, exception=MatrixError): """Validate that all rows have the same length.""" if message is None: message = 'All rows must have the same length (same number of columns)' for row in data: if len(row) != length: raise exception(mess...
[ "def", "validate_rows_length", "(", "data", ",", "length", ",", "message", "=", "None", ",", "exception", "=", "MatrixError", ")", ":", "if", "message", "is", "None", ":", "message", "=", "'All rows must have the same length (same number of columns)'", "for", "row",...
Validate that all rows have the same length.
[ "Validate", "that", "all", "rows", "have", "the", "same", "length", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/dsm.py#L15-L21
train
Genida/archan
src/archan/dsm.py
validate_square
def validate_square(data, message=None, exception=MatrixError): """Validate that the matrix has equal number of rows and columns.""" rows, columns = len(data), len(data[0]) if data else 0 if message is None: message = 'Number of rows: %s != number of columns: %s in matrix' % ( rows, colu...
python
def validate_square(data, message=None, exception=MatrixError): """Validate that the matrix has equal number of rows and columns.""" rows, columns = len(data), len(data[0]) if data else 0 if message is None: message = 'Number of rows: %s != number of columns: %s in matrix' % ( rows, colu...
[ "def", "validate_square", "(", "data", ",", "message", "=", "None", ",", "exception", "=", "MatrixError", ")", ":", "rows", ",", "columns", "=", "len", "(", "data", ")", ",", "len", "(", "data", "[", "0", "]", ")", "if", "data", "else", "0", "if", ...
Validate that the matrix has equal number of rows and columns.
[ "Validate", "that", "the", "matrix", "has", "equal", "number", "of", "rows", "and", "columns", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/dsm.py#L24-L31
train
Genida/archan
src/archan/dsm.py
validate_categories_equal_entities
def validate_categories_equal_entities(categories, entities, message=None, exception=MatrixError): """Validate that the matrix has equal number of entities and categories.""" nb_categories = len(categories) nb_entities = len(entities) if message is None: me...
python
def validate_categories_equal_entities(categories, entities, message=None, exception=MatrixError): """Validate that the matrix has equal number of entities and categories.""" nb_categories = len(categories) nb_entities = len(entities) if message is None: me...
[ "def", "validate_categories_equal_entities", "(", "categories", ",", "entities", ",", "message", "=", "None", ",", "exception", "=", "MatrixError", ")", ":", "nb_categories", "=", "len", "(", "categories", ")", "nb_entities", "=", "len", "(", "entities", ")", ...
Validate that the matrix has equal number of entities and categories.
[ "Validate", "that", "the", "matrix", "has", "equal", "number", "of", "entities", "and", "categories", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/dsm.py#L34-L43
train
Genida/archan
src/archan/dsm.py
DesignStructureMatrix.validate
def validate(self): """Base validation + entities = rows.""" super().validate() nb_entities = len(self.entities) if nb_entities != self.rows: raise self.error( 'Number of entities: %s != number of rows: %s' % ( nb_entities, self.rows))
python
def validate(self): """Base validation + entities = rows.""" super().validate() nb_entities = len(self.entities) if nb_entities != self.rows: raise self.error( 'Number of entities: %s != number of rows: %s' % ( nb_entities, self.rows))
[ "def", "validate", "(", "self", ")", ":", "super", "(", ")", ".", "validate", "(", ")", "nb_entities", "=", "len", "(", "self", ".", "entities", ")", "if", "nb_entities", "!=", "self", ".", "rows", ":", "raise", "self", ".", "error", "(", "'Number of...
Base validation + entities = rows.
[ "Base", "validation", "+", "entities", "=", "rows", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/dsm.py#L109-L116
train
Genida/archan
src/archan/dsm.py
DesignStructureMatrix.transitive_closure
def transitive_closure(self): """Compute the transitive closure of the matrix.""" data = [[1 if j else 0 for j in i] for i in self.data] for k in range(self.rows): for i in range(self.rows): for j in range(self.rows): if data[i][k] and data[k][j]: ...
python
def transitive_closure(self): """Compute the transitive closure of the matrix.""" data = [[1 if j else 0 for j in i] for i in self.data] for k in range(self.rows): for i in range(self.rows): for j in range(self.rows): if data[i][k] and data[k][j]: ...
[ "def", "transitive_closure", "(", "self", ")", ":", "data", "=", "[", "[", "1", "if", "j", "else", "0", "for", "j", "in", "i", "]", "for", "i", "in", "self", ".", "data", "]", "for", "k", "in", "range", "(", "self", ".", "rows", ")", ":", "fo...
Compute the transitive closure of the matrix.
[ "Compute", "the", "transitive", "closure", "of", "the", "matrix", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/dsm.py#L118-L126
train
Genida/archan
src/archan/dsm.py
DomainMappingMatrix.validate
def validate(self): """Base validation + entities = rows + columns.""" super().validate() nb_entities = len(self.entities) if nb_entities != self.rows + self.columns: raise self.error( 'Number of entities: %s != number of rows + ' 'number of co...
python
def validate(self): """Base validation + entities = rows + columns.""" super().validate() nb_entities = len(self.entities) if nb_entities != self.rows + self.columns: raise self.error( 'Number of entities: %s != number of rows + ' 'number of co...
[ "def", "validate", "(", "self", ")", ":", "super", "(", ")", ".", "validate", "(", ")", "nb_entities", "=", "len", "(", "self", ".", "entities", ")", "if", "nb_entities", "!=", "self", ".", "rows", "+", "self", ".", "columns", ":", "raise", "self", ...
Base validation + entities = rows + columns.
[ "Base", "validation", "+", "entities", "=", "rows", "+", "columns", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/dsm.py#L134-L143
train
Genida/archan
src/archan/dsm.py
DomainMappingMatrix.default_entities
def default_entities(self): """Return range from 0 to rows + columns.""" return [str(i) for i in range(self.rows + self.columns)]
python
def default_entities(self): """Return range from 0 to rows + columns.""" return [str(i) for i in range(self.rows + self.columns)]
[ "def", "default_entities", "(", "self", ")", ":", "return", "[", "str", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "rows", "+", "self", ".", "columns", ")", "]" ]
Return range from 0 to rows + columns.
[ "Return", "range", "from", "0", "to", "rows", "+", "columns", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/dsm.py#L145-L147
train
Genida/archan
src/archan/dsm.py
MultipleDomainMatrix.validate
def validate(self): """Base validation + each cell is instance of DSM or MDM.""" super().validate() message_dsm = 'Matrix at [%s:%s] is not an instance of '\ 'DesignStructureMatrix or MultipleDomainMatrix.' message_ddm = 'Matrix at [%s:%s] is not an instance of '\ ...
python
def validate(self): """Base validation + each cell is instance of DSM or MDM.""" super().validate() message_dsm = 'Matrix at [%s:%s] is not an instance of '\ 'DesignStructureMatrix or MultipleDomainMatrix.' message_ddm = 'Matrix at [%s:%s] is not an instance of '\ ...
[ "def", "validate", "(", "self", ")", ":", "super", "(", ")", ".", "validate", "(", ")", "message_dsm", "=", "'Matrix at [%s:%s] is not an instance of '", "'DesignStructureMatrix or MultipleDomainMatrix.'", "message_ddm", "=", "'Matrix at [%s:%s] is not an instance of '", "'Do...
Base validation + each cell is instance of DSM or MDM.
[ "Base", "validation", "+", "each", "cell", "is", "instance", "of", "DSM", "or", "MDM", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/dsm.py#L156-L174
train
VIVelev/PyDojoML
dojo/cluster/kmeans.py
KMeans._calc_distortion
def _calc_distortion(self): """Calculates the distortion value of the current clusters """ m = self._X.shape[0] self.distortion = 1/m * sum( linalg.norm(self._X[i, :] - self.centroids[self.clusters[i]])**2 for i in range(m) ) return self.distortion
python
def _calc_distortion(self): """Calculates the distortion value of the current clusters """ m = self._X.shape[0] self.distortion = 1/m * sum( linalg.norm(self._X[i, :] - self.centroids[self.clusters[i]])**2 for i in range(m) ) return self.distortion
[ "def", "_calc_distortion", "(", "self", ")", ":", "m", "=", "self", ".", "_X", ".", "shape", "[", "0", "]", "self", ".", "distortion", "=", "1", "/", "m", "*", "sum", "(", "linalg", ".", "norm", "(", "self", ".", "_X", "[", "i", ",", ":", "]"...
Calculates the distortion value of the current clusters
[ "Calculates", "the", "distortion", "value", "of", "the", "current", "clusters" ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/kmeans.py#L30-L37
train
VIVelev/PyDojoML
dojo/cluster/kmeans.py
KMeans._move_centroids
def _move_centroids(self): """Calculate new centroids as the means of the samples in each cluster """ for k in range(self.n_clusters): if k in self.clusters: centroid = np.mean(self._X[self.clusters == k, :], axis=0) self.centroids[k] = centroid ...
python
def _move_centroids(self): """Calculate new centroids as the means of the samples in each cluster """ for k in range(self.n_clusters): if k in self.clusters: centroid = np.mean(self._X[self.clusters == k, :], axis=0) self.centroids[k] = centroid ...
[ "def", "_move_centroids", "(", "self", ")", ":", "for", "k", "in", "range", "(", "self", ".", "n_clusters", ")", ":", "if", "k", "in", "self", ".", "clusters", ":", "centroid", "=", "np", ".", "mean", "(", "self", ".", "_X", "[", "self", ".", "cl...
Calculate new centroids as the means of the samples in each cluster
[ "Calculate", "new", "centroids", "as", "the", "means", "of", "the", "samples", "in", "each", "cluster" ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/kmeans.py#L44-L56
train
VIVelev/PyDojoML
dojo/cluster/kmeans.py
KMeans._closest_centroid
def _closest_centroid(self, x): """Returns the index of the closest centroid to the sample """ closest_centroid = 0 distance = 10^9 for i in range(self.n_clusters): current_distance = linalg.norm(x - self.centroids[i]) if current_distance < distance: ...
python
def _closest_centroid(self, x): """Returns the index of the closest centroid to the sample """ closest_centroid = 0 distance = 10^9 for i in range(self.n_clusters): current_distance = linalg.norm(x - self.centroids[i]) if current_distance < distance: ...
[ "def", "_closest_centroid", "(", "self", ",", "x", ")", ":", "closest_centroid", "=", "0", "distance", "=", "10", "^", "9", "for", "i", "in", "range", "(", "self", ".", "n_clusters", ")", ":", "current_distance", "=", "linalg", ".", "norm", "(", "x", ...
Returns the index of the closest centroid to the sample
[ "Returns", "the", "index", "of", "the", "closest", "centroid", "to", "the", "sample" ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/kmeans.py#L58-L70
train
VIVelev/PyDojoML
dojo/cluster/kmeans.py
KMeans._assign_clusters
def _assign_clusters(self): """Assign the samples to the closest centroids to create clusters """ self.clusters = np.array([self._closest_centroid(x) for x in self._X])
python
def _assign_clusters(self): """Assign the samples to the closest centroids to create clusters """ self.clusters = np.array([self._closest_centroid(x) for x in self._X])
[ "def", "_assign_clusters", "(", "self", ")", ":", "self", ".", "clusters", "=", "np", ".", "array", "(", "[", "self", ".", "_closest_centroid", "(", "x", ")", "for", "x", "in", "self", ".", "_X", "]", ")" ]
Assign the samples to the closest centroids to create clusters
[ "Assign", "the", "samples", "to", "the", "closest", "centroids", "to", "create", "clusters" ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/kmeans.py#L72-L75
train
VIVelev/PyDojoML
dojo/cluster/kmeans.py
KMeans.fit
def fit(self, X): """The K-Means itself """ self._X = super().cluster(X) candidates = [] for _ in range(self.n_runs): self._init_random_centroids() while True: prev_clusters = self.clusters self._assign_clusters() ...
python
def fit(self, X): """The K-Means itself """ self._X = super().cluster(X) candidates = [] for _ in range(self.n_runs): self._init_random_centroids() while True: prev_clusters = self.clusters self._assign_clusters() ...
[ "def", "fit", "(", "self", ",", "X", ")", ":", "self", ".", "_X", "=", "super", "(", ")", ".", "cluster", "(", "X", ")", "candidates", "=", "[", "]", "for", "_", "in", "range", "(", "self", ".", "n_runs", ")", ":", "self", ".", "_init_random_ce...
The K-Means itself
[ "The", "K", "-", "Means", "itself" ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/kmeans.py#L77-L102
train
tjcsl/cslbot
cslbot/commands/jargon.py
cmd
def cmd(send, *_): """Causes the bot to generate some jargon. Syntax: {command} """ words = [[verb, noun, abbrev, noun, adj, abbrev, noun], [verb, adj, abbrev, noun], [verb, abbrev, noun, verb, adj, noun], [verb, noun, ingverb, adj, abbrev, noun], [adj, abbrev, noun, verb, adj, noun], [ab...
python
def cmd(send, *_): """Causes the bot to generate some jargon. Syntax: {command} """ words = [[verb, noun, abbrev, noun, adj, abbrev, noun], [verb, adj, abbrev, noun], [verb, abbrev, noun, verb, adj, noun], [verb, noun, ingverb, adj, abbrev, noun], [adj, abbrev, noun, verb, adj, noun], [ab...
[ "def", "cmd", "(", "send", ",", "*", "_", ")", ":", "words", "=", "[", "[", "verb", ",", "noun", ",", "abbrev", ",", "noun", ",", "adj", ",", "abbrev", ",", "noun", "]", ",", "[", "verb", ",", "adj", ",", "abbrev", ",", "noun", "]", ",", "[...
Causes the bot to generate some jargon. Syntax: {command}
[ "Causes", "the", "bot", "to", "generate", "some", "jargon", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/jargon.py#L49-L69
train
banesullivan/gendocs
gendocs/generator.py
Generator._GenerateStaticsTable
def _GenerateStaticsTable(self, title='Current Statistics'): """Generates a statics table based on set categories""" if len(self.__categories.keys()) < 1: return '' d = self.__categories keys = sorted(d.keys()) cats = ', '.join(['"%s"' % k for k in keys]) vals...
python
def _GenerateStaticsTable(self, title='Current Statistics'): """Generates a statics table based on set categories""" if len(self.__categories.keys()) < 1: return '' d = self.__categories keys = sorted(d.keys()) cats = ', '.join(['"%s"' % k for k in keys]) vals...
[ "def", "_GenerateStaticsTable", "(", "self", ",", "title", "=", "'Current Statistics'", ")", ":", "if", "len", "(", "self", ".", "__categories", ".", "keys", "(", ")", ")", "<", "1", ":", "return", "''", "d", "=", "self", ".", "__categories", "keys", "...
Generates a statics table based on set categories
[ "Generates", "a", "statics", "table", "based", "on", "set", "categories" ]
4ff6277370143ba698701beccc05d5eace43b632
https://github.com/banesullivan/gendocs/blob/4ff6277370143ba698701beccc05d5eace43b632/gendocs/generator.py#L212-L231
train
banesullivan/gendocs
gendocs/generator.py
Generator._ProduceSingleContent
def _ProduceSingleContent(self, mod, showprivate=False, showinh=False): """An internal helper to create a page for a single module. This will automatically generate the needed RSF to document the module and save the module to its own page in its appropriate location. Args: m...
python
def _ProduceSingleContent(self, mod, showprivate=False, showinh=False): """An internal helper to create a page for a single module. This will automatically generate the needed RSF to document the module and save the module to its own page in its appropriate location. Args: m...
[ "def", "_ProduceSingleContent", "(", "self", ",", "mod", ",", "showprivate", "=", "False", ",", "showinh", "=", "False", ")", ":", "try", ":", "all", "=", "mod", "[", "1", "]", ".", "__all__", "except", "AttributeError", ":", "raise", "RuntimeError", "("...
An internal helper to create a page for a single module. This will automatically generate the needed RSF to document the module and save the module to its own page in its appropriate location. Args: mod (module): The single module to document as its own page showprivate ...
[ "An", "internal", "helper", "to", "create", "a", "page", "for", "a", "single", "module", ".", "This", "will", "automatically", "generate", "the", "needed", "RSF", "to", "document", "the", "module", "and", "save", "the", "module", "to", "its", "own", "page"...
4ff6277370143ba698701beccc05d5eace43b632
https://github.com/banesullivan/gendocs/blob/4ff6277370143ba698701beccc05d5eace43b632/gendocs/generator.py#L233-L285
train
banesullivan/gendocs
gendocs/generator.py
Generator._ProduceContent
def _ProduceContent(self, mods, showprivate=False, showinh=False): """An internal helper to create pages for several modules that do not have nested modules. This will automatically generate the needed RSF to document each module module and save the module to its own page appropriately. ...
python
def _ProduceContent(self, mods, showprivate=False, showinh=False): """An internal helper to create pages for several modules that do not have nested modules. This will automatically generate the needed RSF to document each module module and save the module to its own page appropriately. ...
[ "def", "_ProduceContent", "(", "self", ",", "mods", ",", "showprivate", "=", "False", ",", "showinh", "=", "False", ")", ":", "result", "=", "''", "nestedresult", "=", "''", "for", "mod", "in", "mods", ":", "try", ":", "all", "=", "mod", "[", "1", ...
An internal helper to create pages for several modules that do not have nested modules. This will automatically generate the needed RSF to document each module module and save the module to its own page appropriately. Args: mods (module): The modules to document that do not contain ...
[ "An", "internal", "helper", "to", "create", "pages", "for", "several", "modules", "that", "do", "not", "have", "nested", "modules", ".", "This", "will", "automatically", "generate", "the", "needed", "RSF", "to", "document", "each", "module", "module", "and", ...
4ff6277370143ba698701beccc05d5eace43b632
https://github.com/banesullivan/gendocs/blob/4ff6277370143ba698701beccc05d5eace43b632/gendocs/generator.py#L289-L316
train
banesullivan/gendocs
gendocs/generator.py
Generator._MakePackagePages
def _MakePackagePages(self, package, showprivate=False, nested=False, showinh=False): """An internal helper to generate all of the pages for a given package Args: package (module): The top-level package to document showprivate (bool): A flag for whether or not to display private...
python
def _MakePackagePages(self, package, showprivate=False, nested=False, showinh=False): """An internal helper to generate all of the pages for a given package Args: package (module): The top-level package to document showprivate (bool): A flag for whether or not to display private...
[ "def", "_MakePackagePages", "(", "self", ",", "package", ",", "showprivate", "=", "False", ",", "nested", "=", "False", ",", "showinh", "=", "False", ")", ":", "def", "checkNoNested", "(", "mod", ")", ":", "try", ":", "all", "=", "mod", ".", "__all__",...
An internal helper to generate all of the pages for a given package Args: package (module): The top-level package to document showprivate (bool): A flag for whether or not to display private members nested (bool): Foor internal use ONLY Returns: str: The...
[ "An", "internal", "helper", "to", "generate", "all", "of", "the", "pages", "for", "a", "given", "package" ]
4ff6277370143ba698701beccc05d5eace43b632
https://github.com/banesullivan/gendocs/blob/4ff6277370143ba698701beccc05d5eace43b632/gendocs/generator.py#L321-L401
train
banesullivan/gendocs
gendocs/generator.py
Generator._DocPackageFromTop
def _DocPackageFromTop(self, packages, showprivate=False, showinh=False): """Generates all of the documentation for given packages and appends new tocrees to the index. All documentation pages will be under the set relative path. Args: packages (list(module)): A package or l...
python
def _DocPackageFromTop(self, packages, showprivate=False, showinh=False): """Generates all of the documentation for given packages and appends new tocrees to the index. All documentation pages will be under the set relative path. Args: packages (list(module)): A package or l...
[ "def", "_DocPackageFromTop", "(", "self", ",", "packages", ",", "showprivate", "=", "False", ",", "showinh", "=", "False", ")", ":", "appIndex", "=", "''", "if", "not", "isinstance", "(", "packages", ",", "list", ")", ":", "packages", "=", "[", "packages...
Generates all of the documentation for given packages and appends new tocrees to the index. All documentation pages will be under the set relative path. Args: packages (list(module)): A package or list of packages that contain submodules to document showprivate (bool): A...
[ "Generates", "all", "of", "the", "documentation", "for", "given", "packages", "and", "appends", "new", "tocrees", "to", "the", "index", ".", "All", "documentation", "pages", "will", "be", "under", "the", "set", "relative", "path", "." ]
4ff6277370143ba698701beccc05d5eace43b632
https://github.com/banesullivan/gendocs/blob/4ff6277370143ba698701beccc05d5eace43b632/gendocs/generator.py#L405-L481
train
davisagli/eye
eye/__init__.py
eye
def eye(root=None, zodb_uri=None, port=8080): """Serves a WSGI app to browse objects based on a root object or ZODB URI. """ if root is not None: root_factory = lambda request: Node(root) elif zodb_uri is not None: if '://' not in zodb_uri: # treat it as a file:// ...
python
def eye(root=None, zodb_uri=None, port=8080): """Serves a WSGI app to browse objects based on a root object or ZODB URI. """ if root is not None: root_factory = lambda request: Node(root) elif zodb_uri is not None: if '://' not in zodb_uri: # treat it as a file:// ...
[ "def", "eye", "(", "root", "=", "None", ",", "zodb_uri", "=", "None", ",", "port", "=", "8080", ")", ":", "if", "root", "is", "not", "None", ":", "root_factory", "=", "lambda", "request", ":", "Node", "(", "root", ")", "elif", "zodb_uri", "is", "no...
Serves a WSGI app to browse objects based on a root object or ZODB URI.
[ "Serves", "a", "WSGI", "app", "to", "browse", "objects", "based", "on", "a", "root", "object", "or", "ZODB", "URI", "." ]
4007b6b490ac667c8423c6cc789b303e93f9d03d
https://github.com/davisagli/eye/blob/4007b6b490ac667c8423c6cc789b303e93f9d03d/eye/__init__.py#L53-L75
train
tjcsl/cslbot
cslbot/commands/active.py
cmd
def cmd(send, _, args): """Returns stats on the active users. Syntax: {command} """ if args['target'] == 'private': send("You're all alone!") return with args['handler'].data_lock: channel = args['handler'].channels[args['target']] voiced = len([x for x in args['han...
python
def cmd(send, _, args): """Returns stats on the active users. Syntax: {command} """ if args['target'] == 'private': send("You're all alone!") return with args['handler'].data_lock: channel = args['handler'].channels[args['target']] voiced = len([x for x in args['han...
[ "def", "cmd", "(", "send", ",", "_", ",", "args", ")", ":", "if", "args", "[", "'target'", "]", "==", "'private'", ":", "send", "(", "\"You're all alone!\"", ")", "return", "with", "args", "[", "'handler'", "]", ".", "data_lock", ":", "channel", "=", ...
Returns stats on the active users. Syntax: {command}
[ "Returns", "stats", "on", "the", "active", "users", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/active.py#L22-L35
train
Aplopio/django_rip
rip/django_adapter/action_resolver.py
determine_end_point
def determine_end_point(http_request, url): """ returns detail, list or aggregates """ if url.endswith('aggregates') or url.endswith('aggregates/'): return 'aggregates' else: return 'detail' if is_detail_url(http_request, url) else 'list'
python
def determine_end_point(http_request, url): """ returns detail, list or aggregates """ if url.endswith('aggregates') or url.endswith('aggregates/'): return 'aggregates' else: return 'detail' if is_detail_url(http_request, url) else 'list'
[ "def", "determine_end_point", "(", "http_request", ",", "url", ")", ":", "if", "url", ".", "endswith", "(", "'aggregates'", ")", "or", "url", ".", "endswith", "(", "'aggregates/'", ")", ":", "return", "'aggregates'", "else", ":", "return", "'detail'", "if", ...
returns detail, list or aggregates
[ "returns", "detail", "list", "or", "aggregates" ]
6b03962ccb778c1a95950a3803e5170c7a2392df
https://github.com/Aplopio/django_rip/blob/6b03962ccb778c1a95950a3803e5170c7a2392df/rip/django_adapter/action_resolver.py#L18-L25
train
acutesoftware/virtual-AI-simulator
vais/battle.py
BattleSimulator.run_simulation
def run_simulation(self): """ runs the simulation """ for _ in range(self.num_fights): # restore health between each fight self.c1.stats['Health'] = self.c1.stats['max_health'] self.c2.stats['Health'] = self.c2.stats['max_health'] ...
python
def run_simulation(self): """ runs the simulation """ for _ in range(self.num_fights): # restore health between each fight self.c1.stats['Health'] = self.c1.stats['max_health'] self.c2.stats['Health'] = self.c2.stats['max_health'] ...
[ "def", "run_simulation", "(", "self", ")", ":", "for", "_", "in", "range", "(", "self", ".", "num_fights", ")", ":", "self", ".", "c1", ".", "stats", "[", "'Health'", "]", "=", "self", ".", "c1", ".", "stats", "[", "'max_health'", "]", "self", ".",...
runs the simulation
[ "runs", "the", "simulation" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/battle.py#L53-L74
train
acutesoftware/virtual-AI-simulator
vais/battle.py
Battle.take_damage
def take_damage(self, c, dmg): """ wrapper to apply damage taken to a character """ if c.name == self.c1.name: self.c1.stats['Health'] = self.c1.stats['Health'] - dmg else: self.c2.stats['Health'] = self.c2.stats['Health'] - dmg
python
def take_damage(self, c, dmg): """ wrapper to apply damage taken to a character """ if c.name == self.c1.name: self.c1.stats['Health'] = self.c1.stats['Health'] - dmg else: self.c2.stats['Health'] = self.c2.stats['Health'] - dmg
[ "def", "take_damage", "(", "self", ",", "c", ",", "dmg", ")", ":", "if", "c", ".", "name", "==", "self", ".", "c1", ".", "name", ":", "self", ".", "c1", ".", "stats", "[", "'Health'", "]", "=", "self", ".", "c1", ".", "stats", "[", "'Health'", ...
wrapper to apply damage taken to a character
[ "wrapper", "to", "apply", "damage", "taken", "to", "a", "character" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/battle.py#L119-L126
train
acutesoftware/virtual-AI-simulator
vais/battle.py
Battle.show_message
def show_message(self, c_attack, c_defend, result, dmg, print_console='Yes'): """ function to wrap the display of the battle messages """ perc_health_att = '[' + str(round((c_attack.stats['Health']*100) / c_attack.stats['max_health'] )) + '%]' perc_health_def = '[' + str(round((c...
python
def show_message(self, c_attack, c_defend, result, dmg, print_console='Yes'): """ function to wrap the display of the battle messages """ perc_health_att = '[' + str(round((c_attack.stats['Health']*100) / c_attack.stats['max_health'] )) + '%]' perc_health_def = '[' + str(round((c...
[ "def", "show_message", "(", "self", ",", "c_attack", ",", "c_defend", ",", "result", ",", "dmg", ",", "print_console", "=", "'Yes'", ")", ":", "perc_health_att", "=", "'['", "+", "str", "(", "round", "(", "(", "c_attack", ".", "stats", "[", "'Health'", ...
function to wrap the display of the battle messages
[ "function", "to", "wrap", "the", "display", "of", "the", "battle", "messages" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/battle.py#L129-L145
train
gtsystem/parallelpipe
parallelpipe.py
iterqueue
def iterqueue(queue, expected): """Iterate all value from the queue until the ``expected`` number of EXIT elements is received""" while expected > 0: for item in iter(queue.get, EXIT): yield item expected -= 1
python
def iterqueue(queue, expected): """Iterate all value from the queue until the ``expected`` number of EXIT elements is received""" while expected > 0: for item in iter(queue.get, EXIT): yield item expected -= 1
[ "def", "iterqueue", "(", "queue", ",", "expected", ")", ":", "while", "expected", ">", "0", ":", "for", "item", "in", "iter", "(", "queue", ".", "get", ",", "EXIT", ")", ":", "yield", "item", "expected", "-=", "1" ]
Iterate all value from the queue until the ``expected`` number of EXIT elements is received
[ "Iterate", "all", "value", "from", "the", "queue", "until", "the", "expected", "number", "of", "EXIT", "elements", "is", "received" ]
b10eba28de6019cbf34e08ac575d31a4c493b39c
https://github.com/gtsystem/parallelpipe/blob/b10eba28de6019cbf34e08ac575d31a4c493b39c/parallelpipe.py#L16-L22
train