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 {}.'.format(self.kwargs['date'])
)
office_ids = []
for election in date.elections.all():
office = election.race.office
if not office.body:
office_ids.append(office.uid)
return Office.objects.filter(uid__in=office_ids) | 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 {}.'.format(self.kwargs['date'])
)
office_ids = []
for election in date.elections.all():
office = election.race.office
if not office.body:
office_ids.append(office.uid)
return Office.objects.filter(uid__in=office_ids) | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"try",
":",
"date",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"kwargs",
"[",
"'date'",
"]",
")",
"except",
"Exception",
":",
"raise",
"APIException",
"(",
"'No elections on {}.'",
".",
"format",
"(",
"self",
".",
"kwargs",
"[",
"'date'",
"]",
")",
")",
"office_ids",
"=",
"[",
"]",
"for",
"election",
"in",
"date",
".",
"elections",
".",
"all",
"(",
")",
":",
"office",
"=",
"election",
".",
"race",
".",
"office",
"if",
"not",
"office",
".",
"body",
":",
"office_ids",
".",
"append",
"(",
"office",
".",
"uid",
")",
"return",
"Office",
".",
"objects",
".",
"filter",
"(",
"uid__in",
"=",
"office_ids",
")"
]
| 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:
channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel']
with args['handler'].data_lock:
users = list(args['handler'].channels[channel].users())
slap = 'slaps %s %s with %s'
send(slap % (choice(users), choice(methods), choice(implements)), 'action')
else:
reason = ''
method = choice(methods)
implement = ''
msg = msg.split()
slapee = msg[0]
# Basic and stupid NLP!
i = 1
args = False
while i < len(msg):
if msg[i] == 'for':
args = True
if reason:
send("Invalid Syntax: You can only have one for clause!")
return
i += 1
while i < len(msg):
if msg[i] == 'with':
break
reason += " "
reason += msg[i]
i += 1
reason = reason.strip()
elif msg[i] == 'with':
args = True
if implement:
send("Invalid Synatx: You can only have one with clause!")
return
i += 1
while i < len(msg):
if msg[i] == 'for':
break
implement += msg[i]
implement += ' '
i += 1
implement = implement.strip()
elif not args:
slapee += ' ' + msg[i]
i += 1
if not implement:
implement = choice(implements)
if reason:
slap = 'slaps %s %s with %s for %s' % (slapee, method, implement, reason)
else:
slap = 'slaps %s %s with %s' % (slapee, method, implement)
send(slap, 'action') | 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:
channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel']
with args['handler'].data_lock:
users = list(args['handler'].channels[channel].users())
slap = 'slaps %s %s with %s'
send(slap % (choice(users), choice(methods), choice(implements)), 'action')
else:
reason = ''
method = choice(methods)
implement = ''
msg = msg.split()
slapee = msg[0]
# Basic and stupid NLP!
i = 1
args = False
while i < len(msg):
if msg[i] == 'for':
args = True
if reason:
send("Invalid Syntax: You can only have one for clause!")
return
i += 1
while i < len(msg):
if msg[i] == 'with':
break
reason += " "
reason += msg[i]
i += 1
reason = reason.strip()
elif msg[i] == 'with':
args = True
if implement:
send("Invalid Synatx: You can only have one with clause!")
return
i += 1
while i < len(msg):
if msg[i] == 'for':
break
implement += msg[i]
implement += ' '
i += 1
implement = implement.strip()
elif not args:
slapee += ' ' + msg[i]
i += 1
if not implement:
implement = choice(implements)
if reason:
slap = 'slaps %s %s with %s for %s' % (slapee, method, implement, reason)
else:
slap = 'slaps %s %s with %s' % (slapee, method, implement)
send(slap, 'action') | [
"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'",
"]",
"methods",
"=",
"[",
"'around a bit'",
",",
"'upside the head'",
"]",
"if",
"not",
"msg",
":",
"channel",
"=",
"args",
"[",
"'target'",
"]",
"if",
"args",
"[",
"'target'",
"]",
"!=",
"'private'",
"else",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'channel'",
"]",
"with",
"args",
"[",
"'handler'",
"]",
".",
"data_lock",
":",
"users",
"=",
"list",
"(",
"args",
"[",
"'handler'",
"]",
".",
"channels",
"[",
"channel",
"]",
".",
"users",
"(",
")",
")",
"slap",
"=",
"'slaps %s %s with %s'",
"send",
"(",
"slap",
"%",
"(",
"choice",
"(",
"users",
")",
",",
"choice",
"(",
"methods",
")",
",",
"choice",
"(",
"implements",
")",
")",
",",
"'action'",
")",
"else",
":",
"reason",
"=",
"''",
"method",
"=",
"choice",
"(",
"methods",
")",
"implement",
"=",
"''",
"msg",
"=",
"msg",
".",
"split",
"(",
")",
"slapee",
"=",
"msg",
"[",
"0",
"]",
"# Basic and stupid NLP!",
"i",
"=",
"1",
"args",
"=",
"False",
"while",
"i",
"<",
"len",
"(",
"msg",
")",
":",
"if",
"msg",
"[",
"i",
"]",
"==",
"'for'",
":",
"args",
"=",
"True",
"if",
"reason",
":",
"send",
"(",
"\"Invalid Syntax: You can only have one for clause!\"",
")",
"return",
"i",
"+=",
"1",
"while",
"i",
"<",
"len",
"(",
"msg",
")",
":",
"if",
"msg",
"[",
"i",
"]",
"==",
"'with'",
":",
"break",
"reason",
"+=",
"\" \"",
"reason",
"+=",
"msg",
"[",
"i",
"]",
"i",
"+=",
"1",
"reason",
"=",
"reason",
".",
"strip",
"(",
")",
"elif",
"msg",
"[",
"i",
"]",
"==",
"'with'",
":",
"args",
"=",
"True",
"if",
"implement",
":",
"send",
"(",
"\"Invalid Synatx: You can only have one with clause!\"",
")",
"return",
"i",
"+=",
"1",
"while",
"i",
"<",
"len",
"(",
"msg",
")",
":",
"if",
"msg",
"[",
"i",
"]",
"==",
"'for'",
":",
"break",
"implement",
"+=",
"msg",
"[",
"i",
"]",
"implement",
"+=",
"' '",
"i",
"+=",
"1",
"implement",
"=",
"implement",
".",
"strip",
"(",
")",
"elif",
"not",
"args",
":",
"slapee",
"+=",
"' '",
"+",
"msg",
"[",
"i",
"]",
"i",
"+=",
"1",
"if",
"not",
"implement",
":",
"implement",
"=",
"choice",
"(",
"implements",
")",
"if",
"reason",
":",
"slap",
"=",
"'slaps %s %s with %s for %s'",
"%",
"(",
"slapee",
",",
"method",
",",
"implement",
",",
"reason",
")",
"else",
":",
"slap",
"=",
"'slaps %s %s with %s'",
"%",
"(",
"slapee",
",",
"method",
",",
"implement",
")",
"send",
"(",
"slap",
",",
"'action'",
")"
]
| 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_chain(args['db'], msg)
if chain:
send(" -> ".join(chain))
else:
send("%s has never changed their nick." % msg) | 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_chain(args['db'], msg)
if chain:
send(" -> ".join(chain))
else:
send("%s has never changed their nick." % msg) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"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_chain",
"(",
"args",
"[",
"'db'",
"]",
",",
"msg",
")",
"if",
"chain",
":",
"send",
"(",
"\" -> \"",
".",
"join",
"(",
"chain",
")",
")",
"else",
":",
"send",
"(",
"\"%s has never changed their nick.\"",
"%",
"msg",
")"
]
| 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 = []
all_schemas = (None,) # type: Tuple[Optional[str], ...]
all_schemas += tuple(schemas)
for schema in all_schemas:
# Reflect the schema to get the list of the tables, views and constraints
metadata = MetaData()
metadata.reflect(engine, schema=schema, views=True)
metadatas.append(metadata)
for metadata in metadatas:
metadata.drop_all(engine, checkfirst=False) | 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 = []
all_schemas = (None,) # type: Tuple[Optional[str], ...]
all_schemas += tuple(schemas)
for schema in all_schemas:
# Reflect the schema to get the list of the tables, views and constraints
metadata = MetaData()
metadata.reflect(engine, schema=schema, views=True)
metadatas.append(metadata)
for metadata in metadatas:
metadata.drop_all(engine, checkfirst=False) | [
"def",
"clear_database",
"(",
"engine",
":",
"Connectable",
",",
"schemas",
":",
"Iterable",
"[",
"str",
"]",
"=",
"(",
")",
")",
"->",
"None",
":",
"assert",
"check_argument_types",
"(",
")",
"metadatas",
"=",
"[",
"]",
"all_schemas",
"=",
"(",
"None",
",",
")",
"# type: Tuple[Optional[str], ...]",
"all_schemas",
"+=",
"tuple",
"(",
"schemas",
")",
"for",
"schema",
"in",
"all_schemas",
":",
"# Reflect the schema to get the list of the tables, views and constraints",
"metadata",
"=",
"MetaData",
"(",
")",
"metadata",
".",
"reflect",
"(",
"engine",
",",
"schema",
"=",
"schema",
",",
"views",
"=",
"True",
")",
"metadatas",
".",
"append",
"(",
"metadata",
")",
"for",
"metadata",
"in",
"metadatas",
":",
"metadata",
".",
"drop_all",
"(",
"engine",
",",
"checkfirst",
"=",
"False",
")"
]
| 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",
"(",
"getattr",
"(",
"args",
"[",
"'handler'",
"]",
",",
"msg",
")",
")",
")"
]
| 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 who forget a trailing slash
if len(msg) == 2 and args['config']['feature'].getboolean('lazyregex'):
msg.append('')
# not a valid sed statement.
if not msg or len(msg) < 3:
send("Invalid Syntax.")
return
if args['type'] == 'privmsg':
send("Don't worry, %s is not a grammar Nazi." % args['botnick'])
return
string = msg[0]
replacement = msg[1]
modifiers = get_modifiers(msg[2], args['nick'], args['config']['core']['nickregex'])
if modifiers is None:
send("Invalid modifiers.")
return
try:
regex = re.compile(string, re.IGNORECASE) if modifiers['ignorecase'] else re.compile(string)
log = get_log(args['db'], args['target'], modifiers['nick'])
workers = args['handler'].workers
result = workers.run_pool(do_replace, [log, args['config']['core'], char, regex, replacement])
try:
msg = result.get(5)
except multiprocessing.TimeoutError:
workers.restart_pool()
send("Sed regex timed out.")
return
if msg:
send(msg)
else:
send("No match found.")
except sre_constants.error as ex:
raise CommandFailedException(ex) | 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 who forget a trailing slash
if len(msg) == 2 and args['config']['feature'].getboolean('lazyregex'):
msg.append('')
# not a valid sed statement.
if not msg or len(msg) < 3:
send("Invalid Syntax.")
return
if args['type'] == 'privmsg':
send("Don't worry, %s is not a grammar Nazi." % args['botnick'])
return
string = msg[0]
replacement = msg[1]
modifiers = get_modifiers(msg[2], args['nick'], args['config']['core']['nickregex'])
if modifiers is None:
send("Invalid modifiers.")
return
try:
regex = re.compile(string, re.IGNORECASE) if modifiers['ignorecase'] else re.compile(string)
log = get_log(args['db'], args['target'], modifiers['nick'])
workers = args['handler'].workers
result = workers.run_pool(do_replace, [log, args['config']['core'], char, regex, replacement])
try:
msg = result.get(5)
except multiprocessing.TimeoutError:
workers.restart_pool()
send("Sed regex timed out.")
return
if msg:
send(msg)
else:
send("No match found.")
except sre_constants.error as ex:
raise CommandFailedException(ex) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"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 who forget a trailing slash",
"if",
"len",
"(",
"msg",
")",
"==",
"2",
"and",
"args",
"[",
"'config'",
"]",
"[",
"'feature'",
"]",
".",
"getboolean",
"(",
"'lazyregex'",
")",
":",
"msg",
".",
"append",
"(",
"''",
")",
"# not a valid sed statement.",
"if",
"not",
"msg",
"or",
"len",
"(",
"msg",
")",
"<",
"3",
":",
"send",
"(",
"\"Invalid Syntax.\"",
")",
"return",
"if",
"args",
"[",
"'type'",
"]",
"==",
"'privmsg'",
":",
"send",
"(",
"\"Don't worry, %s is not a grammar Nazi.\"",
"%",
"args",
"[",
"'botnick'",
"]",
")",
"return",
"string",
"=",
"msg",
"[",
"0",
"]",
"replacement",
"=",
"msg",
"[",
"1",
"]",
"modifiers",
"=",
"get_modifiers",
"(",
"msg",
"[",
"2",
"]",
",",
"args",
"[",
"'nick'",
"]",
",",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'nickregex'",
"]",
")",
"if",
"modifiers",
"is",
"None",
":",
"send",
"(",
"\"Invalid modifiers.\"",
")",
"return",
"try",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"string",
",",
"re",
".",
"IGNORECASE",
")",
"if",
"modifiers",
"[",
"'ignorecase'",
"]",
"else",
"re",
".",
"compile",
"(",
"string",
")",
"log",
"=",
"get_log",
"(",
"args",
"[",
"'db'",
"]",
",",
"args",
"[",
"'target'",
"]",
",",
"modifiers",
"[",
"'nick'",
"]",
")",
"workers",
"=",
"args",
"[",
"'handler'",
"]",
".",
"workers",
"result",
"=",
"workers",
".",
"run_pool",
"(",
"do_replace",
",",
"[",
"log",
",",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
",",
"char",
",",
"regex",
",",
"replacement",
"]",
")",
"try",
":",
"msg",
"=",
"result",
".",
"get",
"(",
"5",
")",
"except",
"multiprocessing",
".",
"TimeoutError",
":",
"workers",
".",
"restart_pool",
"(",
")",
"send",
"(",
"\"Sed regex timed out.\"",
")",
"return",
"if",
"msg",
":",
"send",
"(",
"msg",
")",
"else",
":",
"send",
"(",
"\"No match found.\"",
")",
"except",
"sre_constants",
".",
"error",
"as",
"ex",
":",
"raise",
"CommandFailedException",
"(",
"ex",
")"
]
| 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):
self._value = bytes()
elif count > 0:
self._value += b'\x00' * count
else:
self._value = self._value[:count]
size = len(self)
self._bit_size = size * 8
self._align_to_byte_size = size | 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):
self._value = bytes()
elif count > 0:
self._value += b'\x00' * count
else:
self._value = self._value[:count]
size = len(self)
self._bit_size = size * 8
self._align_to_byte_size = size | [
"def",
"resize",
"(",
"self",
",",
"size",
")",
":",
"count",
"=",
"max",
"(",
"int",
"(",
"size",
")",
",",
"0",
")",
"-",
"len",
"(",
"self",
")",
"if",
"count",
"==",
"0",
":",
"pass",
"elif",
"-",
"count",
"==",
"len",
"(",
"self",
")",
":",
"self",
".",
"_value",
"=",
"bytes",
"(",
")",
"elif",
"count",
">",
"0",
":",
"self",
".",
"_value",
"+=",
"b'\\x00'",
"*",
"count",
"else",
":",
"self",
".",
"_value",
"=",
"self",
".",
"_value",
"[",
":",
"count",
"]",
"size",
"=",
"len",
"(",
"self",
")",
"self",
".",
"_bit_size",
"=",
"size",
"*",
"8",
"self",
".",
"_align_to_byte_size",
"=",
"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. | [
"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",
":",
"return",
"self",
".",
"_value",
".",
"decode",
"(",
"'ascii'",
")"
]
| 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 the
aligned `Field` group, can be between ``0`` and ``63``.
:param bool auto_align: if ``True`` the `Decimal` field aligns itself
to the next matching byte size according to the *size* of the
`Decimal` field.
"""
# Field alignment offset
field_offset = int(bit_offset)
# Auto alignment
if auto_align:
# Field alignment size
field_size, bit_offset = divmod(field_offset, 8)
if bit_offset is not 0:
field_size += 1
field_size = max(field_size, 1)
# No auto alignment
else:
# Field alignment size
field_size = int(group_size)
# Field alignment
alignment = Alignment(field_size, field_offset)
# Invalid field alignment size
if field_size not in range(1, 8):
raise FieldAlignmentError(self, self.index, alignment)
# Invalid field alignment offset
if not (0 <= field_offset <= 63):
raise FieldAlignmentError(self, self.index, alignment)
# Invalid field alignment
if field_offset >= field_size * 8:
raise FieldAlignmentError(self, self.index, alignment)
# Set field alignment
self._align_to_byte_size = alignment.byte_size
self._align_to_bit_offset = alignment.bit_offset | 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 the
aligned `Field` group, can be between ``0`` and ``63``.
:param bool auto_align: if ``True`` the `Decimal` field aligns itself
to the next matching byte size according to the *size* of the
`Decimal` field.
"""
# Field alignment offset
field_offset = int(bit_offset)
# Auto alignment
if auto_align:
# Field alignment size
field_size, bit_offset = divmod(field_offset, 8)
if bit_offset is not 0:
field_size += 1
field_size = max(field_size, 1)
# No auto alignment
else:
# Field alignment size
field_size = int(group_size)
# Field alignment
alignment = Alignment(field_size, field_offset)
# Invalid field alignment size
if field_size not in range(1, 8):
raise FieldAlignmentError(self, self.index, alignment)
# Invalid field alignment offset
if not (0 <= field_offset <= 63):
raise FieldAlignmentError(self, self.index, alignment)
# Invalid field alignment
if field_offset >= field_size * 8:
raise FieldAlignmentError(self, self.index, alignment)
# Set field alignment
self._align_to_byte_size = alignment.byte_size
self._align_to_bit_offset = alignment.bit_offset | [
"def",
"_set_alignment",
"(",
"self",
",",
"group_size",
",",
"bit_offset",
"=",
"0",
",",
"auto_align",
"=",
"False",
")",
":",
"# Field alignment offset",
"field_offset",
"=",
"int",
"(",
"bit_offset",
")",
"# Auto alignment",
"if",
"auto_align",
":",
"# Field alignment size",
"field_size",
",",
"bit_offset",
"=",
"divmod",
"(",
"field_offset",
",",
"8",
")",
"if",
"bit_offset",
"is",
"not",
"0",
":",
"field_size",
"+=",
"1",
"field_size",
"=",
"max",
"(",
"field_size",
",",
"1",
")",
"# No auto alignment",
"else",
":",
"# Field alignment size",
"field_size",
"=",
"int",
"(",
"group_size",
")",
"# Field alignment",
"alignment",
"=",
"Alignment",
"(",
"field_size",
",",
"field_offset",
")",
"# Invalid field alignment size",
"if",
"field_size",
"not",
"in",
"range",
"(",
"1",
",",
"8",
")",
":",
"raise",
"FieldAlignmentError",
"(",
"self",
",",
"self",
".",
"index",
",",
"alignment",
")",
"# Invalid field alignment offset",
"if",
"not",
"(",
"0",
"<=",
"field_offset",
"<=",
"63",
")",
":",
"raise",
"FieldAlignmentError",
"(",
"self",
",",
"self",
".",
"index",
",",
"alignment",
")",
"# Invalid field alignment",
"if",
"field_offset",
">=",
"field_size",
"*",
"8",
":",
"raise",
"FieldAlignmentError",
"(",
"self",
",",
"self",
".",
"index",
",",
"alignment",
")",
"# Set field alignment",
"self",
".",
"_align_to_byte_size",
"=",
"alignment",
".",
"byte_size",
"self",
".",
"_align_to_bit_offset",
"=",
"alignment",
".",
"bit_offset"
]
| 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``.
:param bool auto_align: if ``True`` the `Decimal` field aligns itself
to the next matching byte size according to the *size* of the
`Decimal` field. | [
"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",
":",
"return",
"name",
"return",
"self",
".",
"_value"
]
| 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",
")",
"return",
"d"
]
| 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 observed proportion
- n = the total number in the group in question
- z = Z(1-alpha/2) is the inverse standard normal cumulative
distribution function evaluated at 1-alpha/2
- q = 1-p.
The error bars shown in BMDS plots use alpha = 0.05 and so
represent the 95% confidence intervals on the observed
proportions (independent of model).
"""
p = incidence / float(n)
z = stats.norm.ppf(0.975)
q = 1. - p
ll = (
(2 * n * p + 2 * z - 1) - z * np.sqrt(2 * z - (2 + 1 / n) + 4 * p * (n * q + 1))
) / (2 * (n + 2 * z))
ul = (
(2 * n * p + 2 * z + 1) + z * np.sqrt(2 * z + (2 + 1 / n) + 4 * p * (n * q - 1))
) / (2 * (n + 2 * z))
return p, ll, ul | 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 observed proportion
- n = the total number in the group in question
- z = Z(1-alpha/2) is the inverse standard normal cumulative
distribution function evaluated at 1-alpha/2
- q = 1-p.
The error bars shown in BMDS plots use alpha = 0.05 and so
represent the 95% confidence intervals on the observed
proportions (independent of model).
"""
p = incidence / float(n)
z = stats.norm.ppf(0.975)
q = 1. - p
ll = (
(2 * n * p + 2 * z - 1) - z * np.sqrt(2 * z - (2 + 1 / n) + 4 * p * (n * q + 1))
) / (2 * (n + 2 * z))
ul = (
(2 * n * p + 2 * z + 1) + z * np.sqrt(2 * z + (2 + 1 / n) + 4 * p * (n * q - 1))
) / (2 * (n + 2 * z))
return p, ll, ul | [
"def",
"_calculate_plotting",
"(",
"n",
",",
"incidence",
")",
":",
"p",
"=",
"incidence",
"/",
"float",
"(",
"n",
")",
"z",
"=",
"stats",
".",
"norm",
".",
"ppf",
"(",
"0.975",
")",
"q",
"=",
"1.",
"-",
"p",
"ll",
"=",
"(",
"(",
"2",
"*",
"n",
"*",
"p",
"+",
"2",
"*",
"z",
"-",
"1",
")",
"-",
"z",
"*",
"np",
".",
"sqrt",
"(",
"2",
"*",
"z",
"-",
"(",
"2",
"+",
"1",
"/",
"n",
")",
"+",
"4",
"*",
"p",
"*",
"(",
"n",
"*",
"q",
"+",
"1",
")",
")",
")",
"/",
"(",
"2",
"*",
"(",
"n",
"+",
"2",
"*",
"z",
")",
")",
"ul",
"=",
"(",
"(",
"2",
"*",
"n",
"*",
"p",
"+",
"2",
"*",
"z",
"+",
"1",
")",
"+",
"z",
"*",
"np",
".",
"sqrt",
"(",
"2",
"*",
"z",
"+",
"(",
"2",
"+",
"1",
"/",
"n",
")",
"+",
"4",
"*",
"p",
"*",
"(",
"n",
"*",
"q",
"-",
"1",
")",
")",
")",
"/",
"(",
"2",
"*",
"(",
"n",
"+",
"2",
"*",
"z",
")",
")",
"return",
"p",
",",
"ll",
",",
"ul"
]
| 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 in question
- z = Z(1-alpha/2) is the inverse standard normal cumulative
distribution function evaluated at 1-alpha/2
- q = 1-p.
The error bars shown in BMDS plots use alpha = 0.05 and so
represent the 95% confidence intervals on the observed
proportions (independent of model). | [
"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)
yield
on.chdir(original) | 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)
yield
on.chdir(original) | [
"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.
params: (:py:class:`dict`, optional): The values for format
into the created URL (defaults to ``None``).
url_params: (:py:class:`dict`, optional): Parameters to add
to the end of the URL (defaults to ``None``).
Returns:
:py:class:`str`: The resulting URL.
"""
if root is None:
root = self.ROOT
return ''.join([
root,
endpoint,
'?' + urlencode(url_params) if url_params else '',
]).format(**params or {}) | 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.
params: (:py:class:`dict`, optional): The values for format
into the created URL (defaults to ``None``).
url_params: (:py:class:`dict`, optional): Parameters to add
to the end of the URL (defaults to ``None``).
Returns:
:py:class:`str`: The resulting URL.
"""
if root is None:
root = self.ROOT
return ''.join([
root,
endpoint,
'?' + urlencode(url_params) if url_params else '',
]).format(**params or {}) | [
"def",
"url_builder",
"(",
"self",
",",
"endpoint",
",",
"*",
",",
"root",
"=",
"None",
",",
"params",
"=",
"None",
",",
"url_params",
"=",
"None",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"self",
".",
"ROOT",
"return",
"''",
".",
"join",
"(",
"[",
"root",
",",
"endpoint",
",",
"'?'",
"+",
"urlencode",
"(",
"url_params",
")",
"if",
"url_params",
"else",
"''",
",",
"]",
")",
".",
"format",
"(",
"*",
"*",
"params",
"or",
"{",
"}",
")"
]
| 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 (defaults to ``None``).
url_params: (:py:class:`dict`, optional): Parameters to add
to the end of the URL (defaults to ``None``).
Returns:
:py:class:`str`: The resulting 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",
"ValueError",
"(",
"msg",
")",
"return",
"cls",
"(",
"api_token",
"=",
"token",
")"
]
| 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,
url_params=url_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,
url_params=url_params,
) | [
"def",
"url_builder",
"(",
"self",
",",
"endpoint",
",",
"params",
"=",
"None",
",",
"url_params",
"=",
"None",
")",
":",
"if",
"url_params",
"is",
"None",
":",
"url_params",
"=",
"OrderedDict",
"(",
")",
"url_params",
"[",
"self",
".",
"AUTH_PARAM",
"]",
"=",
"self",
".",
"api_token",
"return",
"super",
"(",
")",
".",
"url_builder",
"(",
"endpoint",
",",
"params",
"=",
"params",
",",
"url_params",
"=",
"url_params",
",",
")"
]
| 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",
"(",
"random_post",
"(",
"subreddit",
",",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'bitlykey'",
"]",
")",
")"
]
| 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, miney, moe and chooses...', 'picks a random number and gets...',
'rolls dice and gets...', 'asks a random person and gets...', 'plays rock, paper, scissors, lizard, spock and gets...'
]
send("%s %s" % (choice(action), choice(choices)), 'action') | 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, miney, moe and chooses...', 'picks a random number and gets...',
'rolls dice and gets...', 'asks a random person and gets...', 'plays rock, paper, scissors, lizard, spock and gets...'
]
send("%s %s" % (choice(action), choice(choices)), 'action') | [
"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...'",
",",
"'says eenie, menie, miney, moe and chooses...'",
",",
"'picks a random number and gets...'",
",",
"'rolls dice and gets...'",
",",
"'asks a random person and gets...'",
",",
"'plays rock, paper, scissors, lizard, spock and gets...'",
"]",
"send",
"(",
"\"%s %s\"",
"%",
"(",
"choice",
"(",
"action",
")",
",",
"choice",
"(",
"choices",
")",
")",
",",
"'action'",
")"
]
| 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 = match.group(2) + " "
send('%s: %s' % (match.group(1), message * 3))
else:
send("Invalid Syntax.") | 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 = match.group(2) + " "
send('%s: %s' % (match.group(1), message * 3))
else:
send("Invalid Syntax.") | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"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",
"=",
"match",
".",
"group",
"(",
"2",
")",
"+",
"\" \"",
"send",
"(",
"'%s: %s'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"message",
"*",
"3",
")",
")",
"else",
":",
"send",
"(",
"\"Invalid Syntax.\"",
")"
]
| 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]
raise ValueError("Unknown model name") | 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]
raise ValueError("Unknown model name") | [
"def",
"get_model",
"(",
"cls",
",",
"version",
",",
"model_name",
")",
":",
"models",
"=",
"cls",
".",
"versions",
"[",
"version",
"]",
".",
"model_options",
"for",
"keystore",
"in",
"models",
".",
"values",
"(",
")",
":",
"if",
"model_name",
"in",
"keystore",
":",
"return",
"keystore",
"[",
"model_name",
"]",
"raise",
"ValueError",
"(",
"\"Unknown model name\"",
")"
]
| 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.
"""
if self.doses_dropped_sessions:
for key in sorted(list(self.doses_dropped_sessions.keys())):
session = self.doses_dropped_sessions[key]
session._add_single_session_to_to_ordered_dict(d, dataset_index, recommended_only)
self._add_single_session_to_to_ordered_dict(d, dataset_index, recommended_only) | 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.
"""
if self.doses_dropped_sessions:
for key in sorted(list(self.doses_dropped_sessions.keys())):
session = self.doses_dropped_sessions[key]
session._add_single_session_to_to_ordered_dict(d, dataset_index, recommended_only)
self._add_single_session_to_to_ordered_dict(d, dataset_index, recommended_only) | [
"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_sessions",
".",
"keys",
"(",
")",
")",
")",
":",
"session",
"=",
"self",
".",
"doses_dropped_sessions",
"[",
"key",
"]",
"session",
".",
"_add_single_session_to_to_ordered_dict",
"(",
"d",
",",
"dataset_index",
",",
"recommended_only",
")",
"self",
".",
"_add_single_session_to_to_ordered_dict",
"(",
"d",
",",
"dataset_index",
",",
"recommended_only",
")"
]
| 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",
"will",
"include",
"all",
"sessions",
"."
]
| 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 presented (if no model is recommended.)
show_null = False
if recommended_only:
if self.recommendation_enabled:
if self.recommended_model is None:
if model_index == 0:
show_null = True
else:
continue
elif self.recommended_model == model:
pass
else:
continue
else:
if model_index == 0:
show_null = True
else:
continue
d["dataset_index"].append(dataset_index)
d["doses_dropped"].append(self.doses_dropped)
model._to_df(d, model_index, show_null) | 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 presented (if no model is recommended.)
show_null = False
if recommended_only:
if self.recommendation_enabled:
if self.recommended_model is None:
if model_index == 0:
show_null = True
else:
continue
elif self.recommended_model == model:
pass
else:
continue
else:
if model_index == 0:
show_null = True
else:
continue
d["dataset_index"].append(dataset_index)
d["doses_dropped"].append(self.doses_dropped)
model._to_df(d, model_index, show_null) | [
"def",
"_add_single_session_to_to_ordered_dict",
"(",
"self",
",",
"d",
",",
"dataset_index",
",",
"recommended_only",
")",
":",
"for",
"model_index",
",",
"model",
"in",
"enumerate",
"(",
"self",
".",
"models",
")",
":",
"# determine if model should be presented, or if a null-model should",
"# be presented (if no model is recommended.)",
"show_null",
"=",
"False",
"if",
"recommended_only",
":",
"if",
"self",
".",
"recommendation_enabled",
":",
"if",
"self",
".",
"recommended_model",
"is",
"None",
":",
"if",
"model_index",
"==",
"0",
":",
"show_null",
"=",
"True",
"else",
":",
"continue",
"elif",
"self",
".",
"recommended_model",
"==",
"model",
":",
"pass",
"else",
":",
"continue",
"else",
":",
"if",
"model_index",
"==",
"0",
":",
"show_null",
"=",
"True",
"else",
":",
"continue",
"d",
"[",
"\"dataset_index\"",
"]",
".",
"append",
"(",
"dataset_index",
")",
"d",
"[",
"\"doses_dropped\"",
"]",
".",
"append",
"(",
"self",
".",
"doses_dropped",
")",
"model",
".",
"_to_df",
"(",
"d",
",",
"model_index",
",",
"show_null",
")"
]
| 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.
This is required because in some cases, a higher-order model may not use
some parameters and can effectively collapse to a lower order model
(for example, a 2nd order polynomial and power model may collapse to a
linear model). In summary outputs, we may want to present all models in
one row, since they are the same model effectively.
"""
od = OrderedDict()
# Add models to appropriate list. We only aggregate models which
# completed successfully and have a valid AIC and BMD.
for i, model in enumerate(self.models):
output = getattr(model, "output", {})
if output.get("AIC") and output.get("BMD") and output["BMD"] > 0:
key = "{}-{}".format(output["AIC"], output["BMD"])
if key in od:
od[key].append(model)
else:
od[key] = [model]
else:
od[i] = [model]
# Sort each list by the number of parameters
def _get_num_params(model):
return (
len(model.output["parameters"])
if hasattr(model, "output") and "parameters" in model.output
else 0
)
for key, _models in od.items():
_models.sort(key=_get_num_params)
return list(od.values()) | 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.
This is required because in some cases, a higher-order model may not use
some parameters and can effectively collapse to a lower order model
(for example, a 2nd order polynomial and power model may collapse to a
linear model). In summary outputs, we may want to present all models in
one row, since they are the same model effectively.
"""
od = OrderedDict()
# Add models to appropriate list. We only aggregate models which
# completed successfully and have a valid AIC and BMD.
for i, model in enumerate(self.models):
output = getattr(model, "output", {})
if output.get("AIC") and output.get("BMD") and output["BMD"] > 0:
key = "{}-{}".format(output["AIC"], output["BMD"])
if key in od:
od[key].append(model)
else:
od[key] = [model]
else:
od[i] = [model]
# Sort each list by the number of parameters
def _get_num_params(model):
return (
len(model.output["parameters"])
if hasattr(model, "output") and "parameters" in model.output
else 0
)
for key, _models in od.items():
_models.sort(key=_get_num_params)
return list(od.values()) | [
"def",
"_group_models",
"(",
"self",
")",
":",
"od",
"=",
"OrderedDict",
"(",
")",
"# Add models to appropriate list. We only aggregate models which",
"# completed successfully and have a valid AIC and BMD.",
"for",
"i",
",",
"model",
"in",
"enumerate",
"(",
"self",
".",
"models",
")",
":",
"output",
"=",
"getattr",
"(",
"model",
",",
"\"output\"",
",",
"{",
"}",
")",
"if",
"output",
".",
"get",
"(",
"\"AIC\"",
")",
"and",
"output",
".",
"get",
"(",
"\"BMD\"",
")",
"and",
"output",
"[",
"\"BMD\"",
"]",
">",
"0",
":",
"key",
"=",
"\"{}-{}\"",
".",
"format",
"(",
"output",
"[",
"\"AIC\"",
"]",
",",
"output",
"[",
"\"BMD\"",
"]",
")",
"if",
"key",
"in",
"od",
":",
"od",
"[",
"key",
"]",
".",
"append",
"(",
"model",
")",
"else",
":",
"od",
"[",
"key",
"]",
"=",
"[",
"model",
"]",
"else",
":",
"od",
"[",
"i",
"]",
"=",
"[",
"model",
"]",
"# Sort each list by the number of parameters",
"def",
"_get_num_params",
"(",
"model",
")",
":",
"return",
"(",
"len",
"(",
"model",
".",
"output",
"[",
"\"parameters\"",
"]",
")",
"if",
"hasattr",
"(",
"model",
",",
"\"output\"",
")",
"and",
"\"parameters\"",
"in",
"model",
".",
"output",
"else",
"0",
")",
"for",
"key",
",",
"_models",
"in",
"od",
".",
"items",
"(",
")",
":",
"_models",
".",
"sort",
"(",
"key",
"=",
"_get_num_params",
")",
"return",
"list",
"(",
"od",
".",
"values",
"(",
")",
")"
]
| 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 higher-order model may not use
some parameters and can effectively collapse to a lower order model
(for example, a 2nd order polynomial and power model may collapse to a
linear model). In summary outputs, we may want to present all models in
one row, since they are the same model effectively. | [
"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",
"."
]
| 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",
":",
"return",
"False",
"else",
":",
"return",
"True"
]
| 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:
return
if args['type'] == 'privmsg':
send('Hey, no points in private messages!')
return
for match in matches:
# limit to 5 score changes per minute
if args['abuse'](args['nick'], 5, 'scores'):
return
name, direction = match[0].lower(), match[1]
if direction == "++":
score = 1
if name == args['nick'].lower():
send("%s: No self promotion! You lose 10 points." % args['nick'])
score = -10
else:
score = -1
row = session.query(Scores).filter(Scores.nick == name).first()
if row is None:
session.add(Scores(score=score, nick=name))
session.commit()
else:
row.score += score
session.commit() | 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:
return
if args['type'] == 'privmsg':
send('Hey, no points in private messages!')
return
for match in matches:
# limit to 5 score changes per minute
if args['abuse'](args['nick'], 5, 'scores'):
return
name, direction = match[0].lower(), match[1]
if direction == "++":
score = 1
if name == args['nick'].lower():
send("%s: No self promotion! You lose 10 points." % args['nick'])
score = -10
else:
score = -1
row = session.query(Scores).filter(Scores.nick == name).first()
if row is None:
session.add(Scores(score=score, nick=name))
session.commit()
else:
row.score += score
session.commit() | [
"def",
"handle",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"session",
"=",
"args",
"[",
"'db'",
"]",
"matches",
"=",
"re",
".",
"findall",
"(",
"r\"\\b(?<!-)(%s{2,16})(\\+\\+|--)\"",
"%",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'nickregex'",
"]",
",",
"msg",
")",
"if",
"not",
"matches",
":",
"return",
"if",
"args",
"[",
"'type'",
"]",
"==",
"'privmsg'",
":",
"send",
"(",
"'Hey, no points in private messages!'",
")",
"return",
"for",
"match",
"in",
"matches",
":",
"# limit to 5 score changes per minute",
"if",
"args",
"[",
"'abuse'",
"]",
"(",
"args",
"[",
"'nick'",
"]",
",",
"5",
",",
"'scores'",
")",
":",
"return",
"name",
",",
"direction",
"=",
"match",
"[",
"0",
"]",
".",
"lower",
"(",
")",
",",
"match",
"[",
"1",
"]",
"if",
"direction",
"==",
"\"++\"",
":",
"score",
"=",
"1",
"if",
"name",
"==",
"args",
"[",
"'nick'",
"]",
".",
"lower",
"(",
")",
":",
"send",
"(",
"\"%s: No self promotion! You lose 10 points.\"",
"%",
"args",
"[",
"'nick'",
"]",
")",
"score",
"=",
"-",
"10",
"else",
":",
"score",
"=",
"-",
"1",
"row",
"=",
"session",
".",
"query",
"(",
"Scores",
")",
".",
"filter",
"(",
"Scores",
".",
"nick",
"==",
"name",
")",
".",
"first",
"(",
")",
"if",
"row",
"is",
"None",
":",
"session",
".",
"add",
"(",
"Scores",
"(",
"score",
"=",
"score",
",",
"nick",
"=",
"name",
")",
")",
"session",
".",
"commit",
"(",
")",
"else",
":",
"row",
".",
"score",
"+=",
"score",
"session",
".",
"commit",
"(",
")"
]
| 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'",
":",
"send",
"(",
"\"correction: * %s %s\"",
"%",
"(",
"args",
"[",
"'nick'",
"]",
",",
"output",
")",
")",
"else",
":",
"send",
"(",
"\"%s actually meant: %s\"",
"%",
"(",
"args",
"[",
"'nick'",
"]",
",",
"output",
")",
")"
]
| 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['handler'].data_lock:
users = args['handler'].channels[channel].users()
if msg in users:
do_nuke(c, nick, msg, channel)
elif msg == args['botnick']:
send("Sorry, Self-Nuking is disabled pending aquisition of a Lead-Lined Fridge.")
else:
send("I'm sorry. Anonymous Nuking is not allowed") | 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['handler'].data_lock:
users = args['handler'].channels[channel].users()
if msg in users:
do_nuke(c, nick, msg, channel)
elif msg == args['botnick']:
send("Sorry, Self-Nuking is disabled pending aquisition of a Lead-Lined Fridge.")
else:
send("I'm sorry. Anonymous Nuking is not allowed") | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"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",
"[",
"'handler'",
"]",
".",
"data_lock",
":",
"users",
"=",
"args",
"[",
"'handler'",
"]",
".",
"channels",
"[",
"channel",
"]",
".",
"users",
"(",
")",
"if",
"msg",
"in",
"users",
":",
"do_nuke",
"(",
"c",
",",
"nick",
",",
"msg",
",",
"channel",
")",
"elif",
"msg",
"==",
"args",
"[",
"'botnick'",
"]",
":",
"send",
"(",
"\"Sorry, Self-Nuking is disabled pending aquisition of a Lead-Lined Fridge.\"",
")",
"else",
":",
"send",
"(",
"\"I'm sorry. Anonymous Nuking is not allowed\"",
")"
]
| 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``.
By default, if the infix is not found, function will simply
return the string passed.
Either ``prefix`` or ``suffix`` must be provided, but not both
(which would be ambiguous as to what to remove first).
:raise ValueError: If ``strict`` is True and required prefix or suffix
was not found
Examples::
trim('foobar', prefix='foo') # 'bar'
trim('foobar', suffix='bar') # 'foo'
trim('foobar', prefix='baz', strict=True) # exception
.. versionadded:: 0.0.4
"""
ensure_string(s)
has_prefix = prefix is not None
has_suffix = suffix is not None
if has_prefix == has_suffix:
raise ValueError(
"exactly one of either prefix or suffix must be provided")
if has_prefix:
ensure_string(prefix)
if s.startswith(prefix):
return s[len(prefix):]
elif strict:
raise ValueError(
"string %r does not start with expected prefix %r" % (
s, prefix))
if has_suffix:
ensure_string(suffix)
if s.endswith(suffix):
return s[:-len(suffix)] if suffix else s
elif strict:
raise ValueError(
"string %r does not end with expected suffix %r" % (
s, suffix))
return 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``.
By default, if the infix is not found, function will simply
return the string passed.
Either ``prefix`` or ``suffix`` must be provided, but not both
(which would be ambiguous as to what to remove first).
:raise ValueError: If ``strict`` is True and required prefix or suffix
was not found
Examples::
trim('foobar', prefix='foo') # 'bar'
trim('foobar', suffix='bar') # 'foo'
trim('foobar', prefix='baz', strict=True) # exception
.. versionadded:: 0.0.4
"""
ensure_string(s)
has_prefix = prefix is not None
has_suffix = suffix is not None
if has_prefix == has_suffix:
raise ValueError(
"exactly one of either prefix or suffix must be provided")
if has_prefix:
ensure_string(prefix)
if s.startswith(prefix):
return s[len(prefix):]
elif strict:
raise ValueError(
"string %r does not start with expected prefix %r" % (
s, prefix))
if has_suffix:
ensure_string(suffix)
if s.endswith(suffix):
return s[:-len(suffix)] if suffix else s
elif strict:
raise ValueError(
"string %r does not end with expected suffix %r" % (
s, suffix))
return 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",
"if",
"has_prefix",
"==",
"has_suffix",
":",
"raise",
"ValueError",
"(",
"\"exactly one of either prefix or suffix must be provided\"",
")",
"if",
"has_prefix",
":",
"ensure_string",
"(",
"prefix",
")",
"if",
"s",
".",
"startswith",
"(",
"prefix",
")",
":",
"return",
"s",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"elif",
"strict",
":",
"raise",
"ValueError",
"(",
"\"string %r does not start with expected prefix %r\"",
"%",
"(",
"s",
",",
"prefix",
")",
")",
"if",
"has_suffix",
":",
"ensure_string",
"(",
"suffix",
")",
"if",
"s",
".",
"endswith",
"(",
"suffix",
")",
":",
"return",
"s",
"[",
":",
"-",
"len",
"(",
"suffix",
")",
"]",
"if",
"suffix",
"else",
"s",
"elif",
"strict",
":",
"raise",
"ValueError",
"(",
"\"string %r does not end with expected suffix %r\"",
"%",
"(",
"s",
",",
"suffix",
")",
")",
"return",
"s"
]
| 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 simply
return the string passed.
Either ``prefix`` or ``suffix`` must be provided, but not both
(which would be ambiguous as to what to remove first).
:raise ValueError: If ``strict`` is True and required prefix or suffix
was not found
Examples::
trim('foobar', prefix='foo') # 'bar'
trim('foobar', suffix='bar') # 'foo'
trim('foobar', prefix='baz', strict=True) # exception
.. versionadded:: 0.0.4 | [
"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:
:param errors:
What to do with erroneous non-strings in the input.
Possible values include:
* ``'ignore'`` (or ``None``)
* ``'cast'`` (or ``False``) -- convert non-strings to strings
* ``'raise'`` (or ``True``) -- raise exception for any non-strings
* ``'replace'`` -- replace non-strings with alternative value
:param with_: Replacement used when ``errors == 'replace'``.
This can be a string, or a callable taking erroneous value
and returning a string replacement.
.. versionadded:: 0.0.3
Allow to specify error handling policy through ``errors`` parameter
"""
ensure_string(delimiter)
ensure_iterable(iterable)
ensure_keyword_args(kwargs, optional=('errors', 'with_'))
errors = kwargs.get('errors', True)
if errors in ('raise', True):
iterable = imap(ensure_string, iterable)
elif errors in ('ignore', None):
iterable = ifilter(is_string, iterable)
elif errors in ('cast', False):
iterable = imap(delimiter.__class__, iterable)
elif errors == 'replace':
if 'with_' not in kwargs:
raise ValueError("'replace' error policy requires specifying "
"replacement through with_=")
with_ = kwargs['with_']
if is_string(with_):
replacement = lambda x: with_
elif callable(with_):
replacement = with_
else:
raise TypeError("error replacement must be a string or function, "
"got %s" % type(with_).__name__)
iterable = (x if is_string(x) else ensure_string(replacement(x))
for x in iterable)
else:
raise TypeError(
"%r is not a valid error handling policy for join()" % (errors,))
return delimiter.join(iterable) | 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:
:param errors:
What to do with erroneous non-strings in the input.
Possible values include:
* ``'ignore'`` (or ``None``)
* ``'cast'`` (or ``False``) -- convert non-strings to strings
* ``'raise'`` (or ``True``) -- raise exception for any non-strings
* ``'replace'`` -- replace non-strings with alternative value
:param with_: Replacement used when ``errors == 'replace'``.
This can be a string, or a callable taking erroneous value
and returning a string replacement.
.. versionadded:: 0.0.3
Allow to specify error handling policy through ``errors`` parameter
"""
ensure_string(delimiter)
ensure_iterable(iterable)
ensure_keyword_args(kwargs, optional=('errors', 'with_'))
errors = kwargs.get('errors', True)
if errors in ('raise', True):
iterable = imap(ensure_string, iterable)
elif errors in ('ignore', None):
iterable = ifilter(is_string, iterable)
elif errors in ('cast', False):
iterable = imap(delimiter.__class__, iterable)
elif errors == 'replace':
if 'with_' not in kwargs:
raise ValueError("'replace' error policy requires specifying "
"replacement through with_=")
with_ = kwargs['with_']
if is_string(with_):
replacement = lambda x: with_
elif callable(with_):
replacement = with_
else:
raise TypeError("error replacement must be a string or function, "
"got %s" % type(with_).__name__)
iterable = (x if is_string(x) else ensure_string(replacement(x))
for x in iterable)
else:
raise TypeError(
"%r is not a valid error handling policy for join()" % (errors,))
return delimiter.join(iterable) | [
"def",
"join",
"(",
"delimiter",
",",
"iterable",
",",
"*",
"*",
"kwargs",
")",
":",
"ensure_string",
"(",
"delimiter",
")",
"ensure_iterable",
"(",
"iterable",
")",
"ensure_keyword_args",
"(",
"kwargs",
",",
"optional",
"=",
"(",
"'errors'",
",",
"'with_'",
")",
")",
"errors",
"=",
"kwargs",
".",
"get",
"(",
"'errors'",
",",
"True",
")",
"if",
"errors",
"in",
"(",
"'raise'",
",",
"True",
")",
":",
"iterable",
"=",
"imap",
"(",
"ensure_string",
",",
"iterable",
")",
"elif",
"errors",
"in",
"(",
"'ignore'",
",",
"None",
")",
":",
"iterable",
"=",
"ifilter",
"(",
"is_string",
",",
"iterable",
")",
"elif",
"errors",
"in",
"(",
"'cast'",
",",
"False",
")",
":",
"iterable",
"=",
"imap",
"(",
"delimiter",
".",
"__class__",
",",
"iterable",
")",
"elif",
"errors",
"==",
"'replace'",
":",
"if",
"'with_'",
"not",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"'replace' error policy requires specifying \"",
"\"replacement through with_=\"",
")",
"with_",
"=",
"kwargs",
"[",
"'with_'",
"]",
"if",
"is_string",
"(",
"with_",
")",
":",
"replacement",
"=",
"lambda",
"x",
":",
"with_",
"elif",
"callable",
"(",
"with_",
")",
":",
"replacement",
"=",
"with_",
"else",
":",
"raise",
"TypeError",
"(",
"\"error replacement must be a string or function, \"",
"\"got %s\"",
"%",
"type",
"(",
"with_",
")",
".",
"__name__",
")",
"iterable",
"=",
"(",
"x",
"if",
"is_string",
"(",
"x",
")",
"else",
"ensure_string",
"(",
"replacement",
"(",
"x",
")",
")",
"for",
"x",
"in",
"iterable",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"%r is not a valid error handling policy for join()\"",
"%",
"(",
"errors",
",",
")",
")",
"return",
"delimiter",
".",
"join",
"(",
"iterable",
")"
]
| 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 erroneous non-strings in the input.
Possible values include:
* ``'ignore'`` (or ``None``)
* ``'cast'`` (or ``False``) -- convert non-strings to strings
* ``'raise'`` (or ``True``) -- raise exception for any non-strings
* ``'replace'`` -- replace non-strings with alternative value
:param with_: Replacement used when ``errors == 'replace'``.
This can be a string, or a callable taking erroneous value
and returning a string replacement.
.. versionadded:: 0.0.3
Allow to specify error handling policy through ``errors`` parameter | [
"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 camel-case "equivalent"
"""
ensure_string(arg)
if not arg:
return arg
words = split(arg)
first_word = words[0] if len(words) > 0 else None
words = [word.capitalize() for word in words]
if first_word is not None:
if capitalize is True:
first_word = first_word.capitalize()
elif capitalize is False:
first_word = first_word[0].lower() + first_word[1:]
words[0] = first_word
return join(arg.__class__(), words) | 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 camel-case "equivalent"
"""
ensure_string(arg)
if not arg:
return arg
words = split(arg)
first_word = words[0] if len(words) > 0 else None
words = [word.capitalize() for word in words]
if first_word is not None:
if capitalize is True:
first_word = first_word.capitalize()
elif capitalize is False:
first_word = first_word[0].lower() + first_word[1:]
words[0] = first_word
return join(arg.__class__(), words) | [
"def",
"camel_case",
"(",
"arg",
",",
"capitalize",
"=",
"None",
")",
":",
"ensure_string",
"(",
"arg",
")",
"if",
"not",
"arg",
":",
"return",
"arg",
"words",
"=",
"split",
"(",
"arg",
")",
"first_word",
"=",
"words",
"[",
"0",
"]",
"if",
"len",
"(",
"words",
")",
">",
"0",
"else",
"None",
"words",
"=",
"[",
"word",
".",
"capitalize",
"(",
")",
"for",
"word",
"in",
"words",
"]",
"if",
"first_word",
"is",
"not",
"None",
":",
"if",
"capitalize",
"is",
"True",
":",
"first_word",
"=",
"first_word",
".",
"capitalize",
"(",
")",
"elif",
"capitalize",
"is",
"False",
":",
"first_word",
"=",
"first_word",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"+",
"first_word",
"[",
"1",
":",
"]",
"words",
"[",
"0",
"]",
"=",
"first_word",
"return",
"join",
"(",
"arg",
".",
"__class__",
"(",
")",
",",
"words",
")"
]
| 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 + string.digits
else:
ensure_string(chars)
if not chars:
raise ValueError("character set must not be empty")
if is_pair(length):
length = randint(*length)
elif isinstance(length, Integral):
if not length > 0:
raise ValueError(
"random string length must be positive (got %r)" % (length,))
else:
raise TypeError("random string length must be an integer; "
"got '%s'" % type(length).__name__)
return join(chars.__class__(), (choice(chars) for _ in xrange(length))) | 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 + string.digits
else:
ensure_string(chars)
if not chars:
raise ValueError("character set must not be empty")
if is_pair(length):
length = randint(*length)
elif isinstance(length, Integral):
if not length > 0:
raise ValueError(
"random string length must be positive (got %r)" % (length,))
else:
raise TypeError("random string length must be an integer; "
"got '%s'" % type(length).__name__)
return join(chars.__class__(), (choice(chars) for _ in xrange(length))) | [
"def",
"random",
"(",
"length",
",",
"chars",
"=",
"None",
")",
":",
"if",
"chars",
"is",
"None",
":",
"chars",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"else",
":",
"ensure_string",
"(",
"chars",
")",
"if",
"not",
"chars",
":",
"raise",
"ValueError",
"(",
"\"character set must not be empty\"",
")",
"if",
"is_pair",
"(",
"length",
")",
":",
"length",
"=",
"randint",
"(",
"*",
"length",
")",
"elif",
"isinstance",
"(",
"length",
",",
"Integral",
")",
":",
"if",
"not",
"length",
">",
"0",
":",
"raise",
"ValueError",
"(",
"\"random string length must be positive (got %r)\"",
"%",
"(",
"length",
",",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"random string length must be an integer; \"",
"\"got '%s'\"",
"%",
"type",
"(",
"length",
")",
".",
"__name__",
")",
"return",
"join",
"(",
"chars",
".",
"__class__",
"(",
")",
",",
"(",
"choice",
"(",
"chars",
")",
"for",
"_",
"in",
"xrange",
"(",
"length",
")",
")",
")"
]
| 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 replacement has been already given
"""
ensure_string(replacement)
if is_mapping(self._replacements):
raise ReplacementError("string replacements already provided")
self._replacements = dict.fromkeys(self._replacements, replacement)
return self | 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 replacement has been already given
"""
ensure_string(replacement)
if is_mapping(self._replacements):
raise ReplacementError("string replacements already provided")
self._replacements = dict.fromkeys(self._replacements, replacement)
return self | [
"def",
"with_",
"(",
"self",
",",
"replacement",
")",
":",
"ensure_string",
"(",
"replacement",
")",
"if",
"is_mapping",
"(",
"self",
".",
"_replacements",
")",
":",
"raise",
"ReplacementError",
"(",
"\"string replacements already provided\"",
")",
"self",
".",
"_replacements",
"=",
"dict",
".",
"fromkeys",
"(",
"self",
".",
"_replacements",
",",
"replacement",
")",
"return",
"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 yet
"""
from taipan.collections import dicts
ensure_string(haystack)
if not is_mapping(self._replacements):
raise ReplacementError("string replacements not provided")
# handle special cases
if not self._replacements:
return haystack
if len(self._replacements) == 1:
return haystack.replace(*dicts.peekitem(self._replacements))
# construct a regex matching any of the needles in the order
# of descending length (to prevent issues if they contain each other)
or_ = haystack.__class__('|')
regex = join(or_, imap(
re.escape, sorted(self._replacements, key=len, reverse=True)))
# do the substituion, looking up the replacement for every match
do_replace = lambda match: self._replacements[match.group()]
return re.sub(regex, do_replace, haystack) | 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 yet
"""
from taipan.collections import dicts
ensure_string(haystack)
if not is_mapping(self._replacements):
raise ReplacementError("string replacements not provided")
# handle special cases
if not self._replacements:
return haystack
if len(self._replacements) == 1:
return haystack.replace(*dicts.peekitem(self._replacements))
# construct a regex matching any of the needles in the order
# of descending length (to prevent issues if they contain each other)
or_ = haystack.__class__('|')
regex = join(or_, imap(
re.escape, sorted(self._replacements, key=len, reverse=True)))
# do the substituion, looking up the replacement for every match
do_replace = lambda match: self._replacements[match.group()]
return re.sub(regex, do_replace, haystack) | [
"def",
"in_",
"(",
"self",
",",
"haystack",
")",
":",
"from",
"taipan",
".",
"collections",
"import",
"dicts",
"ensure_string",
"(",
"haystack",
")",
"if",
"not",
"is_mapping",
"(",
"self",
".",
"_replacements",
")",
":",
"raise",
"ReplacementError",
"(",
"\"string replacements not provided\"",
")",
"# handle special cases",
"if",
"not",
"self",
".",
"_replacements",
":",
"return",
"haystack",
"if",
"len",
"(",
"self",
".",
"_replacements",
")",
"==",
"1",
":",
"return",
"haystack",
".",
"replace",
"(",
"*",
"dicts",
".",
"peekitem",
"(",
"self",
".",
"_replacements",
")",
")",
"# construct a regex matching any of the needles in the order",
"# of descending length (to prevent issues if they contain each other)",
"or_",
"=",
"haystack",
".",
"__class__",
"(",
"'|'",
")",
"regex",
"=",
"join",
"(",
"or_",
",",
"imap",
"(",
"re",
".",
"escape",
",",
"sorted",
"(",
"self",
".",
"_replacements",
",",
"key",
"=",
"len",
",",
"reverse",
"=",
"True",
")",
")",
")",
"# do the substituion, looking up the replacement for every match",
"do_replace",
"=",
"lambda",
"match",
":",
"self",
".",
"_replacements",
"[",
"match",
".",
"group",
"(",
")",
"]",
"return",
"re",
".",
"sub",
"(",
"regex",
",",
"do_replace",
",",
"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 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):
return item
elif isinstance(item, (tuple, set)):
return list(item)
else:
return [item] | 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):
return item
elif isinstance(item, (tuple, set)):
return list(item)
else:
return [item] | [
"def",
"wrap_list",
"(",
"item",
")",
":",
"if",
"item",
"is",
"None",
":",
"return",
"[",
"]",
"elif",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"return",
"item",
"elif",
"isinstance",
"(",
"item",
",",
"(",
"tuple",
",",
"set",
")",
")",
":",
"return",
"list",
"(",
"item",
")",
"else",
":",
"return",
"[",
"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. | [
"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 ``dict2`` is a mapping type itself, then
``update_additive`` is called recursively. This ensures that nested maps are updated rather than simply
overwritten.
This method should be functionally equivalent to ``dict.update()`` except in the case of values that are
themselves nested maps. If you know that ``dict1`` does not have nested maps,
or you want to overwrite all values with the exact content of then you should simply use ``dict.update()``.
"""
for key, value in dict2.items():
if key not in dict1:
dict1[key] = value
else: # key in dict1
if isinstance(dict1[key], collections.Mapping):
assert isinstance(value, collections.Mapping)
update_additive(dict1[key], value)
else: # value is not a mapping type
assert not isinstance(value, collections.Mapping)
dict1[key] = value | 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 ``dict2`` is a mapping type itself, then
``update_additive`` is called recursively. This ensures that nested maps are updated rather than simply
overwritten.
This method should be functionally equivalent to ``dict.update()`` except in the case of values that are
themselves nested maps. If you know that ``dict1`` does not have nested maps,
or you want to overwrite all values with the exact content of then you should simply use ``dict.update()``.
"""
for key, value in dict2.items():
if key not in dict1:
dict1[key] = value
else: # key in dict1
if isinstance(dict1[key], collections.Mapping):
assert isinstance(value, collections.Mapping)
update_additive(dict1[key], value)
else: # value is not a mapping type
assert not isinstance(value, collections.Mapping)
dict1[key] = value | [
"def",
"update_additive",
"(",
"dict1",
",",
"dict2",
")",
":",
"for",
"key",
",",
"value",
"in",
"dict2",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"dict1",
":",
"dict1",
"[",
"key",
"]",
"=",
"value",
"else",
":",
"# key in dict1",
"if",
"isinstance",
"(",
"dict1",
"[",
"key",
"]",
",",
"collections",
".",
"Mapping",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Mapping",
")",
"update_additive",
"(",
"dict1",
"[",
"key",
"]",
",",
"value",
")",
"else",
":",
"# value is not a mapping type",
"assert",
"not",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Mapping",
")",
"dict1",
"[",
"key",
"]",
"=",
"value"
]
| 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
``update_additive`` is called recursively. This ensures that nested maps are updated rather than simply
overwritten.
This method should be functionally equivalent to ``dict.update()`` except in the case of values that are
themselves nested maps. If you know that ``dict1`` does not have nested maps,
or you want to overwrite all values with the exact content of then you should simply use ``dict.update()``. | [
"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 dircmp.left. Else paths will be relative to dircmp.right.
"""
for name in dir_cmp.diff_files:
if left_path:
path_root = dir_cmp.left
else:
path_root = dir_cmp.right
yield path.joinpath(path_root, name)
for sub in dir_cmp.subdirs.values():
# Need to iterate over the recursive call to make sure the individual values are yielded up the stack
for the_dir in diff_dir(sub, left_path):
yield the_dir | 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 dircmp.left. Else paths will be relative to dircmp.right.
"""
for name in dir_cmp.diff_files:
if left_path:
path_root = dir_cmp.left
else:
path_root = dir_cmp.right
yield path.joinpath(path_root, name)
for sub in dir_cmp.subdirs.values():
# Need to iterate over the recursive call to make sure the individual values are yielded up the stack
for the_dir in diff_dir(sub, left_path):
yield the_dir | [
"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",
"yield",
"path",
".",
"joinpath",
"(",
"path_root",
",",
"name",
")",
"for",
"sub",
"in",
"dir_cmp",
".",
"subdirs",
".",
"values",
"(",
")",
":",
"# Need to iterate over the recursive call to make sure the individual values are yielded up the stack",
"for",
"the_dir",
"in",
"diff_dir",
"(",
"sub",
",",
"left_path",
")",
":",
"yield",
"the_dir"
]
| 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.right. | [
"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 specified
those named parameters' values are returned, otherwise
all parameters are returned as a dictionary
"""
if len(keys) == 0:
return vars(self)
else:
return [vars(self)[k] for k in keys] | 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 specified
those named parameters' values are returned, otherwise
all parameters are returned as a dictionary
"""
if len(keys) == 0:
return vars(self)
else:
return [vars(self)[k] for k in keys] | [
"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' values are returned, otherwise
all parameters are returned as a dictionary | [
"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 = {
# (?<!Setting ) is a special case for preventing
# "Setting BMD = 100*(maximum dose)" matches
"BMD": r"(?<!Setting )BMD = +(%s)" % self.re_num,
"BMDL": r"BMDL = +(%s)" % self.re_num,
"BMDU": r"BMDU = +(%s)" % self.re_num,
"CSF": r"Cancer Slope Factor = +(%s)" % self.re_num,
"AIC": r"AIC: +(%s)" % (self.re_num),
"model_version": r"Version: ([\d\.]+);",
"model_date": r"Date: ([\d/]+)",
}
for search in searches:
m = re.search(searches[search], self.output_text)
if m:
try:
self.output[search] = float(m.group(1))
except:
self.output[search] = m.group(1)
else:
self.output[search] = -999 | 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 = {
# (?<!Setting ) is a special case for preventing
# "Setting BMD = 100*(maximum dose)" matches
"BMD": r"(?<!Setting )BMD = +(%s)" % self.re_num,
"BMDL": r"BMDL = +(%s)" % self.re_num,
"BMDU": r"BMDU = +(%s)" % self.re_num,
"CSF": r"Cancer Slope Factor = +(%s)" % self.re_num,
"AIC": r"AIC: +(%s)" % (self.re_num),
"model_version": r"Version: ([\d\.]+);",
"model_date": r"Date: ([\d/]+)",
}
for search in searches:
m = re.search(searches[search], self.output_text)
if m:
try:
self.output[search] = float(m.group(1))
except:
self.output[search] = m.group(1)
else:
self.output[search] = -999 | [
"def",
"_import_single_searches",
"(",
"self",
")",
":",
"searches",
"=",
"{",
"# (?<!Setting ) is a special case for preventing",
"# \"Setting BMD = 100*(maximum dose)\" matches",
"\"BMD\"",
":",
"r\"(?<!Setting )BMD = +(%s)\"",
"%",
"self",
".",
"re_num",
",",
"\"BMDL\"",
":",
"r\"BMDL = +(%s)\"",
"%",
"self",
".",
"re_num",
",",
"\"BMDU\"",
":",
"r\"BMDU = +(%s)\"",
"%",
"self",
".",
"re_num",
",",
"\"CSF\"",
":",
"r\"Cancer Slope Factor = +(%s)\"",
"%",
"self",
".",
"re_num",
",",
"\"AIC\"",
":",
"r\"AIC: +(%s)\"",
"%",
"(",
"self",
".",
"re_num",
")",
",",
"\"model_version\"",
":",
"r\"Version: ([\\d\\.]+);\"",
",",
"\"model_date\"",
":",
"r\"Date: ([\\d/]+)\"",
",",
"}",
"for",
"search",
"in",
"searches",
":",
"m",
"=",
"re",
".",
"search",
"(",
"searches",
"[",
"search",
"]",
",",
"self",
".",
"output_text",
")",
"if",
"m",
":",
"try",
":",
"self",
".",
"output",
"[",
"search",
"]",
"=",
"float",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"except",
":",
"self",
".",
"output",
"[",
"search",
"]",
"=",
"m",
".",
"group",
"(",
"1",
")",
"else",
":",
"self",
".",
"output",
"[",
"search",
"]",
"=",
"-",
"999"
]
| 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 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 the range of the mean function",
r"BMD = 100\*\(maximum dose\)",
r"BMDL computation failed\.",
"Warning: optimum may not have been found. Bad completion code in Optimization routine.", # noqa
"Warning: Likelihood for fitted model larger than the Likelihood for model A3.", # noqa
)
self.output["warnings"] = []
for warning in warnings:
m = re.search(warning, self.output_text)
if m:
self.output["warnings"].append(m.group()) | 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 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 the range of the mean function",
r"BMD = 100\*\(maximum dose\)",
r"BMDL computation failed\.",
"Warning: optimum may not have been found. Bad completion code in Optimization routine.", # noqa
"Warning: Likelihood for fitted model larger than the Likelihood for model A3.", # noqa
)
self.output["warnings"] = []
for warning in warnings:
m = re.search(warning, self.output_text)
if m:
self.output["warnings"].append(m.group()) | [
"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 the range of the mean function\"",
",",
"r\"BMD = 100\\*\\(maximum dose\\)\"",
",",
"r\"BMDL computation failed\\.\"",
",",
"\"Warning: optimum may not have been found. Bad completion code in Optimization routine.\"",
",",
"# noqa",
"\"Warning: Likelihood for fitted model larger than the Likelihood for model A3.\"",
",",
"# noqa",
")",
"self",
".",
"output",
"[",
"\"warnings\"",
"]",
"=",
"[",
"]",
"for",
"warning",
"in",
"warnings",
":",
"m",
"=",
"re",
".",
"search",
"(",
"warning",
",",
"self",
".",
"output_text",
")",
"if",
"m",
":",
"self",
".",
"output",
"[",
"\"warnings\"",
"]",
".",
"append",
"(",
"m",
".",
"group",
"(",
")",
")"
]
| 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}|\w+) +d.f. = +({0}|\w+) +P-value = +({0}|\w+)".format(
self.re_num
), # noqa
self.output_text,
)
cw = {1: "Chi2", 2: "df", 3: "p_value4"}
for val in cw:
try:
self.output[cw[val]] = float(m.group(val))
except:
self.output[cw[val]] = -999 | 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}|\w+) +d.f. = +({0}|\w+) +P-value = +({0}|\w+)".format(
self.re_num
), # noqa
self.output_text,
)
cw = {1: "Chi2", 2: "df", 3: "p_value4"}
for val in cw:
try:
self.output[cw[val]] = float(m.group(val))
except:
self.output[cw[val]] = -999 | [
"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",
")",
",",
"# noqa",
"self",
".",
"output_text",
",",
")",
"cw",
"=",
"{",
"1",
":",
"\"Chi2\"",
",",
"2",
":",
"\"df\"",
",",
"3",
":",
"\"p_value4\"",
"}",
"for",
"val",
"in",
"cw",
":",
"try",
":",
"self",
".",
"output",
"[",
"cw",
"[",
"val",
"]",
"]",
"=",
"float",
"(",
"m",
".",
"group",
"(",
"val",
")",
")",
"except",
":",
"self",
".",
"output",
"[",
"cw",
"[",
"val",
"]",
"]",
"=",
"-",
"999"
]
| 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.
# One therefore needs to:
# - Extract the history from the input jicimagelib.image.Image.
# - Apply the transformation, which may return a numpy ndarray.
# - Force the image to the jicimagelib.image.Image type.
# - Re-attach the extracted history
if hasattr(args[0], 'history'):
# Working on jicimagelib.Image.
history = args[0].history
else:
# Working on something without a history, e.g. a ndarray stack.
history = []
image = func(*args, **kwargs)
image = Image.from_array(image, log_in_history=False)
image.history = history
image.history.append('Applied {} transform'.format(func.__name__))
if AutoWrite.on:
fpath = AutoName.name(func)
try:
if AutoWrite.auto_safe_dtype:
safe_range_im = 255 * normalise(image)
pil_im = PIL.Image.fromarray(safe_range_im.astype(np.uint8))
else:
pil_im = PIL.Image.fromarray(image)
except TypeError:
# Give a more meaningful error message.
raise(TypeError(
"Cannot handle this data type: {}".format(image.dtype)))
pil_im.save(fpath)
return image
return func_as_transformation | 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.
# One therefore needs to:
# - Extract the history from the input jicimagelib.image.Image.
# - Apply the transformation, which may return a numpy ndarray.
# - Force the image to the jicimagelib.image.Image type.
# - Re-attach the extracted history
if hasattr(args[0], 'history'):
# Working on jicimagelib.Image.
history = args[0].history
else:
# Working on something without a history, e.g. a ndarray stack.
history = []
image = func(*args, **kwargs)
image = Image.from_array(image, log_in_history=False)
image.history = history
image.history.append('Applied {} transform'.format(func.__name__))
if AutoWrite.on:
fpath = AutoName.name(func)
try:
if AutoWrite.auto_safe_dtype:
safe_range_im = 255 * normalise(image)
pil_im = PIL.Image.fromarray(safe_range_im.astype(np.uint8))
else:
pil_im = PIL.Image.fromarray(image)
except TypeError:
# Give a more meaningful error message.
raise(TypeError(
"Cannot handle this data type: {}".format(image.dtype)))
pil_im.save(fpath)
return image
return func_as_transformation | [
"def",
"transformation",
"(",
"func",
")",
":",
"@",
"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.",
"# One therefore needs to:",
"# - Extract the history from the input jicimagelib.image.Image.",
"# - Apply the transformation, which may return a numpy ndarray.",
"# - Force the image to the jicimagelib.image.Image type.",
"# - Re-attach the extracted history",
"if",
"hasattr",
"(",
"args",
"[",
"0",
"]",
",",
"'history'",
")",
":",
"# Working on jicimagelib.Image.",
"history",
"=",
"args",
"[",
"0",
"]",
".",
"history",
"else",
":",
"# Working on something without a history, e.g. a ndarray stack.",
"history",
"=",
"[",
"]",
"image",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"image",
"=",
"Image",
".",
"from_array",
"(",
"image",
",",
"log_in_history",
"=",
"False",
")",
"image",
".",
"history",
"=",
"history",
"image",
".",
"history",
".",
"append",
"(",
"'Applied {} transform'",
".",
"format",
"(",
"func",
".",
"__name__",
")",
")",
"if",
"AutoWrite",
".",
"on",
":",
"fpath",
"=",
"AutoName",
".",
"name",
"(",
"func",
")",
"try",
":",
"if",
"AutoWrite",
".",
"auto_safe_dtype",
":",
"safe_range_im",
"=",
"255",
"*",
"normalise",
"(",
"image",
")",
"pil_im",
"=",
"PIL",
".",
"Image",
".",
"fromarray",
"(",
"safe_range_im",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
")",
"else",
":",
"pil_im",
"=",
"PIL",
".",
"Image",
".",
"fromarray",
"(",
"image",
")",
"except",
"TypeError",
":",
"# Give a more meaningful error message.",
"raise",
"(",
"TypeError",
"(",
"\"Cannot handle this data type: {}\"",
".",
"format",
"(",
"image",
".",
"dtype",
")",
")",
")",
"pil_im",
".",
"save",
"(",
"fpath",
")",
"return",
"image",
"return",
"func_as_transformation"
]
| 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
:param clip_limit: clipping limit in range 0 to 1,
higher values give more contrast
"""
# Convert input for skimage.
skimage_float_im = normalise(image)
if np.all(skimage_float_im):
raise(RuntimeError("Cannot equalise when there is no variation."))
normalised = skimage.exposure.equalize_adapthist(skimage_float_im,
ntiles_x=ntiles, ntiles_y=ntiles, clip_limit=clip_limit)
assert np.max(normalised) == 1.0
assert np.min(normalised) == 0.0
return normalised | 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
:param clip_limit: clipping limit in range 0 to 1,
higher values give more contrast
"""
# Convert input for skimage.
skimage_float_im = normalise(image)
if np.all(skimage_float_im):
raise(RuntimeError("Cannot equalise when there is no variation."))
normalised = skimage.exposure.equalize_adapthist(skimage_float_im,
ntiles_x=ntiles, ntiles_y=ntiles, clip_limit=clip_limit)
assert np.max(normalised) == 1.0
assert np.min(normalised) == 0.0
return normalised | [
"def",
"equalize_adaptive_clahe",
"(",
"image",
",",
"ntiles",
"=",
"8",
",",
"clip_limit",
"=",
"0.01",
")",
":",
"# Convert input for skimage.",
"skimage_float_im",
"=",
"normalise",
"(",
"image",
")",
"if",
"np",
".",
"all",
"(",
"skimage_float_im",
")",
":",
"raise",
"(",
"RuntimeError",
"(",
"\"Cannot equalise when there is no variation.\"",
")",
")",
"normalised",
"=",
"skimage",
".",
"exposure",
".",
"equalize_adapthist",
"(",
"skimage_float_im",
",",
"ntiles_x",
"=",
"ntiles",
",",
"ntiles_y",
"=",
"ntiles",
",",
"clip_limit",
"=",
"clip_limit",
")",
"assert",
"np",
".",
"max",
"(",
"normalised",
")",
"==",
"1.0",
"assert",
"np",
".",
"min",
"(",
"normalised",
")",
"==",
"0.0",
"return",
"normalised"
]
| 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,
higher values give more contrast | [
"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.ArgumentException as e:
send(str(e))
return
api_output = get('https://api.github.com/repos/%s/branches/master' % args['config']['api']['githubrepo']).json()
commit, version = misc.get_version(args['handler'].confdir)
if not cmdargs.action:
send(version)
return
if cmdargs.action == 'master':
send(api_output['commit']['sha'])
elif cmdargs.action == 'check':
if commit is None:
send("Not running from git, version %s" % version)
else:
check = 'Same' if api_output['commit']['sha'] == commit else 'Different'
send(check)
elif cmdargs.action == 'commit':
if commit is None:
send("Not running from git, version %s" % version)
else:
send(commit) | 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.ArgumentException as e:
send(str(e))
return
api_output = get('https://api.github.com/repos/%s/branches/master' % args['config']['api']['githubrepo']).json()
commit, version = misc.get_version(args['handler'].confdir)
if not cmdargs.action:
send(version)
return
if cmdargs.action == 'master':
send(api_output['commit']['sha'])
elif cmdargs.action == 'check':
if commit is None:
send("Not running from git, version %s" % version)
else:
check = 'Same' if api_output['commit']['sha'] == commit else 'Different'
send(check)
elif cmdargs.action == 'commit':
if commit is None:
send("Not running from git, version %s" % version)
else:
send(commit) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'action'",
",",
"choices",
"=",
"[",
"'check'",
",",
"'master'",
",",
"'commit'",
"]",
",",
"nargs",
"=",
"'?'",
")",
"try",
":",
"cmdargs",
"=",
"parser",
".",
"parse_args",
"(",
"msg",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"e",
":",
"send",
"(",
"str",
"(",
"e",
")",
")",
"return",
"api_output",
"=",
"get",
"(",
"'https://api.github.com/repos/%s/branches/master'",
"%",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'githubrepo'",
"]",
")",
".",
"json",
"(",
")",
"commit",
",",
"version",
"=",
"misc",
".",
"get_version",
"(",
"args",
"[",
"'handler'",
"]",
".",
"confdir",
")",
"if",
"not",
"cmdargs",
".",
"action",
":",
"send",
"(",
"version",
")",
"return",
"if",
"cmdargs",
".",
"action",
"==",
"'master'",
":",
"send",
"(",
"api_output",
"[",
"'commit'",
"]",
"[",
"'sha'",
"]",
")",
"elif",
"cmdargs",
".",
"action",
"==",
"'check'",
":",
"if",
"commit",
"is",
"None",
":",
"send",
"(",
"\"Not running from git, version %s\"",
"%",
"version",
")",
"else",
":",
"check",
"=",
"'Same'",
"if",
"api_output",
"[",
"'commit'",
"]",
"[",
"'sha'",
"]",
"==",
"commit",
"else",
"'Different'",
"send",
"(",
"check",
")",
"elif",
"cmdargs",
".",
"action",
"==",
"'commit'",
":",
"if",
"commit",
"is",
"None",
":",
"send",
"(",
"\"Not running from git, version %s\"",
"%",
"version",
")",
"else",
":",
"send",
"(",
"commit",
")"
]
| 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(rasterFieldName, tableName, rasterIdFieldName, rasterId, 'AAIGrid', newSRID).splitlines()
## Convert arcInfoGrid to GRASS ASCII format ##
# Get values from header which look something this:
# ncols 67
# nrows 55
# xllcorner 425802.32143212341
# yllcorner 44091450.41551345213
# cellsize 90.0000000
# ...
nCols = int(arcInfoGrid[0].split()[1])
nRows = int(arcInfoGrid[1].split()[1])
xLLCorner = float(arcInfoGrid[2].split()[1])
yLLCorner = float(arcInfoGrid[3].split()[1])
cellSize = float(arcInfoGrid[4].split()[1])
# Remove old headers
for i in range(0, 5):
arcInfoGrid.pop(0)
# Check for NODATA_value row and remove if it is there
if 'NODATA_value' in arcInfoGrid[0]:
arcInfoGrid.pop(0)
## Calculate values for GRASS ASCII headers ##
# These should look like this:
# north: 4501028.972140
# south: 4494548.972140
# east: 460348.288604
# west: 454318.288604
# rows: 72
# cols: 67
# ...
# xLLCorner and yLLCorner represent the coordinates for the Lower Left corner of the raster
north = yLLCorner + (cellSize * nRows)
south = yLLCorner
east = xLLCorner + (cellSize * nCols)
west = xLLCorner
# Create header Lines (the first shall be last and the last shall be first)
grassHeader = ['cols: %s' % nCols,
'rows: %s' % nRows,
'west: %s' % west,
'east: %s' % east,
'south: %s' % south,
'north: %s' % north]
# Insert grass headers into the grid
for header in grassHeader:
arcInfoGrid.insert(0, header)
# Create string
arcInfoGridString = '\n'.join(arcInfoGrid)
return arcInfoGridString | 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(rasterFieldName, tableName, rasterIdFieldName, rasterId, 'AAIGrid', newSRID).splitlines()
## Convert arcInfoGrid to GRASS ASCII format ##
# Get values from header which look something this:
# ncols 67
# nrows 55
# xllcorner 425802.32143212341
# yllcorner 44091450.41551345213
# cellsize 90.0000000
# ...
nCols = int(arcInfoGrid[0].split()[1])
nRows = int(arcInfoGrid[1].split()[1])
xLLCorner = float(arcInfoGrid[2].split()[1])
yLLCorner = float(arcInfoGrid[3].split()[1])
cellSize = float(arcInfoGrid[4].split()[1])
# Remove old headers
for i in range(0, 5):
arcInfoGrid.pop(0)
# Check for NODATA_value row and remove if it is there
if 'NODATA_value' in arcInfoGrid[0]:
arcInfoGrid.pop(0)
## Calculate values for GRASS ASCII headers ##
# These should look like this:
# north: 4501028.972140
# south: 4494548.972140
# east: 460348.288604
# west: 454318.288604
# rows: 72
# cols: 67
# ...
# xLLCorner and yLLCorner represent the coordinates for the Lower Left corner of the raster
north = yLLCorner + (cellSize * nRows)
south = yLLCorner
east = xLLCorner + (cellSize * nCols)
west = xLLCorner
# Create header Lines (the first shall be last and the last shall be first)
grassHeader = ['cols: %s' % nCols,
'rows: %s' % nRows,
'west: %s' % west,
'east: %s' % east,
'south: %s' % south,
'north: %s' % north]
# Insert grass headers into the grid
for header in grassHeader:
arcInfoGrid.insert(0, header)
# Create string
arcInfoGridString = '\n'.join(arcInfoGrid)
return arcInfoGridString | [
"def",
"getAsGrassAsciiRaster",
"(",
"self",
",",
"tableName",
",",
"rasterId",
"=",
"1",
",",
"rasterIdFieldName",
"=",
"'id'",
",",
"rasterFieldName",
"=",
"'raster'",
",",
"newSRID",
"=",
"None",
")",
":",
"# Get raster in ArcInfo Grid format",
"arcInfoGrid",
"=",
"self",
".",
"getAsGdalRaster",
"(",
"rasterFieldName",
",",
"tableName",
",",
"rasterIdFieldName",
",",
"rasterId",
",",
"'AAIGrid'",
",",
"newSRID",
")",
".",
"splitlines",
"(",
")",
"## Convert arcInfoGrid to GRASS ASCII format ##",
"# Get values from header which look something this:",
"# ncols 67",
"# nrows 55",
"# xllcorner 425802.32143212341",
"# yllcorner 44091450.41551345213",
"# cellsize 90.0000000",
"# ...",
"nCols",
"=",
"int",
"(",
"arcInfoGrid",
"[",
"0",
"]",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
"nRows",
"=",
"int",
"(",
"arcInfoGrid",
"[",
"1",
"]",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
"xLLCorner",
"=",
"float",
"(",
"arcInfoGrid",
"[",
"2",
"]",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
"yLLCorner",
"=",
"float",
"(",
"arcInfoGrid",
"[",
"3",
"]",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
"cellSize",
"=",
"float",
"(",
"arcInfoGrid",
"[",
"4",
"]",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
"# Remove old headers",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"5",
")",
":",
"arcInfoGrid",
".",
"pop",
"(",
"0",
")",
"# Check for NODATA_value row and remove if it is there",
"if",
"'NODATA_value'",
"in",
"arcInfoGrid",
"[",
"0",
"]",
":",
"arcInfoGrid",
".",
"pop",
"(",
"0",
")",
"## Calculate values for GRASS ASCII headers ##",
"# These should look like this:",
"# north: 4501028.972140",
"# south: 4494548.972140",
"# east: 460348.288604",
"# west: 454318.288604",
"# rows: 72",
"# cols: 67",
"# ...",
"# xLLCorner and yLLCorner represent the coordinates for the Lower Left corner of the raster",
"north",
"=",
"yLLCorner",
"+",
"(",
"cellSize",
"*",
"nRows",
")",
"south",
"=",
"yLLCorner",
"east",
"=",
"xLLCorner",
"+",
"(",
"cellSize",
"*",
"nCols",
")",
"west",
"=",
"xLLCorner",
"# Create header Lines (the first shall be last and the last shall be first)",
"grassHeader",
"=",
"[",
"'cols: %s'",
"%",
"nCols",
",",
"'rows: %s'",
"%",
"nRows",
",",
"'west: %s'",
"%",
"west",
",",
"'east: %s'",
"%",
"east",
",",
"'south: %s'",
"%",
"south",
",",
"'north: %s'",
"%",
"north",
"]",
"# Insert grass headers into the grid",
"for",
"header",
"in",
"grassHeader",
":",
"arcInfoGrid",
".",
"insert",
"(",
"0",
",",
"header",
")",
"# Create string",
"arcInfoGridString",
"=",
"'\\n'",
".",
"join",
"(",
"arcInfoGrid",
")",
"return",
"arcInfoGridString"
]
| 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)
session = sessionMaker()
elif isinstance(sqlAlchemyEngineOrSession, Session):
session = sqlAlchemyEngineOrSession
# Execute statement
statement = 'SELECT * FROM st_gdaldrivers() ORDER BY short_name;'
result = session.execute(statement)
supported = dict()
for row in result:
supported[row[1]] = {'description': row[2], 'options': row[3]}
return supported | 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)
session = sessionMaker()
elif isinstance(sqlAlchemyEngineOrSession, Session):
session = sqlAlchemyEngineOrSession
# Execute statement
statement = 'SELECT * FROM st_gdaldrivers() ORDER BY short_name;'
result = session.execute(statement)
supported = dict()
for row in result:
supported[row[1]] = {'description': row[2], 'options': row[3]}
return supported | [
"def",
"supportedGdalRasterFormats",
"(",
"cls",
",",
"sqlAlchemyEngineOrSession",
")",
":",
"if",
"isinstance",
"(",
"sqlAlchemyEngineOrSession",
",",
"Engine",
")",
":",
"# Create sqlalchemy session",
"sessionMaker",
"=",
"sessionmaker",
"(",
"bind",
"=",
"sqlAlchemyEngineOrSession",
")",
"session",
"=",
"sessionMaker",
"(",
")",
"elif",
"isinstance",
"(",
"sqlAlchemyEngineOrSession",
",",
"Session",
")",
":",
"session",
"=",
"sqlAlchemyEngineOrSession",
"# Execute statement",
"statement",
"=",
"'SELECT * FROM st_gdaldrivers() ORDER BY short_name;'",
"result",
"=",
"session",
".",
"execute",
"(",
"statement",
")",
"supported",
"=",
"dict",
"(",
")",
"for",
"row",
"in",
"result",
":",
"supported",
"[",
"row",
"[",
"1",
"]",
"]",
"=",
"{",
"'description'",
":",
"row",
"[",
"2",
"]",
",",
"'options'",
":",
"row",
"[",
"3",
"]",
"}",
"return",
"supported"
]
| 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",
".",
"_colorRamp",
"=",
"colorRamp"
]
| 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
return req.status_code == 200 | 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
return req.status_code == 200 | [
"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",
"(",
"'kind'",
")",
"==",
"'Listing'",
":",
"# no subreddit exists, search results page is shown",
"return",
"False",
"return",
"req",
".",
"status_code",
"==",
"200"
]
| 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': 'CslBot/1.0'}).url
return '** %s - %s' % (get_title(url, apikey), get_short(url, apikey)) | 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': 'CslBot/1.0'}).url
return '** %s - %s' % (get_title(url, apikey), get_short(url, apikey)) | [
"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",
".",
"time",
"(",
")",
")",
"url",
"=",
"get",
"(",
"urlstr",
",",
"headers",
"=",
"{",
"'User-Agent'",
":",
"'CslBot/1.0'",
"}",
")",
".",
"url",
"return",
"'** %s - %s'",
"%",
"(",
"get_title",
"(",
"url",
",",
"apikey",
")",
",",
"get_short",
"(",
"url",
",",
"apikey",
")",
")"
]
| 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.split(',')
if len(cols) == len(self.hdrs):
#print(cols)
d = {}
for ndx, col_header in enumerate(self.hdrs):
#d[self.hdrs[ndx].strip('\n').strip()] = cols[ndx].strip('\n').strip()
d[col_header.strip('\n').strip()] = cols[ndx].strip('\n').strip()
lst.append(d)
else:
print("Error parsing " + self.fname + " line : " + line)
return lst | 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.split(',')
if len(cols) == len(self.hdrs):
#print(cols)
d = {}
for ndx, col_header in enumerate(self.hdrs):
#d[self.hdrs[ndx].strip('\n').strip()] = cols[ndx].strip('\n').strip()
d[col_header.strip('\n').strip()] = cols[ndx].strip('\n').strip()
lst.append(d)
else:
print("Error parsing " + self.fname + " line : " + line)
return lst | [
"def",
"parse_to_dict",
"(",
"self",
")",
":",
"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",
".",
"split",
"(",
"','",
")",
"if",
"len",
"(",
"cols",
")",
"==",
"len",
"(",
"self",
".",
"hdrs",
")",
":",
"#print(cols)",
"d",
"=",
"{",
"}",
"for",
"ndx",
",",
"col_header",
"in",
"enumerate",
"(",
"self",
".",
"hdrs",
")",
":",
"#d[self.hdrs[ndx].strip('\\n').strip()] = cols[ndx].strip('\\n').strip()",
"d",
"[",
"col_header",
".",
"strip",
"(",
"'\\n'",
")",
".",
"strip",
"(",
")",
"]",
"=",
"cols",
"[",
"ndx",
"]",
".",
"strip",
"(",
"'\\n'",
")",
".",
"strip",
"(",
")",
"lst",
".",
"append",
"(",
"d",
")",
"else",
":",
"print",
"(",
"\"Error parsing \"",
"+",
"self",
".",
"fname",
"+",
"\" line : \"",
"+",
"line",
")",
"return",
"lst"
]
| 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
stats = []
res = {}
for s in all_stats:
stats.append(s['stat'])
res[s['stat']] = 0
cur_stat = 0
for stat in stats:
for ndx, i in enumerate(self.classes.dat):
if i['name'] == ch_class:
cur_stat = int(i[stat]) # use stats for this class as baseline
for ndx, i in enumerate(self.races.dat):
if i['name'] == race:
cur_stat += int(i[stat]) # use stats for this race to modify base stats
#print(stat, cur_stat)
if cur_stat < 1:
cur_stat = 1
elif cur_stat > 10:
if stat not in ('Health', 'max_health'): # dont trim down health
cur_stat = 10
res[stat] = cur_stat
return res | 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
stats = []
res = {}
for s in all_stats:
stats.append(s['stat'])
res[s['stat']] = 0
cur_stat = 0
for stat in stats:
for ndx, i in enumerate(self.classes.dat):
if i['name'] == ch_class:
cur_stat = int(i[stat]) # use stats for this class as baseline
for ndx, i in enumerate(self.races.dat):
if i['name'] == race:
cur_stat += int(i[stat]) # use stats for this race to modify base stats
#print(stat, cur_stat)
if cur_stat < 1:
cur_stat = 1
elif cur_stat > 10:
if stat not in ('Health', 'max_health'): # dont trim down health
cur_stat = 10
res[stat] = cur_stat
return res | [
"def",
"random_stats",
"(",
"self",
",",
"all_stats",
",",
"race",
",",
"ch_class",
")",
":",
"# create blank list of stats to be generated",
"stats",
"=",
"[",
"]",
"res",
"=",
"{",
"}",
"for",
"s",
"in",
"all_stats",
":",
"stats",
".",
"append",
"(",
"s",
"[",
"'stat'",
"]",
")",
"res",
"[",
"s",
"[",
"'stat'",
"]",
"]",
"=",
"0",
"cur_stat",
"=",
"0",
"for",
"stat",
"in",
"stats",
":",
"for",
"ndx",
",",
"i",
"in",
"enumerate",
"(",
"self",
".",
"classes",
".",
"dat",
")",
":",
"if",
"i",
"[",
"'name'",
"]",
"==",
"ch_class",
":",
"cur_stat",
"=",
"int",
"(",
"i",
"[",
"stat",
"]",
")",
"# use stats for this class as baseline",
"for",
"ndx",
",",
"i",
"in",
"enumerate",
"(",
"self",
".",
"races",
".",
"dat",
")",
":",
"if",
"i",
"[",
"'name'",
"]",
"==",
"race",
":",
"cur_stat",
"+=",
"int",
"(",
"i",
"[",
"stat",
"]",
")",
"# use stats for this race to modify base stats",
"#print(stat, cur_stat)",
"if",
"cur_stat",
"<",
"1",
":",
"cur_stat",
"=",
"1",
"elif",
"cur_stat",
">",
"10",
":",
"if",
"stat",
"not",
"in",
"(",
"'Health'",
",",
"'max_health'",
")",
":",
"# dont trim down health",
"cur_stat",
"=",
"10",
"res",
"[",
"stat",
"]",
"=",
"cur_stat",
"return",
"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_line_to_self",
"(",
"k",
",",
"v",
")"
]
| 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): ' , k, v)
if k == 'CHARACTER':
self.name = v
elif k == 'Race':
self.race = v
elif k == 'Class':
self.ch_class = v
elif k == 'STATS':
self.stats = self._extract_stats_from_line(v)
elif k == 'Story':
self.story = v.strip(' ').strip('\n')
elif k == 'SKILLS':
self.skills = v.split(', ')
elif k == 'INVENTORY':
self.inventory = v.split(', ') | 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): ' , k, v)
if k == 'CHARACTER':
self.name = v
elif k == 'Race':
self.race = v
elif k == 'Class':
self.ch_class = v
elif k == 'STATS':
self.stats = self._extract_stats_from_line(v)
elif k == 'Story':
self.story = v.strip(' ').strip('\n')
elif k == 'SKILLS':
self.skills = v.split(', ')
elif k == 'INVENTORY':
self.inventory = v.split(', ') | [
"def",
"_parse_char_line_to_self",
"(",
"self",
",",
"k",
",",
"v",
")",
":",
"k",
"=",
"k",
".",
"strip",
"(",
"' '",
")",
".",
"strip",
"(",
"'\\n'",
")",
"v",
"=",
"v",
".",
"strip",
"(",
"' '",
")",
".",
"strip",
"(",
"'\\n'",
")",
"# print('_parse_char_line_to_self(self, k,v): ' , k, v)",
"if",
"k",
"==",
"'CHARACTER'",
":",
"self",
".",
"name",
"=",
"v",
"elif",
"k",
"==",
"'Race'",
":",
"self",
".",
"race",
"=",
"v",
"elif",
"k",
"==",
"'Class'",
":",
"self",
".",
"ch_class",
"=",
"v",
"elif",
"k",
"==",
"'STATS'",
":",
"self",
".",
"stats",
"=",
"self",
".",
"_extract_stats_from_line",
"(",
"v",
")",
"elif",
"k",
"==",
"'Story'",
":",
"self",
".",
"story",
"=",
"v",
".",
"strip",
"(",
"' '",
")",
".",
"strip",
"(",
"'\\n'",
")",
"elif",
"k",
"==",
"'SKILLS'",
":",
"self",
".",
"skills",
"=",
"v",
".",
"split",
"(",
"', '",
")",
"elif",
"k",
"==",
"'INVENTORY'",
":",
"self",
".",
"inventory",
"=",
"v",
".",
"split",
"(",
"', '",
")"
]
| 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",
".",
"inventory",
")"
]
| 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.selections = {}
selection = "%s%s" % (str(fg), str(bg))
if not selection in palette.selections:
palette.selections[selection] = palette.counter
palette.counter += 1
# Get available colours
colors = [c for c in dir(_curses) if c.startswith('COLOR')]
if isinstance(fg, str):
if not "COLOR_"+fg.upper() in colors:
fg = -1
else:
fg = getattr(_curses, "COLOR_"+fg.upper())
if isinstance(bg, str):
if not "COLOR_"+bg.upper() in colors:
bg = -1
else:
bg = getattr(_curses, "COLOR_"+bg.upper())
_curses.init_pair(palette.selections[selection], fg, bg)
return _curses.color_pair(palette.selections[selection]) | 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.selections = {}
selection = "%s%s" % (str(fg), str(bg))
if not selection in palette.selections:
palette.selections[selection] = palette.counter
palette.counter += 1
# Get available colours
colors = [c for c in dir(_curses) if c.startswith('COLOR')]
if isinstance(fg, str):
if not "COLOR_"+fg.upper() in colors:
fg = -1
else:
fg = getattr(_curses, "COLOR_"+fg.upper())
if isinstance(bg, str):
if not "COLOR_"+bg.upper() in colors:
bg = -1
else:
bg = getattr(_curses, "COLOR_"+bg.upper())
_curses.init_pair(palette.selections[selection], fg, bg)
return _curses.color_pair(palette.selections[selection]) | [
"def",
"palette",
"(",
"fg",
",",
"bg",
"=",
"-",
"1",
")",
":",
"if",
"not",
"hasattr",
"(",
"palette",
",",
"\"counter\"",
")",
":",
"palette",
".",
"counter",
"=",
"1",
"if",
"not",
"hasattr",
"(",
"palette",
",",
"\"selections\"",
")",
":",
"palette",
".",
"selections",
"=",
"{",
"}",
"selection",
"=",
"\"%s%s\"",
"%",
"(",
"str",
"(",
"fg",
")",
",",
"str",
"(",
"bg",
")",
")",
"if",
"not",
"selection",
"in",
"palette",
".",
"selections",
":",
"palette",
".",
"selections",
"[",
"selection",
"]",
"=",
"palette",
".",
"counter",
"palette",
".",
"counter",
"+=",
"1",
"# Get available colours",
"colors",
"=",
"[",
"c",
"for",
"c",
"in",
"dir",
"(",
"_curses",
")",
"if",
"c",
".",
"startswith",
"(",
"'COLOR'",
")",
"]",
"if",
"isinstance",
"(",
"fg",
",",
"str",
")",
":",
"if",
"not",
"\"COLOR_\"",
"+",
"fg",
".",
"upper",
"(",
")",
"in",
"colors",
":",
"fg",
"=",
"-",
"1",
"else",
":",
"fg",
"=",
"getattr",
"(",
"_curses",
",",
"\"COLOR_\"",
"+",
"fg",
".",
"upper",
"(",
")",
")",
"if",
"isinstance",
"(",
"bg",
",",
"str",
")",
":",
"if",
"not",
"\"COLOR_\"",
"+",
"bg",
".",
"upper",
"(",
")",
"in",
"colors",
":",
"bg",
"=",
"-",
"1",
"else",
":",
"bg",
"=",
"getattr",
"(",
"_curses",
",",
"\"COLOR_\"",
"+",
"bg",
".",
"upper",
"(",
")",
")",
"_curses",
".",
"init_pair",
"(",
"palette",
".",
"selections",
"[",
"selection",
"]",
",",
"fg",
",",
"bg",
")",
"return",
"_curses",
".",
"color_pair",
"(",
"palette",
".",
"selections",
"[",
"selection",
"]",
")"
]
| 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()
_curses.cbreak()
_curses.nonl()
_curses.curs_set(0)
if self.blocking:
self.window.nodelay(0)
else:
self.window.nodelay(1)
self.running = True
while self.running:
self.cycle()
if self.friendly and not self.blocking:
time.sleep(self.delay)
self.stop() | 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()
_curses.cbreak()
_curses.nonl()
_curses.curs_set(0)
if self.blocking:
self.window.nodelay(0)
else:
self.window.nodelay(1)
self.running = True
while self.running:
self.cycle()
if self.friendly and not self.blocking:
time.sleep(self.delay)
self.stop() | [
"def",
"start",
"(",
"self",
")",
":",
"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",
"(",
")",
"_curses",
".",
"cbreak",
"(",
")",
"_curses",
".",
"nonl",
"(",
")",
"_curses",
".",
"curs_set",
"(",
"0",
")",
"if",
"self",
".",
"blocking",
":",
"self",
".",
"window",
".",
"nodelay",
"(",
"0",
")",
"else",
":",
"self",
".",
"window",
".",
"nodelay",
"(",
"1",
")",
"self",
".",
"running",
"=",
"True",
"while",
"self",
".",
"running",
":",
"self",
".",
"cycle",
"(",
")",
"if",
"self",
".",
"friendly",
"and",
"not",
"self",
".",
"blocking",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"delay",
")",
"self",
".",
"stop",
"(",
")"
]
| 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",
".",
"running",
"=",
"False"
]
| 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 for floating panes and self-coordinating panes adjacent to panes set to EXPAND.
Coordinates are of the form:
[
((top-left-from-top, top-left-from-left),
(top-right-from-top, top-right-from-left)),
((bottom-left-from-top, bottom-left-from-left),
(bottom-right-from-top, bottom-right-from-left))
]
We can then use these to determine things such as whether corners are inverted and how
many characters may be drawn
"""
y = 0 # height
for i, element in enumerate(self.panes):
x = 0 # width
if isinstance(element, list):
current_height = 0
for j, pane in enumerate(element):
if pane.hidden: continue
current_width = pane.width
current_height = pane.height
upper = ((y, x), (y, x+current_width))
lower = ((y+(current_height if current_height > 1 else 0), x),
(y+(current_height if current_height > 1 else 0), x+current_width))
pane.coords = [upper, lower]
x += current_width
y += (current_height+1 if current_height > 1 else 1)
else:
if element.hidden: continue
current_width = element.width
current_height = element.height
upper = ((y, x), (y, x+current_width))
lower = ((y+(current_height if current_height > 1 else 0), x),
(y+(current_height if current_height > 1 else 0), x+current_width))
element.coords = [upper, lower]
y += (current_height+1 if current_height > 1 else 1)
if self.debug:
coordinates = "Coordinates: " + str([p.coords for p in self])
if len(coordinates) > self.width:
coordinates = coordinates[:self.width - 3]
coordinates += '...'
self.addstr(self.height-3, 0, coordinates) | 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 for floating panes and self-coordinating panes adjacent to panes set to EXPAND.
Coordinates are of the form:
[
((top-left-from-top, top-left-from-left),
(top-right-from-top, top-right-from-left)),
((bottom-left-from-top, bottom-left-from-left),
(bottom-right-from-top, bottom-right-from-left))
]
We can then use these to determine things such as whether corners are inverted and how
many characters may be drawn
"""
y = 0 # height
for i, element in enumerate(self.panes):
x = 0 # width
if isinstance(element, list):
current_height = 0
for j, pane in enumerate(element):
if pane.hidden: continue
current_width = pane.width
current_height = pane.height
upper = ((y, x), (y, x+current_width))
lower = ((y+(current_height if current_height > 1 else 0), x),
(y+(current_height if current_height > 1 else 0), x+current_width))
pane.coords = [upper, lower]
x += current_width
y += (current_height+1 if current_height > 1 else 1)
else:
if element.hidden: continue
current_width = element.width
current_height = element.height
upper = ((y, x), (y, x+current_width))
lower = ((y+(current_height if current_height > 1 else 0), x),
(y+(current_height if current_height > 1 else 0), x+current_width))
element.coords = [upper, lower]
y += (current_height+1 if current_height > 1 else 1)
if self.debug:
coordinates = "Coordinates: " + str([p.coords for p in self])
if len(coordinates) > self.width:
coordinates = coordinates[:self.width - 3]
coordinates += '...'
self.addstr(self.height-3, 0, coordinates) | [
"def",
"coordinate",
"(",
"self",
",",
"panes",
"=",
"[",
"]",
",",
"index",
"=",
"0",
")",
":",
"y",
"=",
"0",
"# height",
"for",
"i",
",",
"element",
"in",
"enumerate",
"(",
"self",
".",
"panes",
")",
":",
"x",
"=",
"0",
"# width",
"if",
"isinstance",
"(",
"element",
",",
"list",
")",
":",
"current_height",
"=",
"0",
"for",
"j",
",",
"pane",
"in",
"enumerate",
"(",
"element",
")",
":",
"if",
"pane",
".",
"hidden",
":",
"continue",
"current_width",
"=",
"pane",
".",
"width",
"current_height",
"=",
"pane",
".",
"height",
"upper",
"=",
"(",
"(",
"y",
",",
"x",
")",
",",
"(",
"y",
",",
"x",
"+",
"current_width",
")",
")",
"lower",
"=",
"(",
"(",
"y",
"+",
"(",
"current_height",
"if",
"current_height",
">",
"1",
"else",
"0",
")",
",",
"x",
")",
",",
"(",
"y",
"+",
"(",
"current_height",
"if",
"current_height",
">",
"1",
"else",
"0",
")",
",",
"x",
"+",
"current_width",
")",
")",
"pane",
".",
"coords",
"=",
"[",
"upper",
",",
"lower",
"]",
"x",
"+=",
"current_width",
"y",
"+=",
"(",
"current_height",
"+",
"1",
"if",
"current_height",
">",
"1",
"else",
"1",
")",
"else",
":",
"if",
"element",
".",
"hidden",
":",
"continue",
"current_width",
"=",
"element",
".",
"width",
"current_height",
"=",
"element",
".",
"height",
"upper",
"=",
"(",
"(",
"y",
",",
"x",
")",
",",
"(",
"y",
",",
"x",
"+",
"current_width",
")",
")",
"lower",
"=",
"(",
"(",
"y",
"+",
"(",
"current_height",
"if",
"current_height",
">",
"1",
"else",
"0",
")",
",",
"x",
")",
",",
"(",
"y",
"+",
"(",
"current_height",
"if",
"current_height",
">",
"1",
"else",
"0",
")",
",",
"x",
"+",
"current_width",
")",
")",
"element",
".",
"coords",
"=",
"[",
"upper",
",",
"lower",
"]",
"y",
"+=",
"(",
"current_height",
"+",
"1",
"if",
"current_height",
">",
"1",
"else",
"1",
")",
"if",
"self",
".",
"debug",
":",
"coordinates",
"=",
"\"Coordinates: \"",
"+",
"str",
"(",
"[",
"p",
".",
"coords",
"for",
"p",
"in",
"self",
"]",
")",
"if",
"len",
"(",
"coordinates",
")",
">",
"self",
".",
"width",
":",
"coordinates",
"=",
"coordinates",
"[",
":",
"self",
".",
"width",
"-",
"3",
"]",
"coordinates",
"+=",
"'...'",
"self",
".",
"addstr",
"(",
"self",
".",
"height",
"-",
"3",
",",
"0",
",",
"coordinates",
")"
]
| 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 panes set to EXPAND.
Coordinates are of the form:
[
((top-left-from-top, top-left-from-left),
(top-right-from-top, top-right-from-left)),
((bottom-left-from-top, bottom-left-from-left),
(bottom-right-from-top, bottom-right-from-left))
]
We can then use these to determine things such as whether corners are inverted and how
many characters may be drawn | [
"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, text.encode("ascii", "ignore"), attrs)
self.window.addstr(h, w, text, attrs)
except Exception as e:
pass | 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, text.encode("ascii", "ignore"), attrs)
self.window.addstr(h, w, text, attrs)
except Exception as e:
pass | [
"def",
"addstr",
"(",
"self",
",",
"h",
",",
"w",
",",
"text",
",",
"attrs",
"=",
"0",
")",
":",
"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, text.encode(\"ascii\", \"ignore\"), attrs)",
"self",
".",
"window",
".",
"addstr",
"(",
"h",
",",
"w",
",",
"text",
",",
"attrs",
")",
"except",
"Exception",
"as",
"e",
":",
"pass"
]
| 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 = height, width
self.window.clear() | 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 = height, width
self.window.clear() | [
"def",
"update_window_size",
"(",
"self",
")",
":",
"height",
",",
"width",
"=",
"self",
".",
"window",
".",
"getmaxyx",
"(",
")",
"if",
"self",
".",
"height",
"!=",
"height",
"or",
"self",
".",
"width",
"!=",
"width",
":",
"self",
".",
"height",
",",
"self",
".",
"width",
"=",
"height",
",",
"width",
"self",
".",
"window",
".",
"clear",
"(",
")"
]
| 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:
pane = self.init_pane(pane)
self.panes.append(pane) | 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:
pane = self.init_pane(pane)
self.panes.append(pane) | [
"def",
"add",
"(",
"self",
",",
"pane",
")",
":",
"if",
"isinstance",
"(",
"pane",
",",
"list",
")",
":",
"initialised_panes",
"=",
"[",
"]",
"for",
"p",
"in",
"pane",
":",
"initialised_panes",
".",
"append",
"(",
"self",
".",
"init_pane",
"(",
"p",
")",
")",
"self",
".",
"panes",
".",
"append",
"(",
"initialised_panes",
")",
"else",
":",
"pane",
"=",
"self",
".",
"init_pane",
"(",
"pane",
")",
"self",
".",
"panes",
".",
"append",
"(",
"pane",
")"
]
| 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
for pane in self:
if pane.name == name:
return pane
return default | 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
for pane in self:
if pane.name == name:
return pane
return default | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"cache",
"=",
"False",
")",
":",
"if",
"cache",
"==",
"True",
":",
"for",
"pane",
"in",
"self",
".",
"cache",
":",
"if",
"pane",
".",
"name",
"==",
"name",
":",
"return",
"pane",
"return",
"default",
"for",
"pane",
"in",
"self",
":",
"if",
"pane",
".",
"name",
"==",
"name",
":",
"return",
"pane",
"return",
"default"
]
| 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",
":",
"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:
send("I'll have you know that standards compliance is important.")
return
tmpfile = tempfile.NamedTemporaryFile()
for line in msg.splitlines():
line = line + '\n'
tmpfile.write(line.encode())
tmpfile.flush()
process = subprocess.run(['gcc', '-o', '/dev/null', '-xc', tmpfile.name],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=5,
universal_newlines=True)
tmpfile.close()
# Take the last 3 lines to prevent Excess Flood on long error messages
output = process.stdout.splitlines()[:3]
for line in output:
send(line, target=args['nick'])
if process.returncode == 0:
send(gen_slogan("gcc victory"))
else:
send(gen_slogan("gcc failed")) | 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:
send("I'll have you know that standards compliance is important.")
return
tmpfile = tempfile.NamedTemporaryFile()
for line in msg.splitlines():
line = line + '\n'
tmpfile.write(line.encode())
tmpfile.flush()
process = subprocess.run(['gcc', '-o', '/dev/null', '-xc', tmpfile.name],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=5,
universal_newlines=True)
tmpfile.close()
# Take the last 3 lines to prevent Excess Flood on long error messages
output = process.stdout.splitlines()[:3]
for line in output:
send(line, target=args['nick'])
if process.returncode == 0:
send(gen_slogan("gcc victory"))
else:
send(gen_slogan("gcc failed")) | [
"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 inclusive community around here.\"",
")",
"return",
"if",
"'import'",
"in",
"msg",
":",
"send",
"(",
"\"I'll have you know that standards compliance is important.\"",
")",
"return",
"tmpfile",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
")",
"for",
"line",
"in",
"msg",
".",
"splitlines",
"(",
")",
":",
"line",
"=",
"line",
"+",
"'\\n'",
"tmpfile",
".",
"write",
"(",
"line",
".",
"encode",
"(",
")",
")",
"tmpfile",
".",
"flush",
"(",
")",
"process",
"=",
"subprocess",
".",
"run",
"(",
"[",
"'gcc'",
",",
"'-o'",
",",
"'/dev/null'",
",",
"'-xc'",
",",
"tmpfile",
".",
"name",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"timeout",
"=",
"5",
",",
"universal_newlines",
"=",
"True",
")",
"tmpfile",
".",
"close",
"(",
")",
"# Take the last 3 lines to prevent Excess Flood on long error messages",
"output",
"=",
"process",
".",
"stdout",
".",
"splitlines",
"(",
")",
"[",
":",
"3",
"]",
"for",
"line",
"in",
"output",
":",
"send",
"(",
"line",
",",
"target",
"=",
"args",
"[",
"'nick'",
"]",
")",
"if",
"process",
".",
"returncode",
"==",
"0",
":",
"send",
"(",
"gen_slogan",
"(",
"\"gcc victory\"",
")",
")",
"else",
":",
"send",
"(",
"gen_slogan",
"(",
"\"gcc failed\"",
")",
")"
]
| 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/images'
params = {
'page': page,
'per_page': per_page
}
response = self._request_url(
url, 'get', params=params, with_access_token=True)
headers, result = self._parse_and_check(response)
images = ImageList.from_list(result)
images.set_attributes_from_headers(headers)
return images | 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/images'
params = {
'page': page,
'per_page': per_page
}
response = self._request_url(
url, 'get', params=params, with_access_token=True)
headers, result = self._parse_and_check(response)
images = ImageList.from_list(result)
images.set_attributes_from_headers(headers)
return images | [
"def",
"get_image_list",
"(",
"self",
",",
"page",
"=",
"1",
",",
"per_page",
"=",
"20",
")",
":",
"url",
"=",
"self",
".",
"api_url",
"+",
"'/api/images'",
"params",
"=",
"{",
"'page'",
":",
"page",
",",
"'per_page'",
":",
"per_page",
"}",
"response",
"=",
"self",
".",
"_request_url",
"(",
"url",
",",
"'get'",
",",
"params",
"=",
"params",
",",
"with_access_token",
"=",
"True",
")",
"headers",
",",
"result",
"=",
"self",
".",
"_parse_and_check",
"(",
"response",
")",
"images",
"=",
"ImageList",
".",
"from_list",
"(",
"result",
")",
"images",
".",
"set_attributes_from_headers",
"(",
"headers",
")",
"return",
"images"
]
| 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 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
"""
url = self.upload_url + '/api/upload'
data = {}
if referer_url is not None:
data['referer_url'] = referer_url
if title is not None:
data['title'] = title
if desc is not None:
data['desc'] = desc
if created_at is not None:
data['created_at'] = str(created_at)
if collection_id is not None:
data['collection_id'] = collection_id
files = {
'imagedata': image_file
}
response = self._request_url(
url, 'post', data=data, files=files, with_access_token=True)
headers, result = self._parse_and_check(response)
return Image.from_dict(result) | 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 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
"""
url = self.upload_url + '/api/upload'
data = {}
if referer_url is not None:
data['referer_url'] = referer_url
if title is not None:
data['title'] = title
if desc is not None:
data['desc'] = desc
if created_at is not None:
data['created_at'] = str(created_at)
if collection_id is not None:
data['collection_id'] = collection_id
files = {
'imagedata': image_file
}
response = self._request_url(
url, 'post', data=data, files=files, with_access_token=True)
headers, result = self._parse_and_check(response)
return Image.from_dict(result) | [
"def",
"upload_image",
"(",
"self",
",",
"image_file",
",",
"referer_url",
"=",
"None",
",",
"title",
"=",
"None",
",",
"desc",
"=",
"None",
",",
"created_at",
"=",
"None",
",",
"collection_id",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"upload_url",
"+",
"'/api/upload'",
"data",
"=",
"{",
"}",
"if",
"referer_url",
"is",
"not",
"None",
":",
"data",
"[",
"'referer_url'",
"]",
"=",
"referer_url",
"if",
"title",
"is",
"not",
"None",
":",
"data",
"[",
"'title'",
"]",
"=",
"title",
"if",
"desc",
"is",
"not",
"None",
":",
"data",
"[",
"'desc'",
"]",
"=",
"desc",
"if",
"created_at",
"is",
"not",
"None",
":",
"data",
"[",
"'created_at'",
"]",
"=",
"str",
"(",
"created_at",
")",
"if",
"collection_id",
"is",
"not",
"None",
":",
"data",
"[",
"'collection_id'",
"]",
"=",
"collection_id",
"files",
"=",
"{",
"'imagedata'",
":",
"image_file",
"}",
"response",
"=",
"self",
".",
"_request_url",
"(",
"url",
",",
"'post'",
",",
"data",
"=",
"data",
",",
"files",
"=",
"files",
",",
"with_access_token",
"=",
"True",
")",
"headers",
",",
"result",
"=",
"self",
".",
"_parse_and_check",
"(",
"response",
")",
"return",
"Image",
".",
"from_dict",
"(",
"result",
")"
]
| 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=parameters)
headers, result = self._parse_and_check(response)
return result | 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=parameters)
headers, result = self._parse_and_check(response)
return result | [
"def",
"get_oembed",
"(",
"self",
",",
"url",
")",
":",
"api_url",
"=",
"self",
".",
"api_url",
"+",
"'/api/oembed'",
"parameters",
"=",
"{",
"'url'",
":",
"url",
"}",
"response",
"=",
"self",
".",
"_request_url",
"(",
"api_url",
",",
"'get'",
",",
"params",
"=",
"parameters",
")",
"headers",
",",
"result",
"=",
"self",
".",
"_parse_and_check",
"(",
"response",
")",
"return",
"result"
]
| 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
: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 GyazoError:
"""
headers = {} # type: Dict[str, Any]
if data is None:
data = {}
if params is None:
params = {}
if with_client_id and self._client_id is not None:
params['client_id'] = self._client_id
if with_access_token and self._access_token is not None:
headers['Authorization'] = "Bearer " + self._access_token
try:
return requests.request(method, url,
params=params,
data=data,
files=files,
headers=headers)
except requests.RequestException as e:
raise GyazoError(str(e)) | 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
: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 GyazoError:
"""
headers = {} # type: Dict[str, Any]
if data is None:
data = {}
if params is None:
params = {}
if with_client_id and self._client_id is not None:
params['client_id'] = self._client_id
if with_access_token and self._access_token is not None:
headers['Authorization'] = "Bearer " + self._access_token
try:
return requests.request(method, url,
params=params,
data=data,
files=files,
headers=headers)
except requests.RequestException as e:
raise GyazoError(str(e)) | [
"def",
"_request_url",
"(",
"self",
",",
"url",
",",
"method",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"files",
"=",
"None",
",",
"with_client_id",
"=",
"False",
",",
"with_access_token",
"=",
"False",
")",
":",
"headers",
"=",
"{",
"}",
"# type: Dict[str, Any]",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"if",
"with_client_id",
"and",
"self",
".",
"_client_id",
"is",
"not",
"None",
":",
"params",
"[",
"'client_id'",
"]",
"=",
"self",
".",
"_client_id",
"if",
"with_access_token",
"and",
"self",
".",
"_access_token",
"is",
"not",
"None",
":",
"headers",
"[",
"'Authorization'",
"]",
"=",
"\"Bearer \"",
"+",
"self",
".",
"_access_token",
"try",
":",
"return",
"requests",
".",
"request",
"(",
"method",
",",
"url",
",",
"params",
"=",
"params",
",",
"data",
"=",
"data",
",",
"files",
"=",
"files",
",",
"headers",
"=",
"headers",
")",
"except",
"requests",
".",
"RequestException",
"as",
"e",
":",
"raise",
"GyazoError",
"(",
"str",
"(",
"e",
")",
")"
]
| 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 GyazoError: | [
"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(message) | 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(message) | [
"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",
"in",
"data",
":",
"if",
"len",
"(",
"row",
")",
"!=",
"length",
":",
"raise",
"exception",
"(",
"message",
")"
]
| 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, columns)
if rows != columns:
raise exception(message) | 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, columns)
if rows != columns:
raise exception(message) | [
"def",
"validate_square",
"(",
"data",
",",
"message",
"=",
"None",
",",
"exception",
"=",
"MatrixError",
")",
":",
"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",
",",
"columns",
")",
"if",
"rows",
"!=",
"columns",
":",
"raise",
"exception",
"(",
"message",
")"
]
| 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:
message = 'Number of categories: %s != number of entities: %s' % (
nb_categories, nb_entities)
if categories and nb_categories != nb_entities:
raise exception(message) | 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:
message = 'Number of categories: %s != number of entities: %s' % (
nb_categories, nb_entities)
if categories and nb_categories != nb_entities:
raise exception(message) | [
"def",
"validate_categories_equal_entities",
"(",
"categories",
",",
"entities",
",",
"message",
"=",
"None",
",",
"exception",
"=",
"MatrixError",
")",
":",
"nb_categories",
"=",
"len",
"(",
"categories",
")",
"nb_entities",
"=",
"len",
"(",
"entities",
")",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"'Number of categories: %s != number of entities: %s'",
"%",
"(",
"nb_categories",
",",
"nb_entities",
")",
"if",
"categories",
"and",
"nb_categories",
"!=",
"nb_entities",
":",
"raise",
"exception",
"(",
"message",
")"
]
| 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 entities: %s != number of rows: %s'",
"%",
"(",
"nb_entities",
",",
"self",
".",
"rows",
")",
")"
]
| 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]:
data[i][j] = 1
return data | 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]:
data[i][j] = 1
return data | [
"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",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"rows",
")",
":",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"rows",
")",
":",
"if",
"data",
"[",
"i",
"]",
"[",
"k",
"]",
"and",
"data",
"[",
"k",
"]",
"[",
"j",
"]",
":",
"data",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"1",
"return",
"data"
]
| 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 columns: %s+%s=%s' % (
nb_entities, self.rows, self.columns,
self.rows + self.columns)) | 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 columns: %s+%s=%s' % (
nb_entities, self.rows, self.columns,
self.rows + self.columns)) | [
"def",
"validate",
"(",
"self",
")",
":",
"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 columns: %s+%s=%s'",
"%",
"(",
"nb_entities",
",",
"self",
".",
"rows",
",",
"self",
".",
"columns",
",",
"self",
".",
"rows",
"+",
"self",
".",
"columns",
")",
")"
]
| 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 '\
'DomainMappingMatrix or MultipleDomainMatrix.'
messages = []
for i, row in enumerate(self.data):
for j, cell in enumerate(row):
if i == j:
if not isinstance(cell, (
DesignStructureMatrix, MultipleDomainMatrix)):
messages.append(message_dsm % (i, j))
elif not isinstance(cell, (
DomainMappingMatrix, MultipleDomainMatrix)):
messages.append(message_ddm % (i, j))
if messages:
raise self.error('\n'.join(messages)) | 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 '\
'DomainMappingMatrix or MultipleDomainMatrix.'
messages = []
for i, row in enumerate(self.data):
for j, cell in enumerate(row):
if i == j:
if not isinstance(cell, (
DesignStructureMatrix, MultipleDomainMatrix)):
messages.append(message_dsm % (i, j))
elif not isinstance(cell, (
DomainMappingMatrix, MultipleDomainMatrix)):
messages.append(message_ddm % (i, j))
if messages:
raise self.error('\n'.join(messages)) | [
"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 '",
"'DomainMappingMatrix or MultipleDomainMatrix.'",
"messages",
"=",
"[",
"]",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"self",
".",
"data",
")",
":",
"for",
"j",
",",
"cell",
"in",
"enumerate",
"(",
"row",
")",
":",
"if",
"i",
"==",
"j",
":",
"if",
"not",
"isinstance",
"(",
"cell",
",",
"(",
"DesignStructureMatrix",
",",
"MultipleDomainMatrix",
")",
")",
":",
"messages",
".",
"append",
"(",
"message_dsm",
"%",
"(",
"i",
",",
"j",
")",
")",
"elif",
"not",
"isinstance",
"(",
"cell",
",",
"(",
"DomainMappingMatrix",
",",
"MultipleDomainMatrix",
")",
")",
":",
"messages",
".",
"append",
"(",
"message_ddm",
"%",
"(",
"i",
",",
"j",
")",
")",
"if",
"messages",
":",
"raise",
"self",
".",
"error",
"(",
"'\\n'",
".",
"join",
"(",
"messages",
")",
")"
]
| 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",
",",
":",
"]",
"-",
"self",
".",
"centroids",
"[",
"self",
".",
"clusters",
"[",
"i",
"]",
"]",
")",
"**",
"2",
"for",
"i",
"in",
"range",
"(",
"m",
")",
")",
"return",
"self",
".",
"distortion"
]
| 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
else:
self.n_clusters-=1
self.centroids = self.centroids[:self.n_clusters]
self.clusters-=1
k-=1 | 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
else:
self.n_clusters-=1
self.centroids = self.centroids[:self.n_clusters]
self.clusters-=1
k-=1 | [
"def",
"_move_centroids",
"(",
"self",
")",
":",
"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",
"else",
":",
"self",
".",
"n_clusters",
"-=",
"1",
"self",
".",
"centroids",
"=",
"self",
".",
"centroids",
"[",
":",
"self",
".",
"n_clusters",
"]",
"self",
".",
"clusters",
"-=",
"1",
"k",
"-=",
"1"
]
| 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:
closest_centroid = i
distance = current_distance
return closest_centroid | 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:
closest_centroid = i
distance = current_distance
return closest_centroid | [
"def",
"_closest_centroid",
"(",
"self",
",",
"x",
")",
":",
"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",
":",
"closest_centroid",
"=",
"i",
"distance",
"=",
"current_distance",
"return",
"closest_centroid"
]
| 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()
self._move_centroids()
if np.all(prev_clusters == self.clusters):
break
self._calc_distortion()
candidates.append((self.distortion, self.centroids, self.clusters))
candidates.sort(key=lambda x: x[0])
self.distortion = candidates[0][0]
self.centroids = candidates[0][1]
self.clusters = candidates[0][2]
return self | 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()
self._move_centroids()
if np.all(prev_clusters == self.clusters):
break
self._calc_distortion()
candidates.append((self.distortion, self.centroids, self.clusters))
candidates.sort(key=lambda x: x[0])
self.distortion = candidates[0][0]
self.centroids = candidates[0][1]
self.clusters = candidates[0][2]
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
")",
":",
"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",
"(",
")",
"self",
".",
"_move_centroids",
"(",
")",
"if",
"np",
".",
"all",
"(",
"prev_clusters",
"==",
"self",
".",
"clusters",
")",
":",
"break",
"self",
".",
"_calc_distortion",
"(",
")",
"candidates",
".",
"append",
"(",
"(",
"self",
".",
"distortion",
",",
"self",
".",
"centroids",
",",
"self",
".",
"clusters",
")",
")",
"candidates",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
"self",
".",
"distortion",
"=",
"candidates",
"[",
"0",
"]",
"[",
"0",
"]",
"self",
".",
"centroids",
"=",
"candidates",
"[",
"0",
"]",
"[",
"1",
"]",
"self",
".",
"clusters",
"=",
"candidates",
"[",
"0",
"]",
"[",
"2",
"]",
"return",
"self"
]
| 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], [abbrev, noun, verb, adj, noun, verb, abbrev, noun],
[ingverb, noun, verb, adj, abbrev, noun], [verb, adj, abbrev, noun, verb, abbrev, noun]]
msgtype = [
"If we %s the %s, we can get to the %s %s through the %s %s %s!" % tuple(map(choice, words[0])),
"We need to %s the %s %s %s!" % tuple(map(choice, words[1])),
"Try to %s the %s %s, maybe it will %s the %s %s!" % tuple(map(choice, words[2])),
"You can't %s the %s without %s the %s %s %s!" % tuple(map(choice, words[3])),
"Use the %s %s %s, then you can %s the %s %s!" % tuple(map(choice, words[4])),
"The %s %s is down, %s the %s %s so we can %s the %s %s!" % tuple(map(choice, words[5])),
"%s the %s won't do anything, we need to %s the %s %s %s!" % tuple(map(choice, words[6])),
"I'll %s the %s %s %s, that should %s the %s %s!" % tuple(map(choice, words[7]))
]
send(choice(msgtype)) | 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], [abbrev, noun, verb, adj, noun, verb, abbrev, noun],
[ingverb, noun, verb, adj, abbrev, noun], [verb, adj, abbrev, noun, verb, abbrev, noun]]
msgtype = [
"If we %s the %s, we can get to the %s %s through the %s %s %s!" % tuple(map(choice, words[0])),
"We need to %s the %s %s %s!" % tuple(map(choice, words[1])),
"Try to %s the %s %s, maybe it will %s the %s %s!" % tuple(map(choice, words[2])),
"You can't %s the %s without %s the %s %s %s!" % tuple(map(choice, words[3])),
"Use the %s %s %s, then you can %s the %s %s!" % tuple(map(choice, words[4])),
"The %s %s is down, %s the %s %s so we can %s the %s %s!" % tuple(map(choice, words[5])),
"%s the %s won't do anything, we need to %s the %s %s %s!" % tuple(map(choice, words[6])),
"I'll %s the %s %s %s, that should %s the %s %s!" % tuple(map(choice, words[7]))
]
send(choice(msgtype)) | [
"def",
"cmd",
"(",
"send",
",",
"*",
"_",
")",
":",
"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",
"]",
",",
"[",
"abbrev",
",",
"noun",
",",
"verb",
",",
"adj",
",",
"noun",
",",
"verb",
",",
"abbrev",
",",
"noun",
"]",
",",
"[",
"ingverb",
",",
"noun",
",",
"verb",
",",
"adj",
",",
"abbrev",
",",
"noun",
"]",
",",
"[",
"verb",
",",
"adj",
",",
"abbrev",
",",
"noun",
",",
"verb",
",",
"abbrev",
",",
"noun",
"]",
"]",
"msgtype",
"=",
"[",
"\"If we %s the %s, we can get to the %s %s through the %s %s %s!\"",
"%",
"tuple",
"(",
"map",
"(",
"choice",
",",
"words",
"[",
"0",
"]",
")",
")",
",",
"\"We need to %s the %s %s %s!\"",
"%",
"tuple",
"(",
"map",
"(",
"choice",
",",
"words",
"[",
"1",
"]",
")",
")",
",",
"\"Try to %s the %s %s, maybe it will %s the %s %s!\"",
"%",
"tuple",
"(",
"map",
"(",
"choice",
",",
"words",
"[",
"2",
"]",
")",
")",
",",
"\"You can't %s the %s without %s the %s %s %s!\"",
"%",
"tuple",
"(",
"map",
"(",
"choice",
",",
"words",
"[",
"3",
"]",
")",
")",
",",
"\"Use the %s %s %s, then you can %s the %s %s!\"",
"%",
"tuple",
"(",
"map",
"(",
"choice",
",",
"words",
"[",
"4",
"]",
")",
")",
",",
"\"The %s %s is down, %s the %s %s so we can %s the %s %s!\"",
"%",
"tuple",
"(",
"map",
"(",
"choice",
",",
"words",
"[",
"5",
"]",
")",
")",
",",
"\"%s the %s won't do anything, we need to %s the %s %s %s!\"",
"%",
"tuple",
"(",
"map",
"(",
"choice",
",",
"words",
"[",
"6",
"]",
")",
")",
",",
"\"I'll %s the %s %s %s, that should %s the %s %s!\"",
"%",
"tuple",
"(",
"map",
"(",
"choice",
",",
"words",
"[",
"7",
"]",
")",
")",
"]",
"send",
"(",
"choice",
"(",
"msgtype",
")",
")"
]
| 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 = ', '.join(['%d' % d[k] for k in keys])
return r'''
%s
%s
.. csv-table::
:header: %s
%s
''' % (title, '-'*len(title), cats, 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 = ', '.join(['%d' % d[k] for k in keys])
return r'''
%s
%s
.. csv-table::
:header: %s
%s
''' % (title, '-'*len(title), cats, vals) | [
"def",
"_GenerateStaticsTable",
"(",
"self",
",",
"title",
"=",
"'Current Statistics'",
")",
":",
"if",
"len",
"(",
"self",
".",
"__categories",
".",
"keys",
"(",
")",
")",
"<",
"1",
":",
"return",
"''",
"d",
"=",
"self",
".",
"__categories",
"keys",
"=",
"sorted",
"(",
"d",
".",
"keys",
"(",
")",
")",
"cats",
"=",
"', '",
".",
"join",
"(",
"[",
"'\"%s\"'",
"%",
"k",
"for",
"k",
"in",
"keys",
"]",
")",
"vals",
"=",
"', '",
".",
"join",
"(",
"[",
"'%d'",
"%",
"d",
"[",
"k",
"]",
"for",
"k",
"in",
"keys",
"]",
")",
"return",
"r'''\n\n%s\n%s\n\n.. csv-table::\n :header: %s\n\n %s\n\n'''",
"%",
"(",
"title",
",",
"'-'",
"*",
"len",
"(",
"title",
")",
",",
"cats",
",",
"vals",
")"
]
| 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:
mod (module): The single module to document as its own page
showprivate (bool): A flag for whether or not to display private members
Returns:
str: The file name ready to be appended to a toctree
"""
try:
all = mod[1].__all__
except AttributeError:
raise RuntimeError('Module (%s) MUST have `__all__` defined.' % mod[1].__name__)
try:
name = mod[1].__displayname__
except AttributeError:
name = mod[0]
try:
category = mod[1].__category__
self.__categories.setdefault(category, 0)
self.__categories[category] += 1
except AttributeError:
pass
feats = inspect.getmembers(mod[1])
fname = 'content/' + mod[1].__name__.replace('.', '/').replace(' ', '-')+'.rst'
feats = [f for f in feats if f[0] in all and (showprivate or not f[0][0:1] == '_')]
with open(fname, 'w') as fid:
fid.write(Classifier.GetModuleText(name, mod[1].__name__, showprivate=showprivate))
for f in feats:
# Check for a __displayname__
if inspect.isclass(f[1]) or inspect.isfunction(f[1]):
try:
featname = f[1].__displayname__
except AttributeError:
featname = f[1].__name__
try:
category = f[1].__category__
self.__categories.setdefault(category, 0)
self.__categories[category] += 1
except AttributeError:
pass
# Make the auto doc rst
if inspect.isclass(f[1]):
fid.write(Classifier.GetClassText(featname, '%s.%s' % (mod[1].__name__, f[1].__name__), showprivate=showprivate, showinh=showinh))
elif inspect.isfunction(f[1]):
fid.write(Classifier.GetFunctionText(featname, '%s.%s' % (mod[1].__name__, f[1].__name__)))
fid.close()
return '\n %s' % (fname.split('/')[-1]) | 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:
mod (module): The single module to document as its own page
showprivate (bool): A flag for whether or not to display private members
Returns:
str: The file name ready to be appended to a toctree
"""
try:
all = mod[1].__all__
except AttributeError:
raise RuntimeError('Module (%s) MUST have `__all__` defined.' % mod[1].__name__)
try:
name = mod[1].__displayname__
except AttributeError:
name = mod[0]
try:
category = mod[1].__category__
self.__categories.setdefault(category, 0)
self.__categories[category] += 1
except AttributeError:
pass
feats = inspect.getmembers(mod[1])
fname = 'content/' + mod[1].__name__.replace('.', '/').replace(' ', '-')+'.rst'
feats = [f for f in feats if f[0] in all and (showprivate or not f[0][0:1] == '_')]
with open(fname, 'w') as fid:
fid.write(Classifier.GetModuleText(name, mod[1].__name__, showprivate=showprivate))
for f in feats:
# Check for a __displayname__
if inspect.isclass(f[1]) or inspect.isfunction(f[1]):
try:
featname = f[1].__displayname__
except AttributeError:
featname = f[1].__name__
try:
category = f[1].__category__
self.__categories.setdefault(category, 0)
self.__categories[category] += 1
except AttributeError:
pass
# Make the auto doc rst
if inspect.isclass(f[1]):
fid.write(Classifier.GetClassText(featname, '%s.%s' % (mod[1].__name__, f[1].__name__), showprivate=showprivate, showinh=showinh))
elif inspect.isfunction(f[1]):
fid.write(Classifier.GetFunctionText(featname, '%s.%s' % (mod[1].__name__, f[1].__name__)))
fid.close()
return '\n %s' % (fname.split('/')[-1]) | [
"def",
"_ProduceSingleContent",
"(",
"self",
",",
"mod",
",",
"showprivate",
"=",
"False",
",",
"showinh",
"=",
"False",
")",
":",
"try",
":",
"all",
"=",
"mod",
"[",
"1",
"]",
".",
"__all__",
"except",
"AttributeError",
":",
"raise",
"RuntimeError",
"(",
"'Module (%s) MUST have `__all__` defined.'",
"%",
"mod",
"[",
"1",
"]",
".",
"__name__",
")",
"try",
":",
"name",
"=",
"mod",
"[",
"1",
"]",
".",
"__displayname__",
"except",
"AttributeError",
":",
"name",
"=",
"mod",
"[",
"0",
"]",
"try",
":",
"category",
"=",
"mod",
"[",
"1",
"]",
".",
"__category__",
"self",
".",
"__categories",
".",
"setdefault",
"(",
"category",
",",
"0",
")",
"self",
".",
"__categories",
"[",
"category",
"]",
"+=",
"1",
"except",
"AttributeError",
":",
"pass",
"feats",
"=",
"inspect",
".",
"getmembers",
"(",
"mod",
"[",
"1",
"]",
")",
"fname",
"=",
"'content/'",
"+",
"mod",
"[",
"1",
"]",
".",
"__name__",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
".",
"replace",
"(",
"' '",
",",
"'-'",
")",
"+",
"'.rst'",
"feats",
"=",
"[",
"f",
"for",
"f",
"in",
"feats",
"if",
"f",
"[",
"0",
"]",
"in",
"all",
"and",
"(",
"showprivate",
"or",
"not",
"f",
"[",
"0",
"]",
"[",
"0",
":",
"1",
"]",
"==",
"'_'",
")",
"]",
"with",
"open",
"(",
"fname",
",",
"'w'",
")",
"as",
"fid",
":",
"fid",
".",
"write",
"(",
"Classifier",
".",
"GetModuleText",
"(",
"name",
",",
"mod",
"[",
"1",
"]",
".",
"__name__",
",",
"showprivate",
"=",
"showprivate",
")",
")",
"for",
"f",
"in",
"feats",
":",
"# Check for a __displayname__",
"if",
"inspect",
".",
"isclass",
"(",
"f",
"[",
"1",
"]",
")",
"or",
"inspect",
".",
"isfunction",
"(",
"f",
"[",
"1",
"]",
")",
":",
"try",
":",
"featname",
"=",
"f",
"[",
"1",
"]",
".",
"__displayname__",
"except",
"AttributeError",
":",
"featname",
"=",
"f",
"[",
"1",
"]",
".",
"__name__",
"try",
":",
"category",
"=",
"f",
"[",
"1",
"]",
".",
"__category__",
"self",
".",
"__categories",
".",
"setdefault",
"(",
"category",
",",
"0",
")",
"self",
".",
"__categories",
"[",
"category",
"]",
"+=",
"1",
"except",
"AttributeError",
":",
"pass",
"# Make the auto doc rst",
"if",
"inspect",
".",
"isclass",
"(",
"f",
"[",
"1",
"]",
")",
":",
"fid",
".",
"write",
"(",
"Classifier",
".",
"GetClassText",
"(",
"featname",
",",
"'%s.%s'",
"%",
"(",
"mod",
"[",
"1",
"]",
".",
"__name__",
",",
"f",
"[",
"1",
"]",
".",
"__name__",
")",
",",
"showprivate",
"=",
"showprivate",
",",
"showinh",
"=",
"showinh",
")",
")",
"elif",
"inspect",
".",
"isfunction",
"(",
"f",
"[",
"1",
"]",
")",
":",
"fid",
".",
"write",
"(",
"Classifier",
".",
"GetFunctionText",
"(",
"featname",
",",
"'%s.%s'",
"%",
"(",
"mod",
"[",
"1",
"]",
".",
"__name__",
",",
"f",
"[",
"1",
"]",
".",
"__name__",
")",
")",
")",
"fid",
".",
"close",
"(",
")",
"return",
"'\\n %s'",
"%",
"(",
"fname",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
")"
]
| 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 (bool): A flag for whether or not to display private members
Returns:
str: The file name ready to be appended to a toctree | [
"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",
"."
]
| 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.
Args:
mods (module): The modules to document that do not contain nested modules
showprivate (bool): A flag for whether or not to display private members
Returns:
str: The file names ready to be appended to a toctree
"""
result = ''
nestedresult = ''
# For each module
for mod in mods:
# Test to see if module to document has an __all__ variable
try:
all = mod[1].__all__
except AttributeError:
raise RuntimeError('Module (%s) MUST have `__all__` defined.' % mod[1].__name__)
if not showprivate and mod[0][0:1] == '_':
continue
if mod[0][0:2] == '__': #and not showprivate
continue
result += self._ProduceSingleContent(mod, showprivate, showinh)
return result | 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.
Args:
mods (module): The modules to document that do not contain nested modules
showprivate (bool): A flag for whether or not to display private members
Returns:
str: The file names ready to be appended to a toctree
"""
result = ''
nestedresult = ''
# For each module
for mod in mods:
# Test to see if module to document has an __all__ variable
try:
all = mod[1].__all__
except AttributeError:
raise RuntimeError('Module (%s) MUST have `__all__` defined.' % mod[1].__name__)
if not showprivate and mod[0][0:1] == '_':
continue
if mod[0][0:2] == '__': #and not showprivate
continue
result += self._ProduceSingleContent(mod, showprivate, showinh)
return result | [
"def",
"_ProduceContent",
"(",
"self",
",",
"mods",
",",
"showprivate",
"=",
"False",
",",
"showinh",
"=",
"False",
")",
":",
"result",
"=",
"''",
"nestedresult",
"=",
"''",
"# For each module",
"for",
"mod",
"in",
"mods",
":",
"# Test to see if module to document has an __all__ variable",
"try",
":",
"all",
"=",
"mod",
"[",
"1",
"]",
".",
"__all__",
"except",
"AttributeError",
":",
"raise",
"RuntimeError",
"(",
"'Module (%s) MUST have `__all__` defined.'",
"%",
"mod",
"[",
"1",
"]",
".",
"__name__",
")",
"if",
"not",
"showprivate",
"and",
"mod",
"[",
"0",
"]",
"[",
"0",
":",
"1",
"]",
"==",
"'_'",
":",
"continue",
"if",
"mod",
"[",
"0",
"]",
"[",
"0",
":",
"2",
"]",
"==",
"'__'",
":",
"#and not showprivate",
"continue",
"result",
"+=",
"self",
".",
"_ProduceSingleContent",
"(",
"mod",
",",
"showprivate",
",",
"showinh",
")",
"return",
"result"
]
| 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 nested modules
showprivate (bool): A flag for whether or not to display private members
Returns:
str: The file names ready to be appended to a toctree | [
"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",
"."
]
| 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 members
nested (bool): Foor internal use ONLY
Returns:
str: The file names ready to be appended to a top-level toctree
"""
def checkNoNested(mod):
try:
all = mod.__all__
except AttributeError:
return False
mems = inspect.getmembers(mod, inspect.ismodule)
mems = [m for m in mems if m[0] in mod.__all__]
if len(mems) > 0:
return False
return True
# Get package module members
mods = inspect.getmembers(package, inspect.ismodule)
# Split into modules and sub-packages
nmods, pvt, npkgs = [], [], []
for mod in mods:
# Deal with private modules
if checkNoNested(mod[1]):
if mod[0][0] == '_': pvt.append(mod)
else: nmods.append(mod)
else: npkgs.append(mod)
if showprivate: nmods += pvt
# for each member that has a nested module
# recurse and keep track of index files for that package
files = []
ignore = []
for pkg in npkgs:
pt = '%s/%s/%s' % (self.path, package.__name__.replace('.', '/'), pkg[1].__name__.split('.')[-1])
if os.path.exists(pt): shutil.rmtree(pt)
os.makedirs(pt)
ignore += inspect.getmembers(pkg[1])
f = self._MakePackagePages(pkg[1], showprivate=showprivate, nested=True, showinh=showinh)
files.append(f.split(package.__name__.replace('.', '/')+'/')[1])
if nested:
try:
name = package.__displayname__
except AttributeError:
name = package.__name__
# Create index file here
index = r'''
%s
%s
.. toctree::
:maxdepth: 5
''' % (name, '*' * len(name))
# include sub packages first
index += '\n '.join(files)
# then include modules
index += '\n ' + self._ProduceContent(nmods, showprivate=showprivate, showinh=showinh)
findex = 'content/%s/index.rst' % (package.__name__.replace('.', '/'))
# Write the file
with open(findex, 'w') as f:
if package.__doc__: f.write(package.__doc__)
f.write(index)
# return filename for index file at package level
return '\n ' + findex
# Not nested: return all files
names = '\n %s/%s/' % ( self.path, package.__name__.replace('.', '/'))
nmods = [m for m in nmods if m not in ignore]
return names.join(self._ProduceContent(nmods, showprivate=showprivate, showinh=showinh).split('\n ')+files) | 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 members
nested (bool): Foor internal use ONLY
Returns:
str: The file names ready to be appended to a top-level toctree
"""
def checkNoNested(mod):
try:
all = mod.__all__
except AttributeError:
return False
mems = inspect.getmembers(mod, inspect.ismodule)
mems = [m for m in mems if m[0] in mod.__all__]
if len(mems) > 0:
return False
return True
# Get package module members
mods = inspect.getmembers(package, inspect.ismodule)
# Split into modules and sub-packages
nmods, pvt, npkgs = [], [], []
for mod in mods:
# Deal with private modules
if checkNoNested(mod[1]):
if mod[0][0] == '_': pvt.append(mod)
else: nmods.append(mod)
else: npkgs.append(mod)
if showprivate: nmods += pvt
# for each member that has a nested module
# recurse and keep track of index files for that package
files = []
ignore = []
for pkg in npkgs:
pt = '%s/%s/%s' % (self.path, package.__name__.replace('.', '/'), pkg[1].__name__.split('.')[-1])
if os.path.exists(pt): shutil.rmtree(pt)
os.makedirs(pt)
ignore += inspect.getmembers(pkg[1])
f = self._MakePackagePages(pkg[1], showprivate=showprivate, nested=True, showinh=showinh)
files.append(f.split(package.__name__.replace('.', '/')+'/')[1])
if nested:
try:
name = package.__displayname__
except AttributeError:
name = package.__name__
# Create index file here
index = r'''
%s
%s
.. toctree::
:maxdepth: 5
''' % (name, '*' * len(name))
# include sub packages first
index += '\n '.join(files)
# then include modules
index += '\n ' + self._ProduceContent(nmods, showprivate=showprivate, showinh=showinh)
findex = 'content/%s/index.rst' % (package.__name__.replace('.', '/'))
# Write the file
with open(findex, 'w') as f:
if package.__doc__: f.write(package.__doc__)
f.write(index)
# return filename for index file at package level
return '\n ' + findex
# Not nested: return all files
names = '\n %s/%s/' % ( self.path, package.__name__.replace('.', '/'))
nmods = [m for m in nmods if m not in ignore]
return names.join(self._ProduceContent(nmods, showprivate=showprivate, showinh=showinh).split('\n ')+files) | [
"def",
"_MakePackagePages",
"(",
"self",
",",
"package",
",",
"showprivate",
"=",
"False",
",",
"nested",
"=",
"False",
",",
"showinh",
"=",
"False",
")",
":",
"def",
"checkNoNested",
"(",
"mod",
")",
":",
"try",
":",
"all",
"=",
"mod",
".",
"__all__",
"except",
"AttributeError",
":",
"return",
"False",
"mems",
"=",
"inspect",
".",
"getmembers",
"(",
"mod",
",",
"inspect",
".",
"ismodule",
")",
"mems",
"=",
"[",
"m",
"for",
"m",
"in",
"mems",
"if",
"m",
"[",
"0",
"]",
"in",
"mod",
".",
"__all__",
"]",
"if",
"len",
"(",
"mems",
")",
">",
"0",
":",
"return",
"False",
"return",
"True",
"# Get package module members",
"mods",
"=",
"inspect",
".",
"getmembers",
"(",
"package",
",",
"inspect",
".",
"ismodule",
")",
"# Split into modules and sub-packages",
"nmods",
",",
"pvt",
",",
"npkgs",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"for",
"mod",
"in",
"mods",
":",
"# Deal with private modules",
"if",
"checkNoNested",
"(",
"mod",
"[",
"1",
"]",
")",
":",
"if",
"mod",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"'_'",
":",
"pvt",
".",
"append",
"(",
"mod",
")",
"else",
":",
"nmods",
".",
"append",
"(",
"mod",
")",
"else",
":",
"npkgs",
".",
"append",
"(",
"mod",
")",
"if",
"showprivate",
":",
"nmods",
"+=",
"pvt",
"# for each member that has a nested module",
"# recurse and keep track of index files for that package",
"files",
"=",
"[",
"]",
"ignore",
"=",
"[",
"]",
"for",
"pkg",
"in",
"npkgs",
":",
"pt",
"=",
"'%s/%s/%s'",
"%",
"(",
"self",
".",
"path",
",",
"package",
".",
"__name__",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
",",
"pkg",
"[",
"1",
"]",
".",
"__name__",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"pt",
")",
":",
"shutil",
".",
"rmtree",
"(",
"pt",
")",
"os",
".",
"makedirs",
"(",
"pt",
")",
"ignore",
"+=",
"inspect",
".",
"getmembers",
"(",
"pkg",
"[",
"1",
"]",
")",
"f",
"=",
"self",
".",
"_MakePackagePages",
"(",
"pkg",
"[",
"1",
"]",
",",
"showprivate",
"=",
"showprivate",
",",
"nested",
"=",
"True",
",",
"showinh",
"=",
"showinh",
")",
"files",
".",
"append",
"(",
"f",
".",
"split",
"(",
"package",
".",
"__name__",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
"+",
"'/'",
")",
"[",
"1",
"]",
")",
"if",
"nested",
":",
"try",
":",
"name",
"=",
"package",
".",
"__displayname__",
"except",
"AttributeError",
":",
"name",
"=",
"package",
".",
"__name__",
"# Create index file here",
"index",
"=",
"r'''\n%s\n%s\n\n.. toctree::\n :maxdepth: 5\n\n '''",
"%",
"(",
"name",
",",
"'*'",
"*",
"len",
"(",
"name",
")",
")",
"# include sub packages first",
"index",
"+=",
"'\\n '",
".",
"join",
"(",
"files",
")",
"# then include modules",
"index",
"+=",
"'\\n '",
"+",
"self",
".",
"_ProduceContent",
"(",
"nmods",
",",
"showprivate",
"=",
"showprivate",
",",
"showinh",
"=",
"showinh",
")",
"findex",
"=",
"'content/%s/index.rst'",
"%",
"(",
"package",
".",
"__name__",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
")",
"# Write the file",
"with",
"open",
"(",
"findex",
",",
"'w'",
")",
"as",
"f",
":",
"if",
"package",
".",
"__doc__",
":",
"f",
".",
"write",
"(",
"package",
".",
"__doc__",
")",
"f",
".",
"write",
"(",
"index",
")",
"# return filename for index file at package level",
"return",
"'\\n '",
"+",
"findex",
"# Not nested: return all files",
"names",
"=",
"'\\n %s/%s/'",
"%",
"(",
"self",
".",
"path",
",",
"package",
".",
"__name__",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
")",
"nmods",
"=",
"[",
"m",
"for",
"m",
"in",
"nmods",
"if",
"m",
"not",
"in",
"ignore",
"]",
"return",
"names",
".",
"join",
"(",
"self",
".",
"_ProduceContent",
"(",
"nmods",
",",
"showprivate",
"=",
"showprivate",
",",
"showinh",
"=",
"showinh",
")",
".",
"split",
"(",
"'\\n '",
")",
"+",
"files",
")"
]
| 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 file names ready to be appended to a top-level toctree | [
"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 list of packages that contain submodules to document
showprivate (bool): A flag for whether or not to display private members
Returns:
str: The new content to append to the index
"""
appIndex = ''
if not isinstance(packages, list):
packages = [packages]
if os.path.exists('content'):
shutil.rmtree('content')
os.makedirs('content')
appIndex += r'''
.. toctree::
:maxdepth: 5
:hidden:
:caption: %s:
''' % ('API Index')
# Iterate over each package and generate appropriate pages
for i in range(len(packages)):
# The package to document and its path
package = packages[i]
try:
name = package.__displayname__
except AttributeError:
name = package.__name__
# Make sure paths are ready
path = 'content/%s' % package.__name__
if os.path.exists(path):
shutil.rmtree(path)
os.makedirs(path)
# Check if there is top level documentation
# if package.__doc__:
# Get metadata
meta = 'About %s\n%s\n' % (name, '='*len('About ' + name))
author = getattr(package, "__author__", None)
license = getattr(package, "__license__", None)
copyright = getattr(package, "__copyright__", None)
version = getattr(package, "__version__", None)
if author: meta += '\n* Author: %s' % author
if license: meta += '\n* License: %s' % license
if copyright: meta += '\n* Copyright: %s' % copyright
if version: meta += '\n* Version: %s' % version
about = '%s/%s' % (path, 'index.rst')
this_toc = r'''
.. toctree::
:maxdepth: 5
:caption: %s:
''' % (name)
this_toc += self._MakePackagePages(package, showprivate=showprivate, showinh=showinh)
this_toc = this_toc.replace('%s/' % path, '')
with open(about, 'w') as f:
f.write('%s\n\n' % meta)
if package.__doc__:
f.write(package.__doc__)
f.write(this_toc)
appIndex += '\n %s' % about
# Return the new content to append
return appIndex | 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 list of packages that contain submodules to document
showprivate (bool): A flag for whether or not to display private members
Returns:
str: The new content to append to the index
"""
appIndex = ''
if not isinstance(packages, list):
packages = [packages]
if os.path.exists('content'):
shutil.rmtree('content')
os.makedirs('content')
appIndex += r'''
.. toctree::
:maxdepth: 5
:hidden:
:caption: %s:
''' % ('API Index')
# Iterate over each package and generate appropriate pages
for i in range(len(packages)):
# The package to document and its path
package = packages[i]
try:
name = package.__displayname__
except AttributeError:
name = package.__name__
# Make sure paths are ready
path = 'content/%s' % package.__name__
if os.path.exists(path):
shutil.rmtree(path)
os.makedirs(path)
# Check if there is top level documentation
# if package.__doc__:
# Get metadata
meta = 'About %s\n%s\n' % (name, '='*len('About ' + name))
author = getattr(package, "__author__", None)
license = getattr(package, "__license__", None)
copyright = getattr(package, "__copyright__", None)
version = getattr(package, "__version__", None)
if author: meta += '\n* Author: %s' % author
if license: meta += '\n* License: %s' % license
if copyright: meta += '\n* Copyright: %s' % copyright
if version: meta += '\n* Version: %s' % version
about = '%s/%s' % (path, 'index.rst')
this_toc = r'''
.. toctree::
:maxdepth: 5
:caption: %s:
''' % (name)
this_toc += self._MakePackagePages(package, showprivate=showprivate, showinh=showinh)
this_toc = this_toc.replace('%s/' % path, '')
with open(about, 'w') as f:
f.write('%s\n\n' % meta)
if package.__doc__:
f.write(package.__doc__)
f.write(this_toc)
appIndex += '\n %s' % about
# Return the new content to append
return appIndex | [
"def",
"_DocPackageFromTop",
"(",
"self",
",",
"packages",
",",
"showprivate",
"=",
"False",
",",
"showinh",
"=",
"False",
")",
":",
"appIndex",
"=",
"''",
"if",
"not",
"isinstance",
"(",
"packages",
",",
"list",
")",
":",
"packages",
"=",
"[",
"packages",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"'content'",
")",
":",
"shutil",
".",
"rmtree",
"(",
"'content'",
")",
"os",
".",
"makedirs",
"(",
"'content'",
")",
"appIndex",
"+=",
"r'''\n\n.. toctree::\n :maxdepth: 5\n :hidden:\n :caption: %s:\n\n'''",
"%",
"(",
"'API Index'",
")",
"# Iterate over each package and generate appropriate pages",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"packages",
")",
")",
":",
"# The package to document and its path",
"package",
"=",
"packages",
"[",
"i",
"]",
"try",
":",
"name",
"=",
"package",
".",
"__displayname__",
"except",
"AttributeError",
":",
"name",
"=",
"package",
".",
"__name__",
"# Make sure paths are ready",
"path",
"=",
"'content/%s'",
"%",
"package",
".",
"__name__",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"os",
".",
"makedirs",
"(",
"path",
")",
"# Check if there is top level documentation",
"# if package.__doc__:",
"# Get metadata",
"meta",
"=",
"'About %s\\n%s\\n'",
"%",
"(",
"name",
",",
"'='",
"*",
"len",
"(",
"'About '",
"+",
"name",
")",
")",
"author",
"=",
"getattr",
"(",
"package",
",",
"\"__author__\"",
",",
"None",
")",
"license",
"=",
"getattr",
"(",
"package",
",",
"\"__license__\"",
",",
"None",
")",
"copyright",
"=",
"getattr",
"(",
"package",
",",
"\"__copyright__\"",
",",
"None",
")",
"version",
"=",
"getattr",
"(",
"package",
",",
"\"__version__\"",
",",
"None",
")",
"if",
"author",
":",
"meta",
"+=",
"'\\n* Author: %s'",
"%",
"author",
"if",
"license",
":",
"meta",
"+=",
"'\\n* License: %s'",
"%",
"license",
"if",
"copyright",
":",
"meta",
"+=",
"'\\n* Copyright: %s'",
"%",
"copyright",
"if",
"version",
":",
"meta",
"+=",
"'\\n* Version: %s'",
"%",
"version",
"about",
"=",
"'%s/%s'",
"%",
"(",
"path",
",",
"'index.rst'",
")",
"this_toc",
"=",
"r'''\n\n.. toctree::\n :maxdepth: 5\n :caption: %s:\n'''",
"%",
"(",
"name",
")",
"this_toc",
"+=",
"self",
".",
"_MakePackagePages",
"(",
"package",
",",
"showprivate",
"=",
"showprivate",
",",
"showinh",
"=",
"showinh",
")",
"this_toc",
"=",
"this_toc",
".",
"replace",
"(",
"'%s/'",
"%",
"path",
",",
"''",
")",
"with",
"open",
"(",
"about",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'%s\\n\\n'",
"%",
"meta",
")",
"if",
"package",
".",
"__doc__",
":",
"f",
".",
"write",
"(",
"package",
".",
"__doc__",
")",
"f",
".",
"write",
"(",
"this_toc",
")",
"appIndex",
"+=",
"'\\n %s'",
"%",
"about",
"# Return the new content to append",
"return",
"appIndex"
]
| 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 flag for whether or not to display private members
Returns:
str: The new content to append to the index | [
"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://
zodb_uri = 'file://' + os.path.abspath(zodb_uri)
from repoze.zodbconn.finder import PersistentApplicationFinder
finder = PersistentApplicationFinder(zodb_uri, appmaker=lambda root: Node(root))
root_factory = lambda request: finder(request.environ)
else:
raise RuntimeError("Must specify root object or ZODB URI.")
app = Eye(root_factory)
if 'DEBUG' in os.environ:
from repoze.debug.pdbpm import PostMortemDebug
app = PostMortemDebug(app)
serve(app, host='127.0.0.1', port=port) | 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://
zodb_uri = 'file://' + os.path.abspath(zodb_uri)
from repoze.zodbconn.finder import PersistentApplicationFinder
finder = PersistentApplicationFinder(zodb_uri, appmaker=lambda root: Node(root))
root_factory = lambda request: finder(request.environ)
else:
raise RuntimeError("Must specify root object or ZODB URI.")
app = Eye(root_factory)
if 'DEBUG' in os.environ:
from repoze.debug.pdbpm import PostMortemDebug
app = PostMortemDebug(app)
serve(app, host='127.0.0.1', port=port) | [
"def",
"eye",
"(",
"root",
"=",
"None",
",",
"zodb_uri",
"=",
"None",
",",
"port",
"=",
"8080",
")",
":",
"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://",
"zodb_uri",
"=",
"'file://'",
"+",
"os",
".",
"path",
".",
"abspath",
"(",
"zodb_uri",
")",
"from",
"repoze",
".",
"zodbconn",
".",
"finder",
"import",
"PersistentApplicationFinder",
"finder",
"=",
"PersistentApplicationFinder",
"(",
"zodb_uri",
",",
"appmaker",
"=",
"lambda",
"root",
":",
"Node",
"(",
"root",
")",
")",
"root_factory",
"=",
"lambda",
"request",
":",
"finder",
"(",
"request",
".",
"environ",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Must specify root object or ZODB URI.\"",
")",
"app",
"=",
"Eye",
"(",
"root_factory",
")",
"if",
"'DEBUG'",
"in",
"os",
".",
"environ",
":",
"from",
"repoze",
".",
"debug",
".",
"pdbpm",
"import",
"PostMortemDebug",
"app",
"=",
"PostMortemDebug",
"(",
"app",
")",
"serve",
"(",
"app",
",",
"host",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"port",
")"
]
| 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['handler'].voiced[args['target']].values() if x])
total = len(channel.users())
send("%d active users, %d total users, %g%% active" % (voiced, total, voiced / total * 100)) | 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['handler'].voiced[args['target']].values() if x])
total = len(channel.users())
send("%d active users, %d total users, %g%% active" % (voiced, total, voiced / total * 100)) | [
"def",
"cmd",
"(",
"send",
",",
"_",
",",
"args",
")",
":",
"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",
"[",
"'handler'",
"]",
".",
"voiced",
"[",
"args",
"[",
"'target'",
"]",
"]",
".",
"values",
"(",
")",
"if",
"x",
"]",
")",
"total",
"=",
"len",
"(",
"channel",
".",
"users",
"(",
")",
")",
"send",
"(",
"\"%d active users, %d total users, %g%% active\"",
"%",
"(",
"voiced",
",",
"total",
",",
"voiced",
"/",
"total",
"*",
"100",
")",
")"
]
| 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",
"is_detail_url",
"(",
"http_request",
",",
"url",
")",
"else",
"'list'"
]
| 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']
# run the Battles
b = Battle(self.c1, self.c2, self.traits, self.rules, print_console='No')
#print(b)
if b.status == self.c1.name:
self.num_c1 += 1
else:
self.num_c2 += 1
# tag winner
if self.num_c1 > self.num_c2:
self.winner = self.c1.name
else:
self.winner = self.c2.name | 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']
# run the Battles
b = Battle(self.c1, self.c2, self.traits, self.rules, print_console='No')
#print(b)
if b.status == self.c1.name:
self.num_c1 += 1
else:
self.num_c2 += 1
# tag winner
if self.num_c1 > self.num_c2:
self.winner = self.c1.name
else:
self.winner = self.c2.name | [
"def",
"run_simulation",
"(",
"self",
")",
":",
"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'",
"]",
"# run the Battles",
"b",
"=",
"Battle",
"(",
"self",
".",
"c1",
",",
"self",
".",
"c2",
",",
"self",
".",
"traits",
",",
"self",
".",
"rules",
",",
"print_console",
"=",
"'No'",
")",
"#print(b)",
"if",
"b",
".",
"status",
"==",
"self",
".",
"c1",
".",
"name",
":",
"self",
".",
"num_c1",
"+=",
"1",
"else",
":",
"self",
".",
"num_c2",
"+=",
"1",
"# tag winner ",
"if",
"self",
".",
"num_c1",
">",
"self",
".",
"num_c2",
":",
"self",
".",
"winner",
"=",
"self",
".",
"c1",
".",
"name",
"else",
":",
"self",
".",
"winner",
"=",
"self",
".",
"c2",
".",
"name"
]
| 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'",
"]",
"-",
"dmg",
"else",
":",
"self",
".",
"c2",
".",
"stats",
"[",
"'Health'",
"]",
"=",
"self",
".",
"c2",
".",
"stats",
"[",
"'Health'",
"]",
"-",
"dmg"
]
| 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_defend.stats['Health']*100) / c_defend.stats['max_health'] )) + '%]'
if result == 'Miss':
txt = c_attack.name + ' ' + perc_health_att.rjust(6) + ' miss ' + c_defend.name + ' ' + perc_health_def.rjust(6)
elif result == 'Crit':
txt = c_attack.name + ' ' + perc_health_att.rjust(6) + ' CRIT ' + c_defend.name + ' ' + perc_health_def.rjust(6)
txt += ' for ' + str(dmg)
else:
txt = c_attack.name + ' ' + perc_health_att.rjust(6) + ' hits ' + c_defend.name + ' ' + perc_health_def.rjust(6)
txt += ' for ' + str(dmg)
if print_console == 'Yes':
print(txt) | 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_defend.stats['Health']*100) / c_defend.stats['max_health'] )) + '%]'
if result == 'Miss':
txt = c_attack.name + ' ' + perc_health_att.rjust(6) + ' miss ' + c_defend.name + ' ' + perc_health_def.rjust(6)
elif result == 'Crit':
txt = c_attack.name + ' ' + perc_health_att.rjust(6) + ' CRIT ' + c_defend.name + ' ' + perc_health_def.rjust(6)
txt += ' for ' + str(dmg)
else:
txt = c_attack.name + ' ' + perc_health_att.rjust(6) + ' hits ' + c_defend.name + ' ' + perc_health_def.rjust(6)
txt += ' for ' + str(dmg)
if print_console == 'Yes':
print(txt) | [
"def",
"show_message",
"(",
"self",
",",
"c_attack",
",",
"c_defend",
",",
"result",
",",
"dmg",
",",
"print_console",
"=",
"'Yes'",
")",
":",
"perc_health_att",
"=",
"'['",
"+",
"str",
"(",
"round",
"(",
"(",
"c_attack",
".",
"stats",
"[",
"'Health'",
"]",
"*",
"100",
")",
"/",
"c_attack",
".",
"stats",
"[",
"'max_health'",
"]",
")",
")",
"+",
"'%]'",
"perc_health_def",
"=",
"'['",
"+",
"str",
"(",
"round",
"(",
"(",
"c_defend",
".",
"stats",
"[",
"'Health'",
"]",
"*",
"100",
")",
"/",
"c_defend",
".",
"stats",
"[",
"'max_health'",
"]",
")",
")",
"+",
"'%]'",
"if",
"result",
"==",
"'Miss'",
":",
"txt",
"=",
"c_attack",
".",
"name",
"+",
"' '",
"+",
"perc_health_att",
".",
"rjust",
"(",
"6",
")",
"+",
"' miss '",
"+",
"c_defend",
".",
"name",
"+",
"' '",
"+",
"perc_health_def",
".",
"rjust",
"(",
"6",
")",
"elif",
"result",
"==",
"'Crit'",
":",
"txt",
"=",
"c_attack",
".",
"name",
"+",
"' '",
"+",
"perc_health_att",
".",
"rjust",
"(",
"6",
")",
"+",
"' CRIT '",
"+",
"c_defend",
".",
"name",
"+",
"' '",
"+",
"perc_health_def",
".",
"rjust",
"(",
"6",
")",
"txt",
"+=",
"' for '",
"+",
"str",
"(",
"dmg",
")",
"else",
":",
"txt",
"=",
"c_attack",
".",
"name",
"+",
"' '",
"+",
"perc_health_att",
".",
"rjust",
"(",
"6",
")",
"+",
"' hits '",
"+",
"c_defend",
".",
"name",
"+",
"' '",
"+",
"perc_health_def",
".",
"rjust",
"(",
"6",
")",
"txt",
"+=",
"' for '",
"+",
"str",
"(",
"dmg",
")",
"if",
"print_console",
"==",
"'Yes'",
":",
"print",
"(",
"txt",
")"
]
| 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.