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
acutesoftware/virtual-AI-simulator
vais/run.py
main
def main(): """ test program for VAIS. Generates several planets and populates with animals and plants. Then places objects and tests the sequences. """ print("|---------------------------------------------------") print("| Virtual AI Simulator") print("|------------------------...
python
def main(): """ test program for VAIS. Generates several planets and populates with animals and plants. Then places objects and tests the sequences. """ print("|---------------------------------------------------") print("| Virtual AI Simulator") print("|------------------------...
[ "def", "main", "(", ")", ":", "print", "(", "\"|---------------------------------------------------\"", ")", "print", "(", "\"| Virtual AI Simulator\"", ")", "print", "(", "\"|---------------------------------------------------\"", ")", "print", "(", "\"| \"", ")", ...
test program for VAIS. Generates several planets and populates with animals and plants. Then places objects and tests the sequences.
[ "test", "program", "for", "VAIS", ".", "Generates", "several", "planets", "and", "populates", "with", "animals", "and", "plants", ".", "Then", "places", "objects", "and", "tests", "the", "sequences", "." ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/run.py#L14-L51
train
acutesoftware/virtual-AI-simulator
vais/run.py
load_planet_list
def load_planet_list(): """ load the list of prebuilt planets """ planet_list = [] with open(fldr + os.sep + 'planet_samples.csv') as f: hdr = f.readline() for line in f: #print("Building ", line) name, num_seeds, width, height, wind, rain, sun, lava = parse_p...
python
def load_planet_list(): """ load the list of prebuilt planets """ planet_list = [] with open(fldr + os.sep + 'planet_samples.csv') as f: hdr = f.readline() for line in f: #print("Building ", line) name, num_seeds, width, height, wind, rain, sun, lava = parse_p...
[ "def", "load_planet_list", "(", ")", ":", "planet_list", "=", "[", "]", "with", "open", "(", "fldr", "+", "os", ".", "sep", "+", "'planet_samples.csv'", ")", "as", "f", ":", "hdr", "=", "f", ".", "readline", "(", ")", "for", "line", "in", "f", ":",...
load the list of prebuilt planets
[ "load", "the", "list", "of", "prebuilt", "planets" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/run.py#L53-L64
train
acutesoftware/virtual-AI-simulator
vais/run.py
create_character
def create_character(): """ create a random character """ traits = character.CharacterCollection(character.fldr) c = traits.generate_random_character() print(c) return c
python
def create_character(): """ create a random character """ traits = character.CharacterCollection(character.fldr) c = traits.generate_random_character() print(c) return c
[ "def", "create_character", "(", ")", ":", "traits", "=", "character", ".", "CharacterCollection", "(", "character", ".", "fldr", ")", "c", "=", "traits", ".", "generate_random_character", "(", ")", "print", "(", "c", ")", "return", "c" ]
create a random character
[ "create", "a", "random", "character" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/run.py#L100-L107
train
acutesoftware/virtual-AI-simulator
vais/run.py
run_simulation
def run_simulation(c1, c2): """ using character and planet, run the simulation """ print('running simulation...') traits = character.CharacterCollection(character.fldr) c1 = traits.generate_random_character() c2 = traits.generate_random_character() print(c1) print(c2) rules = bat...
python
def run_simulation(c1, c2): """ using character and planet, run the simulation """ print('running simulation...') traits = character.CharacterCollection(character.fldr) c1 = traits.generate_random_character() c2 = traits.generate_random_character() print(c1) print(c2) rules = bat...
[ "def", "run_simulation", "(", "c1", ",", "c2", ")", ":", "print", "(", "'running simulation...'", ")", "traits", "=", "character", ".", "CharacterCollection", "(", "character", ".", "fldr", ")", "c1", "=", "traits", ".", "generate_random_character", "(", ")", ...
using character and planet, run the simulation
[ "using", "character", "and", "planet", "run", "the", "simulation" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/run.py#L109-L121
train
jmbeach/KEP.py
src/keppy/tag.py
Tag.name_replace
def name_replace(self, to_replace, replacement): """Replaces part of tag name with new value""" self.name = self.name.replace(to_replace, replacement)
python
def name_replace(self, to_replace, replacement): """Replaces part of tag name with new value""" self.name = self.name.replace(to_replace, replacement)
[ "def", "name_replace", "(", "self", ",", "to_replace", ",", "replacement", ")", ":", "self", ".", "name", "=", "self", ".", "name", ".", "replace", "(", "to_replace", ",", "replacement", ")" ]
Replaces part of tag name with new value
[ "Replaces", "part", "of", "tag", "name", "with", "new", "value" ]
68cda64ab649640a486534867c81274c41e39446
https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/tag.py#L31-L33
train
tjcsl/cslbot
cslbot/commands/seen.py
cmd
def cmd(send, msg, args): """When a nick was last seen. Syntax: {command} <nick> """ if not msg: send("Seen who?") return cmdchar, ctrlchan = args['config']['core']['cmdchar'], args['config']['core']['ctrlchan'] last = get_last(args['db'], cmdchar, ctrlchan, msg) if last is...
python
def cmd(send, msg, args): """When a nick was last seen. Syntax: {command} <nick> """ if not msg: send("Seen who?") return cmdchar, ctrlchan = args['config']['core']['cmdchar'], args['config']['core']['ctrlchan'] last = get_last(args['db'], cmdchar, ctrlchan, msg) if last is...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "send", "(", "\"Seen who?\"", ")", "return", "cmdchar", ",", "ctrlchan", "=", "args", "[", "'config'", "]", "[", "'core'", "]", "[", "'cmdchar'", "]", ",", "args...
When a nick was last seen. Syntax: {command} <nick>
[ "When", "a", "nick", "was", "last", "seen", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/seen.py#L31-L69
train
tjcsl/cslbot
cslbot/commands/morse.py
cmd
def cmd(send, msg, args): """Converts text to morse code. Syntax: {command} [text] """ if not msg: msg = gen_word() morse = gen_morse(msg) if len(morse) > 100: send("Your morse is too long. Have you considered Western Union?") else: send(morse)
python
def cmd(send, msg, args): """Converts text to morse code. Syntax: {command} [text] """ if not msg: msg = gen_word() morse = gen_morse(msg) if len(morse) > 100: send("Your morse is too long. Have you considered Western Union?") else: send(morse)
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "msg", "=", "gen_word", "(", ")", "morse", "=", "gen_morse", "(", "msg", ")", "if", "len", "(", "morse", ")", ">", "100", ":", "send", "(", "\"Your morse is to...
Converts text to morse code. Syntax: {command} [text]
[ "Converts", "text", "to", "morse", "code", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/morse.py#L23-L35
train
marrow/util
marrow/util/text.py
ellipsis
def ellipsis(text, length, symbol="..."): """Present a block of text of given length. If the length of available text exceeds the requested length, truncate and intelligently append an ellipsis. """ if len(text) > length: pos = text.rfind(" ", 0, length) if pos < 0: ...
python
def ellipsis(text, length, symbol="..."): """Present a block of text of given length. If the length of available text exceeds the requested length, truncate and intelligently append an ellipsis. """ if len(text) > length: pos = text.rfind(" ", 0, length) if pos < 0: ...
[ "def", "ellipsis", "(", "text", ",", "length", ",", "symbol", "=", "\"...\"", ")", ":", "if", "len", "(", "text", ")", ">", "length", ":", "pos", "=", "text", ".", "rfind", "(", "\" \"", ",", "0", ",", "length", ")", "if", "pos", "<", "0", ":",...
Present a block of text of given length. If the length of available text exceeds the requested length, truncate and intelligently append an ellipsis.
[ "Present", "a", "block", "of", "text", "of", "given", "length", ".", "If", "the", "length", "of", "available", "text", "exceeds", "the", "requested", "length", "truncate", "and", "intelligently", "append", "an", "ellipsis", "." ]
abb8163dbd1fa0692d42a44d129b12ae2b39cdf2
https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/text.py#L26-L40
train
tjcsl/cslbot
cslbot/commands/repost.py
cmd
def cmd(send, msg, args): """Reposts a url. Syntax: {command} """ result = args['db'].query(Urls).order_by(func.random()).first() send("%s" % result.url)
python
def cmd(send, msg, args): """Reposts a url. Syntax: {command} """ result = args['db'].query(Urls).order_by(func.random()).first() send("%s" % result.url)
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "result", "=", "args", "[", "'db'", "]", ".", "query", "(", "Urls", ")", ".", "order_by", "(", "func", ".", "random", "(", ")", ")", ".", "first", "(", ")", "send", "(", "\"%s\"", ...
Reposts a url. Syntax: {command}
[ "Reposts", "a", "url", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/repost.py#L25-L32
train
The-Politico/politico-civic-election-night
electionnight/serializers/office.py
OfficeSerializer.get_elections
def get_elections(self, obj): """All elections on an election day.""" election_day = ElectionDay.objects.get( date=self.context['election_date']) elections = Election.objects.filter( race__office=obj, election_day=election_day ) return Election...
python
def get_elections(self, obj): """All elections on an election day.""" election_day = ElectionDay.objects.get( date=self.context['election_date']) elections = Election.objects.filter( race__office=obj, election_day=election_day ) return Election...
[ "def", "get_elections", "(", "self", ",", "obj", ")", ":", "election_day", "=", "ElectionDay", ".", "objects", ".", "get", "(", "date", "=", "self", ".", "context", "[", "'election_date'", "]", ")", "elections", "=", "Election", ".", "objects", ".", "fil...
All elections on an election day.
[ "All", "elections", "on", "an", "election", "day", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/office.py#L49-L57
train
The-Politico/politico-civic-election-night
electionnight/serializers/office.py
OfficeSerializer.get_content
def get_content(self, obj): """All content for office's page on an election day.""" election_day = ElectionDay.objects.get( date=self.context['election_date']) return PageContent.objects.office_content(election_day, obj)
python
def get_content(self, obj): """All content for office's page on an election day.""" election_day = ElectionDay.objects.get( date=self.context['election_date']) return PageContent.objects.office_content(election_day, obj)
[ "def", "get_content", "(", "self", ",", "obj", ")", ":", "election_day", "=", "ElectionDay", ".", "objects", ".", "get", "(", "date", "=", "self", ".", "context", "[", "'election_date'", "]", ")", "return", "PageContent", ".", "objects", ".", "office_conte...
All content for office's page on an election day.
[ "All", "content", "for", "office", "s", "page", "on", "an", "election", "day", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/office.py#L59-L63
train
tjcsl/cslbot
cslbot/commands/cancel.py
cmd
def cmd(send, msg, args): """Cancels a deferred action with the given id. Syntax: {command} <id> """ try: args['handler'].workers.cancel(int(msg)) except ValueError: send("Index must be a digit.") return except KeyError: send("No such event.") return ...
python
def cmd(send, msg, args): """Cancels a deferred action with the given id. Syntax: {command} <id> """ try: args['handler'].workers.cancel(int(msg)) except ValueError: send("Index must be a digit.") return except KeyError: send("No such event.") return ...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "try", ":", "args", "[", "'handler'", "]", ".", "workers", ".", "cancel", "(", "int", "(", "msg", ")", ")", "except", "ValueError", ":", "send", "(", "\"Index must be a digit.\"", ")", "re...
Cancels a deferred action with the given id. Syntax: {command} <id>
[ "Cancels", "a", "deferred", "action", "with", "the", "given", "id", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/cancel.py#L22-L36
train
tjcsl/cslbot
cslbot/commands/roman.py
cmd
def cmd(send, msg, _): """Convert a number to the roman numeral equivalent. Syntax: {command} [number] """ if not msg: msg = randrange(5000) elif not msg.isdigit(): send("Invalid Number.") return send(gen_roman(int(msg)))
python
def cmd(send, msg, _): """Convert a number to the roman numeral equivalent. Syntax: {command} [number] """ if not msg: msg = randrange(5000) elif not msg.isdigit(): send("Invalid Number.") return send(gen_roman(int(msg)))
[ "def", "cmd", "(", "send", ",", "msg", ",", "_", ")", ":", "if", "not", "msg", ":", "msg", "=", "randrange", "(", "5000", ")", "elif", "not", "msg", ".", "isdigit", "(", ")", ":", "send", "(", "\"Invalid Number.\"", ")", "return", "send", "(", "g...
Convert a number to the roman numeral equivalent. Syntax: {command} [number]
[ "Convert", "a", "number", "to", "the", "roman", "numeral", "equivalent", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/roman.py#L42-L53
train
tjcsl/cslbot
cslbot/commands/kill.py
cmd
def cmd(send, msg, args): """Kills somebody. Syntax: {command} <victim> """ if not msg: send("kill who?") return if msg.lower() == args['botnick'].lower(): send('%s is not feeling suicidal right now.' % msg) else: send('Die, %s!' % msg)
python
def cmd(send, msg, args): """Kills somebody. Syntax: {command} <victim> """ if not msg: send("kill who?") return if msg.lower() == args['botnick'].lower(): send('%s is not feeling suicidal right now.' % msg) else: send('Die, %s!' % msg)
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "send", "(", "\"kill who?\"", ")", "return", "if", "msg", ".", "lower", "(", ")", "==", "args", "[", "'botnick'", "]", ".", "lower", "(", ")", ":", "send", "...
Kills somebody. Syntax: {command} <victim>
[ "Kills", "somebody", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/kill.py#L22-L34
train
tjcsl/cslbot
cslbot/commands/help.py
cmd
def cmd(send, msg, args): """Gives help. Syntax: {command} [command] """ cmdchar = args['config']['core']['cmdchar'] if msg: if msg.startswith(cmdchar): msg = msg[len(cmdchar):] if len(msg.split()) > 1: send("One argument only") elif not command_regi...
python
def cmd(send, msg, args): """Gives help. Syntax: {command} [command] """ cmdchar = args['config']['core']['cmdchar'] if msg: if msg.startswith(cmdchar): msg = msg[len(cmdchar):] if len(msg.split()) > 1: send("One argument only") elif not command_regi...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "cmdchar", "=", "args", "[", "'config'", "]", "[", "'core'", "]", "[", "'cmdchar'", "]", "if", "msg", ":", "if", "msg", ".", "startswith", "(", "cmdchar", ")", ":", "msg", "=", "msg", ...
Gives help. Syntax: {command} [command]
[ "Gives", "help", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/help.py#L23-L48
train
mardix/Juice
juice/decorators.py
plugin
def plugin(module, *args, **kwargs): """ Decorator to extend a package to a view. The module can be a class or function. It will copy all the methods to the class ie: # Your module.py my_ext(view, **kwargs): class MyExtension(object): def my_view(self): ...
python
def plugin(module, *args, **kwargs): """ Decorator to extend a package to a view. The module can be a class or function. It will copy all the methods to the class ie: # Your module.py my_ext(view, **kwargs): class MyExtension(object): def my_view(self): ...
[ "def", "plugin", "(", "module", ",", "*", "args", ",", "**", "kwargs", ")", ":", "def", "wrap", "(", "f", ")", ":", "m", "=", "module", "(", "f", ",", "*", "args", ",", "**", "kwargs", ")", "if", "inspect", ".", "isclass", "(", "m", ")", ":",...
Decorator to extend a package to a view. The module can be a class or function. It will copy all the methods to the class ie: # Your module.py my_ext(view, **kwargs): class MyExtension(object): def my_view(self): return {} return MyEx...
[ "Decorator", "to", "extend", "a", "package", "to", "a", "view", ".", "The", "module", "can", "be", "a", "class", "or", "function", ".", "It", "will", "copy", "all", "the", "methods", "to", "the", "class" ]
7afa8d4238868235dfcdae82272bd77958dd416a
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/decorators.py#L23-L56
train
mardix/Juice
juice/decorators.py
template
def template(page=None, layout=None, **kwargs): """ Decorator to change the view template and layout. It works on both View class and view methods on class only $layout is applied, everything else will be passed to the kwargs Using as first argument, it will be the layout. :fi...
python
def template(page=None, layout=None, **kwargs): """ Decorator to change the view template and layout. It works on both View class and view methods on class only $layout is applied, everything else will be passed to the kwargs Using as first argument, it will be the layout. :fi...
[ "def", "template", "(", "page", "=", "None", ",", "layout", "=", "None", ",", "**", "kwargs", ")", ":", "pkey", "=", "\"_template_extends__\"", "def", "decorator", "(", "f", ")", ":", "if", "inspect", ".", "isclass", "(", "f", ")", ":", "layout_", "=...
Decorator to change the view template and layout. It works on both View class and view methods on class only $layout is applied, everything else will be passed to the kwargs Using as first argument, it will be the layout. :first arg or $layout: The layout to use for that view ...
[ "Decorator", "to", "change", "the", "view", "template", "and", "layout", "." ]
7afa8d4238868235dfcdae82272bd77958dd416a
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/decorators.py#L127-L190
train
marrow/util
marrow/util/object.py
merge
def merge(s, t): """Merge dictionary t into s.""" for k, v in t.items(): if isinstance(v, dict): if k not in s: s[k] = v continue s[k] = merge(s[k], v) continue s[k] = v return s
python
def merge(s, t): """Merge dictionary t into s.""" for k, v in t.items(): if isinstance(v, dict): if k not in s: s[k] = v continue s[k] = merge(s[k], v) continue s[k] = v return s
[ "def", "merge", "(", "s", ",", "t", ")", ":", "for", "k", ",", "v", "in", "t", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "if", "k", "not", "in", "s", ":", "s", "[", "k", "]", "=", "v", "continue", ...
Merge dictionary t into s.
[ "Merge", "dictionary", "t", "into", "s", "." ]
abb8163dbd1fa0692d42a44d129b12ae2b39cdf2
https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/object.py#L51-L65
train
marrow/util
marrow/util/object.py
load_object
def load_object(target, namespace=None): """This helper function loads an object identified by a dotted-notation string. For example: # Load class Foo from example.objects load_object('example.objects:Foo') If a plugin namespace is provided simple name references are allowed. For example...
python
def load_object(target, namespace=None): """This helper function loads an object identified by a dotted-notation string. For example: # Load class Foo from example.objects load_object('example.objects:Foo') If a plugin namespace is provided simple name references are allowed. For example...
[ "def", "load_object", "(", "target", ",", "namespace", "=", "None", ")", ":", "if", "namespace", "and", "':'", "not", "in", "target", ":", "allowable", "=", "dict", "(", "(", "i", ".", "name", ",", "i", ")", "for", "i", "in", "pkg_resources", ".", ...
This helper function loads an object identified by a dotted-notation string. For example: # Load class Foo from example.objects load_object('example.objects:Foo') If a plugin namespace is provided simple name references are allowed. For example: # Load the plugin named 'routing' fro...
[ "This", "helper", "function", "loads", "an", "object", "identified", "by", "a", "dotted", "-", "notation", "string", "." ]
abb8163dbd1fa0692d42a44d129b12ae2b39cdf2
https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/object.py#L68-L95
train
marrow/util
marrow/util/object.py
getargspec
def getargspec(obj): """An improved inspect.getargspec. Has a slightly different return value from the default getargspec. Returns a tuple of: required, optional, args, kwargs list, dict, bool, bool Required is a list of required named arguments. Optional is a dictionary mapping o...
python
def getargspec(obj): """An improved inspect.getargspec. Has a slightly different return value from the default getargspec. Returns a tuple of: required, optional, args, kwargs list, dict, bool, bool Required is a list of required named arguments. Optional is a dictionary mapping o...
[ "def", "getargspec", "(", "obj", ")", ":", "argnames", ",", "varargs", ",", "varkw", ",", "_defaults", "=", "None", ",", "None", ",", "None", ",", "None", "if", "inspect", ".", "isfunction", "(", "obj", ")", "or", "inspect", ".", "ismethod", "(", "ob...
An improved inspect.getargspec. Has a slightly different return value from the default getargspec. Returns a tuple of: required, optional, args, kwargs list, dict, bool, bool Required is a list of required named arguments. Optional is a dictionary mapping optional arguments to default...
[ "An", "improved", "inspect", ".", "getargspec", "." ]
abb8163dbd1fa0692d42a44d129b12ae2b39cdf2
https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/object.py#L253-L308
train
The-Politico/politico-civic-election-night
electionnight/viewsets/state.py
StateMixin.get_queryset
def get_queryset(self): """ Returns a queryset of all states holding a non-special election on a date. """ try: date = ElectionDay.objects.get(date=self.kwargs["date"]) except Exception: raise APIException( "No elections on {}.".for...
python
def get_queryset(self): """ Returns a queryset of all states holding a non-special election on a date. """ try: date = ElectionDay.objects.get(date=self.kwargs["date"]) except Exception: raise APIException( "No elections on {}.".for...
[ "def", "get_queryset", "(", "self", ")", ":", "try", ":", "date", "=", "ElectionDay", ".", "objects", ".", "get", "(", "date", "=", "self", ".", "kwargs", "[", "\"date\"", "]", ")", "except", "Exception", ":", "raise", "APIException", "(", "\"No election...
Returns a queryset of all states holding a non-special election on a date.
[ "Returns", "a", "queryset", "of", "all", "states", "holding", "a", "non", "-", "special", "election", "on", "a", "date", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/viewsets/state.py#L10-L32
train
adamziel/python_translate
python_translate/dumpers.py
FileDumper.get_relative_path
def get_relative_path(self, domain, locale): """ Gets the relative file path using the template. @type domain: str @param domain: The domain @type locale: str @param locale: The locale @rtype: string @return: The relative file path """ r...
python
def get_relative_path(self, domain, locale): """ Gets the relative file path using the template. @type domain: str @param domain: The domain @type locale: str @param locale: The locale @rtype: string @return: The relative file path """ r...
[ "def", "get_relative_path", "(", "self", ",", "domain", ",", "locale", ")", ":", "return", "self", ".", "relative_path_template", ".", "format", "(", "domain", "=", "domain", ",", "locale", "=", "locale", ",", "extension", "=", "self", ".", "get_extension", ...
Gets the relative file path using the template. @type domain: str @param domain: The domain @type locale: str @param locale: The locale @rtype: string @return: The relative file path
[ "Gets", "the", "relative", "file", "path", "using", "the", "template", "." ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/dumpers.py#L112-L129
train
textbook/atmdb
atmdb/utils.py
_overlap
async def _overlap(items, overlap_attr, client=None, get_method=None): """Generic overlap implementation. Arguments: item (:py:class:`collections.abc.Sequence`): The objects to find overlaps for. overlap_attr (:py:class:`str`): The attribute of the items to use as input for the over...
python
async def _overlap(items, overlap_attr, client=None, get_method=None): """Generic overlap implementation. Arguments: item (:py:class:`collections.abc.Sequence`): The objects to find overlaps for. overlap_attr (:py:class:`str`): The attribute of the items to use as input for the over...
[ "async", "def", "_overlap", "(", "items", ",", "overlap_attr", ",", "client", "=", "None", ",", "get_method", "=", "None", ")", ":", "overlap", "=", "set", ".", "intersection", "(", "*", "(", "getattr", "(", "item", ",", "overlap_attr", ")", "for", "it...
Generic overlap implementation. Arguments: item (:py:class:`collections.abc.Sequence`): The objects to find overlaps for. overlap_attr (:py:class:`str`): The attribute of the items to use as input for the overlap. client (:py:class:`~.TMDbClient`, optional): The TMDb client ...
[ "Generic", "overlap", "implementation", "." ]
cab14547d2e777a1e26c2560266365c484855789
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/utils.py#L77-L101
train
textbook/atmdb
atmdb/utils.py
_find_overlap
async def _find_overlap(queries, client, find_method, get_method, overlap_function): """Generic find and overlap implementation. Arguments names (:py:class:`collections.abc.Sequence`): The queries of the people to find overlaps for. client (:py:class:`~.TMDbClient`):...
python
async def _find_overlap(queries, client, find_method, get_method, overlap_function): """Generic find and overlap implementation. Arguments names (:py:class:`collections.abc.Sequence`): The queries of the people to find overlaps for. client (:py:class:`~.TMDbClient`):...
[ "async", "def", "_find_overlap", "(", "queries", ",", "client", ",", "find_method", ",", "get_method", ",", "overlap_function", ")", ":", "results", "=", "[", "]", "for", "query", "in", "queries", ":", "candidates", "=", "await", "getattr", "(", "client", ...
Generic find and overlap implementation. Arguments names (:py:class:`collections.abc.Sequence`): The queries of the people to find overlaps for. client (:py:class:`~.TMDbClient`): The TMDb client. find_method (:py:class:`str`): The name of the client method to use for finding cand...
[ "Generic", "find", "and", "overlap", "implementation", "." ]
cab14547d2e777a1e26c2560266365c484855789
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/utils.py#L104-L127
train
jeffh/describe
describe/spec/containers.py
Example.before
def before(self, context): "Invokes all before functions with context passed to them." run.before_each.execute(context) self._invoke(self._before, context)
python
def before(self, context): "Invokes all before functions with context passed to them." run.before_each.execute(context) self._invoke(self._before, context)
[ "def", "before", "(", "self", ",", "context", ")", ":", "\"Invokes all before functions with context passed to them.\"", "run", ".", "before_each", ".", "execute", "(", "context", ")", "self", ".", "_invoke", "(", "self", ".", "_before", ",", "context", ")" ]
Invokes all before functions with context passed to them.
[ "Invokes", "all", "before", "functions", "with", "context", "passed", "to", "them", "." ]
6a33ffecc3340b57e60bc8a7095521882ff9a156
https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/containers.py#L175-L178
train
jeffh/describe
describe/spec/containers.py
Example.after
def after(self, context): "Invokes all after functions with context passed to them." self._invoke(self._after, context) run.after_each.execute(context)
python
def after(self, context): "Invokes all after functions with context passed to them." self._invoke(self._after, context) run.after_each.execute(context)
[ "def", "after", "(", "self", ",", "context", ")", ":", "\"Invokes all after functions with context passed to them.\"", "self", ".", "_invoke", "(", "self", ".", "_after", ",", "context", ")", "run", ".", "after_each", ".", "execute", "(", "context", ")" ]
Invokes all after functions with context passed to them.
[ "Invokes", "all", "after", "functions", "with", "context", "passed", "to", "them", "." ]
6a33ffecc3340b57e60bc8a7095521882ff9a156
https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/containers.py#L180-L183
train
riga/scinum
scinum.py
Number.repr
def repr(self, *args, **kwargs): """ Returns the unique string representation of the number. """ if not self.is_numpy: text = "'" + self.str(*args, **kwargs) + "'" else: text = "{} numpy array, {} uncertainties".format(self.shape, len(self.uncertainties)) ...
python
def repr(self, *args, **kwargs): """ Returns the unique string representation of the number. """ if not self.is_numpy: text = "'" + self.str(*args, **kwargs) + "'" else: text = "{} numpy array, {} uncertainties".format(self.shape, len(self.uncertainties)) ...
[ "def", "repr", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "self", ".", "is_numpy", ":", "text", "=", "\"'\"", "+", "self", ".", "str", "(", "*", "args", ",", "**", "kwargs", ")", "+", "\"'\"", "else", ":", "text"...
Returns the unique string representation of the number.
[ "Returns", "the", "unique", "string", "representation", "of", "the", "number", "." ]
55eb6d8aa77beacee5a07443392954b8a0aad8cb
https://github.com/riga/scinum/blob/55eb6d8aa77beacee5a07443392954b8a0aad8cb/scinum.py#L585-L594
train
The-Politico/politico-civic-election-night
electionnight/serializers/election_day.py
ElectionDaySerializer.get_states
def get_states(self, obj): """States holding a non-special election on election day.""" return reverse( 'electionnight_api_state-election-list', request=self.context['request'], kwargs={'date': obj.date} )
python
def get_states(self, obj): """States holding a non-special election on election day.""" return reverse( 'electionnight_api_state-election-list', request=self.context['request'], kwargs={'date': obj.date} )
[ "def", "get_states", "(", "self", ",", "obj", ")", ":", "return", "reverse", "(", "'electionnight_api_state-election-list'", ",", "request", "=", "self", ".", "context", "[", "'request'", "]", ",", "kwargs", "=", "{", "'date'", ":", "obj", ".", "date", "}"...
States holding a non-special election on election day.
[ "States", "holding", "a", "non", "-", "special", "election", "on", "election", "day", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election_day.py#L12-L18
train
The-Politico/politico-civic-election-night
electionnight/serializers/election_day.py
ElectionDaySerializer.get_bodies
def get_bodies(self, obj): """Bodies with offices up for election on election day.""" return reverse( 'electionnight_api_body-election-list', request=self.context['request'], kwargs={'date': obj.date} )
python
def get_bodies(self, obj): """Bodies with offices up for election on election day.""" return reverse( 'electionnight_api_body-election-list', request=self.context['request'], kwargs={'date': obj.date} )
[ "def", "get_bodies", "(", "self", ",", "obj", ")", ":", "return", "reverse", "(", "'electionnight_api_body-election-list'", ",", "request", "=", "self", ".", "context", "[", "'request'", "]", ",", "kwargs", "=", "{", "'date'", ":", "obj", ".", "date", "}",...
Bodies with offices up for election on election day.
[ "Bodies", "with", "offices", "up", "for", "election", "on", "election", "day", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election_day.py#L20-L26
train
The-Politico/politico-civic-election-night
electionnight/serializers/election_day.py
ElectionDaySerializer.get_executive_offices
def get_executive_offices(self, obj): """Executive offices up for election on election day.""" return reverse( 'electionnight_api_office-election-list', request=self.context['request'], kwargs={'date': obj.date} )
python
def get_executive_offices(self, obj): """Executive offices up for election on election day.""" return reverse( 'electionnight_api_office-election-list', request=self.context['request'], kwargs={'date': obj.date} )
[ "def", "get_executive_offices", "(", "self", ",", "obj", ")", ":", "return", "reverse", "(", "'electionnight_api_office-election-list'", ",", "request", "=", "self", ".", "context", "[", "'request'", "]", ",", "kwargs", "=", "{", "'date'", ":", "obj", ".", "...
Executive offices up for election on election day.
[ "Executive", "offices", "up", "for", "election", "on", "election", "day", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election_day.py#L28-L34
train
The-Politico/politico-civic-election-night
electionnight/serializers/election_day.py
ElectionDaySerializer.get_special_elections
def get_special_elections(self, obj): """States holding a special election on election day.""" return reverse( 'electionnight_api_special-election-list', request=self.context['request'], kwargs={'date': obj.date} )
python
def get_special_elections(self, obj): """States holding a special election on election day.""" return reverse( 'electionnight_api_special-election-list', request=self.context['request'], kwargs={'date': obj.date} )
[ "def", "get_special_elections", "(", "self", ",", "obj", ")", ":", "return", "reverse", "(", "'electionnight_api_special-election-list'", ",", "request", "=", "self", ".", "context", "[", "'request'", "]", ",", "kwargs", "=", "{", "'date'", ":", "obj", ".", ...
States holding a special election on election day.
[ "States", "holding", "a", "special", "election", "on", "election", "day", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election_day.py#L36-L42
train
dailymotion/cloudkey-py
cloudkey.py
normalize
def normalize(arg=None): """Normalizes an argument for signing purpose. This is used for normalizing the arguments of RPC method calls. :param arg: The argument to normalize :return: A string representating the normalized argument. .. doctest:: >>> from cloud.rpc import normalize >>> ...
python
def normalize(arg=None): """Normalizes an argument for signing purpose. This is used for normalizing the arguments of RPC method calls. :param arg: The argument to normalize :return: A string representating the normalized argument. .. doctest:: >>> from cloud.rpc import normalize >>> ...
[ "def", "normalize", "(", "arg", "=", "None", ")", ":", "res", "=", "''", "t_arg", "=", "type", "(", "arg", ")", "if", "t_arg", "in", "(", "list", ",", "tuple", ")", ":", "for", "i", "in", "arg", ":", "res", "+=", "normalize", "(", "i", ")", "...
Normalizes an argument for signing purpose. This is used for normalizing the arguments of RPC method calls. :param arg: The argument to normalize :return: A string representating the normalized argument. .. doctest:: >>> from cloud.rpc import normalize >>> normalize(['foo', 42, 'bar']) ...
[ "Normalizes", "an", "argument", "for", "signing", "purpose", "." ]
81334553e0737b87c66b12ad2f1eb8e26ef68a96
https://github.com/dailymotion/cloudkey-py/blob/81334553e0737b87c66b12ad2f1eb8e26ef68a96/cloudkey.py#L92-L135
train
dailymotion/cloudkey-py
cloudkey.py
sign
def sign(shared_secret, msg): """Signs a message using a shared secret. :param shared_secret: The shared secret used to sign the message :param msg: The message to sign :return: The signature as a string .. doctest:: >>> from cloud.rpc import sign >>> sign('sEcReT_KeY', 'hello world') ...
python
def sign(shared_secret, msg): """Signs a message using a shared secret. :param shared_secret: The shared secret used to sign the message :param msg: The message to sign :return: The signature as a string .. doctest:: >>> from cloud.rpc import sign >>> sign('sEcReT_KeY', 'hello world') ...
[ "def", "sign", "(", "shared_secret", ",", "msg", ")", ":", "if", "isinstance", "(", "msg", ",", "unicode", ")", ":", "msg", "=", "msg", ".", "encode", "(", "'utf8'", ")", "return", "hashlib", ".", "md5", "(", "msg", "+", "shared_secret", ")", ".", ...
Signs a message using a shared secret. :param shared_secret: The shared secret used to sign the message :param msg: The message to sign :return: The signature as a string .. doctest:: >>> from cloud.rpc import sign >>> sign('sEcReT_KeY', 'hello world') '5f048ebaf6f06576b60716dc8f815d8...
[ "Signs", "a", "message", "using", "a", "shared", "secret", "." ]
81334553e0737b87c66b12ad2f1eb8e26ef68a96
https://github.com/dailymotion/cloudkey-py/blob/81334553e0737b87c66b12ad2f1eb8e26ef68a96/cloudkey.py#L137-L153
train
louib/confirm
confirm/utils.py
config_parser_to_dict
def config_parser_to_dict(config_parser): """ Convert a ConfigParser to a dictionary. """ response = {} for section in config_parser.sections(): for option in config_parser.options(section): response.setdefault(section, {})[option] = config_parser.get(section, option) retur...
python
def config_parser_to_dict(config_parser): """ Convert a ConfigParser to a dictionary. """ response = {} for section in config_parser.sections(): for option in config_parser.options(section): response.setdefault(section, {})[option] = config_parser.get(section, option) retur...
[ "def", "config_parser_to_dict", "(", "config_parser", ")", ":", "response", "=", "{", "}", "for", "section", "in", "config_parser", ".", "sections", "(", ")", ":", "for", "option", "in", "config_parser", ".", "options", "(", "section", ")", ":", "response", ...
Convert a ConfigParser to a dictionary.
[ "Convert", "a", "ConfigParser", "to", "a", "dictionary", "." ]
0acd1eccda6cd71c69d2ae33166a16a257685811
https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/utils.py#L18-L28
train
louib/confirm
confirm/utils.py
load_config_file
def load_config_file(config_file_path, config_file): """ Loads a config file, whether it is a yaml file or a .INI file. :param config_file_path: Path of the configuration file, used to infer the file format. :returns: Dictionary representation of the configuration file. """ if config_file_path...
python
def load_config_file(config_file_path, config_file): """ Loads a config file, whether it is a yaml file or a .INI file. :param config_file_path: Path of the configuration file, used to infer the file format. :returns: Dictionary representation of the configuration file. """ if config_file_path...
[ "def", "load_config_file", "(", "config_file_path", ",", "config_file", ")", ":", "if", "config_file_path", ".", "lower", "(", ")", ".", "endswith", "(", "\".yaml\"", ")", ":", "return", "yaml", ".", "load", "(", "config_file", ")", "if", "any", "(", "conf...
Loads a config file, whether it is a yaml file or a .INI file. :param config_file_path: Path of the configuration file, used to infer the file format. :returns: Dictionary representation of the configuration file.
[ "Loads", "a", "config", "file", "whether", "it", "is", "a", "yaml", "file", "or", "a", ".", "INI", "file", "." ]
0acd1eccda6cd71c69d2ae33166a16a257685811
https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/utils.py#L38-L63
train
Xion/taipan
taipan/collections/dicts.py
select
def select(keys, from_, strict=False): """Selects a subset of given dictionary, including only the specified keys. :param keys: Iterable of keys to include :param strict: Whether ``keys`` are required to exist in the dictionary. :return: Dictionary whose keys are a subset of given ``keys`` :raise...
python
def select(keys, from_, strict=False): """Selects a subset of given dictionary, including only the specified keys. :param keys: Iterable of keys to include :param strict: Whether ``keys`` are required to exist in the dictionary. :return: Dictionary whose keys are a subset of given ``keys`` :raise...
[ "def", "select", "(", "keys", ",", "from_", ",", "strict", "=", "False", ")", ":", "ensure_iterable", "(", "keys", ")", "ensure_mapping", "(", "from_", ")", "if", "strict", ":", "return", "from_", ".", "__class__", "(", "(", "k", ",", "from_", "[", "...
Selects a subset of given dictionary, including only the specified keys. :param keys: Iterable of keys to include :param strict: Whether ``keys`` are required to exist in the dictionary. :return: Dictionary whose keys are a subset of given ``keys`` :raise KeyError: If ``strict`` is True and one of ``...
[ "Selects", "a", "subset", "of", "given", "dictionary", "including", "only", "the", "specified", "keys", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L162-L180
train
Xion/taipan
taipan/collections/dicts.py
omit
def omit(keys, from_, strict=False): """Returns a subset of given dictionary, omitting specified keys. :param keys: Iterable of keys to exclude :param strict: Whether ``keys`` are required to exist in the dictionary :return: Dictionary filtered by omitting ``keys`` :raise KeyError: If ``strict`` ...
python
def omit(keys, from_, strict=False): """Returns a subset of given dictionary, omitting specified keys. :param keys: Iterable of keys to exclude :param strict: Whether ``keys`` are required to exist in the dictionary :return: Dictionary filtered by omitting ``keys`` :raise KeyError: If ``strict`` ...
[ "def", "omit", "(", "keys", ",", "from_", ",", "strict", "=", "False", ")", ":", "ensure_iterable", "(", "keys", ")", "ensure_mapping", "(", "from_", ")", "if", "strict", ":", "remaining_keys", "=", "set", "(", "iterkeys", "(", "from_", ")", ")", "remo...
Returns a subset of given dictionary, omitting specified keys. :param keys: Iterable of keys to exclude :param strict: Whether ``keys`` are required to exist in the dictionary :return: Dictionary filtered by omitting ``keys`` :raise KeyError: If ``strict`` is True and one of ``keys`` is not found ...
[ "Returns", "a", "subset", "of", "given", "dictionary", "omitting", "specified", "keys", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L188-L210
train
Xion/taipan
taipan/collections/dicts.py
filteritems
def filteritems(predicate, dict_): """Return a new dictionary comprising of items for which ``predicate`` returns True. :param predicate: Predicate taking a key-value pair, or None .. versionchanged: 0.0.2 ``predicate`` is now taking a key-value pair as a single argument. """ predicate ...
python
def filteritems(predicate, dict_): """Return a new dictionary comprising of items for which ``predicate`` returns True. :param predicate: Predicate taking a key-value pair, or None .. versionchanged: 0.0.2 ``predicate`` is now taking a key-value pair as a single argument. """ predicate ...
[ "def", "filteritems", "(", "predicate", ",", "dict_", ")", ":", "predicate", "=", "all", "if", "predicate", "is", "None", "else", "ensure_callable", "(", "predicate", ")", "ensure_mapping", "(", "dict_", ")", "return", "dict_", ".", "__class__", "(", "ifilte...
Return a new dictionary comprising of items for which ``predicate`` returns True. :param predicate: Predicate taking a key-value pair, or None .. versionchanged: 0.0.2 ``predicate`` is now taking a key-value pair as a single argument.
[ "Return", "a", "new", "dictionary", "comprising", "of", "items", "for", "which", "predicate", "returns", "True", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L215-L226
train
Xion/taipan
taipan/collections/dicts.py
starfilteritems
def starfilteritems(predicate, dict_): """Return a new dictionary comprising of keys and values for which ``predicate`` returns True. :param predicate: Predicate taking key and value, or None .. versionchanged:: 0.0.2 Renamed ``starfilteritems`` for consistency with :func:`starmapitems`. ""...
python
def starfilteritems(predicate, dict_): """Return a new dictionary comprising of keys and values for which ``predicate`` returns True. :param predicate: Predicate taking key and value, or None .. versionchanged:: 0.0.2 Renamed ``starfilteritems`` for consistency with :func:`starmapitems`. ""...
[ "def", "starfilteritems", "(", "predicate", ",", "dict_", ")", ":", "ensure_mapping", "(", "dict_", ")", "if", "predicate", "is", "None", ":", "predicate", "=", "lambda", "k", ",", "v", ":", "all", "(", "(", "k", ",", "v", ")", ")", "else", ":", "e...
Return a new dictionary comprising of keys and values for which ``predicate`` returns True. :param predicate: Predicate taking key and value, or None .. versionchanged:: 0.0.2 Renamed ``starfilteritems`` for consistency with :func:`starmapitems`.
[ "Return", "a", "new", "dictionary", "comprising", "of", "keys", "and", "values", "for", "which", "predicate", "returns", "True", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L229-L246
train
Xion/taipan
taipan/collections/dicts.py
filterkeys
def filterkeys(predicate, dict_): """Return a new dictionary comprising of keys for which ``predicate`` returns True, and their corresponding values. :param predicate: Predicate taking a dictionary key, or None """ predicate = bool if predicate is None else ensure_callable(predicate) ensure_map...
python
def filterkeys(predicate, dict_): """Return a new dictionary comprising of keys for which ``predicate`` returns True, and their corresponding values. :param predicate: Predicate taking a dictionary key, or None """ predicate = bool if predicate is None else ensure_callable(predicate) ensure_map...
[ "def", "filterkeys", "(", "predicate", ",", "dict_", ")", ":", "predicate", "=", "bool", "if", "predicate", "is", "None", "else", "ensure_callable", "(", "predicate", ")", "ensure_mapping", "(", "dict_", ")", "return", "dict_", ".", "__class__", "(", "(", ...
Return a new dictionary comprising of keys for which ``predicate`` returns True, and their corresponding values. :param predicate: Predicate taking a dictionary key, or None
[ "Return", "a", "new", "dictionary", "comprising", "of", "keys", "for", "which", "predicate", "returns", "True", "and", "their", "corresponding", "values", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L249-L257
train
Xion/taipan
taipan/collections/dicts.py
mapitems
def mapitems(function, dict_): """Return a new dictionary where the keys and values come from applying ``function`` to key-value pairs from given dictionary. .. warning:: If ``function`` returns a key-value pair with the same key more than once, it is undefined which value will be chosen ...
python
def mapitems(function, dict_): """Return a new dictionary where the keys and values come from applying ``function`` to key-value pairs from given dictionary. .. warning:: If ``function`` returns a key-value pair with the same key more than once, it is undefined which value will be chosen ...
[ "def", "mapitems", "(", "function", ",", "dict_", ")", ":", "ensure_mapping", "(", "dict_", ")", "function", "=", "identity", "(", ")", "if", "function", "is", "None", "else", "ensure_callable", "(", "function", ")", "return", "dict_", ".", "__class__", "(...
Return a new dictionary where the keys and values come from applying ``function`` to key-value pairs from given dictionary. .. warning:: If ``function`` returns a key-value pair with the same key more than once, it is undefined which value will be chosen for that key in the resulting d...
[ "Return", "a", "new", "dictionary", "where", "the", "keys", "and", "values", "come", "from", "applying", "function", "to", "key", "-", "value", "pairs", "from", "given", "dictionary", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L273-L291
train
Xion/taipan
taipan/collections/dicts.py
starmapitems
def starmapitems(function, dict_): """Return a new dictionary where the keys and values come from applying ``function`` to the keys and values of given dictionary. .. warning:: If ``function`` returns a key-value pair with the same key more than once, it is undefined which value will be ch...
python
def starmapitems(function, dict_): """Return a new dictionary where the keys and values come from applying ``function`` to the keys and values of given dictionary. .. warning:: If ``function`` returns a key-value pair with the same key more than once, it is undefined which value will be ch...
[ "def", "starmapitems", "(", "function", ",", "dict_", ")", ":", "ensure_mapping", "(", "dict_", ")", "if", "function", "is", "None", ":", "function", "=", "lambda", "k", ",", "v", ":", "(", "k", ",", "v", ")", "else", ":", "ensure_callable", "(", "fu...
Return a new dictionary where the keys and values come from applying ``function`` to the keys and values of given dictionary. .. warning:: If ``function`` returns a key-value pair with the same key more than once, it is undefined which value will be chosen for that key in the resulting...
[ "Return", "a", "new", "dictionary", "where", "the", "keys", "and", "values", "come", "from", "applying", "function", "to", "the", "keys", "and", "values", "of", "given", "dictionary", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L294-L317
train
Xion/taipan
taipan/collections/dicts.py
mapkeys
def mapkeys(function, dict_): """Return a new dictionary where the keys come from applying ``function`` to the keys of given dictionary. .. warning:: If ``function`` returns the same value for more than one key, it is undefined which key will be chosen for the resulting dictionary. :p...
python
def mapkeys(function, dict_): """Return a new dictionary where the keys come from applying ``function`` to the keys of given dictionary. .. warning:: If ``function`` returns the same value for more than one key, it is undefined which key will be chosen for the resulting dictionary. :p...
[ "def", "mapkeys", "(", "function", ",", "dict_", ")", ":", "ensure_mapping", "(", "dict_", ")", "function", "=", "identity", "(", ")", "if", "function", "is", "None", "else", "ensure_callable", "(", "function", ")", "return", "dict_", ".", "__class__", "("...
Return a new dictionary where the keys come from applying ``function`` to the keys of given dictionary. .. warning:: If ``function`` returns the same value for more than one key, it is undefined which key will be chosen for the resulting dictionary. :param function: Function taking a dict...
[ "Return", "a", "new", "dictionary", "where", "the", "keys", "come", "from", "applying", "function", "to", "the", "keys", "of", "given", "dictionary", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L320-L336
train
Xion/taipan
taipan/collections/dicts.py
merge
def merge(*dicts, **kwargs): """Merges two or more dictionaries into a single one. Optional keyword arguments allow to control the exact way in which the dictionaries will be merged. :param overwrite: Whether repeated keys should have their values overwritten, retaining the last value...
python
def merge(*dicts, **kwargs): """Merges two or more dictionaries into a single one. Optional keyword arguments allow to control the exact way in which the dictionaries will be merged. :param overwrite: Whether repeated keys should have their values overwritten, retaining the last value...
[ "def", "merge", "(", "*", "dicts", ",", "**", "kwargs", ")", ":", "ensure_argcount", "(", "dicts", ",", "min_", "=", "1", ")", "dicts", "=", "list", "(", "imap", "(", "ensure_mapping", ",", "dicts", ")", ")", "ensure_keyword_args", "(", "kwargs", ",", ...
Merges two or more dictionaries into a single one. Optional keyword arguments allow to control the exact way in which the dictionaries will be merged. :param overwrite: Whether repeated keys should have their values overwritten, retaining the last value, as per given order of dictionaries...
[ "Merges", "two", "or", "more", "dictionaries", "into", "a", "single", "one", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L355-L403
train
Xion/taipan
taipan/collections/dicts.py
extend
def extend(dict_, *dicts, **kwargs): """Extend a dictionary with keys and values from other dictionaries. :param dict_: Dictionary to extend Optional keyword arguments allow to control the exact way in which ``dict_`` will be extended. :param overwrite: Whether repeated keys should have ...
python
def extend(dict_, *dicts, **kwargs): """Extend a dictionary with keys and values from other dictionaries. :param dict_: Dictionary to extend Optional keyword arguments allow to control the exact way in which ``dict_`` will be extended. :param overwrite: Whether repeated keys should have ...
[ "def", "extend", "(", "dict_", ",", "*", "dicts", ",", "**", "kwargs", ")", ":", "ensure_mapping", "(", "dict_", ")", "dicts", "=", "list", "(", "imap", "(", "ensure_mapping", ",", "dicts", ")", ")", "ensure_keyword_args", "(", "kwargs", ",", "optional",...
Extend a dictionary with keys and values from other dictionaries. :param dict_: Dictionary to extend Optional keyword arguments allow to control the exact way in which ``dict_`` will be extended. :param overwrite: Whether repeated keys should have their values overwritten, retaining ...
[ "Extend", "a", "dictionary", "with", "keys", "and", "values", "from", "other", "dictionaries", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L406-L456
train
Xion/taipan
taipan/collections/dicts.py
_nary_dict_update
def _nary_dict_update(dicts, **kwargs): """Implementation of n-argument ``dict.update``, with flags controlling the exact strategy. """ copy = kwargs['copy'] res = dicts[0].copy() if copy else dicts[0] if len(dicts) == 1: return res # decide what strategy to use when updating a dict...
python
def _nary_dict_update(dicts, **kwargs): """Implementation of n-argument ``dict.update``, with flags controlling the exact strategy. """ copy = kwargs['copy'] res = dicts[0].copy() if copy else dicts[0] if len(dicts) == 1: return res # decide what strategy to use when updating a dict...
[ "def", "_nary_dict_update", "(", "dicts", ",", "**", "kwargs", ")", ":", "copy", "=", "kwargs", "[", "'copy'", "]", "res", "=", "dicts", "[", "0", "]", ".", "copy", "(", ")", "if", "copy", "else", "dicts", "[", "0", "]", "if", "len", "(", "dicts"...
Implementation of n-argument ``dict.update``, with flags controlling the exact strategy.
[ "Implementation", "of", "n", "-", "argument", "dict", ".", "update", "with", "flags", "controlling", "the", "exact", "strategy", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L459-L484
train
Xion/taipan
taipan/collections/dicts.py
invert
def invert(dict_): """Return an inverted dictionary, where former values are keys and former keys are values. .. warning:: If more than one key maps to any given value in input dictionary, it is undefined which one will be chosen for the result. :param dict_: Dictionary to swap keys a...
python
def invert(dict_): """Return an inverted dictionary, where former values are keys and former keys are values. .. warning:: If more than one key maps to any given value in input dictionary, it is undefined which one will be chosen for the result. :param dict_: Dictionary to swap keys a...
[ "def", "invert", "(", "dict_", ")", ":", "ensure_mapping", "(", "dict_", ")", "return", "dict_", ".", "__class__", "(", "izip", "(", "itervalues", "(", "dict_", ")", ",", "iterkeys", "(", "dict_", ")", ")", ")" ]
Return an inverted dictionary, where former values are keys and former keys are values. .. warning:: If more than one key maps to any given value in input dictionary, it is undefined which one will be chosen for the result. :param dict_: Dictionary to swap keys and values in :return: ...
[ "Return", "an", "inverted", "dictionary", "where", "former", "values", "are", "keys", "and", "former", "keys", "are", "values", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L511-L524
train
tjcsl/cslbot
cslbot/commands/wikipath.py
cmd
def cmd(send, msg, args): """Find a path between two wikipedia articles. Syntax: {command} [article] [article] """ parser = arguments.ArgParser(args['config']) parser.add_argument('first', nargs='?') parser.add_argument('second', nargs='?') try: cmdargs = parser.parse_args(msg) ...
python
def cmd(send, msg, args): """Find a path between two wikipedia articles. Syntax: {command} [article] [article] """ parser = arguments.ArgParser(args['config']) parser.add_argument('first', nargs='?') parser.add_argument('second', nargs='?') try: cmdargs = parser.parse_args(msg) ...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "parser", "=", "arguments", ".", "ArgParser", "(", "args", "[", "'config'", "]", ")", "parser", ".", "add_argument", "(", "'first'", ",", "nargs", "=", "'?'", ")", "parser", ".", "add_argu...
Find a path between two wikipedia articles. Syntax: {command} [article] [article]
[ "Find", "a", "path", "between", "two", "wikipedia", "articles", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/wikipath.py#L56-L87
train
Xion/taipan
taipan/collections/sets.py
remove_subset
def remove_subset(set_, subset): """Remove a subset from given set. This is essentially an extension of :func:`set.remove` to work with more than one set element. :raise KeyError: If some element from ``subset`` is not present in ``set_`` .. versionadded:: 0.0.2 """ ensure_set(set_) e...
python
def remove_subset(set_, subset): """Remove a subset from given set. This is essentially an extension of :func:`set.remove` to work with more than one set element. :raise KeyError: If some element from ``subset`` is not present in ``set_`` .. versionadded:: 0.0.2 """ ensure_set(set_) e...
[ "def", "remove_subset", "(", "set_", ",", "subset", ")", ":", "ensure_set", "(", "set_", ")", "ensure_iterable", "(", "subset", ")", "for", "elem", "in", "subset", ":", "set_", ".", "remove", "(", "elem", ")" ]
Remove a subset from given set. This is essentially an extension of :func:`set.remove` to work with more than one set element. :raise KeyError: If some element from ``subset`` is not present in ``set_`` .. versionadded:: 0.0.2
[ "Remove", "a", "subset", "from", "given", "set", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/sets.py#L36-L50
train
Xion/taipan
taipan/collections/sets.py
power
def power(set_): """Returns all subsets of given set. :return: Powerset of given set, i.e. iterable containing all its subsets, sorted by ascending cardinality. """ ensure_countable(set_) result = chain.from_iterable(combinations(set_, r) for r in xran...
python
def power(set_): """Returns all subsets of given set. :return: Powerset of given set, i.e. iterable containing all its subsets, sorted by ascending cardinality. """ ensure_countable(set_) result = chain.from_iterable(combinations(set_, r) for r in xran...
[ "def", "power", "(", "set_", ")", ":", "ensure_countable", "(", "set_", ")", "result", "=", "chain", ".", "from_iterable", "(", "combinations", "(", "set_", ",", "r", ")", "for", "r", "in", "xrange", "(", "len", "(", "set_", ")", "+", "1", ")", ")"...
Returns all subsets of given set. :return: Powerset of given set, i.e. iterable containing all its subsets, sorted by ascending cardinality.
[ "Returns", "all", "subsets", "of", "given", "set", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/sets.py#L73-L83
train
Xion/taipan
taipan/collections/sets.py
trivial_partition
def trivial_partition(set_): """Returns a parition of given set into 1-element subsets. :return: Trivial partition of given set, i.e. iterable containing disjoint 1-element sets, each consisting of a single element from given set """ ensure_countable(set_) result = ((x,) ...
python
def trivial_partition(set_): """Returns a parition of given set into 1-element subsets. :return: Trivial partition of given set, i.e. iterable containing disjoint 1-element sets, each consisting of a single element from given set """ ensure_countable(set_) result = ((x,) ...
[ "def", "trivial_partition", "(", "set_", ")", ":", "ensure_countable", "(", "set_", ")", "result", "=", "(", "(", "x", ",", ")", "for", "x", "in", "set_", ")", "return", "_harmonize_subset_types", "(", "set_", ",", "result", ")" ]
Returns a parition of given set into 1-element subsets. :return: Trivial partition of given set, i.e. iterable containing disjoint 1-element sets, each consisting of a single element from given set
[ "Returns", "a", "parition", "of", "given", "set", "into", "1", "-", "element", "subsets", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/sets.py#L89-L99
train
tjcsl/cslbot
cslbot/commands/demorse.py
cmd
def cmd(send, msg, _): """Converts morse to ascii. Syntax: {command} <text> """ demorse_codes = { '.----': '1', '-.--': 'y', '..-': 'u', '...': 's', '-.-.': 'c', '.-.-.': '+', '--..--': ',', '-.-': 'k', '.--.': 'p', '----....
python
def cmd(send, msg, _): """Converts morse to ascii. Syntax: {command} <text> """ demorse_codes = { '.----': '1', '-.--': 'y', '..-': 'u', '...': 's', '-.-.': 'c', '.-.-.': '+', '--..--': ',', '-.-': 'k', '.--.': 'p', '----....
[ "def", "cmd", "(", "send", ",", "msg", ",", "_", ")", ":", "demorse_codes", "=", "{", "'.----'", ":", "'1'", ",", "'-.--'", ":", "'y'", ",", "'..-'", ":", "'u'", ",", "'...'", ":", "'s'", ",", "'-.-.'", ":", "'c'", ",", "'.-.-.'", ":", "'+'", "...
Converts morse to ascii. Syntax: {command} <text>
[ "Converts", "morse", "to", "ascii", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/demorse.py#L22-L96
train
tjcsl/cslbot
cslbot/commands/wai.py
cmd
def cmd(send, *_): """Gives a reason for something. Syntax: {command} """ a = ["primary", "secondary", "tertiary", "hydraulic", "compressed", "required", "pseudo", "intangible", "flux"] b = [ "compressor", "engine", "lift", "elevator", "irc bot", "stabilizer", "computer", "fwilson", "csl",...
python
def cmd(send, *_): """Gives a reason for something. Syntax: {command} """ a = ["primary", "secondary", "tertiary", "hydraulic", "compressed", "required", "pseudo", "intangible", "flux"] b = [ "compressor", "engine", "lift", "elevator", "irc bot", "stabilizer", "computer", "fwilson", "csl",...
[ "def", "cmd", "(", "send", ",", "*", "_", ")", ":", "a", "=", "[", "\"primary\"", ",", "\"secondary\"", ",", "\"tertiary\"", ",", "\"hydraulic\"", ",", "\"compressed\"", ",", "\"required\"", ",", "\"pseudo\"", ",", "\"intangible\"", ",", "\"flux\"", "]", "...
Gives a reason for something. Syntax: {command}
[ "Gives", "a", "reason", "for", "something", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/wai.py#L24-L39
train
Xion/taipan
taipan/lang.py
cast
def cast(type_, value, default=ABSENT): """Cast a value to given type, optionally returning a default, if provided. :param type_: Type to cast the ``value`` into :param value: Value to cast into ``type_`` :return: ``value`` casted to ``type_``. If cast was unsuccessful and ``default`` was...
python
def cast(type_, value, default=ABSENT): """Cast a value to given type, optionally returning a default, if provided. :param type_: Type to cast the ``value`` into :param value: Value to cast into ``type_`` :return: ``value`` casted to ``type_``. If cast was unsuccessful and ``default`` was...
[ "def", "cast", "(", "type_", ",", "value", ",", "default", "=", "ABSENT", ")", ":", "assert", "isinstance", "(", "type_", ",", "type", ")", "to_number", "=", "issubclass", "(", "type_", ",", "Number", ")", "exception", "=", "ValueError", "if", "to_number...
Cast a value to given type, optionally returning a default, if provided. :param type_: Type to cast the ``value`` into :param value: Value to cast into ``type_`` :return: ``value`` casted to ``type_``. If cast was unsuccessful and ``default`` was provided, it is returned instead....
[ "Cast", "a", "value", "to", "given", "type", "optionally", "returning", "a", "default", "if", "provided", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/lang.py#L76-L113
train
Xion/taipan
taipan/lang.py
is_identifier
def is_identifier(s): """Check whether given string is a valid Python identifier. Note that this excludes language keywords, even though they exhibit a general form of an identifier. See also :func:`has_identifier_form`. :param s: String to check :return: Whether ``s`` is a valid Python identifier...
python
def is_identifier(s): """Check whether given string is a valid Python identifier. Note that this excludes language keywords, even though they exhibit a general form of an identifier. See also :func:`has_identifier_form`. :param s: String to check :return: Whether ``s`` is a valid Python identifier...
[ "def", "is_identifier", "(", "s", ")", ":", "ensure_string", "(", "s", ")", "if", "not", "IDENTIFIER_FORM_RE", ".", "match", "(", "s", ")", ":", "return", "False", "if", "is_keyword", "(", "s", ")", ":", "return", "False", "if", "s", "==", "'None'", ...
Check whether given string is a valid Python identifier. Note that this excludes language keywords, even though they exhibit a general form of an identifier. See also :func:`has_identifier_form`. :param s: String to check :return: Whether ``s`` is a valid Python identifier
[ "Check", "whether", "given", "string", "is", "a", "valid", "Python", "identifier", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/lang.py#L182-L203
train
rchatterjee/pwmodels
src/pwmodel/models.py
normalize
def normalize(pw): """ Lower case, and change the symbols to closest characters""" pw_lower = pw.lower() return ''.join(helper.L33T.get(c, c) for c in pw_lower)
python
def normalize(pw): """ Lower case, and change the symbols to closest characters""" pw_lower = pw.lower() return ''.join(helper.L33T.get(c, c) for c in pw_lower)
[ "def", "normalize", "(", "pw", ")", ":", "pw_lower", "=", "pw", ".", "lower", "(", ")", "return", "''", ".", "join", "(", "helper", ".", "L33T", ".", "get", "(", "c", ",", "c", ")", "for", "c", "in", "pw_lower", ")" ]
Lower case, and change the symbols to closest characters
[ "Lower", "case", "and", "change", "the", "symbols", "to", "closest", "characters" ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L441-L444
train
rchatterjee/pwmodels
src/pwmodel/models.py
PwModel.qth_pw
def qth_pw(self, q): """ returns the qth most probable element in the dawg. """ return heapq.nlargest(q + 2, self._T.iteritems(), key=operator.itemgetter(1))[-1]
python
def qth_pw(self, q): """ returns the qth most probable element in the dawg. """ return heapq.nlargest(q + 2, self._T.iteritems(), key=operator.itemgetter(1))[-1]
[ "def", "qth_pw", "(", "self", ",", "q", ")", ":", "return", "heapq", ".", "nlargest", "(", "q", "+", "2", ",", "self", ".", "_T", ".", "iteritems", "(", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "1", ")", ")", "[", "-", "1", "...
returns the qth most probable element in the dawg.
[ "returns", "the", "qth", "most", "probable", "element", "in", "the", "dawg", "." ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L142-L147
train
rchatterjee/pwmodels
src/pwmodel/models.py
PcfgPw.prob
def prob(self, pw): """ Return the probability of pw under the Weir PCFG model. P[{S -> L2D1Y3, L2 -> 'ab', D1 -> '1', Y3 -> '!@#'}] """ tokens = self.pcfgtokensofw(pw) S, tokens = tokens[0], tokens[1:] l = len(tokens) assert l % 2 == 0, "Expecting even n...
python
def prob(self, pw): """ Return the probability of pw under the Weir PCFG model. P[{S -> L2D1Y3, L2 -> 'ab', D1 -> '1', Y3 -> '!@#'}] """ tokens = self.pcfgtokensofw(pw) S, tokens = tokens[0], tokens[1:] l = len(tokens) assert l % 2 == 0, "Expecting even n...
[ "def", "prob", "(", "self", ",", "pw", ")", ":", "tokens", "=", "self", ".", "pcfgtokensofw", "(", "pw", ")", "S", ",", "tokens", "=", "tokens", "[", "0", "]", ",", "tokens", "[", "1", ":", "]", "l", "=", "len", "(", "tokens", ")", "assert", ...
Return the probability of pw under the Weir PCFG model. P[{S -> L2D1Y3, L2 -> 'ab', D1 -> '1', Y3 -> '!@#'}]
[ "Return", "the", "probability", "of", "pw", "under", "the", "Weir", "PCFG", "model", ".", "P", "[", "{", "S", "-", ">", "L2D1Y3", "L2", "-", ">", "ab", "D1", "-", ">", "1", "Y3", "-", ">", "!" ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L206-L227
train
rchatterjee/pwmodels
src/pwmodel/models.py
NGramPw._get_next
def _get_next(self, history): """Get the next set of characters and their probabilities""" orig_history = history if not history: return helper.START history = history[-(self._n-1):] while history and not self._T.get(history): history = history[1:] ...
python
def _get_next(self, history): """Get the next set of characters and their probabilities""" orig_history = history if not history: return helper.START history = history[-(self._n-1):] while history and not self._T.get(history): history = history[1:] ...
[ "def", "_get_next", "(", "self", ",", "history", ")", ":", "orig_history", "=", "history", "if", "not", "history", ":", "return", "helper", ".", "START", "history", "=", "history", "[", "-", "(", "self", ".", "_n", "-", "1", ")", ":", "]", "while", ...
Get the next set of characters and their probabilities
[ "Get", "the", "next", "set", "of", "characters", "and", "their", "probabilities" ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L311-L333
train
rchatterjee/pwmodels
src/pwmodel/models.py
NGramPw._gen_next
def _gen_next(self, history): """Generate next character sampled from the distribution of characters next. """ orig_history = history if not history: return helper.START history = history[-(self._n-1):] kv = [(k, v) for k, v in self._T.items(history) ...
python
def _gen_next(self, history): """Generate next character sampled from the distribution of characters next. """ orig_history = history if not history: return helper.START history = history[-(self._n-1):] kv = [(k, v) for k, v in self._T.items(history) ...
[ "def", "_gen_next", "(", "self", ",", "history", ")", ":", "orig_history", "=", "history", "if", "not", "history", ":", "return", "helper", ".", "START", "history", "=", "history", "[", "-", "(", "self", ".", "_n", "-", "1", ")", ":", "]", "kv", "=...
Generate next character sampled from the distribution of characters next.
[ "Generate", "next", "character", "sampled", "from", "the", "distribution", "of", "characters", "next", "." ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L335-L353
train
rchatterjee/pwmodels
src/pwmodel/models.py
NGramPw.generate_pws_in_order
def generate_pws_in_order(self, n, filter_func=None, N_max=1e6): """ Generates passwords in order between upto N_max @N_max is the maximum size of the priority queue will be tolerated, so if the size of the queue is bigger than 1.5 * N_max, it will shrink the size to 0.75 * N_max...
python
def generate_pws_in_order(self, n, filter_func=None, N_max=1e6): """ Generates passwords in order between upto N_max @N_max is the maximum size of the priority queue will be tolerated, so if the size of the queue is bigger than 1.5 * N_max, it will shrink the size to 0.75 * N_max...
[ "def", "generate_pws_in_order", "(", "self", ",", "n", ",", "filter_func", "=", "None", ",", "N_max", "=", "1e6", ")", ":", "states", "=", "[", "(", "-", "1.0", ",", "helper", ".", "START", ")", "]", "p_min", "=", "1e-9", "/", "(", "n", "**", "2"...
Generates passwords in order between upto N_max @N_max is the maximum size of the priority queue will be tolerated, so if the size of the queue is bigger than 1.5 * N_max, it will shrink the size to 0.75 * N_max @n is the number of password to generate. **This function is expensi...
[ "Generates", "passwords", "in", "order", "between", "upto", "N_max" ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L361-L407
train
rchatterjee/pwmodels
src/pwmodel/models.py
HistPw.prob_correction
def prob_correction(self, f=1): """ Corrects the probability error due to truncating the distribution. """ total = {'rockyou': 32602160} return f * self._T[TOTALF_W] / total.get(self._leak, self._T[TOTALF_W])
python
def prob_correction(self, f=1): """ Corrects the probability error due to truncating the distribution. """ total = {'rockyou': 32602160} return f * self._T[TOTALF_W] / total.get(self._leak, self._T[TOTALF_W])
[ "def", "prob_correction", "(", "self", ",", "f", "=", "1", ")", ":", "total", "=", "{", "'rockyou'", ":", "32602160", "}", "return", "f", "*", "self", ".", "_T", "[", "TOTALF_W", "]", "/", "total", ".", "get", "(", "self", ".", "_leak", ",", "sel...
Corrects the probability error due to truncating the distribution.
[ "Corrects", "the", "probability", "error", "due", "to", "truncating", "the", "distribution", "." ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L481-L486
train
someones/jaweson
jaweson/serialisable.py
Serialisable.serialisable
def serialisable(cls, key, obj): '''Determines what can be serialised and what shouldn't ''' # ignore class method names if key.startswith('_Serialisable'.format(cls.__name__)): return False if key in obj.__whitelist: return True # class variables ...
python
def serialisable(cls, key, obj): '''Determines what can be serialised and what shouldn't ''' # ignore class method names if key.startswith('_Serialisable'.format(cls.__name__)): return False if key in obj.__whitelist: return True # class variables ...
[ "def", "serialisable", "(", "cls", ",", "key", ",", "obj", ")", ":", "if", "key", ".", "startswith", "(", "'_Serialisable'", ".", "format", "(", "cls", ".", "__name__", ")", ")", ":", "return", "False", "if", "key", "in", "obj", ".", "__whitelist", "...
Determines what can be serialised and what shouldn't
[ "Determines", "what", "can", "be", "serialised", "and", "what", "shouldn", "t" ]
744c3ca0f3af86c48738e2d89ea69646f48cc013
https://github.com/someones/jaweson/blob/744c3ca0f3af86c48738e2d89ea69646f48cc013/jaweson/serialisable.py#L36-L60
train
JIC-CSB/jicimagelib
jicimagelib/util/array.py
normalise
def normalise(array): """Return array normalised such that all values are between 0 and 1. If all the values in the array are the same the function will return: - np.zeros(array.shape, dtype=np.float) if the value is 0 or less - np.ones(array.shape, dtype=np.float) if the value is greater than 0 :...
python
def normalise(array): """Return array normalised such that all values are between 0 and 1. If all the values in the array are the same the function will return: - np.zeros(array.shape, dtype=np.float) if the value is 0 or less - np.ones(array.shape, dtype=np.float) if the value is greater than 0 :...
[ "def", "normalise", "(", "array", ")", ":", "min_val", "=", "array", ".", "min", "(", ")", "max_val", "=", "array", ".", "max", "(", ")", "array_range", "=", "max_val", "-", "min_val", "if", "array_range", "==", "0", ":", "if", "min_val", ">", "0", ...
Return array normalised such that all values are between 0 and 1. If all the values in the array are the same the function will return: - np.zeros(array.shape, dtype=np.float) if the value is 0 or less - np.ones(array.shape, dtype=np.float) if the value is greater than 0 :param array: numpy.array ...
[ "Return", "array", "normalised", "such", "that", "all", "values", "are", "between", "0", "and", "1", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/util/array.py#L7-L27
train
JIC-CSB/jicimagelib
jicimagelib/util/array.py
reduce_stack
def reduce_stack(array3D, z_function): """Return 2D array projection of the input 3D array. The input function is applied to each line of an input x, y value. :param array3D: 3D numpy.array :param z_function: function to use for the projection (e.g. :func:`max`) """ xmax, ymax, _ = array3D.sha...
python
def reduce_stack(array3D, z_function): """Return 2D array projection of the input 3D array. The input function is applied to each line of an input x, y value. :param array3D: 3D numpy.array :param z_function: function to use for the projection (e.g. :func:`max`) """ xmax, ymax, _ = array3D.sha...
[ "def", "reduce_stack", "(", "array3D", ",", "z_function", ")", ":", "xmax", ",", "ymax", ",", "_", "=", "array3D", ".", "shape", "projection", "=", "np", ".", "zeros", "(", "(", "xmax", ",", "ymax", ")", ",", "dtype", "=", "array3D", ".", "dtype", ...
Return 2D array projection of the input 3D array. The input function is applied to each line of an input x, y value. :param array3D: 3D numpy.array :param z_function: function to use for the projection (e.g. :func:`max`)
[ "Return", "2D", "array", "projection", "of", "the", "input", "3D", "array", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/util/array.py#L29-L42
train
JIC-CSB/jicimagelib
jicimagelib/util/array.py
map_stack
def map_stack(array3D, z_function): """Return 3D array where each z-slice has had the function applied to it. :param array3D: 3D numpy.array :param z_function: function to be mapped to each z-slice """ _, _, zdim = array3D.shape return np.dstack([z_function(array3D[:,:,z]) for z in range(zdim)]...
python
def map_stack(array3D, z_function): """Return 3D array where each z-slice has had the function applied to it. :param array3D: 3D numpy.array :param z_function: function to be mapped to each z-slice """ _, _, zdim = array3D.shape return np.dstack([z_function(array3D[:,:,z]) for z in range(zdim)]...
[ "def", "map_stack", "(", "array3D", ",", "z_function", ")", ":", "_", ",", "_", ",", "zdim", "=", "array3D", ".", "shape", "return", "np", ".", "dstack", "(", "[", "z_function", "(", "array3D", "[", ":", ",", ":", ",", "z", "]", ")", "for", "z", ...
Return 3D array where each z-slice has had the function applied to it. :param array3D: 3D numpy.array :param z_function: function to be mapped to each z-slice
[ "Return", "3D", "array", "where", "each", "z", "-", "slice", "has", "had", "the", "function", "applied", "to", "it", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/util/array.py#L44-L51
train
JIC-CSB/jicimagelib
jicimagelib/util/array.py
check_dtype
def check_dtype(array, allowed): """Raises TypeError if the array is not of an allowed dtype. :param array: array whose dtype is to be checked :param allowed: instance or list of allowed dtypes """ if not hasattr(allowed, "__iter__"): allowed = [allowed,] if array.dtype not in allowed: ...
python
def check_dtype(array, allowed): """Raises TypeError if the array is not of an allowed dtype. :param array: array whose dtype is to be checked :param allowed: instance or list of allowed dtypes """ if not hasattr(allowed, "__iter__"): allowed = [allowed,] if array.dtype not in allowed: ...
[ "def", "check_dtype", "(", "array", ",", "allowed", ")", ":", "if", "not", "hasattr", "(", "allowed", ",", "\"__iter__\"", ")", ":", "allowed", "=", "[", "allowed", ",", "]", "if", "array", ".", "dtype", "not", "in", "allowed", ":", "raise", "(", "Ty...
Raises TypeError if the array is not of an allowed dtype. :param array: array whose dtype is to be checked :param allowed: instance or list of allowed dtypes
[ "Raises", "TypeError", "if", "the", "array", "is", "not", "of", "an", "allowed", "dtype", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/util/array.py#L54-L64
train
tjcsl/cslbot
cslbot/helpers/control.py
handle_ctrlchan
def handle_ctrlchan(handler, msg, nick, send): """Handle the control channel.""" with handler.db.session_scope() as db: parser = init_parser(send, handler, nick, db) try: cmdargs = parser.parse_args(msg) except arguments.ArgumentException as e: # FIXME: figure out...
python
def handle_ctrlchan(handler, msg, nick, send): """Handle the control channel.""" with handler.db.session_scope() as db: parser = init_parser(send, handler, nick, db) try: cmdargs = parser.parse_args(msg) except arguments.ArgumentException as e: # FIXME: figure out...
[ "def", "handle_ctrlchan", "(", "handler", ",", "msg", ",", "nick", ",", "send", ")", ":", "with", "handler", ".", "db", ".", "session_scope", "(", ")", "as", "db", ":", "parser", "=", "init_parser", "(", "send", ",", "handler", ",", "nick", ",", "db"...
Handle the control channel.
[ "Handle", "the", "control", "channel", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/control.py#L334-L346
train
tjcsl/cslbot
cslbot/commands/metro.py
cmd
def cmd(send, msg, args): """Provides Metro Info. Syntax: {command} """ incidents = get_incidents(args['config']['api']['wmatakey']) if not incidents: send("No incidents found. Sure you picked the right metro system?") return for t, i in incidents.items(): send("%s:" % ...
python
def cmd(send, msg, args): """Provides Metro Info. Syntax: {command} """ incidents = get_incidents(args['config']['api']['wmatakey']) if not incidents: send("No incidents found. Sure you picked the right metro system?") return for t, i in incidents.items(): send("%s:" % ...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "incidents", "=", "get_incidents", "(", "args", "[", "'config'", "]", "[", "'api'", "]", "[", "'wmatakey'", "]", ")", "if", "not", "incidents", ":", "send", "(", "\"No incidents found. Sure yo...
Provides Metro Info. Syntax: {command}
[ "Provides", "Metro", "Info", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/metro.py#L43-L56
train
The-Politico/politico-civic-election-night
electionnight/models/page_content.py
PageContent.page_location
def page_location(self): """ Returns the published URL for page. """ cycle = self.election_day.cycle.name if self.content_type.model_class() == PageType: print(self.content_object) return self.content_object.page_location_template() elif self.conte...
python
def page_location(self): """ Returns the published URL for page. """ cycle = self.election_day.cycle.name if self.content_type.model_class() == PageType: print(self.content_object) return self.content_object.page_location_template() elif self.conte...
[ "def", "page_location", "(", "self", ")", ":", "cycle", "=", "self", ".", "election_day", ".", "cycle", ".", "name", "if", "self", ".", "content_type", ".", "model_class", "(", ")", "==", "PageType", ":", "print", "(", "self", ".", "content_object", ")",...
Returns the published URL for page.
[ "Returns", "the", "published", "URL", "for", "page", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/models/page_content.py#L68-L104
train
pydanny-archive/dj-libcloud
djlibcloud/storage.py
LibCloudStorage._get_object
def _get_object(self, name): """Get object by its name. Return None if object not found""" clean_name = self._clean_name(name) try: return self.driver.get_object(self.bucket, clean_name) except ObjectDoesNotExistError: return None
python
def _get_object(self, name): """Get object by its name. Return None if object not found""" clean_name = self._clean_name(name) try: return self.driver.get_object(self.bucket, clean_name) except ObjectDoesNotExistError: return None
[ "def", "_get_object", "(", "self", ",", "name", ")", ":", "clean_name", "=", "self", ".", "_clean_name", "(", "name", ")", "try", ":", "return", "self", ".", "driver", ".", "get_object", "(", "self", ".", "bucket", ",", "clean_name", ")", "except", "Ob...
Get object by its name. Return None if object not found
[ "Get", "object", "by", "its", "name", ".", "Return", "None", "if", "object", "not", "found" ]
dc485ed56a8dec9f5f200e1effb91f6113353aa4
https://github.com/pydanny-archive/dj-libcloud/blob/dc485ed56a8dec9f5f200e1effb91f6113353aa4/djlibcloud/storage.py#L108-L114
train
pydanny-archive/dj-libcloud
djlibcloud/storage.py
LibCloudStorage.delete
def delete(self, name): """Delete object on remote""" obj = self._get_object(name) if obj: return self.driver.delete_object(obj)
python
def delete(self, name): """Delete object on remote""" obj = self._get_object(name) if obj: return self.driver.delete_object(obj)
[ "def", "delete", "(", "self", ",", "name", ")", ":", "obj", "=", "self", ".", "_get_object", "(", "name", ")", "if", "obj", ":", "return", "self", ".", "driver", ".", "delete_object", "(", "obj", ")" ]
Delete object on remote
[ "Delete", "object", "on", "remote" ]
dc485ed56a8dec9f5f200e1effb91f6113353aa4
https://github.com/pydanny-archive/dj-libcloud/blob/dc485ed56a8dec9f5f200e1effb91f6113353aa4/djlibcloud/storage.py#L116-L120
train
pydanny-archive/dj-libcloud
djlibcloud/storage.py
LibCloudStorage.listdir
def listdir(self, path='/'): """Lists the contents of the specified path, returning a 2-tuple of lists; the first item being directories, the second item being files. """ container = self._get_bucket() objects = self.driver.list_container_objects(container) path =...
python
def listdir(self, path='/'): """Lists the contents of the specified path, returning a 2-tuple of lists; the first item being directories, the second item being files. """ container = self._get_bucket() objects = self.driver.list_container_objects(container) path =...
[ "def", "listdir", "(", "self", ",", "path", "=", "'/'", ")", ":", "container", "=", "self", ".", "_get_bucket", "(", ")", "objects", "=", "self", ".", "driver", ".", "list_container_objects", "(", "container", ")", "path", "=", "self", ".", "_clean_name"...
Lists the contents of the specified path, returning a 2-tuple of lists; the first item being directories, the second item being files.
[ "Lists", "the", "contents", "of", "the", "specified", "path", "returning", "a", "2", "-", "tuple", "of", "lists", ";", "the", "first", "item", "being", "directories", "the", "second", "item", "being", "files", "." ]
dc485ed56a8dec9f5f200e1effb91f6113353aa4
https://github.com/pydanny-archive/dj-libcloud/blob/dc485ed56a8dec9f5f200e1effb91f6113353aa4/djlibcloud/storage.py#L126-L158
train
JIC-CSB/jicimagelib
jicimagelib/io.py
AutoName.name
def name(cls, func): """Return auto generated file name.""" cls.count = cls.count + 1 fpath = '{}_{}{}'.format(cls.count, func.__name__, cls.suffix) if cls.directory: fpath = os.path.join(cls.directory, fpath) return fpath
python
def name(cls, func): """Return auto generated file name.""" cls.count = cls.count + 1 fpath = '{}_{}{}'.format(cls.count, func.__name__, cls.suffix) if cls.directory: fpath = os.path.join(cls.directory, fpath) return fpath
[ "def", "name", "(", "cls", ",", "func", ")", ":", "cls", ".", "count", "=", "cls", ".", "count", "+", "1", "fpath", "=", "'{}_{}{}'", ".", "format", "(", "cls", ".", "count", ",", "func", ".", "__name__", ",", "cls", ".", "suffix", ")", "if", "...
Return auto generated file name.
[ "Return", "auto", "generated", "file", "name", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/io.py#L32-L38
train
JIC-CSB/jicimagelib
jicimagelib/io.py
BFConvertWrapper.split_pattern
def split_pattern(self): """Pattern used to split the input file.""" patterns = [] for p in self.split_order: patterns.append('_{}%{}'.format(p.capitalize(), p)) return ''.join(patterns)
python
def split_pattern(self): """Pattern used to split the input file.""" patterns = [] for p in self.split_order: patterns.append('_{}%{}'.format(p.capitalize(), p)) return ''.join(patterns)
[ "def", "split_pattern", "(", "self", ")", ":", "patterns", "=", "[", "]", "for", "p", "in", "self", ".", "split_order", ":", "patterns", ".", "append", "(", "'_{}%{}'", ".", "format", "(", "p", ".", "capitalize", "(", ")", ",", "p", ")", ")", "retu...
Pattern used to split the input file.
[ "Pattern", "used", "to", "split", "the", "input", "file", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/io.py#L112-L117
train
acutesoftware/virtual-AI-simulator
vais/worlds.py
World.pick_random_target
def pick_random_target(self): """ returns coords of a randomly generated starting position mostly over to the right hand side of the world """ start_x = math.floor(self.grd.grid_height/2) start_y = math.floor(self.grd.grid_width /2) min_dist_from_x = 3 min...
python
def pick_random_target(self): """ returns coords of a randomly generated starting position mostly over to the right hand side of the world """ start_x = math.floor(self.grd.grid_height/2) start_y = math.floor(self.grd.grid_width /2) min_dist_from_x = 3 min...
[ "def", "pick_random_target", "(", "self", ")", ":", "start_x", "=", "math", ".", "floor", "(", "self", ".", "grd", ".", "grid_height", "/", "2", ")", "start_y", "=", "math", ".", "floor", "(", "self", ".", "grd", ".", "grid_width", "/", "2", ")", "...
returns coords of a randomly generated starting position mostly over to the right hand side of the world
[ "returns", "coords", "of", "a", "randomly", "generated", "starting", "position", "mostly", "over", "to", "the", "right", "hand", "side", "of", "the", "world" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L98-L111
train
acutesoftware/virtual-AI-simulator
vais/worlds.py
World.expand_seed
def expand_seed(self, start_seed, num_iterations, val): """ takes a seed start point and grows out in random directions setting cell points to val """ self.grd.set_tile(start_seed[0], start_seed[1], val) cur_pos = [start_seed[0], start_seed[1]] while num_iteration...
python
def expand_seed(self, start_seed, num_iterations, val): """ takes a seed start point and grows out in random directions setting cell points to val """ self.grd.set_tile(start_seed[0], start_seed[1], val) cur_pos = [start_seed[0], start_seed[1]] while num_iteration...
[ "def", "expand_seed", "(", "self", ",", "start_seed", ",", "num_iterations", ",", "val", ")", ":", "self", ".", "grd", ".", "set_tile", "(", "start_seed", "[", "0", "]", ",", "start_seed", "[", "1", "]", ",", "val", ")", "cur_pos", "=", "[", "start_s...
takes a seed start point and grows out in random directions setting cell points to val
[ "takes", "a", "seed", "start", "point", "and", "grows", "out", "in", "random", "directions", "setting", "cell", "points", "to", "val" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L126-L152
train
acutesoftware/virtual-AI-simulator
vais/worlds.py
World.denoise_grid
def denoise_grid(self, val, expand=1): """ for every cell in the grid of 'val' fill all cells around it to de noise the grid """ updated_grid = [[self.grd.get_tile(y,x) \ for x in range(self.grd.grid_width)] \ for y in rang...
python
def denoise_grid(self, val, expand=1): """ for every cell in the grid of 'val' fill all cells around it to de noise the grid """ updated_grid = [[self.grd.get_tile(y,x) \ for x in range(self.grd.grid_width)] \ for y in rang...
[ "def", "denoise_grid", "(", "self", ",", "val", ",", "expand", "=", "1", ")", ":", "updated_grid", "=", "[", "[", "self", ".", "grd", ".", "get_tile", "(", "y", ",", "x", ")", "for", "x", "in", "range", "(", "self", ".", "grd", ".", "grid_width",...
for every cell in the grid of 'val' fill all cells around it to de noise the grid
[ "for", "every", "cell", "in", "the", "grid", "of", "val", "fill", "all", "cells", "around", "it", "to", "de", "noise", "the", "grid" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L154-L183
train
acutesoftware/virtual-AI-simulator
vais/worlds.py
World.add_mountains
def add_mountains(self): """ instead of the add_blocks function which was to produce line shaped walls for blocking path finding agents, this function creates more natural looking blocking areas like mountains """ from noise import pnoise2 import random ...
python
def add_mountains(self): """ instead of the add_blocks function which was to produce line shaped walls for blocking path finding agents, this function creates more natural looking blocking areas like mountains """ from noise import pnoise2 import random ...
[ "def", "add_mountains", "(", "self", ")", ":", "from", "noise", "import", "pnoise2", "import", "random", "random", ".", "seed", "(", ")", "octaves", "=", "(", "random", ".", "random", "(", ")", "*", "0.5", ")", "+", "0.5", "freq", "=", "17.0", "*", ...
instead of the add_blocks function which was to produce line shaped walls for blocking path finding agents, this function creates more natural looking blocking areas like mountains
[ "instead", "of", "the", "add_blocks", "function", "which", "was", "to", "produce", "line", "shaped", "walls", "for", "blocking", "path", "finding", "agents", "this", "function", "creates", "more", "natural", "looking", "blocking", "areas", "like", "mountains" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L198-L216
train
acutesoftware/virtual-AI-simulator
vais/worlds.py
World.add_block
def add_block(self): """ adds a random size block to the map """ row_max = self.grd.get_grid_height() - 15 if row_max < 2: row_max = 2 row = randint(0, row_max) col_max = self.grd.get_grid_width() - 10 if col_max < 2: col_max = 2 c...
python
def add_block(self): """ adds a random size block to the map """ row_max = self.grd.get_grid_height() - 15 if row_max < 2: row_max = 2 row = randint(0, row_max) col_max = self.grd.get_grid_width() - 10 if col_max < 2: col_max = 2 c...
[ "def", "add_block", "(", "self", ")", ":", "row_max", "=", "self", ".", "grd", ".", "get_grid_height", "(", ")", "-", "15", "if", "row_max", "<", "2", ":", "row_max", "=", "2", "row", "=", "randint", "(", "0", ",", "row_max", ")", "col_max", "=", ...
adds a random size block to the map
[ "adds", "a", "random", "size", "block", "to", "the", "map" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L220-L243
train
acutesoftware/virtual-AI-simulator
vais/worlds.py
WorldSimulation.run
def run(self, num_runs, show_trails, log_file_base): """ Run each agent in the world for 'num_runs' iterations Optionally saves grid results to file if base name is passed to method. """ print("--------------------------------------------------") print("Starting S...
python
def run(self, num_runs, show_trails, log_file_base): """ Run each agent in the world for 'num_runs' iterations Optionally saves grid results to file if base name is passed to method. """ print("--------------------------------------------------") print("Starting S...
[ "def", "run", "(", "self", ",", "num_runs", ",", "show_trails", ",", "log_file_base", ")", ":", "print", "(", "\"--------------------------------------------------\"", ")", "print", "(", "\"Starting Simulation - target = \"", ",", "self", ".", "agent_list", "[", "0", ...
Run each agent in the world for 'num_runs' iterations Optionally saves grid results to file if base name is passed to method.
[ "Run", "each", "agent", "in", "the", "world", "for", "num_runs", "iterations", "Optionally", "saves", "grid", "results", "to", "file", "if", "base", "name", "is", "passed", "to", "method", "." ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L259-L302
train
acutesoftware/virtual-AI-simulator
vais/worlds.py
WorldSimulation.highlight_cell_surroundings
def highlight_cell_surroundings(self, target_y, target_x): """ highlights the cells around a target to make it simpler to see on a grid. Currently assumes the target is within the boundary by 1 on all sides """ #print('SELF_WORLD', self.world) #print('target_y, ta...
python
def highlight_cell_surroundings(self, target_y, target_x): """ highlights the cells around a target to make it simpler to see on a grid. Currently assumes the target is within the boundary by 1 on all sides """ #print('SELF_WORLD', self.world) #print('target_y, ta...
[ "def", "highlight_cell_surroundings", "(", "self", ",", "target_y", ",", "target_x", ")", ":", "if", "target_y", "<", "1", ":", "print", "(", "\"target too close to top\"", ")", "if", "target_y", ">", "self", ".", "world", ".", "grd", ".", "grid_height", "-"...
highlights the cells around a target to make it simpler to see on a grid. Currently assumes the target is within the boundary by 1 on all sides
[ "highlights", "the", "cells", "around", "a", "target", "to", "make", "it", "simpler", "to", "see", "on", "a", "grid", ".", "Currently", "assumes", "the", "target", "is", "within", "the", "boundary", "by", "1", "on", "all", "sides" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L304-L332
train
tjcsl/cslbot
cslbot/commands/botspam.py
cmd
def cmd(send, _, args): """Abuses the bot. Syntax: {command} """ def lenny_send(msg): send(gen_lenny(msg)) key = args['config']['api']['bitlykey'] cmds = [lambda: gen_fortune(lenny_send), lambda: gen_urban(lenny_send, args['db'], key)] choice(cmds)()
python
def cmd(send, _, args): """Abuses the bot. Syntax: {command} """ def lenny_send(msg): send(gen_lenny(msg)) key = args['config']['api']['bitlykey'] cmds = [lambda: gen_fortune(lenny_send), lambda: gen_urban(lenny_send, args['db'], key)] choice(cmds)()
[ "def", "cmd", "(", "send", ",", "_", ",", "args", ")", ":", "def", "lenny_send", "(", "msg", ")", ":", "send", "(", "gen_lenny", "(", "msg", ")", ")", "key", "=", "args", "[", "'config'", "]", "[", "'api'", "]", "[", "'bitlykey'", "]", "cmds", ...
Abuses the bot. Syntax: {command}
[ "Abuses", "the", "bot", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/botspam.py#L39-L51
train
rraadd88/rohan
rohan/dandage/io_seqs.py
hamming_distance
def hamming_distance(s1, s2): """Return the Hamming distance between equal-length sequences""" # print(s1,s2) if len(s1) != len(s2): raise ValueError("Undefined for sequences of unequal length") return sum(el1 != el2 for el1, el2 in zip(s1.upper(), s2.upper()))
python
def hamming_distance(s1, s2): """Return the Hamming distance between equal-length sequences""" # print(s1,s2) if len(s1) != len(s2): raise ValueError("Undefined for sequences of unequal length") return sum(el1 != el2 for el1, el2 in zip(s1.upper(), s2.upper()))
[ "def", "hamming_distance", "(", "s1", ",", "s2", ")", ":", "if", "len", "(", "s1", ")", "!=", "len", "(", "s2", ")", ":", "raise", "ValueError", "(", "\"Undefined for sequences of unequal length\"", ")", "return", "sum", "(", "el1", "!=", "el2", "for", "...
Return the Hamming distance between equal-length sequences
[ "Return", "the", "Hamming", "distance", "between", "equal", "-", "length", "sequences" ]
b0643a3582a2fffc0165ace69fb80880d92bfb10
https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_seqs.py#L131-L136
train
tjcsl/cslbot
cslbot/commands/lmgtfy.py
cmd
def cmd(send, msg, args): """Explain things. Syntax: {command} <text> """ if not msg: send("Explain What?") return msg = msg.replace(' ', '+') msg = 'http://lmgtfy.com/?q=%s' % msg key = args['config']['api']['bitlykey'] send(get_short(msg, key))
python
def cmd(send, msg, args): """Explain things. Syntax: {command} <text> """ if not msg: send("Explain What?") return msg = msg.replace(' ', '+') msg = 'http://lmgtfy.com/?q=%s' % msg key = args['config']['api']['bitlykey'] send(get_short(msg, key))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "send", "(", "\"Explain What?\"", ")", "return", "msg", "=", "msg", ".", "replace", "(", "' '", ",", "'+'", ")", "msg", "=", "'http://lmgtfy.com/?q=%s'", "%", "msg...
Explain things. Syntax: {command} <text>
[ "Explain", "things", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/lmgtfy.py#L23-L35
train
tjcsl/cslbot
cslbot/helpers/misc.py
split_msg
def split_msg(msgs: List[bytes], max_len: int) -> Tuple[str, List[bytes]]: """Splits as close to the end as possible.""" msg = "" while len(msg.encode()) < max_len: if len(msg.encode()) + len(msgs[0]) > max_len: return msg, msgs char = msgs.pop(0).decode() # If we have a ...
python
def split_msg(msgs: List[bytes], max_len: int) -> Tuple[str, List[bytes]]: """Splits as close to the end as possible.""" msg = "" while len(msg.encode()) < max_len: if len(msg.encode()) + len(msgs[0]) > max_len: return msg, msgs char = msgs.pop(0).decode() # If we have a ...
[ "def", "split_msg", "(", "msgs", ":", "List", "[", "bytes", "]", ",", "max_len", ":", "int", ")", "->", "Tuple", "[", "str", ",", "List", "[", "bytes", "]", "]", ":", "msg", "=", "\"\"", "while", "len", "(", "msg", ".", "encode", "(", ")", ")",...
Splits as close to the end as possible.
[ "Splits", "as", "close", "to", "the", "end", "as", "possible", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/misc.py#L258-L269
train
intuition-io/insights
insights/plugins/messaging.py
RedisProtocol.check
def check(self, order, sids): ''' Check if a message is available ''' payload = "{}" #TODO store hashes {'intuition': {'id1': value, 'id2': value}} # Block self.timeout seconds on self.channel for a message raw_msg = self.client.blpop(self.channel, timeout=self.timeout) i...
python
def check(self, order, sids): ''' Check if a message is available ''' payload = "{}" #TODO store hashes {'intuition': {'id1': value, 'id2': value}} # Block self.timeout seconds on self.channel for a message raw_msg = self.client.blpop(self.channel, timeout=self.timeout) i...
[ "def", "check", "(", "self", ",", "order", ",", "sids", ")", ":", "payload", "=", "\"{}\"", "raw_msg", "=", "self", ".", "client", ".", "blpop", "(", "self", ".", "channel", ",", "timeout", "=", "self", ".", "timeout", ")", "if", "raw_msg", ":", "_...
Check if a message is available
[ "Check", "if", "a", "message", "is", "available" ]
a4eae53a1886164db96751d2b0964aa2acb7c2d7
https://github.com/intuition-io/insights/blob/a4eae53a1886164db96751d2b0964aa2acb7c2d7/insights/plugins/messaging.py#L45-L62
train
tjcsl/cslbot
cslbot/commands/botsnack.py
cmd
def cmd(send, msg, args): """Causes the bot to snack on something. Syntax: {command} [object] """ if not msg: send("This tastes yummy!") elif msg == args['botnick']: send("wyang says Cannibalism is generally frowned upon.") else: send("%s tastes yummy!" % msg.capitalize...
python
def cmd(send, msg, args): """Causes the bot to snack on something. Syntax: {command} [object] """ if not msg: send("This tastes yummy!") elif msg == args['botnick']: send("wyang says Cannibalism is generally frowned upon.") else: send("%s tastes yummy!" % msg.capitalize...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "send", "(", "\"This tastes yummy!\"", ")", "elif", "msg", "==", "args", "[", "'botnick'", "]", ":", "send", "(", "\"wyang says Cannibalism is generally frowned upon.\"", ...
Causes the bot to snack on something. Syntax: {command} [object]
[ "Causes", "the", "bot", "to", "snack", "on", "something", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/botsnack.py#L22-L33
train
Yipit/pyeqs
pyeqs/queryset.py
QuerySet.next
def next(self): """ Provide iteration capabilities Use a small object cache for performance """ if not self._cache: self._cache = self._get_results() self._retrieved += len(self._cache) # If we don't have any other data to return, we just ...
python
def next(self): """ Provide iteration capabilities Use a small object cache for performance """ if not self._cache: self._cache = self._get_results() self._retrieved += len(self._cache) # If we don't have any other data to return, we just ...
[ "def", "next", "(", "self", ")", ":", "if", "not", "self", ".", "_cache", ":", "self", ".", "_cache", "=", "self", ".", "_get_results", "(", ")", "self", ".", "_retrieved", "+=", "len", "(", "self", ".", "_cache", ")", "if", "not", "self", ".", "...
Provide iteration capabilities Use a small object cache for performance
[ "Provide", "iteration", "capabilities" ]
2e385c0a5d113af0e20be4d9393add2aabdd9565
https://github.com/Yipit/pyeqs/blob/2e385c0a5d113af0e20be4d9393add2aabdd9565/pyeqs/queryset.py#L87-L103
train
tjcsl/cslbot
cslbot/commands/throw.py
cmd
def cmd(send, msg, args): """Throw something. Syntax: {command} <object> [at <target>] """ users = get_users(args) if " into " in msg and msg != "into": match = re.match('(.*) into (.*)', msg) if match: msg = 'throws %s into %s' % (match.group(1), match.group(2)) ...
python
def cmd(send, msg, args): """Throw something. Syntax: {command} <object> [at <target>] """ users = get_users(args) if " into " in msg and msg != "into": match = re.match('(.*) into (.*)', msg) if match: msg = 'throws %s into %s' % (match.group(1), match.group(2)) ...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "users", "=", "get_users", "(", "args", ")", "if", "\" into \"", "in", "msg", "and", "msg", "!=", "\"into\"", ":", "match", "=", "re", ".", "match", "(", "'(.*) into (.*)'", ",", "msg", ...
Throw something. Syntax: {command} <object> [at <target>]
[ "Throw", "something", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/throw.py#L26-L52
train
delvelabs/easyinject
easyinject/injector.py
Injector.wrap
def wrap(self, function): """ Wraps a function so that all unspecified arguments will be injected if possible. Specified arguments always have precedence. """ func = inspect.getfullargspec(function) needed_arguments = func.args + func.kwonlyargs @wraps(function) ...
python
def wrap(self, function): """ Wraps a function so that all unspecified arguments will be injected if possible. Specified arguments always have precedence. """ func = inspect.getfullargspec(function) needed_arguments = func.args + func.kwonlyargs @wraps(function) ...
[ "def", "wrap", "(", "self", ",", "function", ")", ":", "func", "=", "inspect", ".", "getfullargspec", "(", "function", ")", "needed_arguments", "=", "func", ".", "args", "+", "func", ".", "kwonlyargs", "@", "wraps", "(", "function", ")", "def", "wrapper"...
Wraps a function so that all unspecified arguments will be injected if possible. Specified arguments always have precedence.
[ "Wraps", "a", "function", "so", "that", "all", "unspecified", "arguments", "will", "be", "injected", "if", "possible", ".", "Specified", "arguments", "always", "have", "precedence", "." ]
3373890732221032db0ca2e842923a835106a4e9
https://github.com/delvelabs/easyinject/blob/3373890732221032db0ca2e842923a835106a4e9/easyinject/injector.py#L48-L67
train
delvelabs/easyinject
easyinject/injector.py
Injector.call
def call(self, func, *args, **kwargs): """ Calls a specified function using the provided arguments and injectable arguments. If the function must be called multiple times, it may be best to use wrap(). """ wrapped = self.wrap(func) return wrapped(*args, *...
python
def call(self, func, *args, **kwargs): """ Calls a specified function using the provided arguments and injectable arguments. If the function must be called multiple times, it may be best to use wrap(). """ wrapped = self.wrap(func) return wrapped(*args, *...
[ "def", "call", "(", "self", ",", "func", ",", "*", "args", ",", "**", "kwargs", ")", ":", "wrapped", "=", "self", ".", "wrap", "(", "func", ")", "return", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")" ]
Calls a specified function using the provided arguments and injectable arguments. If the function must be called multiple times, it may be best to use wrap().
[ "Calls", "a", "specified", "function", "using", "the", "provided", "arguments", "and", "injectable", "arguments", "." ]
3373890732221032db0ca2e842923a835106a4e9
https://github.com/delvelabs/easyinject/blob/3373890732221032db0ca2e842923a835106a4e9/easyinject/injector.py#L97-L106
train
JIC-CSB/jicimagelib
jicimagelib/image.py
Image.png
def png(self): """Return png string of image.""" use_plugin('freeimage') with TemporaryFilePath(suffix='.png') as tmp: safe_range_im = 255 * normalise(self) imsave(tmp.fpath, safe_range_im.astype(np.uint8)) with open(tmp.fpath, 'rb') as fh: ret...
python
def png(self): """Return png string of image.""" use_plugin('freeimage') with TemporaryFilePath(suffix='.png') as tmp: safe_range_im = 255 * normalise(self) imsave(tmp.fpath, safe_range_im.astype(np.uint8)) with open(tmp.fpath, 'rb') as fh: ret...
[ "def", "png", "(", "self", ")", ":", "use_plugin", "(", "'freeimage'", ")", "with", "TemporaryFilePath", "(", "suffix", "=", "'.png'", ")", "as", "tmp", ":", "safe_range_im", "=", "255", "*", "normalise", "(", "self", ")", "imsave", "(", "tmp", ".", "f...
Return png string of image.
[ "Return", "png", "string", "of", "image", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/image.py#L86-L93
train
JIC-CSB/jicimagelib
jicimagelib/image.py
MicroscopyImage.is_me
def is_me(self, s, c, z, t): """Return True if arguments match my meta data. :param s: series :param c: channel :param z: zslice :param t: timepoint :returns: :class:`bool` """ if (self.series == s and self.channel == c and self.zs...
python
def is_me(self, s, c, z, t): """Return True if arguments match my meta data. :param s: series :param c: channel :param z: zslice :param t: timepoint :returns: :class:`bool` """ if (self.series == s and self.channel == c and self.zs...
[ "def", "is_me", "(", "self", ",", "s", ",", "c", ",", "z", ",", "t", ")", ":", "if", "(", "self", ".", "series", "==", "s", "and", "self", ".", "channel", "==", "c", "and", "self", ".", "zslice", "==", "z", "and", "self", ".", "timepoint", "=...
Return True if arguments match my meta data. :param s: series :param c: channel :param z: zslice :param t: timepoint :returns: :class:`bool`
[ "Return", "True", "if", "arguments", "match", "my", "meta", "data", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/image.py#L137-L151
train
JIC-CSB/jicimagelib
jicimagelib/image.py
MicroscopyImage.in_zstack
def in_zstack(self, s, c, t): """Return True if I am in the zstack. :param s: series :param c: channel :param t: timepoint :returns: :class:`bool` """ if (self.series == s and self.channel == c and self.timepoint == t): return ...
python
def in_zstack(self, s, c, t): """Return True if I am in the zstack. :param s: series :param c: channel :param t: timepoint :returns: :class:`bool` """ if (self.series == s and self.channel == c and self.timepoint == t): return ...
[ "def", "in_zstack", "(", "self", ",", "s", ",", "c", ",", "t", ")", ":", "if", "(", "self", ".", "series", "==", "s", "and", "self", ".", "channel", "==", "c", "and", "self", ".", "timepoint", "==", "t", ")", ":", "return", "True", "return", "F...
Return True if I am in the zstack. :param s: series :param c: channel :param t: timepoint :returns: :class:`bool`
[ "Return", "True", "if", "I", "am", "in", "the", "zstack", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/image.py#L153-L165
train
jeffh/describe
describe/spec/coordinator.py
SpecCoordinator.find_specs
def find_specs(self, directory): """Finds all specs in a given directory. Returns a list of Example and ExampleGroup instances. """ specs = [] spec_files = self.file_finder.find(directory) for spec_file in spec_files: specs.extend(self.spec_finder.find(spec_fi...
python
def find_specs(self, directory): """Finds all specs in a given directory. Returns a list of Example and ExampleGroup instances. """ specs = [] spec_files = self.file_finder.find(directory) for spec_file in spec_files: specs.extend(self.spec_finder.find(spec_fi...
[ "def", "find_specs", "(", "self", ",", "directory", ")", ":", "specs", "=", "[", "]", "spec_files", "=", "self", ".", "file_finder", ".", "find", "(", "directory", ")", "for", "spec_file", "in", "spec_files", ":", "specs", ".", "extend", "(", "self", "...
Finds all specs in a given directory. Returns a list of Example and ExampleGroup instances.
[ "Finds", "all", "specs", "in", "a", "given", "directory", ".", "Returns", "a", "list", "of", "Example", "and", "ExampleGroup", "instances", "." ]
6a33ffecc3340b57e60bc8a7095521882ff9a156
https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/coordinator.py#L16-L24
train
Xion/taipan
taipan/functional/combinators.py
flip
def flip(f): """Flip the order of positonal arguments of given function.""" ensure_callable(f) result = lambda *args, **kwargs: f(*reversed(args), **kwargs) functools.update_wrapper(result, f, ('__name__', '__module__')) return result
python
def flip(f): """Flip the order of positonal arguments of given function.""" ensure_callable(f) result = lambda *args, **kwargs: f(*reversed(args), **kwargs) functools.update_wrapper(result, f, ('__name__', '__module__')) return result
[ "def", "flip", "(", "f", ")", ":", "ensure_callable", "(", "f", ")", "result", "=", "lambda", "*", "args", ",", "**", "kwargs", ":", "f", "(", "*", "reversed", "(", "args", ")", ",", "**", "kwargs", ")", "functools", ".", "update_wrapper", "(", "re...
Flip the order of positonal arguments of given function.
[ "Flip", "the", "order", "of", "positonal", "arguments", "of", "given", "function", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/combinators.py#L35-L41
train
Xion/taipan
taipan/functional/combinators.py
compose
def compose(*fs): """Creates composition of the functions passed in. :param fs: One-argument functions, with the possible exception of last one that can accept arbitrary arguments :return: Function returning a result of functions from ``fs`` applied consecutively to the argumen...
python
def compose(*fs): """Creates composition of the functions passed in. :param fs: One-argument functions, with the possible exception of last one that can accept arbitrary arguments :return: Function returning a result of functions from ``fs`` applied consecutively to the argumen...
[ "def", "compose", "(", "*", "fs", ")", ":", "ensure_argcount", "(", "fs", ",", "min_", "=", "1", ")", "fs", "=", "list", "(", "imap", "(", "ensure_callable", ",", "fs", ")", ")", "if", "len", "(", "fs", ")", "==", "1", ":", "return", "fs", "[",...
Creates composition of the functions passed in. :param fs: One-argument functions, with the possible exception of last one that can accept arbitrary arguments :return: Function returning a result of functions from ``fs`` applied consecutively to the argument(s), in reverse order
[ "Creates", "composition", "of", "the", "functions", "passed", "in", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/combinators.py#L44-L73
train
Xion/taipan
taipan/functional/combinators.py
merge
def merge(arg, *rest, **kwargs): """Merge a collection, with functions as items, into a single function that takes a collection and maps its items through corresponding functions. :param arg: A collection of functions, such as list, tuple, or dictionary :param default: Optional default function to use ...
python
def merge(arg, *rest, **kwargs): """Merge a collection, with functions as items, into a single function that takes a collection and maps its items through corresponding functions. :param arg: A collection of functions, such as list, tuple, or dictionary :param default: Optional default function to use ...
[ "def", "merge", "(", "arg", ",", "*", "rest", ",", "**", "kwargs", ")", ":", "ensure_keyword_args", "(", "kwargs", ",", "optional", "=", "(", "'default'", ",", ")", ")", "has_default", "=", "'default'", "in", "kwargs", "if", "has_default", ":", "default"...
Merge a collection, with functions as items, into a single function that takes a collection and maps its items through corresponding functions. :param arg: A collection of functions, such as list, tuple, or dictionary :param default: Optional default function to use for items within mer...
[ "Merge", "a", "collection", "with", "functions", "as", "items", "into", "a", "single", "function", "that", "takes", "a", "collection", "and", "maps", "its", "items", "through", "corresponding", "functions", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/combinators.py#L76-L145
train
Xion/taipan
taipan/functional/combinators.py
and_
def and_(*fs): """Creates a function that returns true for given arguments iff every given function evalutes to true for those arguments. :param fs: Functions to combine :return: Short-circuiting function performing logical conjunction on results of ``fs`` applied to its arguments """...
python
def and_(*fs): """Creates a function that returns true for given arguments iff every given function evalutes to true for those arguments. :param fs: Functions to combine :return: Short-circuiting function performing logical conjunction on results of ``fs`` applied to its arguments """...
[ "def", "and_", "(", "*", "fs", ")", ":", "ensure_argcount", "(", "fs", ",", "min_", "=", "1", ")", "fs", "=", "list", "(", "imap", "(", "ensure_callable", ",", "fs", ")", ")", "if", "len", "(", "fs", ")", "==", "1", ":", "return", "fs", "[", ...
Creates a function that returns true for given arguments iff every given function evalutes to true for those arguments. :param fs: Functions to combine :return: Short-circuiting function performing logical conjunction on results of ``fs`` applied to its arguments
[ "Creates", "a", "function", "that", "returns", "true", "for", "given", "arguments", "iff", "every", "given", "function", "evalutes", "to", "true", "for", "those", "arguments", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/combinators.py#L162-L191
train