Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
command_admins
(bot, user, channel, args)
Add, remove or list admins. Usage: admins [(add|del) <nick>,...]
Add, remove or list admins. Usage: admins [(add|del) <nick>,...]
def command_admins(bot, user, channel, args): "Add, remove or list admins. Usage: admins [(add|del) <nick>,...]" if permissions(user) < 20: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format( get_nick(user))) superadmins = bot.factory.network["superadmins"] admins = set(superadmins) ^ set(bot.factory.network["admins"]) str_sadmins = " ".join(superadmins) str_admins = " ".join(admins) if admins else 0 if not args: return bot.say(channel, "superadmins: {}, admins: {}" .format(str_sadmins, str_admins)) args = args.split() if len(args) > 2: return bot.say(channel, "Too many arguments.") elif len(args) == 1: return bot.say(channel, "Not enough arguments.") mod_admins = None if "," in args[1]: # Create the list of entities to add/del but ignore superadmins. mod_admins = [i for i in args[1].split(",") if i not in superadmins] else: if args[1] in superadmins: return bot.say(channel, "Cannot modify superadmins.") # Handle addition and removal of admins. if args[0] == "del": if mod_admins: for i in mod_admins: if i in admins: bot.factory.network["admins"].discard(i) bot.say(channel, "Removed {} from admins.".format(i)) log.debug("Discarded {} from admins.".format(i)) else: bot.factory.network["admins"].discard(args[1]) bot.say(channel, "Removed {} from admins.".format(args[1])) log.debug("Discarded {} from admins.".format(args[1])) elif args[0] == "add": if mod_admins: for i in mod_admins: if i not in admins: bot.factory.network["admins"].add(i) bot.say(channel, "Added {} to admins.".format(i)) log.debug("Added {} to admins.".format(i)) else: bot.factory.network["admins"].add(args[1]) bot.say(channel, "Added {} to admins.".format(args[1])) log.debug("Added {} to admins.".format(args[1]))
[ "def", "command_admins", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "if", "permissions", "(", "user", ")", "<", "20", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")", "superadmins", "=", "bot", ".", "factory", ".", "network", "[", "\"superadmins\"", "]", "admins", "=", "set", "(", "superadmins", ")", "^", "set", "(", "bot", ".", "factory", ".", "network", "[", "\"admins\"", "]", ")", "str_sadmins", "=", "\" \"", ".", "join", "(", "superadmins", ")", "str_admins", "=", "\" \"", ".", "join", "(", "admins", ")", "if", "admins", "else", "0", "if", "not", "args", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"superadmins: {}, admins: {}\"", ".", "format", "(", "str_sadmins", ",", "str_admins", ")", ")", "args", "=", "args", ".", "split", "(", ")", "if", "len", "(", "args", ")", ">", "2", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Too many arguments.\"", ")", "elif", "len", "(", "args", ")", "==", "1", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Not enough arguments.\"", ")", "mod_admins", "=", "None", "if", "\",\"", "in", "args", "[", "1", "]", ":", "# Create the list of entities to add/del but ignore superadmins.", "mod_admins", "=", "[", "i", "for", "i", "in", "args", "[", "1", "]", ".", "split", "(", "\",\"", ")", "if", "i", "not", "in", "superadmins", "]", "else", ":", "if", "args", "[", "1", "]", "in", "superadmins", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Cannot modify superadmins.\"", ")", "# Handle addition and removal of admins.", "if", "args", "[", "0", "]", "==", "\"del\"", ":", "if", "mod_admins", ":", "for", "i", "in", "mod_admins", ":", "if", "i", "in", "admins", ":", "bot", ".", "factory", ".", "network", "[", "\"admins\"", "]", ".", "discard", "(", "i", ")", "bot", ".", "say", "(", "channel", ",", "\"Removed {} from admins.\"", ".", "format", "(", "i", ")", ")", "log", ".", "debug", "(", "\"Discarded {} from admins.\"", ".", "format", "(", "i", ")", ")", "else", ":", "bot", ".", "factory", ".", "network", "[", "\"admins\"", "]", ".", "discard", "(", "args", "[", "1", "]", ")", "bot", ".", "say", "(", "channel", ",", "\"Removed {} from admins.\"", ".", "format", "(", "args", "[", "1", "]", ")", ")", "log", ".", "debug", "(", "\"Discarded {} from admins.\"", ".", "format", "(", "args", "[", "1", "]", ")", ")", "elif", "args", "[", "0", "]", "==", "\"add\"", ":", "if", "mod_admins", ":", "for", "i", "in", "mod_admins", ":", "if", "i", "not", "in", "admins", ":", "bot", ".", "factory", ".", "network", "[", "\"admins\"", "]", ".", "add", "(", "i", ")", "bot", ".", "say", "(", "channel", ",", "\"Added {} to admins.\"", ".", "format", "(", "i", ")", ")", "log", ".", "debug", "(", "\"Added {} to admins.\"", ".", "format", "(", "i", ")", ")", "else", ":", "bot", ".", "factory", ".", "network", "[", "\"admins\"", "]", ".", "add", "(", "args", "[", "1", "]", ")", "bot", ".", "say", "(", "channel", ",", "\"Added {} to admins.\"", ".", "format", "(", "args", "[", "1", "]", ")", ")", "log", ".", "debug", "(", "\"Added {} to admins.\"", ".", "format", "(", "args", "[", "1", "]", ")", ")" ]
[ 36, 0 ]
[ 89, 60 ]
python
en
['en', 'mt', 'en']
True
command_rehash
(bot, user, channel, args)
Rehashes all available modules to reflect any changes.
Rehashes all available modules to reflect any changes.
def command_rehash(bot, user, channel, args): "Rehashes all available modules to reflect any changes." if permissions(user) < 20: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format( get_nick(user))) try: log.info("Rebuilding {}".format(bot)) rebuild.updateInstance(bot) bot.factory._unload_removed_modules() bot.factory._loadmodules() except Exception, e: log.error("Rehash error: {}.".format(e)) return bot.say(channel, "Rehash error: {}.".format(e)) else: log.info("Rehash OK.") return bot.say(channel, "Rehash OK.")
[ "def", "command_rehash", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "if", "permissions", "(", "user", ")", "<", "20", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")", "try", ":", "log", ".", "info", "(", "\"Rebuilding {}\"", ".", "format", "(", "bot", ")", ")", "rebuild", ".", "updateInstance", "(", "bot", ")", "bot", ".", "factory", ".", "_unload_removed_modules", "(", ")", "bot", ".", "factory", ".", "_loadmodules", "(", ")", "except", "Exception", ",", "e", ":", "log", ".", "error", "(", "\"Rehash error: {}.\"", ".", "format", "(", "e", ")", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"Rehash error: {}.\"", ".", "format", "(", "e", ")", ")", "else", ":", "log", ".", "info", "(", "\"Rehash OK.\"", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"Rehash OK.\"", ")" ]
[ 92, 0 ]
[ 109, 45 ]
python
en
['en', 'en', 'en']
True
command_quit
(bot, user, channel, args)
Ends this or optionally all client instances. Usage: quit [all].
Ends this or optionally all client instances. Usage: quit [all].
def command_quit(bot, user, channel, args): "Ends this or optionally all client instances. Usage: quit [all]." if permissions(user) < 20: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format( get_nick(user))) if args == "all": reactor.stop() bot.factory.retry_enabled = False log.info("Received quit command for {} from {}. Bye." .format(bot.factory.network_name, user)) bot.quit()
[ "def", "command_quit", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "if", "permissions", "(", "user", ")", "<", "20", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")", "if", "args", "==", "\"all\"", ":", "reactor", ".", "stop", "(", ")", "bot", ".", "factory", ".", "retry_enabled", "=", "False", "log", ".", "info", "(", "\"Received quit command for {} from {}. Bye.\"", ".", "format", "(", "bot", ".", "factory", ".", "network_name", ",", "user", ")", ")", "bot", ".", "quit", "(", ")" ]
[ 112, 0 ]
[ 125, 14 ]
python
en
['en', 'en', 'en']
True
command_kick
(bot, user, channel, args, reason=None)
Usage: kick <user> [<reason>]
Usage: kick <user> [<reason>]
def command_kick(bot, user, channel, args, reason=None): "Usage: kick <user> [<reason>]" if permissions(user) < 10: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format( get_nick(user))) args = [i for i in args.partition(" ") if i and i != " "] if len(args) > 2: return bot.say(channel, "Usage: kick <user> [<reason>]") else: reason = args[1] usr = args[0] bot.kick(channel, usr, reason)
[ "def", "command_kick", "(", "bot", ",", "user", ",", "channel", ",", "args", ",", "reason", "=", "None", ")", ":", "if", "permissions", "(", "user", ")", "<", "10", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")", "args", "=", "[", "i", "for", "i", "in", "args", ".", "partition", "(", "\" \"", ")", "if", "i", "and", "i", "!=", "\" \"", "]", "if", "len", "(", "args", ")", ">", "2", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Usage: kick <user> [<reason>]\"", ")", "else", ":", "reason", "=", "args", "[", "1", "]", "usr", "=", "args", "[", "0", "]", "bot", ".", "kick", "(", "channel", ",", "usr", ",", "reason", ")" ]
[ 128, 0 ]
[ 141, 34 ]
python
en
['en', 'jv', 'sw']
False
command_mode
(bot, user, channel, args)
Usage: mode <(+|-)mode> <user> [<channel>]
Usage: mode <(+|-)mode> <user> [<channel>]
def command_mode(bot, user, channel, args): "Usage: mode <(+|-)mode> <user> [<channel>]" # TODO: "all" argument instead of user. if permissions(user) < 20: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format( get_nick(user))) args = args.split() if len(args) > 3 or len(args) < 2: return bot.say(channel, "Usage: mode <(+|-)mode> <user> [<channel>]") elif len(args) == 3: chan = args[2] else: chan = channel mode, usr = args[0], args[1] if len(mode) == 2: if "+" in mode: operation, finalmode = True, mode.strip("+") elif "-" in mode: operation, finalmode = False, mode.strip("-") else: return bot.say(channel, "Mode have this format: +b") bot.mode(chan, operation, finalmode, user=usr)
[ "def", "command_mode", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "# TODO: \"all\" argument instead of user.", "if", "permissions", "(", "user", ")", "<", "20", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")", "args", "=", "args", ".", "split", "(", ")", "if", "len", "(", "args", ")", ">", "3", "or", "len", "(", "args", ")", "<", "2", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Usage: mode <(+|-)mode> <user> [<channel>]\"", ")", "elif", "len", "(", "args", ")", "==", "3", ":", "chan", "=", "args", "[", "2", "]", "else", ":", "chan", "=", "channel", "mode", ",", "usr", "=", "args", "[", "0", "]", ",", "args", "[", "1", "]", "if", "len", "(", "mode", ")", "==", "2", ":", "if", "\"+\"", "in", "mode", ":", "operation", ",", "finalmode", "=", "True", ",", "mode", ".", "strip", "(", "\"+\"", ")", "elif", "\"-\"", "in", "mode", ":", "operation", ",", "finalmode", "=", "False", ",", "mode", ".", "strip", "(", "\"-\"", ")", "else", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Mode have this format: +b\"", ")", "bot", ".", "mode", "(", "chan", ",", "operation", ",", "finalmode", ",", "user", "=", "usr", ")" ]
[ 144, 0 ]
[ 168, 50 ]
python
en
['en', 'en', 'ur']
True
command_tempban
(bot, user, channel, args)
Usage: tempban <duration> <user> [<channel>]
Usage: tempban <duration> <user> [<channel>]
def command_tempban(bot, user, channel, args): "Usage: tempban <duration> <user> [<channel>]" if permissions(user) < 20: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format( get_nick(user))) args = args.split() if len(args) > 3 or len(args) < 2: return bot.say(channel, "Usage: tempban <duration> <user> [<channel>]") elif len(args) == 3: chan = args[2] else: chan = channel duration, usr = args[0].lower(), args[1] # Accept only valid duration input e.g. 5, 5d, 5h, 5m. _valid_duration = re.compile("[0-9]+[mhd]?") def valid_duration(d): return bool(_valid_duration.search(d)) if len(duration) > 2 or not valid_duration(duration): return bot.say(channel, "Duration can be 5, 5m, 5h, 5d") if "m" in duration: cut_duration = int(duration.strip("m")) * 60 elif "h" in duration: cut_duration = int(duration.strip("h")) * 3600 elif "d" in duration: cut_duration = int(duration.strip("d")) * 86400 else: cut_duration = int(duration) bot.say(chan, "Banning {} for {}.".format(usr, duration)) log.info("Banning {} for {} on {}.".format(usr, duration, chan)) bot.mode(chan, True, "b", user=usr) reactor.callLater(cut_duration, bot.mode, chan, False, "b", user=usr)
[ "def", "command_tempban", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "if", "permissions", "(", "user", ")", "<", "20", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")", "args", "=", "args", ".", "split", "(", ")", "if", "len", "(", "args", ")", ">", "3", "or", "len", "(", "args", ")", "<", "2", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Usage: tempban <duration> <user> [<channel>]\"", ")", "elif", "len", "(", "args", ")", "==", "3", ":", "chan", "=", "args", "[", "2", "]", "else", ":", "chan", "=", "channel", "duration", ",", "usr", "=", "args", "[", "0", "]", ".", "lower", "(", ")", ",", "args", "[", "1", "]", "# Accept only valid duration input e.g. 5, 5d, 5h, 5m.", "_valid_duration", "=", "re", ".", "compile", "(", "\"[0-9]+[mhd]?\"", ")", "def", "valid_duration", "(", "d", ")", ":", "return", "bool", "(", "_valid_duration", ".", "search", "(", "d", ")", ")", "if", "len", "(", "duration", ")", ">", "2", "or", "not", "valid_duration", "(", "duration", ")", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Duration can be 5, 5m, 5h, 5d\"", ")", "if", "\"m\"", "in", "duration", ":", "cut_duration", "=", "int", "(", "duration", ".", "strip", "(", "\"m\"", ")", ")", "*", "60", "elif", "\"h\"", "in", "duration", ":", "cut_duration", "=", "int", "(", "duration", ".", "strip", "(", "\"h\"", ")", ")", "*", "3600", "elif", "\"d\"", "in", "duration", ":", "cut_duration", "=", "int", "(", "duration", ".", "strip", "(", "\"d\"", ")", ")", "*", "86400", "else", ":", "cut_duration", "=", "int", "(", "duration", ")", "bot", ".", "say", "(", "chan", ",", "\"Banning {} for {}.\"", ".", "format", "(", "usr", ",", "duration", ")", ")", "log", ".", "info", "(", "\"Banning {} for {} on {}.\"", ".", "format", "(", "usr", ",", "duration", ",", "chan", ")", ")", "bot", ".", "mode", "(", "chan", ",", "True", ",", "\"b\"", ",", "user", "=", "usr", ")", "reactor", ".", "callLater", "(", "cut_duration", ",", "bot", ".", "mode", ",", "chan", ",", "False", ",", "\"b\"", ",", "user", "=", "usr", ")" ]
[ 171, 0 ]
[ 206, 73 ]
python
en
['hu', 'en', 'ur']
False
command_setnick
(bot, user, channel, args)
Change the bots nickname. Usage: setnick <nick>
Change the bots nickname. Usage: setnick <nick>
def command_setnick(bot, user, channel, args): "Change the bots nickname. Usage: setnick <nick>" if permissions(user) < 20: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format( get_nick(user))) args = args.split() if len(args) > 1: return bot.factory.network["nickname"] = args[0] bot.nickname = bot.factory.network["nickname"] bot.setNick(bot.nickname) log.info("Changed nickname to {}".format(args[0]))
[ "def", "command_setnick", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "if", "permissions", "(", "user", ")", "<", "20", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")", "args", "=", "args", ".", "split", "(", ")", "if", "len", "(", "args", ")", ">", "1", ":", "return", "bot", ".", "factory", ".", "network", "[", "\"nickname\"", "]", "=", "args", "[", "0", "]", "bot", ".", "nickname", "=", "bot", ".", "factory", ".", "network", "[", "\"nickname\"", "]", "bot", ".", "setNick", "(", "bot", ".", "nickname", ")", "log", ".", "info", "(", "\"Changed nickname to {}\"", ".", "format", "(", "args", "[", "0", "]", ")", ")" ]
[ 209, 0 ]
[ 222, 54 ]
python
en
['en', 'ceb', 'en']
True
command_setlead
(bot, user, channel, args)
Change the bots command identifier. Usage: setlead <lead>.
Change the bots command identifier. Usage: setlead <lead>.
def command_setlead(bot, user, channel, args): "Change the bots command identifier. Usage: setlead <lead>." perms, nick = permissions(user), get_nick(user) if perms < 20: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format(nick)) if not args: return bot.say(channel, "Usage: setlead <lead>. Punctuation only.") if len(args.split()) > 1 or not args in punctuation: return bot.say(channel, "Lead has to be a punctuation mark.") bot.lead = args log.info("Command identifier changed to {}".format(bot.lead)) return bot.say(channel, "Command identifier changed to: {}" .format(bot.lead))
[ "def", "command_setlead", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "perms", ",", "nick", "=", "permissions", "(", "user", ")", ",", "get_nick", "(", "user", ")", "if", "perms", "<", "20", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "nick", ")", ")", "if", "not", "args", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Usage: setlead <lead>. Punctuation only.\"", ")", "if", "len", "(", "args", ".", "split", "(", ")", ")", ">", "1", "or", "not", "args", "in", "punctuation", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Lead has to be a punctuation mark.\"", ")", "bot", ".", "lead", "=", "args", "log", ".", "info", "(", "\"Command identifier changed to {}\"", ".", "format", "(", "bot", ".", "lead", ")", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"Command identifier changed to: {}\"", ".", "format", "(", "bot", ".", "lead", ")", ")" ]
[ 225, 0 ]
[ 240, 37 ]
python
en
['en', 'fy', 'en']
True
command_setmin
(bot, user, channel, args)
Change the bots nickname. Usage: setnick <nick>
Change the bots nickname. Usage: setnick <nick>
def command_setmin(bot, user, channel, args): "Change the bots nickname. Usage: setnick <nick>" perms, nick = permissions(user), get_nick(user) if perms < 20: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format(nick)) if len(args.split()) > 1 or not args.isdigit(): return bot.say(channel, "Minperms: {}".format(bot.factory.minperms)) minperm = int(args) if minperm > perms: # Don't shut yourself out. return bot.say(channel, "Your maximum is {}, {}".format(perms, nick)) minperm = 20 bot.factory.minperms = minperm log.info("Minperms set to {}".format(bot.factory.minperms)) return bot.say(channel, "Minperms set to: {}".format(bot.factory.minperms))
[ "def", "command_setmin", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "perms", ",", "nick", "=", "permissions", "(", "user", ")", ",", "get_nick", "(", "user", ")", "if", "perms", "<", "20", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "nick", ")", ")", "if", "len", "(", "args", ".", "split", "(", ")", ")", ">", "1", "or", "not", "args", ".", "isdigit", "(", ")", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Minperms: {}\"", ".", "format", "(", "bot", ".", "factory", ".", "minperms", ")", ")", "minperm", "=", "int", "(", "args", ")", "if", "minperm", ">", "perms", ":", "# Don't shut yourself out.", "return", "bot", ".", "say", "(", "channel", ",", "\"Your maximum is {}, {}\"", ".", "format", "(", "perms", ",", "nick", ")", ")", "minperm", "=", "20", "bot", ".", "factory", ".", "minperms", "=", "minperm", "log", ".", "info", "(", "\"Minperms set to {}\"", ".", "format", "(", "bot", ".", "factory", ".", "minperms", ")", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"Minperms set to: {}\"", ".", "format", "(", "bot", ".", "factory", ".", "minperms", ")", ")" ]
[ 243, 0 ]
[ 259, 79 ]
python
en
['en', 'ceb', 'en']
True
command_settopic
(bot, user, channel, args)
Set the channel topic. Usage: settopic <topic>
Set the channel topic. Usage: settopic <topic>
def command_settopic(bot, user, channel, args): "Set the channel topic. Usage: settopic <topic>" if permissions(user) < 10: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format( get_nick(user))) if not args: return bot.say(channel, "Usage: settopic <topic>") bot.topic(channel, args) log.info("Changed {}'s topic to {}".format(channel, args))
[ "def", "command_settopic", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "if", "permissions", "(", "user", ")", "<", "10", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")", "if", "not", "args", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Usage: settopic <topic>\"", ")", "bot", ".", "topic", "(", "channel", ",", "args", ")", "log", ".", "info", "(", "\"Changed {}'s topic to {}\"", ".", "format", "(", "channel", ",", "args", ")", ")" ]
[ 262, 0 ]
[ 272, 62 ]
python
en
['en', 'en', 'en']
True
command_join
(bot, user, channel, args)
Usage: join <channel>,... (Comma separated, hash not required).
Usage: join <channel>,... (Comma separated, hash not required).
def command_join(bot, user, channel, args): "Usage: join <channel>,... (Comma separated, hash not required)." if permissions(user) < 10: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format( get_nick(user))) channels = [i if i.startswith("#") else "#" + i\ for i in args.split(",")] network = bot.factory.network for c in channels: log.debug("Attempting to join channel {}.".format(c)) if c in network["channels"]: bot.say(channel, "I am already in {}".format(c)) log.debug("Already on channel {}".format(c)) log.debug("Channels I'm on this network: {}" .format(", ".join(network["channels"]))) else: bot.say(channel, "Joining {}.".format(c)) bot.join(c)
[ "def", "command_join", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "if", "permissions", "(", "user", ")", "<", "10", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")", "channels", "=", "[", "i", "if", "i", ".", "startswith", "(", "\"#\"", ")", "else", "\"#\"", "+", "i", "for", "i", "in", "args", ".", "split", "(", "\",\"", ")", "]", "network", "=", "bot", ".", "factory", ".", "network", "for", "c", "in", "channels", ":", "log", ".", "debug", "(", "\"Attempting to join channel {}.\"", ".", "format", "(", "c", ")", ")", "if", "c", "in", "network", "[", "\"channels\"", "]", ":", "bot", ".", "say", "(", "channel", ",", "\"I am already in {}\"", ".", "format", "(", "c", ")", ")", "log", ".", "debug", "(", "\"Already on channel {}\"", ".", "format", "(", "c", ")", ")", "log", ".", "debug", "(", "\"Channels I'm on this network: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "network", "[", "\"channels\"", "]", ")", ")", ")", "else", ":", "bot", ".", "say", "(", "channel", ",", "\"Joining {}.\"", ".", "format", "(", "c", ")", ")", "bot", ".", "join", "(", "c", ")" ]
[ 275, 0 ]
[ 295, 23 ]
python
en
['en', 'en', 'en']
True
command_leave
(bot, user, channel, args)
Usage: leave <channel>,... (Comma separated, hash not required).
Usage: leave <channel>,... (Comma separated, hash not required).
def command_leave(bot, user, channel, args): "Usage: leave <channel>,... (Comma separated, hash not required)." if permissions(user) < 10: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format( get_nick(user))) network = bot.factory.network # No arguments, so we leave the current channel. if not args: bot.factory.network["channels"].discard(channel) bot.part(channel) return # We have input, so split it into channels. channels = [i if i.startswith("#") else "#" + i\ for i in args.split(",")] for c in channels: if c in network["channels"]: if c != channel: bot.say(channel, "Leaving {}".format(c)) bot.factory.network["channels"].discard(c) bot.part(c) else: bot.say(channel, "I am not in {}".format(c)) log.debug("Attempted to leave a channel i'm not in: {}" .format(c)) log.debug("Channels I'm in: {}".format(", ".join(network["channels"])))
[ "def", "command_leave", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "if", "permissions", "(", "user", ")", "<", "10", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")", "network", "=", "bot", ".", "factory", ".", "network", "# No arguments, so we leave the current channel.", "if", "not", "args", ":", "bot", ".", "factory", ".", "network", "[", "\"channels\"", "]", ".", "discard", "(", "channel", ")", "bot", ".", "part", "(", "channel", ")", "return", "# We have input, so split it into channels.", "channels", "=", "[", "i", "if", "i", ".", "startswith", "(", "\"#\"", ")", "else", "\"#\"", "+", "i", "for", "i", "in", "args", ".", "split", "(", "\",\"", ")", "]", "for", "c", "in", "channels", ":", "if", "c", "in", "network", "[", "\"channels\"", "]", ":", "if", "c", "!=", "channel", ":", "bot", ".", "say", "(", "channel", ",", "\"Leaving {}\"", ".", "format", "(", "c", ")", ")", "bot", ".", "factory", ".", "network", "[", "\"channels\"", "]", ".", "discard", "(", "c", ")", "bot", ".", "part", "(", "c", ")", "else", ":", "bot", ".", "say", "(", "channel", ",", "\"I am not in {}\"", ".", "format", "(", "c", ")", ")", "log", ".", "debug", "(", "\"Attempted to leave a channel i'm not in: {}\"", ".", "format", "(", "c", ")", ")", "log", ".", "debug", "(", "\"Channels I'm in: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "network", "[", "\"channels\"", "]", ")", ")", ")" ]
[ 298, 0 ]
[ 328, 75 ]
python
en
['en', 'en', 'en']
True
command_channels
(bot, user, channel, args)
List channels the bot is on.
List channels the bot is on.
def command_channels(bot, user, channel, args): "List channels the bot is on." if permissions(user) < 10: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format( get_nick(user))) return bot.say(channel, "I am on {}" .format(",".join(bot.factory.network["channels"])))
[ "def", "command_channels", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "if", "permissions", "(", "user", ")", "<", "10", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"I am on {}\"", ".", "format", "(", "\",\"", ".", "join", "(", "bot", ".", "factory", ".", "network", "[", "\"channels\"", "]", ")", ")", ")" ]
[ 331, 0 ]
[ 338, 71 ]
python
en
['en', 'en', 'en']
True
command_help
(bot, user, channel, cmnd)
Get help on all commands or a specific one. Usage: help [<command>]
Get help on all commands or a specific one. Usage: help [<command>]
def command_help(bot, user, channel, cmnd): "Get help on all commands or a specific one. Usage: help [<command>]" # TODO: Only print commands that are available to the user. commands = [] for module, env in bot.factory.ns.items(): myglobals, mylocals = env commands += [(c.replace("command_", ""), ref) for c, ref in\ mylocals.items() if c.startswith("command_%s" % cmnd)] # Help for a specific command if len(cmnd): for cname, ref in commands: if cname == cmnd: helptext = ref.__doc__.split("\n", 1)[0] bot.say(channel, "Help for %s: %s" % (cmnd, helptext)) return # Generic help else: commandlist = ", ".join([c for c, ref in commands]) bot.say(channel, "Available commands: {}".format(commandlist))
[ "def", "command_help", "(", "bot", ",", "user", ",", "channel", ",", "cmnd", ")", ":", "# TODO: Only print commands that are available to the user.", "commands", "=", "[", "]", "for", "module", ",", "env", "in", "bot", ".", "factory", ".", "ns", ".", "items", "(", ")", ":", "myglobals", ",", "mylocals", "=", "env", "commands", "+=", "[", "(", "c", ".", "replace", "(", "\"command_\"", ",", "\"\"", ")", ",", "ref", ")", "for", "c", ",", "ref", "in", "mylocals", ".", "items", "(", ")", "if", "c", ".", "startswith", "(", "\"command_%s\"", "%", "cmnd", ")", "]", "# Help for a specific command", "if", "len", "(", "cmnd", ")", ":", "for", "cname", ",", "ref", "in", "commands", ":", "if", "cname", "==", "cmnd", ":", "helptext", "=", "ref", ".", "__doc__", ".", "split", "(", "\"\\n\"", ",", "1", ")", "[", "0", "]", "bot", ".", "say", "(", "channel", ",", "\"Help for %s: %s\"", "%", "(", "cmnd", ",", "helptext", ")", ")", "return", "# Generic help", "else", ":", "commandlist", "=", "\", \"", ".", "join", "(", "[", "c", "for", "c", ",", "ref", "in", "commands", "]", ")", "bot", ".", "say", "(", "channel", ",", "\"Available commands: {}\"", ".", "format", "(", "commandlist", ")", ")" ]
[ 341, 0 ]
[ 359, 70 ]
python
en
['en', 'en', 'en']
True
command_logs
(bot, user, channel, args)
Usage: logs [on|off|level].
Usage: logs [on|off|level].
def command_logs(bot, user, channel, args): "Usage: logs [on|off|level]." if permissions(user) < 20: return bot.say(channel, "{}, insufficient permissions.".format( get_nick(user))) if args == "off" and bot.factory.logs_enabled: bot.factory.logs_enabled = False bot.chatlogger.close_logs() log.info("Chatlogs enabled") return bot.say(channel, "Chatlogs are now disabled.") elif args == "on" and not bot.factory.logs_enabled: bot.factory.logs_enabled = True bot.chatlogger.open_logs(bot.factory.network["channels"]) log.info("Chatlogs disabled") return bot.say(channel, "Chatlogs are now enabled.") elif args == "level": level = logging.getLogger().getEffectiveLevel() levels = ["notset", "debug [-vvv]", "info [-vv]", "warn [-v]", "error, least verbose"] label = levels[level / 10] return bot.say(channel, "Log level is {} ({})." .format(level / 10, label)) elif args == "dir" or args == "logdir": return bot.say(channel, "{}".format(bot.factory.logdir)) else: if bot.factory.logs_enabled: return bot.say(channel, "Logs are enabled. Use {}logs off to disable." .format(bot.lead)) else: return bot.say(channel, "Logs are disabled. Use {}logs on to disable." .format(bot.lead))
[ "def", "command_logs", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "if", "permissions", "(", "user", ")", "<", "20", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")", "if", "args", "==", "\"off\"", "and", "bot", ".", "factory", ".", "logs_enabled", ":", "bot", ".", "factory", ".", "logs_enabled", "=", "False", "bot", ".", "chatlogger", ".", "close_logs", "(", ")", "log", ".", "info", "(", "\"Chatlogs enabled\"", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"Chatlogs are now disabled.\"", ")", "elif", "args", "==", "\"on\"", "and", "not", "bot", ".", "factory", ".", "logs_enabled", ":", "bot", ".", "factory", ".", "logs_enabled", "=", "True", "bot", ".", "chatlogger", ".", "open_logs", "(", "bot", ".", "factory", ".", "network", "[", "\"channels\"", "]", ")", "log", ".", "info", "(", "\"Chatlogs disabled\"", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"Chatlogs are now enabled.\"", ")", "elif", "args", "==", "\"level\"", ":", "level", "=", "logging", ".", "getLogger", "(", ")", ".", "getEffectiveLevel", "(", ")", "levels", "=", "[", "\"notset\"", ",", "\"debug [-vvv]\"", ",", "\"info [-vv]\"", ",", "\"warn [-v]\"", ",", "\"error, least verbose\"", "]", "label", "=", "levels", "[", "level", "/", "10", "]", "return", "bot", ".", "say", "(", "channel", ",", "\"Log level is {} ({}).\"", ".", "format", "(", "level", "/", "10", ",", "label", ")", ")", "elif", "args", "==", "\"dir\"", "or", "args", "==", "\"logdir\"", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"{}\"", ".", "format", "(", "bot", ".", "factory", ".", "logdir", ")", ")", "else", ":", "if", "bot", ".", "factory", ".", "logs_enabled", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Logs are enabled. Use {}logs off to disable.\"", ".", "format", "(", "bot", ".", "lead", ")", ")", "else", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Logs are disabled. Use {}logs on to disable.\"", ".", "format", "(", "bot", ".", "lead", ")", ")" ]
[ 362, 0 ]
[ 395, 34 ]
python
en
['en', 'en', 'en']
True
command_me
(bot, user, channel, args)
Displays information about the user.
Displays information about the user.
def command_me(bot, user, channel, args): "Displays information about the user." nick = get_nick(user) perms = permissions(user) return bot.say(channel, "{}, your permission level is {}.".format(nick, perms))
[ "def", "command_me", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "nick", "=", "get_nick", "(", "user", ")", "perms", "=", "permissions", "(", "user", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, your permission level is {}.\"", ".", "format", "(", "nick", ",", "perms", ")", ")" ]
[ 398, 0 ]
[ 403, 77 ]
python
en
['en', 'en', 'en']
True
command_version
(bot, user, channel, args)
Displays the current bot version.
Displays the current bot version.
def command_version(bot, user, channel, args): "Displays the current bot version." return bot.say(channel, "demibot v{} ({})".format(bot.factory.VERSION, bot.factory.URL))
[ "def", "command_version", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"demibot v{} ({})\"", ".", "format", "(", "bot", ".", "factory", ".", "VERSION", ",", "bot", ".", "factory", ".", "URL", ")", ")" ]
[ 406, 0 ]
[ 409, 71 ]
python
en
['en', 'en', 'en']
True
command_setvar
(bot, user, channel, args)
Change internal variables. Use with extreme caution. Can break the bot. Usage: setvar <var>.
Change internal variables. Use with extreme caution. Can break the bot. Usage: setvar <var>.
def command_setvar(bot, user, channel, args): """Change internal variables. Use with extreme caution. Can break the bot. Usage: setvar <var>.""" perms, nick = permissions(user), get_nick(user) if perms < 20: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format(nick)) f = bot.factory if not args: return bot.say(channel, "retry: {}, minperms: {}, lost_delay: {},"\ "failed_delay: {}, lineRate: {}".format( f.retry_enabled, f.minperms, f.lost_delay, f.failed_delay, bot.lineRate)) args = args.split() if args[0] == "retry": f.retry_enabled = not f.retry_enabled return bot.say(channel, "retry_enabled: {}".format(f.retry_enabled)) if args[0] == "titles" or args[0] == "url": f.urltitles_enabled = not f.urltitles_enabled return bot.say(channel, "urltitles_enabled: {}".format(f.urltitles_enabled)) elif args[0] == "minperms": f.minperms = int(args[1]) return bot.say(channel, "minperms: {}".format(f.minperms)) elif args[0] == "lost_delay": f.lost_delay = int(args[1]) return bot.say(channel, "lost_delay: {}".format(f.lost_delay)) elif args[0] == "failed_delay": f.failed_delay = int(args[1]) return bot.say(channel, "failed_delay: {}".format(f.failed_delay)) elif args[0] == "linerate": bot.lineRate = int(args[1]) return bot.say(channel, "lineRate: {}".format(bot.lineRate)) bot.lead = args log.info("Command identifier changed to {}".format(bot.lead)) return bot.say(channel, "Command identifier changed to: {}" .format(bot.lead))
[ "def", "command_setvar", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "perms", ",", "nick", "=", "permissions", "(", "user", ")", ",", "get_nick", "(", "user", ")", "if", "perms", "<", "20", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "nick", ")", ")", "f", "=", "bot", ".", "factory", "if", "not", "args", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"retry: {}, minperms: {}, lost_delay: {},\"", "\"failed_delay: {}, lineRate: {}\"", ".", "format", "(", "f", ".", "retry_enabled", ",", "f", ".", "minperms", ",", "f", ".", "lost_delay", ",", "f", ".", "failed_delay", ",", "bot", ".", "lineRate", ")", ")", "args", "=", "args", ".", "split", "(", ")", "if", "args", "[", "0", "]", "==", "\"retry\"", ":", "f", ".", "retry_enabled", "=", "not", "f", ".", "retry_enabled", "return", "bot", ".", "say", "(", "channel", ",", "\"retry_enabled: {}\"", ".", "format", "(", "f", ".", "retry_enabled", ")", ")", "if", "args", "[", "0", "]", "==", "\"titles\"", "or", "args", "[", "0", "]", "==", "\"url\"", ":", "f", ".", "urltitles_enabled", "=", "not", "f", ".", "urltitles_enabled", "return", "bot", ".", "say", "(", "channel", ",", "\"urltitles_enabled: {}\"", ".", "format", "(", "f", ".", "urltitles_enabled", ")", ")", "elif", "args", "[", "0", "]", "==", "\"minperms\"", ":", "f", ".", "minperms", "=", "int", "(", "args", "[", "1", "]", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"minperms: {}\"", ".", "format", "(", "f", ".", "minperms", ")", ")", "elif", "args", "[", "0", "]", "==", "\"lost_delay\"", ":", "f", ".", "lost_delay", "=", "int", "(", "args", "[", "1", "]", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"lost_delay: {}\"", ".", "format", "(", "f", ".", "lost_delay", ")", ")", "elif", "args", "[", "0", "]", "==", "\"failed_delay\"", ":", "f", ".", "failed_delay", "=", "int", "(", "args", "[", "1", "]", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"failed_delay: {}\"", ".", "format", "(", "f", ".", "failed_delay", ")", ")", "elif", "args", "[", "0", "]", "==", "\"linerate\"", ":", "bot", ".", "lineRate", "=", "int", "(", "args", "[", "1", "]", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"lineRate: {}\"", ".", "format", "(", "bot", ".", "lineRate", ")", ")", "bot", ".", "lead", "=", "args", "log", ".", "info", "(", "\"Command identifier changed to {}\"", ".", "format", "(", "bot", ".", "lead", ")", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"Command identifier changed to: {}\"", ".", "format", "(", "bot", ".", "lead", ")", ")" ]
[ 412, 0 ]
[ 449, 37 ]
python
en
['en', 'en', 'en']
True
command_printvars
(bot, user, channel, args)
Prints out crucial variables. Usage: printvars [<var>].
Prints out crucial variables. Usage: printvars [<var>].
def command_printvars(bot, user, channel, args): "Prints out crucial variables. Usage: printvars [<var>]." f = bot.factory perms, nick = permissions(user), get_nick(user) if perms < 20: # 0 public, 1-9 undefined, 10-19 admin, 20 root return bot.say(channel, "{}, insufficient permissions.".format(nick)) if not args: bot.say(channel, "logs_enabled: {}, retry_enabled: {},"\ " urltitles_enabled: {}, minperms: {}, lost_delay: {},"\ " failed_delay: {}".format(f.logs_enabled, f.retry_enabled, f.urltitles_enabled, f.minperms, f.lost_delay, f.failed_delay)) bot.say(channel, "logdir: {}, configdir: {}, moduledir: {}" .format(f.logdir, f.configdir, f.moduledir)) return bot.say(channel, "realname: {}, username: {}, password: {}, "\ "userinfo: {}, hostname: {}, lineRate: {}, lead: {}" .format(bot.realname, bot.username, bot.password, bot.userinfo, bot.hostname, bot.lineRate, bot.lead)) elif args == "client": return bot.say(channel, "realname: {}, username: {}, password: {}, "\ "userinfo: {}, hostname: {}, lineRate: {}, lead: {}" .format(bot.realname, bot.username, bot.password, bot.userinfo, bot.hostname, bot.lineRate, bot.lead)) elif args == "dirs": return bot.say(channel, "logdir: {}, configdir: {}, moduledir: {}" .format(f.logdir, f.configdir, f.moduledir)) elif args == "factory": return bot.say(channel, "logs_enabled: {}, retry_enabled: {},"\ " urltitles_enabled: {}, minperms: {}, lost_delay: {},"\ " failed_delay: {}".format(f.logs_enabled, f.retry_enabled, f.urltitles_enabled, f.minperms, f.lost_delay, f.failed_delay))
[ "def", "command_printvars", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "f", "=", "bot", ".", "factory", "perms", ",", "nick", "=", "permissions", "(", "user", ")", ",", "get_nick", "(", "user", ")", "if", "perms", "<", "20", ":", "# 0 public, 1-9 undefined, 10-19 admin, 20 root", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, insufficient permissions.\"", ".", "format", "(", "nick", ")", ")", "if", "not", "args", ":", "bot", ".", "say", "(", "channel", ",", "\"logs_enabled: {}, retry_enabled: {},\"", "\" urltitles_enabled: {}, minperms: {}, lost_delay: {},\"", "\" failed_delay: {}\"", ".", "format", "(", "f", ".", "logs_enabled", ",", "f", ".", "retry_enabled", ",", "f", ".", "urltitles_enabled", ",", "f", ".", "minperms", ",", "f", ".", "lost_delay", ",", "f", ".", "failed_delay", ")", ")", "bot", ".", "say", "(", "channel", ",", "\"logdir: {}, configdir: {}, moduledir: {}\"", ".", "format", "(", "f", ".", "logdir", ",", "f", ".", "configdir", ",", "f", ".", "moduledir", ")", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"realname: {}, username: {}, password: {}, \"", "\"userinfo: {}, hostname: {}, lineRate: {}, lead: {}\"", ".", "format", "(", "bot", ".", "realname", ",", "bot", ".", "username", ",", "bot", ".", "password", ",", "bot", ".", "userinfo", ",", "bot", ".", "hostname", ",", "bot", ".", "lineRate", ",", "bot", ".", "lead", ")", ")", "elif", "args", "==", "\"client\"", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"realname: {}, username: {}, password: {}, \"", "\"userinfo: {}, hostname: {}, lineRate: {}, lead: {}\"", ".", "format", "(", "bot", ".", "realname", ",", "bot", ".", "username", ",", "bot", ".", "password", ",", "bot", ".", "userinfo", ",", "bot", ".", "hostname", ",", "bot", ".", "lineRate", ",", "bot", ".", "lead", ")", ")", "elif", "args", "==", "\"dirs\"", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"logdir: {}, configdir: {}, moduledir: {}\"", ".", "format", "(", "f", ".", "logdir", ",", "f", ".", "configdir", ",", "f", ".", "moduledir", ")", ")", "elif", "args", "==", "\"factory\"", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"logs_enabled: {}, retry_enabled: {},\"", "\" urltitles_enabled: {}, minperms: {}, lost_delay: {},\"", "\" failed_delay: {}\"", ".", "format", "(", "f", ".", "logs_enabled", ",", "f", ".", "retry_enabled", ",", "f", ".", "urltitles_enabled", ",", "f", ".", "minperms", ",", "f", ".", "lost_delay", ",", "f", ".", "failed_delay", ")", ")" ]
[ 452, 0 ]
[ 486, 80 ]
python
en
['en', 'af', 'en']
True
command_ping
(bot, user, channel, args)
Dummy command. Try it!
Dummy command. Try it!
def command_ping(bot, user, channel, args): "Dummy command. Try it!" return bot.say(channel, "{}, Pong.".format(get_nick(user)))
[ "def", "command_ping", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, Pong.\"", ".", "format", "(", "get_nick", "(", "user", ")", ")", ")" ]
[ 489, 0 ]
[ 491, 63 ]
python
en
['en', 'en', 'en']
True
process_row
(bq_row)
Convert bq_row into dictionary and replace identifiers to nominal values Args: bq_row: BigQuery row Returns: dictionary
Convert bq_row into dictionary and replace identifiers to nominal values
def process_row(bq_row): """ Convert bq_row into dictionary and replace identifiers to nominal values Args: bq_row: BigQuery row Returns: dictionary """ # modify opaque numeric race code into human-readable data races = dict(zip([1, 2, 3, 4, 5, 6, 7, 18, 28, 39, 48], ['White', 'Black', 'American Indian', 'Chinese', 'Japanese', 'Hawaiian', 'Filipino', 'Asian bq_row', 'Korean', 'Samaon', 'Vietnamese'])) instance = dict() instance['is_male'] = str(bq_row['is_male']) instance['mother_age'] = bq_row['mother_age'] if 'mother_race' in bq_row and bq_row['mother_race'] in races: instance['mother_race'] = races[bq_row['mother_race']] else: instance['mother_race'] = 'Unknown' instance['plurality'] = bq_row['plurality'] instance['gestation_weeks'] = bq_row['gestation_weeks'] instance['mother_married'] = str(bq_row['mother_married']) instance['cigarette_use'] = str(bq_row['cigarette_use']) instance['alcohol_use'] = str(bq_row['alcohol_use']) instance['weight_pounds'] = str(bq_row['weight_pounds']) return instance
[ "def", "process_row", "(", "bq_row", ")", ":", "# modify opaque numeric race code into human-readable data", "races", "=", "dict", "(", "zip", "(", "[", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "6", ",", "7", ",", "18", ",", "28", ",", "39", ",", "48", "]", ",", "[", "'White'", ",", "'Black'", ",", "'American Indian'", ",", "'Chinese'", ",", "'Japanese'", ",", "'Hawaiian'", ",", "'Filipino'", ",", "'Asian bq_row'", ",", "'Korean'", ",", "'Samaon'", ",", "'Vietnamese'", "]", ")", ")", "instance", "=", "dict", "(", ")", "instance", "[", "'is_male'", "]", "=", "str", "(", "bq_row", "[", "'is_male'", "]", ")", "instance", "[", "'mother_age'", "]", "=", "bq_row", "[", "'mother_age'", "]", "if", "'mother_race'", "in", "bq_row", "and", "bq_row", "[", "'mother_race'", "]", "in", "races", ":", "instance", "[", "'mother_race'", "]", "=", "races", "[", "bq_row", "[", "'mother_race'", "]", "]", "else", ":", "instance", "[", "'mother_race'", "]", "=", "'Unknown'", "instance", "[", "'plurality'", "]", "=", "bq_row", "[", "'plurality'", "]", "instance", "[", "'gestation_weeks'", "]", "=", "bq_row", "[", "'gestation_weeks'", "]", "instance", "[", "'mother_married'", "]", "=", "str", "(", "bq_row", "[", "'mother_married'", "]", ")", "instance", "[", "'cigarette_use'", "]", "=", "str", "(", "bq_row", "[", "'cigarette_use'", "]", ")", "instance", "[", "'alcohol_use'", "]", "=", "str", "(", "bq_row", "[", "'alcohol_use'", "]", ")", "instance", "[", "'weight_pounds'", "]", "=", "str", "(", "bq_row", "[", "'weight_pounds'", "]", ")", "return", "instance" ]
[ 51, 0 ]
[ 85, 19 ]
python
en
['en', 'error', 'th']
False
to_json_line
(bq_row)
Convert bq_row into json and replace identifiers to nominal values Args: bq_row: BigQuery row Returns: dictionary
Convert bq_row into json and replace identifiers to nominal values
def to_json_line(bq_row): """ Convert bq_row into json and replace identifiers to nominal values Args: bq_row: BigQuery row Returns: dictionary """ # modify opaque numeric race code into human-readable data races = dict(zip([1, 2, 3, 4, 5, 6, 7, 18, 28, 39, 48], ['White', 'Black', 'American Indian', 'Chinese', 'Japanese', 'Hawaiian', 'Filipino', 'Asian bq_row', 'Korean', 'Samaon', 'Vietnamese'])) instance = dict() instance['is_male'] = str(bq_row['is_male']) instance['mother_age'] = bq_row['mother_age'] if 'mother_race' in bq_row and bq_row['mother_race'] in races: instance['mother_race'] = races[bq_row['mother_race']] else: instance['mother_race'] = 'Unknown' instance['plurality'] = bq_row['plurality'] instance['gestation_weeks'] = bq_row['gestation_weeks'] instance['mother_married'] = str(bq_row['mother_married']) instance['cigarette_use'] = str(bq_row['cigarette_use']) instance['alcohol_use'] = str(bq_row['alcohol_use']) return json.dumps(instance)
[ "def", "to_json_line", "(", "bq_row", ")", ":", "# modify opaque numeric race code into human-readable data", "races", "=", "dict", "(", "zip", "(", "[", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "6", ",", "7", ",", "18", ",", "28", ",", "39", ",", "48", "]", ",", "[", "'White'", ",", "'Black'", ",", "'American Indian'", ",", "'Chinese'", ",", "'Japanese'", ",", "'Hawaiian'", ",", "'Filipino'", ",", "'Asian bq_row'", ",", "'Korean'", ",", "'Samaon'", ",", "'Vietnamese'", "]", ")", ")", "instance", "=", "dict", "(", ")", "instance", "[", "'is_male'", "]", "=", "str", "(", "bq_row", "[", "'is_male'", "]", ")", "instance", "[", "'mother_age'", "]", "=", "bq_row", "[", "'mother_age'", "]", "if", "'mother_race'", "in", "bq_row", "and", "bq_row", "[", "'mother_race'", "]", "in", "races", ":", "instance", "[", "'mother_race'", "]", "=", "races", "[", "bq_row", "[", "'mother_race'", "]", "]", "else", ":", "instance", "[", "'mother_race'", "]", "=", "'Unknown'", "instance", "[", "'plurality'", "]", "=", "bq_row", "[", "'plurality'", "]", "instance", "[", "'gestation_weeks'", "]", "=", "bq_row", "[", "'gestation_weeks'", "]", "instance", "[", "'mother_married'", "]", "=", "str", "(", "bq_row", "[", "'mother_married'", "]", ")", "instance", "[", "'cigarette_use'", "]", "=", "str", "(", "bq_row", "[", "'cigarette_use'", "]", ")", "instance", "[", "'alcohol_use'", "]", "=", "str", "(", "bq_row", "[", "'alcohol_use'", "]", ")", "return", "json", ".", "dumps", "(", "instance", ")" ]
[ 88, 0 ]
[ 121, 31 ]
python
en
['en', 'error', 'th']
False
estimate
(instance, inference_type)
Estimate the baby weight given an instance If inference type is 'cmle', the model API deployed on Coud ML Engine is called, otherwise, the local model is called Agrs: instance: dictionary of values representing the input features of the instance inference_type: cane be 'local or 'cmle' Returns: int - baby weight estimate from the model
Estimate the baby weight given an instance If inference type is 'cmle', the model API deployed on Coud ML Engine is called, otherwise, the local model is called
def estimate(instance, inference_type): """ Estimate the baby weight given an instance If inference type is 'cmle', the model API deployed on Coud ML Engine is called, otherwise, the local model is called Agrs: instance: dictionary of values representing the input features of the instance inference_type: cane be 'local or 'cmle' Returns: int - baby weight estimate from the model """ # pop the actual weight if exists weight_pounds = instance.pop('weight_pounds', 'NA') if inference_type == 'local': estimated_weights = inference.estimate_local([instance]) elif inference_type == 'cmle': estimated_weights = inference.estimate_cmle([instance]) else: estimated_weights = 'NA' instance['estimated_weight'] = estimated_weights[0] instance['weight_pounds'] = weight_pounds[0] return instance
[ "def", "estimate", "(", "instance", ",", "inference_type", ")", ":", "# pop the actual weight if exists", "weight_pounds", "=", "instance", ".", "pop", "(", "'weight_pounds'", ",", "'NA'", ")", "if", "inference_type", "==", "'local'", ":", "estimated_weights", "=", "inference", ".", "estimate_local", "(", "[", "instance", "]", ")", "elif", "inference_type", "==", "'cmle'", ":", "estimated_weights", "=", "inference", ".", "estimate_cmle", "(", "[", "instance", "]", ")", "else", ":", "estimated_weights", "=", "'NA'", "instance", "[", "'estimated_weight'", "]", "=", "estimated_weights", "[", "0", "]", "instance", "[", "'weight_pounds'", "]", "=", "weight_pounds", "[", "0", "]", "return", "instance" ]
[ 124, 0 ]
[ 150, 19 ]
python
en
['en', 'error', 'th']
False
to_csv
(instance)
Convert the instance, including the estimated baby weight, to csv string Args: instance: dictionary of instance feature values and estimated target Returns: string: comma separated values
Convert the instance, including the estimated baby weight, to csv string
def to_csv(instance): """ Convert the instance, including the estimated baby weight, to csv string Args: instance: dictionary of instance feature values and estimated target Returns: string: comma separated values """ csv_row = ','.join([str(instance[k]) for k in HEADER]) csv_row += ',{}'.format(instance['estimated_weight']) return csv_row
[ "def", "to_csv", "(", "instance", ")", ":", "csv_row", "=", "','", ".", "join", "(", "[", "str", "(", "instance", "[", "k", "]", ")", "for", "k", "in", "HEADER", "]", ")", "csv_row", "+=", "',{}'", ".", "format", "(", "instance", "[", "'estimated_weight'", "]", ")", "return", "csv_row" ]
[ 153, 0 ]
[ 165, 18 ]
python
en
['en', 'error', 'th']
False
path_to_url
(path)
Convert a path to a file: URL. The path will be made absolute and have quoted path parts.
Convert a path to a file: URL. The path will be made absolute and have quoted path parts.
def path_to_url(path): # type: (str) -> str """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) url = urllib.parse.urljoin("file:", urllib.request.pathname2url(path)) return url
[ "def", "path_to_url", "(", "path", ")", ":", "# type: (str) -> str", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", "url", "=", "urllib", ".", "parse", ".", "urljoin", "(", "\"file:\"", ",", "urllib", ".", "request", ".", "pathname2url", "(", "path", ")", ")", "return", "url" ]
[ 16, 0 ]
[ 24, 14 ]
python
en
['en', 'error', 'th']
False
url_to_path
(url)
Convert a file: URL to a path.
Convert a file: URL to a path.
def url_to_path(url): # type: (str) -> str """ Convert a file: URL to a path. """ assert url.startswith( "file:" ), f"You can only turn file: urls into filenames (not {url!r})" _, netloc, path, _, _ = urllib.parse.urlsplit(url) if not netloc or netloc == "localhost": # According to RFC 8089, same as empty authority. netloc = "" elif WINDOWS: # If we have a UNC path, prepend UNC share notation. netloc = "\\\\" + netloc else: raise ValueError( f"non-local file URIs are not supported on this platform: {url!r}" ) path = urllib.request.url2pathname(netloc + path) # On Windows, urlsplit parses the path as something like "/C:/Users/foo". # This creates issues for path-related functions like io.open(), so we try # to detect and strip the leading slash. if ( WINDOWS and not netloc # Not UNC. and len(path) >= 3 and path[0] == "/" # Leading slash to strip. and path[1] in string.ascii_letters # Drive letter. and path[2:4] in (":", ":/") # Colon + end of string, or colon + absolute path. ): path = path[1:] return path
[ "def", "url_to_path", "(", "url", ")", ":", "# type: (str) -> str", "assert", "url", ".", "startswith", "(", "\"file:\"", ")", ",", "f\"You can only turn file: urls into filenames (not {url!r})\"", "_", ",", "netloc", ",", "path", ",", "_", ",", "_", "=", "urllib", ".", "parse", ".", "urlsplit", "(", "url", ")", "if", "not", "netloc", "or", "netloc", "==", "\"localhost\"", ":", "# According to RFC 8089, same as empty authority.", "netloc", "=", "\"\"", "elif", "WINDOWS", ":", "# If we have a UNC path, prepend UNC share notation.", "netloc", "=", "\"\\\\\\\\\"", "+", "netloc", "else", ":", "raise", "ValueError", "(", "f\"non-local file URIs are not supported on this platform: {url!r}\"", ")", "path", "=", "urllib", ".", "request", ".", "url2pathname", "(", "netloc", "+", "path", ")", "# On Windows, urlsplit parses the path as something like \"/C:/Users/foo\".", "# This creates issues for path-related functions like io.open(), so we try", "# to detect and strip the leading slash.", "if", "(", "WINDOWS", "and", "not", "netloc", "# Not UNC.", "and", "len", "(", "path", ")", ">=", "3", "and", "path", "[", "0", "]", "==", "\"/\"", "# Leading slash to strip.", "and", "path", "[", "1", "]", "in", "string", ".", "ascii_letters", "# Drive letter.", "and", "path", "[", "2", ":", "4", "]", "in", "(", "\":\"", ",", "\":/\"", ")", "# Colon + end of string, or colon + absolute path.", ")", ":", "path", "=", "path", "[", "1", ":", "]", "return", "path" ]
[ 27, 0 ]
[ 64, 15 ]
python
en
['en', 'error', 'th']
False
CartServiceStub.__init__
(self, channel)
Constructor. Args: channel: A grpc.Channel.
Constructor.
def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.AddItem = channel.unary_unary( '/hipstershop.CartService/AddItem', request_serializer=demo__pb2.AddItemRequest.SerializeToString, response_deserializer=demo__pb2.Empty.FromString, ) self.GetCart = channel.unary_unary( '/hipstershop.CartService/GetCart', request_serializer=demo__pb2.GetCartRequest.SerializeToString, response_deserializer=demo__pb2.Cart.FromString, ) self.EmptyCart = channel.unary_unary( '/hipstershop.CartService/EmptyCart', request_serializer=demo__pb2.EmptyCartRequest.SerializeToString, response_deserializer=demo__pb2.Empty.FromString, )
[ "def", "__init__", "(", "self", ",", "channel", ")", ":", "self", ".", "AddItem", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.CartService/AddItem'", ",", "request_serializer", "=", "demo__pb2", ".", "AddItemRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "Empty", ".", "FromString", ",", ")", "self", ".", "GetCart", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.CartService/GetCart'", ",", "request_serializer", "=", "demo__pb2", ".", "GetCartRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "Cart", ".", "FromString", ",", ")", "self", ".", "EmptyCart", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.CartService/EmptyCart'", ",", "request_serializer", "=", "demo__pb2", ".", "EmptyCartRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "Empty", ".", "FromString", ",", ")" ]
[ 27, 2 ]
[ 47, 9 ]
python
en
['en', 'en', 'en']
False
RecommendationServiceStub.__init__
(self, channel)
Constructor. Args: channel: A grpc.Channel.
Constructor.
def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.ListRecommendations = channel.unary_unary( '/hipstershop.RecommendationService/ListRecommendations', request_serializer=demo__pb2.ListRecommendationsRequest.SerializeToString, response_deserializer=demo__pb2.ListRecommendationsResponse.FromString, )
[ "def", "__init__", "(", "self", ",", "channel", ")", ":", "self", ".", "ListRecommendations", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.RecommendationService/ListRecommendations'", ",", "request_serializer", "=", "demo__pb2", ".", "ListRecommendationsRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "ListRecommendationsResponse", ".", "FromString", ",", ")" ]
[ 105, 2 ]
[ 115, 9 ]
python
en
['en', 'en', 'en']
False
ProductCatalogServiceStub.__init__
(self, channel)
Constructor. Args: channel: A grpc.Channel.
Constructor.
def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.ListProducts = channel.unary_unary( '/hipstershop.ProductCatalogService/ListProducts', request_serializer=demo__pb2.Empty.SerializeToString, response_deserializer=demo__pb2.ListProductsResponse.FromString, ) self.GetProduct = channel.unary_unary( '/hipstershop.ProductCatalogService/GetProduct', request_serializer=demo__pb2.GetProductRequest.SerializeToString, response_deserializer=demo__pb2.Product.FromString, ) self.SearchProducts = channel.unary_unary( '/hipstershop.ProductCatalogService/SearchProducts', request_serializer=demo__pb2.SearchProductsRequest.SerializeToString, response_deserializer=demo__pb2.SearchProductsResponse.FromString, )
[ "def", "__init__", "(", "self", ",", "channel", ")", ":", "self", ".", "ListProducts", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.ProductCatalogService/ListProducts'", ",", "request_serializer", "=", "demo__pb2", ".", "Empty", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "ListProductsResponse", ".", "FromString", ",", ")", "self", ".", "GetProduct", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.ProductCatalogService/GetProduct'", ",", "request_serializer", "=", "demo__pb2", ".", "GetProductRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "Product", ".", "FromString", ",", ")", "self", ".", "SearchProducts", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.ProductCatalogService/SearchProducts'", ",", "request_serializer", "=", "demo__pb2", ".", "SearchProductsRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "SearchProductsResponse", ".", "FromString", ",", ")" ]
[ 149, 2 ]
[ 169, 9 ]
python
en
['en', 'en', 'en']
False
ShippingServiceStub.__init__
(self, channel)
Constructor. Args: channel: A grpc.Channel.
Constructor.
def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GetQuote = channel.unary_unary( '/hipstershop.ShippingService/GetQuote', request_serializer=demo__pb2.GetQuoteRequest.SerializeToString, response_deserializer=demo__pb2.GetQuoteResponse.FromString, ) self.ShipOrder = channel.unary_unary( '/hipstershop.ShippingService/ShipOrder', request_serializer=demo__pb2.ShipOrderRequest.SerializeToString, response_deserializer=demo__pb2.ShipOrderResponse.FromString, )
[ "def", "__init__", "(", "self", ",", "channel", ")", ":", "self", ".", "GetQuote", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.ShippingService/GetQuote'", ",", "request_serializer", "=", "demo__pb2", ".", "GetQuoteRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "GetQuoteResponse", ".", "FromString", ",", ")", "self", ".", "ShipOrder", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.ShippingService/ShipOrder'", ",", "request_serializer", "=", "demo__pb2", ".", "ShipOrderRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "ShipOrderResponse", ".", "FromString", ",", ")" ]
[ 227, 2 ]
[ 242, 9 ]
python
en
['en', 'en', 'en']
False
CurrencyServiceStub.__init__
(self, channel)
Constructor. Args: channel: A grpc.Channel.
Constructor.
def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GetSupportedCurrencies = channel.unary_unary( '/hipstershop.CurrencyService/GetSupportedCurrencies', request_serializer=demo__pb2.Empty.SerializeToString, response_deserializer=demo__pb2.GetSupportedCurrenciesResponse.FromString, ) self.Convert = channel.unary_unary( '/hipstershop.CurrencyService/Convert', request_serializer=demo__pb2.CurrencyConversionRequest.SerializeToString, response_deserializer=demo__pb2.Money.FromString, )
[ "def", "__init__", "(", "self", ",", "channel", ")", ":", "self", ".", "GetSupportedCurrencies", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.CurrencyService/GetSupportedCurrencies'", ",", "request_serializer", "=", "demo__pb2", ".", "Empty", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "GetSupportedCurrenciesResponse", ".", "FromString", ",", ")", "self", ".", "Convert", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.CurrencyService/Convert'", ",", "request_serializer", "=", "demo__pb2", ".", "CurrencyConversionRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "Money", ".", "FromString", ",", ")" ]
[ 288, 2 ]
[ 303, 9 ]
python
en
['en', 'en', 'en']
False
PaymentServiceStub.__init__
(self, channel)
Constructor. Args: channel: A grpc.Channel.
Constructor.
def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.Charge = channel.unary_unary( '/hipstershop.PaymentService/Charge', request_serializer=demo__pb2.ChargeRequest.SerializeToString, response_deserializer=demo__pb2.ChargeResponse.FromString, )
[ "def", "__init__", "(", "self", ",", "channel", ")", ":", "self", ".", "Charge", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.PaymentService/Charge'", ",", "request_serializer", "=", "demo__pb2", ".", "ChargeRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "ChargeResponse", ".", "FromString", ",", ")" ]
[ 349, 2 ]
[ 359, 9 ]
python
en
['en', 'en', 'en']
False
EmailServiceStub.__init__
(self, channel)
Constructor. Args: channel: A grpc.Channel.
Constructor.
def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SendOrderConfirmation = channel.unary_unary( '/hipstershop.EmailService/SendOrderConfirmation', request_serializer=demo__pb2.SendOrderConfirmationRequest.SerializeToString, response_deserializer=demo__pb2.Empty.FromString, )
[ "def", "__init__", "(", "self", ",", "channel", ")", ":", "self", ".", "SendOrderConfirmation", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.EmailService/SendOrderConfirmation'", ",", "request_serializer", "=", "demo__pb2", ".", "SendOrderConfirmationRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "Empty", ".", "FromString", ",", ")" ]
[ 393, 2 ]
[ 403, 9 ]
python
en
['en', 'en', 'en']
False
CheckoutServiceStub.__init__
(self, channel)
Constructor. Args: channel: A grpc.Channel.
Constructor.
def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.CreateOrder = channel.unary_unary( '/hipstershop.CheckoutService/CreateOrder', request_serializer=demo__pb2.CreateOrderRequest.SerializeToString, response_deserializer=demo__pb2.CreateOrderResponse.FromString, ) self.PlaceOrder = channel.unary_unary( '/hipstershop.CheckoutService/PlaceOrder', request_serializer=demo__pb2.PlaceOrderRequest.SerializeToString, response_deserializer=demo__pb2.PlaceOrderResponse.FromString, )
[ "def", "__init__", "(", "self", ",", "channel", ")", ":", "self", ".", "CreateOrder", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.CheckoutService/CreateOrder'", ",", "request_serializer", "=", "demo__pb2", ".", "CreateOrderRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "CreateOrderResponse", ".", "FromString", ",", ")", "self", ".", "PlaceOrder", "=", "channel", ".", "unary_unary", "(", "'/hipstershop.CheckoutService/PlaceOrder'", ",", "request_serializer", "=", "demo__pb2", ".", "PlaceOrderRequest", ".", "SerializeToString", ",", "response_deserializer", "=", "demo__pb2", ".", "PlaceOrderResponse", ".", "FromString", ",", ")" ]
[ 437, 2 ]
[ 452, 9 ]
python
en
['en', 'en', 'en']
False
decode_dxt1
(data, alpha=False)
input: one "row" of data (i.e. will produce 4*width pixels)
input: one "row" of data (i.e. will produce 4*width pixels)
def decode_dxt1(data, alpha=False): """ input: one "row" of data (i.e. will produce 4*width pixels) """ blocks = len(data) // 8 # number of blocks in row ret = (bytearray(), bytearray(), bytearray(), bytearray()) for block in range(blocks): # Decode next 8-byte block. idx = block * 8 color0, color1, bits = struct.unpack_from("<HHI", data, idx) r0, g0, b0 = unpack_565(color0) r1, g1, b1 = unpack_565(color1) # Decode this block into 4x4 pixels # Accumulate the results onto our 4 row accumulators for j in range(4): for i in range(4): # get next control op and generate a pixel control = bits & 3 bits = bits >> 2 a = 0xFF if control == 0: r, g, b = r0, g0, b0 elif control == 1: r, g, b = r1, g1, b1 elif control == 2: if color0 > color1: r = (2 * r0 + r1) // 3 g = (2 * g0 + g1) // 3 b = (2 * b0 + b1) // 3 else: r = (r0 + r1) // 2 g = (g0 + g1) // 2 b = (b0 + b1) // 2 elif control == 3: if color0 > color1: r = (2 * r1 + r0) // 3 g = (2 * g1 + g0) // 3 b = (2 * b1 + b0) // 3 else: r, g, b, a = 0, 0, 0, 0 if alpha: ret[j].extend([r, g, b, a]) else: ret[j].extend([r, g, b]) return ret
[ "def", "decode_dxt1", "(", "data", ",", "alpha", "=", "False", ")", ":", "blocks", "=", "len", "(", "data", ")", "//", "8", "# number of blocks in row", "ret", "=", "(", "bytearray", "(", ")", ",", "bytearray", "(", ")", ",", "bytearray", "(", ")", ",", "bytearray", "(", ")", ")", "for", "block", "in", "range", "(", "blocks", ")", ":", "# Decode next 8-byte block.", "idx", "=", "block", "*", "8", "color0", ",", "color1", ",", "bits", "=", "struct", ".", "unpack_from", "(", "\"<HHI\"", ",", "data", ",", "idx", ")", "r0", ",", "g0", ",", "b0", "=", "unpack_565", "(", "color0", ")", "r1", ",", "g1", ",", "b1", "=", "unpack_565", "(", "color1", ")", "# Decode this block into 4x4 pixels", "# Accumulate the results onto our 4 row accumulators", "for", "j", "in", "range", "(", "4", ")", ":", "for", "i", "in", "range", "(", "4", ")", ":", "# get next control op and generate a pixel", "control", "=", "bits", "&", "3", "bits", "=", "bits", ">>", "2", "a", "=", "0xFF", "if", "control", "==", "0", ":", "r", ",", "g", ",", "b", "=", "r0", ",", "g0", ",", "b0", "elif", "control", "==", "1", ":", "r", ",", "g", ",", "b", "=", "r1", ",", "g1", ",", "b1", "elif", "control", "==", "2", ":", "if", "color0", ">", "color1", ":", "r", "=", "(", "2", "*", "r0", "+", "r1", ")", "//", "3", "g", "=", "(", "2", "*", "g0", "+", "g1", ")", "//", "3", "b", "=", "(", "2", "*", "b0", "+", "b1", ")", "//", "3", "else", ":", "r", "=", "(", "r0", "+", "r1", ")", "//", "2", "g", "=", "(", "g0", "+", "g1", ")", "//", "2", "b", "=", "(", "b0", "+", "b1", ")", "//", "2", "elif", "control", "==", "3", ":", "if", "color0", ">", "color1", ":", "r", "=", "(", "2", "*", "r1", "+", "r0", ")", "//", "3", "g", "=", "(", "2", "*", "g1", "+", "g0", ")", "//", "3", "b", "=", "(", "2", "*", "b1", "+", "b0", ")", "//", "3", "else", ":", "r", ",", "g", ",", "b", ",", "a", "=", "0", ",", "0", ",", "0", ",", "0", "if", "alpha", ":", "ret", "[", "j", "]", ".", "extend", "(", "[", "r", ",", "g", ",", "b", ",", "a", "]", ")", "else", ":", "ret", "[", "j", "]", ".", "extend", "(", "[", "r", ",", "g", ",", "b", "]", ")", "return", "ret" ]
[ 51, 0 ]
[ 103, 14 ]
python
en
['en', 'error', 'th']
False
decode_dxt3
(data)
input: one "row" of data (i.e. will produce 4*width pixels)
input: one "row" of data (i.e. will produce 4*width pixels)
def decode_dxt3(data): """ input: one "row" of data (i.e. will produce 4*width pixels) """ blocks = len(data) // 16 # number of blocks in row ret = (bytearray(), bytearray(), bytearray(), bytearray()) for block in range(blocks): idx = block * 16 block = data[idx : idx + 16] # Decode next 16-byte block. bits = struct.unpack_from("<8B", block) color0, color1 = struct.unpack_from("<HH", block, 8) (code,) = struct.unpack_from("<I", block, 12) r0, g0, b0 = unpack_565(color0) r1, g1, b1 = unpack_565(color1) for j in range(4): high = False # Do we want the higher bits? for i in range(4): alphacode_index = (4 * j + i) // 2 a = bits[alphacode_index] if high: high = False a >>= 4 else: high = True a &= 0xF a *= 17 # We get a value between 0 and 15 color_code = (code >> 2 * (4 * j + i)) & 0x03 if color_code == 0: r, g, b = r0, g0, b0 elif color_code == 1: r, g, b = r1, g1, b1 elif color_code == 2: r = (2 * r0 + r1) // 3 g = (2 * g0 + g1) // 3 b = (2 * b0 + b1) // 3 elif color_code == 3: r = (2 * r1 + r0) // 3 g = (2 * g1 + g0) // 3 b = (2 * b1 + b0) // 3 ret[j].extend([r, g, b, a]) return ret
[ "def", "decode_dxt3", "(", "data", ")", ":", "blocks", "=", "len", "(", "data", ")", "//", "16", "# number of blocks in row", "ret", "=", "(", "bytearray", "(", ")", ",", "bytearray", "(", ")", ",", "bytearray", "(", ")", ",", "bytearray", "(", ")", ")", "for", "block", "in", "range", "(", "blocks", ")", ":", "idx", "=", "block", "*", "16", "block", "=", "data", "[", "idx", ":", "idx", "+", "16", "]", "# Decode next 16-byte block.", "bits", "=", "struct", ".", "unpack_from", "(", "\"<8B\"", ",", "block", ")", "color0", ",", "color1", "=", "struct", ".", "unpack_from", "(", "\"<HH\"", ",", "block", ",", "8", ")", "(", "code", ",", ")", "=", "struct", ".", "unpack_from", "(", "\"<I\"", ",", "block", ",", "12", ")", "r0", ",", "g0", ",", "b0", "=", "unpack_565", "(", "color0", ")", "r1", ",", "g1", ",", "b1", "=", "unpack_565", "(", "color1", ")", "for", "j", "in", "range", "(", "4", ")", ":", "high", "=", "False", "# Do we want the higher bits?", "for", "i", "in", "range", "(", "4", ")", ":", "alphacode_index", "=", "(", "4", "*", "j", "+", "i", ")", "//", "2", "a", "=", "bits", "[", "alphacode_index", "]", "if", "high", ":", "high", "=", "False", "a", ">>=", "4", "else", ":", "high", "=", "True", "a", "&=", "0xF", "a", "*=", "17", "# We get a value between 0 and 15", "color_code", "=", "(", "code", ">>", "2", "*", "(", "4", "*", "j", "+", "i", ")", ")", "&", "0x03", "if", "color_code", "==", "0", ":", "r", ",", "g", ",", "b", "=", "r0", ",", "g0", ",", "b0", "elif", "color_code", "==", "1", ":", "r", ",", "g", ",", "b", "=", "r1", ",", "g1", ",", "b1", "elif", "color_code", "==", "2", ":", "r", "=", "(", "2", "*", "r0", "+", "r1", ")", "//", "3", "g", "=", "(", "2", "*", "g0", "+", "g1", ")", "//", "3", "b", "=", "(", "2", "*", "b0", "+", "b1", ")", "//", "3", "elif", "color_code", "==", "3", ":", "r", "=", "(", "2", "*", "r1", "+", "r0", ")", "//", "3", "g", "=", "(", "2", "*", "g1", "+", "g0", ")", "//", "3", "b", "=", "(", "2", "*", "b1", "+", "b0", ")", "//", "3", "ret", "[", "j", "]", ".", "extend", "(", "[", "r", ",", "g", ",", "b", ",", "a", "]", ")", "return", "ret" ]
[ 106, 0 ]
[ 156, 14 ]
python
en
['en', 'error', 'th']
False
decode_dxt5
(data)
input: one "row" of data (i.e. will produce 4 * width pixels)
input: one "row" of data (i.e. will produce 4 * width pixels)
def decode_dxt5(data): """ input: one "row" of data (i.e. will produce 4 * width pixels) """ blocks = len(data) // 16 # number of blocks in row ret = (bytearray(), bytearray(), bytearray(), bytearray()) for block in range(blocks): idx = block * 16 block = data[idx : idx + 16] # Decode next 16-byte block. a0, a1 = struct.unpack_from("<BB", block) bits = struct.unpack_from("<6B", block, 2) alphacode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24) alphacode2 = bits[0] | (bits[1] << 8) color0, color1 = struct.unpack_from("<HH", block, 8) (code,) = struct.unpack_from("<I", block, 12) r0, g0, b0 = unpack_565(color0) r1, g1, b1 = unpack_565(color1) for j in range(4): for i in range(4): # get next control op and generate a pixel alphacode_index = 3 * (4 * j + i) if alphacode_index <= 12: alphacode = (alphacode2 >> alphacode_index) & 0x07 elif alphacode_index == 15: alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06) else: # alphacode_index >= 18 and alphacode_index <= 45 alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07 if alphacode == 0: a = a0 elif alphacode == 1: a = a1 elif a0 > a1: a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7 elif alphacode == 6: a = 0 elif alphacode == 7: a = 255 else: a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5 color_code = (code >> 2 * (4 * j + i)) & 0x03 if color_code == 0: r, g, b = r0, g0, b0 elif color_code == 1: r, g, b = r1, g1, b1 elif color_code == 2: r = (2 * r0 + r1) // 3 g = (2 * g0 + g1) // 3 b = (2 * b0 + b1) // 3 elif color_code == 3: r = (2 * r1 + r0) // 3 g = (2 * g1 + g0) // 3 b = (2 * b1 + b0) // 3 ret[j].extend([r, g, b, a]) return ret
[ "def", "decode_dxt5", "(", "data", ")", ":", "blocks", "=", "len", "(", "data", ")", "//", "16", "# number of blocks in row", "ret", "=", "(", "bytearray", "(", ")", ",", "bytearray", "(", ")", ",", "bytearray", "(", ")", ",", "bytearray", "(", ")", ")", "for", "block", "in", "range", "(", "blocks", ")", ":", "idx", "=", "block", "*", "16", "block", "=", "data", "[", "idx", ":", "idx", "+", "16", "]", "# Decode next 16-byte block.", "a0", ",", "a1", "=", "struct", ".", "unpack_from", "(", "\"<BB\"", ",", "block", ")", "bits", "=", "struct", ".", "unpack_from", "(", "\"<6B\"", ",", "block", ",", "2", ")", "alphacode1", "=", "bits", "[", "2", "]", "|", "(", "bits", "[", "3", "]", "<<", "8", ")", "|", "(", "bits", "[", "4", "]", "<<", "16", ")", "|", "(", "bits", "[", "5", "]", "<<", "24", ")", "alphacode2", "=", "bits", "[", "0", "]", "|", "(", "bits", "[", "1", "]", "<<", "8", ")", "color0", ",", "color1", "=", "struct", ".", "unpack_from", "(", "\"<HH\"", ",", "block", ",", "8", ")", "(", "code", ",", ")", "=", "struct", ".", "unpack_from", "(", "\"<I\"", ",", "block", ",", "12", ")", "r0", ",", "g0", ",", "b0", "=", "unpack_565", "(", "color0", ")", "r1", ",", "g1", ",", "b1", "=", "unpack_565", "(", "color1", ")", "for", "j", "in", "range", "(", "4", ")", ":", "for", "i", "in", "range", "(", "4", ")", ":", "# get next control op and generate a pixel", "alphacode_index", "=", "3", "*", "(", "4", "*", "j", "+", "i", ")", "if", "alphacode_index", "<=", "12", ":", "alphacode", "=", "(", "alphacode2", ">>", "alphacode_index", ")", "&", "0x07", "elif", "alphacode_index", "==", "15", ":", "alphacode", "=", "(", "alphacode2", ">>", "15", ")", "|", "(", "(", "alphacode1", "<<", "1", ")", "&", "0x06", ")", "else", ":", "# alphacode_index >= 18 and alphacode_index <= 45", "alphacode", "=", "(", "alphacode1", ">>", "(", "alphacode_index", "-", "16", ")", ")", "&", "0x07", "if", "alphacode", "==", "0", ":", "a", "=", "a0", "elif", "alphacode", "==", "1", ":", "a", "=", "a1", "elif", "a0", ">", "a1", ":", "a", "=", "(", "(", "8", "-", "alphacode", ")", "*", "a0", "+", "(", "alphacode", "-", "1", ")", "*", "a1", ")", "//", "7", "elif", "alphacode", "==", "6", ":", "a", "=", "0", "elif", "alphacode", "==", "7", ":", "a", "=", "255", "else", ":", "a", "=", "(", "(", "6", "-", "alphacode", ")", "*", "a0", "+", "(", "alphacode", "-", "1", ")", "*", "a1", ")", "//", "5", "color_code", "=", "(", "code", ">>", "2", "*", "(", "4", "*", "j", "+", "i", ")", ")", "&", "0x03", "if", "color_code", "==", "0", ":", "r", ",", "g", ",", "b", "=", "r0", ",", "g0", ",", "b0", "elif", "color_code", "==", "1", ":", "r", ",", "g", ",", "b", "=", "r1", ",", "g1", ",", "b1", "elif", "color_code", "==", "2", ":", "r", "=", "(", "2", "*", "r0", "+", "r1", ")", "//", "3", "g", "=", "(", "2", "*", "g0", "+", "g1", ")", "//", "3", "b", "=", "(", "2", "*", "b0", "+", "b1", ")", "//", "3", "elif", "color_code", "==", "3", ":", "r", "=", "(", "2", "*", "r1", "+", "r0", ")", "//", "3", "g", "=", "(", "2", "*", "g1", "+", "g0", ")", "//", "3", "b", "=", "(", "2", "*", "b1", "+", "b0", ")", "//", "3", "ret", "[", "j", "]", ".", "extend", "(", "[", "r", ",", "g", ",", "b", ",", "a", "]", ")", "return", "ret" ]
[ 159, 0 ]
[ 226, 14 ]
python
en
['en', 'error', 'th']
False
AppEngineAdminHook.get_ae_conn
(self)
Returns: a App Engine service object.
Returns: a App Engine service object.
def get_ae_conn(self): """Returns: a App Engine service object.""" credentials = GoogleCredentials.get_application_default() return build('appengine', 'v1', credentials=credentials)
[ "def", "get_ae_conn", "(", "self", ")", ":", "credentials", "=", "GoogleCredentials", ".", "get_application_default", "(", ")", "return", "build", "(", "'appengine'", ",", "'v1'", ",", "credentials", "=", "credentials", ")" ]
[ 38, 2 ]
[ 41, 60 ]
python
en
['en', 'en', 'en']
True
AppEngineAdminHook.get_svc_conn
(self)
Returns: a Services Management service object.
Returns: a Services Management service object.
def get_svc_conn(self): """Returns: a Services Management service object.""" credentials = GoogleCredentials.get_application_default() return build('servicemanagement', 'v1', credentials=credentials)
[ "def", "get_svc_conn", "(", "self", ")", ":", "credentials", "=", "GoogleCredentials", ".", "get_application_default", "(", ")", "return", "build", "(", "'servicemanagement'", ",", "'v1'", ",", "credentials", "=", "credentials", ")" ]
[ 43, 2 ]
[ 46, 68 ]
python
en
['en', 'fr', 'en']
True
AppEngineAdminHook.create_version
(self, project_id, service_id, version_spec)
Creates new service version on App Engine Engine. Args: project_id: project id service_id: service id version_spec: app version spec Returns: The operation if the version was created successfully and raises an error otherwise.
Creates new service version on App Engine Engine.
def create_version(self, project_id, service_id, version_spec): """Creates new service version on App Engine Engine. Args: project_id: project id service_id: service id version_spec: app version spec Returns: The operation if the version was created successfully and raises an error otherwise. """ create_request = self._gaeadmin.apps().services().versions().create( appsId=project_id, servicesId=service_id, body=version_spec) response = create_request.execute() op_name = response['name'].split('/')[-1] return self._wait_for_operation_done(project_id, op_name)
[ "def", "create_version", "(", "self", ",", "project_id", ",", "service_id", ",", "version_spec", ")", ":", "create_request", "=", "self", ".", "_gaeadmin", ".", "apps", "(", ")", ".", "services", "(", ")", ".", "versions", "(", ")", ".", "create", "(", "appsId", "=", "project_id", ",", "servicesId", "=", "service_id", ",", "body", "=", "version_spec", ")", "response", "=", "create_request", ".", "execute", "(", ")", "op_name", "=", "response", "[", "'name'", "]", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "return", "self", ".", "_wait_for_operation_done", "(", "project_id", ",", "op_name", ")" ]
[ 48, 2 ]
[ 64, 61 ]
python
en
['en', 'ja', 'en']
True
AppEngineAdminHook.migrate_traffic
(self, project_id, service_id, new_version)
Migrate AE traffic from current version to new version. Args: project_id: project id service_id: service id new_version: new version id Returns: the operation if the migration was successful and raises an error otherwise.
Migrate AE traffic from current version to new version.
def migrate_traffic(self, project_id, service_id, new_version): """Migrate AE traffic from current version to new version. Args: project_id: project id service_id: service id new_version: new version id Returns: the operation if the migration was successful and raises an error otherwise. """ split_config = {'split': {'allocations': {new_version: '1'}}} migrate_request = self._gaeadmin.apps().services().patch( appsId=project_id, servicesId=service_id, updateMask='split', body=split_config) response = migrate_request.execute() op_name = response['name'].split('/')[-1] return self._wait_for_operation_done(project_id, op_name)
[ "def", "migrate_traffic", "(", "self", ",", "project_id", ",", "service_id", ",", "new_version", ")", ":", "split_config", "=", "{", "'split'", ":", "{", "'allocations'", ":", "{", "new_version", ":", "'1'", "}", "}", "}", "migrate_request", "=", "self", ".", "_gaeadmin", ".", "apps", "(", ")", ".", "services", "(", ")", ".", "patch", "(", "appsId", "=", "project_id", ",", "servicesId", "=", "service_id", ",", "updateMask", "=", "'split'", ",", "body", "=", "split_config", ")", "response", "=", "migrate_request", ".", "execute", "(", ")", "op_name", "=", "response", "[", "'name'", "]", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "return", "self", ".", "_wait_for_operation_done", "(", "project_id", ",", "op_name", ")" ]
[ 66, 2 ]
[ 84, 61 ]
python
en
['en', 'en', 'en']
True
AppEngineAdminHook.get_endpoint_config
(self, service_id)
Get latest endpoint config for an endpoint service. Args: service_id: service id Returns: the config version if successful and raises an error otherwise.
Get latest endpoint config for an endpoint service.
def get_endpoint_config(self, service_id): """Get latest endpoint config for an endpoint service. Args: service_id: service id Returns: the config version if successful and raises an error otherwise. """ resource = self._svcadmin.services().rollouts() list_request = resource.list(serviceName=service_id) response = list_request.execute() config_id = response['rollouts'][0]['rolloutId'] return config_id
[ "def", "get_endpoint_config", "(", "self", ",", "service_id", ")", ":", "resource", "=", "self", ".", "_svcadmin", ".", "services", "(", ")", ".", "rollouts", "(", ")", "list_request", "=", "resource", ".", "list", "(", "serviceName", "=", "service_id", ")", "response", "=", "list_request", ".", "execute", "(", ")", "config_id", "=", "response", "[", "'rollouts'", "]", "[", "0", "]", "[", "'rolloutId'", "]", "return", "config_id" ]
[ 86, 2 ]
[ 100, 20 ]
python
en
['en', 'en', 'en']
True
AppEngineAdminHook.get_version
(self, project_id, service_id, version)
Get spec for a version of a service on App Engine Engine. Args: project_id: project id service_id: service id version: version id Returns: the version spec if successful and raises an error otherwise.
Get spec for a version of a service on App Engine Engine.
def get_version(self, project_id, service_id, version): """Get spec for a version of a service on App Engine Engine. Args: project_id: project id service_id: service id version: version id Returns: the version spec if successful and raises an error otherwise. """ resource = self._gaeadmin.apps().services().versions() get_request = resource.get(appsId=project_id, servicesId=service_id, versionsId=version, view='FULL') response = get_request.execute() return response
[ "def", "get_version", "(", "self", ",", "project_id", ",", "service_id", ",", "version", ")", ":", "resource", "=", "self", ".", "_gaeadmin", ".", "apps", "(", ")", ".", "services", "(", ")", ".", "versions", "(", ")", "get_request", "=", "resource", ".", "get", "(", "appsId", "=", "project_id", ",", "servicesId", "=", "service_id", ",", "versionsId", "=", "version", ",", "view", "=", "'FULL'", ")", "response", "=", "get_request", ".", "execute", "(", ")", "return", "response" ]
[ 102, 2 ]
[ 118, 19 ]
python
en
['en', 'en', 'en']
True
AppEngineAdminHook.get_version_identifiers
(self, project_id, service_id)
Get list of versions of a service on App Engine Engine. Args: project_id: project id service_id: service id Returns: the list of version identifiers if successful and raises an error otherwise.
Get list of versions of a service on App Engine Engine.
def get_version_identifiers(self, project_id, service_id): """Get list of versions of a service on App Engine Engine. Args: project_id: project id service_id: service id Returns: the list of version identifiers if successful and raises an error otherwise. """ request = self._gaeadmin.apps().services().versions().list(appsId=project_id, servicesId=service_id) versions = [] while request is not None: versions_doc = request.execute() versions.extend([v['id'] for v in versions_doc['versions']]) request = self._gaeadmin.apps().services().versions().list_next(request, versions_doc) return versions
[ "def", "get_version_identifiers", "(", "self", ",", "project_id", ",", "service_id", ")", ":", "request", "=", "self", ".", "_gaeadmin", ".", "apps", "(", ")", ".", "services", "(", ")", ".", "versions", "(", ")", ".", "list", "(", "appsId", "=", "project_id", ",", "servicesId", "=", "service_id", ")", "versions", "=", "[", "]", "while", "request", "is", "not", "None", ":", "versions_doc", "=", "request", ".", "execute", "(", ")", "versions", ".", "extend", "(", "[", "v", "[", "'id'", "]", "for", "v", "in", "versions_doc", "[", "'versions'", "]", "]", ")", "request", "=", "self", ".", "_gaeadmin", ".", "apps", "(", ")", ".", "services", "(", ")", ".", "versions", "(", ")", ".", "list_next", "(", "request", ",", "versions_doc", ")", "return", "versions" ]
[ 120, 2 ]
[ 139, 19 ]
python
en
['en', 'en', 'en']
True
AppEngineAdminHook._get_operation
(self, project_id, op_name)
Gets an AppEngine operation based on the operation name. Args: project_id: project id op_name: operation name Returns: AppEngine operation object if succeed. Raises: apiclient.errors.HttpError: if HTTP error is returned from server
Gets an AppEngine operation based on the operation name.
def _get_operation(self, project_id, op_name): """Gets an AppEngine operation based on the operation name. Args: project_id: project id op_name: operation name Returns: AppEngine operation object if succeed. Raises: apiclient.errors.HttpError: if HTTP error is returned from server """ resource = self._gaeadmin.apps().operations() request = resource.get(appsId=project_id, operationsId=op_name) return request.execute()
[ "def", "_get_operation", "(", "self", ",", "project_id", ",", "op_name", ")", ":", "resource", "=", "self", ".", "_gaeadmin", ".", "apps", "(", ")", ".", "operations", "(", ")", "request", "=", "resource", ".", "get", "(", "appsId", "=", "project_id", ",", "operationsId", "=", "op_name", ")", "return", "request", ".", "execute", "(", ")" ]
[ 141, 2 ]
[ 156, 28 ]
python
en
['en', 'en', 'en']
True
AppEngineAdminHook._wait_for_operation_done
(self, project_id, op_name, interval=30)
Waits for the Operation to reach a terminal state. This method will periodically check the job state until the operation reaches a terminal state. Args: project_id: project id op_name: operation name interval: check interval in seconds Returns: AppEngine operation object if succeed. Raises: apiclient.errors.HttpError: if HTTP error is returned when getting the operation
Waits for the Operation to reach a terminal state.
def _wait_for_operation_done(self, project_id, op_name, interval=30): """Waits for the Operation to reach a terminal state. This method will periodically check the job state until the operation reaches a terminal state. Args: project_id: project id op_name: operation name interval: check interval in seconds Returns: AppEngine operation object if succeed. Raises: apiclient.errors.HttpError: if HTTP error is returned when getting the operation """ assert interval > 0 while True: operation = self._get_operation(project_id, op_name) if 'done' in operation and operation['done']: return operation time.sleep(interval)
[ "def", "_wait_for_operation_done", "(", "self", ",", "project_id", ",", "op_name", ",", "interval", "=", "30", ")", ":", "assert", "interval", ">", "0", "while", "True", ":", "operation", "=", "self", ".", "_get_operation", "(", "project_id", ",", "op_name", ")", "if", "'done'", "in", "operation", "and", "operation", "[", "'done'", "]", ":", "return", "operation", "time", ".", "sleep", "(", "interval", ")" ]
[ 158, 2 ]
[ 181, 26 ]
python
en
['en', 'en', 'en']
True
usage
(**options)
Get account usage details. Get a report on the status of your Cloudinary account usage details, including storage, credits, bandwidth, requests, number of resources, and add-on usage. Note that numbers are updated periodically. See: `Get account usage details <https://cloudinary.com/documentation/admin_api#get_account_usage_details>`_ :param options: Additional options :type options: dict, optional :return: Detailed usage information :rtype: Response
Get account usage details.
def usage(**options): """Get account usage details. Get a report on the status of your Cloudinary account usage details, including storage, credits, bandwidth, requests, number of resources, and add-on usage. Note that numbers are updated periodically. See: `Get account usage details <https://cloudinary.com/documentation/admin_api#get_account_usage_details>`_ :param options: Additional options :type options: dict, optional :return: Detailed usage information :rtype: Response """ date = options.pop("date", None) uri = ["usage"] if date: if isinstance(date, datetime.date): date = utils.encode_date_to_usage_api_format(date) uri.append(date) return call_api("get", uri, {}, **options)
[ "def", "usage", "(", "*", "*", "options", ")", ":", "date", "=", "options", ".", "pop", "(", "\"date\"", ",", "None", ")", "uri", "=", "[", "\"usage\"", "]", "if", "date", ":", "if", "isinstance", "(", "date", ",", "datetime", ".", "date", ")", ":", "date", "=", "utils", ".", "encode_date_to_usage_api_format", "(", "date", ")", "uri", ".", "append", "(", "date", ")", "return", "call_api", "(", "\"get\"", ",", "uri", ",", "{", "}", ",", "*", "*", "options", ")" ]
[ 33, 0 ]
[ 53, 46 ]
python
de
['fr', 'de', 'en']
False
resources_by_context
(key, value=None, **options)
Retrieves resources (assets) with a specified context key. This method does not return deleted assets even if they have been backed up. See: `Get resources by context API reference <https://cloudinary.com/documentation/admin_api#get_resources_by_context>`_ :param key: Only assets with this context key are returned :type key: str :param value: Only assets with this value for the context key are returned :type value: str, optional :param options: Additional options :type options: dict, optional :return: Resources (assets) with a specified context key :rtype: Response
Retrieves resources (assets) with a specified context key. This method does not return deleted assets even if they have been backed up.
def resources_by_context(key, value=None, **options): """Retrieves resources (assets) with a specified context key. This method does not return deleted assets even if they have been backed up. See: `Get resources by context API reference <https://cloudinary.com/documentation/admin_api#get_resources_by_context>`_ :param key: Only assets with this context key are returned :type key: str :param value: Only assets with this value for the context key are returned :type value: str, optional :param options: Additional options :type options: dict, optional :return: Resources (assets) with a specified context key :rtype: Response """ resource_type = options.pop("resource_type", "image") uri = ["resources", resource_type, "context"] params = only(options, "next_cursor", "max_results", "tags", "context", "moderations", "direction", "metadata") params["key"] = key if value is not None: params["value"] = value return call_api("get", uri, params, **options)
[ "def", "resources_by_context", "(", "key", ",", "value", "=", "None", ",", "*", "*", "options", ")", ":", "resource_type", "=", "options", ".", "pop", "(", "\"resource_type\"", ",", "\"image\"", ")", "uri", "=", "[", "\"resources\"", ",", "resource_type", ",", "\"context\"", "]", "params", "=", "only", "(", "options", ",", "\"next_cursor\"", ",", "\"max_results\"", ",", "\"tags\"", ",", "\"context\"", ",", "\"moderations\"", ",", "\"direction\"", ",", "\"metadata\"", ")", "params", "[", "\"key\"", "]", "=", "key", "if", "value", "is", "not", "None", ":", "params", "[", "\"value\"", "]", "=", "value", "return", "call_api", "(", "\"get\"", ",", "uri", ",", "params", ",", "*", "*", "options", ")" ]
[ 95, 0 ]
[ 118, 50 ]
python
en
['en', 'en', 'en']
True
delete_derived_by_transformation
(public_ids, transformations, resource_type='image', type='upload', invalidate=None, **options)
Delete derived resources of public ids, identified by transformations :param public_ids: the base resources :type public_ids: list of str :param transformations: the transformation of derived resources, optionally including the format :type transformations: list of (dict or str) :param type: The upload type :type type: str :param resource_type: The type of the resource: defaults to "image" :type resource_type: str :param invalidate: (optional) True to invalidate the resources after deletion :type invalidate: bool :return: a list of the public ids for which derived resources were deleted :rtype: dict
Delete derived resources of public ids, identified by transformations
def delete_derived_by_transformation(public_ids, transformations, resource_type='image', type='upload', invalidate=None, **options): """Delete derived resources of public ids, identified by transformations :param public_ids: the base resources :type public_ids: list of str :param transformations: the transformation of derived resources, optionally including the format :type transformations: list of (dict or str) :param type: The upload type :type type: str :param resource_type: The type of the resource: defaults to "image" :type resource_type: str :param invalidate: (optional) True to invalidate the resources after deletion :type invalidate: bool :return: a list of the public ids for which derived resources were deleted :rtype: dict """ uri = ["resources", resource_type, type] if not isinstance(public_ids, list): public_ids = [public_ids] params = {"public_ids": public_ids, "transformations": utils.build_eager(transformations), "keep_original": True} if invalidate is not None: params['invalidate'] = invalidate return call_api("delete", uri, params, **options)
[ "def", "delete_derived_by_transformation", "(", "public_ids", ",", "transformations", ",", "resource_type", "=", "'image'", ",", "type", "=", "'upload'", ",", "invalidate", "=", "None", ",", "*", "*", "options", ")", ":", "uri", "=", "[", "\"resources\"", ",", "resource_type", ",", "type", "]", "if", "not", "isinstance", "(", "public_ids", ",", "list", ")", ":", "public_ids", "=", "[", "public_ids", "]", "params", "=", "{", "\"public_ids\"", ":", "public_ids", ",", "\"transformations\"", ":", "utils", ".", "build_eager", "(", "transformations", ")", ",", "\"keep_original\"", ":", "True", "}", "if", "invalidate", "is", "not", "None", ":", "params", "[", "'invalidate'", "]", "=", "invalidate", "return", "call_api", "(", "\"delete\"", ",", "uri", ",", "params", ",", "*", "*", "options", ")" ]
[ 194, 0 ]
[ 220, 53 ]
python
en
['en', 'en', 'en']
True
delete_folder
(path, **options)
Deletes folder Deleted folder must be empty, but can have descendant empty sub folders :param path: The folder to delete :param options: Additional options :rtype: Response
Deletes folder
def delete_folder(path, **options): """Deletes folder Deleted folder must be empty, but can have descendant empty sub folders :param path: The folder to delete :param options: Additional options :rtype: Response """ return call_api("delete", ["folders", path], {}, **options)
[ "def", "delete_folder", "(", "path", ",", "*", "*", "options", ")", ":", "return", "call_api", "(", "\"delete\"", ",", "[", "\"folders\"", ",", "path", "]", ",", "{", "}", ",", "*", "*", "options", ")" ]
[ 340, 0 ]
[ 350, 63 ]
python
da
['en', 'da', 'tr']
False
list_metadata_fields
(**options)
Returns a list of all metadata field definitions See: `Get metadata fields API reference <https://cloudinary.com/documentation/admin_api#get_metadata_fields>`_ :param options: Additional options :rtype: Response
Returns a list of all metadata field definitions
def list_metadata_fields(**options): """Returns a list of all metadata field definitions See: `Get metadata fields API reference <https://cloudinary.com/documentation/admin_api#get_metadata_fields>`_ :param options: Additional options :rtype: Response """ return call_metadata_api("get", [], {}, **options)
[ "def", "list_metadata_fields", "(", "*", "*", "options", ")", ":", "return", "call_metadata_api", "(", "\"get\"", ",", "[", "]", ",", "{", "}", ",", "*", "*", "options", ")" ]
[ 447, 0 ]
[ 456, 54 ]
python
en
['en', 'lb', 'en']
True
metadata_field_by_field_id
(field_external_id, **options)
Gets a metadata field by external id See: `Get metadata field by external ID API reference <https://cloudinary.com/documentation/admin_api#get_a_metadata_field_by_external_id>`_ :param field_external_id: The ID of the metadata field to retrieve :param options: Additional options :rtype: Response
Gets a metadata field by external id
def metadata_field_by_field_id(field_external_id, **options): """Gets a metadata field by external id See: `Get metadata field by external ID API reference <https://cloudinary.com/documentation/admin_api#get_a_metadata_field_by_external_id>`_ :param field_external_id: The ID of the metadata field to retrieve :param options: Additional options :rtype: Response """ uri = [field_external_id] return call_metadata_api("get", uri, {}, **options)
[ "def", "metadata_field_by_field_id", "(", "field_external_id", ",", "*", "*", "options", ")", ":", "uri", "=", "[", "field_external_id", "]", "return", "call_metadata_api", "(", "\"get\"", ",", "uri", ",", "{", "}", ",", "*", "*", "options", ")" ]
[ 459, 0 ]
[ 471, 55 ]
python
en
['en', 'lb', 'en']
True
add_metadata_field
(field, **options)
Creates a new metadata field definition See: `Create metadata field API reference <https://cloudinary.com/documentation/admin_api#create_a_metadata_field>`_ :param field: The field to add :param options: Additional options :rtype: Response
Creates a new metadata field definition
def add_metadata_field(field, **options): """Creates a new metadata field definition See: `Create metadata field API reference <https://cloudinary.com/documentation/admin_api#create_a_metadata_field>`_ :param field: The field to add :param options: Additional options :rtype: Response """ params = only(field, "type", "external_id", "label", "mandatory", "default_value", "validation", "datasource") return call_metadata_api("post", [], params, **options)
[ "def", "add_metadata_field", "(", "field", ",", "*", "*", "options", ")", ":", "params", "=", "only", "(", "field", ",", "\"type\"", ",", "\"external_id\"", ",", "\"label\"", ",", "\"mandatory\"", ",", "\"default_value\"", ",", "\"validation\"", ",", "\"datasource\"", ")", "return", "call_metadata_api", "(", "\"post\"", ",", "[", "]", ",", "params", ",", "*", "*", "options", ")" ]
[ 474, 0 ]
[ 486, 59 ]
python
en
['en', 'en', 'en']
True
update_metadata_field
(field_external_id, field, **options)
Updates a metadata field by external id Updates a metadata field definition (partially, no need to pass the entire object) passed as JSON data. See `Generic structure of a metadata field <https://cloudinary.com/documentation/admin_api#generic_structure_of_a_metadata_field>`_ for details. :param field_external_id: The id of the metadata field to update :param field: The field definition :param options: Additional options :rtype: Response
Updates a metadata field by external id
def update_metadata_field(field_external_id, field, **options): """Updates a metadata field by external id Updates a metadata field definition (partially, no need to pass the entire object) passed as JSON data. See `Generic structure of a metadata field <https://cloudinary.com/documentation/admin_api#generic_structure_of_a_metadata_field>`_ for details. :param field_external_id: The id of the metadata field to update :param field: The field definition :param options: Additional options :rtype: Response """ uri = [field_external_id] params = only(field, "label", "mandatory", "default_value", "validation") return call_metadata_api("put", uri, params, **options)
[ "def", "update_metadata_field", "(", "field_external_id", ",", "field", ",", "*", "*", "options", ")", ":", "uri", "=", "[", "field_external_id", "]", "params", "=", "only", "(", "field", ",", "\"label\"", ",", "\"mandatory\"", ",", "\"default_value\"", ",", "\"validation\"", ")", "return", "call_metadata_api", "(", "\"put\"", ",", "uri", ",", "params", ",", "*", "*", "options", ")" ]
[ 489, 0 ]
[ 506, 59 ]
python
en
['en', 'lb', 'en']
True
delete_metadata_field
(field_external_id, **options)
Deletes a metadata field definition. The field should no longer be considered a valid candidate for all other endpoints See: `Delete metadata field API reference <https://cloudinary.com/documentation/admin_api#delete_a_metadata_field_by_external_id>`_ :param field_external_id: The external id of the field to delete :param options: Additional options :return: An array with a "message" key. "ok" value indicates a successful deletion. :rtype: Response
Deletes a metadata field definition. The field should no longer be considered a valid candidate for all other endpoints
def delete_metadata_field(field_external_id, **options): """Deletes a metadata field definition. The field should no longer be considered a valid candidate for all other endpoints See: `Delete metadata field API reference <https://cloudinary.com/documentation/admin_api#delete_a_metadata_field_by_external_id>`_ :param field_external_id: The external id of the field to delete :param options: Additional options :return: An array with a "message" key. "ok" value indicates a successful deletion. :rtype: Response """ uri = [field_external_id] return call_metadata_api("delete", uri, {}, **options)
[ "def", "delete_metadata_field", "(", "field_external_id", ",", "*", "*", "options", ")", ":", "uri", "=", "[", "field_external_id", "]", "return", "call_metadata_api", "(", "\"delete\"", ",", "uri", ",", "{", "}", ",", "*", "*", "options", ")" ]
[ 509, 0 ]
[ 523, 58 ]
python
en
['en', 'en', 'en']
True
delete_datasource_entries
(field_external_id, entries_external_id, **options)
Deletes entries in a metadata field datasource Deletes (blocks) the datasource entries for a specified metadata field definition. Sets the state of the entries to inactive. This is a soft delete, the entries still exist under the hood and can be activated again with the restore datasource entries method. See: `Delete entries in a metadata field datasource API reference <https://cloudinary.com/documentation/admin_api#delete_entries_in_a_metadata_field_datasource>`_ :param field_external_id: The id of the field to update :param entries_external_id: The ids of all the entries to delete from the datasource :param options: Additional options :rtype: Response
Deletes entries in a metadata field datasource
def delete_datasource_entries(field_external_id, entries_external_id, **options): """Deletes entries in a metadata field datasource Deletes (blocks) the datasource entries for a specified metadata field definition. Sets the state of the entries to inactive. This is a soft delete, the entries still exist under the hood and can be activated again with the restore datasource entries method. See: `Delete entries in a metadata field datasource API reference <https://cloudinary.com/documentation/admin_api#delete_entries_in_a_metadata_field_datasource>`_ :param field_external_id: The id of the field to update :param entries_external_id: The ids of all the entries to delete from the datasource :param options: Additional options :rtype: Response """ uri = [field_external_id, "datasource"] params = {"external_ids": entries_external_id} return call_metadata_api("delete", uri, params, **options)
[ "def", "delete_datasource_entries", "(", "field_external_id", ",", "entries_external_id", ",", "*", "*", "options", ")", ":", "uri", "=", "[", "field_external_id", ",", "\"datasource\"", "]", "params", "=", "{", "\"external_ids\"", ":", "entries_external_id", "}", "return", "call_metadata_api", "(", "\"delete\"", ",", "uri", ",", "params", ",", "*", "*", "options", ")" ]
[ 526, 0 ]
[ 546, 62 ]
python
en
['en', 'en', 'nl']
True
update_metadata_field_datasource
(field_external_id, entries_external_id, **options)
Updates a metadata field datasource Updates the datasource of a supported field type (currently only enum and set), passed as JSON data. The update is partial: datasource entries with an existing external_id will be updated and entries with new external_id's (or without external_id's) will be appended. See: `Update a metadata field datasource API reference <https://cloudinary.com/documentation/admin_api#update_a_metadata_field_datasource>`_ :param field_external_id: The external id of the field to update :param entries_external_id: :param options: Additional options :rtype: Response
Updates a metadata field datasource
def update_metadata_field_datasource(field_external_id, entries_external_id, **options): """Updates a metadata field datasource Updates the datasource of a supported field type (currently only enum and set), passed as JSON data. The update is partial: datasource entries with an existing external_id will be updated and entries with new external_id's (or without external_id's) will be appended. See: `Update a metadata field datasource API reference <https://cloudinary.com/documentation/admin_api#update_a_metadata_field_datasource>`_ :param field_external_id: The external id of the field to update :param entries_external_id: :param options: Additional options :rtype: Response """ values = [] for item in entries_external_id: external = only(item, "external_id", "value") if external: values.append(external) uri = [field_external_id, "datasource"] params = {"values": values} return call_metadata_api("put", uri, params, **options)
[ "def", "update_metadata_field_datasource", "(", "field_external_id", ",", "entries_external_id", ",", "*", "*", "options", ")", ":", "values", "=", "[", "]", "for", "item", "in", "entries_external_id", ":", "external", "=", "only", "(", "item", ",", "\"external_id\"", ",", "\"value\"", ")", "if", "external", ":", "values", ".", "append", "(", "external", ")", "uri", "=", "[", "field_external_id", ",", "\"datasource\"", "]", "params", "=", "{", "\"values\"", ":", "values", "}", "return", "call_metadata_api", "(", "\"put\"", ",", "uri", ",", "params", ",", "*", "*", "options", ")" ]
[ 549, 0 ]
[ 574, 59 ]
python
en
['en', 'lb', 'en']
True
restore_metadata_field_datasource
(field_external_id, entries_external_ids, **options)
Restores entries in a metadata field datasource Restores (unblocks) any previously deleted datasource entries for a specified metadata field definition. Sets the state of the entries to active. See: `Restore entries in a metadata field datasource API reference <https://cloudinary.com/documentation/admin_api#restore_entries_in_a_metadata_field_datasource>`_ :param field_external_id: The ID of the metadata field :param entries_external_ids: An array of IDs of datasource entries to restore (unblock) :param options: Additional options :rtype: Response
Restores entries in a metadata field datasource
def restore_metadata_field_datasource(field_external_id, entries_external_ids, **options): """Restores entries in a metadata field datasource Restores (unblocks) any previously deleted datasource entries for a specified metadata field definition. Sets the state of the entries to active. See: `Restore entries in a metadata field datasource API reference <https://cloudinary.com/documentation/admin_api#restore_entries_in_a_metadata_field_datasource>`_ :param field_external_id: The ID of the metadata field :param entries_external_ids: An array of IDs of datasource entries to restore (unblock) :param options: Additional options :rtype: Response """ uri = [field_external_id, 'datasource_restore'] params = {"external_ids": entries_external_ids} return call_metadata_api("post", uri, params, **options)
[ "def", "restore_metadata_field_datasource", "(", "field_external_id", ",", "entries_external_ids", ",", "*", "*", "options", ")", ":", "uri", "=", "[", "field_external_id", ",", "'datasource_restore'", "]", "params", "=", "{", "\"external_ids\"", ":", "entries_external_ids", "}", "return", "call_metadata_api", "(", "\"post\"", ",", "uri", ",", "params", ",", "*", "*", "options", ")" ]
[ 577, 0 ]
[ 596, 60 ]
python
en
['en', 'de', 'en']
True
build_wheel
(source_dir, wheel_dir, config_settings=None)
Build a wheel from a source directory using PEP 517 hooks. :param str source_dir: Source directory containing pyproject.toml :param str wheel_dir: Target directory to create wheel in :param dict config_settings: Options to pass to build backend This is a blocking function which will run pip in a subprocess to install build requirements.
Build a wheel from a source directory using PEP 517 hooks.
def build_wheel(source_dir, wheel_dir, config_settings=None): """Build a wheel from a source directory using PEP 517 hooks. :param str source_dir: Source directory containing pyproject.toml :param str wheel_dir: Target directory to create wheel in :param dict config_settings: Options to pass to build backend This is a blocking function which will run pip in a subprocess to install build requirements. """ if config_settings is None: config_settings = {} requires, backend, backend_path = _load_pyproject(source_dir) hooks = Pep517HookCaller(source_dir, backend, backend_path) with BuildEnvironment() as env: env.pip_install(requires) reqs = hooks.get_requires_for_build_wheel(config_settings) env.pip_install(reqs) return hooks.build_wheel(wheel_dir, config_settings)
[ "def", "build_wheel", "(", "source_dir", ",", "wheel_dir", ",", "config_settings", "=", "None", ")", ":", "if", "config_settings", "is", "None", ":", "config_settings", "=", "{", "}", "requires", ",", "backend", ",", "backend_path", "=", "_load_pyproject", "(", "source_dir", ")", "hooks", "=", "Pep517HookCaller", "(", "source_dir", ",", "backend", ",", "backend_path", ")", "with", "BuildEnvironment", "(", ")", "as", "env", ":", "env", ".", "pip_install", "(", "requires", ")", "reqs", "=", "hooks", ".", "get_requires_for_build_wheel", "(", "config_settings", ")", "env", ".", "pip_install", "(", "reqs", ")", "return", "hooks", ".", "build_wheel", "(", "wheel_dir", ",", "config_settings", ")" ]
[ 129, 0 ]
[ 148, 60 ]
python
en
['en', 'en', 'en']
True
build_sdist
(source_dir, sdist_dir, config_settings=None)
Build an sdist from a source directory using PEP 517 hooks. :param str source_dir: Source directory containing pyproject.toml :param str sdist_dir: Target directory to place sdist in :param dict config_settings: Options to pass to build backend This is a blocking function which will run pip in a subprocess to install build requirements.
Build an sdist from a source directory using PEP 517 hooks.
def build_sdist(source_dir, sdist_dir, config_settings=None): """Build an sdist from a source directory using PEP 517 hooks. :param str source_dir: Source directory containing pyproject.toml :param str sdist_dir: Target directory to place sdist in :param dict config_settings: Options to pass to build backend This is a blocking function which will run pip in a subprocess to install build requirements. """ if config_settings is None: config_settings = {} requires, backend, backend_path = _load_pyproject(source_dir) hooks = Pep517HookCaller(source_dir, backend, backend_path) with BuildEnvironment() as env: env.pip_install(requires) reqs = hooks.get_requires_for_build_sdist(config_settings) env.pip_install(reqs) return hooks.build_sdist(sdist_dir, config_settings)
[ "def", "build_sdist", "(", "source_dir", ",", "sdist_dir", ",", "config_settings", "=", "None", ")", ":", "if", "config_settings", "is", "None", ":", "config_settings", "=", "{", "}", "requires", ",", "backend", ",", "backend_path", "=", "_load_pyproject", "(", "source_dir", ")", "hooks", "=", "Pep517HookCaller", "(", "source_dir", ",", "backend", ",", "backend_path", ")", "with", "BuildEnvironment", "(", ")", "as", "env", ":", "env", ".", "pip_install", "(", "requires", ")", "reqs", "=", "hooks", ".", "get_requires_for_build_sdist", "(", "config_settings", ")", "env", ".", "pip_install", "(", "reqs", ")", "return", "hooks", ".", "build_sdist", "(", "sdist_dir", ",", "config_settings", ")" ]
[ 151, 0 ]
[ 170, 60 ]
python
en
['en', 'en', 'en']
True
BuildEnvironment.pip_install
(self, reqs)
Install dependencies into this env by calling pip in a subprocess
Install dependencies into this env by calling pip in a subprocess
def pip_install(self, reqs): """Install dependencies into this env by calling pip in a subprocess""" if not reqs: return log.info('Calling pip to install %s', reqs) cmd = [ sys.executable, '-m', 'pip', 'install', '--ignore-installed', '--prefix', self.path] + list(reqs) check_call( cmd, stdout=LoggerWrapper(log, logging.INFO), stderr=LoggerWrapper(log, logging.ERROR), )
[ "def", "pip_install", "(", "self", ",", "reqs", ")", ":", "if", "not", "reqs", ":", "return", "log", ".", "info", "(", "'Calling pip to install %s'", ",", "reqs", ")", "cmd", "=", "[", "sys", ".", "executable", ",", "'-m'", ",", "'pip'", ",", "'install'", ",", "'--ignore-installed'", ",", "'--prefix'", ",", "self", ".", "path", "]", "+", "list", "(", "reqs", ")", "check_call", "(", "cmd", ",", "stdout", "=", "LoggerWrapper", "(", "log", ",", "logging", ".", "INFO", ")", ",", "stderr", "=", "LoggerWrapper", "(", "log", ",", "logging", ".", "ERROR", ")", ",", ")" ]
[ 95, 4 ]
[ 107, 9 ]
python
en
['en', 'en', 'en']
True
publish_feedback
(feedback)
pull_feedback Starts pulling messages from subscription - receive callback function from calling module - initiate the pull providing the callback function
pull_feedback
def publish_feedback(feedback): # TODO: Publish the feedback object to the feedback topic # END TODO """pull_feedback Starts pulling messages from subscription - receive callback function from calling module - initiate the pull providing the callback function """
[ "def", "publish_feedback", "(", "feedback", ")", ":", "# TODO: Publish the feedback object to the feedback topic", "# END TODO" ]
[ 58, 0 ]
[ 71, 3 ]
python
en
['en', 'cy', 'en']
False
generate_token
(key, user_id, action_id='', when=None)
Generates a URL-safe token for the given user, action, time tuple. Args: key: secret key to use. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. when: the time in seconds since the epoch at which the user was authorized for this action. If not set the current time is used. Returns: A string XSRF protection token.
Generates a URL-safe token for the given user, action, time tuple.
def generate_token(key, user_id, action_id='', when=None): """Generates a URL-safe token for the given user, action, time tuple. Args: key: secret key to use. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. when: the time in seconds since the epoch at which the user was authorized for this action. If not set the current time is used. Returns: A string XSRF protection token. """ digester = hmac.new(_helpers._to_bytes(key, encoding='utf-8')) digester.update(_helpers._to_bytes(str(user_id), encoding='utf-8')) digester.update(DELIMITER) digester.update(_helpers._to_bytes(action_id, encoding='utf-8')) digester.update(DELIMITER) when = _helpers._to_bytes(str(when or int(time.time())), encoding='utf-8') digester.update(when) digest = digester.digest() token = base64.urlsafe_b64encode(digest + DELIMITER + when) return token
[ "def", "generate_token", "(", "key", ",", "user_id", ",", "action_id", "=", "''", ",", "when", "=", "None", ")", ":", "digester", "=", "hmac", ".", "new", "(", "_helpers", ".", "_to_bytes", "(", "key", ",", "encoding", "=", "'utf-8'", ")", ")", "digester", ".", "update", "(", "_helpers", ".", "_to_bytes", "(", "str", "(", "user_id", ")", ",", "encoding", "=", "'utf-8'", ")", ")", "digester", ".", "update", "(", "DELIMITER", ")", "digester", ".", "update", "(", "_helpers", ".", "_to_bytes", "(", "action_id", ",", "encoding", "=", "'utf-8'", ")", ")", "digester", ".", "update", "(", "DELIMITER", ")", "when", "=", "_helpers", ".", "_to_bytes", "(", "str", "(", "when", "or", "int", "(", "time", ".", "time", "(", ")", ")", ")", ",", "encoding", "=", "'utf-8'", ")", "digester", ".", "update", "(", "when", ")", "digest", "=", "digester", ".", "digest", "(", ")", "token", "=", "base64", ".", "urlsafe_b64encode", "(", "digest", "+", "DELIMITER", "+", "when", ")", "return", "token" ]
[ 32, 0 ]
[ 56, 16 ]
python
en
['en', 'en', 'en']
True
validate_token
(key, token, user_id, action_id="", current_time=None)
Validates that the given token authorizes the user for the action. Tokens are invalid if the time of issue is too old or if the token does not match what generateToken outputs (i.e. the token was forged). Args: key: secret key to use. token: a string of the token generated by generateToken. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. Returns: A boolean - True if the user is authorized for the action, False otherwise.
Validates that the given token authorizes the user for the action.
def validate_token(key, token, user_id, action_id="", current_time=None): """Validates that the given token authorizes the user for the action. Tokens are invalid if the time of issue is too old or if the token does not match what generateToken outputs (i.e. the token was forged). Args: key: secret key to use. token: a string of the token generated by generateToken. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. Returns: A boolean - True if the user is authorized for the action, False otherwise. """ if not token: return False try: decoded = base64.urlsafe_b64decode(token) token_time = int(decoded.split(DELIMITER)[-1]) except (TypeError, ValueError, binascii.Error): return False if current_time is None: current_time = time.time() # If the token is too old it's not valid. if current_time - token_time > DEFAULT_TIMEOUT_SECS: return False # The given token should match the generated one with the same time. expected_token = generate_token(key, user_id, action_id=action_id, when=token_time) if len(token) != len(expected_token): return False # Perform constant time comparison to avoid timing attacks different = 0 for x, y in zip(bytearray(token), bytearray(expected_token)): different |= x ^ y return not different
[ "def", "validate_token", "(", "key", ",", "token", ",", "user_id", ",", "action_id", "=", "\"\"", ",", "current_time", "=", "None", ")", ":", "if", "not", "token", ":", "return", "False", "try", ":", "decoded", "=", "base64", ".", "urlsafe_b64decode", "(", "token", ")", "token_time", "=", "int", "(", "decoded", ".", "split", "(", "DELIMITER", ")", "[", "-", "1", "]", ")", "except", "(", "TypeError", ",", "ValueError", ",", "binascii", ".", "Error", ")", ":", "return", "False", "if", "current_time", "is", "None", ":", "current_time", "=", "time", ".", "time", "(", ")", "# If the token is too old it's not valid.", "if", "current_time", "-", "token_time", ">", "DEFAULT_TIMEOUT_SECS", ":", "return", "False", "# The given token should match the generated one with the same time.", "expected_token", "=", "generate_token", "(", "key", ",", "user_id", ",", "action_id", "=", "action_id", ",", "when", "=", "token_time", ")", "if", "len", "(", "token", ")", "!=", "len", "(", "expected_token", ")", ":", "return", "False", "# Perform constant time comparison to avoid timing attacks", "different", "=", "0", "for", "x", ",", "y", "in", "zip", "(", "bytearray", "(", "token", ")", ",", "bytearray", "(", "expected_token", ")", ")", ":", "different", "|=", "x", "^", "y", "return", "not", "different" ]
[ 60, 0 ]
[ 100, 24 ]
python
en
['en', 'en', 'en']
True
filesys_decode
(path)
Ensure that the given path is decoded, NONE when no expected encoding works
Ensure that the given path is decoded, NONE when no expected encoding works
def filesys_decode(path): """ Ensure that the given path is decoded, NONE when no expected encoding works """ if isinstance(path, six.text_type): return path fs_enc = sys.getfilesystemencoding() or 'utf-8' candidates = fs_enc, 'utf-8' for enc in candidates: try: return path.decode(enc) except UnicodeDecodeError: continue
[ "def", "filesys_decode", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "six", ".", "text_type", ")", ":", "return", "path", "fs_enc", "=", "sys", ".", "getfilesystemencoding", "(", ")", "or", "'utf-8'", "candidates", "=", "fs_enc", ",", "'utf-8'", "for", "enc", "in", "candidates", ":", "try", ":", "return", "path", ".", "decode", "(", "enc", ")", "except", "UnicodeDecodeError", ":", "continue" ]
[ 19, 0 ]
[ 35, 20 ]
python
en
['en', 'error', 'th']
False
try_encode
(string, enc)
turn unicode encoding into a functional routine
turn unicode encoding into a functional routine
def try_encode(string, enc): "turn unicode encoding into a functional routine" try: return string.encode(enc) except UnicodeEncodeError: return None
[ "def", "try_encode", "(", "string", ",", "enc", ")", ":", "try", ":", "return", "string", ".", "encode", "(", "enc", ")", "except", "UnicodeEncodeError", ":", "return", "None" ]
[ 38, 0 ]
[ 43, 19 ]
python
en
['en', 'en', 'en']
True
SessionStore.create_model_instance
(self, data)
Return a new instance of the session model object, which represents the current session state. Intended to be used for saving the session data to the database.
Return a new instance of the session model object, which represents the current session state. Intended to be used for saving the session data to the database.
def create_model_instance(self, data): """ Return a new instance of the session model object, which represents the current session state. Intended to be used for saving the session data to the database. """ return self.model( session_key=self._get_or_create_session_key(), session_data=self.encode(data), expire_date=self.get_expiry_date(), )
[ "def", "create_model_instance", "(", "self", ",", "data", ")", ":", "return", "self", ".", "model", "(", "session_key", "=", "self", ".", "_get_or_create_session_key", "(", ")", ",", "session_data", "=", "self", ".", "encode", "(", "data", ")", ",", "expire_date", "=", "self", ".", "get_expiry_date", "(", ")", ",", ")" ]
[ 61, 4 ]
[ 71, 9 ]
python
en
['en', 'error', 'th']
False
SessionStore.save
(self, must_create=False)
Save the current session data to the database. If 'must_create' is True, raise a database error if the saving operation doesn't create a new entry (as opposed to possibly updating an existing entry).
Save the current session data to the database. If 'must_create' is True, raise a database error if the saving operation doesn't create a new entry (as opposed to possibly updating an existing entry).
def save(self, must_create=False): """ Save the current session data to the database. If 'must_create' is True, raise a database error if the saving operation doesn't create a new entry (as opposed to possibly updating an existing entry). """ if self.session_key is None: return self.create() data = self._get_session(no_load=must_create) obj = self.create_model_instance(data) using = router.db_for_write(self.model, instance=obj) try: with transaction.atomic(using=using): obj.save(force_insert=must_create, force_update=not must_create, using=using) except IntegrityError: if must_create: raise CreateError raise except DatabaseError: if not must_create: raise UpdateError raise
[ "def", "save", "(", "self", ",", "must_create", "=", "False", ")", ":", "if", "self", ".", "session_key", "is", "None", ":", "return", "self", ".", "create", "(", ")", "data", "=", "self", ".", "_get_session", "(", "no_load", "=", "must_create", ")", "obj", "=", "self", ".", "create_model_instance", "(", "data", ")", "using", "=", "router", ".", "db_for_write", "(", "self", ".", "model", ",", "instance", "=", "obj", ")", "try", ":", "with", "transaction", ".", "atomic", "(", "using", "=", "using", ")", ":", "obj", ".", "save", "(", "force_insert", "=", "must_create", ",", "force_update", "=", "not", "must_create", ",", "using", "=", "using", ")", "except", "IntegrityError", ":", "if", "must_create", ":", "raise", "CreateError", "raise", "except", "DatabaseError", ":", "if", "not", "must_create", ":", "raise", "UpdateError", "raise" ]
[ 73, 4 ]
[ 94, 17 ]
python
en
['en', 'error', 'th']
False
MonoRandomForestClassifier.predict
(self, X)
Predict class for X. NOTE: We need to override parent method's predict() so we can allow for Kotlowski and Slowinski style monotone ensembling. The predicted class of an input sample is a vote by the trees in the forest, weighted by their probability estimates. That is, the predicted class is the one with highest mean probability estimate across the trees. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- y : array of shape = [n_samples] or [n_samples, n_outputs] The predicted classes.
Predict class for X.
def predict(self, X): """Predict class for X. NOTE: We need to override parent method's predict() so we can allow for Kotlowski and Slowinski style monotone ensembling. The predicted class of an input sample is a vote by the trees in the forest, weighted by their probability estimates. That is, the predicted class is the one with highest mean probability estimate across the trees. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- y : array of shape = [n_samples] or [n_samples, n_outputs] The predicted classes. """ if self.n_outputs_ == 1: if self.n_classes_ <= 2: proba = self.predict_proba(X) return self.classes_.take(np.argmax(proba, axis=1), axis=0) else: proba = self.predict_cum_proba(X) class_index = np.sum((proba > 0.5).astype(np.int), axis=1) return self.classes_.take(class_index, axis=0) else: n_samples = proba[0].shape[0] predictions = np.zeros((n_samples, self.n_outputs_)) for k in range(self.n_outputs_): if self.n_classes_ <= 2: proba = self.predict_proba(X) predictions[:, k] = self.classes_[k].take( np.argmax(proba[k], axis=1), axis=0) else: proba = self.predict_cum_proba(X) class_index = np.sum( (proba[k] > 0.5).astype( np.int), axis=1) predictions[:, k] = self.classes_[ k].take(class_index, axis=0) return predictions
[ "def", "predict", "(", "self", ",", "X", ")", ":", "if", "self", ".", "n_outputs_", "==", "1", ":", "if", "self", ".", "n_classes_", "<=", "2", ":", "proba", "=", "self", ".", "predict_proba", "(", "X", ")", "return", "self", ".", "classes_", ".", "take", "(", "np", ".", "argmax", "(", "proba", ",", "axis", "=", "1", ")", ",", "axis", "=", "0", ")", "else", ":", "proba", "=", "self", ".", "predict_cum_proba", "(", "X", ")", "class_index", "=", "np", ".", "sum", "(", "(", "proba", ">", "0.5", ")", ".", "astype", "(", "np", ".", "int", ")", ",", "axis", "=", "1", ")", "return", "self", ".", "classes_", ".", "take", "(", "class_index", ",", "axis", "=", "0", ")", "else", ":", "n_samples", "=", "proba", "[", "0", "]", ".", "shape", "[", "0", "]", "predictions", "=", "np", ".", "zeros", "(", "(", "n_samples", ",", "self", ".", "n_outputs_", ")", ")", "for", "k", "in", "range", "(", "self", ".", "n_outputs_", ")", ":", "if", "self", ".", "n_classes_", "<=", "2", ":", "proba", "=", "self", ".", "predict_proba", "(", "X", ")", "predictions", "[", ":", ",", "k", "]", "=", "self", ".", "classes_", "[", "k", "]", ".", "take", "(", "np", ".", "argmax", "(", "proba", "[", "k", "]", ",", "axis", "=", "1", ")", ",", "axis", "=", "0", ")", "else", ":", "proba", "=", "self", ".", "predict_cum_proba", "(", "X", ")", "class_index", "=", "np", ".", "sum", "(", "(", "proba", "[", "k", "]", ">", "0.5", ")", ".", "astype", "(", "np", ".", "int", ")", ",", "axis", "=", "1", ")", "predictions", "[", ":", ",", "k", "]", "=", "self", ".", "classes_", "[", "k", "]", ".", "take", "(", "class_index", ",", "axis", "=", "0", ")", "return", "predictions" ]
[ 304, 4 ]
[ 355, 30 ]
python
en
['en', 'it', 'en']
True
MonoRandomForestClassifier.predict_proba
(self, X)
Predict class probabilities for X. NOTE: We need to override parent method's predict() so we can allow for Kotlowski and Slowinski style monotone ensembling. NOTE: because these probabilities are calculated from the component binary classifiers, sometimes small negative numbers can result. The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : array of shape = [n_samples, n_classes], or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute `classes_`.
Predict class probabilities for X.
def predict_proba(self, X): """Predict class probabilities for X. NOTE: We need to override parent method's predict() so we can allow for Kotlowski and Slowinski style monotone ensembling. NOTE: because these probabilities are calculated from the component binary classifiers, sometimes small negative numbers can result. The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : array of shape = [n_samples, n_classes], or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute `classes_`. """ proba = super().predict_proba(X) # if self.n_classes_ > 2: # proba_cum = self.predict_cum_proba(X) # proba = np.zeros([X.shape[0], self.n_classes_]) # for i in range(self.n_classes_): # if i==0: # proba[:,i] = 1.-proba_cum[:,i] # elif i==self.n_classes_-1: # proba[:,i] = proba_cum[:,i-1] # else: # proba[:,i] = proba_cum[:,i-1]-proba_cum[:,i] # else: # binary # proba = super().predict_proba(X) return proba
[ "def", "predict_proba", "(", "self", ",", "X", ")", ":", "proba", "=", "super", "(", ")", ".", "predict_proba", "(", "X", ")", "# if self.n_classes_ > 2:", "# proba_cum = self.predict_cum_proba(X)", "# proba = np.zeros([X.shape[0], self.n_classes_])", "# for i in range(self.n_classes_):", "# if i==0:", "# proba[:,i] = 1.-proba_cum[:,i]", "# elif i==self.n_classes_-1:", "# proba[:,i] = proba_cum[:,i-1]", "# else:", "# proba[:,i] = proba_cum[:,i-1]-proba_cum[:,i]", "# else: # binary", "# proba = super().predict_proba(X)", "return", "proba" ]
[ 357, 4 ]
[ 398, 20 ]
python
en
['en', 'en', 'en']
True
MonoRandomForestClassifier.predict_cum_proba
(self, X)
Predict cumulative class probabilities for X. NOTE: This function should be used with care, as it returns the binary classifier ensemble component probabilities: - e.g. for y in {1,2,3,4} the returned probabilities are [P(y>1), P(y>2), P(y>3)] The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : ndarray of shape (n_samples, n_classes), or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`.
Predict cumulative class probabilities for X. NOTE: This function should be used with care, as it returns the binary classifier ensemble component probabilities: - e.g. for y in {1,2,3,4} the returned probabilities are [P(y>1), P(y>2), P(y>3)] The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : ndarray of shape (n_samples, n_classes), or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`.
def predict_cum_proba(self, X): """ Predict cumulative class probabilities for X. NOTE: This function should be used with care, as it returns the binary classifier ensemble component probabilities: - e.g. for y in {1,2,3,4} the returned probabilities are [P(y>1), P(y>2), P(y>3)] The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : ndarray of shape (n_samples, n_classes), or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`. """ # check_is_fitted(self) # Check data X = self._validate_X_predict(X) # Assign chunk of trees to jobs n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs) # avoid storing the output of every estimator by summing them here all_proba = [np.zeros((X.shape[0], j-1), dtype=np.float64) for j in np.atleast_1d(self.n_classes_)] lock = threading.Lock() # for e in self.estimators_: # print((e.predict_cum_proba(X)).shape[1]) # print(all_proba) Parallel(n_jobs=n_jobs, verbose=self.verbose, **_joblib_parallel_args(require="sharedmem"))( delayed(_accumulate_prediction)(e.predict_cum_proba, X, all_proba, lock) for e in self.estimators_) for proba in all_proba: proba /= len(self.estimators_) if len(all_proba) == 1: return all_proba[0] else: return all_proba
[ "def", "predict_cum_proba", "(", "self", ",", "X", ")", ":", "# check_is_fitted(self)", "# Check data", "X", "=", "self", ".", "_validate_X_predict", "(", "X", ")", "# Assign chunk of trees to jobs", "n_jobs", ",", "_", ",", "_", "=", "_partition_estimators", "(", "self", ".", "n_estimators", ",", "self", ".", "n_jobs", ")", "# avoid storing the output of every estimator by summing them here", "all_proba", "=", "[", "np", ".", "zeros", "(", "(", "X", ".", "shape", "[", "0", "]", ",", "j", "-", "1", ")", ",", "dtype", "=", "np", ".", "float64", ")", "for", "j", "in", "np", ".", "atleast_1d", "(", "self", ".", "n_classes_", ")", "]", "lock", "=", "threading", ".", "Lock", "(", ")", "# for e in self.estimators_:", "# print((e.predict_cum_proba(X)).shape[1])", "# print(all_proba)", "Parallel", "(", "n_jobs", "=", "n_jobs", ",", "verbose", "=", "self", ".", "verbose", ",", "*", "*", "_joblib_parallel_args", "(", "require", "=", "\"sharedmem\"", ")", ")", "(", "delayed", "(", "_accumulate_prediction", ")", "(", "e", ".", "predict_cum_proba", ",", "X", ",", "all_proba", ",", "lock", ")", "for", "e", "in", "self", ".", "estimators_", ")", "for", "proba", "in", "all_proba", ":", "proba", "/=", "len", "(", "self", ".", "estimators_", ")", "if", "len", "(", "all_proba", ")", "==", "1", ":", "return", "all_proba", "[", "0", "]", "else", ":", "return", "all_proba" ]
[ 400, 4 ]
[ 451, 28 ]
python
en
['en', 'error', 'th']
False
MonoRandomForestClassifier._set_oob_score
(self, X, y)
Compute out-of-bag score
Compute out-of-bag score
def _set_oob_score(self, X, y): """Compute out-of-bag score""" X = check_array(X, dtype=DTYPE, accept_sparse='csr') if self.n_classes_[0] > 2: n_classes_ = list( np.asarray( self.n_classes_) - 1) # CHANGED TO K-1 else: n_classes_ = self.n_classes_ n_samples = y.shape[0] n_samples_bootstrap = _get_n_samples_bootstrap( n_samples, self.max_samples ) oob_decision_function = [] oob_score = 0.0 predictions = [] for k in range(self.n_outputs_): predictions.append(np.zeros((n_samples, n_classes_[k]))) for estimator in self.estimators_: unsampled_indices = _generate_unsampled_indices( estimator.random_state, n_samples, n_samples_bootstrap) p_estimator = estimator.predict_cum_proba(X[unsampled_indices, :], check_input=False) if self.n_outputs_ == 1: p_estimator = [p_estimator] for k in range(self.n_outputs_): predictions[k][unsampled_indices, :] += p_estimator[k] for k in range(self.n_outputs_): if (predictions[k].sum(axis=1) == 0).any(): warn("Some inputs do not have OOB scores. " "This probably means too few trees were used " "to compute any reliable oob estimates.") decision = (predictions[k] / predictions[k].sum(axis=1)[:, np.newaxis]) oob_decision_function.append(decision) if self.n_classes_[0] <= 2: oob_score += np.mean(y[:, k] == np.argmax(predictions[k], axis=1), axis=0) else: class_index = np.sum( (predictions[k] > 0.5).astype( np.int), axis=1) oob_score += np.mean(y[:, k] == class_index, axis=0) if self.n_outputs_ == 1: self.oob_decision_function_ = oob_decision_function[0] else: self.oob_decision_function_ = oob_decision_function self.oob_score_ = oob_score / self.n_outputs_
[ "def", "_set_oob_score", "(", "self", ",", "X", ",", "y", ")", ":", "X", "=", "check_array", "(", "X", ",", "dtype", "=", "DTYPE", ",", "accept_sparse", "=", "'csr'", ")", "if", "self", ".", "n_classes_", "[", "0", "]", ">", "2", ":", "n_classes_", "=", "list", "(", "np", ".", "asarray", "(", "self", ".", "n_classes_", ")", "-", "1", ")", "# CHANGED TO K-1", "else", ":", "n_classes_", "=", "self", ".", "n_classes_", "n_samples", "=", "y", ".", "shape", "[", "0", "]", "n_samples_bootstrap", "=", "_get_n_samples_bootstrap", "(", "n_samples", ",", "self", ".", "max_samples", ")", "oob_decision_function", "=", "[", "]", "oob_score", "=", "0.0", "predictions", "=", "[", "]", "for", "k", "in", "range", "(", "self", ".", "n_outputs_", ")", ":", "predictions", ".", "append", "(", "np", ".", "zeros", "(", "(", "n_samples", ",", "n_classes_", "[", "k", "]", ")", ")", ")", "for", "estimator", "in", "self", ".", "estimators_", ":", "unsampled_indices", "=", "_generate_unsampled_indices", "(", "estimator", ".", "random_state", ",", "n_samples", ",", "n_samples_bootstrap", ")", "p_estimator", "=", "estimator", ".", "predict_cum_proba", "(", "X", "[", "unsampled_indices", ",", ":", "]", ",", "check_input", "=", "False", ")", "if", "self", ".", "n_outputs_", "==", "1", ":", "p_estimator", "=", "[", "p_estimator", "]", "for", "k", "in", "range", "(", "self", ".", "n_outputs_", ")", ":", "predictions", "[", "k", "]", "[", "unsampled_indices", ",", ":", "]", "+=", "p_estimator", "[", "k", "]", "for", "k", "in", "range", "(", "self", ".", "n_outputs_", ")", ":", "if", "(", "predictions", "[", "k", "]", ".", "sum", "(", "axis", "=", "1", ")", "==", "0", ")", ".", "any", "(", ")", ":", "warn", "(", "\"Some inputs do not have OOB scores. \"", "\"This probably means too few trees were used \"", "\"to compute any reliable oob estimates.\"", ")", "decision", "=", "(", "predictions", "[", "k", "]", "/", "predictions", "[", "k", "]", ".", "sum", "(", "axis", "=", "1", ")", "[", ":", ",", "np", ".", "newaxis", "]", ")", "oob_decision_function", ".", "append", "(", "decision", ")", "if", "self", ".", "n_classes_", "[", "0", "]", "<=", "2", ":", "oob_score", "+=", "np", ".", "mean", "(", "y", "[", ":", ",", "k", "]", "==", "np", ".", "argmax", "(", "predictions", "[", "k", "]", ",", "axis", "=", "1", ")", ",", "axis", "=", "0", ")", "else", ":", "class_index", "=", "np", ".", "sum", "(", "(", "predictions", "[", "k", "]", ">", "0.5", ")", ".", "astype", "(", "np", ".", "int", ")", ",", "axis", "=", "1", ")", "oob_score", "+=", "np", ".", "mean", "(", "y", "[", ":", ",", "k", "]", "==", "class_index", ",", "axis", "=", "0", ")", "if", "self", ".", "n_outputs_", "==", "1", ":", "self", ".", "oob_decision_function_", "=", "oob_decision_function", "[", "0", "]", "else", ":", "self", ".", "oob_decision_function_", "=", "oob_decision_function", "self", ".", "oob_score_", "=", "oob_score", "/", "self", ".", "n_outputs_" ]
[ 524, 4 ]
[ 582, 53 ]
python
en
['en', 'en', 'en']
True
make_hashable
(value)
Attempt to make value hashable or raise a TypeError if it fails. The returned value should generate the same hash for equal values.
Attempt to make value hashable or raise a TypeError if it fails.
def make_hashable(value): """ Attempt to make value hashable or raise a TypeError if it fails. The returned value should generate the same hash for equal values. """ if isinstance(value, dict): return tuple([ (key, make_hashable(nested_value)) for key, nested_value in sorted(value.items()) ]) # Try hash to avoid converting a hashable iterable (e.g. string, frozenset) # to a tuple. try: hash(value) except TypeError: if is_iterable(value): return tuple(map(make_hashable, value)) # Non-hashable, non-iterable. raise return value
[ "def", "make_hashable", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "tuple", "(", "[", "(", "key", ",", "make_hashable", "(", "nested_value", ")", ")", "for", "key", ",", "nested_value", "in", "sorted", "(", "value", ".", "items", "(", ")", ")", "]", ")", "# Try hash to avoid converting a hashable iterable (e.g. string, frozenset)", "# to a tuple.", "try", ":", "hash", "(", "value", ")", "except", "TypeError", ":", "if", "is_iterable", "(", "value", ")", ":", "return", "tuple", "(", "map", "(", "make_hashable", ",", "value", ")", ")", "# Non-hashable, non-iterable.", "raise", "return", "value" ]
[ 3, 0 ]
[ 23, 16 ]
python
en
['en', 'error', 'th']
False
last_arg_byref
(args)
Return the last C argument's value by reference.
Return the last C argument's value by reference.
def last_arg_byref(args): "Return the last C argument's value by reference." return args[-1]._obj.value
[ "def", "last_arg_byref", "(", "args", ")", ":", "return", "args", "[", "-", "1", "]", ".", "_obj", ".", "value" ]
[ 14, 0 ]
[ 16, 30 ]
python
en
['en', 'en', 'en']
True
check_dbl
(result, func, cargs)
Check the status code and returns the double value passed in by reference.
Check the status code and returns the double value passed in by reference.
def check_dbl(result, func, cargs): "Check the status code and returns the double value passed in by reference." # Checking the status code if result != 1: return None # Double passed in by reference, return its value. return last_arg_byref(cargs)
[ "def", "check_dbl", "(", "result", ",", "func", ",", "cargs", ")", ":", "# Checking the status code", "if", "result", "!=", "1", ":", "return", "None", "# Double passed in by reference, return its value.", "return", "last_arg_byref", "(", "cargs", ")" ]
[ 19, 0 ]
[ 25, 32 ]
python
en
['en', 'en', 'en']
True
check_geom
(result, func, cargs)
Error checking on routines that return Geometries.
Error checking on routines that return Geometries.
def check_geom(result, func, cargs): "Error checking on routines that return Geometries." if not result: raise GEOSException('Error encountered checking Geometry returned from GEOS C function "%s".' % func.__name__) return result
[ "def", "check_geom", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "not", "result", ":", "raise", "GEOSException", "(", "'Error encountered checking Geometry returned from GEOS C function \"%s\".'", "%", "func", ".", "__name__", ")", "return", "result" ]
[ 28, 0 ]
[ 32, 17 ]
python
en
['en', 'el-Latn', 'en']
True
check_minus_one
(result, func, cargs)
Error checking on routines that should not return -1.
Error checking on routines that should not return -1.
def check_minus_one(result, func, cargs): "Error checking on routines that should not return -1." if result == -1: raise GEOSException('Error encountered in GEOS C function "%s".' % func.__name__) else: return result
[ "def", "check_minus_one", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "result", "==", "-", "1", ":", "raise", "GEOSException", "(", "'Error encountered in GEOS C function \"%s\".'", "%", "func", ".", "__name__", ")", "else", ":", "return", "result" ]
[ 35, 0 ]
[ 40, 21 ]
python
en
['en', 'en', 'en']
True
check_predicate
(result, func, cargs)
Error checking for unary/binary predicate functions.
Error checking for unary/binary predicate functions.
def check_predicate(result, func, cargs): "Error checking for unary/binary predicate functions." if result == 1: return True elif result == 0: return False else: raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__)
[ "def", "check_predicate", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "result", "==", "1", ":", "return", "True", "elif", "result", "==", "0", ":", "return", "False", "else", ":", "raise", "GEOSException", "(", "'Error encountered on GEOS C predicate function \"%s\".'", "%", "func", ".", "__name__", ")" ]
[ 43, 0 ]
[ 50, 99 ]
python
en
['en', 'en', 'en']
True
check_sized_string
(result, func, cargs)
Error checking for routines that return explicitly sized strings. This frees the memory allocated by GEOS at the result pointer.
Error checking for routines that return explicitly sized strings.
def check_sized_string(result, func, cargs): """ Error checking for routines that return explicitly sized strings. This frees the memory allocated by GEOS at the result pointer. """ if not result: raise GEOSException('Invalid string pointer returned by GEOS C function "%s"' % func.__name__) # A c_size_t object is passed in by reference for the second # argument on these routines, and its needed to determine the # correct size. s = string_at(result, last_arg_byref(cargs)) # Freeing the memory allocated within GEOS free(result) return s
[ "def", "check_sized_string", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "not", "result", ":", "raise", "GEOSException", "(", "'Invalid string pointer returned by GEOS C function \"%s\"'", "%", "func", ".", "__name__", ")", "# A c_size_t object is passed in by reference for the second", "# argument on these routines, and its needed to determine the", "# correct size.", "s", "=", "string_at", "(", "result", ",", "last_arg_byref", "(", "cargs", ")", ")", "# Freeing the memory allocated within GEOS", "free", "(", "result", ")", "return", "s" ]
[ 53, 0 ]
[ 67, 12 ]
python
en
['en', 'error', 'th']
False
check_string
(result, func, cargs)
Error checking for routines that return strings. This frees the memory allocated by GEOS at the result pointer.
Error checking for routines that return strings.
def check_string(result, func, cargs): """ Error checking for routines that return strings. This frees the memory allocated by GEOS at the result pointer. """ if not result: raise GEOSException('Error encountered checking string return value in GEOS C function "%s".' % func.__name__) # Getting the string value at the pointer address. s = string_at(result) # Freeing the memory allocated within GEOS free(result) return s
[ "def", "check_string", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "not", "result", ":", "raise", "GEOSException", "(", "'Error encountered checking string return value in GEOS C function \"%s\".'", "%", "func", ".", "__name__", ")", "# Getting the string value at the pointer address.", "s", "=", "string_at", "(", "result", ")", "# Freeing the memory allocated within GEOS", "free", "(", "result", ")", "return", "s" ]
[ 70, 0 ]
[ 82, 12 ]
python
en
['en', 'error', 'th']
False
Storage.__init__
(self, session, model_class, key_name, key_value, property_name)
Constructor for Storage. Args: session: An instance of :class:`sqlalchemy.orm.Session`. model_class: SQLAlchemy declarative mapping. key_name: string, key name for the entity that has the credentials key_value: key value for the entity that has the credentials property_name: A string indicating which property on the ``model_class`` to store the credentials. This property must be a :class:`CredentialsType` column.
Constructor for Storage.
def __init__(self, session, model_class, key_name, key_value, property_name): """Constructor for Storage. Args: session: An instance of :class:`sqlalchemy.orm.Session`. model_class: SQLAlchemy declarative mapping. key_name: string, key name for the entity that has the credentials key_value: key value for the entity that has the credentials property_name: A string indicating which property on the ``model_class`` to store the credentials. This property must be a :class:`CredentialsType` column. """ super(Storage, self).__init__() self.session = session self.model_class = model_class self.key_name = key_name self.key_value = key_value self.property_name = property_name
[ "def", "__init__", "(", "self", ",", "session", ",", "model_class", ",", "key_name", ",", "key_value", ",", "property_name", ")", ":", "super", "(", "Storage", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "session", "=", "session", "self", ".", "model_class", "=", "model_class", "self", ".", "key_name", "=", "key_name", "self", ".", "key_value", "=", "key_value", "self", ".", "property_name", "=", "property_name" ]
[ 113, 4 ]
[ 133, 42 ]
python
en
['da', 'en', 'en']
True
Storage.locked_get
(self)
Retrieve stored credential. Returns: A :class:`oauth2client.Credentials` instance or `None`.
Retrieve stored credential.
def locked_get(self): """Retrieve stored credential. Returns: A :class:`oauth2client.Credentials` instance or `None`. """ filters = {self.key_name: self.key_value} query = self.session.query(self.model_class).filter_by(**filters) entity = query.first() if entity: credential = getattr(entity, self.property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self) return credential else: return None
[ "def", "locked_get", "(", "self", ")", ":", "filters", "=", "{", "self", ".", "key_name", ":", "self", ".", "key_value", "}", "query", "=", "self", ".", "session", ".", "query", "(", "self", ".", "model_class", ")", ".", "filter_by", "(", "*", "*", "filters", ")", "entity", "=", "query", ".", "first", "(", ")", "if", "entity", ":", "credential", "=", "getattr", "(", "entity", ",", "self", ".", "property_name", ")", "if", "credential", "and", "hasattr", "(", "credential", ",", "'set_store'", ")", ":", "credential", ".", "set_store", "(", "self", ")", "return", "credential", "else", ":", "return", "None" ]
[ 135, 4 ]
[ 151, 23 ]
python
en
['en', 'pt', 'en']
True
Storage.locked_put
(self, credentials)
Write a credentials to the SQLAlchemy datastore. Args: credentials: :class:`oauth2client.Credentials`
Write a credentials to the SQLAlchemy datastore.
def locked_put(self, credentials): """Write a credentials to the SQLAlchemy datastore. Args: credentials: :class:`oauth2client.Credentials` """ filters = {self.key_name: self.key_value} query = self.session.query(self.model_class).filter_by(**filters) entity = query.first() if not entity: entity = self.model_class(**filters) setattr(entity, self.property_name, credentials) self.session.add(entity)
[ "def", "locked_put", "(", "self", ",", "credentials", ")", ":", "filters", "=", "{", "self", ".", "key_name", ":", "self", ".", "key_value", "}", "query", "=", "self", ".", "session", ".", "query", "(", "self", ".", "model_class", ")", ".", "filter_by", "(", "*", "*", "filters", ")", "entity", "=", "query", ".", "first", "(", ")", "if", "not", "entity", ":", "entity", "=", "self", ".", "model_class", "(", "*", "*", "filters", ")", "setattr", "(", "entity", ",", "self", ".", "property_name", ",", "credentials", ")", "self", ".", "session", ".", "add", "(", "entity", ")" ]
[ 153, 4 ]
[ 167, 32 ]
python
en
['en', 'en', 'en']
True
Storage.locked_delete
(self)
Delete credentials from the SQLAlchemy datastore.
Delete credentials from the SQLAlchemy datastore.
def locked_delete(self): """Delete credentials from the SQLAlchemy datastore.""" filters = {self.key_name: self.key_value} self.session.query(self.model_class).filter_by(**filters).delete()
[ "def", "locked_delete", "(", "self", ")", ":", "filters", "=", "{", "self", ".", "key_name", ":", "self", ".", "key_value", "}", "self", ".", "session", ".", "query", "(", "self", ".", "model_class", ")", ".", "filter_by", "(", "*", "*", "filters", ")", ".", "delete", "(", ")" ]
[ 169, 4 ]
[ 172, 74 ]
python
en
['en', 'en', 'en']
True
_find_all_simple
(path)
Find all files under 'path'
Find all files under 'path'
def _find_all_simple(path): """ Find all files under 'path' """ results = ( os.path.join(base, file) for base, dirs, files in os.walk(path, followlinks=True) for file in files ) return filter(os.path.isfile, results)
[ "def", "_find_all_simple", "(", "path", ")", ":", "results", "=", "(", "os", ".", "path", ".", "join", "(", "base", ",", "file", ")", "for", "base", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ",", "followlinks", "=", "True", ")", "for", "file", "in", "files", ")", "return", "filter", "(", "os", ".", "path", ".", "isfile", ",", "results", ")" ]
[ 155, 0 ]
[ 164, 42 ]
python
en
['en', 'error', 'th']
False
findall
(dir=os.curdir)
Find all files under 'dir' and return the list of full filenames. Unless dir is '.', return full filenames with dir prepended.
Find all files under 'dir' and return the list of full filenames. Unless dir is '.', return full filenames with dir prepended.
def findall(dir=os.curdir): """ Find all files under 'dir' and return the list of full filenames. Unless dir is '.', return full filenames with dir prepended. """ files = _find_all_simple(dir) if dir == os.curdir: make_rel = functools.partial(os.path.relpath, start=dir) files = map(make_rel, files) return list(files)
[ "def", "findall", "(", "dir", "=", "os", ".", "curdir", ")", ":", "files", "=", "_find_all_simple", "(", "dir", ")", "if", "dir", "==", "os", ".", "curdir", ":", "make_rel", "=", "functools", ".", "partial", "(", "os", ".", "path", ".", "relpath", ",", "start", "=", "dir", ")", "files", "=", "map", "(", "make_rel", ",", "files", ")", "return", "list", "(", "files", ")" ]
[ 167, 0 ]
[ 176, 22 ]
python
en
['en', 'error', 'th']
False
PackageFinder.find
(cls, where='.', exclude=(), include=('*',))
Return a list all Python packages found within directory 'where' 'where' is the root directory which will be searched for packages. It should be supplied as a "cross-platform" (i.e. URL-style) path; it will be converted to the appropriate local path syntax. 'exclude' is a sequence of package names to exclude; '*' can be used as a wildcard in the names, such that 'foo.*' will exclude all subpackages of 'foo' (but not 'foo' itself). 'include' is a sequence of package names to include. If it's specified, only the named packages will be included. If it's not specified, all found packages will be included. 'include' can contain shell style wildcard patterns just like 'exclude'.
Return a list all Python packages found within directory 'where'
def find(cls, where='.', exclude=(), include=('*',)): """Return a list all Python packages found within directory 'where' 'where' is the root directory which will be searched for packages. It should be supplied as a "cross-platform" (i.e. URL-style) path; it will be converted to the appropriate local path syntax. 'exclude' is a sequence of package names to exclude; '*' can be used as a wildcard in the names, such that 'foo.*' will exclude all subpackages of 'foo' (but not 'foo' itself). 'include' is a sequence of package names to include. If it's specified, only the named packages will be included. If it's not specified, all found packages will be included. 'include' can contain shell style wildcard patterns just like 'exclude'. """ return list(cls._find_packages_iter( convert_path(where), cls._build_filter('ez_setup', '*__pycache__', *exclude), cls._build_filter(*include)))
[ "def", "find", "(", "cls", ",", "where", "=", "'.'", ",", "exclude", "=", "(", ")", ",", "include", "=", "(", "'*'", ",", ")", ")", ":", "return", "list", "(", "cls", ".", "_find_packages_iter", "(", "convert_path", "(", "where", ")", ",", "cls", ".", "_build_filter", "(", "'ez_setup'", ",", "'*__pycache__'", ",", "*", "exclude", ")", ",", "cls", ".", "_build_filter", "(", "*", "include", ")", ")", ")" ]
[ 39, 4 ]
[ 59, 41 ]
python
en
['en', 'en', 'en']
True
PackageFinder._find_packages_iter
(cls, where, exclude, include)
All the packages found in 'where' that pass the 'include' filter, but not the 'exclude' filter.
All the packages found in 'where' that pass the 'include' filter, but not the 'exclude' filter.
def _find_packages_iter(cls, where, exclude, include): """ All the packages found in 'where' that pass the 'include' filter, but not the 'exclude' filter. """ for root, dirs, files in os.walk(where, followlinks=True): # Copy dirs to iterate over it, then empty dirs. all_dirs = dirs[:] dirs[:] = [] for dir in all_dirs: full_path = os.path.join(root, dir) rel_path = os.path.relpath(full_path, where) package = rel_path.replace(os.path.sep, '.') # Skip directory trees that are not valid packages if ('.' in dir or not cls._looks_like_package(full_path)): continue # Should this package be included? if include(package) and not exclude(package): yield package # Keep searching subdirectories, as there may be more packages # down there, even if the parent was excluded. dirs.append(dir)
[ "def", "_find_packages_iter", "(", "cls", ",", "where", ",", "exclude", ",", "include", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "where", ",", "followlinks", "=", "True", ")", ":", "# Copy dirs to iterate over it, then empty dirs.", "all_dirs", "=", "dirs", "[", ":", "]", "dirs", "[", ":", "]", "=", "[", "]", "for", "dir", "in", "all_dirs", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "dir", ")", "rel_path", "=", "os", ".", "path", ".", "relpath", "(", "full_path", ",", "where", ")", "package", "=", "rel_path", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'.'", ")", "# Skip directory trees that are not valid packages", "if", "(", "'.'", "in", "dir", "or", "not", "cls", ".", "_looks_like_package", "(", "full_path", ")", ")", ":", "continue", "# Should this package be included?", "if", "include", "(", "package", ")", "and", "not", "exclude", "(", "package", ")", ":", "yield", "package", "# Keep searching subdirectories, as there may be more packages", "# down there, even if the parent was excluded.", "dirs", ".", "append", "(", "dir", ")" ]
[ 62, 4 ]
[ 87, 32 ]
python
en
['en', 'error', 'th']
False
PackageFinder._looks_like_package
(path)
Does a directory look like a package?
Does a directory look like a package?
def _looks_like_package(path): """Does a directory look like a package?""" return os.path.isfile(os.path.join(path, '__init__.py'))
[ "def", "_looks_like_package", "(", "path", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'__init__.py'", ")", ")" ]
[ 90, 4 ]
[ 92, 64 ]
python
en
['en', 'en', 'en']
True
PackageFinder._build_filter
(*patterns)
Given a list of patterns, return a callable that will be true only if the input matches at least one of the patterns.
Given a list of patterns, return a callable that will be true only if the input matches at least one of the patterns.
def _build_filter(*patterns): """ Given a list of patterns, return a callable that will be true only if the input matches at least one of the patterns. """ return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
[ "def", "_build_filter", "(", "*", "patterns", ")", ":", "return", "lambda", "name", ":", "any", "(", "fnmatchcase", "(", "name", ",", "pat", "=", "pat", ")", "for", "pat", "in", "patterns", ")" ]
[ 95, 4 ]
[ 100, 79 ]
python
en
['en', 'error', 'th']
False
Command.__init__
(self, dist, **kw)
Construct the command for dist, updating vars(self) with any keyword parameters.
Construct the command for dist, updating vars(self) with any keyword parameters.
def __init__(self, dist, **kw): """ Construct the command for dist, updating vars(self) with any keyword parameters. """ _Command.__init__(self, dist) vars(self).update(kw)
[ "def", "__init__", "(", "self", ",", "dist", ",", "*", "*", "kw", ")", ":", "_Command", ".", "__init__", "(", "self", ",", "dist", ")", "vars", "(", "self", ")", ".", "update", "(", "kw", ")" ]
[ 141, 4 ]
[ 147, 29 ]
python
en
['en', 'error', 'th']
False
Paginator.validate_number
(self, number)
Validate the given 1-based page number.
Validate the given 1-based page number.
def validate_number(self, number): """Validate the given 1-based page number.""" try: if isinstance(number, float) and not number.is_integer(): raise ValueError number = int(number) except (TypeError, ValueError): raise PageNotAnInteger(_('That page number is not an integer')) if number < 1: raise EmptyPage(_('That page number is less than 1')) if number > self.num_pages: if number == 1 and self.allow_empty_first_page: pass else: raise EmptyPage(_('That page contains no results')) return number
[ "def", "validate_number", "(", "self", ",", "number", ")", ":", "try", ":", "if", "isinstance", "(", "number", ",", "float", ")", "and", "not", "number", ".", "is_integer", "(", ")", ":", "raise", "ValueError", "number", "=", "int", "(", "number", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "PageNotAnInteger", "(", "_", "(", "'That page number is not an integer'", ")", ")", "if", "number", "<", "1", ":", "raise", "EmptyPage", "(", "_", "(", "'That page number is less than 1'", ")", ")", "if", "number", ">", "self", ".", "num_pages", ":", "if", "number", "==", "1", "and", "self", ".", "allow_empty_first_page", ":", "pass", "else", ":", "raise", "EmptyPage", "(", "_", "(", "'That page contains no results'", ")", ")", "return", "number" ]
[ 43, 4 ]
[ 58, 21 ]
python
en
['en', 'en', 'en']
True
Paginator.get_page
(self, number)
Return a valid page, even if the page argument isn't a number or isn't in range.
Return a valid page, even if the page argument isn't a number or isn't in range.
def get_page(self, number): """ Return a valid page, even if the page argument isn't a number or isn't in range. """ try: number = self.validate_number(number) except PageNotAnInteger: number = 1 except EmptyPage: number = self.num_pages return self.page(number)
[ "def", "get_page", "(", "self", ",", "number", ")", ":", "try", ":", "number", "=", "self", ".", "validate_number", "(", "number", ")", "except", "PageNotAnInteger", ":", "number", "=", "1", "except", "EmptyPage", ":", "number", "=", "self", ".", "num_pages", "return", "self", ".", "page", "(", "number", ")" ]
[ 60, 4 ]
[ 71, 32 ]
python
en
['en', 'error', 'th']
False
Paginator.page
(self, number)
Return a Page object for the given 1-based page number.
Return a Page object for the given 1-based page number.
def page(self, number): """Return a Page object for the given 1-based page number.""" number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count return self._get_page(self.object_list[bottom:top], number, self)
[ "def", "page", "(", "self", ",", "number", ")", ":", "number", "=", "self", ".", "validate_number", "(", "number", ")", "bottom", "=", "(", "number", "-", "1", ")", "*", "self", ".", "per_page", "top", "=", "bottom", "+", "self", ".", "per_page", "if", "top", "+", "self", ".", "orphans", ">=", "self", ".", "count", ":", "top", "=", "self", ".", "count", "return", "self", ".", "_get_page", "(", "self", ".", "object_list", "[", "bottom", ":", "top", "]", ",", "number", ",", "self", ")" ]
[ 73, 4 ]
[ 80, 73 ]
python
en
['en', 'en', 'en']
True
Paginator._get_page
(self, *args, **kwargs)
Return an instance of a single page. This hook can be used by subclasses to use an alternative to the standard :cls:`Page` object.
Return an instance of a single page.
def _get_page(self, *args, **kwargs): """ Return an instance of a single page. This hook can be used by subclasses to use an alternative to the standard :cls:`Page` object. """ return Page(*args, **kwargs)
[ "def", "_get_page", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "Page", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 82, 4 ]
[ 89, 36 ]
python
en
['en', 'error', 'th']
False
Paginator.count
(self)
Return the total number of objects, across all pages.
Return the total number of objects, across all pages.
def count(self): """Return the total number of objects, across all pages.""" c = getattr(self.object_list, 'count', None) if callable(c) and not inspect.isbuiltin(c) and method_has_no_args(c): return c() return len(self.object_list)
[ "def", "count", "(", "self", ")", ":", "c", "=", "getattr", "(", "self", ".", "object_list", ",", "'count'", ",", "None", ")", "if", "callable", "(", "c", ")", "and", "not", "inspect", ".", "isbuiltin", "(", "c", ")", "and", "method_has_no_args", "(", "c", ")", ":", "return", "c", "(", ")", "return", "len", "(", "self", ".", "object_list", ")" ]
[ 92, 4 ]
[ 97, 36 ]
python
en
['en', 'en', 'en']
True
Paginator.num_pages
(self)
Return the total number of pages.
Return the total number of pages.
def num_pages(self): """Return the total number of pages.""" if self.count == 0 and not self.allow_empty_first_page: return 0 hits = max(1, self.count - self.orphans) return ceil(hits / self.per_page)
[ "def", "num_pages", "(", "self", ")", ":", "if", "self", ".", "count", "==", "0", "and", "not", "self", ".", "allow_empty_first_page", ":", "return", "0", "hits", "=", "max", "(", "1", ",", "self", ".", "count", "-", "self", ".", "orphans", ")", "return", "ceil", "(", "hits", "/", "self", ".", "per_page", ")" ]
[ 100, 4 ]
[ 105, 41 ]
python
en
['en', 'en', 'en']
True
Paginator.page_range
(self)
Return a 1-based range of pages for iterating through within a template for loop.
Return a 1-based range of pages for iterating through within a template for loop.
def page_range(self): """ Return a 1-based range of pages for iterating through within a template for loop. """ return range(1, self.num_pages + 1)
[ "def", "page_range", "(", "self", ")", ":", "return", "range", "(", "1", ",", "self", ".", "num_pages", "+", "1", ")" ]
[ 108, 4 ]
[ 113, 43 ]
python
en
['en', 'error', 'th']
False
Paginator._check_object_list_is_ordered
(self)
Warn if self.object_list is unordered (typically a QuerySet).
Warn if self.object_list is unordered (typically a QuerySet).
def _check_object_list_is_ordered(self): """ Warn if self.object_list is unordered (typically a QuerySet). """ ordered = getattr(self.object_list, 'ordered', None) if ordered is not None and not ordered: obj_list_repr = ( '{} {}'.format(self.object_list.model, self.object_list.__class__.__name__) if hasattr(self.object_list, 'model') else '{!r}'.format(self.object_list) ) warnings.warn( 'Pagination may yield inconsistent results with an unordered ' 'object_list: {}.'.format(obj_list_repr), UnorderedObjectListWarning, stacklevel=3 )
[ "def", "_check_object_list_is_ordered", "(", "self", ")", ":", "ordered", "=", "getattr", "(", "self", ".", "object_list", ",", "'ordered'", ",", "None", ")", "if", "ordered", "is", "not", "None", "and", "not", "ordered", ":", "obj_list_repr", "=", "(", "'{} {}'", ".", "format", "(", "self", ".", "object_list", ".", "model", ",", "self", ".", "object_list", ".", "__class__", ".", "__name__", ")", "if", "hasattr", "(", "self", ".", "object_list", ",", "'model'", ")", "else", "'{!r}'", ".", "format", "(", "self", ".", "object_list", ")", ")", "warnings", ".", "warn", "(", "'Pagination may yield inconsistent results with an unordered '", "'object_list: {}.'", ".", "format", "(", "obj_list_repr", ")", ",", "UnorderedObjectListWarning", ",", "stacklevel", "=", "3", ")" ]
[ 115, 4 ]
[ 131, 13 ]
python
en
['en', 'error', 'th']
False
Paginator.get_elided_page_range
(self, number=1, *, on_each_side=3, on_ends=2)
Return a 1-based range of pages with some values elided. If the page range is larger than a given size, the whole range is not provided and a compact form is returned instead, e.g. for a paginator with 50 pages, if page 43 were the current page, the output, with the default arguments, would be: 1, 2, …, 40, 41, 42, 43, 44, 45, 46, …, 49, 50.
Return a 1-based range of pages with some values elided.
def get_elided_page_range(self, number=1, *, on_each_side=3, on_ends=2): """ Return a 1-based range of pages with some values elided. If the page range is larger than a given size, the whole range is not provided and a compact form is returned instead, e.g. for a paginator with 50 pages, if page 43 were the current page, the output, with the default arguments, would be: 1, 2, …, 40, 41, 42, 43, 44, 45, 46, …, 49, 50. """ number = self.validate_number(number) if self.num_pages <= (on_each_side + on_ends) * 2: yield from self.page_range return if number > (1 + on_each_side + on_ends) + 1: yield from range(1, on_ends + 1) yield self.ELLIPSIS yield from range(number - on_each_side, number + 1) else: yield from range(1, number + 1) if number < (self.num_pages - on_each_side - on_ends) - 1: yield from range(number + 1, number + on_each_side + 1) yield self.ELLIPSIS yield from range(self.num_pages - on_ends + 1, self.num_pages + 1) else: yield from range(number + 1, self.num_pages + 1)
[ "def", "get_elided_page_range", "(", "self", ",", "number", "=", "1", ",", "*", ",", "on_each_side", "=", "3", ",", "on_ends", "=", "2", ")", ":", "number", "=", "self", ".", "validate_number", "(", "number", ")", "if", "self", ".", "num_pages", "<=", "(", "on_each_side", "+", "on_ends", ")", "*", "2", ":", "yield", "from", "self", ".", "page_range", "return", "if", "number", ">", "(", "1", "+", "on_each_side", "+", "on_ends", ")", "+", "1", ":", "yield", "from", "range", "(", "1", ",", "on_ends", "+", "1", ")", "yield", "self", ".", "ELLIPSIS", "yield", "from", "range", "(", "number", "-", "on_each_side", ",", "number", "+", "1", ")", "else", ":", "yield", "from", "range", "(", "1", ",", "number", "+", "1", ")", "if", "number", "<", "(", "self", ".", "num_pages", "-", "on_each_side", "-", "on_ends", ")", "-", "1", ":", "yield", "from", "range", "(", "number", "+", "1", ",", "number", "+", "on_each_side", "+", "1", ")", "yield", "self", ".", "ELLIPSIS", "yield", "from", "range", "(", "self", ".", "num_pages", "-", "on_ends", "+", "1", ",", "self", ".", "num_pages", "+", "1", ")", "else", ":", "yield", "from", "range", "(", "number", "+", "1", ",", "self", ".", "num_pages", "+", "1", ")" ]
[ 133, 4 ]
[ 162, 60 ]
python
en
['en', 'error', 'th']
False