id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
250,900 | eeue56/PyChat.js | pychatjs/server/user_server.py | User.change_name | def change_name(self, username):
""" changes the username to given username, throws exception if username used """
self.release_name()
try:
self.server.register_name(username)
except UsernameInUseException:
logging.log(', '.join(self.server.registered_names))
self.server.register_name(self.name)
raise
self.name = username | python | def change_name(self, username):
""" changes the username to given username, throws exception if username used """
self.release_name()
try:
self.server.register_name(username)
except UsernameInUseException:
logging.log(', '.join(self.server.registered_names))
self.server.register_name(self.name)
raise
self.name = username | [
"def",
"change_name",
"(",
"self",
",",
"username",
")",
":",
"self",
".",
"release_name",
"(",
")",
"try",
":",
"self",
".",
"server",
".",
"register_name",
"(",
"username",
")",
"except",
"UsernameInUseException",
":",
"logging",
".",
"log",
"(",
"', '",
".",
"join",
"(",
"self",
".",
"server",
".",
"registered_names",
")",
")",
"self",
".",
"server",
".",
"register_name",
"(",
"self",
".",
"name",
")",
"raise",
"self",
".",
"name",
"=",
"username"
] | changes the username to given username, throws exception if username used | [
"changes",
"the",
"username",
"to",
"given",
"username",
"throws",
"exception",
"if",
"username",
"used"
] | 45056de6f988350c90a6dbe674459a4affde8abc | https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/user_server.py#L28-L39 |
250,901 | eeue56/PyChat.js | pychatjs/server/user_server.py | UserServer.register_name | def register_name(self, username):
""" register a name """
if self.is_username_used(username):
raise UsernameInUseException('Username {username} already in use!'.format(username=username))
self.registered_names.append(username) | python | def register_name(self, username):
""" register a name """
if self.is_username_used(username):
raise UsernameInUseException('Username {username} already in use!'.format(username=username))
self.registered_names.append(username) | [
"def",
"register_name",
"(",
"self",
",",
"username",
")",
":",
"if",
"self",
".",
"is_username_used",
"(",
"username",
")",
":",
"raise",
"UsernameInUseException",
"(",
"'Username {username} already in use!'",
".",
"format",
"(",
"username",
"=",
"username",
")",
")",
"self",
".",
"registered_names",
".",
"append",
"(",
"username",
")"
] | register a name | [
"register",
"a",
"name"
] | 45056de6f988350c90a6dbe674459a4affde8abc | https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/user_server.py#L59-L63 |
250,902 | eeue56/PyChat.js | pychatjs/server/user_server.py | UserServer.release_name | def release_name(self, username):
""" release a name and add it to the temp list """
self.temp_names.append(username)
if self.is_username_used(username):
self.registered_names.remove(username) | python | def release_name(self, username):
""" release a name and add it to the temp list """
self.temp_names.append(username)
if self.is_username_used(username):
self.registered_names.remove(username) | [
"def",
"release_name",
"(",
"self",
",",
"username",
")",
":",
"self",
".",
"temp_names",
".",
"append",
"(",
"username",
")",
"if",
"self",
".",
"is_username_used",
"(",
"username",
")",
":",
"self",
".",
"registered_names",
".",
"remove",
"(",
"username",
")"
] | release a name and add it to the temp list | [
"release",
"a",
"name",
"and",
"add",
"it",
"to",
"the",
"temp",
"list"
] | 45056de6f988350c90a6dbe674459a4affde8abc | https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/user_server.py#L66-L70 |
250,903 | qzmfranklin/easyshell | easyshell/basic_shell.py | BasicShell._do_exit | def _do_exit(self, cmd, args):
"""\
Exit shell.
exit | C-D Exit to the parent shell.
exit root | end Exit to the root shell.
exit all Exit to the command line.
"""
if cmd == 'end':
if not args:
return 'root'
else:
self.stderr.write(textwrap.dedent('''\
end: unrecognized arguments: {}
''')).format(args)
# Hereafter, cmd == 'exit'.
if not args:
return True
if len(args) > 1:
self.stderr.write(textwrap.dedent('''\
exit: too many arguments: {}
''')).format(args)
exit_directive = args[0]
if exit_directive == 'root':
return 'root'
if exit_directive == 'all':
return 'all'
self.stderr.write(textwrap.dedent('''\
exit: unrecognized arguments: {}
''')).format(args) | python | def _do_exit(self, cmd, args):
"""\
Exit shell.
exit | C-D Exit to the parent shell.
exit root | end Exit to the root shell.
exit all Exit to the command line.
"""
if cmd == 'end':
if not args:
return 'root'
else:
self.stderr.write(textwrap.dedent('''\
end: unrecognized arguments: {}
''')).format(args)
# Hereafter, cmd == 'exit'.
if not args:
return True
if len(args) > 1:
self.stderr.write(textwrap.dedent('''\
exit: too many arguments: {}
''')).format(args)
exit_directive = args[0]
if exit_directive == 'root':
return 'root'
if exit_directive == 'all':
return 'all'
self.stderr.write(textwrap.dedent('''\
exit: unrecognized arguments: {}
''')).format(args) | [
"def",
"_do_exit",
"(",
"self",
",",
"cmd",
",",
"args",
")",
":",
"if",
"cmd",
"==",
"'end'",
":",
"if",
"not",
"args",
":",
"return",
"'root'",
"else",
":",
"self",
".",
"stderr",
".",
"write",
"(",
"textwrap",
".",
"dedent",
"(",
"'''\\\n end: unrecognized arguments: {}\n '''",
")",
")",
".",
"format",
"(",
"args",
")",
"# Hereafter, cmd == 'exit'.",
"if",
"not",
"args",
":",
"return",
"True",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"self",
".",
"stderr",
".",
"write",
"(",
"textwrap",
".",
"dedent",
"(",
"'''\\\n exit: too many arguments: {}\n '''",
")",
")",
".",
"format",
"(",
"args",
")",
"exit_directive",
"=",
"args",
"[",
"0",
"]",
"if",
"exit_directive",
"==",
"'root'",
":",
"return",
"'root'",
"if",
"exit_directive",
"==",
"'all'",
":",
"return",
"'all'",
"self",
".",
"stderr",
".",
"write",
"(",
"textwrap",
".",
"dedent",
"(",
"'''\\\n exit: unrecognized arguments: {}\n '''",
")",
")",
".",
"format",
"(",
"args",
")"
] | \
Exit shell.
exit | C-D Exit to the parent shell.
exit root | end Exit to the root shell.
exit all Exit to the command line. | [
"\\",
"Exit",
"shell",
".",
"exit",
"|",
"C",
"-",
"D",
"Exit",
"to",
"the",
"parent",
"shell",
".",
"exit",
"root",
"|",
"end",
"Exit",
"to",
"the",
"root",
"shell",
".",
"exit",
"all",
"Exit",
"to",
"the",
"command",
"line",
"."
] | 00c2e90e7767d32e7e127fc8c6875845aa308295 | https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/basic_shell.py#L27-L56 |
250,904 | qzmfranklin/easyshell | easyshell/basic_shell.py | BasicShell._complete_exit | def _complete_exit(self, cmd, args, text):
"""Find candidates for the 'exit' command."""
if args:
return
return [ x for x in { 'root', 'all', } \
if x.startswith(text) ] | python | def _complete_exit(self, cmd, args, text):
"""Find candidates for the 'exit' command."""
if args:
return
return [ x for x in { 'root', 'all', } \
if x.startswith(text) ] | [
"def",
"_complete_exit",
"(",
"self",
",",
"cmd",
",",
"args",
",",
"text",
")",
":",
"if",
"args",
":",
"return",
"return",
"[",
"x",
"for",
"x",
"in",
"{",
"'root'",
",",
"'all'",
",",
"}",
"if",
"x",
".",
"startswith",
"(",
"text",
")",
"]"
] | Find candidates for the 'exit' command. | [
"Find",
"candidates",
"for",
"the",
"exit",
"command",
"."
] | 00c2e90e7767d32e7e127fc8c6875845aa308295 | https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/basic_shell.py#L59-L64 |
250,905 | qzmfranklin/easyshell | easyshell/basic_shell.py | BasicShell._do_history | def _do_history(self, cmd, args):
"""\
Display history.
history Display history.
history clear Clear history.
history clearall Clear history for all shells.
"""
if args and args[0] == 'clear':
readline.clear_history()
readline.write_history_file(self.history_fname)
elif args and args[0] == 'clearall':
readline.clear_history()
shutil.rmtree(self._temp_dir, ignore_errors = True)
os.makedirs(os.path.join(self._temp_dir, 'history'))
else:
readline.write_history_file(self.history_fname)
with open(self.history_fname, 'r', encoding = 'utf8') as f:
self.stdout.write(f.read()) | python | def _do_history(self, cmd, args):
"""\
Display history.
history Display history.
history clear Clear history.
history clearall Clear history for all shells.
"""
if args and args[0] == 'clear':
readline.clear_history()
readline.write_history_file(self.history_fname)
elif args and args[0] == 'clearall':
readline.clear_history()
shutil.rmtree(self._temp_dir, ignore_errors = True)
os.makedirs(os.path.join(self._temp_dir, 'history'))
else:
readline.write_history_file(self.history_fname)
with open(self.history_fname, 'r', encoding = 'utf8') as f:
self.stdout.write(f.read()) | [
"def",
"_do_history",
"(",
"self",
",",
"cmd",
",",
"args",
")",
":",
"if",
"args",
"and",
"args",
"[",
"0",
"]",
"==",
"'clear'",
":",
"readline",
".",
"clear_history",
"(",
")",
"readline",
".",
"write_history_file",
"(",
"self",
".",
"history_fname",
")",
"elif",
"args",
"and",
"args",
"[",
"0",
"]",
"==",
"'clearall'",
":",
"readline",
".",
"clear_history",
"(",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"_temp_dir",
",",
"ignore_errors",
"=",
"True",
")",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_temp_dir",
",",
"'history'",
")",
")",
"else",
":",
"readline",
".",
"write_history_file",
"(",
"self",
".",
"history_fname",
")",
"with",
"open",
"(",
"self",
".",
"history_fname",
",",
"'r'",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"f",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"f",
".",
"read",
"(",
")",
")"
] | \
Display history.
history Display history.
history clear Clear history.
history clearall Clear history for all shells. | [
"\\",
"Display",
"history",
".",
"history",
"Display",
"history",
".",
"history",
"clear",
"Clear",
"history",
".",
"history",
"clearall",
"Clear",
"history",
"for",
"all",
"shells",
"."
] | 00c2e90e7767d32e7e127fc8c6875845aa308295 | https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/basic_shell.py#L67-L84 |
250,906 | qzmfranklin/easyshell | easyshell/basic_shell.py | BasicShell._complete_history | def _complete_history(self, cmd, args, text):
"""Find candidates for the 'history' command."""
if args:
return
return [ x for x in { 'clear', 'clearall' } \
if x.startswith(text) ] | python | def _complete_history(self, cmd, args, text):
"""Find candidates for the 'history' command."""
if args:
return
return [ x for x in { 'clear', 'clearall' } \
if x.startswith(text) ] | [
"def",
"_complete_history",
"(",
"self",
",",
"cmd",
",",
"args",
",",
"text",
")",
":",
"if",
"args",
":",
"return",
"return",
"[",
"x",
"for",
"x",
"in",
"{",
"'clear'",
",",
"'clearall'",
"}",
"if",
"x",
".",
"startswith",
"(",
"text",
")",
"]"
] | Find candidates for the 'history' command. | [
"Find",
"candidates",
"for",
"the",
"history",
"command",
"."
] | 00c2e90e7767d32e7e127fc8c6875845aa308295 | https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/basic_shell.py#L87-L92 |
250,907 | qzmfranklin/easyshell | easyshell/basic_shell.py | BasicShell.__dump_stack | def __dump_stack(self):
"""Dump the shell stack in a human friendly way.
An example output is:
0 PlayBoy
1 βββ foo-prompt: foo@[]
2 βββ karPROMPT: kar@[]
3 βββ DEBUG: debug@['shell']
"""
maxdepth = len(self._mode_stack)
maxdepth_strlen = len(str(maxdepth))
index_width = 4 - (-maxdepth_strlen) % 4 + 4
index_str = lambda i: '{:<{}d}'.format(i, index_width)
self.stdout.write(index_str(0) + self.root_prompt)
self.stdout.write('\n')
tree_prefix = 'βββ '
for i in range(maxdepth):
index_prefix = index_str(i + 1)
whitespace_prefix = ' ' * len(tree_prefix) * i
mode = self._mode_stack[i]
line = index_prefix + whitespace_prefix + \
tree_prefix + mode.prompt + \
': {}@{}'.format(mode.cmd, mode.args)
self.stdout.write(line)
self.stdout.write('\n') | python | def __dump_stack(self):
"""Dump the shell stack in a human friendly way.
An example output is:
0 PlayBoy
1 βββ foo-prompt: foo@[]
2 βββ karPROMPT: kar@[]
3 βββ DEBUG: debug@['shell']
"""
maxdepth = len(self._mode_stack)
maxdepth_strlen = len(str(maxdepth))
index_width = 4 - (-maxdepth_strlen) % 4 + 4
index_str = lambda i: '{:<{}d}'.format(i, index_width)
self.stdout.write(index_str(0) + self.root_prompt)
self.stdout.write('\n')
tree_prefix = 'βββ '
for i in range(maxdepth):
index_prefix = index_str(i + 1)
whitespace_prefix = ' ' * len(tree_prefix) * i
mode = self._mode_stack[i]
line = index_prefix + whitespace_prefix + \
tree_prefix + mode.prompt + \
': {}@{}'.format(mode.cmd, mode.args)
self.stdout.write(line)
self.stdout.write('\n') | [
"def",
"__dump_stack",
"(",
"self",
")",
":",
"maxdepth",
"=",
"len",
"(",
"self",
".",
"_mode_stack",
")",
"maxdepth_strlen",
"=",
"len",
"(",
"str",
"(",
"maxdepth",
")",
")",
"index_width",
"=",
"4",
"-",
"(",
"-",
"maxdepth_strlen",
")",
"%",
"4",
"+",
"4",
"index_str",
"=",
"lambda",
"i",
":",
"'{:<{}d}'",
".",
"format",
"(",
"i",
",",
"index_width",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"index_str",
"(",
"0",
")",
"+",
"self",
".",
"root_prompt",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
"tree_prefix",
"=",
"'βββ '",
"for",
"i",
"in",
"range",
"(",
"maxdepth",
")",
":",
"index_prefix",
"=",
"index_str",
"(",
"i",
"+",
"1",
")",
"whitespace_prefix",
"=",
"' '",
"*",
"len",
"(",
"tree_prefix",
")",
"*",
"i",
"mode",
"=",
"self",
".",
"_mode_stack",
"[",
"i",
"]",
"line",
"=",
"index_prefix",
"+",
"whitespace_prefix",
"+",
"tree_prefix",
"+",
"mode",
".",
"prompt",
"+",
"': {}@{}'",
".",
"format",
"(",
"mode",
".",
"cmd",
",",
"mode",
".",
"args",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"line",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")"
] | Dump the shell stack in a human friendly way.
An example output is:
0 PlayBoy
1 βββ foo-prompt: foo@[]
2 βββ karPROMPT: kar@[]
3 βββ DEBUG: debug@['shell'] | [
"Dump",
"the",
"shell",
"stack",
"in",
"a",
"human",
"friendly",
"way",
"."
] | 00c2e90e7767d32e7e127fc8c6875845aa308295 | https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/basic_shell.py#L122-L148 |
250,908 | qzmfranklin/easyshell | easyshell/basic_shell.py | BasicShell._do_help | def _do_help(self, cmd, args):
"""Display doc strings of the shell and its commands.
"""
print(self.doc_string())
print()
# Create data of the commands table.
data_unsorted = []
cls = self.__class__
for name in dir(cls):
obj = getattr(cls, name)
if iscommand(obj):
cmds = []
for cmd in getcommands(obj):
cmds.append(cmd)
cmd_str = ','.join(sorted(cmds))
doc_str = textwrap.dedent(obj.__doc__).strip() if obj.__doc__ else \
'(no doc string available)'
data_unsorted.append([cmd_str, doc_str])
data_sorted = sorted(data_unsorted, key = lambda x: x[0])
data = [['COMMANDS', 'DOC STRING']] + data_sorted
# Create the commands table.
table_banner = 'List of Available Commands'
table = terminaltables.SingleTable(data, table_banner)
table.inner_row_border = True
table.inner_heading_row_border = True
print(table.table) | python | def _do_help(self, cmd, args):
"""Display doc strings of the shell and its commands.
"""
print(self.doc_string())
print()
# Create data of the commands table.
data_unsorted = []
cls = self.__class__
for name in dir(cls):
obj = getattr(cls, name)
if iscommand(obj):
cmds = []
for cmd in getcommands(obj):
cmds.append(cmd)
cmd_str = ','.join(sorted(cmds))
doc_str = textwrap.dedent(obj.__doc__).strip() if obj.__doc__ else \
'(no doc string available)'
data_unsorted.append([cmd_str, doc_str])
data_sorted = sorted(data_unsorted, key = lambda x: x[0])
data = [['COMMANDS', 'DOC STRING']] + data_sorted
# Create the commands table.
table_banner = 'List of Available Commands'
table = terminaltables.SingleTable(data, table_banner)
table.inner_row_border = True
table.inner_heading_row_border = True
print(table.table) | [
"def",
"_do_help",
"(",
"self",
",",
"cmd",
",",
"args",
")",
":",
"print",
"(",
"self",
".",
"doc_string",
"(",
")",
")",
"print",
"(",
")",
"# Create data of the commands table.",
"data_unsorted",
"=",
"[",
"]",
"cls",
"=",
"self",
".",
"__class__",
"for",
"name",
"in",
"dir",
"(",
"cls",
")",
":",
"obj",
"=",
"getattr",
"(",
"cls",
",",
"name",
")",
"if",
"iscommand",
"(",
"obj",
")",
":",
"cmds",
"=",
"[",
"]",
"for",
"cmd",
"in",
"getcommands",
"(",
"obj",
")",
":",
"cmds",
".",
"append",
"(",
"cmd",
")",
"cmd_str",
"=",
"','",
".",
"join",
"(",
"sorted",
"(",
"cmds",
")",
")",
"doc_str",
"=",
"textwrap",
".",
"dedent",
"(",
"obj",
".",
"__doc__",
")",
".",
"strip",
"(",
")",
"if",
"obj",
".",
"__doc__",
"else",
"'(no doc string available)'",
"data_unsorted",
".",
"append",
"(",
"[",
"cmd_str",
",",
"doc_str",
"]",
")",
"data_sorted",
"=",
"sorted",
"(",
"data_unsorted",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
"data",
"=",
"[",
"[",
"'COMMANDS'",
",",
"'DOC STRING'",
"]",
"]",
"+",
"data_sorted",
"# Create the commands table.",
"table_banner",
"=",
"'List of Available Commands'",
"table",
"=",
"terminaltables",
".",
"SingleTable",
"(",
"data",
",",
"table_banner",
")",
"table",
".",
"inner_row_border",
"=",
"True",
"table",
".",
"inner_heading_row_border",
"=",
"True",
"print",
"(",
"table",
".",
"table",
")"
] | Display doc strings of the shell and its commands. | [
"Display",
"doc",
"strings",
"of",
"the",
"shell",
"and",
"its",
"commands",
"."
] | 00c2e90e7767d32e7e127fc8c6875845aa308295 | https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/basic_shell.py#L151-L178 |
250,909 | unixorn/haze | haze/cli/conductor.py | hazeDriver | def hazeDriver():
"""
Process the command line arguments and run the appropriate haze subcommand.
We want to be able to do git-style handoffs to subcommands where if we
do `haze aws foo bar` and the executable haze-aws-foo exists, we'll call
it with the argument bar.
We deliberately don't do anything with the arguments other than hand
them off to the haze subcommand. Subcommands are responsible for their
own argument parsing.
"""
try:
(command, args) = findSubCommand(sys.argv)
# If we can't construct a subcommand from sys.argv, it'll still be able
# to find this haze driver script, and re-running ourself isn't useful.
if os.path.basename(command) == "haze":
print "Could not find a subcommand for %s" % " ".join(sys.argv)
sys.exit(1)
except StandardError:
print "Could not find a subcommand for %s" % " ".join(sys.argv)
sys.exit(1)
check_call([command] + args) | python | def hazeDriver():
"""
Process the command line arguments and run the appropriate haze subcommand.
We want to be able to do git-style handoffs to subcommands where if we
do `haze aws foo bar` and the executable haze-aws-foo exists, we'll call
it with the argument bar.
We deliberately don't do anything with the arguments other than hand
them off to the haze subcommand. Subcommands are responsible for their
own argument parsing.
"""
try:
(command, args) = findSubCommand(sys.argv)
# If we can't construct a subcommand from sys.argv, it'll still be able
# to find this haze driver script, and re-running ourself isn't useful.
if os.path.basename(command) == "haze":
print "Could not find a subcommand for %s" % " ".join(sys.argv)
sys.exit(1)
except StandardError:
print "Could not find a subcommand for %s" % " ".join(sys.argv)
sys.exit(1)
check_call([command] + args) | [
"def",
"hazeDriver",
"(",
")",
":",
"try",
":",
"(",
"command",
",",
"args",
")",
"=",
"findSubCommand",
"(",
"sys",
".",
"argv",
")",
"# If we can't construct a subcommand from sys.argv, it'll still be able",
"# to find this haze driver script, and re-running ourself isn't useful.",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"command",
")",
"==",
"\"haze\"",
":",
"print",
"\"Could not find a subcommand for %s\"",
"%",
"\" \"",
".",
"join",
"(",
"sys",
".",
"argv",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"except",
"StandardError",
":",
"print",
"\"Could not find a subcommand for %s\"",
"%",
"\" \"",
".",
"join",
"(",
"sys",
".",
"argv",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"check_call",
"(",
"[",
"command",
"]",
"+",
"args",
")"
] | Process the command line arguments and run the appropriate haze subcommand.
We want to be able to do git-style handoffs to subcommands where if we
do `haze aws foo bar` and the executable haze-aws-foo exists, we'll call
it with the argument bar.
We deliberately don't do anything with the arguments other than hand
them off to the haze subcommand. Subcommands are responsible for their
own argument parsing. | [
"Process",
"the",
"command",
"line",
"arguments",
"and",
"run",
"the",
"appropriate",
"haze",
"subcommand",
"."
] | 77692b18e6574ac356e3e16659b96505c733afff | https://github.com/unixorn/haze/blob/77692b18e6574ac356e3e16659b96505c733afff/haze/cli/conductor.py#L29-L52 |
250,910 | klmitch/aversion | aversion.py | quoted_split | def quoted_split(string, sep, quotes='"'):
"""
Split a string on the given separation character, but respecting
double-quoted sections of the string. Returns an iterator.
:param string: The string to split.
:param sep: The character separating sections of the string.
:param quotes: A string specifying all legal quote characters.
:returns: An iterator which will iterate over each element of the
string separated by the designated separator.
"""
# Initialize the algorithm
start = None
escape = False
quote = False
# Walk through the string
for i, c in enumerate(string):
# Save the start index
if start is None:
start = i
# Handle escape sequences
if escape:
escape = False
# Handle quoted strings
elif quote:
if c == '\\':
escape = True
elif c == quote:
quote = False
# Handle the separator
elif c == sep:
yield string[start:i]
start = None
# Handle quotes
elif c in quotes:
quote = c
# Yield the last part
if start is not None:
yield string[start:] | python | def quoted_split(string, sep, quotes='"'):
"""
Split a string on the given separation character, but respecting
double-quoted sections of the string. Returns an iterator.
:param string: The string to split.
:param sep: The character separating sections of the string.
:param quotes: A string specifying all legal quote characters.
:returns: An iterator which will iterate over each element of the
string separated by the designated separator.
"""
# Initialize the algorithm
start = None
escape = False
quote = False
# Walk through the string
for i, c in enumerate(string):
# Save the start index
if start is None:
start = i
# Handle escape sequences
if escape:
escape = False
# Handle quoted strings
elif quote:
if c == '\\':
escape = True
elif c == quote:
quote = False
# Handle the separator
elif c == sep:
yield string[start:i]
start = None
# Handle quotes
elif c in quotes:
quote = c
# Yield the last part
if start is not None:
yield string[start:] | [
"def",
"quoted_split",
"(",
"string",
",",
"sep",
",",
"quotes",
"=",
"'\"'",
")",
":",
"# Initialize the algorithm",
"start",
"=",
"None",
"escape",
"=",
"False",
"quote",
"=",
"False",
"# Walk through the string",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"string",
")",
":",
"# Save the start index",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"i",
"# Handle escape sequences",
"if",
"escape",
":",
"escape",
"=",
"False",
"# Handle quoted strings",
"elif",
"quote",
":",
"if",
"c",
"==",
"'\\\\'",
":",
"escape",
"=",
"True",
"elif",
"c",
"==",
"quote",
":",
"quote",
"=",
"False",
"# Handle the separator",
"elif",
"c",
"==",
"sep",
":",
"yield",
"string",
"[",
"start",
":",
"i",
"]",
"start",
"=",
"None",
"# Handle quotes",
"elif",
"c",
"in",
"quotes",
":",
"quote",
"=",
"c",
"# Yield the last part",
"if",
"start",
"is",
"not",
"None",
":",
"yield",
"string",
"[",
"start",
":",
"]"
] | Split a string on the given separation character, but respecting
double-quoted sections of the string. Returns an iterator.
:param string: The string to split.
:param sep: The character separating sections of the string.
:param quotes: A string specifying all legal quote characters.
:returns: An iterator which will iterate over each element of the
string separated by the designated separator. | [
"Split",
"a",
"string",
"on",
"the",
"given",
"separation",
"character",
"but",
"respecting",
"double",
"-",
"quoted",
"sections",
"of",
"the",
"string",
".",
"Returns",
"an",
"iterator",
"."
] | 90ca68e7d6426a77db8a926171f8d3bbeb00ee4c | https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L29-L75 |
250,911 | klmitch/aversion | aversion.py | parse_ctype | def parse_ctype(ctype):
"""
Parse a content type.
:param ctype: The content type, with corresponding parameters.
:returns: A tuple of the content type and a dictionary containing
the content type parameters. The content type will
additionally be available in the dictionary as the '_'
key.
"""
result_ctype = None
result = {}
for part in quoted_split(ctype, ';'):
# Extract the content type first
if result_ctype is None:
result_ctype = part
result['_'] = part
continue
# OK, we have a 'key' or 'key=value' to handle; figure it
# out...
equal = part.find('=')
if equal > 0 and part.find('"', 0, equal) < 0:
result[part[:equal]] = unquote(part[equal + 1:])
else:
# If equal > 0 but it's preceded by a ", it's seriously
# messed up, but go ahead and be liberal...
result[part] = True
# If we failed to parse a content type out, return an empty
# content type
if result_ctype is None:
result_ctype = ''
return result_ctype, result | python | def parse_ctype(ctype):
"""
Parse a content type.
:param ctype: The content type, with corresponding parameters.
:returns: A tuple of the content type and a dictionary containing
the content type parameters. The content type will
additionally be available in the dictionary as the '_'
key.
"""
result_ctype = None
result = {}
for part in quoted_split(ctype, ';'):
# Extract the content type first
if result_ctype is None:
result_ctype = part
result['_'] = part
continue
# OK, we have a 'key' or 'key=value' to handle; figure it
# out...
equal = part.find('=')
if equal > 0 and part.find('"', 0, equal) < 0:
result[part[:equal]] = unquote(part[equal + 1:])
else:
# If equal > 0 but it's preceded by a ", it's seriously
# messed up, but go ahead and be liberal...
result[part] = True
# If we failed to parse a content type out, return an empty
# content type
if result_ctype is None:
result_ctype = ''
return result_ctype, result | [
"def",
"parse_ctype",
"(",
"ctype",
")",
":",
"result_ctype",
"=",
"None",
"result",
"=",
"{",
"}",
"for",
"part",
"in",
"quoted_split",
"(",
"ctype",
",",
"';'",
")",
":",
"# Extract the content type first",
"if",
"result_ctype",
"is",
"None",
":",
"result_ctype",
"=",
"part",
"result",
"[",
"'_'",
"]",
"=",
"part",
"continue",
"# OK, we have a 'key' or 'key=value' to handle; figure it",
"# out...",
"equal",
"=",
"part",
".",
"find",
"(",
"'='",
")",
"if",
"equal",
">",
"0",
"and",
"part",
".",
"find",
"(",
"'\"'",
",",
"0",
",",
"equal",
")",
"<",
"0",
":",
"result",
"[",
"part",
"[",
":",
"equal",
"]",
"]",
"=",
"unquote",
"(",
"part",
"[",
"equal",
"+",
"1",
":",
"]",
")",
"else",
":",
"# If equal > 0 but it's preceded by a \", it's seriously",
"# messed up, but go ahead and be liberal...",
"result",
"[",
"part",
"]",
"=",
"True",
"# If we failed to parse a content type out, return an empty",
"# content type",
"if",
"result_ctype",
"is",
"None",
":",
"result_ctype",
"=",
"''",
"return",
"result_ctype",
",",
"result"
] | Parse a content type.
:param ctype: The content type, with corresponding parameters.
:returns: A tuple of the content type and a dictionary containing
the content type parameters. The content type will
additionally be available in the dictionary as the '_'
key. | [
"Parse",
"a",
"content",
"type",
"."
] | 90ca68e7d6426a77db8a926171f8d3bbeb00ee4c | https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L98-L134 |
250,912 | klmitch/aversion | aversion.py | _match_mask | def _match_mask(mask, ctype):
"""
Determine if a content type mask matches a given content type.
:param mask: The content type mask, taken from the Accept
header.
:param ctype: The content type to match to the mask.
"""
# Handle the simple cases first
if '*' not in mask:
return ctype == mask
elif mask == '*/*':
return True
elif not mask.endswith('/*'):
return False
mask_major = mask[:-2]
ctype_major = ctype.split('/', 1)[0]
return ctype_major == mask_major | python | def _match_mask(mask, ctype):
"""
Determine if a content type mask matches a given content type.
:param mask: The content type mask, taken from the Accept
header.
:param ctype: The content type to match to the mask.
"""
# Handle the simple cases first
if '*' not in mask:
return ctype == mask
elif mask == '*/*':
return True
elif not mask.endswith('/*'):
return False
mask_major = mask[:-2]
ctype_major = ctype.split('/', 1)[0]
return ctype_major == mask_major | [
"def",
"_match_mask",
"(",
"mask",
",",
"ctype",
")",
":",
"# Handle the simple cases first",
"if",
"'*'",
"not",
"in",
"mask",
":",
"return",
"ctype",
"==",
"mask",
"elif",
"mask",
"==",
"'*/*'",
":",
"return",
"True",
"elif",
"not",
"mask",
".",
"endswith",
"(",
"'/*'",
")",
":",
"return",
"False",
"mask_major",
"=",
"mask",
"[",
":",
"-",
"2",
"]",
"ctype_major",
"=",
"ctype",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"[",
"0",
"]",
"return",
"ctype_major",
"==",
"mask_major"
] | Determine if a content type mask matches a given content type.
:param mask: The content type mask, taken from the Accept
header.
:param ctype: The content type to match to the mask. | [
"Determine",
"if",
"a",
"content",
"type",
"mask",
"matches",
"a",
"given",
"content",
"type",
"."
] | 90ca68e7d6426a77db8a926171f8d3bbeb00ee4c | https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L137-L156 |
250,913 | klmitch/aversion | aversion.py | best_match | def best_match(requested, allowed):
"""
Determine the best content type to use for the request.
:param ctypes: A list of the available content types.
:returns: A tuple of the best match content type and the
parameters for that content type.
"""
requested = [parse_ctype(ctype) for ctype in quoted_split(requested, ',')]
best_q = -1
best_ctype = ''
best_params = {}
best_match = '*/*'
# Walk the list of content types
for ctype in allowed:
# Compare to the accept list
for ctype_mask, params in requested:
try:
q = float(params.get('q', 1.0))
except ValueError:
# Bad quality value
continue
if q < best_q:
# Not any better
continue
elif best_q == q:
# Base on the best match
if best_match.count('*') <= ctype_mask.count('*'):
continue
# OK, see if we have a match
if _match_mask(ctype_mask, ctype):
best_q = q
best_ctype = ctype
best_params = params
best_match = ctype_mask
# Return the best match
return best_ctype, best_params | python | def best_match(requested, allowed):
"""
Determine the best content type to use for the request.
:param ctypes: A list of the available content types.
:returns: A tuple of the best match content type and the
parameters for that content type.
"""
requested = [parse_ctype(ctype) for ctype in quoted_split(requested, ',')]
best_q = -1
best_ctype = ''
best_params = {}
best_match = '*/*'
# Walk the list of content types
for ctype in allowed:
# Compare to the accept list
for ctype_mask, params in requested:
try:
q = float(params.get('q', 1.0))
except ValueError:
# Bad quality value
continue
if q < best_q:
# Not any better
continue
elif best_q == q:
# Base on the best match
if best_match.count('*') <= ctype_mask.count('*'):
continue
# OK, see if we have a match
if _match_mask(ctype_mask, ctype):
best_q = q
best_ctype = ctype
best_params = params
best_match = ctype_mask
# Return the best match
return best_ctype, best_params | [
"def",
"best_match",
"(",
"requested",
",",
"allowed",
")",
":",
"requested",
"=",
"[",
"parse_ctype",
"(",
"ctype",
")",
"for",
"ctype",
"in",
"quoted_split",
"(",
"requested",
",",
"','",
")",
"]",
"best_q",
"=",
"-",
"1",
"best_ctype",
"=",
"''",
"best_params",
"=",
"{",
"}",
"best_match",
"=",
"'*/*'",
"# Walk the list of content types",
"for",
"ctype",
"in",
"allowed",
":",
"# Compare to the accept list",
"for",
"ctype_mask",
",",
"params",
"in",
"requested",
":",
"try",
":",
"q",
"=",
"float",
"(",
"params",
".",
"get",
"(",
"'q'",
",",
"1.0",
")",
")",
"except",
"ValueError",
":",
"# Bad quality value",
"continue",
"if",
"q",
"<",
"best_q",
":",
"# Not any better",
"continue",
"elif",
"best_q",
"==",
"q",
":",
"# Base on the best match",
"if",
"best_match",
".",
"count",
"(",
"'*'",
")",
"<=",
"ctype_mask",
".",
"count",
"(",
"'*'",
")",
":",
"continue",
"# OK, see if we have a match",
"if",
"_match_mask",
"(",
"ctype_mask",
",",
"ctype",
")",
":",
"best_q",
"=",
"q",
"best_ctype",
"=",
"ctype",
"best_params",
"=",
"params",
"best_match",
"=",
"ctype_mask",
"# Return the best match",
"return",
"best_ctype",
",",
"best_params"
] | Determine the best content type to use for the request.
:param ctypes: A list of the available content types.
:returns: A tuple of the best match content type and the
parameters for that content type. | [
"Determine",
"the",
"best",
"content",
"type",
"to",
"use",
"for",
"the",
"request",
"."
] | 90ca68e7d6426a77db8a926171f8d3bbeb00ee4c | https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L159-L202 |
250,914 | klmitch/aversion | aversion.py | _set_key | def _set_key(log_prefix, result_dict, key, value, desc="parameter"):
"""
Helper to set a key value in a dictionary. This function issues a
warning if the key has already been set, and issues a warning and
returns without setting the value if the value is not surrounded
by parentheses. This is used to eliminate duplicated code from
the rule parsers below.
:param log_prefix: A prefix to use in log messages. This should
be the configuration key.
:param result_dict: A dictionary of results, into which the key
and value should be inserted.
:param key: The dictionary key to insert.
:param value: The value to insert into the dictionary.
:param desc: A description of what the dictionary is. This is
used in log messages help the user understand what
the log message is referring to. By default, this
description is "parameter", indicating that entries
in the dictionary are parameters of something;
however, _parse_type_rule() also uses "token type" to
help identify its more complex tokens.
"""
if key in result_dict:
LOG.warn("%s: Duplicate value for %s %r" %
(log_prefix, desc, key))
# Allow the overwrite
# Demand the value be quoted
if len(value) <= 2 or value[0] not in ('"', "'") or value[0] != value[-1]:
LOG.warn("%s: Invalid value %r for %s %r" %
(log_prefix, value, desc, key))
return
# Save the value
result_dict[key] = value[1:-1] | python | def _set_key(log_prefix, result_dict, key, value, desc="parameter"):
"""
Helper to set a key value in a dictionary. This function issues a
warning if the key has already been set, and issues a warning and
returns without setting the value if the value is not surrounded
by parentheses. This is used to eliminate duplicated code from
the rule parsers below.
:param log_prefix: A prefix to use in log messages. This should
be the configuration key.
:param result_dict: A dictionary of results, into which the key
and value should be inserted.
:param key: The dictionary key to insert.
:param value: The value to insert into the dictionary.
:param desc: A description of what the dictionary is. This is
used in log messages help the user understand what
the log message is referring to. By default, this
description is "parameter", indicating that entries
in the dictionary are parameters of something;
however, _parse_type_rule() also uses "token type" to
help identify its more complex tokens.
"""
if key in result_dict:
LOG.warn("%s: Duplicate value for %s %r" %
(log_prefix, desc, key))
# Allow the overwrite
# Demand the value be quoted
if len(value) <= 2 or value[0] not in ('"', "'") or value[0] != value[-1]:
LOG.warn("%s: Invalid value %r for %s %r" %
(log_prefix, value, desc, key))
return
# Save the value
result_dict[key] = value[1:-1] | [
"def",
"_set_key",
"(",
"log_prefix",
",",
"result_dict",
",",
"key",
",",
"value",
",",
"desc",
"=",
"\"parameter\"",
")",
":",
"if",
"key",
"in",
"result_dict",
":",
"LOG",
".",
"warn",
"(",
"\"%s: Duplicate value for %s %r\"",
"%",
"(",
"log_prefix",
",",
"desc",
",",
"key",
")",
")",
"# Allow the overwrite",
"# Demand the value be quoted",
"if",
"len",
"(",
"value",
")",
"<=",
"2",
"or",
"value",
"[",
"0",
"]",
"not",
"in",
"(",
"'\"'",
",",
"\"'\"",
")",
"or",
"value",
"[",
"0",
"]",
"!=",
"value",
"[",
"-",
"1",
"]",
":",
"LOG",
".",
"warn",
"(",
"\"%s: Invalid value %r for %s %r\"",
"%",
"(",
"log_prefix",
",",
"value",
",",
"desc",
",",
"key",
")",
")",
"return",
"# Save the value",
"result_dict",
"[",
"key",
"]",
"=",
"value",
"[",
"1",
":",
"-",
"1",
"]"
] | Helper to set a key value in a dictionary. This function issues a
warning if the key has already been set, and issues a warning and
returns without setting the value if the value is not surrounded
by parentheses. This is used to eliminate duplicated code from
the rule parsers below.
:param log_prefix: A prefix to use in log messages. This should
be the configuration key.
:param result_dict: A dictionary of results, into which the key
and value should be inserted.
:param key: The dictionary key to insert.
:param value: The value to insert into the dictionary.
:param desc: A description of what the dictionary is. This is
used in log messages help the user understand what
the log message is referring to. By default, this
description is "parameter", indicating that entries
in the dictionary are parameters of something;
however, _parse_type_rule() also uses "token type" to
help identify its more complex tokens. | [
"Helper",
"to",
"set",
"a",
"key",
"value",
"in",
"a",
"dictionary",
".",
"This",
"function",
"issues",
"a",
"warning",
"if",
"the",
"key",
"has",
"already",
"been",
"set",
"and",
"issues",
"a",
"warning",
"and",
"returns",
"without",
"setting",
"the",
"value",
"if",
"the",
"value",
"is",
"not",
"surrounded",
"by",
"parentheses",
".",
"This",
"is",
"used",
"to",
"eliminate",
"duplicated",
"code",
"from",
"the",
"rule",
"parsers",
"below",
"."
] | 90ca68e7d6426a77db8a926171f8d3bbeb00ee4c | https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L309-L344 |
250,915 | klmitch/aversion | aversion.py | _parse_version_rule | def _parse_version_rule(loader, version, verspec):
"""
Parse a version rule. The first token is the name of the
application implementing that API version. The remaining tokens
are key="quoted value" pairs that specify parameters; these
parameters are ignored by AVersion, but may be used by the
application.
:param loader: An object with a get_app() method, which will be
used to load the actual applications.
:param version: The version name.
:param verspec: The version text, described above.
:returns: A dictionary of three keys: "app" is the application;
"name" is the version identification string; and
"params" is a dictionary of parameters.
"""
result = dict(name=version, params={})
for token in quoted_split(verspec, ' ', quotes='"\''):
if not token:
continue
# Convert the application
if 'app' not in result:
result['app'] = loader.get_app(token)
continue
# What remains is key="quoted value" pairs...
key, _eq, value = token.partition('=')
# Set the parameter key
_set_key('version.%s' % version, result['params'], key, value)
# Make sure we have an application
if 'app' not in result:
raise ImportError("Cannot load application for version %r" % version)
return result | python | def _parse_version_rule(loader, version, verspec):
"""
Parse a version rule. The first token is the name of the
application implementing that API version. The remaining tokens
are key="quoted value" pairs that specify parameters; these
parameters are ignored by AVersion, but may be used by the
application.
:param loader: An object with a get_app() method, which will be
used to load the actual applications.
:param version: The version name.
:param verspec: The version text, described above.
:returns: A dictionary of three keys: "app" is the application;
"name" is the version identification string; and
"params" is a dictionary of parameters.
"""
result = dict(name=version, params={})
for token in quoted_split(verspec, ' ', quotes='"\''):
if not token:
continue
# Convert the application
if 'app' not in result:
result['app'] = loader.get_app(token)
continue
# What remains is key="quoted value" pairs...
key, _eq, value = token.partition('=')
# Set the parameter key
_set_key('version.%s' % version, result['params'], key, value)
# Make sure we have an application
if 'app' not in result:
raise ImportError("Cannot load application for version %r" % version)
return result | [
"def",
"_parse_version_rule",
"(",
"loader",
",",
"version",
",",
"verspec",
")",
":",
"result",
"=",
"dict",
"(",
"name",
"=",
"version",
",",
"params",
"=",
"{",
"}",
")",
"for",
"token",
"in",
"quoted_split",
"(",
"verspec",
",",
"' '",
",",
"quotes",
"=",
"'\"\\''",
")",
":",
"if",
"not",
"token",
":",
"continue",
"# Convert the application",
"if",
"'app'",
"not",
"in",
"result",
":",
"result",
"[",
"'app'",
"]",
"=",
"loader",
".",
"get_app",
"(",
"token",
")",
"continue",
"# What remains is key=\"quoted value\" pairs...",
"key",
",",
"_eq",
",",
"value",
"=",
"token",
".",
"partition",
"(",
"'='",
")",
"# Set the parameter key",
"_set_key",
"(",
"'version.%s'",
"%",
"version",
",",
"result",
"[",
"'params'",
"]",
",",
"key",
",",
"value",
")",
"# Make sure we have an application",
"if",
"'app'",
"not",
"in",
"result",
":",
"raise",
"ImportError",
"(",
"\"Cannot load application for version %r\"",
"%",
"version",
")",
"return",
"result"
] | Parse a version rule. The first token is the name of the
application implementing that API version. The remaining tokens
are key="quoted value" pairs that specify parameters; these
parameters are ignored by AVersion, but may be used by the
application.
:param loader: An object with a get_app() method, which will be
used to load the actual applications.
:param version: The version name.
:param verspec: The version text, described above.
:returns: A dictionary of three keys: "app" is the application;
"name" is the version identification string; and
"params" is a dictionary of parameters. | [
"Parse",
"a",
"version",
"rule",
".",
"The",
"first",
"token",
"is",
"the",
"name",
"of",
"the",
"application",
"implementing",
"that",
"API",
"version",
".",
"The",
"remaining",
"tokens",
"are",
"key",
"=",
"quoted",
"value",
"pairs",
"that",
"specify",
"parameters",
";",
"these",
"parameters",
"are",
"ignored",
"by",
"AVersion",
"but",
"may",
"be",
"used",
"by",
"the",
"application",
"."
] | 90ca68e7d6426a77db8a926171f8d3bbeb00ee4c | https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L347-L385 |
250,916 | klmitch/aversion | aversion.py | _parse_alias_rule | def _parse_alias_rule(alias, alias_spec):
"""
Parse an alias rule. The first token is the canonical name of the
version. The remaining tokens are key="quoted value" pairs that
specify parameters; these parameters are ignored by AVersion, but
may be used by the application.
:param alias: The alias name.
:param alias_spec: The alias text, described above.
:returns: A dictionary of three keys: "alias" is the alias name;
"version" is the canonical version identification
string; and "params" is a dictionary of parameters.
"""
result = dict(alias=alias, params={})
for token in quoted_split(alias_spec, ' ', quotes='"\''):
if not token:
continue
# Suck out the canonical version name
if 'version' not in result:
result['version'] = token
continue
# What remains is key="quoted value" pairs...
key, _eq, value = token.partition('=')
# Set the parameter key
_set_key('alias.%s' % alias, result['params'], key, value)
# Make sure we have a canonical version
if 'version' not in result:
raise KeyError("Cannot determine canonical version for alias %r" %
alias)
return result | python | def _parse_alias_rule(alias, alias_spec):
"""
Parse an alias rule. The first token is the canonical name of the
version. The remaining tokens are key="quoted value" pairs that
specify parameters; these parameters are ignored by AVersion, but
may be used by the application.
:param alias: The alias name.
:param alias_spec: The alias text, described above.
:returns: A dictionary of three keys: "alias" is the alias name;
"version" is the canonical version identification
string; and "params" is a dictionary of parameters.
"""
result = dict(alias=alias, params={})
for token in quoted_split(alias_spec, ' ', quotes='"\''):
if not token:
continue
# Suck out the canonical version name
if 'version' not in result:
result['version'] = token
continue
# What remains is key="quoted value" pairs...
key, _eq, value = token.partition('=')
# Set the parameter key
_set_key('alias.%s' % alias, result['params'], key, value)
# Make sure we have a canonical version
if 'version' not in result:
raise KeyError("Cannot determine canonical version for alias %r" %
alias)
return result | [
"def",
"_parse_alias_rule",
"(",
"alias",
",",
"alias_spec",
")",
":",
"result",
"=",
"dict",
"(",
"alias",
"=",
"alias",
",",
"params",
"=",
"{",
"}",
")",
"for",
"token",
"in",
"quoted_split",
"(",
"alias_spec",
",",
"' '",
",",
"quotes",
"=",
"'\"\\''",
")",
":",
"if",
"not",
"token",
":",
"continue",
"# Suck out the canonical version name",
"if",
"'version'",
"not",
"in",
"result",
":",
"result",
"[",
"'version'",
"]",
"=",
"token",
"continue",
"# What remains is key=\"quoted value\" pairs...",
"key",
",",
"_eq",
",",
"value",
"=",
"token",
".",
"partition",
"(",
"'='",
")",
"# Set the parameter key",
"_set_key",
"(",
"'alias.%s'",
"%",
"alias",
",",
"result",
"[",
"'params'",
"]",
",",
"key",
",",
"value",
")",
"# Make sure we have a canonical version",
"if",
"'version'",
"not",
"in",
"result",
":",
"raise",
"KeyError",
"(",
"\"Cannot determine canonical version for alias %r\"",
"%",
"alias",
")",
"return",
"result"
] | Parse an alias rule. The first token is the canonical name of the
version. The remaining tokens are key="quoted value" pairs that
specify parameters; these parameters are ignored by AVersion, but
may be used by the application.
:param alias: The alias name.
:param alias_spec: The alias text, described above.
:returns: A dictionary of three keys: "alias" is the alias name;
"version" is the canonical version identification
string; and "params" is a dictionary of parameters. | [
"Parse",
"an",
"alias",
"rule",
".",
"The",
"first",
"token",
"is",
"the",
"canonical",
"name",
"of",
"the",
"version",
".",
"The",
"remaining",
"tokens",
"are",
"key",
"=",
"quoted",
"value",
"pairs",
"that",
"specify",
"parameters",
";",
"these",
"parameters",
"are",
"ignored",
"by",
"AVersion",
"but",
"may",
"be",
"used",
"by",
"the",
"application",
"."
] | 90ca68e7d6426a77db8a926171f8d3bbeb00ee4c | https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L388-L424 |
250,917 | klmitch/aversion | aversion.py | Result.set_ctype | def set_ctype(self, ctype, orig_ctype=None):
"""
Set the selected content type. Will not override the value of
the content type if that has already been determined.
:param ctype: The content type string to set.
:param orig_ctype: The original content type, as found in the
configuration.
"""
if self.ctype is None:
self.ctype = ctype
self.orig_ctype = orig_ctype | python | def set_ctype(self, ctype, orig_ctype=None):
"""
Set the selected content type. Will not override the value of
the content type if that has already been determined.
:param ctype: The content type string to set.
:param orig_ctype: The original content type, as found in the
configuration.
"""
if self.ctype is None:
self.ctype = ctype
self.orig_ctype = orig_ctype | [
"def",
"set_ctype",
"(",
"self",
",",
"ctype",
",",
"orig_ctype",
"=",
"None",
")",
":",
"if",
"self",
".",
"ctype",
"is",
"None",
":",
"self",
".",
"ctype",
"=",
"ctype",
"self",
".",
"orig_ctype",
"=",
"orig_ctype"
] | Set the selected content type. Will not override the value of
the content type if that has already been determined.
:param ctype: The content type string to set.
:param orig_ctype: The original content type, as found in the
configuration. | [
"Set",
"the",
"selected",
"content",
"type",
".",
"Will",
"not",
"override",
"the",
"value",
"of",
"the",
"content",
"type",
"if",
"that",
"has",
"already",
"been",
"determined",
"."
] | 90ca68e7d6426a77db8a926171f8d3bbeb00ee4c | https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L293-L306 |
250,918 | klmitch/aversion | aversion.py | AVersion._process | def _process(self, request, result=None):
"""
Process the rules for the request.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in. If
None, one will be allocated.
:returns: A Result object, containing the selected version and
content type.
"""
# Allocate a result and process all the rules
result = result if result is not None else Result()
self._proc_uri(request, result)
self._proc_ctype_header(request, result)
self._proc_accept_header(request, result)
return result | python | def _process(self, request, result=None):
"""
Process the rules for the request.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in. If
None, one will be allocated.
:returns: A Result object, containing the selected version and
content type.
"""
# Allocate a result and process all the rules
result = result if result is not None else Result()
self._proc_uri(request, result)
self._proc_ctype_header(request, result)
self._proc_accept_header(request, result)
return result | [
"def",
"_process",
"(",
"self",
",",
"request",
",",
"result",
"=",
"None",
")",
":",
"# Allocate a result and process all the rules",
"result",
"=",
"result",
"if",
"result",
"is",
"not",
"None",
"else",
"Result",
"(",
")",
"self",
".",
"_proc_uri",
"(",
"request",
",",
"result",
")",
"self",
".",
"_proc_ctype_header",
"(",
"request",
",",
"result",
")",
"self",
".",
"_proc_accept_header",
"(",
"request",
",",
"result",
")",
"return",
"result"
] | Process the rules for the request.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in. If
None, one will be allocated.
:returns: A Result object, containing the selected version and
content type. | [
"Process",
"the",
"rules",
"for",
"the",
"request",
"."
] | 90ca68e7d6426a77db8a926171f8d3bbeb00ee4c | https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L640-L658 |
250,919 | klmitch/aversion | aversion.py | AVersion._proc_uri | def _proc_uri(self, request, result):
"""
Process the URI rules for the request. Both the desired API
version and desired content type can be determined from those
rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in.
"""
if result:
# Result has already been fully determined
return
# First, determine the version based on the URI prefix
for prefix, version in self.uris:
if (request.path_info == prefix or
request.path_info.startswith(prefix + '/')):
result.set_version(version)
# Update the request particulars
request.script_name += prefix
request.path_info = request.path_info[len(prefix):]
if not request.path_info:
request.path_info = '/'
break
# Next, determine the content type based on the URI suffix
for format, ctype in self.formats.items():
if request.path_info.endswith(format):
result.set_ctype(ctype)
# Update the request particulars
request.path_info = request.path_info[:-len(format)]
break | python | def _proc_uri(self, request, result):
"""
Process the URI rules for the request. Both the desired API
version and desired content type can be determined from those
rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in.
"""
if result:
# Result has already been fully determined
return
# First, determine the version based on the URI prefix
for prefix, version in self.uris:
if (request.path_info == prefix or
request.path_info.startswith(prefix + '/')):
result.set_version(version)
# Update the request particulars
request.script_name += prefix
request.path_info = request.path_info[len(prefix):]
if not request.path_info:
request.path_info = '/'
break
# Next, determine the content type based on the URI suffix
for format, ctype in self.formats.items():
if request.path_info.endswith(format):
result.set_ctype(ctype)
# Update the request particulars
request.path_info = request.path_info[:-len(format)]
break | [
"def",
"_proc_uri",
"(",
"self",
",",
"request",
",",
"result",
")",
":",
"if",
"result",
":",
"# Result has already been fully determined",
"return",
"# First, determine the version based on the URI prefix",
"for",
"prefix",
",",
"version",
"in",
"self",
".",
"uris",
":",
"if",
"(",
"request",
".",
"path_info",
"==",
"prefix",
"or",
"request",
".",
"path_info",
".",
"startswith",
"(",
"prefix",
"+",
"'/'",
")",
")",
":",
"result",
".",
"set_version",
"(",
"version",
")",
"# Update the request particulars",
"request",
".",
"script_name",
"+=",
"prefix",
"request",
".",
"path_info",
"=",
"request",
".",
"path_info",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"if",
"not",
"request",
".",
"path_info",
":",
"request",
".",
"path_info",
"=",
"'/'",
"break",
"# Next, determine the content type based on the URI suffix",
"for",
"format",
",",
"ctype",
"in",
"self",
".",
"formats",
".",
"items",
"(",
")",
":",
"if",
"request",
".",
"path_info",
".",
"endswith",
"(",
"format",
")",
":",
"result",
".",
"set_ctype",
"(",
"ctype",
")",
"# Update the request particulars",
"request",
".",
"path_info",
"=",
"request",
".",
"path_info",
"[",
":",
"-",
"len",
"(",
"format",
")",
"]",
"break"
] | Process the URI rules for the request. Both the desired API
version and desired content type can be determined from those
rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in. | [
"Process",
"the",
"URI",
"rules",
"for",
"the",
"request",
".",
"Both",
"the",
"desired",
"API",
"version",
"and",
"desired",
"content",
"type",
"can",
"be",
"determined",
"from",
"those",
"rules",
"."
] | 90ca68e7d6426a77db8a926171f8d3bbeb00ee4c | https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L660-L694 |
250,920 | klmitch/aversion | aversion.py | AVersion._proc_ctype_header | def _proc_ctype_header(self, request, result):
"""
Process the Content-Type header rules for the request. Only
the desired API version can be determined from those rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in.
"""
if result:
# Result has already been fully determined
return
try:
ctype = request.headers['content-type']
except KeyError:
# No content-type header to examine
return
# Parse the content type
ctype, params = parse_ctype(ctype)
# Is it a recognized content type?
if ctype not in self.types:
return
# Get the mapped ctype and version
mapped_ctype, mapped_version = self.types[ctype](params)
# Update the content type header and set the version
if mapped_ctype:
request.environ['aversion.request_type'] = mapped_ctype
request.environ['aversion.orig_request_type'] = ctype
request.environ['aversion.content_type'] = \
request.headers['content-type']
if self.overwrite_headers:
request.headers['content-type'] = mapped_ctype
if mapped_version:
result.set_version(mapped_version) | python | def _proc_ctype_header(self, request, result):
"""
Process the Content-Type header rules for the request. Only
the desired API version can be determined from those rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in.
"""
if result:
# Result has already been fully determined
return
try:
ctype = request.headers['content-type']
except KeyError:
# No content-type header to examine
return
# Parse the content type
ctype, params = parse_ctype(ctype)
# Is it a recognized content type?
if ctype not in self.types:
return
# Get the mapped ctype and version
mapped_ctype, mapped_version = self.types[ctype](params)
# Update the content type header and set the version
if mapped_ctype:
request.environ['aversion.request_type'] = mapped_ctype
request.environ['aversion.orig_request_type'] = ctype
request.environ['aversion.content_type'] = \
request.headers['content-type']
if self.overwrite_headers:
request.headers['content-type'] = mapped_ctype
if mapped_version:
result.set_version(mapped_version) | [
"def",
"_proc_ctype_header",
"(",
"self",
",",
"request",
",",
"result",
")",
":",
"if",
"result",
":",
"# Result has already been fully determined",
"return",
"try",
":",
"ctype",
"=",
"request",
".",
"headers",
"[",
"'content-type'",
"]",
"except",
"KeyError",
":",
"# No content-type header to examine",
"return",
"# Parse the content type",
"ctype",
",",
"params",
"=",
"parse_ctype",
"(",
"ctype",
")",
"# Is it a recognized content type?",
"if",
"ctype",
"not",
"in",
"self",
".",
"types",
":",
"return",
"# Get the mapped ctype and version",
"mapped_ctype",
",",
"mapped_version",
"=",
"self",
".",
"types",
"[",
"ctype",
"]",
"(",
"params",
")",
"# Update the content type header and set the version",
"if",
"mapped_ctype",
":",
"request",
".",
"environ",
"[",
"'aversion.request_type'",
"]",
"=",
"mapped_ctype",
"request",
".",
"environ",
"[",
"'aversion.orig_request_type'",
"]",
"=",
"ctype",
"request",
".",
"environ",
"[",
"'aversion.content_type'",
"]",
"=",
"request",
".",
"headers",
"[",
"'content-type'",
"]",
"if",
"self",
".",
"overwrite_headers",
":",
"request",
".",
"headers",
"[",
"'content-type'",
"]",
"=",
"mapped_ctype",
"if",
"mapped_version",
":",
"result",
".",
"set_version",
"(",
"mapped_version",
")"
] | Process the Content-Type header rules for the request. Only
the desired API version can be determined from those rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in. | [
"Process",
"the",
"Content",
"-",
"Type",
"header",
"rules",
"for",
"the",
"request",
".",
"Only",
"the",
"desired",
"API",
"version",
"can",
"be",
"determined",
"from",
"those",
"rules",
"."
] | 90ca68e7d6426a77db8a926171f8d3bbeb00ee4c | https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L696-L734 |
250,921 | klmitch/aversion | aversion.py | AVersion._proc_accept_header | def _proc_accept_header(self, request, result):
"""
Process the Accept header rules for the request. Both the
desired API version and content type can be determined from
those rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in.
"""
if result:
# Result has already been fully determined
return
try:
accept = request.headers['accept']
except KeyError:
# No Accept header to examine
return
# Obtain the best-match content type and its parameters
ctype, params = best_match(accept, self.types.keys())
# Is it a recognized content type?
if ctype not in self.types:
return
# Get the mapped ctype and version
mapped_ctype, mapped_version = self.types[ctype](params)
# Set the content type and version
if mapped_ctype:
result.set_ctype(mapped_ctype, ctype)
if mapped_version:
result.set_version(mapped_version) | python | def _proc_accept_header(self, request, result):
"""
Process the Accept header rules for the request. Both the
desired API version and content type can be determined from
those rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in.
"""
if result:
# Result has already been fully determined
return
try:
accept = request.headers['accept']
except KeyError:
# No Accept header to examine
return
# Obtain the best-match content type and its parameters
ctype, params = best_match(accept, self.types.keys())
# Is it a recognized content type?
if ctype not in self.types:
return
# Get the mapped ctype and version
mapped_ctype, mapped_version = self.types[ctype](params)
# Set the content type and version
if mapped_ctype:
result.set_ctype(mapped_ctype, ctype)
if mapped_version:
result.set_version(mapped_version) | [
"def",
"_proc_accept_header",
"(",
"self",
",",
"request",
",",
"result",
")",
":",
"if",
"result",
":",
"# Result has already been fully determined",
"return",
"try",
":",
"accept",
"=",
"request",
".",
"headers",
"[",
"'accept'",
"]",
"except",
"KeyError",
":",
"# No Accept header to examine",
"return",
"# Obtain the best-match content type and its parameters",
"ctype",
",",
"params",
"=",
"best_match",
"(",
"accept",
",",
"self",
".",
"types",
".",
"keys",
"(",
")",
")",
"# Is it a recognized content type?",
"if",
"ctype",
"not",
"in",
"self",
".",
"types",
":",
"return",
"# Get the mapped ctype and version",
"mapped_ctype",
",",
"mapped_version",
"=",
"self",
".",
"types",
"[",
"ctype",
"]",
"(",
"params",
")",
"# Set the content type and version",
"if",
"mapped_ctype",
":",
"result",
".",
"set_ctype",
"(",
"mapped_ctype",
",",
"ctype",
")",
"if",
"mapped_version",
":",
"result",
".",
"set_version",
"(",
"mapped_version",
")"
] | Process the Accept header rules for the request. Both the
desired API version and content type can be determined from
those rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in. | [
"Process",
"the",
"Accept",
"header",
"rules",
"for",
"the",
"request",
".",
"Both",
"the",
"desired",
"API",
"version",
"and",
"content",
"type",
"can",
"be",
"determined",
"from",
"those",
"rules",
"."
] | 90ca68e7d6426a77db8a926171f8d3bbeb00ee4c | https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L736-L770 |
250,922 | andrewjsledge/django-hash-filter | django_hash_filter/templatetags/__init__.py | get_available_hashes | def get_available_hashes():
"""
Returns a tuple of the available hashes
"""
if sys.version_info >= (3,2):
return hashlib.algorithms_available
elif sys.version_info >= (2,7) and sys.version_info < (3,0):
return hashlib.algorithms
else:
return 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512' | python | def get_available_hashes():
"""
Returns a tuple of the available hashes
"""
if sys.version_info >= (3,2):
return hashlib.algorithms_available
elif sys.version_info >= (2,7) and sys.version_info < (3,0):
return hashlib.algorithms
else:
return 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512' | [
"def",
"get_available_hashes",
"(",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"2",
")",
":",
"return",
"hashlib",
".",
"algorithms_available",
"elif",
"sys",
".",
"version_info",
">=",
"(",
"2",
",",
"7",
")",
"and",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"return",
"hashlib",
".",
"algorithms",
"else",
":",
"return",
"'md5'",
",",
"'sha1'",
",",
"'sha224'",
",",
"'sha256'",
",",
"'sha384'",
",",
"'sha512'"
] | Returns a tuple of the available hashes | [
"Returns",
"a",
"tuple",
"of",
"the",
"available",
"hashes"
] | ea90b2903938e0733d3abfafed308a8d041d9fe7 | https://github.com/andrewjsledge/django-hash-filter/blob/ea90b2903938e0733d3abfafed308a8d041d9fe7/django_hash_filter/templatetags/__init__.py#L8-L17 |
250,923 | fedora-infra/fmn.lib | fmn/lib/defaults.py | create_defaults_for | def create_defaults_for(session, user, only_for=None, detail_values=None):
""" Create a sizable amount of defaults for a new user. """
detail_values = detail_values or {}
if not user.openid.endswith('.fedoraproject.org'):
log.warn("New user not from fedoraproject.org. No defaults set.")
return
# the openid is of the form USERNAME.id.fedoraproject.org
nick = user.openid.split('.')[0]
# TODO -- make the root here configurable.
valid_paths = fmn.lib.load_rules(root='fmn.rules')
def rule_maker(path, **kw):
""" Shorthand function, used inside loops below. """
return fmn.lib.models.Rule.create_from_code_path(
session, valid_paths, path, **kw)
def contexts():
names = ['email', 'irc', 'sse']
if only_for:
names = [only_for.name]
for name in names:
context = fmn.lib.models.Context.get(session, name)
if context:
yield context
else:
log.warn("No such context %r is in the DB." % name)
# For each context, build one little and two big filters
for context in contexts():
pref = fmn.lib.models.Preference.load(session, user, context)
if not pref:
value = detail_values.get(context.name)
pref = fmn.lib.models.Preference.create(
session, user, context, detail_value=value)
# Add a filter that looks for packages of this user
filt = fmn.lib.models.Filter.create(
session, "Events on packages that I own")
filt.add_rule(session, valid_paths,
"fmn.rules:user_package_filter", fasnick=nick)
# If this is a message about a package of mine, **and** i'm responsible
# for it, then don't trigger this filter. Rely on the previous one.
filt.add_rule(session, valid_paths,
"fmn.rules:user_filter",
fasnick=nick,
negated=True)
# Right off the bat, ignore all messages from non-primary kojis.
filt.add_rule(session, valid_paths,
"fmn.rules:koji_instance",
instance="ppc,s390,arm",
negated=True)
# And furthermore, exclude lots of message types
for code_path in exclusion_packages + exclusion_mutual:
filt.add_rule(
session, valid_paths, "fmn.rules:%s" % code_path, negated=True)
pref.add_filter(session, filt, notify=True)
# END "packages I own"
# Add a filter that looks for this user
filt = fmn.lib.models.Filter.create(
session, "Events referring to my username")
filt.add_rule(session, valid_paths,
"fmn.rules:user_filter", fasnick=nick)
# Right off the bat, ignore all messages from non-primary kojis.
filt.add_rule(session, valid_paths,
"fmn.rules:koji_instance",
instance="ppc,s390,arm",
negated=True)
# And furthermore exclude lots of message types
for code_path in exclusion_username + exclusion_mutual:
filt.add_rule(
session, valid_paths, "fmn.rules:%s" % code_path, negated=True)
pref.add_filter(session, filt, notify=True)
# END "events references my username"
# Add a taskotron filter
filt = fmn.lib.models.Filter.create(
session, "Critical taskotron tasks on my packages")
filt.add_rule(session, valid_paths,
"fmn.rules:user_package_filter",
fasnick=nick)
filt.add_rule(session, valid_paths,
"fmn.rules:taskotron_release_critical_task")
filt.add_rule(session, valid_paths,
"fmn.rules:taskotron_task_particular_or_changed_outcome",
outcome='FAILED')
pref.add_filter(session, filt, notify=True) | python | def create_defaults_for(session, user, only_for=None, detail_values=None):
""" Create a sizable amount of defaults for a new user. """
detail_values = detail_values or {}
if not user.openid.endswith('.fedoraproject.org'):
log.warn("New user not from fedoraproject.org. No defaults set.")
return
# the openid is of the form USERNAME.id.fedoraproject.org
nick = user.openid.split('.')[0]
# TODO -- make the root here configurable.
valid_paths = fmn.lib.load_rules(root='fmn.rules')
def rule_maker(path, **kw):
""" Shorthand function, used inside loops below. """
return fmn.lib.models.Rule.create_from_code_path(
session, valid_paths, path, **kw)
def contexts():
names = ['email', 'irc', 'sse']
if only_for:
names = [only_for.name]
for name in names:
context = fmn.lib.models.Context.get(session, name)
if context:
yield context
else:
log.warn("No such context %r is in the DB." % name)
# For each context, build one little and two big filters
for context in contexts():
pref = fmn.lib.models.Preference.load(session, user, context)
if not pref:
value = detail_values.get(context.name)
pref = fmn.lib.models.Preference.create(
session, user, context, detail_value=value)
# Add a filter that looks for packages of this user
filt = fmn.lib.models.Filter.create(
session, "Events on packages that I own")
filt.add_rule(session, valid_paths,
"fmn.rules:user_package_filter", fasnick=nick)
# If this is a message about a package of mine, **and** i'm responsible
# for it, then don't trigger this filter. Rely on the previous one.
filt.add_rule(session, valid_paths,
"fmn.rules:user_filter",
fasnick=nick,
negated=True)
# Right off the bat, ignore all messages from non-primary kojis.
filt.add_rule(session, valid_paths,
"fmn.rules:koji_instance",
instance="ppc,s390,arm",
negated=True)
# And furthermore, exclude lots of message types
for code_path in exclusion_packages + exclusion_mutual:
filt.add_rule(
session, valid_paths, "fmn.rules:%s" % code_path, negated=True)
pref.add_filter(session, filt, notify=True)
# END "packages I own"
# Add a filter that looks for this user
filt = fmn.lib.models.Filter.create(
session, "Events referring to my username")
filt.add_rule(session, valid_paths,
"fmn.rules:user_filter", fasnick=nick)
# Right off the bat, ignore all messages from non-primary kojis.
filt.add_rule(session, valid_paths,
"fmn.rules:koji_instance",
instance="ppc,s390,arm",
negated=True)
# And furthermore exclude lots of message types
for code_path in exclusion_username + exclusion_mutual:
filt.add_rule(
session, valid_paths, "fmn.rules:%s" % code_path, negated=True)
pref.add_filter(session, filt, notify=True)
# END "events references my username"
# Add a taskotron filter
filt = fmn.lib.models.Filter.create(
session, "Critical taskotron tasks on my packages")
filt.add_rule(session, valid_paths,
"fmn.rules:user_package_filter",
fasnick=nick)
filt.add_rule(session, valid_paths,
"fmn.rules:taskotron_release_critical_task")
filt.add_rule(session, valid_paths,
"fmn.rules:taskotron_task_particular_or_changed_outcome",
outcome='FAILED')
pref.add_filter(session, filt, notify=True) | [
"def",
"create_defaults_for",
"(",
"session",
",",
"user",
",",
"only_for",
"=",
"None",
",",
"detail_values",
"=",
"None",
")",
":",
"detail_values",
"=",
"detail_values",
"or",
"{",
"}",
"if",
"not",
"user",
".",
"openid",
".",
"endswith",
"(",
"'.fedoraproject.org'",
")",
":",
"log",
".",
"warn",
"(",
"\"New user not from fedoraproject.org. No defaults set.\"",
")",
"return",
"# the openid is of the form USERNAME.id.fedoraproject.org",
"nick",
"=",
"user",
".",
"openid",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"# TODO -- make the root here configurable.",
"valid_paths",
"=",
"fmn",
".",
"lib",
".",
"load_rules",
"(",
"root",
"=",
"'fmn.rules'",
")",
"def",
"rule_maker",
"(",
"path",
",",
"*",
"*",
"kw",
")",
":",
"\"\"\" Shorthand function, used inside loops below. \"\"\"",
"return",
"fmn",
".",
"lib",
".",
"models",
".",
"Rule",
".",
"create_from_code_path",
"(",
"session",
",",
"valid_paths",
",",
"path",
",",
"*",
"*",
"kw",
")",
"def",
"contexts",
"(",
")",
":",
"names",
"=",
"[",
"'email'",
",",
"'irc'",
",",
"'sse'",
"]",
"if",
"only_for",
":",
"names",
"=",
"[",
"only_for",
".",
"name",
"]",
"for",
"name",
"in",
"names",
":",
"context",
"=",
"fmn",
".",
"lib",
".",
"models",
".",
"Context",
".",
"get",
"(",
"session",
",",
"name",
")",
"if",
"context",
":",
"yield",
"context",
"else",
":",
"log",
".",
"warn",
"(",
"\"No such context %r is in the DB.\"",
"%",
"name",
")",
"# For each context, build one little and two big filters",
"for",
"context",
"in",
"contexts",
"(",
")",
":",
"pref",
"=",
"fmn",
".",
"lib",
".",
"models",
".",
"Preference",
".",
"load",
"(",
"session",
",",
"user",
",",
"context",
")",
"if",
"not",
"pref",
":",
"value",
"=",
"detail_values",
".",
"get",
"(",
"context",
".",
"name",
")",
"pref",
"=",
"fmn",
".",
"lib",
".",
"models",
".",
"Preference",
".",
"create",
"(",
"session",
",",
"user",
",",
"context",
",",
"detail_value",
"=",
"value",
")",
"# Add a filter that looks for packages of this user",
"filt",
"=",
"fmn",
".",
"lib",
".",
"models",
".",
"Filter",
".",
"create",
"(",
"session",
",",
"\"Events on packages that I own\"",
")",
"filt",
".",
"add_rule",
"(",
"session",
",",
"valid_paths",
",",
"\"fmn.rules:user_package_filter\"",
",",
"fasnick",
"=",
"nick",
")",
"# If this is a message about a package of mine, **and** i'm responsible",
"# for it, then don't trigger this filter. Rely on the previous one.",
"filt",
".",
"add_rule",
"(",
"session",
",",
"valid_paths",
",",
"\"fmn.rules:user_filter\"",
",",
"fasnick",
"=",
"nick",
",",
"negated",
"=",
"True",
")",
"# Right off the bat, ignore all messages from non-primary kojis.",
"filt",
".",
"add_rule",
"(",
"session",
",",
"valid_paths",
",",
"\"fmn.rules:koji_instance\"",
",",
"instance",
"=",
"\"ppc,s390,arm\"",
",",
"negated",
"=",
"True",
")",
"# And furthermore, exclude lots of message types",
"for",
"code_path",
"in",
"exclusion_packages",
"+",
"exclusion_mutual",
":",
"filt",
".",
"add_rule",
"(",
"session",
",",
"valid_paths",
",",
"\"fmn.rules:%s\"",
"%",
"code_path",
",",
"negated",
"=",
"True",
")",
"pref",
".",
"add_filter",
"(",
"session",
",",
"filt",
",",
"notify",
"=",
"True",
")",
"# END \"packages I own\"",
"# Add a filter that looks for this user",
"filt",
"=",
"fmn",
".",
"lib",
".",
"models",
".",
"Filter",
".",
"create",
"(",
"session",
",",
"\"Events referring to my username\"",
")",
"filt",
".",
"add_rule",
"(",
"session",
",",
"valid_paths",
",",
"\"fmn.rules:user_filter\"",
",",
"fasnick",
"=",
"nick",
")",
"# Right off the bat, ignore all messages from non-primary kojis.",
"filt",
".",
"add_rule",
"(",
"session",
",",
"valid_paths",
",",
"\"fmn.rules:koji_instance\"",
",",
"instance",
"=",
"\"ppc,s390,arm\"",
",",
"negated",
"=",
"True",
")",
"# And furthermore exclude lots of message types",
"for",
"code_path",
"in",
"exclusion_username",
"+",
"exclusion_mutual",
":",
"filt",
".",
"add_rule",
"(",
"session",
",",
"valid_paths",
",",
"\"fmn.rules:%s\"",
"%",
"code_path",
",",
"negated",
"=",
"True",
")",
"pref",
".",
"add_filter",
"(",
"session",
",",
"filt",
",",
"notify",
"=",
"True",
")",
"# END \"events references my username\"",
"# Add a taskotron filter",
"filt",
"=",
"fmn",
".",
"lib",
".",
"models",
".",
"Filter",
".",
"create",
"(",
"session",
",",
"\"Critical taskotron tasks on my packages\"",
")",
"filt",
".",
"add_rule",
"(",
"session",
",",
"valid_paths",
",",
"\"fmn.rules:user_package_filter\"",
",",
"fasnick",
"=",
"nick",
")",
"filt",
".",
"add_rule",
"(",
"session",
",",
"valid_paths",
",",
"\"fmn.rules:taskotron_release_critical_task\"",
")",
"filt",
".",
"add_rule",
"(",
"session",
",",
"valid_paths",
",",
"\"fmn.rules:taskotron_task_particular_or_changed_outcome\"",
",",
"outcome",
"=",
"'FAILED'",
")",
"pref",
".",
"add_filter",
"(",
"session",
",",
"filt",
",",
"notify",
"=",
"True",
")"
] | Create a sizable amount of defaults for a new user. | [
"Create",
"a",
"sizable",
"amount",
"of",
"defaults",
"for",
"a",
"new",
"user",
"."
] | 3120725556153d07c1809530f0fadcf250439110 | https://github.com/fedora-infra/fmn.lib/blob/3120725556153d07c1809530f0fadcf250439110/fmn/lib/defaults.py#L219-L317 |
250,924 | armstrong/armstrong.core.arm_sections | armstrong/core/arm_sections/models.py | SectionManager.get_queryset | def get_queryset(self): # DROP_WITH_DJANGO15
"""Use the same ordering as TreeManager"""
args = (self.model._mptt_meta.tree_id_attr,
self.model._mptt_meta.left_attr)
method = 'get_query_set' if django.VERSION < (1, 6) else 'get_queryset'
return getattr(super(SectionManager, self), method)().order_by(*args) | python | def get_queryset(self): # DROP_WITH_DJANGO15
"""Use the same ordering as TreeManager"""
args = (self.model._mptt_meta.tree_id_attr,
self.model._mptt_meta.left_attr)
method = 'get_query_set' if django.VERSION < (1, 6) else 'get_queryset'
return getattr(super(SectionManager, self), method)().order_by(*args) | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"# DROP_WITH_DJANGO15",
"args",
"=",
"(",
"self",
".",
"model",
".",
"_mptt_meta",
".",
"tree_id_attr",
",",
"self",
".",
"model",
".",
"_mptt_meta",
".",
"left_attr",
")",
"method",
"=",
"'get_query_set'",
"if",
"django",
".",
"VERSION",
"<",
"(",
"1",
",",
"6",
")",
"else",
"'get_queryset'",
"return",
"getattr",
"(",
"super",
"(",
"SectionManager",
",",
"self",
")",
",",
"method",
")",
"(",
")",
".",
"order_by",
"(",
"*",
"args",
")"
] | Use the same ordering as TreeManager | [
"Use",
"the",
"same",
"ordering",
"as",
"TreeManager"
] | 39c999c93771da909359e53b35afefe4846f77cb | https://github.com/armstrong/armstrong.core.arm_sections/blob/39c999c93771da909359e53b35afefe4846f77cb/armstrong/core/arm_sections/models.py#L23-L29 |
250,925 | armstrong/armstrong.core.arm_sections | armstrong/core/arm_sections/models.py | BaseSection.item_related_name | def item_related_name(self):
"""
The ManyToMany field on the item class pointing to this class.
If there is more than one field, this value will be None.
"""
if not hasattr(self, '_item_related_name'):
many_to_many_rels = \
get_section_many_to_many_relations(self.__class__)
if len(many_to_many_rels) != 1:
self._item_related_name = None
else:
self._item_related_name = many_to_many_rels[0].field.name
return self._item_related_name | python | def item_related_name(self):
"""
The ManyToMany field on the item class pointing to this class.
If there is more than one field, this value will be None.
"""
if not hasattr(self, '_item_related_name'):
many_to_many_rels = \
get_section_many_to_many_relations(self.__class__)
if len(many_to_many_rels) != 1:
self._item_related_name = None
else:
self._item_related_name = many_to_many_rels[0].field.name
return self._item_related_name | [
"def",
"item_related_name",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_item_related_name'",
")",
":",
"many_to_many_rels",
"=",
"get_section_many_to_many_relations",
"(",
"self",
".",
"__class__",
")",
"if",
"len",
"(",
"many_to_many_rels",
")",
"!=",
"1",
":",
"self",
".",
"_item_related_name",
"=",
"None",
"else",
":",
"self",
".",
"_item_related_name",
"=",
"many_to_many_rels",
"[",
"0",
"]",
".",
"field",
".",
"name",
"return",
"self",
".",
"_item_related_name"
] | The ManyToMany field on the item class pointing to this class.
If there is more than one field, this value will be None. | [
"The",
"ManyToMany",
"field",
"on",
"the",
"item",
"class",
"pointing",
"to",
"this",
"class",
"."
] | 39c999c93771da909359e53b35afefe4846f77cb | https://github.com/armstrong/armstrong.core.arm_sections/blob/39c999c93771da909359e53b35afefe4846f77cb/armstrong/core/arm_sections/models.py#L92-L105 |
250,926 | armstrong/armstrong.core.arm_sections | armstrong/core/arm_sections/models.py | BaseSection.add_item | def add_item(self, item, field_name=None):
"""
Add the item to the specified section.
Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.
Behavior on other items is undefined.
"""
field_name = self._choose_field_name(field_name)
related_manager = getattr(item, field_name)
related_manager.add(self) | python | def add_item(self, item, field_name=None):
"""
Add the item to the specified section.
Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.
Behavior on other items is undefined.
"""
field_name = self._choose_field_name(field_name)
related_manager = getattr(item, field_name)
related_manager.add(self) | [
"def",
"add_item",
"(",
"self",
",",
"item",
",",
"field_name",
"=",
"None",
")",
":",
"field_name",
"=",
"self",
".",
"_choose_field_name",
"(",
"field_name",
")",
"related_manager",
"=",
"getattr",
"(",
"item",
",",
"field_name",
")",
"related_manager",
".",
"add",
"(",
"self",
")"
] | Add the item to the specified section.
Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.
Behavior on other items is undefined. | [
"Add",
"the",
"item",
"to",
"the",
"specified",
"section",
"."
] | 39c999c93771da909359e53b35afefe4846f77cb | https://github.com/armstrong/armstrong.core.arm_sections/blob/39c999c93771da909359e53b35afefe4846f77cb/armstrong/core/arm_sections/models.py#L131-L140 |
250,927 | armstrong/armstrong.core.arm_sections | armstrong/core/arm_sections/models.py | BaseSection.remove_item | def remove_item(self, item, field_name=None):
"""
Remove the item from the specified section.
Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.
Behavior on other items is undefined.
"""
field_name = self._choose_field_name(field_name)
related_manager = getattr(item, field_name)
related_manager.remove(self) | python | def remove_item(self, item, field_name=None):
"""
Remove the item from the specified section.
Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.
Behavior on other items is undefined.
"""
field_name = self._choose_field_name(field_name)
related_manager = getattr(item, field_name)
related_manager.remove(self) | [
"def",
"remove_item",
"(",
"self",
",",
"item",
",",
"field_name",
"=",
"None",
")",
":",
"field_name",
"=",
"self",
".",
"_choose_field_name",
"(",
"field_name",
")",
"related_manager",
"=",
"getattr",
"(",
"item",
",",
"field_name",
")",
"related_manager",
".",
"remove",
"(",
"self",
")"
] | Remove the item from the specified section.
Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.
Behavior on other items is undefined. | [
"Remove",
"the",
"item",
"from",
"the",
"specified",
"section",
"."
] | 39c999c93771da909359e53b35afefe4846f77cb | https://github.com/armstrong/armstrong.core.arm_sections/blob/39c999c93771da909359e53b35afefe4846f77cb/armstrong/core/arm_sections/models.py#L142-L151 |
250,928 | armstrong/armstrong.core.arm_sections | armstrong/core/arm_sections/models.py | BaseSection.toggle_item | def toggle_item(self, item, test_func, field_name=None):
"""
Toggles the section based on test_func.
test_func takes an item and returns a boolean. If it returns True, the
item will be added to the given section. It will be removed from the
section otherwise.
Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.
Behavior on other items is undefined.
"""
if test_func(item):
self.add_item(item, field_name)
return True
else:
self.remove_item(item, field_name)
return False | python | def toggle_item(self, item, test_func, field_name=None):
"""
Toggles the section based on test_func.
test_func takes an item and returns a boolean. If it returns True, the
item will be added to the given section. It will be removed from the
section otherwise.
Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.
Behavior on other items is undefined.
"""
if test_func(item):
self.add_item(item, field_name)
return True
else:
self.remove_item(item, field_name)
return False | [
"def",
"toggle_item",
"(",
"self",
",",
"item",
",",
"test_func",
",",
"field_name",
"=",
"None",
")",
":",
"if",
"test_func",
"(",
"item",
")",
":",
"self",
".",
"add_item",
"(",
"item",
",",
"field_name",
")",
"return",
"True",
"else",
":",
"self",
".",
"remove_item",
"(",
"item",
",",
"field_name",
")",
"return",
"False"
] | Toggles the section based on test_func.
test_func takes an item and returns a boolean. If it returns True, the
item will be added to the given section. It will be removed from the
section otherwise.
Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.
Behavior on other items is undefined. | [
"Toggles",
"the",
"section",
"based",
"on",
"test_func",
"."
] | 39c999c93771da909359e53b35afefe4846f77cb | https://github.com/armstrong/armstrong.core.arm_sections/blob/39c999c93771da909359e53b35afefe4846f77cb/armstrong/core/arm_sections/models.py#L153-L169 |
250,929 | samirelanduk/quickplots | quickplots/charts.py | determine_ticks | def determine_ticks(low, high):
"""The function used to auto-generate ticks for an axis, based on its
range of values.
:param Number low: The lower bound of the axis.
:param Number high: The upper bound of the axis.
:rtype: ``tuple``"""
range_ = high - low
tick_difference = 10 ** math.floor(math.log10(range_ / 1.25))
low_tick = math.floor(low / tick_difference) * tick_difference
ticks = [low_tick + tick_difference] if low_tick < low else [low_tick]
while ticks[-1] + tick_difference <= high:
ticks.append(ticks[-1] + tick_difference)
return tuple(ticks) | python | def determine_ticks(low, high):
"""The function used to auto-generate ticks for an axis, based on its
range of values.
:param Number low: The lower bound of the axis.
:param Number high: The upper bound of the axis.
:rtype: ``tuple``"""
range_ = high - low
tick_difference = 10 ** math.floor(math.log10(range_ / 1.25))
low_tick = math.floor(low / tick_difference) * tick_difference
ticks = [low_tick + tick_difference] if low_tick < low else [low_tick]
while ticks[-1] + tick_difference <= high:
ticks.append(ticks[-1] + tick_difference)
return tuple(ticks) | [
"def",
"determine_ticks",
"(",
"low",
",",
"high",
")",
":",
"range_",
"=",
"high",
"-",
"low",
"tick_difference",
"=",
"10",
"**",
"math",
".",
"floor",
"(",
"math",
".",
"log10",
"(",
"range_",
"/",
"1.25",
")",
")",
"low_tick",
"=",
"math",
".",
"floor",
"(",
"low",
"/",
"tick_difference",
")",
"*",
"tick_difference",
"ticks",
"=",
"[",
"low_tick",
"+",
"tick_difference",
"]",
"if",
"low_tick",
"<",
"low",
"else",
"[",
"low_tick",
"]",
"while",
"ticks",
"[",
"-",
"1",
"]",
"+",
"tick_difference",
"<=",
"high",
":",
"ticks",
".",
"append",
"(",
"ticks",
"[",
"-",
"1",
"]",
"+",
"tick_difference",
")",
"return",
"tuple",
"(",
"ticks",
")"
] | The function used to auto-generate ticks for an axis, based on its
range of values.
:param Number low: The lower bound of the axis.
:param Number high: The upper bound of the axis.
:rtype: ``tuple`` | [
"The",
"function",
"used",
"to",
"auto",
"-",
"generate",
"ticks",
"for",
"an",
"axis",
"based",
"on",
"its",
"range",
"of",
"values",
"."
] | 59f5e6ff367b2c1c24ba7cf1805d03552034c6d8 | https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/charts.py#L694-L708 |
250,930 | samirelanduk/quickplots | quickplots/charts.py | AxisChart.x_ticks | def x_ticks(self, *ticks):
"""The points on the x-axis for which there are markers and grid lines.
There are default ticks, but you can pass values to this method to
override the defaults. Otherwise the method will return the ticks.
:param \*ticks: if given, these will be chart's x-ticks.
:rtype: ``tuple``"""
if ticks:
for tick in ticks:
if not is_numeric(tick):
raise TypeError("'%s' is not a numeric tick" % str(tick))
self._x_ticks = tuple(sorted(ticks))
else:
if self._x_ticks:
return self._x_ticks
else:
return determine_ticks(self.x_lower_limit(), self.x_upper_limit()) | python | def x_ticks(self, *ticks):
"""The points on the x-axis for which there are markers and grid lines.
There are default ticks, but you can pass values to this method to
override the defaults. Otherwise the method will return the ticks.
:param \*ticks: if given, these will be chart's x-ticks.
:rtype: ``tuple``"""
if ticks:
for tick in ticks:
if not is_numeric(tick):
raise TypeError("'%s' is not a numeric tick" % str(tick))
self._x_ticks = tuple(sorted(ticks))
else:
if self._x_ticks:
return self._x_ticks
else:
return determine_ticks(self.x_lower_limit(), self.x_upper_limit()) | [
"def",
"x_ticks",
"(",
"self",
",",
"*",
"ticks",
")",
":",
"if",
"ticks",
":",
"for",
"tick",
"in",
"ticks",
":",
"if",
"not",
"is_numeric",
"(",
"tick",
")",
":",
"raise",
"TypeError",
"(",
"\"'%s' is not a numeric tick\"",
"%",
"str",
"(",
"tick",
")",
")",
"self",
".",
"_x_ticks",
"=",
"tuple",
"(",
"sorted",
"(",
"ticks",
")",
")",
"else",
":",
"if",
"self",
".",
"_x_ticks",
":",
"return",
"self",
".",
"_x_ticks",
"else",
":",
"return",
"determine_ticks",
"(",
"self",
".",
"x_lower_limit",
"(",
")",
",",
"self",
".",
"x_upper_limit",
"(",
")",
")"
] | The points on the x-axis for which there are markers and grid lines.
There are default ticks, but you can pass values to this method to
override the defaults. Otherwise the method will return the ticks.
:param \*ticks: if given, these will be chart's x-ticks.
:rtype: ``tuple`` | [
"The",
"points",
"on",
"the",
"x",
"-",
"axis",
"for",
"which",
"there",
"are",
"markers",
"and",
"grid",
"lines",
"."
] | 59f5e6ff367b2c1c24ba7cf1805d03552034c6d8 | https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/charts.py#L495-L513 |
250,931 | samirelanduk/quickplots | quickplots/charts.py | AxisChart.y_ticks | def y_ticks(self, *ticks):
"""The points on the y-axis for which there are markers and grid lines.
There are default ticks, but you can pass values to this method to
override the defaults. Otherwise the method will return the ticks.
:param \*ticks: if given, these will be chart's x-ticks.
:rtype: ``tuple``"""
if ticks:
for tick in ticks:
if not is_numeric(tick):
raise TypeError("'%s' is not a numeric tick" % str(tick))
self._y_ticks = tuple(sorted(ticks))
else:
if self._y_ticks:
return self._y_ticks
else:
return determine_ticks(self.y_lower_limit(), self.y_upper_limit()) | python | def y_ticks(self, *ticks):
"""The points on the y-axis for which there are markers and grid lines.
There are default ticks, but you can pass values to this method to
override the defaults. Otherwise the method will return the ticks.
:param \*ticks: if given, these will be chart's x-ticks.
:rtype: ``tuple``"""
if ticks:
for tick in ticks:
if not is_numeric(tick):
raise TypeError("'%s' is not a numeric tick" % str(tick))
self._y_ticks = tuple(sorted(ticks))
else:
if self._y_ticks:
return self._y_ticks
else:
return determine_ticks(self.y_lower_limit(), self.y_upper_limit()) | [
"def",
"y_ticks",
"(",
"self",
",",
"*",
"ticks",
")",
":",
"if",
"ticks",
":",
"for",
"tick",
"in",
"ticks",
":",
"if",
"not",
"is_numeric",
"(",
"tick",
")",
":",
"raise",
"TypeError",
"(",
"\"'%s' is not a numeric tick\"",
"%",
"str",
"(",
"tick",
")",
")",
"self",
".",
"_y_ticks",
"=",
"tuple",
"(",
"sorted",
"(",
"ticks",
")",
")",
"else",
":",
"if",
"self",
".",
"_y_ticks",
":",
"return",
"self",
".",
"_y_ticks",
"else",
":",
"return",
"determine_ticks",
"(",
"self",
".",
"y_lower_limit",
"(",
")",
",",
"self",
".",
"y_upper_limit",
"(",
")",
")"
] | The points on the y-axis for which there are markers and grid lines.
There are default ticks, but you can pass values to this method to
override the defaults. Otherwise the method will return the ticks.
:param \*ticks: if given, these will be chart's x-ticks.
:rtype: ``tuple`` | [
"The",
"points",
"on",
"the",
"y",
"-",
"axis",
"for",
"which",
"there",
"are",
"markers",
"and",
"grid",
"lines",
"."
] | 59f5e6ff367b2c1c24ba7cf1805d03552034c6d8 | https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/charts.py#L516-L534 |
250,932 | samirelanduk/quickplots | quickplots/charts.py | AxisChart.x_grid | def x_grid(self, grid=None):
"""The horizontal lines that run accross the chart from the x-ticks.
If a boolean value is given, these gridlines will be turned on or off.
Otherwise, the method will return their current state.
:param bool grid: Turns the gridlines on or off.
:rtype: ``bool``"""
if grid is None:
return self._x_grid
else:
if not isinstance(grid, bool):
raise TypeError("grid must be boolean, not '%s'" % grid)
self._x_grid = grid | python | def x_grid(self, grid=None):
"""The horizontal lines that run accross the chart from the x-ticks.
If a boolean value is given, these gridlines will be turned on or off.
Otherwise, the method will return their current state.
:param bool grid: Turns the gridlines on or off.
:rtype: ``bool``"""
if grid is None:
return self._x_grid
else:
if not isinstance(grid, bool):
raise TypeError("grid must be boolean, not '%s'" % grid)
self._x_grid = grid | [
"def",
"x_grid",
"(",
"self",
",",
"grid",
"=",
"None",
")",
":",
"if",
"grid",
"is",
"None",
":",
"return",
"self",
".",
"_x_grid",
"else",
":",
"if",
"not",
"isinstance",
"(",
"grid",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"grid must be boolean, not '%s'\"",
"%",
"grid",
")",
"self",
".",
"_x_grid",
"=",
"grid"
] | The horizontal lines that run accross the chart from the x-ticks.
If a boolean value is given, these gridlines will be turned on or off.
Otherwise, the method will return their current state.
:param bool grid: Turns the gridlines on or off.
:rtype: ``bool`` | [
"The",
"horizontal",
"lines",
"that",
"run",
"accross",
"the",
"chart",
"from",
"the",
"x",
"-",
"ticks",
"."
] | 59f5e6ff367b2c1c24ba7cf1805d03552034c6d8 | https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/charts.py#L537-L551 |
250,933 | samirelanduk/quickplots | quickplots/charts.py | AxisChart.y_grid | def y_grid(self, grid=None):
"""The vertical lines that run accross the chart from the y-ticks.
If a boolean value is given, these gridlines will be turned on or off.
Otherwise, the method will return their current state.
:param bool grid: Turns the gridlines on or off.
:rtype: ``bool``"""
if grid is None:
return self._y_grid
else:
if not isinstance(grid, bool):
raise TypeError("grid must be boolean, not '%s'" % grid)
self._y_grid = grid | python | def y_grid(self, grid=None):
"""The vertical lines that run accross the chart from the y-ticks.
If a boolean value is given, these gridlines will be turned on or off.
Otherwise, the method will return their current state.
:param bool grid: Turns the gridlines on or off.
:rtype: ``bool``"""
if grid is None:
return self._y_grid
else:
if not isinstance(grid, bool):
raise TypeError("grid must be boolean, not '%s'" % grid)
self._y_grid = grid | [
"def",
"y_grid",
"(",
"self",
",",
"grid",
"=",
"None",
")",
":",
"if",
"grid",
"is",
"None",
":",
"return",
"self",
".",
"_y_grid",
"else",
":",
"if",
"not",
"isinstance",
"(",
"grid",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"grid must be boolean, not '%s'\"",
"%",
"grid",
")",
"self",
".",
"_y_grid",
"=",
"grid"
] | The vertical lines that run accross the chart from the y-ticks.
If a boolean value is given, these gridlines will be turned on or off.
Otherwise, the method will return their current state.
:param bool grid: Turns the gridlines on or off.
:rtype: ``bool`` | [
"The",
"vertical",
"lines",
"that",
"run",
"accross",
"the",
"chart",
"from",
"the",
"y",
"-",
"ticks",
"."
] | 59f5e6ff367b2c1c24ba7cf1805d03552034c6d8 | https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/charts.py#L554-L568 |
250,934 | samirelanduk/quickplots | quickplots/charts.py | AxisChart.grid | def grid(self, grid):
"""Turns all gridlines on or off
:param bool grid: turns the gridlines on if ``True``, off if ``False``"""
if not isinstance(grid, bool):
raise TypeError("grid must be boolean, not '%s'" % grid)
self._x_grid = self._y_grid = grid | python | def grid(self, grid):
"""Turns all gridlines on or off
:param bool grid: turns the gridlines on if ``True``, off if ``False``"""
if not isinstance(grid, bool):
raise TypeError("grid must be boolean, not '%s'" % grid)
self._x_grid = self._y_grid = grid | [
"def",
"grid",
"(",
"self",
",",
"grid",
")",
":",
"if",
"not",
"isinstance",
"(",
"grid",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"grid must be boolean, not '%s'\"",
"%",
"grid",
")",
"self",
".",
"_x_grid",
"=",
"self",
".",
"_y_grid",
"=",
"grid"
] | Turns all gridlines on or off
:param bool grid: turns the gridlines on if ``True``, off if ``False`` | [
"Turns",
"all",
"gridlines",
"on",
"or",
"off"
] | 59f5e6ff367b2c1c24ba7cf1805d03552034c6d8 | https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/charts.py#L571-L578 |
250,935 | geertj/looping | lib/looping/events.py | DefaultEventLoopPolicy.get_event_loop | def get_event_loop(self):
"""Get the event loop.
This may be None or an instance of EventLoop.
"""
if (self._event_loop is None and
threading.current_thread().name == 'MainThread'):
self._event_loop = self.new_event_loop()
return self._event_loop | python | def get_event_loop(self):
"""Get the event loop.
This may be None or an instance of EventLoop.
"""
if (self._event_loop is None and
threading.current_thread().name == 'MainThread'):
self._event_loop = self.new_event_loop()
return self._event_loop | [
"def",
"get_event_loop",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_event_loop",
"is",
"None",
"and",
"threading",
".",
"current_thread",
"(",
")",
".",
"name",
"==",
"'MainThread'",
")",
":",
"self",
".",
"_event_loop",
"=",
"self",
".",
"new_event_loop",
"(",
")",
"return",
"self",
".",
"_event_loop"
] | Get the event loop.
This may be None or an instance of EventLoop. | [
"Get",
"the",
"event",
"loop",
"."
] | b60303714685aede18b37c0d80f8f55175ad7a65 | https://github.com/geertj/looping/blob/b60303714685aede18b37c0d80f8f55175ad7a65/lib/looping/events.py#L276-L284 |
250,936 | geertj/looping | lib/looping/events.py | DefaultEventLoopPolicy.set_event_loop | def set_event_loop(self, event_loop):
"""Set the event loop."""
assert event_loop is None or isinstance(event_loop, AbstractEventLoop)
self._event_loop = event_loop | python | def set_event_loop(self, event_loop):
"""Set the event loop."""
assert event_loop is None or isinstance(event_loop, AbstractEventLoop)
self._event_loop = event_loop | [
"def",
"set_event_loop",
"(",
"self",
",",
"event_loop",
")",
":",
"assert",
"event_loop",
"is",
"None",
"or",
"isinstance",
"(",
"event_loop",
",",
"AbstractEventLoop",
")",
"self",
".",
"_event_loop",
"=",
"event_loop"
] | Set the event loop. | [
"Set",
"the",
"event",
"loop",
"."
] | b60303714685aede18b37c0d80f8f55175ad7a65 | https://github.com/geertj/looping/blob/b60303714685aede18b37c0d80f8f55175ad7a65/lib/looping/events.py#L286-L289 |
250,937 | PyTables/datasette-connectors | datasette_connectors/monkey.py | patch_datasette | def patch_datasette():
"""
Monkey patching for original Datasette
"""
def inspect(self):
" Inspect the database and return a dictionary of table metadata "
if self._inspect:
return self._inspect
_inspect = {}
files = self.files
for filename in files:
self.files = (filename,)
path = Path(filename)
name = path.stem
if name in _inspect:
raise Exception("Multiple files with the same stem %s" % name)
try:
_inspect[name] = self.original_inspect()[name]
except sqlite3.DatabaseError:
tables, views, dbtype = connectors.inspect(path)
_inspect[name] = {
"hash": inspect_hash(path),
"file": str(path),
"dbtype": dbtype,
"tables": tables,
"views": views,
}
self.files = files
self._inspect = _inspect
return self._inspect
datasette.app.Datasette.original_inspect = datasette.app.Datasette.inspect
datasette.app.Datasette.inspect = inspect
async def execute(self, db_name, sql, params=None, truncate=False, custom_time_limit=None, page_size=None):
"""Executes sql against db_name in a thread"""
page_size = page_size or self.page_size
def is_sqlite3_conn():
conn = getattr(connections, db_name, None)
if not conn:
info = self.inspect()[db_name]
return info.get('dbtype', 'sqlite3') == 'sqlite3'
else:
return isinstance(conn, sqlite3.Connection)
def sql_operation_in_thread():
conn = getattr(connections, db_name, None)
if not conn:
info = self.inspect()[db_name]
conn = connectors.connect(info['file'], info['dbtype'])
setattr(connections, db_name, conn)
rows, truncated, description = conn.execute(
sql,
params or {},
truncate=truncate,
page_size=page_size,
max_returned_rows=self.max_returned_rows,
)
return Results(rows, truncated, description)
if is_sqlite3_conn():
return await self.original_execute(db_name, sql, params=params, truncate=truncate, custom_time_limit=custom_time_limit, page_size=page_size)
else:
return await asyncio.get_event_loop().run_in_executor(
self.executor, sql_operation_in_thread
)
datasette.app.Datasette.original_execute = datasette.app.Datasette.execute
datasette.app.Datasette.execute = execute | python | def patch_datasette():
"""
Monkey patching for original Datasette
"""
def inspect(self):
" Inspect the database and return a dictionary of table metadata "
if self._inspect:
return self._inspect
_inspect = {}
files = self.files
for filename in files:
self.files = (filename,)
path = Path(filename)
name = path.stem
if name in _inspect:
raise Exception("Multiple files with the same stem %s" % name)
try:
_inspect[name] = self.original_inspect()[name]
except sqlite3.DatabaseError:
tables, views, dbtype = connectors.inspect(path)
_inspect[name] = {
"hash": inspect_hash(path),
"file": str(path),
"dbtype": dbtype,
"tables": tables,
"views": views,
}
self.files = files
self._inspect = _inspect
return self._inspect
datasette.app.Datasette.original_inspect = datasette.app.Datasette.inspect
datasette.app.Datasette.inspect = inspect
async def execute(self, db_name, sql, params=None, truncate=False, custom_time_limit=None, page_size=None):
"""Executes sql against db_name in a thread"""
page_size = page_size or self.page_size
def is_sqlite3_conn():
conn = getattr(connections, db_name, None)
if not conn:
info = self.inspect()[db_name]
return info.get('dbtype', 'sqlite3') == 'sqlite3'
else:
return isinstance(conn, sqlite3.Connection)
def sql_operation_in_thread():
conn = getattr(connections, db_name, None)
if not conn:
info = self.inspect()[db_name]
conn = connectors.connect(info['file'], info['dbtype'])
setattr(connections, db_name, conn)
rows, truncated, description = conn.execute(
sql,
params or {},
truncate=truncate,
page_size=page_size,
max_returned_rows=self.max_returned_rows,
)
return Results(rows, truncated, description)
if is_sqlite3_conn():
return await self.original_execute(db_name, sql, params=params, truncate=truncate, custom_time_limit=custom_time_limit, page_size=page_size)
else:
return await asyncio.get_event_loop().run_in_executor(
self.executor, sql_operation_in_thread
)
datasette.app.Datasette.original_execute = datasette.app.Datasette.execute
datasette.app.Datasette.execute = execute | [
"def",
"patch_datasette",
"(",
")",
":",
"def",
"inspect",
"(",
"self",
")",
":",
"\" Inspect the database and return a dictionary of table metadata \"",
"if",
"self",
".",
"_inspect",
":",
"return",
"self",
".",
"_inspect",
"_inspect",
"=",
"{",
"}",
"files",
"=",
"self",
".",
"files",
"for",
"filename",
"in",
"files",
":",
"self",
".",
"files",
"=",
"(",
"filename",
",",
")",
"path",
"=",
"Path",
"(",
"filename",
")",
"name",
"=",
"path",
".",
"stem",
"if",
"name",
"in",
"_inspect",
":",
"raise",
"Exception",
"(",
"\"Multiple files with the same stem %s\"",
"%",
"name",
")",
"try",
":",
"_inspect",
"[",
"name",
"]",
"=",
"self",
".",
"original_inspect",
"(",
")",
"[",
"name",
"]",
"except",
"sqlite3",
".",
"DatabaseError",
":",
"tables",
",",
"views",
",",
"dbtype",
"=",
"connectors",
".",
"inspect",
"(",
"path",
")",
"_inspect",
"[",
"name",
"]",
"=",
"{",
"\"hash\"",
":",
"inspect_hash",
"(",
"path",
")",
",",
"\"file\"",
":",
"str",
"(",
"path",
")",
",",
"\"dbtype\"",
":",
"dbtype",
",",
"\"tables\"",
":",
"tables",
",",
"\"views\"",
":",
"views",
",",
"}",
"self",
".",
"files",
"=",
"files",
"self",
".",
"_inspect",
"=",
"_inspect",
"return",
"self",
".",
"_inspect",
"datasette",
".",
"app",
".",
"Datasette",
".",
"original_inspect",
"=",
"datasette",
".",
"app",
".",
"Datasette",
".",
"inspect",
"datasette",
".",
"app",
".",
"Datasette",
".",
"inspect",
"=",
"inspect",
"async",
"def",
"execute",
"(",
"self",
",",
"db_name",
",",
"sql",
",",
"params",
"=",
"None",
",",
"truncate",
"=",
"False",
",",
"custom_time_limit",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"\"\"\"Executes sql against db_name in a thread\"\"\"",
"page_size",
"=",
"page_size",
"or",
"self",
".",
"page_size",
"def",
"is_sqlite3_conn",
"(",
")",
":",
"conn",
"=",
"getattr",
"(",
"connections",
",",
"db_name",
",",
"None",
")",
"if",
"not",
"conn",
":",
"info",
"=",
"self",
".",
"inspect",
"(",
")",
"[",
"db_name",
"]",
"return",
"info",
".",
"get",
"(",
"'dbtype'",
",",
"'sqlite3'",
")",
"==",
"'sqlite3'",
"else",
":",
"return",
"isinstance",
"(",
"conn",
",",
"sqlite3",
".",
"Connection",
")",
"def",
"sql_operation_in_thread",
"(",
")",
":",
"conn",
"=",
"getattr",
"(",
"connections",
",",
"db_name",
",",
"None",
")",
"if",
"not",
"conn",
":",
"info",
"=",
"self",
".",
"inspect",
"(",
")",
"[",
"db_name",
"]",
"conn",
"=",
"connectors",
".",
"connect",
"(",
"info",
"[",
"'file'",
"]",
",",
"info",
"[",
"'dbtype'",
"]",
")",
"setattr",
"(",
"connections",
",",
"db_name",
",",
"conn",
")",
"rows",
",",
"truncated",
",",
"description",
"=",
"conn",
".",
"execute",
"(",
"sql",
",",
"params",
"or",
"{",
"}",
",",
"truncate",
"=",
"truncate",
",",
"page_size",
"=",
"page_size",
",",
"max_returned_rows",
"=",
"self",
".",
"max_returned_rows",
",",
")",
"return",
"Results",
"(",
"rows",
",",
"truncated",
",",
"description",
")",
"if",
"is_sqlite3_conn",
"(",
")",
":",
"return",
"await",
"self",
".",
"original_execute",
"(",
"db_name",
",",
"sql",
",",
"params",
"=",
"params",
",",
"truncate",
"=",
"truncate",
",",
"custom_time_limit",
"=",
"custom_time_limit",
",",
"page_size",
"=",
"page_size",
")",
"else",
":",
"return",
"await",
"asyncio",
".",
"get_event_loop",
"(",
")",
".",
"run_in_executor",
"(",
"self",
".",
"executor",
",",
"sql_operation_in_thread",
")",
"datasette",
".",
"app",
".",
"Datasette",
".",
"original_execute",
"=",
"datasette",
".",
"app",
".",
"Datasette",
".",
"execute",
"datasette",
".",
"app",
".",
"Datasette",
".",
"execute",
"=",
"execute"
] | Monkey patching for original Datasette | [
"Monkey",
"patching",
"for",
"original",
"Datasette"
] | b0802bdb9d86cd65524d6ffa7afb66488d167b1e | https://github.com/PyTables/datasette-connectors/blob/b0802bdb9d86cd65524d6ffa7afb66488d167b1e/datasette_connectors/monkey.py#L12-L87 |
250,938 | fedora-infra/fmn.rules | fmn/rules/utils.py | get_fas | def get_fas(config):
""" Return a fedora.client.fas2.AccountSystem object if the provided
configuration contains a FAS username and password.
"""
global _FAS
if _FAS is not None:
return _FAS
# In some development environments, having fas_credentials around is a
# pain.. so, let things proceed here, but emit a warning.
try:
creds = config['fas_credentials']
except KeyError:
log.warn("No fas_credentials available. Unable to query FAS.")
return None
default_url = 'https://admin.fedoraproject.org/accounts/'
_FAS = AccountSystem(
creds.get('base_url', default_url),
username=creds['username'],
password=creds['password'],
cache_session=False,
insecure=creds.get('insecure', False)
)
return _FAS | python | def get_fas(config):
""" Return a fedora.client.fas2.AccountSystem object if the provided
configuration contains a FAS username and password.
"""
global _FAS
if _FAS is not None:
return _FAS
# In some development environments, having fas_credentials around is a
# pain.. so, let things proceed here, but emit a warning.
try:
creds = config['fas_credentials']
except KeyError:
log.warn("No fas_credentials available. Unable to query FAS.")
return None
default_url = 'https://admin.fedoraproject.org/accounts/'
_FAS = AccountSystem(
creds.get('base_url', default_url),
username=creds['username'],
password=creds['password'],
cache_session=False,
insecure=creds.get('insecure', False)
)
return _FAS | [
"def",
"get_fas",
"(",
"config",
")",
":",
"global",
"_FAS",
"if",
"_FAS",
"is",
"not",
"None",
":",
"return",
"_FAS",
"# In some development environments, having fas_credentials around is a",
"# pain.. so, let things proceed here, but emit a warning.",
"try",
":",
"creds",
"=",
"config",
"[",
"'fas_credentials'",
"]",
"except",
"KeyError",
":",
"log",
".",
"warn",
"(",
"\"No fas_credentials available. Unable to query FAS.\"",
")",
"return",
"None",
"default_url",
"=",
"'https://admin.fedoraproject.org/accounts/'",
"_FAS",
"=",
"AccountSystem",
"(",
"creds",
".",
"get",
"(",
"'base_url'",
",",
"default_url",
")",
",",
"username",
"=",
"creds",
"[",
"'username'",
"]",
",",
"password",
"=",
"creds",
"[",
"'password'",
"]",
",",
"cache_session",
"=",
"False",
",",
"insecure",
"=",
"creds",
".",
"get",
"(",
"'insecure'",
",",
"False",
")",
")",
"return",
"_FAS"
] | Return a fedora.client.fas2.AccountSystem object if the provided
configuration contains a FAS username and password. | [
"Return",
"a",
"fedora",
".",
"client",
".",
"fas2",
".",
"AccountSystem",
"object",
"if",
"the",
"provided",
"configuration",
"contains",
"a",
"FAS",
"username",
"and",
"password",
"."
] | f9ec790619fcc8b41803077c4dec094e5127fc24 | https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/utils.py#L40-L66 |
250,939 | fedora-infra/fmn.rules | fmn/rules/utils.py | get_packagers_of_package | def get_packagers_of_package(config, package):
""" Retrieve the list of users who have commit on a package.
:arg config: a dict containing the fedmsg config
:arg package: the package you are interested in.
:return: a set listing all the fas usernames that have some ACL on package.
"""
if not _cache.is_configured:
_cache.configure(**config['fmn.rules.cache'])
key = cache_key_generator(get_packagers_of_package, package)
creator = lambda: _get_pkgdb2_packagers_for(config, package)
return _cache.get_or_create(key, creator) | python | def get_packagers_of_package(config, package):
""" Retrieve the list of users who have commit on a package.
:arg config: a dict containing the fedmsg config
:arg package: the package you are interested in.
:return: a set listing all the fas usernames that have some ACL on package.
"""
if not _cache.is_configured:
_cache.configure(**config['fmn.rules.cache'])
key = cache_key_generator(get_packagers_of_package, package)
creator = lambda: _get_pkgdb2_packagers_for(config, package)
return _cache.get_or_create(key, creator) | [
"def",
"get_packagers_of_package",
"(",
"config",
",",
"package",
")",
":",
"if",
"not",
"_cache",
".",
"is_configured",
":",
"_cache",
".",
"configure",
"(",
"*",
"*",
"config",
"[",
"'fmn.rules.cache'",
"]",
")",
"key",
"=",
"cache_key_generator",
"(",
"get_packagers_of_package",
",",
"package",
")",
"creator",
"=",
"lambda",
":",
"_get_pkgdb2_packagers_for",
"(",
"config",
",",
"package",
")",
"return",
"_cache",
".",
"get_or_create",
"(",
"key",
",",
"creator",
")"
] | Retrieve the list of users who have commit on a package.
:arg config: a dict containing the fedmsg config
:arg package: the package you are interested in.
:return: a set listing all the fas usernames that have some ACL on package. | [
"Retrieve",
"the",
"list",
"of",
"users",
"who",
"have",
"commit",
"on",
"a",
"package",
"."
] | f9ec790619fcc8b41803077c4dec094e5127fc24 | https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/utils.py#L69-L82 |
250,940 | fedora-infra/fmn.rules | fmn/rules/utils.py | get_packages_of_user | def get_packages_of_user(config, username, flags):
""" Retrieve the list of packages where the specified user some acl.
:arg config: a dict containing the fedmsg config
:arg username: the fas username of the packager whose packages are of
interest.
:return: a set listing all the packages where the specified user has
some ACL.
"""
if not _cache.is_configured:
_cache.configure(**config['fmn.rules.cache'])
packages = []
groups = get_groups_of_user(config, get_fas(config), username)
owners = [username] + ['group::' + group for group in groups]
for owner in owners:
key = cache_key_generator(get_packages_of_user, owner)
creator = lambda: _get_pkgdb2_packages_for(config, owner, flags)
subset = _cache.get_or_create(key, creator)
packages.extend(subset)
return set(packages) | python | def get_packages_of_user(config, username, flags):
""" Retrieve the list of packages where the specified user some acl.
:arg config: a dict containing the fedmsg config
:arg username: the fas username of the packager whose packages are of
interest.
:return: a set listing all the packages where the specified user has
some ACL.
"""
if not _cache.is_configured:
_cache.configure(**config['fmn.rules.cache'])
packages = []
groups = get_groups_of_user(config, get_fas(config), username)
owners = [username] + ['group::' + group for group in groups]
for owner in owners:
key = cache_key_generator(get_packages_of_user, owner)
creator = lambda: _get_pkgdb2_packages_for(config, owner, flags)
subset = _cache.get_or_create(key, creator)
packages.extend(subset)
return set(packages) | [
"def",
"get_packages_of_user",
"(",
"config",
",",
"username",
",",
"flags",
")",
":",
"if",
"not",
"_cache",
".",
"is_configured",
":",
"_cache",
".",
"configure",
"(",
"*",
"*",
"config",
"[",
"'fmn.rules.cache'",
"]",
")",
"packages",
"=",
"[",
"]",
"groups",
"=",
"get_groups_of_user",
"(",
"config",
",",
"get_fas",
"(",
"config",
")",
",",
"username",
")",
"owners",
"=",
"[",
"username",
"]",
"+",
"[",
"'group::'",
"+",
"group",
"for",
"group",
"in",
"groups",
"]",
"for",
"owner",
"in",
"owners",
":",
"key",
"=",
"cache_key_generator",
"(",
"get_packages_of_user",
",",
"owner",
")",
"creator",
"=",
"lambda",
":",
"_get_pkgdb2_packages_for",
"(",
"config",
",",
"owner",
",",
"flags",
")",
"subset",
"=",
"_cache",
".",
"get_or_create",
"(",
"key",
",",
"creator",
")",
"packages",
".",
"extend",
"(",
"subset",
")",
"return",
"set",
"(",
"packages",
")"
] | Retrieve the list of packages where the specified user some acl.
:arg config: a dict containing the fedmsg config
:arg username: the fas username of the packager whose packages are of
interest.
:return: a set listing all the packages where the specified user has
some ACL. | [
"Retrieve",
"the",
"list",
"of",
"packages",
"where",
"the",
"specified",
"user",
"some",
"acl",
"."
] | f9ec790619fcc8b41803077c4dec094e5127fc24 | https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/utils.py#L123-L148 |
250,941 | fedora-infra/fmn.rules | fmn/rules/utils.py | get_user_of_group | def get_user_of_group(config, fas, groupname):
''' Return the list of users in the specified group.
:arg config: a dict containing the fedmsg config
:arg fas: a fedora.client.fas2.AccountSystem object instanciated and loged
into FAS.
:arg groupname: the name of the group for which we want to retrieve the
members.
:return: a list of FAS user members of the specified group.
'''
if not _cache.is_configured:
_cache.configure(**config['fmn.rules.cache'])
key = cache_key_generator(get_user_of_group, groupname)
def creator():
if not fas:
return set()
return set([u.username for u in fas.group_members(groupname)])
return _cache.get_or_create(key, creator) | python | def get_user_of_group(config, fas, groupname):
''' Return the list of users in the specified group.
:arg config: a dict containing the fedmsg config
:arg fas: a fedora.client.fas2.AccountSystem object instanciated and loged
into FAS.
:arg groupname: the name of the group for which we want to retrieve the
members.
:return: a list of FAS user members of the specified group.
'''
if not _cache.is_configured:
_cache.configure(**config['fmn.rules.cache'])
key = cache_key_generator(get_user_of_group, groupname)
def creator():
if not fas:
return set()
return set([u.username for u in fas.group_members(groupname)])
return _cache.get_or_create(key, creator) | [
"def",
"get_user_of_group",
"(",
"config",
",",
"fas",
",",
"groupname",
")",
":",
"if",
"not",
"_cache",
".",
"is_configured",
":",
"_cache",
".",
"configure",
"(",
"*",
"*",
"config",
"[",
"'fmn.rules.cache'",
"]",
")",
"key",
"=",
"cache_key_generator",
"(",
"get_user_of_group",
",",
"groupname",
")",
"def",
"creator",
"(",
")",
":",
"if",
"not",
"fas",
":",
"return",
"set",
"(",
")",
"return",
"set",
"(",
"[",
"u",
".",
"username",
"for",
"u",
"in",
"fas",
".",
"group_members",
"(",
"groupname",
")",
"]",
")",
"return",
"_cache",
".",
"get_or_create",
"(",
"key",
",",
"creator",
")"
] | Return the list of users in the specified group.
:arg config: a dict containing the fedmsg config
:arg fas: a fedora.client.fas2.AccountSystem object instanciated and loged
into FAS.
:arg groupname: the name of the group for which we want to retrieve the
members.
:return: a list of FAS user members of the specified group. | [
"Return",
"the",
"list",
"of",
"users",
"in",
"the",
"specified",
"group",
"."
] | f9ec790619fcc8b41803077c4dec094e5127fc24 | https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/utils.py#L186-L205 |
250,942 | MakerReduxCorp/MARDS | MARDS/mards_library.py | delist | def delist(target):
''' for any "list" found, replace with a single entry if the list has exactly one entry '''
result = target
if type(target) is dict:
for key in target:
target[key] = delist(target[key])
if type(target) is list:
if len(target)==0:
result = None
elif len(target)==1:
result = delist(target[0])
else:
result = [delist(e) for e in target]
return result | python | def delist(target):
''' for any "list" found, replace with a single entry if the list has exactly one entry '''
result = target
if type(target) is dict:
for key in target:
target[key] = delist(target[key])
if type(target) is list:
if len(target)==0:
result = None
elif len(target)==1:
result = delist(target[0])
else:
result = [delist(e) for e in target]
return result | [
"def",
"delist",
"(",
"target",
")",
":",
"result",
"=",
"target",
"if",
"type",
"(",
"target",
")",
"is",
"dict",
":",
"for",
"key",
"in",
"target",
":",
"target",
"[",
"key",
"]",
"=",
"delist",
"(",
"target",
"[",
"key",
"]",
")",
"if",
"type",
"(",
"target",
")",
"is",
"list",
":",
"if",
"len",
"(",
"target",
")",
"==",
"0",
":",
"result",
"=",
"None",
"elif",
"len",
"(",
"target",
")",
"==",
"1",
":",
"result",
"=",
"delist",
"(",
"target",
"[",
"0",
"]",
")",
"else",
":",
"result",
"=",
"[",
"delist",
"(",
"e",
")",
"for",
"e",
"in",
"target",
"]",
"return",
"result"
] | for any "list" found, replace with a single entry if the list has exactly one entry | [
"for",
"any",
"list",
"found",
"replace",
"with",
"a",
"single",
"entry",
"if",
"the",
"list",
"has",
"exactly",
"one",
"entry"
] | f8ddecc70f2ce1703984cb403c9d5417895170d6 | https://github.com/MakerReduxCorp/MARDS/blob/f8ddecc70f2ce1703984cb403c9d5417895170d6/MARDS/mards_library.py#L189-L202 |
250,943 | MakerReduxCorp/MARDS | MARDS/mards_library.py | check_schema_coverage | def check_schema_coverage(doc, schema):
'''
FORWARD CHECK OF DOCUMENT
This routine looks at each element in the doc, and makes sure there
is a matching 'name' in the schema at that level.
'''
error_list = []
to_delete = []
for entry in doc.list_tuples():
(name, value, index, seq) = entry
temp_schema = schema_match_up(doc, schema)
if not name in temp_schema.list_values("name"):
error_list.append( ("[error]", "doc", seq, "a name of '{}' not found in schema".format(name)) )
to_delete.append(seq)
else:
# check subs
el = check_schema_coverage(doc[name, value, index], temp_schema["name", name])
error_list.extend(el)
for seq in to_delete:
doc.seq_delete(seq)
return error_list | python | def check_schema_coverage(doc, schema):
'''
FORWARD CHECK OF DOCUMENT
This routine looks at each element in the doc, and makes sure there
is a matching 'name' in the schema at that level.
'''
error_list = []
to_delete = []
for entry in doc.list_tuples():
(name, value, index, seq) = entry
temp_schema = schema_match_up(doc, schema)
if not name in temp_schema.list_values("name"):
error_list.append( ("[error]", "doc", seq, "a name of '{}' not found in schema".format(name)) )
to_delete.append(seq)
else:
# check subs
el = check_schema_coverage(doc[name, value, index], temp_schema["name", name])
error_list.extend(el)
for seq in to_delete:
doc.seq_delete(seq)
return error_list | [
"def",
"check_schema_coverage",
"(",
"doc",
",",
"schema",
")",
":",
"error_list",
"=",
"[",
"]",
"to_delete",
"=",
"[",
"]",
"for",
"entry",
"in",
"doc",
".",
"list_tuples",
"(",
")",
":",
"(",
"name",
",",
"value",
",",
"index",
",",
"seq",
")",
"=",
"entry",
"temp_schema",
"=",
"schema_match_up",
"(",
"doc",
",",
"schema",
")",
"if",
"not",
"name",
"in",
"temp_schema",
".",
"list_values",
"(",
"\"name\"",
")",
":",
"error_list",
".",
"append",
"(",
"(",
"\"[error]\"",
",",
"\"doc\"",
",",
"seq",
",",
"\"a name of '{}' not found in schema\"",
".",
"format",
"(",
"name",
")",
")",
")",
"to_delete",
".",
"append",
"(",
"seq",
")",
"else",
":",
"# check subs",
"el",
"=",
"check_schema_coverage",
"(",
"doc",
"[",
"name",
",",
"value",
",",
"index",
"]",
",",
"temp_schema",
"[",
"\"name\"",
",",
"name",
"]",
")",
"error_list",
".",
"extend",
"(",
"el",
")",
"for",
"seq",
"in",
"to_delete",
":",
"doc",
".",
"seq_delete",
"(",
"seq",
")",
"return",
"error_list"
] | FORWARD CHECK OF DOCUMENT
This routine looks at each element in the doc, and makes sure there
is a matching 'name' in the schema at that level. | [
"FORWARD",
"CHECK",
"OF",
"DOCUMENT",
"This",
"routine",
"looks",
"at",
"each",
"element",
"in",
"the",
"doc",
"and",
"makes",
"sure",
"there",
"is",
"a",
"matching",
"name",
"in",
"the",
"schema",
"at",
"that",
"level",
"."
] | f8ddecc70f2ce1703984cb403c9d5417895170d6 | https://github.com/MakerReduxCorp/MARDS/blob/f8ddecc70f2ce1703984cb403c9d5417895170d6/MARDS/mards_library.py#L622-L643 |
250,944 | MakerReduxCorp/MARDS | MARDS/mards_library.py | sub_schema_raises | def sub_schema_raises(doc, schema):
'''
Look for "raise_error", "raise_warning", and "raise_log"
'''
error_list = []
temp_schema = schema_match_up(doc, schema)
for msg in temp_schema.list_values("raise_error"):
error_list.append( ("[error]", "doc", doc.seq, "'{}'".format(msg)) )
for msg in temp_schema.list_values("raise_warning"):
error_list.append( ("[warning]", "doc", doc.seq, "'{}'".format(msg)) )
for msg in temp_schema.list_values("raise_log"):
error_list.append( ("[log]", "doc", doc.seq, "'{}'".format(msg)) )
for entry in doc:
if temp_schema.has(("name", entry.name)):
el = sub_schema_raises(entry, temp_schema["name", entry.name])
error_list.extend(el)
return error_list | python | def sub_schema_raises(doc, schema):
'''
Look for "raise_error", "raise_warning", and "raise_log"
'''
error_list = []
temp_schema = schema_match_up(doc, schema)
for msg in temp_schema.list_values("raise_error"):
error_list.append( ("[error]", "doc", doc.seq, "'{}'".format(msg)) )
for msg in temp_schema.list_values("raise_warning"):
error_list.append( ("[warning]", "doc", doc.seq, "'{}'".format(msg)) )
for msg in temp_schema.list_values("raise_log"):
error_list.append( ("[log]", "doc", doc.seq, "'{}'".format(msg)) )
for entry in doc:
if temp_schema.has(("name", entry.name)):
el = sub_schema_raises(entry, temp_schema["name", entry.name])
error_list.extend(el)
return error_list | [
"def",
"sub_schema_raises",
"(",
"doc",
",",
"schema",
")",
":",
"error_list",
"=",
"[",
"]",
"temp_schema",
"=",
"schema_match_up",
"(",
"doc",
",",
"schema",
")",
"for",
"msg",
"in",
"temp_schema",
".",
"list_values",
"(",
"\"raise_error\"",
")",
":",
"error_list",
".",
"append",
"(",
"(",
"\"[error]\"",
",",
"\"doc\"",
",",
"doc",
".",
"seq",
",",
"\"'{}'\"",
".",
"format",
"(",
"msg",
")",
")",
")",
"for",
"msg",
"in",
"temp_schema",
".",
"list_values",
"(",
"\"raise_warning\"",
")",
":",
"error_list",
".",
"append",
"(",
"(",
"\"[warning]\"",
",",
"\"doc\"",
",",
"doc",
".",
"seq",
",",
"\"'{}'\"",
".",
"format",
"(",
"msg",
")",
")",
")",
"for",
"msg",
"in",
"temp_schema",
".",
"list_values",
"(",
"\"raise_log\"",
")",
":",
"error_list",
".",
"append",
"(",
"(",
"\"[log]\"",
",",
"\"doc\"",
",",
"doc",
".",
"seq",
",",
"\"'{}'\"",
".",
"format",
"(",
"msg",
")",
")",
")",
"for",
"entry",
"in",
"doc",
":",
"if",
"temp_schema",
".",
"has",
"(",
"(",
"\"name\"",
",",
"entry",
".",
"name",
")",
")",
":",
"el",
"=",
"sub_schema_raises",
"(",
"entry",
",",
"temp_schema",
"[",
"\"name\"",
",",
"entry",
".",
"name",
"]",
")",
"error_list",
".",
"extend",
"(",
"el",
")",
"return",
"error_list"
] | Look for "raise_error", "raise_warning", and "raise_log" | [
"Look",
"for",
"raise_error",
"raise_warning",
"and",
"raise_log"
] | f8ddecc70f2ce1703984cb403c9d5417895170d6 | https://github.com/MakerReduxCorp/MARDS/blob/f8ddecc70f2ce1703984cb403c9d5417895170d6/MARDS/mards_library.py#L777-L794 |
250,945 | etscrivner/nose-perfdump | perfdump/models.py | BaseTimeModel.is_valid_row | def is_valid_row(cls, row):
"""Indicates whether or not the given row contains valid data."""
for k in row.keys():
if row[k] is None:
return False
return True | python | def is_valid_row(cls, row):
"""Indicates whether or not the given row contains valid data."""
for k in row.keys():
if row[k] is None:
return False
return True | [
"def",
"is_valid_row",
"(",
"cls",
",",
"row",
")",
":",
"for",
"k",
"in",
"row",
".",
"keys",
"(",
")",
":",
"if",
"row",
"[",
"k",
"]",
"is",
"None",
":",
"return",
"False",
"return",
"True"
] | Indicates whether or not the given row contains valid data. | [
"Indicates",
"whether",
"or",
"not",
"the",
"given",
"row",
"contains",
"valid",
"data",
"."
] | a203a68495d30346fab43fb903cb60cd29b17d49 | https://github.com/etscrivner/nose-perfdump/blob/a203a68495d30346fab43fb903cb60cd29b17d49/perfdump/models.py#L151-L156 |
250,946 | etscrivner/nose-perfdump | perfdump/models.py | BaseTimeModel.get_cursor | def get_cursor(cls):
"""Return a message list cursor that returns sqlite3.Row objects"""
db = SqliteConnection.get()
db.row_factory = sqlite3.Row
return db.cursor() | python | def get_cursor(cls):
"""Return a message list cursor that returns sqlite3.Row objects"""
db = SqliteConnection.get()
db.row_factory = sqlite3.Row
return db.cursor() | [
"def",
"get_cursor",
"(",
"cls",
")",
":",
"db",
"=",
"SqliteConnection",
".",
"get",
"(",
")",
"db",
".",
"row_factory",
"=",
"sqlite3",
".",
"Row",
"return",
"db",
".",
"cursor",
"(",
")"
] | Return a message list cursor that returns sqlite3.Row objects | [
"Return",
"a",
"message",
"list",
"cursor",
"that",
"returns",
"sqlite3",
".",
"Row",
"objects"
] | a203a68495d30346fab43fb903cb60cd29b17d49 | https://github.com/etscrivner/nose-perfdump/blob/a203a68495d30346fab43fb903cb60cd29b17d49/perfdump/models.py#L159-L163 |
250,947 | qbicsoftware/mtb-parser-lib | mtbparser/snv_parser.py | SnvParser._parse_header | def _parse_header(self, header_string):
"""
Parses the header and determines the column type
and its column index.
"""
header_content = header_string.strip().split('\t')
if len(header_content) != self._snv_enum.HEADER_LEN.value:
raise MTBParserException(
"Only {} header columns found, {} expected!"
.format(len(header_content), self._snv_enum.HEADER_LEN.value))
counter = 0
for column in header_content:
for enum_type in self._snv_enum:
if column == enum_type.value:
self._header_to_column_mapping[enum_type.name] = counter
continue
counter+=1
if len(self._header_to_column_mapping) != self._snv_enum.HEADER_LEN.value:
debug_string = self._header_to_column_mapping.keys()
raise MTBParserException("Parsing incomplete: Not all columns have been "
"matched to speficied column types. Identified {} columns, but expected {}. {}"
.format(len(self._header_to_column_mapping), self._snv_enum.HEADER_LEN.value, debug_string)) | python | def _parse_header(self, header_string):
"""
Parses the header and determines the column type
and its column index.
"""
header_content = header_string.strip().split('\t')
if len(header_content) != self._snv_enum.HEADER_LEN.value:
raise MTBParserException(
"Only {} header columns found, {} expected!"
.format(len(header_content), self._snv_enum.HEADER_LEN.value))
counter = 0
for column in header_content:
for enum_type in self._snv_enum:
if column == enum_type.value:
self._header_to_column_mapping[enum_type.name] = counter
continue
counter+=1
if len(self._header_to_column_mapping) != self._snv_enum.HEADER_LEN.value:
debug_string = self._header_to_column_mapping.keys()
raise MTBParserException("Parsing incomplete: Not all columns have been "
"matched to speficied column types. Identified {} columns, but expected {}. {}"
.format(len(self._header_to_column_mapping), self._snv_enum.HEADER_LEN.value, debug_string)) | [
"def",
"_parse_header",
"(",
"self",
",",
"header_string",
")",
":",
"header_content",
"=",
"header_string",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"if",
"len",
"(",
"header_content",
")",
"!=",
"self",
".",
"_snv_enum",
".",
"HEADER_LEN",
".",
"value",
":",
"raise",
"MTBParserException",
"(",
"\"Only {} header columns found, {} expected!\"",
".",
"format",
"(",
"len",
"(",
"header_content",
")",
",",
"self",
".",
"_snv_enum",
".",
"HEADER_LEN",
".",
"value",
")",
")",
"counter",
"=",
"0",
"for",
"column",
"in",
"header_content",
":",
"for",
"enum_type",
"in",
"self",
".",
"_snv_enum",
":",
"if",
"column",
"==",
"enum_type",
".",
"value",
":",
"self",
".",
"_header_to_column_mapping",
"[",
"enum_type",
".",
"name",
"]",
"=",
"counter",
"continue",
"counter",
"+=",
"1",
"if",
"len",
"(",
"self",
".",
"_header_to_column_mapping",
")",
"!=",
"self",
".",
"_snv_enum",
".",
"HEADER_LEN",
".",
"value",
":",
"debug_string",
"=",
"self",
".",
"_header_to_column_mapping",
".",
"keys",
"(",
")",
"raise",
"MTBParserException",
"(",
"\"Parsing incomplete: Not all columns have been \"",
"\"matched to speficied column types. Identified {} columns, but expected {}. {}\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"_header_to_column_mapping",
")",
",",
"self",
".",
"_snv_enum",
".",
"HEADER_LEN",
".",
"value",
",",
"debug_string",
")",
")"
] | Parses the header and determines the column type
and its column index. | [
"Parses",
"the",
"header",
"and",
"determines",
"the",
"column",
"type",
"and",
"its",
"column",
"index",
"."
] | e8b96e34b27e457ea7def2927fe44017fa173ba7 | https://github.com/qbicsoftware/mtb-parser-lib/blob/e8b96e34b27e457ea7def2927fe44017fa173ba7/mtbparser/snv_parser.py#L26-L48 |
250,948 | qbicsoftware/mtb-parser-lib | mtbparser/snv_parser.py | SnvParser._parse_content | def _parse_content(self, snv_entries):
"""
Parses SNV entries to SNVItems, objects
representing the content for every entry, that
can be used for further processing.
"""
if len(snv_entries) == 1:
return
for line in snv_entries[1:]:
info_dict = self._map_info_to_col(line)
self._snv_list.append(SNVItem(**info_dict)) | python | def _parse_content(self, snv_entries):
"""
Parses SNV entries to SNVItems, objects
representing the content for every entry, that
can be used for further processing.
"""
if len(snv_entries) == 1:
return
for line in snv_entries[1:]:
info_dict = self._map_info_to_col(line)
self._snv_list.append(SNVItem(**info_dict)) | [
"def",
"_parse_content",
"(",
"self",
",",
"snv_entries",
")",
":",
"if",
"len",
"(",
"snv_entries",
")",
"==",
"1",
":",
"return",
"for",
"line",
"in",
"snv_entries",
"[",
"1",
":",
"]",
":",
"info_dict",
"=",
"self",
".",
"_map_info_to_col",
"(",
"line",
")",
"self",
".",
"_snv_list",
".",
"append",
"(",
"SNVItem",
"(",
"*",
"*",
"info_dict",
")",
")"
] | Parses SNV entries to SNVItems, objects
representing the content for every entry, that
can be used for further processing. | [
"Parses",
"SNV",
"entries",
"to",
"SNVItems",
"objects",
"representing",
"the",
"content",
"for",
"every",
"entry",
"that",
"can",
"be",
"used",
"for",
"further",
"processing",
"."
] | e8b96e34b27e457ea7def2927fe44017fa173ba7 | https://github.com/qbicsoftware/mtb-parser-lib/blob/e8b96e34b27e457ea7def2927fe44017fa173ba7/mtbparser/snv_parser.py#L50-L60 |
250,949 | alexhayes/django-toolkit | django_toolkit/templatetags/actions.py | actions | def actions(obj, **kwargs):
"""
Return actions available for an object
"""
if 'exclude' in kwargs:
kwargs['exclude'] = kwargs['exclude'].split(',')
actions = obj.get_actions(**kwargs)
if isinstance(actions, dict):
actions = actions.values()
buttons = "".join("%s" % action.render() for action in actions)
return '<div class="actions">%s</div>' % buttons | python | def actions(obj, **kwargs):
"""
Return actions available for an object
"""
if 'exclude' in kwargs:
kwargs['exclude'] = kwargs['exclude'].split(',')
actions = obj.get_actions(**kwargs)
if isinstance(actions, dict):
actions = actions.values()
buttons = "".join("%s" % action.render() for action in actions)
return '<div class="actions">%s</div>' % buttons | [
"def",
"actions",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'exclude'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'exclude'",
"]",
"=",
"kwargs",
"[",
"'exclude'",
"]",
".",
"split",
"(",
"','",
")",
"actions",
"=",
"obj",
".",
"get_actions",
"(",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"actions",
",",
"dict",
")",
":",
"actions",
"=",
"actions",
".",
"values",
"(",
")",
"buttons",
"=",
"\"\"",
".",
"join",
"(",
"\"%s\"",
"%",
"action",
".",
"render",
"(",
")",
"for",
"action",
"in",
"actions",
")",
"return",
"'<div class=\"actions\">%s</div>'",
"%",
"buttons"
] | Return actions available for an object | [
"Return",
"actions",
"available",
"for",
"an",
"object"
] | b64106392fad596defc915b8235fe6e1d0013b5b | https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/templatetags/actions.py#L8-L18 |
250,950 | heikomuller/sco-engine | scoengine/__init__.py | SCOEngine.list_models | def list_models(self, limit=-1, offset=-1):
"""Get a list of models in the registry.
Parameters
----------
limit : int
Limit number of items in the result set
offset : int
Set offset in list (order as defined by object store)
Returns
-------
list(ModelHandle)
"""
return self.registry.list_models(limit=limit, offset=offset) | python | def list_models(self, limit=-1, offset=-1):
"""Get a list of models in the registry.
Parameters
----------
limit : int
Limit number of items in the result set
offset : int
Set offset in list (order as defined by object store)
Returns
-------
list(ModelHandle)
"""
return self.registry.list_models(limit=limit, offset=offset) | [
"def",
"list_models",
"(",
"self",
",",
"limit",
"=",
"-",
"1",
",",
"offset",
"=",
"-",
"1",
")",
":",
"return",
"self",
".",
"registry",
".",
"list_models",
"(",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
")"
] | Get a list of models in the registry.
Parameters
----------
limit : int
Limit number of items in the result set
offset : int
Set offset in list (order as defined by object store)
Returns
-------
list(ModelHandle) | [
"Get",
"a",
"list",
"of",
"models",
"in",
"the",
"registry",
"."
] | 3e7782d059ec808d930f0992794b6f5a8fd73c2c | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L94-L108 |
250,951 | heikomuller/sco-engine | scoengine/__init__.py | SCOEngine.register_model | def register_model(self, model_id, properties, parameters, outputs, connector):
"""Register a new model with the engine. Expects connection information
for RabbitMQ to submit model run requests to workers.
Raises ValueError if the given model identifier is not unique.
Parameters
----------
model_id : string
Unique model identifier
properties : Dictionary
Dictionary of model specific properties.
parameters : list(scodata.attribute.AttributeDefinition)
List of attribute definitions for model run parameters
outputs : ModelOutputs
Description of model outputs
connector : dict
Connection information to communicate with model workers. Expected
to contain at least the connector name 'connector'.
Returns
-------
ModelHandle
"""
# Validate the given connector information
self.validate_connector(connector)
# Connector information is valid. Ok to register the model. Will raise
# ValueError if model with given identifier exists. Catch duplicate
# key error to transform it into a ValueError
try:
return self.registry.register_model(
model_id,
properties,
parameters,
outputs,
connector
)
except DuplicateKeyError as ex:
raise ValueError(str(ex)) | python | def register_model(self, model_id, properties, parameters, outputs, connector):
"""Register a new model with the engine. Expects connection information
for RabbitMQ to submit model run requests to workers.
Raises ValueError if the given model identifier is not unique.
Parameters
----------
model_id : string
Unique model identifier
properties : Dictionary
Dictionary of model specific properties.
parameters : list(scodata.attribute.AttributeDefinition)
List of attribute definitions for model run parameters
outputs : ModelOutputs
Description of model outputs
connector : dict
Connection information to communicate with model workers. Expected
to contain at least the connector name 'connector'.
Returns
-------
ModelHandle
"""
# Validate the given connector information
self.validate_connector(connector)
# Connector information is valid. Ok to register the model. Will raise
# ValueError if model with given identifier exists. Catch duplicate
# key error to transform it into a ValueError
try:
return self.registry.register_model(
model_id,
properties,
parameters,
outputs,
connector
)
except DuplicateKeyError as ex:
raise ValueError(str(ex)) | [
"def",
"register_model",
"(",
"self",
",",
"model_id",
",",
"properties",
",",
"parameters",
",",
"outputs",
",",
"connector",
")",
":",
"# Validate the given connector information",
"self",
".",
"validate_connector",
"(",
"connector",
")",
"# Connector information is valid. Ok to register the model. Will raise",
"# ValueError if model with given identifier exists. Catch duplicate",
"# key error to transform it into a ValueError",
"try",
":",
"return",
"self",
".",
"registry",
".",
"register_model",
"(",
"model_id",
",",
"properties",
",",
"parameters",
",",
"outputs",
",",
"connector",
")",
"except",
"DuplicateKeyError",
"as",
"ex",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"ex",
")",
")"
] | Register a new model with the engine. Expects connection information
for RabbitMQ to submit model run requests to workers.
Raises ValueError if the given model identifier is not unique.
Parameters
----------
model_id : string
Unique model identifier
properties : Dictionary
Dictionary of model specific properties.
parameters : list(scodata.attribute.AttributeDefinition)
List of attribute definitions for model run parameters
outputs : ModelOutputs
Description of model outputs
connector : dict
Connection information to communicate with model workers. Expected
to contain at least the connector name 'connector'.
Returns
-------
ModelHandle | [
"Register",
"a",
"new",
"model",
"with",
"the",
"engine",
".",
"Expects",
"connection",
"information",
"for",
"RabbitMQ",
"to",
"submit",
"model",
"run",
"requests",
"to",
"workers",
"."
] | 3e7782d059ec808d930f0992794b6f5a8fd73c2c | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L110-L148 |
250,952 | heikomuller/sco-engine | scoengine/__init__.py | SCOEngine.run_model | def run_model(self, model_run, run_url):
"""Execute the given model run.
Throws a ValueError if the given run specifies an unknown model or if
the model connector is invalid. An EngineException is thrown if running
the model (i.e., communication with the backend) fails.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information
"""
# Get model to verify that it exists and to get connector information
model = self.get_model(model_run.model_id)
if model is None:
raise ValueError('unknown model: ' + model_run.model_id)
# By now there is only one connector. Use the buffered connector to
# avoid closed connection exceptions
RabbitMQConnector(model.connector).run_model(model_run, run_url) | python | def run_model(self, model_run, run_url):
"""Execute the given model run.
Throws a ValueError if the given run specifies an unknown model or if
the model connector is invalid. An EngineException is thrown if running
the model (i.e., communication with the backend) fails.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information
"""
# Get model to verify that it exists and to get connector information
model = self.get_model(model_run.model_id)
if model is None:
raise ValueError('unknown model: ' + model_run.model_id)
# By now there is only one connector. Use the buffered connector to
# avoid closed connection exceptions
RabbitMQConnector(model.connector).run_model(model_run, run_url) | [
"def",
"run_model",
"(",
"self",
",",
"model_run",
",",
"run_url",
")",
":",
"# Get model to verify that it exists and to get connector information",
"model",
"=",
"self",
".",
"get_model",
"(",
"model_run",
".",
"model_id",
")",
"if",
"model",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'unknown model: '",
"+",
"model_run",
".",
"model_id",
")",
"# By now there is only one connector. Use the buffered connector to",
"# avoid closed connection exceptions",
"RabbitMQConnector",
"(",
"model",
".",
"connector",
")",
".",
"run_model",
"(",
"model_run",
",",
"run_url",
")"
] | Execute the given model run.
Throws a ValueError if the given run specifies an unknown model or if
the model connector is invalid. An EngineException is thrown if running
the model (i.e., communication with the backend) fails.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information | [
"Execute",
"the",
"given",
"model",
"run",
"."
] | 3e7782d059ec808d930f0992794b6f5a8fd73c2c | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L150-L170 |
250,953 | heikomuller/sco-engine | scoengine/__init__.py | SCOEngine.validate_connector | def validate_connector(self, connector):
"""Validate a given connector. Raises ValueError if the connector is not
valid.
Parameters
----------
connector : dict
Connection information
"""
if not 'connector' in connector:
raise ValueError('missing connector name')
elif connector['connector'] != CONNECTOR_RABBITMQ:
raise ValueError('unknown connector: ' + str(connector['connector']))
# Call the connector specific validator. Will raise a ValueError if
# given connector information is invalid
RabbitMQConnector.validate(connector) | python | def validate_connector(self, connector):
"""Validate a given connector. Raises ValueError if the connector is not
valid.
Parameters
----------
connector : dict
Connection information
"""
if not 'connector' in connector:
raise ValueError('missing connector name')
elif connector['connector'] != CONNECTOR_RABBITMQ:
raise ValueError('unknown connector: ' + str(connector['connector']))
# Call the connector specific validator. Will raise a ValueError if
# given connector information is invalid
RabbitMQConnector.validate(connector) | [
"def",
"validate_connector",
"(",
"self",
",",
"connector",
")",
":",
"if",
"not",
"'connector'",
"in",
"connector",
":",
"raise",
"ValueError",
"(",
"'missing connector name'",
")",
"elif",
"connector",
"[",
"'connector'",
"]",
"!=",
"CONNECTOR_RABBITMQ",
":",
"raise",
"ValueError",
"(",
"'unknown connector: '",
"+",
"str",
"(",
"connector",
"[",
"'connector'",
"]",
")",
")",
"# Call the connector specific validator. Will raise a ValueError if",
"# given connector information is invalid",
"RabbitMQConnector",
".",
"validate",
"(",
"connector",
")"
] | Validate a given connector. Raises ValueError if the connector is not
valid.
Parameters
----------
connector : dict
Connection information | [
"Validate",
"a",
"given",
"connector",
".",
"Raises",
"ValueError",
"if",
"the",
"connector",
"is",
"not",
"valid",
"."
] | 3e7782d059ec808d930f0992794b6f5a8fd73c2c | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L214-L229 |
250,954 | heikomuller/sco-engine | scoengine/__init__.py | RabbitMQConnector.run_model | def run_model(self, model_run, run_url):
"""Run model by sending message to RabbitMQ queue containing the
run end experiment identifier. Messages are persistent to ensure that
a worker will process process the run request at some point.
Throws a EngineException if communication with the server fails.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information
"""
# Open connection to RabbitMQ server. Will raise an exception if the
# server is not running. In this case we raise an EngineException to
# allow caller to delete model run.
try:
credentials = pika.PlainCredentials(self.user, self.password)
con = pika.BlockingConnection(pika.ConnectionParameters(
host=self.host,
port=self.port,
virtual_host=self.virtual_host,
credentials=credentials
))
channel = con.channel()
channel.queue_declare(queue=self.queue, durable=True)
except pika.exceptions.AMQPError as ex:
err_msg = str(ex)
if err_msg == '':
err_msg = 'unable to connect to RabbitMQ: ' + self.user + '@'
err_msg += self.host + ':' + str(self.port)
err_msg += self.virtual_host + ' ' + self.queue
raise EngineException(err_msg, 500)
# Create model run request
request = RequestFactory().get_request(model_run, run_url)
# Send request
channel.basic_publish(
exchange='',
routing_key=self.queue,
body=json.dumps(request.to_dict()),
properties=pika.BasicProperties(
delivery_mode = 2, # make message persistent
)
)
con.close() | python | def run_model(self, model_run, run_url):
"""Run model by sending message to RabbitMQ queue containing the
run end experiment identifier. Messages are persistent to ensure that
a worker will process process the run request at some point.
Throws a EngineException if communication with the server fails.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information
"""
# Open connection to RabbitMQ server. Will raise an exception if the
# server is not running. In this case we raise an EngineException to
# allow caller to delete model run.
try:
credentials = pika.PlainCredentials(self.user, self.password)
con = pika.BlockingConnection(pika.ConnectionParameters(
host=self.host,
port=self.port,
virtual_host=self.virtual_host,
credentials=credentials
))
channel = con.channel()
channel.queue_declare(queue=self.queue, durable=True)
except pika.exceptions.AMQPError as ex:
err_msg = str(ex)
if err_msg == '':
err_msg = 'unable to connect to RabbitMQ: ' + self.user + '@'
err_msg += self.host + ':' + str(self.port)
err_msg += self.virtual_host + ' ' + self.queue
raise EngineException(err_msg, 500)
# Create model run request
request = RequestFactory().get_request(model_run, run_url)
# Send request
channel.basic_publish(
exchange='',
routing_key=self.queue,
body=json.dumps(request.to_dict()),
properties=pika.BasicProperties(
delivery_mode = 2, # make message persistent
)
)
con.close() | [
"def",
"run_model",
"(",
"self",
",",
"model_run",
",",
"run_url",
")",
":",
"# Open connection to RabbitMQ server. Will raise an exception if the",
"# server is not running. In this case we raise an EngineException to",
"# allow caller to delete model run.",
"try",
":",
"credentials",
"=",
"pika",
".",
"PlainCredentials",
"(",
"self",
".",
"user",
",",
"self",
".",
"password",
")",
"con",
"=",
"pika",
".",
"BlockingConnection",
"(",
"pika",
".",
"ConnectionParameters",
"(",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
",",
"virtual_host",
"=",
"self",
".",
"virtual_host",
",",
"credentials",
"=",
"credentials",
")",
")",
"channel",
"=",
"con",
".",
"channel",
"(",
")",
"channel",
".",
"queue_declare",
"(",
"queue",
"=",
"self",
".",
"queue",
",",
"durable",
"=",
"True",
")",
"except",
"pika",
".",
"exceptions",
".",
"AMQPError",
"as",
"ex",
":",
"err_msg",
"=",
"str",
"(",
"ex",
")",
"if",
"err_msg",
"==",
"''",
":",
"err_msg",
"=",
"'unable to connect to RabbitMQ: '",
"+",
"self",
".",
"user",
"+",
"'@'",
"err_msg",
"+=",
"self",
".",
"host",
"+",
"':'",
"+",
"str",
"(",
"self",
".",
"port",
")",
"err_msg",
"+=",
"self",
".",
"virtual_host",
"+",
"' '",
"+",
"self",
".",
"queue",
"raise",
"EngineException",
"(",
"err_msg",
",",
"500",
")",
"# Create model run request",
"request",
"=",
"RequestFactory",
"(",
")",
".",
"get_request",
"(",
"model_run",
",",
"run_url",
")",
"# Send request",
"channel",
".",
"basic_publish",
"(",
"exchange",
"=",
"''",
",",
"routing_key",
"=",
"self",
".",
"queue",
",",
"body",
"=",
"json",
".",
"dumps",
"(",
"request",
".",
"to_dict",
"(",
")",
")",
",",
"properties",
"=",
"pika",
".",
"BasicProperties",
"(",
"delivery_mode",
"=",
"2",
",",
"# make message persistent",
")",
")",
"con",
".",
"close",
"(",
")"
] | Run model by sending message to RabbitMQ queue containing the
run end experiment identifier. Messages are persistent to ensure that
a worker will process process the run request at some point.
Throws a EngineException if communication with the server fails.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information | [
"Run",
"model",
"by",
"sending",
"message",
"to",
"RabbitMQ",
"queue",
"containing",
"the",
"run",
"end",
"experiment",
"identifier",
".",
"Messages",
"are",
"persistent",
"to",
"ensure",
"that",
"a",
"worker",
"will",
"process",
"process",
"the",
"run",
"request",
"at",
"some",
"point",
"."
] | 3e7782d059ec808d930f0992794b6f5a8fd73c2c | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L278-L323 |
250,955 | heikomuller/sco-engine | scoengine/__init__.py | BufferedConnector.run_model | def run_model(self, model_run, run_url):
"""Create entry in run request buffer.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information
"""
# Create model run request
request = RequestFactory().get_request(model_run, run_url)
# Write request and connector information into buffer
self.collection.insert_one({
'connector' : self.connector,
'request' : request.to_dict()
}) | python | def run_model(self, model_run, run_url):
"""Create entry in run request buffer.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information
"""
# Create model run request
request = RequestFactory().get_request(model_run, run_url)
# Write request and connector information into buffer
self.collection.insert_one({
'connector' : self.connector,
'request' : request.to_dict()
}) | [
"def",
"run_model",
"(",
"self",
",",
"model_run",
",",
"run_url",
")",
":",
"# Create model run request",
"request",
"=",
"RequestFactory",
"(",
")",
".",
"get_request",
"(",
"model_run",
",",
"run_url",
")",
"# Write request and connector information into buffer",
"self",
".",
"collection",
".",
"insert_one",
"(",
"{",
"'connector'",
":",
"self",
".",
"connector",
",",
"'request'",
":",
"request",
".",
"to_dict",
"(",
")",
"}",
")"
] | Create entry in run request buffer.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information | [
"Create",
"entry",
"in",
"run",
"request",
"buffer",
"."
] | 3e7782d059ec808d930f0992794b6f5a8fd73c2c | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L357-L373 |
250,956 | heikomuller/sco-engine | scoengine/__init__.py | RequestFactory.get_request | def get_request(self, model_run, run_url):
"""Create request object to run model. Requests are handled by SCO
worker implementations.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information
Returns
-------
ModelRunRequest
Object representing model run request
"""
return ModelRunRequest(
model_run.identifier,
model_run.experiment_id,
run_url
) | python | def get_request(self, model_run, run_url):
"""Create request object to run model. Requests are handled by SCO
worker implementations.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information
Returns
-------
ModelRunRequest
Object representing model run request
"""
return ModelRunRequest(
model_run.identifier,
model_run.experiment_id,
run_url
) | [
"def",
"get_request",
"(",
"self",
",",
"model_run",
",",
"run_url",
")",
":",
"return",
"ModelRunRequest",
"(",
"model_run",
".",
"identifier",
",",
"model_run",
".",
"experiment_id",
",",
"run_url",
")"
] | Create request object to run model. Requests are handled by SCO
worker implementations.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information
Returns
-------
ModelRunRequest
Object representing model run request | [
"Create",
"request",
"object",
"to",
"run",
"model",
".",
"Requests",
"are",
"handled",
"by",
"SCO",
"worker",
"implementations",
"."
] | 3e7782d059ec808d930f0992794b6f5a8fd73c2c | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L383-L403 |
250,957 | thomasvandoren/bugzscout-py | bugzscout/ext/celery_app.py | submit_error | def submit_error(url, user, project, area, description,
extra=None, default_message=None):
"""Celery task for submitting errors asynchronously.
:param url: string URL for bugzscout
:param user: string fogbugz user to designate when submitting
via bugzscout
:param project: string fogbugz project to designate for cases
:param area: string fogbugz area to designate for cases
:param description: string description for error
:param extra: string details for error
:param default_message: string default message to return in responses
"""
LOG.debug('Creating new BugzScout instance.')
client = bugzscout.BugzScout(
url, user, project, area)
LOG.debug('Submitting BugzScout error.')
client.submit_error(
description, extra=extra, default_message=default_message) | python | def submit_error(url, user, project, area, description,
extra=None, default_message=None):
"""Celery task for submitting errors asynchronously.
:param url: string URL for bugzscout
:param user: string fogbugz user to designate when submitting
via bugzscout
:param project: string fogbugz project to designate for cases
:param area: string fogbugz area to designate for cases
:param description: string description for error
:param extra: string details for error
:param default_message: string default message to return in responses
"""
LOG.debug('Creating new BugzScout instance.')
client = bugzscout.BugzScout(
url, user, project, area)
LOG.debug('Submitting BugzScout error.')
client.submit_error(
description, extra=extra, default_message=default_message) | [
"def",
"submit_error",
"(",
"url",
",",
"user",
",",
"project",
",",
"area",
",",
"description",
",",
"extra",
"=",
"None",
",",
"default_message",
"=",
"None",
")",
":",
"LOG",
".",
"debug",
"(",
"'Creating new BugzScout instance.'",
")",
"client",
"=",
"bugzscout",
".",
"BugzScout",
"(",
"url",
",",
"user",
",",
"project",
",",
"area",
")",
"LOG",
".",
"debug",
"(",
"'Submitting BugzScout error.'",
")",
"client",
".",
"submit_error",
"(",
"description",
",",
"extra",
"=",
"extra",
",",
"default_message",
"=",
"default_message",
")"
] | Celery task for submitting errors asynchronously.
:param url: string URL for bugzscout
:param user: string fogbugz user to designate when submitting
via bugzscout
:param project: string fogbugz project to designate for cases
:param area: string fogbugz area to designate for cases
:param description: string description for error
:param extra: string details for error
:param default_message: string default message to return in responses | [
"Celery",
"task",
"for",
"submitting",
"errors",
"asynchronously",
"."
] | 514528e958a97e0e7b36870037c5c69661511824 | https://github.com/thomasvandoren/bugzscout-py/blob/514528e958a97e0e7b36870037c5c69661511824/bugzscout/ext/celery_app.py#L30-L49 |
250,958 | wheeler-microfluidics/nested-structures | nested_structures/__init__.py | apply_depth_first | def apply_depth_first(nodes, func, depth=0, as_dict=False, parents=None):
'''
Given a structure such as the application menu layout described above, we
may want to apply an operation to each entry to create a transformed
version of the structure.
For example, let's convert all entries in the application menu layout from
above to upper-case:
>>> pprint(apply_depth_first(menu_actions, lambda node, parents, nodes: node.upper()))
[('FILE',
['LOAD', 'SAVE', ('QUIT', ['QUIT WITHOUT SAVING', 'SAVE AND QUIT'])]),
('EDIT', ['COPY', 'PASTE', ('FILL', ['DOWN', 'SERIES'])])]
Here we used the `apply_depth_first` function to apply a `lambda` function
to each entry to compute the upper-case value corresponding to each node/key.
`as_dict`
---------
To make traversing the structure easier, the output may be expressed as a
nested `OrderedDict` structure. For instance, let's apply the upper-case
transformation from above, but this time with `as_dict=True`:
>>> result = apply_depth_first(menu_actions, as_dict=True, \
... func=lambda node, parents, nodes: node.upper())
>>> type(result)
<class 'collections.OrderedDict'>
Here we see that the result is an ordered dictionary. Moreover, we can
look up the transformed `"File"` entry based on the original key/node
value. Since an entry may contain children, each entry is wrapped as a
`namedtuple` with `item` and `children` attributes.
>>> type(result['File'])
<class 'nested_structures.Node'>
>>> result['File'].item
'FILE'
>>> type(result['File'].children)
<class 'collections.OrderedDict'>
If an entry has children, the `children` attribute is an `OrderedDict`.
Otherwise, the `children` is set to `None`.
Given the information from above, we can look up the `"Load"` child entry
of the `"File"` entry.
>>> result['File'].children['Load']
Node(item='LOAD', children=None)
Similarly, we can look up the `"Save and quit"` child entry of the `"Quit"`
entry.
>>> result['File'].children['Quit'].children['Save and quit']
Node(item='SAVE AND QUIT', children=None)
Note that this function *(i.e., `apply_depth_first`)* could be used to,
e.g., create a menu GUI item for each entry in the structure. This would
decouple the description of the layout from the GUI framework used.
'''
if as_dict:
items = OrderedDict()
else:
items = []
if parents is None:
parents = []
node_count = len(nodes)
for i, node in enumerate(nodes):
first = (i == 0)
last = (i == (node_count - 1))
if isinstance(node, tuple):
node, nodes = node
else:
nodes = []
item = func(node, parents, nodes, first, last, depth)
item_parents = parents + [node]
if nodes:
children = apply_depth_first(nodes, func,
depth=depth + 1,
as_dict=as_dict,
parents=item_parents)
else:
children = None
if as_dict:
items[node] = Node(item, children)
elif nodes:
items.append((item, children))
else:
items.append(item)
return items | python | def apply_depth_first(nodes, func, depth=0, as_dict=False, parents=None):
'''
Given a structure such as the application menu layout described above, we
may want to apply an operation to each entry to create a transformed
version of the structure.
For example, let's convert all entries in the application menu layout from
above to upper-case:
>>> pprint(apply_depth_first(menu_actions, lambda node, parents, nodes: node.upper()))
[('FILE',
['LOAD', 'SAVE', ('QUIT', ['QUIT WITHOUT SAVING', 'SAVE AND QUIT'])]),
('EDIT', ['COPY', 'PASTE', ('FILL', ['DOWN', 'SERIES'])])]
Here we used the `apply_depth_first` function to apply a `lambda` function
to each entry to compute the upper-case value corresponding to each node/key.
`as_dict`
---------
To make traversing the structure easier, the output may be expressed as a
nested `OrderedDict` structure. For instance, let's apply the upper-case
transformation from above, but this time with `as_dict=True`:
>>> result = apply_depth_first(menu_actions, as_dict=True, \
... func=lambda node, parents, nodes: node.upper())
>>> type(result)
<class 'collections.OrderedDict'>
Here we see that the result is an ordered dictionary. Moreover, we can
look up the transformed `"File"` entry based on the original key/node
value. Since an entry may contain children, each entry is wrapped as a
`namedtuple` with `item` and `children` attributes.
>>> type(result['File'])
<class 'nested_structures.Node'>
>>> result['File'].item
'FILE'
>>> type(result['File'].children)
<class 'collections.OrderedDict'>
If an entry has children, the `children` attribute is an `OrderedDict`.
Otherwise, the `children` is set to `None`.
Given the information from above, we can look up the `"Load"` child entry
of the `"File"` entry.
>>> result['File'].children['Load']
Node(item='LOAD', children=None)
Similarly, we can look up the `"Save and quit"` child entry of the `"Quit"`
entry.
>>> result['File'].children['Quit'].children['Save and quit']
Node(item='SAVE AND QUIT', children=None)
Note that this function *(i.e., `apply_depth_first`)* could be used to,
e.g., create a menu GUI item for each entry in the structure. This would
decouple the description of the layout from the GUI framework used.
'''
if as_dict:
items = OrderedDict()
else:
items = []
if parents is None:
parents = []
node_count = len(nodes)
for i, node in enumerate(nodes):
first = (i == 0)
last = (i == (node_count - 1))
if isinstance(node, tuple):
node, nodes = node
else:
nodes = []
item = func(node, parents, nodes, first, last, depth)
item_parents = parents + [node]
if nodes:
children = apply_depth_first(nodes, func,
depth=depth + 1,
as_dict=as_dict,
parents=item_parents)
else:
children = None
if as_dict:
items[node] = Node(item, children)
elif nodes:
items.append((item, children))
else:
items.append(item)
return items | [
"def",
"apply_depth_first",
"(",
"nodes",
",",
"func",
",",
"depth",
"=",
"0",
",",
"as_dict",
"=",
"False",
",",
"parents",
"=",
"None",
")",
":",
"if",
"as_dict",
":",
"items",
"=",
"OrderedDict",
"(",
")",
"else",
":",
"items",
"=",
"[",
"]",
"if",
"parents",
"is",
"None",
":",
"parents",
"=",
"[",
"]",
"node_count",
"=",
"len",
"(",
"nodes",
")",
"for",
"i",
",",
"node",
"in",
"enumerate",
"(",
"nodes",
")",
":",
"first",
"=",
"(",
"i",
"==",
"0",
")",
"last",
"=",
"(",
"i",
"==",
"(",
"node_count",
"-",
"1",
")",
")",
"if",
"isinstance",
"(",
"node",
",",
"tuple",
")",
":",
"node",
",",
"nodes",
"=",
"node",
"else",
":",
"nodes",
"=",
"[",
"]",
"item",
"=",
"func",
"(",
"node",
",",
"parents",
",",
"nodes",
",",
"first",
",",
"last",
",",
"depth",
")",
"item_parents",
"=",
"parents",
"+",
"[",
"node",
"]",
"if",
"nodes",
":",
"children",
"=",
"apply_depth_first",
"(",
"nodes",
",",
"func",
",",
"depth",
"=",
"depth",
"+",
"1",
",",
"as_dict",
"=",
"as_dict",
",",
"parents",
"=",
"item_parents",
")",
"else",
":",
"children",
"=",
"None",
"if",
"as_dict",
":",
"items",
"[",
"node",
"]",
"=",
"Node",
"(",
"item",
",",
"children",
")",
"elif",
"nodes",
":",
"items",
".",
"append",
"(",
"(",
"item",
",",
"children",
")",
")",
"else",
":",
"items",
".",
"append",
"(",
"item",
")",
"return",
"items"
] | Given a structure such as the application menu layout described above, we
may want to apply an operation to each entry to create a transformed
version of the structure.
For example, let's convert all entries in the application menu layout from
above to upper-case:
>>> pprint(apply_depth_first(menu_actions, lambda node, parents, nodes: node.upper()))
[('FILE',
['LOAD', 'SAVE', ('QUIT', ['QUIT WITHOUT SAVING', 'SAVE AND QUIT'])]),
('EDIT', ['COPY', 'PASTE', ('FILL', ['DOWN', 'SERIES'])])]
Here we used the `apply_depth_first` function to apply a `lambda` function
to each entry to compute the upper-case value corresponding to each node/key.
`as_dict`
---------
To make traversing the structure easier, the output may be expressed as a
nested `OrderedDict` structure. For instance, let's apply the upper-case
transformation from above, but this time with `as_dict=True`:
>>> result = apply_depth_first(menu_actions, as_dict=True, \
... func=lambda node, parents, nodes: node.upper())
>>> type(result)
<class 'collections.OrderedDict'>
Here we see that the result is an ordered dictionary. Moreover, we can
look up the transformed `"File"` entry based on the original key/node
value. Since an entry may contain children, each entry is wrapped as a
`namedtuple` with `item` and `children` attributes.
>>> type(result['File'])
<class 'nested_structures.Node'>
>>> result['File'].item
'FILE'
>>> type(result['File'].children)
<class 'collections.OrderedDict'>
If an entry has children, the `children` attribute is an `OrderedDict`.
Otherwise, the `children` is set to `None`.
Given the information from above, we can look up the `"Load"` child entry
of the `"File"` entry.
>>> result['File'].children['Load']
Node(item='LOAD', children=None)
Similarly, we can look up the `"Save and quit"` child entry of the `"Quit"`
entry.
>>> result['File'].children['Quit'].children['Save and quit']
Node(item='SAVE AND QUIT', children=None)
Note that this function *(i.e., `apply_depth_first`)* could be used to,
e.g., create a menu GUI item for each entry in the structure. This would
decouple the description of the layout from the GUI framework used. | [
"Given",
"a",
"structure",
"such",
"as",
"the",
"application",
"menu",
"layout",
"described",
"above",
"we",
"may",
"want",
"to",
"apply",
"an",
"operation",
"to",
"each",
"entry",
"to",
"create",
"a",
"transformed",
"version",
"of",
"the",
"structure",
"."
] | e3586bcca01c59f18ae16b8240e6e49197b63ecb | https://github.com/wheeler-microfluidics/nested-structures/blob/e3586bcca01c59f18ae16b8240e6e49197b63ecb/nested_structures/__init__.py#L51-L146 |
250,959 | wheeler-microfluidics/nested-structures | nested_structures/__init__.py | apply_dict_depth_first | def apply_dict_depth_first(nodes, func, depth=0, as_dict=True, parents=None, pre=None, post=None):
'''
This function is similar to the `apply_depth_first` except that it operates
on the `OrderedDict`-based structure returned from `apply_depth_first` when
`as_dict=True`.
Note that if `as_dict` is `False`, the result of this function is given in
the entry/tuple form.
'''
if as_dict:
items = OrderedDict()
else:
items = []
if parents is None:
parents = []
node_count = len(nodes)
for i, (k, node) in enumerate(nodes.iteritems()):
first = (i == 0)
last = (i == (node_count - 1))
if pre is not None:
pre(k, node, parents, first, last, depth)
item = func(k, node, parents, first, last, depth)
item_parents = parents + [(k, node)]
if node.children is not None:
children = apply_dict_depth_first(node.children, func,
depth=depth + 1,
as_dict=as_dict,
parents=item_parents,
pre=pre, post=post)
else:
children = None
if post is not None:
post(k, node, parents, first, last, depth)
if as_dict:
items[k] = Node(item, children)
elif children:
items.append((item, children))
else:
items.append(item)
return items | python | def apply_dict_depth_first(nodes, func, depth=0, as_dict=True, parents=None, pre=None, post=None):
'''
This function is similar to the `apply_depth_first` except that it operates
on the `OrderedDict`-based structure returned from `apply_depth_first` when
`as_dict=True`.
Note that if `as_dict` is `False`, the result of this function is given in
the entry/tuple form.
'''
if as_dict:
items = OrderedDict()
else:
items = []
if parents is None:
parents = []
node_count = len(nodes)
for i, (k, node) in enumerate(nodes.iteritems()):
first = (i == 0)
last = (i == (node_count - 1))
if pre is not None:
pre(k, node, parents, first, last, depth)
item = func(k, node, parents, first, last, depth)
item_parents = parents + [(k, node)]
if node.children is not None:
children = apply_dict_depth_first(node.children, func,
depth=depth + 1,
as_dict=as_dict,
parents=item_parents,
pre=pre, post=post)
else:
children = None
if post is not None:
post(k, node, parents, first, last, depth)
if as_dict:
items[k] = Node(item, children)
elif children:
items.append((item, children))
else:
items.append(item)
return items | [
"def",
"apply_dict_depth_first",
"(",
"nodes",
",",
"func",
",",
"depth",
"=",
"0",
",",
"as_dict",
"=",
"True",
",",
"parents",
"=",
"None",
",",
"pre",
"=",
"None",
",",
"post",
"=",
"None",
")",
":",
"if",
"as_dict",
":",
"items",
"=",
"OrderedDict",
"(",
")",
"else",
":",
"items",
"=",
"[",
"]",
"if",
"parents",
"is",
"None",
":",
"parents",
"=",
"[",
"]",
"node_count",
"=",
"len",
"(",
"nodes",
")",
"for",
"i",
",",
"(",
"k",
",",
"node",
")",
"in",
"enumerate",
"(",
"nodes",
".",
"iteritems",
"(",
")",
")",
":",
"first",
"=",
"(",
"i",
"==",
"0",
")",
"last",
"=",
"(",
"i",
"==",
"(",
"node_count",
"-",
"1",
")",
")",
"if",
"pre",
"is",
"not",
"None",
":",
"pre",
"(",
"k",
",",
"node",
",",
"parents",
",",
"first",
",",
"last",
",",
"depth",
")",
"item",
"=",
"func",
"(",
"k",
",",
"node",
",",
"parents",
",",
"first",
",",
"last",
",",
"depth",
")",
"item_parents",
"=",
"parents",
"+",
"[",
"(",
"k",
",",
"node",
")",
"]",
"if",
"node",
".",
"children",
"is",
"not",
"None",
":",
"children",
"=",
"apply_dict_depth_first",
"(",
"node",
".",
"children",
",",
"func",
",",
"depth",
"=",
"depth",
"+",
"1",
",",
"as_dict",
"=",
"as_dict",
",",
"parents",
"=",
"item_parents",
",",
"pre",
"=",
"pre",
",",
"post",
"=",
"post",
")",
"else",
":",
"children",
"=",
"None",
"if",
"post",
"is",
"not",
"None",
":",
"post",
"(",
"k",
",",
"node",
",",
"parents",
",",
"first",
",",
"last",
",",
"depth",
")",
"if",
"as_dict",
":",
"items",
"[",
"k",
"]",
"=",
"Node",
"(",
"item",
",",
"children",
")",
"elif",
"children",
":",
"items",
".",
"append",
"(",
"(",
"item",
",",
"children",
")",
")",
"else",
":",
"items",
".",
"append",
"(",
"item",
")",
"return",
"items"
] | This function is similar to the `apply_depth_first` except that it operates
on the `OrderedDict`-based structure returned from `apply_depth_first` when
`as_dict=True`.
Note that if `as_dict` is `False`, the result of this function is given in
the entry/tuple form. | [
"This",
"function",
"is",
"similar",
"to",
"the",
"apply_depth_first",
"except",
"that",
"it",
"operates",
"on",
"the",
"OrderedDict",
"-",
"based",
"structure",
"returned",
"from",
"apply_depth_first",
"when",
"as_dict",
"=",
"True",
"."
] | e3586bcca01c59f18ae16b8240e6e49197b63ecb | https://github.com/wheeler-microfluidics/nested-structures/blob/e3586bcca01c59f18ae16b8240e6e49197b63ecb/nested_structures/__init__.py#L149-L190 |
250,960 | wheeler-microfluidics/nested-structures | nested_structures/__init__.py | collect | def collect(nested_nodes, transform=None):
'''
Return list containing the result of the `transform` function applied to
each item in the supplied list of nested nodes.
A custom transform function may be applied to each entry during the
flattening by specifying a function through the `transform` keyword
argument. The `transform` function will be passed the following arguments:
- `node`: The node/key of the entry.
- `parents`: The node/key of the parents as a `list`.
- `nodes`: The children of the entry.
By default, the `transform` function simply returns the node/key, resulting
in a flattened version of the original nested nodes structure.
'''
items = []
if transform is None:
transform = lambda node, parents, nodes, *args: node
def __collect__(node, parents, nodes, first, last, depth):
items.append(transform(node, parents, nodes, first, last, depth))
apply_depth_first(nested_nodes, __collect__)
return items | python | def collect(nested_nodes, transform=None):
'''
Return list containing the result of the `transform` function applied to
each item in the supplied list of nested nodes.
A custom transform function may be applied to each entry during the
flattening by specifying a function through the `transform` keyword
argument. The `transform` function will be passed the following arguments:
- `node`: The node/key of the entry.
- `parents`: The node/key of the parents as a `list`.
- `nodes`: The children of the entry.
By default, the `transform` function simply returns the node/key, resulting
in a flattened version of the original nested nodes structure.
'''
items = []
if transform is None:
transform = lambda node, parents, nodes, *args: node
def __collect__(node, parents, nodes, first, last, depth):
items.append(transform(node, parents, nodes, first, last, depth))
apply_depth_first(nested_nodes, __collect__)
return items | [
"def",
"collect",
"(",
"nested_nodes",
",",
"transform",
"=",
"None",
")",
":",
"items",
"=",
"[",
"]",
"if",
"transform",
"is",
"None",
":",
"transform",
"=",
"lambda",
"node",
",",
"parents",
",",
"nodes",
",",
"*",
"args",
":",
"node",
"def",
"__collect__",
"(",
"node",
",",
"parents",
",",
"nodes",
",",
"first",
",",
"last",
",",
"depth",
")",
":",
"items",
".",
"append",
"(",
"transform",
"(",
"node",
",",
"parents",
",",
"nodes",
",",
"first",
",",
"last",
",",
"depth",
")",
")",
"apply_depth_first",
"(",
"nested_nodes",
",",
"__collect__",
")",
"return",
"items"
] | Return list containing the result of the `transform` function applied to
each item in the supplied list of nested nodes.
A custom transform function may be applied to each entry during the
flattening by specifying a function through the `transform` keyword
argument. The `transform` function will be passed the following arguments:
- `node`: The node/key of the entry.
- `parents`: The node/key of the parents as a `list`.
- `nodes`: The children of the entry.
By default, the `transform` function simply returns the node/key, resulting
in a flattened version of the original nested nodes structure. | [
"Return",
"list",
"containing",
"the",
"result",
"of",
"the",
"transform",
"function",
"applied",
"to",
"each",
"item",
"in",
"the",
"supplied",
"list",
"of",
"nested",
"nodes",
"."
] | e3586bcca01c59f18ae16b8240e6e49197b63ecb | https://github.com/wheeler-microfluidics/nested-structures/blob/e3586bcca01c59f18ae16b8240e6e49197b63ecb/nested_structures/__init__.py#L193-L218 |
250,961 | ramrod-project/database-brain | schema/brain/binary/decorators.py | wrap_split_big_content | def wrap_split_big_content(func_, *args, **kwargs):
"""
chunk the content into smaller binary blobs before inserting
this function should chunk in such a way that this
is completely transparent to the user.
:param func_:
:param args:
:param kwargs:
:return: <dict> RethinkDB dict from insert
"""
obj_dict = args[0]
if len(obj_dict[CONTENT_FIELD]) < MAX_PUT:
obj_dict[PART_FIELD] = False
return func_(*args, **kwargs)
else:
return _perform_chunking(func_, *args, **kwargs) | python | def wrap_split_big_content(func_, *args, **kwargs):
"""
chunk the content into smaller binary blobs before inserting
this function should chunk in such a way that this
is completely transparent to the user.
:param func_:
:param args:
:param kwargs:
:return: <dict> RethinkDB dict from insert
"""
obj_dict = args[0]
if len(obj_dict[CONTENT_FIELD]) < MAX_PUT:
obj_dict[PART_FIELD] = False
return func_(*args, **kwargs)
else:
return _perform_chunking(func_, *args, **kwargs) | [
"def",
"wrap_split_big_content",
"(",
"func_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obj_dict",
"=",
"args",
"[",
"0",
"]",
"if",
"len",
"(",
"obj_dict",
"[",
"CONTENT_FIELD",
"]",
")",
"<",
"MAX_PUT",
":",
"obj_dict",
"[",
"PART_FIELD",
"]",
"=",
"False",
"return",
"func_",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"_perform_chunking",
"(",
"func_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | chunk the content into smaller binary blobs before inserting
this function should chunk in such a way that this
is completely transparent to the user.
:param func_:
:param args:
:param kwargs:
:return: <dict> RethinkDB dict from insert | [
"chunk",
"the",
"content",
"into",
"smaller",
"binary",
"blobs",
"before",
"inserting"
] | b024cb44f34cabb9d80af38271ddb65c25767083 | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/binary/decorators.py#L35-L52 |
250,962 | ramrod-project/database-brain | schema/brain/binary/decorators.py | _only_if_file_not_exist | def _only_if_file_not_exist(func_, *args, **kwargs):
"""
horribly non-atomic
:param func_:
:param args:
:param kwargs:
:return:
"""
obj_dict = args[1]
conn = args[-1]
try:
RBF.get(obj_dict[PRIMARY_FIELD]).pluck(PRIMARY_FIELD).run(conn)
err_str = "Duplicate primary key `Name`: {}".format(obj_dict[PRIMARY_FIELD])
err_dict = {'errors': 1,
'first_error': err_str}
return err_dict
except r.errors.ReqlNonExistenceError:
return func_(*args, **kwargs) | python | def _only_if_file_not_exist(func_, *args, **kwargs):
"""
horribly non-atomic
:param func_:
:param args:
:param kwargs:
:return:
"""
obj_dict = args[1]
conn = args[-1]
try:
RBF.get(obj_dict[PRIMARY_FIELD]).pluck(PRIMARY_FIELD).run(conn)
err_str = "Duplicate primary key `Name`: {}".format(obj_dict[PRIMARY_FIELD])
err_dict = {'errors': 1,
'first_error': err_str}
return err_dict
except r.errors.ReqlNonExistenceError:
return func_(*args, **kwargs) | [
"def",
"_only_if_file_not_exist",
"(",
"func_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obj_dict",
"=",
"args",
"[",
"1",
"]",
"conn",
"=",
"args",
"[",
"-",
"1",
"]",
"try",
":",
"RBF",
".",
"get",
"(",
"obj_dict",
"[",
"PRIMARY_FIELD",
"]",
")",
".",
"pluck",
"(",
"PRIMARY_FIELD",
")",
".",
"run",
"(",
"conn",
")",
"err_str",
"=",
"\"Duplicate primary key `Name`: {}\"",
".",
"format",
"(",
"obj_dict",
"[",
"PRIMARY_FIELD",
"]",
")",
"err_dict",
"=",
"{",
"'errors'",
":",
"1",
",",
"'first_error'",
":",
"err_str",
"}",
"return",
"err_dict",
"except",
"r",
".",
"errors",
".",
"ReqlNonExistenceError",
":",
"return",
"func_",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | horribly non-atomic
:param func_:
:param args:
:param kwargs:
:return: | [
"horribly",
"non",
"-",
"atomic"
] | b024cb44f34cabb9d80af38271ddb65c25767083 | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/binary/decorators.py#L56-L74 |
250,963 | ramrod-project/database-brain | schema/brain/binary/decorators.py | _perform_chunking | def _perform_chunking(func_, *args, **kwargs):
"""
internal function alled only by
wrap_split_big_content
performs the actual chunking.
:param func_:
:param args:
:param kwargs:
:return: <dict> RethinkDB dict from insert
"""
obj_dict = args[0]
start_point = 0
file_count = 0
new_dict = {}
resp_dict = Counter({})
file_list = []
while start_point < len(obj_dict[CONTENT_FIELD]):
file_count += 1
chunk_fn = CHUNK_POSTFIX.format(obj_dict[PRIMARY_FIELD],
str(file_count).zfill(CHUNK_ZPAD))
new_dict[PRIMARY_FIELD] = chunk_fn
file_list.append(new_dict[PRIMARY_FIELD])
new_dict[CONTENTTYPE_FIELD] = obj_dict[CONTENTTYPE_FIELD]
new_dict[TIMESTAMP_FIELD] = obj_dict[TIMESTAMP_FIELD]
end_point = file_count * MAX_PUT
sliced = obj_dict[CONTENT_FIELD][start_point: end_point]
new_dict[CONTENT_FIELD] = sliced
new_dict[PART_FIELD] = True
new_dict[PARENT_FIELD] = obj_dict[PRIMARY_FIELD]
start_point = end_point
new_args = (new_dict, args[1])
resp_dict += Counter(func_(*new_args, **kwargs))
obj_dict[CONTENT_FIELD] = b""
obj_dict[PARTS_FIELD] = file_list
obj_dict[PART_FIELD] = False
new_args = (obj_dict, args[1])
resp_dict += Counter(func_(*new_args, **kwargs))
return resp_dict | python | def _perform_chunking(func_, *args, **kwargs):
"""
internal function alled only by
wrap_split_big_content
performs the actual chunking.
:param func_:
:param args:
:param kwargs:
:return: <dict> RethinkDB dict from insert
"""
obj_dict = args[0]
start_point = 0
file_count = 0
new_dict = {}
resp_dict = Counter({})
file_list = []
while start_point < len(obj_dict[CONTENT_FIELD]):
file_count += 1
chunk_fn = CHUNK_POSTFIX.format(obj_dict[PRIMARY_FIELD],
str(file_count).zfill(CHUNK_ZPAD))
new_dict[PRIMARY_FIELD] = chunk_fn
file_list.append(new_dict[PRIMARY_FIELD])
new_dict[CONTENTTYPE_FIELD] = obj_dict[CONTENTTYPE_FIELD]
new_dict[TIMESTAMP_FIELD] = obj_dict[TIMESTAMP_FIELD]
end_point = file_count * MAX_PUT
sliced = obj_dict[CONTENT_FIELD][start_point: end_point]
new_dict[CONTENT_FIELD] = sliced
new_dict[PART_FIELD] = True
new_dict[PARENT_FIELD] = obj_dict[PRIMARY_FIELD]
start_point = end_point
new_args = (new_dict, args[1])
resp_dict += Counter(func_(*new_args, **kwargs))
obj_dict[CONTENT_FIELD] = b""
obj_dict[PARTS_FIELD] = file_list
obj_dict[PART_FIELD] = False
new_args = (obj_dict, args[1])
resp_dict += Counter(func_(*new_args, **kwargs))
return resp_dict | [
"def",
"_perform_chunking",
"(",
"func_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obj_dict",
"=",
"args",
"[",
"0",
"]",
"start_point",
"=",
"0",
"file_count",
"=",
"0",
"new_dict",
"=",
"{",
"}",
"resp_dict",
"=",
"Counter",
"(",
"{",
"}",
")",
"file_list",
"=",
"[",
"]",
"while",
"start_point",
"<",
"len",
"(",
"obj_dict",
"[",
"CONTENT_FIELD",
"]",
")",
":",
"file_count",
"+=",
"1",
"chunk_fn",
"=",
"CHUNK_POSTFIX",
".",
"format",
"(",
"obj_dict",
"[",
"PRIMARY_FIELD",
"]",
",",
"str",
"(",
"file_count",
")",
".",
"zfill",
"(",
"CHUNK_ZPAD",
")",
")",
"new_dict",
"[",
"PRIMARY_FIELD",
"]",
"=",
"chunk_fn",
"file_list",
".",
"append",
"(",
"new_dict",
"[",
"PRIMARY_FIELD",
"]",
")",
"new_dict",
"[",
"CONTENTTYPE_FIELD",
"]",
"=",
"obj_dict",
"[",
"CONTENTTYPE_FIELD",
"]",
"new_dict",
"[",
"TIMESTAMP_FIELD",
"]",
"=",
"obj_dict",
"[",
"TIMESTAMP_FIELD",
"]",
"end_point",
"=",
"file_count",
"*",
"MAX_PUT",
"sliced",
"=",
"obj_dict",
"[",
"CONTENT_FIELD",
"]",
"[",
"start_point",
":",
"end_point",
"]",
"new_dict",
"[",
"CONTENT_FIELD",
"]",
"=",
"sliced",
"new_dict",
"[",
"PART_FIELD",
"]",
"=",
"True",
"new_dict",
"[",
"PARENT_FIELD",
"]",
"=",
"obj_dict",
"[",
"PRIMARY_FIELD",
"]",
"start_point",
"=",
"end_point",
"new_args",
"=",
"(",
"new_dict",
",",
"args",
"[",
"1",
"]",
")",
"resp_dict",
"+=",
"Counter",
"(",
"func_",
"(",
"*",
"new_args",
",",
"*",
"*",
"kwargs",
")",
")",
"obj_dict",
"[",
"CONTENT_FIELD",
"]",
"=",
"b\"\"",
"obj_dict",
"[",
"PARTS_FIELD",
"]",
"=",
"file_list",
"obj_dict",
"[",
"PART_FIELD",
"]",
"=",
"False",
"new_args",
"=",
"(",
"obj_dict",
",",
"args",
"[",
"1",
"]",
")",
"resp_dict",
"+=",
"Counter",
"(",
"func_",
"(",
"*",
"new_args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"resp_dict"
] | internal function alled only by
wrap_split_big_content
performs the actual chunking.
:param func_:
:param args:
:param kwargs:
:return: <dict> RethinkDB dict from insert | [
"internal",
"function",
"alled",
"only",
"by",
"wrap_split_big_content"
] | b024cb44f34cabb9d80af38271ddb65c25767083 | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/binary/decorators.py#L78-L118 |
250,964 | henrysher/kotocore | kotocore/utils/import_utils.py | import_class | def import_class(import_path):
"""
Imports a class dynamically from a full import path.
"""
if not '.' in import_path:
raise IncorrectImportPath(
"Invalid Python-style import path provided: {0}.".format(
import_path
)
)
path_bits = import_path.split('.')
mod_path = '.'.join(path_bits[:-1])
klass_name = path_bits[-1]
try:
mod = importlib.import_module(mod_path)
except ImportError:
raise IncorrectImportPath(
"Could not import module '{0}'.".format(mod_path)
)
try:
klass = getattr(mod, klass_name)
except AttributeError:
raise IncorrectImportPath(
"Imported module '{0}' but could not find class '{1}'.".format(
mod_path,
klass_name
)
)
return klass | python | def import_class(import_path):
"""
Imports a class dynamically from a full import path.
"""
if not '.' in import_path:
raise IncorrectImportPath(
"Invalid Python-style import path provided: {0}.".format(
import_path
)
)
path_bits = import_path.split('.')
mod_path = '.'.join(path_bits[:-1])
klass_name = path_bits[-1]
try:
mod = importlib.import_module(mod_path)
except ImportError:
raise IncorrectImportPath(
"Could not import module '{0}'.".format(mod_path)
)
try:
klass = getattr(mod, klass_name)
except AttributeError:
raise IncorrectImportPath(
"Imported module '{0}' but could not find class '{1}'.".format(
mod_path,
klass_name
)
)
return klass | [
"def",
"import_class",
"(",
"import_path",
")",
":",
"if",
"not",
"'.'",
"in",
"import_path",
":",
"raise",
"IncorrectImportPath",
"(",
"\"Invalid Python-style import path provided: {0}.\"",
".",
"format",
"(",
"import_path",
")",
")",
"path_bits",
"=",
"import_path",
".",
"split",
"(",
"'.'",
")",
"mod_path",
"=",
"'.'",
".",
"join",
"(",
"path_bits",
"[",
":",
"-",
"1",
"]",
")",
"klass_name",
"=",
"path_bits",
"[",
"-",
"1",
"]",
"try",
":",
"mod",
"=",
"importlib",
".",
"import_module",
"(",
"mod_path",
")",
"except",
"ImportError",
":",
"raise",
"IncorrectImportPath",
"(",
"\"Could not import module '{0}'.\"",
".",
"format",
"(",
"mod_path",
")",
")",
"try",
":",
"klass",
"=",
"getattr",
"(",
"mod",
",",
"klass_name",
")",
"except",
"AttributeError",
":",
"raise",
"IncorrectImportPath",
"(",
"\"Imported module '{0}' but could not find class '{1}'.\"",
".",
"format",
"(",
"mod_path",
",",
"klass_name",
")",
")",
"return",
"klass"
] | Imports a class dynamically from a full import path. | [
"Imports",
"a",
"class",
"dynamically",
"from",
"a",
"full",
"import",
"path",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/utils/import_utils.py#L6-L38 |
250,965 | uw-it-aca/uw-restclients-hfs | uw_hfs/idcard.py | get_hfs_accounts | def get_hfs_accounts(netid):
"""
Return a restclients.models.hfs.HfsAccounts object on the given uwnetid
"""
url = ACCOUNTS_URL.format(uwnetid=netid)
response = get_resource(url)
return _object_from_json(response) | python | def get_hfs_accounts(netid):
"""
Return a restclients.models.hfs.HfsAccounts object on the given uwnetid
"""
url = ACCOUNTS_URL.format(uwnetid=netid)
response = get_resource(url)
return _object_from_json(response) | [
"def",
"get_hfs_accounts",
"(",
"netid",
")",
":",
"url",
"=",
"ACCOUNTS_URL",
".",
"format",
"(",
"uwnetid",
"=",
"netid",
")",
"response",
"=",
"get_resource",
"(",
"url",
")",
"return",
"_object_from_json",
"(",
"response",
")"
] | Return a restclients.models.hfs.HfsAccounts object on the given uwnetid | [
"Return",
"a",
"restclients",
".",
"models",
".",
"hfs",
".",
"HfsAccounts",
"object",
"on",
"the",
"given",
"uwnetid"
] | 685c3b16280d9e8b11b0d295c8852fa876f55ad0 | https://github.com/uw-it-aca/uw-restclients-hfs/blob/685c3b16280d9e8b11b0d295c8852fa876f55ad0/uw_hfs/idcard.py#L19-L25 |
250,966 | OldhamMade/PySO8601 | PySO8601/utility.py | _timedelta_from_elements | def _timedelta_from_elements(elements):
"""
Return a timedelta from a dict of date elements.
Accepts a dict containing any of the following:
- years
- months
- days
- hours
- minutes
- seconds
If years and/or months are provided, it will use a naive calcuation
of 365 days in a year and 30 days in a month.
"""
days = sum((
elements['days'],
_months_to_days(elements.get('months', 0)),
_years_to_days(elements.get('years', 0))
))
return datetime.timedelta(days=days,
hours=elements.get('hours', 0),
minutes=elements.get('minutes', 0),
seconds=elements.get('seconds', 0)) | python | def _timedelta_from_elements(elements):
"""
Return a timedelta from a dict of date elements.
Accepts a dict containing any of the following:
- years
- months
- days
- hours
- minutes
- seconds
If years and/or months are provided, it will use a naive calcuation
of 365 days in a year and 30 days in a month.
"""
days = sum((
elements['days'],
_months_to_days(elements.get('months', 0)),
_years_to_days(elements.get('years', 0))
))
return datetime.timedelta(days=days,
hours=elements.get('hours', 0),
minutes=elements.get('minutes', 0),
seconds=elements.get('seconds', 0)) | [
"def",
"_timedelta_from_elements",
"(",
"elements",
")",
":",
"days",
"=",
"sum",
"(",
"(",
"elements",
"[",
"'days'",
"]",
",",
"_months_to_days",
"(",
"elements",
".",
"get",
"(",
"'months'",
",",
"0",
")",
")",
",",
"_years_to_days",
"(",
"elements",
".",
"get",
"(",
"'years'",
",",
"0",
")",
")",
")",
")",
"return",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"days",
",",
"hours",
"=",
"elements",
".",
"get",
"(",
"'hours'",
",",
"0",
")",
",",
"minutes",
"=",
"elements",
".",
"get",
"(",
"'minutes'",
",",
"0",
")",
",",
"seconds",
"=",
"elements",
".",
"get",
"(",
"'seconds'",
",",
"0",
")",
")"
] | Return a timedelta from a dict of date elements.
Accepts a dict containing any of the following:
- years
- months
- days
- hours
- minutes
- seconds
If years and/or months are provided, it will use a naive calcuation
of 365 days in a year and 30 days in a month. | [
"Return",
"a",
"timedelta",
"from",
"a",
"dict",
"of",
"date",
"elements",
"."
] | b7d3b3cb3ed3e12eb2a21caa26a3abeab3c96fe4 | https://github.com/OldhamMade/PySO8601/blob/b7d3b3cb3ed3e12eb2a21caa26a3abeab3c96fe4/PySO8601/utility.py#L28-L52 |
250,967 | laysakura/relshell | relshell/batch.py | Batch.next | def next(self):
"""Return one of record in this batch in out-of-order.
:raises: `StopIteration` when no more record is in this batch
"""
if self._records_iter >= len(self._records):
raise StopIteration
self._records_iter += 1
return self._records[self._records_iter - 1] | python | def next(self):
"""Return one of record in this batch in out-of-order.
:raises: `StopIteration` when no more record is in this batch
"""
if self._records_iter >= len(self._records):
raise StopIteration
self._records_iter += 1
return self._records[self._records_iter - 1] | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_records_iter",
">=",
"len",
"(",
"self",
".",
"_records",
")",
":",
"raise",
"StopIteration",
"self",
".",
"_records_iter",
"+=",
"1",
"return",
"self",
".",
"_records",
"[",
"self",
".",
"_records_iter",
"-",
"1",
"]"
] | Return one of record in this batch in out-of-order.
:raises: `StopIteration` when no more record is in this batch | [
"Return",
"one",
"of",
"record",
"in",
"this",
"batch",
"in",
"out",
"-",
"of",
"-",
"order",
"."
] | 9ca5c03a34c11cb763a4a75595f18bf4383aa8cc | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch.py#L39-L47 |
250,968 | laysakura/relshell | relshell/batch.py | Batch.formatted_str | def formatted_str(self, format):
"""Return formatted str.
:param format: one of 'json', 'csv' are supported
"""
assert(format in ('json', 'csv'))
ret_str_list = []
for rec in self._records:
if format == 'json':
ret_str_list.append('{')
for i in xrange(len(rec)):
colname, colval = self._rdef[i].name, rec[i]
ret_str_list.append('"%s":"%s"' % (colname, str(colval).replace('"', r'\"')))
ret_str_list.append(',')
ret_str_list.pop() # drop last comma
ret_str_list.append('}%s' % (os.linesep))
elif format == 'csv':
for i in xrange(len(rec)):
colval = rec[i]
ret_str_list.append('"%s"' % (str(colval).replace('"', r'\"')))
ret_str_list.append(',')
ret_str_list.pop() # drop last comma
ret_str_list.append('%s' % (os.linesep))
else:
assert(False)
return ''.join(ret_str_list) | python | def formatted_str(self, format):
"""Return formatted str.
:param format: one of 'json', 'csv' are supported
"""
assert(format in ('json', 'csv'))
ret_str_list = []
for rec in self._records:
if format == 'json':
ret_str_list.append('{')
for i in xrange(len(rec)):
colname, colval = self._rdef[i].name, rec[i]
ret_str_list.append('"%s":"%s"' % (colname, str(colval).replace('"', r'\"')))
ret_str_list.append(',')
ret_str_list.pop() # drop last comma
ret_str_list.append('}%s' % (os.linesep))
elif format == 'csv':
for i in xrange(len(rec)):
colval = rec[i]
ret_str_list.append('"%s"' % (str(colval).replace('"', r'\"')))
ret_str_list.append(',')
ret_str_list.pop() # drop last comma
ret_str_list.append('%s' % (os.linesep))
else:
assert(False)
return ''.join(ret_str_list) | [
"def",
"formatted_str",
"(",
"self",
",",
"format",
")",
":",
"assert",
"(",
"format",
"in",
"(",
"'json'",
",",
"'csv'",
")",
")",
"ret_str_list",
"=",
"[",
"]",
"for",
"rec",
"in",
"self",
".",
"_records",
":",
"if",
"format",
"==",
"'json'",
":",
"ret_str_list",
".",
"append",
"(",
"'{'",
")",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"rec",
")",
")",
":",
"colname",
",",
"colval",
"=",
"self",
".",
"_rdef",
"[",
"i",
"]",
".",
"name",
",",
"rec",
"[",
"i",
"]",
"ret_str_list",
".",
"append",
"(",
"'\"%s\":\"%s\"'",
"%",
"(",
"colname",
",",
"str",
"(",
"colval",
")",
".",
"replace",
"(",
"'\"'",
",",
"r'\\\"'",
")",
")",
")",
"ret_str_list",
".",
"append",
"(",
"','",
")",
"ret_str_list",
".",
"pop",
"(",
")",
"# drop last comma",
"ret_str_list",
".",
"append",
"(",
"'}%s'",
"%",
"(",
"os",
".",
"linesep",
")",
")",
"elif",
"format",
"==",
"'csv'",
":",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"rec",
")",
")",
":",
"colval",
"=",
"rec",
"[",
"i",
"]",
"ret_str_list",
".",
"append",
"(",
"'\"%s\"'",
"%",
"(",
"str",
"(",
"colval",
")",
".",
"replace",
"(",
"'\"'",
",",
"r'\\\"'",
")",
")",
")",
"ret_str_list",
".",
"append",
"(",
"','",
")",
"ret_str_list",
".",
"pop",
"(",
")",
"# drop last comma",
"ret_str_list",
".",
"append",
"(",
"'%s'",
"%",
"(",
"os",
".",
"linesep",
")",
")",
"else",
":",
"assert",
"(",
"False",
")",
"return",
"''",
".",
"join",
"(",
"ret_str_list",
")"
] | Return formatted str.
:param format: one of 'json', 'csv' are supported | [
"Return",
"formatted",
"str",
"."
] | 9ca5c03a34c11cb763a4a75595f18bf4383aa8cc | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch.py#L52-L77 |
250,969 | rochacbruno/shiftpy | shiftpy/wsgi_utils.py | envify | def envify(app=None, add_repo_to_path=True):
"""
This will simply activate virtualenv on openshift ans returs the app
in a wsgi.py or app.py in your openshift python web app
- wsgi.py
from shiftpy.wsgi_utils import envify
from myproject import app
# wsgi expects an object named 'application'
application = envify(app)
"""
if getvar('HOMEDIR'):
if add_repo_to_path:
sys.path.append(os.path.join(getvar('REPO_DIR')))
sys.path.insert(0, os.path.dirname(__file__) or '.')
virtenv = getvar('PYTHON_DIR') + '/virtenv/'
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
exec_namespace = dict(__file__=virtualenv)
try:
if sys.version_info >= (3, 0):
with open(virtualenv, 'rb') as f:
code = compile(f.read(), virtualenv, 'exec')
exec(code, exec_namespace)
else:
execfile(virtualenv, exec_namespace) # noqa
except IOError:
pass
return app | python | def envify(app=None, add_repo_to_path=True):
"""
This will simply activate virtualenv on openshift ans returs the app
in a wsgi.py or app.py in your openshift python web app
- wsgi.py
from shiftpy.wsgi_utils import envify
from myproject import app
# wsgi expects an object named 'application'
application = envify(app)
"""
if getvar('HOMEDIR'):
if add_repo_to_path:
sys.path.append(os.path.join(getvar('REPO_DIR')))
sys.path.insert(0, os.path.dirname(__file__) or '.')
virtenv = getvar('PYTHON_DIR') + '/virtenv/'
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
exec_namespace = dict(__file__=virtualenv)
try:
if sys.version_info >= (3, 0):
with open(virtualenv, 'rb') as f:
code = compile(f.read(), virtualenv, 'exec')
exec(code, exec_namespace)
else:
execfile(virtualenv, exec_namespace) # noqa
except IOError:
pass
return app | [
"def",
"envify",
"(",
"app",
"=",
"None",
",",
"add_repo_to_path",
"=",
"True",
")",
":",
"if",
"getvar",
"(",
"'HOMEDIR'",
")",
":",
"if",
"add_repo_to_path",
":",
"sys",
".",
"path",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"getvar",
"(",
"'REPO_DIR'",
")",
")",
")",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"or",
"'.'",
")",
"virtenv",
"=",
"getvar",
"(",
"'PYTHON_DIR'",
")",
"+",
"'/virtenv/'",
"virtualenv",
"=",
"os",
".",
"path",
".",
"join",
"(",
"virtenv",
",",
"'bin/activate_this.py'",
")",
"exec_namespace",
"=",
"dict",
"(",
"__file__",
"=",
"virtualenv",
")",
"try",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"with",
"open",
"(",
"virtualenv",
",",
"'rb'",
")",
"as",
"f",
":",
"code",
"=",
"compile",
"(",
"f",
".",
"read",
"(",
")",
",",
"virtualenv",
",",
"'exec'",
")",
"exec",
"(",
"code",
",",
"exec_namespace",
")",
"else",
":",
"execfile",
"(",
"virtualenv",
",",
"exec_namespace",
")",
"# noqa",
"except",
"IOError",
":",
"pass",
"return",
"app"
] | This will simply activate virtualenv on openshift ans returs the app
in a wsgi.py or app.py in your openshift python web app
- wsgi.py
from shiftpy.wsgi_utils import envify
from myproject import app
# wsgi expects an object named 'application'
application = envify(app) | [
"This",
"will",
"simply",
"activate",
"virtualenv",
"on",
"openshift",
"ans",
"returs",
"the",
"app"
] | 6bffccf511f24b7e53dcfee9807e0e3388aa823a | https://github.com/rochacbruno/shiftpy/blob/6bffccf511f24b7e53dcfee9807e0e3388aa823a/shiftpy/wsgi_utils.py#L7-L38 |
250,970 | pglass/nose-blacklist | noseblacklist/plugin.py | BlacklistPlugin._read_file | def _read_file(self, filename):
"""Return the lines from the given file, ignoring lines that start with
comments"""
result = []
with open(filename, 'r') as f:
lines = f.read().split('\n')
for line in lines:
nocomment = line.strip().split('#')[0].strip()
if nocomment:
result.append(nocomment)
return result | python | def _read_file(self, filename):
"""Return the lines from the given file, ignoring lines that start with
comments"""
result = []
with open(filename, 'r') as f:
lines = f.read().split('\n')
for line in lines:
nocomment = line.strip().split('#')[0].strip()
if nocomment:
result.append(nocomment)
return result | [
"def",
"_read_file",
"(",
"self",
",",
"filename",
")",
":",
"result",
"=",
"[",
"]",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines",
":",
"nocomment",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'#'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"if",
"nocomment",
":",
"result",
".",
"append",
"(",
"nocomment",
")",
"return",
"result"
] | Return the lines from the given file, ignoring lines that start with
comments | [
"Return",
"the",
"lines",
"from",
"the",
"given",
"file",
"ignoring",
"lines",
"that",
"start",
"with",
"comments"
] | 68e340ecea45d98e3a5ebf8aa9bf7975146cc20d | https://github.com/pglass/nose-blacklist/blob/68e340ecea45d98e3a5ebf8aa9bf7975146cc20d/noseblacklist/plugin.py#L71-L81 |
250,971 | josegomezr/pqb | pqb/queries.py | Select.order_by | def order_by(self, field, orientation='ASC'):
"""
Indica los campos y el criterio de ordenamiento
"""
if isinstance(field, list):
self.raw_order_by.append(field)
else:
self.raw_order_by.append([field, orientation])
return self | python | def order_by(self, field, orientation='ASC'):
"""
Indica los campos y el criterio de ordenamiento
"""
if isinstance(field, list):
self.raw_order_by.append(field)
else:
self.raw_order_by.append([field, orientation])
return self | [
"def",
"order_by",
"(",
"self",
",",
"field",
",",
"orientation",
"=",
"'ASC'",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"list",
")",
":",
"self",
".",
"raw_order_by",
".",
"append",
"(",
"field",
")",
"else",
":",
"self",
".",
"raw_order_by",
".",
"append",
"(",
"[",
"field",
",",
"orientation",
"]",
")",
"return",
"self"
] | Indica los campos y el criterio de ordenamiento | [
"Indica",
"los",
"campos",
"y",
"el",
"criterio",
"de",
"ordenamiento"
] | a600cc6e4e9acdaaf2cff171d13eb85c9ed1757c | https://github.com/josegomezr/pqb/blob/a600cc6e4e9acdaaf2cff171d13eb85c9ed1757c/pqb/queries.py#L108-L117 |
250,972 | vedarthk/exreporter | exreporter/stores/github.py | GithubStore.create_or_update_issue | def create_or_update_issue(self, title, body, culprit, labels, **kwargs):
'''Creates or comments on existing issue in the store.
:params title: title for the issue
:params body: body, the content of the issue
:params culprit: string used to identify the cause of the issue,
also used for aggregation
:params labels: (optional) list of labels attached to the issue
:returns: issue object
:rtype: :class:`exreporter.stores.github.GithubIssue`
'''
issues = self.search(q=culprit, labels=labels)
self.time_delta = kwargs.pop('time_delta')
self.max_comments = kwargs.pop('max_comments')
if issues:
latest_issue = issues.pop(0)
return self.handle_issue_comment(
issue=latest_issue, title=title, body=body, **kwargs)
else:
return self.create_issue(
title=title, body=body, **kwargs) | python | def create_or_update_issue(self, title, body, culprit, labels, **kwargs):
'''Creates or comments on existing issue in the store.
:params title: title for the issue
:params body: body, the content of the issue
:params culprit: string used to identify the cause of the issue,
also used for aggregation
:params labels: (optional) list of labels attached to the issue
:returns: issue object
:rtype: :class:`exreporter.stores.github.GithubIssue`
'''
issues = self.search(q=culprit, labels=labels)
self.time_delta = kwargs.pop('time_delta')
self.max_comments = kwargs.pop('max_comments')
if issues:
latest_issue = issues.pop(0)
return self.handle_issue_comment(
issue=latest_issue, title=title, body=body, **kwargs)
else:
return self.create_issue(
title=title, body=body, **kwargs) | [
"def",
"create_or_update_issue",
"(",
"self",
",",
"title",
",",
"body",
",",
"culprit",
",",
"labels",
",",
"*",
"*",
"kwargs",
")",
":",
"issues",
"=",
"self",
".",
"search",
"(",
"q",
"=",
"culprit",
",",
"labels",
"=",
"labels",
")",
"self",
".",
"time_delta",
"=",
"kwargs",
".",
"pop",
"(",
"'time_delta'",
")",
"self",
".",
"max_comments",
"=",
"kwargs",
".",
"pop",
"(",
"'max_comments'",
")",
"if",
"issues",
":",
"latest_issue",
"=",
"issues",
".",
"pop",
"(",
"0",
")",
"return",
"self",
".",
"handle_issue_comment",
"(",
"issue",
"=",
"latest_issue",
",",
"title",
"=",
"title",
",",
"body",
"=",
"body",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"self",
".",
"create_issue",
"(",
"title",
"=",
"title",
",",
"body",
"=",
"body",
",",
"*",
"*",
"kwargs",
")"
] | Creates or comments on existing issue in the store.
:params title: title for the issue
:params body: body, the content of the issue
:params culprit: string used to identify the cause of the issue,
also used for aggregation
:params labels: (optional) list of labels attached to the issue
:returns: issue object
:rtype: :class:`exreporter.stores.github.GithubIssue` | [
"Creates",
"or",
"comments",
"on",
"existing",
"issue",
"in",
"the",
"store",
"."
] | 8adf445477341d43a13d3baa2551e1c0f68229bb | https://github.com/vedarthk/exreporter/blob/8adf445477341d43a13d3baa2551e1c0f68229bb/exreporter/stores/github.py#L49-L70 |
250,973 | vedarthk/exreporter | exreporter/stores/github.py | GithubStore.search | def search(self, q, labels, state='open,closed', **kwargs):
"""Search for issues in Github.
:param q: query string to search
:param state: state of the issue
:returns: list of issue objects
:rtype: list
"""
search_result = self.github_request.search(q=q, state=state, **kwargs)
if search_result['total_count'] > 0:
return list(
map(lambda issue_dict: GithubIssue(
github_request=self.github_request, **issue_dict),
search_result['items'])
) | python | def search(self, q, labels, state='open,closed', **kwargs):
"""Search for issues in Github.
:param q: query string to search
:param state: state of the issue
:returns: list of issue objects
:rtype: list
"""
search_result = self.github_request.search(q=q, state=state, **kwargs)
if search_result['total_count'] > 0:
return list(
map(lambda issue_dict: GithubIssue(
github_request=self.github_request, **issue_dict),
search_result['items'])
) | [
"def",
"search",
"(",
"self",
",",
"q",
",",
"labels",
",",
"state",
"=",
"'open,closed'",
",",
"*",
"*",
"kwargs",
")",
":",
"search_result",
"=",
"self",
".",
"github_request",
".",
"search",
"(",
"q",
"=",
"q",
",",
"state",
"=",
"state",
",",
"*",
"*",
"kwargs",
")",
"if",
"search_result",
"[",
"'total_count'",
"]",
">",
"0",
":",
"return",
"list",
"(",
"map",
"(",
"lambda",
"issue_dict",
":",
"GithubIssue",
"(",
"github_request",
"=",
"self",
".",
"github_request",
",",
"*",
"*",
"issue_dict",
")",
",",
"search_result",
"[",
"'items'",
"]",
")",
")"
] | Search for issues in Github.
:param q: query string to search
:param state: state of the issue
:returns: list of issue objects
:rtype: list | [
"Search",
"for",
"issues",
"in",
"Github",
"."
] | 8adf445477341d43a13d3baa2551e1c0f68229bb | https://github.com/vedarthk/exreporter/blob/8adf445477341d43a13d3baa2551e1c0f68229bb/exreporter/stores/github.py#L72-L87 |
250,974 | vedarthk/exreporter | exreporter/stores/github.py | GithubStore.handle_issue_comment | def handle_issue_comment(self, issue, title, body, **kwargs):
"""Decides whether to comment or create a new issue when trying to comment.
:param issue: issue on which the comment is to be added
:param title: title of the issue if new one is to be created
:param body: body of the issue/comment to be created
:returns: newly created issue or the one on which comment was created
:rtype: :class:`exreporter.stores.github.GithubIssue`
"""
if self._is_time_delta_valid(issue.updated_time_delta):
if issue.comments_count < self.max_comments:
issue.comment(body=body)
return issue
else:
return self.create_issue(title=title, body=body, **kwargs) | python | def handle_issue_comment(self, issue, title, body, **kwargs):
"""Decides whether to comment or create a new issue when trying to comment.
:param issue: issue on which the comment is to be added
:param title: title of the issue if new one is to be created
:param body: body of the issue/comment to be created
:returns: newly created issue or the one on which comment was created
:rtype: :class:`exreporter.stores.github.GithubIssue`
"""
if self._is_time_delta_valid(issue.updated_time_delta):
if issue.comments_count < self.max_comments:
issue.comment(body=body)
return issue
else:
return self.create_issue(title=title, body=body, **kwargs) | [
"def",
"handle_issue_comment",
"(",
"self",
",",
"issue",
",",
"title",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_is_time_delta_valid",
"(",
"issue",
".",
"updated_time_delta",
")",
":",
"if",
"issue",
".",
"comments_count",
"<",
"self",
".",
"max_comments",
":",
"issue",
".",
"comment",
"(",
"body",
"=",
"body",
")",
"return",
"issue",
"else",
":",
"return",
"self",
".",
"create_issue",
"(",
"title",
"=",
"title",
",",
"body",
"=",
"body",
",",
"*",
"*",
"kwargs",
")"
] | Decides whether to comment or create a new issue when trying to comment.
:param issue: issue on which the comment is to be added
:param title: title of the issue if new one is to be created
:param body: body of the issue/comment to be created
:returns: newly created issue or the one on which comment was created
:rtype: :class:`exreporter.stores.github.GithubIssue` | [
"Decides",
"whether",
"to",
"comment",
"or",
"create",
"a",
"new",
"issue",
"when",
"trying",
"to",
"comment",
"."
] | 8adf445477341d43a13d3baa2551e1c0f68229bb | https://github.com/vedarthk/exreporter/blob/8adf445477341d43a13d3baa2551e1c0f68229bb/exreporter/stores/github.py#L89-L104 |
250,975 | vedarthk/exreporter | exreporter/stores/github.py | GithubStore.create_issue | def create_issue(self, title, body, labels=None):
"""Creates a new issue in Github.
:params title: title of the issue to be created
:params body: body of the issue to be created
:params labels: (optional) list of labels for the issue
:returns: newly created issue
:rtype: :class:`exreporter.stores.github.GithubIssue`
"""
kwargs = self.github_request.create(
title=title, body=body, labels=labels)
return GithubIssue(github_request=self.github_request, **kwargs) | python | def create_issue(self, title, body, labels=None):
"""Creates a new issue in Github.
:params title: title of the issue to be created
:params body: body of the issue to be created
:params labels: (optional) list of labels for the issue
:returns: newly created issue
:rtype: :class:`exreporter.stores.github.GithubIssue`
"""
kwargs = self.github_request.create(
title=title, body=body, labels=labels)
return GithubIssue(github_request=self.github_request, **kwargs) | [
"def",
"create_issue",
"(",
"self",
",",
"title",
",",
"body",
",",
"labels",
"=",
"None",
")",
":",
"kwargs",
"=",
"self",
".",
"github_request",
".",
"create",
"(",
"title",
"=",
"title",
",",
"body",
"=",
"body",
",",
"labels",
"=",
"labels",
")",
"return",
"GithubIssue",
"(",
"github_request",
"=",
"self",
".",
"github_request",
",",
"*",
"*",
"kwargs",
")"
] | Creates a new issue in Github.
:params title: title of the issue to be created
:params body: body of the issue to be created
:params labels: (optional) list of labels for the issue
:returns: newly created issue
:rtype: :class:`exreporter.stores.github.GithubIssue` | [
"Creates",
"a",
"new",
"issue",
"in",
"Github",
"."
] | 8adf445477341d43a13d3baa2551e1c0f68229bb | https://github.com/vedarthk/exreporter/blob/8adf445477341d43a13d3baa2551e1c0f68229bb/exreporter/stores/github.py#L109-L120 |
250,976 | vedarthk/exreporter | exreporter/stores/github.py | GithubIssue.updated_time_delta | def updated_time_delta(self):
"""Returns the number of seconds ago the issue was updated from current time.
"""
local_timezone = tzlocal()
update_at = datetime.datetime.strptime(self.updated_at, '%Y-%m-%dT%XZ')
update_at_utc = pytz.utc.localize(update_at)
update_at_local = update_at_utc.astimezone(local_timezone)
delta = datetime.datetime.now(local_timezone) - update_at_local
return int(delta.total_seconds()) | python | def updated_time_delta(self):
"""Returns the number of seconds ago the issue was updated from current time.
"""
local_timezone = tzlocal()
update_at = datetime.datetime.strptime(self.updated_at, '%Y-%m-%dT%XZ')
update_at_utc = pytz.utc.localize(update_at)
update_at_local = update_at_utc.astimezone(local_timezone)
delta = datetime.datetime.now(local_timezone) - update_at_local
return int(delta.total_seconds()) | [
"def",
"updated_time_delta",
"(",
"self",
")",
":",
"local_timezone",
"=",
"tzlocal",
"(",
")",
"update_at",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"self",
".",
"updated_at",
",",
"'%Y-%m-%dT%XZ'",
")",
"update_at_utc",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"update_at",
")",
"update_at_local",
"=",
"update_at_utc",
".",
"astimezone",
"(",
"local_timezone",
")",
"delta",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"local_timezone",
")",
"-",
"update_at_local",
"return",
"int",
"(",
"delta",
".",
"total_seconds",
"(",
")",
")"
] | Returns the number of seconds ago the issue was updated from current time. | [
"Returns",
"the",
"number",
"of",
"seconds",
"ago",
"the",
"issue",
"was",
"updated",
"from",
"current",
"time",
"."
] | 8adf445477341d43a13d3baa2551e1c0f68229bb | https://github.com/vedarthk/exreporter/blob/8adf445477341d43a13d3baa2551e1c0f68229bb/exreporter/stores/github.py#L145-L153 |
250,977 | vedarthk/exreporter | exreporter/stores/github.py | GithubIssue.open_issue | def open_issue(self):
"""Changes the state of issue to 'open'.
"""
self.github_request.update(issue=self, state='open')
self.state = 'open' | python | def open_issue(self):
"""Changes the state of issue to 'open'.
"""
self.github_request.update(issue=self, state='open')
self.state = 'open' | [
"def",
"open_issue",
"(",
"self",
")",
":",
"self",
".",
"github_request",
".",
"update",
"(",
"issue",
"=",
"self",
",",
"state",
"=",
"'open'",
")",
"self",
".",
"state",
"=",
"'open'"
] | Changes the state of issue to 'open'. | [
"Changes",
"the",
"state",
"of",
"issue",
"to",
"open",
"."
] | 8adf445477341d43a13d3baa2551e1c0f68229bb | https://github.com/vedarthk/exreporter/blob/8adf445477341d43a13d3baa2551e1c0f68229bb/exreporter/stores/github.py#L155-L159 |
250,978 | vedarthk/exreporter | exreporter/stores/github.py | GithubIssue.comment | def comment(self, body):
"""Adds a comment to the issue.
:params body: body, content of the comment
:returns: issue object
:rtype: :class:`exreporter.stores.github.GithubIssue`
"""
self.github_request.comment(issue=self, body=body)
if self.state == 'closed':
self.open_issue()
return self | python | def comment(self, body):
"""Adds a comment to the issue.
:params body: body, content of the comment
:returns: issue object
:rtype: :class:`exreporter.stores.github.GithubIssue`
"""
self.github_request.comment(issue=self, body=body)
if self.state == 'closed':
self.open_issue()
return self | [
"def",
"comment",
"(",
"self",
",",
"body",
")",
":",
"self",
".",
"github_request",
".",
"comment",
"(",
"issue",
"=",
"self",
",",
"body",
"=",
"body",
")",
"if",
"self",
".",
"state",
"==",
"'closed'",
":",
"self",
".",
"open_issue",
"(",
")",
"return",
"self"
] | Adds a comment to the issue.
:params body: body, content of the comment
:returns: issue object
:rtype: :class:`exreporter.stores.github.GithubIssue` | [
"Adds",
"a",
"comment",
"to",
"the",
"issue",
"."
] | 8adf445477341d43a13d3baa2551e1c0f68229bb | https://github.com/vedarthk/exreporter/blob/8adf445477341d43a13d3baa2551e1c0f68229bb/exreporter/stores/github.py#L161-L172 |
250,979 | jmgilman/Neolib | neolib/pyamf/alias.py | ClassAlias.createInstance | def createInstance(self, codec=None):
"""
Creates an instance of the klass.
@return: Instance of C{self.klass}.
"""
if type(self.klass) is type:
return self.klass.__new__(self.klass)
return self.klass() | python | def createInstance(self, codec=None):
"""
Creates an instance of the klass.
@return: Instance of C{self.klass}.
"""
if type(self.klass) is type:
return self.klass.__new__(self.klass)
return self.klass() | [
"def",
"createInstance",
"(",
"self",
",",
"codec",
"=",
"None",
")",
":",
"if",
"type",
"(",
"self",
".",
"klass",
")",
"is",
"type",
":",
"return",
"self",
".",
"klass",
".",
"__new__",
"(",
"self",
".",
"klass",
")",
"return",
"self",
".",
"klass",
"(",
")"
] | Creates an instance of the klass.
@return: Instance of C{self.klass}. | [
"Creates",
"an",
"instance",
"of",
"the",
"klass",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/alias.py#L537-L546 |
250,980 | amadev/doan | doan/graph.py | plot_date | def plot_date(datasets, **kwargs):
"""Plot points with dates.
datasets can be Dataset object or list of Dataset.
"""
defaults = {
'grid': True,
'xlabel': '',
'ylabel': '',
'title': '',
'output': None,
'figsize': (8, 6),
}
plot_params = {
'color': 'b',
'ls': '',
'alpha': 0.75,
}
_update_params(defaults, plot_params, kwargs)
if isinstance(datasets, Dataset):
datasets = [datasets]
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
color = plot_params.pop('color')
try:
del colors[colors.index(color)]
colors.insert(0, color)
except IndexError:
pass
colors = cycle(colors)
fig, ax = plt.subplots()
fig.set_size_inches(*defaults['figsize'])
fig.autofmt_xdate()
ax.autoscale_view()
for dataset in datasets:
if isinstance(dataset, Dataset):
dates = list(dataset.get_column_by_type(dataset.DATE))
values = list(dataset.get_column_by_type(dataset.NUM))
label = dataset.name
else:
dates, values = dataset
label = ''
dates = date2num(dates)
color = next(colors)
plt.plot_date(dates, values, color=color, label=label, **plot_params)
plt.xlabel(defaults['xlabel'])
plt.ylabel(defaults['ylabel'])
plt.title(defaults['title'])
plt.grid(defaults['grid'])
plt.legend(loc='best', prop={'size': 10})
filename = defaults['output'] or get_tmp_file_name('.png')
plt.savefig(filename)
return filename | python | def plot_date(datasets, **kwargs):
"""Plot points with dates.
datasets can be Dataset object or list of Dataset.
"""
defaults = {
'grid': True,
'xlabel': '',
'ylabel': '',
'title': '',
'output': None,
'figsize': (8, 6),
}
plot_params = {
'color': 'b',
'ls': '',
'alpha': 0.75,
}
_update_params(defaults, plot_params, kwargs)
if isinstance(datasets, Dataset):
datasets = [datasets]
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
color = plot_params.pop('color')
try:
del colors[colors.index(color)]
colors.insert(0, color)
except IndexError:
pass
colors = cycle(colors)
fig, ax = plt.subplots()
fig.set_size_inches(*defaults['figsize'])
fig.autofmt_xdate()
ax.autoscale_view()
for dataset in datasets:
if isinstance(dataset, Dataset):
dates = list(dataset.get_column_by_type(dataset.DATE))
values = list(dataset.get_column_by_type(dataset.NUM))
label = dataset.name
else:
dates, values = dataset
label = ''
dates = date2num(dates)
color = next(colors)
plt.plot_date(dates, values, color=color, label=label, **plot_params)
plt.xlabel(defaults['xlabel'])
plt.ylabel(defaults['ylabel'])
plt.title(defaults['title'])
plt.grid(defaults['grid'])
plt.legend(loc='best', prop={'size': 10})
filename = defaults['output'] or get_tmp_file_name('.png')
plt.savefig(filename)
return filename | [
"def",
"plot_date",
"(",
"datasets",
",",
"*",
"*",
"kwargs",
")",
":",
"defaults",
"=",
"{",
"'grid'",
":",
"True",
",",
"'xlabel'",
":",
"''",
",",
"'ylabel'",
":",
"''",
",",
"'title'",
":",
"''",
",",
"'output'",
":",
"None",
",",
"'figsize'",
":",
"(",
"8",
",",
"6",
")",
",",
"}",
"plot_params",
"=",
"{",
"'color'",
":",
"'b'",
",",
"'ls'",
":",
"''",
",",
"'alpha'",
":",
"0.75",
",",
"}",
"_update_params",
"(",
"defaults",
",",
"plot_params",
",",
"kwargs",
")",
"if",
"isinstance",
"(",
"datasets",
",",
"Dataset",
")",
":",
"datasets",
"=",
"[",
"datasets",
"]",
"colors",
"=",
"[",
"'b'",
",",
"'g'",
",",
"'r'",
",",
"'c'",
",",
"'m'",
",",
"'y'",
",",
"'k'",
"]",
"color",
"=",
"plot_params",
".",
"pop",
"(",
"'color'",
")",
"try",
":",
"del",
"colors",
"[",
"colors",
".",
"index",
"(",
"color",
")",
"]",
"colors",
".",
"insert",
"(",
"0",
",",
"color",
")",
"except",
"IndexError",
":",
"pass",
"colors",
"=",
"cycle",
"(",
"colors",
")",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
")",
"fig",
".",
"set_size_inches",
"(",
"*",
"defaults",
"[",
"'figsize'",
"]",
")",
"fig",
".",
"autofmt_xdate",
"(",
")",
"ax",
".",
"autoscale_view",
"(",
")",
"for",
"dataset",
"in",
"datasets",
":",
"if",
"isinstance",
"(",
"dataset",
",",
"Dataset",
")",
":",
"dates",
"=",
"list",
"(",
"dataset",
".",
"get_column_by_type",
"(",
"dataset",
".",
"DATE",
")",
")",
"values",
"=",
"list",
"(",
"dataset",
".",
"get_column_by_type",
"(",
"dataset",
".",
"NUM",
")",
")",
"label",
"=",
"dataset",
".",
"name",
"else",
":",
"dates",
",",
"values",
"=",
"dataset",
"label",
"=",
"''",
"dates",
"=",
"date2num",
"(",
"dates",
")",
"color",
"=",
"next",
"(",
"colors",
")",
"plt",
".",
"plot_date",
"(",
"dates",
",",
"values",
",",
"color",
"=",
"color",
",",
"label",
"=",
"label",
",",
"*",
"*",
"plot_params",
")",
"plt",
".",
"xlabel",
"(",
"defaults",
"[",
"'xlabel'",
"]",
")",
"plt",
".",
"ylabel",
"(",
"defaults",
"[",
"'ylabel'",
"]",
")",
"plt",
".",
"title",
"(",
"defaults",
"[",
"'title'",
"]",
")",
"plt",
".",
"grid",
"(",
"defaults",
"[",
"'grid'",
"]",
")",
"plt",
".",
"legend",
"(",
"loc",
"=",
"'best'",
",",
"prop",
"=",
"{",
"'size'",
":",
"10",
"}",
")",
"filename",
"=",
"defaults",
"[",
"'output'",
"]",
"or",
"get_tmp_file_name",
"(",
"'.png'",
")",
"plt",
".",
"savefig",
"(",
"filename",
")",
"return",
"filename"
] | Plot points with dates.
datasets can be Dataset object or list of Dataset. | [
"Plot",
"points",
"with",
"dates",
"."
] | 5adfa983ac547007a688fe7517291a432919aa3e | https://github.com/amadev/doan/blob/5adfa983ac547007a688fe7517291a432919aa3e/doan/graph.py#L28-L85 |
250,981 | tbreitenfeldt/invisible_ui | invisible_ui/events/handler.py | Handler.call_actions | def call_actions(self, event, *args, **kwargs):
"""Call each function in self._actions after setting self._event."""
self._event = event
for func in self._actions:
func(event, *args, **kwargs) | python | def call_actions(self, event, *args, **kwargs):
"""Call each function in self._actions after setting self._event."""
self._event = event
for func in self._actions:
func(event, *args, **kwargs) | [
"def",
"call_actions",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_event",
"=",
"event",
"for",
"func",
"in",
"self",
".",
"_actions",
":",
"func",
"(",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Call each function in self._actions after setting self._event. | [
"Call",
"each",
"function",
"in",
"self",
".",
"_actions",
"after",
"setting",
"self",
".",
"_event",
"."
] | 1a6907bfa61bded13fa9fb83ec7778c0df84487f | https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/events/handler.py#L53-L58 |
250,982 | KnowledgeLinks/rdfframework | rdfframework/sparql/__init__.py | read_query_notes | def read_query_notes(query_str, first_line=False):
"""
Returns the Comments from a query string that are in the header
"""
lines = query_str.split("\n")
started = False
parts = []
for line in lines:
line = line.strip()
if line.startswith("#"):
parts.append(line)
started = True
if first_line:
break
if started and line and not line.startswith("#"):
break
return "\n".join(parts) | python | def read_query_notes(query_str, first_line=False):
"""
Returns the Comments from a query string that are in the header
"""
lines = query_str.split("\n")
started = False
parts = []
for line in lines:
line = line.strip()
if line.startswith("#"):
parts.append(line)
started = True
if first_line:
break
if started and line and not line.startswith("#"):
break
return "\n".join(parts) | [
"def",
"read_query_notes",
"(",
"query_str",
",",
"first_line",
"=",
"False",
")",
":",
"lines",
"=",
"query_str",
".",
"split",
"(",
"\"\\n\"",
")",
"started",
"=",
"False",
"parts",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"parts",
".",
"append",
"(",
"line",
")",
"started",
"=",
"True",
"if",
"first_line",
":",
"break",
"if",
"started",
"and",
"line",
"and",
"not",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"break",
"return",
"\"\\n\"",
".",
"join",
"(",
"parts",
")"
] | Returns the Comments from a query string that are in the header | [
"Returns",
"the",
"Comments",
"from",
"a",
"query",
"string",
"that",
"are",
"in",
"the",
"header"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/sparql/__init__.py#L4-L20 |
250,983 | bluec0re/python-helperlib | helperlib/binary.py | hexdump | def hexdump(data, cols=8, folded=False, stream=False, offset=0, header=False):
"""
yields the rows of the hex dump
Arguments:
data -- data to dump
cols -- number of octets per row
folded -- fold long ranges of equal bytes
stream -- dont use len on data
>>> from string import ascii_uppercase
>>> print('\\n'.join(hexdump("".join(chr(i) for i in range(256)))))
00: 00 01 02 03 04 05 06 07 ........
08: 08 09 0A 0B 0C 0D 0E 0F ........
10: 10 11 12 13 14 15 16 17 ........
18: 18 19 1A 1B 1C 1D 1E 1F ........
20: 20 21 22 23 24 25 26 27 !"#$%&'
28: 28 29 2A 2B 2C 2D 2E 2F ()*+,-./
30: 30 31 32 33 34 35 36 37 01234567
38: 38 39 3A 3B 3C 3D 3E 3F 89:;<=>?
40: 40 41 42 43 44 45 46 47 @ABCDEFG
48: 48 49 4A 4B 4C 4D 4E 4F HIJKLMNO
50: 50 51 52 53 54 55 56 57 PQRSTUVW
58: 58 59 5A 5B 5C 5D 5E 5F XYZ[\]^_
60: 60 61 62 63 64 65 66 67 `abcdefg
68: 68 69 6A 6B 6C 6D 6E 6F hijklmno
70: 70 71 72 73 74 75 76 77 pqrstuvw
78: 78 79 7A 7B 7C 7D 7E 7F xyz{|}~.
80: 80 81 82 83 84 85 86 87 ........
88: 88 89 8A 8B 8C 8D 8E 8F ........
90: 90 91 92 93 94 95 96 97 ........
98: 98 99 9A 9B 9C 9D 9E 9F ........
A0: A0 A1 A2 A3 A4 A5 A6 A7 ........
A8: A8 A9 AA AB AC AD AE AF ........
B0: B0 B1 B2 B3 B4 B5 B6 B7 ........
B8: B8 B9 BA BB BC BD BE BF ........
C0: C0 C1 C2 C3 C4 C5 C6 C7 ........
C8: C8 C9 CA CB CC CD CE CF ........
D0: D0 D1 D2 D3 D4 D5 D6 D7 ........
D8: D8 D9 DA DB DC DD DE DF ........
E0: E0 E1 E2 E3 E4 E5 E6 E7 ........
E8: E8 E9 EA EB EC ED EE EF ........
F0: F0 F1 F2 F3 F4 F5 F6 F7 ........
F8: F8 F9 FA FB FC FD FE FF ........
>>> print('\\n'.join(hexdump(ascii_uppercase)))
00: 41 42 43 44 45 46 47 48 ABCDEFGH
08: 49 4A 4B 4C 4D 4E 4F 50 IJKLMNOP
10: 51 52 53 54 55 56 57 58 QRSTUVWX
18: 59 5A YZ
>>> print('\\n'.join(hexdump(ascii_uppercase, stream=True)))
00000: 41 42 43 44 45 46 47 48 ABCDEFGH
00008: 49 4A 4B 4C 4D 4E 4F 50 IJKLMNOP
00010: 51 52 53 54 55 56 57 58 QRSTUVWX
00018: 59 5A YZ
>>> print('\\n'.join(hexdump(ascii_uppercase + "0"*256, folded=True)))
000: 41 42 43 44 45 46 47 48 ABCDEFGH
008: 49 4A 4B 4C 4D 4E 4F 50 IJKLMNOP
010: 51 52 53 54 55 56 57 58 QRSTUVWX
018: 59 5A 30 30 30 30 30 30 YZ000000
*
118: 30 30 00
>>> print('\\n'.join(hexdump(ascii_uppercase + "0"*256, folded=True, stream=True)))
00000: 41 42 43 44 45 46 47 48 ABCDEFGH
00008: 49 4A 4B 4C 4D 4E 4F 50 IJKLMNOP
00010: 51 52 53 54 55 56 57 58 QRSTUVWX
00018: 59 5A 30 30 30 30 30 30 YZ000000
*
00118: 30 30 00
>>> print('\\n'.join(hexdump(ascii_uppercase, cols=16)))
00: 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 ABCDEFGHIJKLMNOP
10: 51 52 53 54 55 56 57 58 59 5A QRSTUVWXYZ
"""
last_byte = None
fold = False
# determine index width
if not stream:
size = len(data)
hexlen = len(hex(offset + size - 1)) - 2
offset_fmt = '{{:0{}X}}: '.format(hexlen)
if header:
line = ' ' * (hexlen + 2)
for i in range(min(cols, size + offset)):
line += '{:2X} '.format(i)
yield line.rstrip()
else:
size = None
hexlen = 5
offset_fmt = '{:05X}: '
if header:
line = ' ' * (5 + 2)
for i in range(cols):
line += '{:2X} '.format(i)
yield line.rstrip()
# convert input into iter if needed
if hasattr(data, 'read'):
def _tmp():
return data.read(1)
data_iter = iter(_tmp, '')
else:
data_iter = iter(data)
run = True
while run:
line = offset_fmt.format(offset - (offset % cols))
# ASCII dump
string = ''
skipped = 0
prefix = (offset % cols)
# padding
if offset % cols != 0:
line += ' ' * prefix
string += ' ' * prefix
try:
for _ in range(cols - (offset % cols)):
byte = next(data_iter)
# byte is equal to previous => count range of equal bytes
if last_byte == byte:
skipped += 1
last_byte = byte
offset += 1
if isinstance(byte, str):
bval = ord(byte)
elif isinstance(byte, int):
bval = byte
if 31 < bval < 127:
byte = chr(bval)
else:
bval = list(byte)[0]
if 31 < bval < 127:
byte = chr(bval)
if 31 < bval < 127:
string += byte
else:
string += '.'
line += '{:02X} '.format(bval)
except StopIteration:
run = False
# if folding is requested
if folded:
# all bytes are equal to the last byte of the previous block
if skipped == cols:
# show * the first time
if not fold:
yield ' ' * (hexlen + 2) + '*'
fold = True
continue
else:
fold = False
# padding
if offset % cols != 0:
line += ' ' * (cols - (offset % cols))
# yield only if no StopIteration was thrown or bytes are remaining
if offset % cols != 0 or run:
line += string
yield line.rstrip() | python | def hexdump(data, cols=8, folded=False, stream=False, offset=0, header=False):
"""
yields the rows of the hex dump
Arguments:
data -- data to dump
cols -- number of octets per row
folded -- fold long ranges of equal bytes
stream -- dont use len on data
>>> from string import ascii_uppercase
>>> print('\\n'.join(hexdump("".join(chr(i) for i in range(256)))))
00: 00 01 02 03 04 05 06 07 ........
08: 08 09 0A 0B 0C 0D 0E 0F ........
10: 10 11 12 13 14 15 16 17 ........
18: 18 19 1A 1B 1C 1D 1E 1F ........
20: 20 21 22 23 24 25 26 27 !"#$%&'
28: 28 29 2A 2B 2C 2D 2E 2F ()*+,-./
30: 30 31 32 33 34 35 36 37 01234567
38: 38 39 3A 3B 3C 3D 3E 3F 89:;<=>?
40: 40 41 42 43 44 45 46 47 @ABCDEFG
48: 48 49 4A 4B 4C 4D 4E 4F HIJKLMNO
50: 50 51 52 53 54 55 56 57 PQRSTUVW
58: 58 59 5A 5B 5C 5D 5E 5F XYZ[\]^_
60: 60 61 62 63 64 65 66 67 `abcdefg
68: 68 69 6A 6B 6C 6D 6E 6F hijklmno
70: 70 71 72 73 74 75 76 77 pqrstuvw
78: 78 79 7A 7B 7C 7D 7E 7F xyz{|}~.
80: 80 81 82 83 84 85 86 87 ........
88: 88 89 8A 8B 8C 8D 8E 8F ........
90: 90 91 92 93 94 95 96 97 ........
98: 98 99 9A 9B 9C 9D 9E 9F ........
A0: A0 A1 A2 A3 A4 A5 A6 A7 ........
A8: A8 A9 AA AB AC AD AE AF ........
B0: B0 B1 B2 B3 B4 B5 B6 B7 ........
B8: B8 B9 BA BB BC BD BE BF ........
C0: C0 C1 C2 C3 C4 C5 C6 C7 ........
C8: C8 C9 CA CB CC CD CE CF ........
D0: D0 D1 D2 D3 D4 D5 D6 D7 ........
D8: D8 D9 DA DB DC DD DE DF ........
E0: E0 E1 E2 E3 E4 E5 E6 E7 ........
E8: E8 E9 EA EB EC ED EE EF ........
F0: F0 F1 F2 F3 F4 F5 F6 F7 ........
F8: F8 F9 FA FB FC FD FE FF ........
>>> print('\\n'.join(hexdump(ascii_uppercase)))
00: 41 42 43 44 45 46 47 48 ABCDEFGH
08: 49 4A 4B 4C 4D 4E 4F 50 IJKLMNOP
10: 51 52 53 54 55 56 57 58 QRSTUVWX
18: 59 5A YZ
>>> print('\\n'.join(hexdump(ascii_uppercase, stream=True)))
00000: 41 42 43 44 45 46 47 48 ABCDEFGH
00008: 49 4A 4B 4C 4D 4E 4F 50 IJKLMNOP
00010: 51 52 53 54 55 56 57 58 QRSTUVWX
00018: 59 5A YZ
>>> print('\\n'.join(hexdump(ascii_uppercase + "0"*256, folded=True)))
000: 41 42 43 44 45 46 47 48 ABCDEFGH
008: 49 4A 4B 4C 4D 4E 4F 50 IJKLMNOP
010: 51 52 53 54 55 56 57 58 QRSTUVWX
018: 59 5A 30 30 30 30 30 30 YZ000000
*
118: 30 30 00
>>> print('\\n'.join(hexdump(ascii_uppercase + "0"*256, folded=True, stream=True)))
00000: 41 42 43 44 45 46 47 48 ABCDEFGH
00008: 49 4A 4B 4C 4D 4E 4F 50 IJKLMNOP
00010: 51 52 53 54 55 56 57 58 QRSTUVWX
00018: 59 5A 30 30 30 30 30 30 YZ000000
*
00118: 30 30 00
>>> print('\\n'.join(hexdump(ascii_uppercase, cols=16)))
00: 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 ABCDEFGHIJKLMNOP
10: 51 52 53 54 55 56 57 58 59 5A QRSTUVWXYZ
"""
last_byte = None
fold = False
# determine index width
if not stream:
size = len(data)
hexlen = len(hex(offset + size - 1)) - 2
offset_fmt = '{{:0{}X}}: '.format(hexlen)
if header:
line = ' ' * (hexlen + 2)
for i in range(min(cols, size + offset)):
line += '{:2X} '.format(i)
yield line.rstrip()
else:
size = None
hexlen = 5
offset_fmt = '{:05X}: '
if header:
line = ' ' * (5 + 2)
for i in range(cols):
line += '{:2X} '.format(i)
yield line.rstrip()
# convert input into iter if needed
if hasattr(data, 'read'):
def _tmp():
return data.read(1)
data_iter = iter(_tmp, '')
else:
data_iter = iter(data)
run = True
while run:
line = offset_fmt.format(offset - (offset % cols))
# ASCII dump
string = ''
skipped = 0
prefix = (offset % cols)
# padding
if offset % cols != 0:
line += ' ' * prefix
string += ' ' * prefix
try:
for _ in range(cols - (offset % cols)):
byte = next(data_iter)
# byte is equal to previous => count range of equal bytes
if last_byte == byte:
skipped += 1
last_byte = byte
offset += 1
if isinstance(byte, str):
bval = ord(byte)
elif isinstance(byte, int):
bval = byte
if 31 < bval < 127:
byte = chr(bval)
else:
bval = list(byte)[0]
if 31 < bval < 127:
byte = chr(bval)
if 31 < bval < 127:
string += byte
else:
string += '.'
line += '{:02X} '.format(bval)
except StopIteration:
run = False
# if folding is requested
if folded:
# all bytes are equal to the last byte of the previous block
if skipped == cols:
# show * the first time
if not fold:
yield ' ' * (hexlen + 2) + '*'
fold = True
continue
else:
fold = False
# padding
if offset % cols != 0:
line += ' ' * (cols - (offset % cols))
# yield only if no StopIteration was thrown or bytes are remaining
if offset % cols != 0 or run:
line += string
yield line.rstrip() | [
"def",
"hexdump",
"(",
"data",
",",
"cols",
"=",
"8",
",",
"folded",
"=",
"False",
",",
"stream",
"=",
"False",
",",
"offset",
"=",
"0",
",",
"header",
"=",
"False",
")",
":",
"last_byte",
"=",
"None",
"fold",
"=",
"False",
"# determine index width",
"if",
"not",
"stream",
":",
"size",
"=",
"len",
"(",
"data",
")",
"hexlen",
"=",
"len",
"(",
"hex",
"(",
"offset",
"+",
"size",
"-",
"1",
")",
")",
"-",
"2",
"offset_fmt",
"=",
"'{{:0{}X}}: '",
".",
"format",
"(",
"hexlen",
")",
"if",
"header",
":",
"line",
"=",
"' '",
"*",
"(",
"hexlen",
"+",
"2",
")",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"cols",
",",
"size",
"+",
"offset",
")",
")",
":",
"line",
"+=",
"'{:2X} '",
".",
"format",
"(",
"i",
")",
"yield",
"line",
".",
"rstrip",
"(",
")",
"else",
":",
"size",
"=",
"None",
"hexlen",
"=",
"5",
"offset_fmt",
"=",
"'{:05X}: '",
"if",
"header",
":",
"line",
"=",
"' '",
"*",
"(",
"5",
"+",
"2",
")",
"for",
"i",
"in",
"range",
"(",
"cols",
")",
":",
"line",
"+=",
"'{:2X} '",
".",
"format",
"(",
"i",
")",
"yield",
"line",
".",
"rstrip",
"(",
")",
"# convert input into iter if needed",
"if",
"hasattr",
"(",
"data",
",",
"'read'",
")",
":",
"def",
"_tmp",
"(",
")",
":",
"return",
"data",
".",
"read",
"(",
"1",
")",
"data_iter",
"=",
"iter",
"(",
"_tmp",
",",
"''",
")",
"else",
":",
"data_iter",
"=",
"iter",
"(",
"data",
")",
"run",
"=",
"True",
"while",
"run",
":",
"line",
"=",
"offset_fmt",
".",
"format",
"(",
"offset",
"-",
"(",
"offset",
"%",
"cols",
")",
")",
"# ASCII dump",
"string",
"=",
"''",
"skipped",
"=",
"0",
"prefix",
"=",
"(",
"offset",
"%",
"cols",
")",
"# padding",
"if",
"offset",
"%",
"cols",
"!=",
"0",
":",
"line",
"+=",
"' '",
"*",
"prefix",
"string",
"+=",
"' '",
"*",
"prefix",
"try",
":",
"for",
"_",
"in",
"range",
"(",
"cols",
"-",
"(",
"offset",
"%",
"cols",
")",
")",
":",
"byte",
"=",
"next",
"(",
"data_iter",
")",
"# byte is equal to previous => count range of equal bytes",
"if",
"last_byte",
"==",
"byte",
":",
"skipped",
"+=",
"1",
"last_byte",
"=",
"byte",
"offset",
"+=",
"1",
"if",
"isinstance",
"(",
"byte",
",",
"str",
")",
":",
"bval",
"=",
"ord",
"(",
"byte",
")",
"elif",
"isinstance",
"(",
"byte",
",",
"int",
")",
":",
"bval",
"=",
"byte",
"if",
"31",
"<",
"bval",
"<",
"127",
":",
"byte",
"=",
"chr",
"(",
"bval",
")",
"else",
":",
"bval",
"=",
"list",
"(",
"byte",
")",
"[",
"0",
"]",
"if",
"31",
"<",
"bval",
"<",
"127",
":",
"byte",
"=",
"chr",
"(",
"bval",
")",
"if",
"31",
"<",
"bval",
"<",
"127",
":",
"string",
"+=",
"byte",
"else",
":",
"string",
"+=",
"'.'",
"line",
"+=",
"'{:02X} '",
".",
"format",
"(",
"bval",
")",
"except",
"StopIteration",
":",
"run",
"=",
"False",
"# if folding is requested",
"if",
"folded",
":",
"# all bytes are equal to the last byte of the previous block",
"if",
"skipped",
"==",
"cols",
":",
"# show * the first time",
"if",
"not",
"fold",
":",
"yield",
"' '",
"*",
"(",
"hexlen",
"+",
"2",
")",
"+",
"'*'",
"fold",
"=",
"True",
"continue",
"else",
":",
"fold",
"=",
"False",
"# padding",
"if",
"offset",
"%",
"cols",
"!=",
"0",
":",
"line",
"+=",
"' '",
"*",
"(",
"cols",
"-",
"(",
"offset",
"%",
"cols",
")",
")",
"# yield only if no StopIteration was thrown or bytes are remaining",
"if",
"offset",
"%",
"cols",
"!=",
"0",
"or",
"run",
":",
"line",
"+=",
"string",
"yield",
"line",
".",
"rstrip",
"(",
")"
] | yields the rows of the hex dump
Arguments:
data -- data to dump
cols -- number of octets per row
folded -- fold long ranges of equal bytes
stream -- dont use len on data
>>> from string import ascii_uppercase
>>> print('\\n'.join(hexdump("".join(chr(i) for i in range(256)))))
00: 00 01 02 03 04 05 06 07 ........
08: 08 09 0A 0B 0C 0D 0E 0F ........
10: 10 11 12 13 14 15 16 17 ........
18: 18 19 1A 1B 1C 1D 1E 1F ........
20: 20 21 22 23 24 25 26 27 !"#$%&'
28: 28 29 2A 2B 2C 2D 2E 2F ()*+,-./
30: 30 31 32 33 34 35 36 37 01234567
38: 38 39 3A 3B 3C 3D 3E 3F 89:;<=>?
40: 40 41 42 43 44 45 46 47 @ABCDEFG
48: 48 49 4A 4B 4C 4D 4E 4F HIJKLMNO
50: 50 51 52 53 54 55 56 57 PQRSTUVW
58: 58 59 5A 5B 5C 5D 5E 5F XYZ[\]^_
60: 60 61 62 63 64 65 66 67 `abcdefg
68: 68 69 6A 6B 6C 6D 6E 6F hijklmno
70: 70 71 72 73 74 75 76 77 pqrstuvw
78: 78 79 7A 7B 7C 7D 7E 7F xyz{|}~.
80: 80 81 82 83 84 85 86 87 ........
88: 88 89 8A 8B 8C 8D 8E 8F ........
90: 90 91 92 93 94 95 96 97 ........
98: 98 99 9A 9B 9C 9D 9E 9F ........
A0: A0 A1 A2 A3 A4 A5 A6 A7 ........
A8: A8 A9 AA AB AC AD AE AF ........
B0: B0 B1 B2 B3 B4 B5 B6 B7 ........
B8: B8 B9 BA BB BC BD BE BF ........
C0: C0 C1 C2 C3 C4 C5 C6 C7 ........
C8: C8 C9 CA CB CC CD CE CF ........
D0: D0 D1 D2 D3 D4 D5 D6 D7 ........
D8: D8 D9 DA DB DC DD DE DF ........
E0: E0 E1 E2 E3 E4 E5 E6 E7 ........
E8: E8 E9 EA EB EC ED EE EF ........
F0: F0 F1 F2 F3 F4 F5 F6 F7 ........
F8: F8 F9 FA FB FC FD FE FF ........
>>> print('\\n'.join(hexdump(ascii_uppercase)))
00: 41 42 43 44 45 46 47 48 ABCDEFGH
08: 49 4A 4B 4C 4D 4E 4F 50 IJKLMNOP
10: 51 52 53 54 55 56 57 58 QRSTUVWX
18: 59 5A YZ
>>> print('\\n'.join(hexdump(ascii_uppercase, stream=True)))
00000: 41 42 43 44 45 46 47 48 ABCDEFGH
00008: 49 4A 4B 4C 4D 4E 4F 50 IJKLMNOP
00010: 51 52 53 54 55 56 57 58 QRSTUVWX
00018: 59 5A YZ
>>> print('\\n'.join(hexdump(ascii_uppercase + "0"*256, folded=True)))
000: 41 42 43 44 45 46 47 48 ABCDEFGH
008: 49 4A 4B 4C 4D 4E 4F 50 IJKLMNOP
010: 51 52 53 54 55 56 57 58 QRSTUVWX
018: 59 5A 30 30 30 30 30 30 YZ000000
*
118: 30 30 00
>>> print('\\n'.join(hexdump(ascii_uppercase + "0"*256, folded=True, stream=True)))
00000: 41 42 43 44 45 46 47 48 ABCDEFGH
00008: 49 4A 4B 4C 4D 4E 4F 50 IJKLMNOP
00010: 51 52 53 54 55 56 57 58 QRSTUVWX
00018: 59 5A 30 30 30 30 30 30 YZ000000
*
00118: 30 30 00
>>> print('\\n'.join(hexdump(ascii_uppercase, cols=16)))
00: 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 ABCDEFGHIJKLMNOP
10: 51 52 53 54 55 56 57 58 59 5A QRSTUVWXYZ | [
"yields",
"the",
"rows",
"of",
"the",
"hex",
"dump"
] | a2ac429668a6b86d3dc5e686978965c938f07d2c | https://github.com/bluec0re/python-helperlib/blob/a2ac429668a6b86d3dc5e686978965c938f07d2c/helperlib/binary.py#L13-L176 |
250,984 | PSU-OIT-ARC/django-cloak | cloak/__init__.py | can_cloak_as | def can_cloak_as(user, other_user):
"""
Returns true if `user` can cloak as `other_user`
"""
# check to see if the user is allowed to do this
can_cloak = False
try:
can_cloak = user.can_cloak_as(other_user)
except AttributeError as e:
try:
can_cloak = user.is_staff
except AttributeError as e:
pass
return can_cloak | python | def can_cloak_as(user, other_user):
"""
Returns true if `user` can cloak as `other_user`
"""
# check to see if the user is allowed to do this
can_cloak = False
try:
can_cloak = user.can_cloak_as(other_user)
except AttributeError as e:
try:
can_cloak = user.is_staff
except AttributeError as e:
pass
return can_cloak | [
"def",
"can_cloak_as",
"(",
"user",
",",
"other_user",
")",
":",
"# check to see if the user is allowed to do this",
"can_cloak",
"=",
"False",
"try",
":",
"can_cloak",
"=",
"user",
".",
"can_cloak_as",
"(",
"other_user",
")",
"except",
"AttributeError",
"as",
"e",
":",
"try",
":",
"can_cloak",
"=",
"user",
".",
"is_staff",
"except",
"AttributeError",
"as",
"e",
":",
"pass",
"return",
"can_cloak"
] | Returns true if `user` can cloak as `other_user` | [
"Returns",
"true",
"if",
"user",
"can",
"cloak",
"as",
"other_user"
] | 3f09711837f4fe7b1813692daa064e536135ffa3 | https://github.com/PSU-OIT-ARC/django-cloak/blob/3f09711837f4fe7b1813692daa064e536135ffa3/cloak/__init__.py#L5-L19 |
250,985 | jmvrbanac/lplight | lplight/client.py | LaunchpadClient.get_project | def get_project(self, name):
""" Retrives project information by name
:param name: The formal project name in string form.
"""
uri = '{base}/{project}'.format(base=self.BASE_URI, project=name)
resp = self._client.get(uri, model=models.Project)
return resp | python | def get_project(self, name):
""" Retrives project information by name
:param name: The formal project name in string form.
"""
uri = '{base}/{project}'.format(base=self.BASE_URI, project=name)
resp = self._client.get(uri, model=models.Project)
return resp | [
"def",
"get_project",
"(",
"self",
",",
"name",
")",
":",
"uri",
"=",
"'{base}/{project}'",
".",
"format",
"(",
"base",
"=",
"self",
".",
"BASE_URI",
",",
"project",
"=",
"name",
")",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"uri",
",",
"model",
"=",
"models",
".",
"Project",
")",
"return",
"resp"
] | Retrives project information by name
:param name: The formal project name in string form. | [
"Retrives",
"project",
"information",
"by",
"name"
] | 4d58b45e49ad9ba9e95f8c106d5c49e1658a69a7 | https://github.com/jmvrbanac/lplight/blob/4d58b45e49ad9ba9e95f8c106d5c49e1658a69a7/lplight/client.py#L57-L65 |
250,986 | jmvrbanac/lplight | lplight/client.py | LaunchpadClient.get_bugs | def get_bugs(self, project, status=None):
""" Retrives a List of bugs for a given project.
By default, this will only return activate bugs. If you wish to
retrieve a non-active bug then specify the status through the
status parameter.
:param project: The formal project name.
:param status: Allows filtering of bugs by current status.
"""
uri = '{base}/{project}'.format(base=self.BASE_URI, project=project)
parameters = {'ws.op': 'searchTasks'}
if status:
parameters['status'] = status
resp = self._client.get(uri, model=models.Bug, is_collection=True,
params=parameters)
return resp | python | def get_bugs(self, project, status=None):
""" Retrives a List of bugs for a given project.
By default, this will only return activate bugs. If you wish to
retrieve a non-active bug then specify the status through the
status parameter.
:param project: The formal project name.
:param status: Allows filtering of bugs by current status.
"""
uri = '{base}/{project}'.format(base=self.BASE_URI, project=project)
parameters = {'ws.op': 'searchTasks'}
if status:
parameters['status'] = status
resp = self._client.get(uri, model=models.Bug, is_collection=True,
params=parameters)
return resp | [
"def",
"get_bugs",
"(",
"self",
",",
"project",
",",
"status",
"=",
"None",
")",
":",
"uri",
"=",
"'{base}/{project}'",
".",
"format",
"(",
"base",
"=",
"self",
".",
"BASE_URI",
",",
"project",
"=",
"project",
")",
"parameters",
"=",
"{",
"'ws.op'",
":",
"'searchTasks'",
"}",
"if",
"status",
":",
"parameters",
"[",
"'status'",
"]",
"=",
"status",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"uri",
",",
"model",
"=",
"models",
".",
"Bug",
",",
"is_collection",
"=",
"True",
",",
"params",
"=",
"parameters",
")",
"return",
"resp"
] | Retrives a List of bugs for a given project.
By default, this will only return activate bugs. If you wish to
retrieve a non-active bug then specify the status through the
status parameter.
:param project: The formal project name.
:param status: Allows filtering of bugs by current status. | [
"Retrives",
"a",
"List",
"of",
"bugs",
"for",
"a",
"given",
"project",
".",
"By",
"default",
"this",
"will",
"only",
"return",
"activate",
"bugs",
".",
"If",
"you",
"wish",
"to",
"retrieve",
"a",
"non",
"-",
"active",
"bug",
"then",
"specify",
"the",
"status",
"through",
"the",
"status",
"parameter",
"."
] | 4d58b45e49ad9ba9e95f8c106d5c49e1658a69a7 | https://github.com/jmvrbanac/lplight/blob/4d58b45e49ad9ba9e95f8c106d5c49e1658a69a7/lplight/client.py#L67-L85 |
250,987 | jmvrbanac/lplight | lplight/client.py | LaunchpadClient.get_bug_by_id | def get_bug_by_id(self, bug_id):
""" Retrieves a single bug by it's Launchpad bug_id
:param bug_id: The Launchpad id for the bug.
"""
uri = '{base}/bugs/{bug_id}'.format(base=self.BASE_URI, bug_id=bug_id)
resp = self._client.get(uri, model=models.Bug)
return resp | python | def get_bug_by_id(self, bug_id):
""" Retrieves a single bug by it's Launchpad bug_id
:param bug_id: The Launchpad id for the bug.
"""
uri = '{base}/bugs/{bug_id}'.format(base=self.BASE_URI, bug_id=bug_id)
resp = self._client.get(uri, model=models.Bug)
return resp | [
"def",
"get_bug_by_id",
"(",
"self",
",",
"bug_id",
")",
":",
"uri",
"=",
"'{base}/bugs/{bug_id}'",
".",
"format",
"(",
"base",
"=",
"self",
".",
"BASE_URI",
",",
"bug_id",
"=",
"bug_id",
")",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"uri",
",",
"model",
"=",
"models",
".",
"Bug",
")",
"return",
"resp"
] | Retrieves a single bug by it's Launchpad bug_id
:param bug_id: The Launchpad id for the bug. | [
"Retrieves",
"a",
"single",
"bug",
"by",
"it",
"s",
"Launchpad",
"bug_id"
] | 4d58b45e49ad9ba9e95f8c106d5c49e1658a69a7 | https://github.com/jmvrbanac/lplight/blob/4d58b45e49ad9ba9e95f8c106d5c49e1658a69a7/lplight/client.py#L87-L95 |
250,988 | ramrod-project/database-brain | schema/brain/jobs.py | transition | def transition(prior_state, next_state):
"""
Transitions to a non-standard state
Raises InvalidStateTransition if next_state is not allowed.
:param prior_state: <str>
:param next_state: <str>
:return: <str>
"""
if next_state not in STATES[prior_state][TRANSITION]:
acceptable = STATES[prior_state][TRANSITION]
err = "cannot {}->{} may only {}->{}".format(prior_state,
next_state,
prior_state,
acceptable)
raise InvalidStateTransition(err)
return next_state | python | def transition(prior_state, next_state):
"""
Transitions to a non-standard state
Raises InvalidStateTransition if next_state is not allowed.
:param prior_state: <str>
:param next_state: <str>
:return: <str>
"""
if next_state not in STATES[prior_state][TRANSITION]:
acceptable = STATES[prior_state][TRANSITION]
err = "cannot {}->{} may only {}->{}".format(prior_state,
next_state,
prior_state,
acceptable)
raise InvalidStateTransition(err)
return next_state | [
"def",
"transition",
"(",
"prior_state",
",",
"next_state",
")",
":",
"if",
"next_state",
"not",
"in",
"STATES",
"[",
"prior_state",
"]",
"[",
"TRANSITION",
"]",
":",
"acceptable",
"=",
"STATES",
"[",
"prior_state",
"]",
"[",
"TRANSITION",
"]",
"err",
"=",
"\"cannot {}->{} may only {}->{}\"",
".",
"format",
"(",
"prior_state",
",",
"next_state",
",",
"prior_state",
",",
"acceptable",
")",
"raise",
"InvalidStateTransition",
"(",
"err",
")",
"return",
"next_state"
] | Transitions to a non-standard state
Raises InvalidStateTransition if next_state is not allowed.
:param prior_state: <str>
:param next_state: <str>
:return: <str> | [
"Transitions",
"to",
"a",
"non",
"-",
"standard",
"state"
] | b024cb44f34cabb9d80af38271ddb65c25767083 | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/jobs.py#L135-L152 |
250,989 | jabbas/pynapi | pynapi/services/napiprojekt.py | Napiprojekt.get | def get(self, filename):
""" returns subtitles as string """
params = {
"v": 'dreambox',
"kolejka": "false",
"nick": "",
"pass": "",
"napios": sys.platform,
"l": self.language.upper(),
"f": self.prepareHash(filename),
}
params['t'] = self.discombobulate(params['f'])
url = self.url_base + urllib.urlencode(params)
subs = urllib.urlopen(url).read()
if subs.startswith('brak pliku tymczasowego'):
raise NapiprojektException('napiprojekt.pl API error')
if subs[0:4] != 'NPc0':
# napiprojekt keeps subtitles in cp1250
# ... but, sometimes they are in utf8
for cdc in ['cp1250', 'utf8']:
try:
return codecs.decode(subs, cdc)
except:
pass | python | def get(self, filename):
""" returns subtitles as string """
params = {
"v": 'dreambox',
"kolejka": "false",
"nick": "",
"pass": "",
"napios": sys.platform,
"l": self.language.upper(),
"f": self.prepareHash(filename),
}
params['t'] = self.discombobulate(params['f'])
url = self.url_base + urllib.urlencode(params)
subs = urllib.urlopen(url).read()
if subs.startswith('brak pliku tymczasowego'):
raise NapiprojektException('napiprojekt.pl API error')
if subs[0:4] != 'NPc0':
# napiprojekt keeps subtitles in cp1250
# ... but, sometimes they are in utf8
for cdc in ['cp1250', 'utf8']:
try:
return codecs.decode(subs, cdc)
except:
pass | [
"def",
"get",
"(",
"self",
",",
"filename",
")",
":",
"params",
"=",
"{",
"\"v\"",
":",
"'dreambox'",
",",
"\"kolejka\"",
":",
"\"false\"",
",",
"\"nick\"",
":",
"\"\"",
",",
"\"pass\"",
":",
"\"\"",
",",
"\"napios\"",
":",
"sys",
".",
"platform",
",",
"\"l\"",
":",
"self",
".",
"language",
".",
"upper",
"(",
")",
",",
"\"f\"",
":",
"self",
".",
"prepareHash",
"(",
"filename",
")",
",",
"}",
"params",
"[",
"'t'",
"]",
"=",
"self",
".",
"discombobulate",
"(",
"params",
"[",
"'f'",
"]",
")",
"url",
"=",
"self",
".",
"url_base",
"+",
"urllib",
".",
"urlencode",
"(",
"params",
")",
"subs",
"=",
"urllib",
".",
"urlopen",
"(",
"url",
")",
".",
"read",
"(",
")",
"if",
"subs",
".",
"startswith",
"(",
"'brak pliku tymczasowego'",
")",
":",
"raise",
"NapiprojektException",
"(",
"'napiprojekt.pl API error'",
")",
"if",
"subs",
"[",
"0",
":",
"4",
"]",
"!=",
"'NPc0'",
":",
"# napiprojekt keeps subtitles in cp1250",
"# ... but, sometimes they are in utf8",
"for",
"cdc",
"in",
"[",
"'cp1250'",
",",
"'utf8'",
"]",
":",
"try",
":",
"return",
"codecs",
".",
"decode",
"(",
"subs",
",",
"cdc",
")",
"except",
":",
"pass"
] | returns subtitles as string | [
"returns",
"subtitles",
"as",
"string"
] | d9b3b4d9cd05501c14fe5cc5903b1c21e1905753 | https://github.com/jabbas/pynapi/blob/d9b3b4d9cd05501c14fe5cc5903b1c21e1905753/pynapi/services/napiprojekt.py#L21-L51 |
250,990 | jabbas/pynapi | pynapi/services/napiprojekt.py | Napiprojekt.discombobulate | def discombobulate(self, filehash):
""" prepare napiprojekt scrambled hash """
idx = [0xe, 0x3, 0x6, 0x8, 0x2]
mul = [2, 2, 5, 4, 3]
add = [0, 0xd, 0x10, 0xb, 0x5]
b = []
for i in xrange(len(idx)):
a = add[i]
m = mul[i]
i = idx[i]
t = a + int(filehash[i], 16)
v = int(filehash[t:t + 2], 16)
b.append(("%x" % (v * m))[-1])
return ''.join(b) | python | def discombobulate(self, filehash):
""" prepare napiprojekt scrambled hash """
idx = [0xe, 0x3, 0x6, 0x8, 0x2]
mul = [2, 2, 5, 4, 3]
add = [0, 0xd, 0x10, 0xb, 0x5]
b = []
for i in xrange(len(idx)):
a = add[i]
m = mul[i]
i = idx[i]
t = a + int(filehash[i], 16)
v = int(filehash[t:t + 2], 16)
b.append(("%x" % (v * m))[-1])
return ''.join(b) | [
"def",
"discombobulate",
"(",
"self",
",",
"filehash",
")",
":",
"idx",
"=",
"[",
"0xe",
",",
"0x3",
",",
"0x6",
",",
"0x8",
",",
"0x2",
"]",
"mul",
"=",
"[",
"2",
",",
"2",
",",
"5",
",",
"4",
",",
"3",
"]",
"add",
"=",
"[",
"0",
",",
"0xd",
",",
"0x10",
",",
"0xb",
",",
"0x5",
"]",
"b",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"idx",
")",
")",
":",
"a",
"=",
"add",
"[",
"i",
"]",
"m",
"=",
"mul",
"[",
"i",
"]",
"i",
"=",
"idx",
"[",
"i",
"]",
"t",
"=",
"a",
"+",
"int",
"(",
"filehash",
"[",
"i",
"]",
",",
"16",
")",
"v",
"=",
"int",
"(",
"filehash",
"[",
"t",
":",
"t",
"+",
"2",
"]",
",",
"16",
")",
"b",
".",
"append",
"(",
"(",
"\"%x\"",
"%",
"(",
"v",
"*",
"m",
")",
")",
"[",
"-",
"1",
"]",
")",
"return",
"''",
".",
"join",
"(",
"b",
")"
] | prepare napiprojekt scrambled hash | [
"prepare",
"napiprojekt",
"scrambled",
"hash"
] | d9b3b4d9cd05501c14fe5cc5903b1c21e1905753 | https://github.com/jabbas/pynapi/blob/d9b3b4d9cd05501c14fe5cc5903b1c21e1905753/pynapi/services/napiprojekt.py#L53-L70 |
250,991 | ploneintranet/ploneintranet.workspace | src/ploneintranet/workspace/browser/forms.py | user_has_email | def user_has_email(username):
""" make sure, that given user has an email associated """
user = api.user.get(username=username)
if not user.getProperty("email"):
msg = _(
"This user doesn't have an email associated "
"with their account."
)
raise Invalid(msg)
return True | python | def user_has_email(username):
""" make sure, that given user has an email associated """
user = api.user.get(username=username)
if not user.getProperty("email"):
msg = _(
"This user doesn't have an email associated "
"with their account."
)
raise Invalid(msg)
return True | [
"def",
"user_has_email",
"(",
"username",
")",
":",
"user",
"=",
"api",
".",
"user",
".",
"get",
"(",
"username",
"=",
"username",
")",
"if",
"not",
"user",
".",
"getProperty",
"(",
"\"email\"",
")",
":",
"msg",
"=",
"_",
"(",
"\"This user doesn't have an email associated \"",
"\"with their account.\"",
")",
"raise",
"Invalid",
"(",
"msg",
")",
"return",
"True"
] | make sure, that given user has an email associated | [
"make",
"sure",
"that",
"given",
"user",
"has",
"an",
"email",
"associated"
] | a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba | https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/browser/forms.py#L19-L29 |
250,992 | ploneintranet/ploneintranet.workspace | src/ploneintranet/workspace/browser/forms.py | workspaces_provider | def workspaces_provider(context):
"""
create a vocab of all workspaces in this site
"""
catalog = api.portal.get_tool(name="portal_catalog")
workspaces = catalog(portal_type="ploneintranet.workspace.workspacefolder")
current = api.content.get_uuid(context)
terms = []
for ws in workspaces:
if current != ws["UID"]:
terms.append(SimpleVocabulary.createTerm(
ws["UID"], ws["UID"], ws["Title"]))
return SimpleVocabulary(terms) | python | def workspaces_provider(context):
"""
create a vocab of all workspaces in this site
"""
catalog = api.portal.get_tool(name="portal_catalog")
workspaces = catalog(portal_type="ploneintranet.workspace.workspacefolder")
current = api.content.get_uuid(context)
terms = []
for ws in workspaces:
if current != ws["UID"]:
terms.append(SimpleVocabulary.createTerm(
ws["UID"], ws["UID"], ws["Title"]))
return SimpleVocabulary(terms) | [
"def",
"workspaces_provider",
"(",
"context",
")",
":",
"catalog",
"=",
"api",
".",
"portal",
".",
"get_tool",
"(",
"name",
"=",
"\"portal_catalog\"",
")",
"workspaces",
"=",
"catalog",
"(",
"portal_type",
"=",
"\"ploneintranet.workspace.workspacefolder\"",
")",
"current",
"=",
"api",
".",
"content",
".",
"get_uuid",
"(",
"context",
")",
"terms",
"=",
"[",
"]",
"for",
"ws",
"in",
"workspaces",
":",
"if",
"current",
"!=",
"ws",
"[",
"\"UID\"",
"]",
":",
"terms",
".",
"append",
"(",
"SimpleVocabulary",
".",
"createTerm",
"(",
"ws",
"[",
"\"UID\"",
"]",
",",
"ws",
"[",
"\"UID\"",
"]",
",",
"ws",
"[",
"\"Title\"",
"]",
")",
")",
"return",
"SimpleVocabulary",
"(",
"terms",
")"
] | create a vocab of all workspaces in this site | [
"create",
"a",
"vocab",
"of",
"all",
"workspaces",
"in",
"this",
"site"
] | a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba | https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/browser/forms.py#L32-L46 |
250,993 | Aslan11/wilos-cli | wilos/writers.py | Stdout.live_weather | def live_weather(self, live_weather):
"""Prints the live weather in a pretty format"""
summary = live_weather['currently']['summary']
self.summary(summary)
click.echo() | python | def live_weather(self, live_weather):
"""Prints the live weather in a pretty format"""
summary = live_weather['currently']['summary']
self.summary(summary)
click.echo() | [
"def",
"live_weather",
"(",
"self",
",",
"live_weather",
")",
":",
"summary",
"=",
"live_weather",
"[",
"'currently'",
"]",
"[",
"'summary'",
"]",
"self",
".",
"summary",
"(",
"summary",
")",
"click",
".",
"echo",
"(",
")"
] | Prints the live weather in a pretty format | [
"Prints",
"the",
"live",
"weather",
"in",
"a",
"pretty",
"format"
] | 2c3da3589f685e95b4f73237a1bfe56373ea4574 | https://github.com/Aslan11/wilos-cli/blob/2c3da3589f685e95b4f73237a1bfe56373ea4574/wilos/writers.py#L43-L47 |
250,994 | Aslan11/wilos-cli | wilos/writers.py | Stdout.title | def title(self, title):
"""Prints the title"""
title = " What's it like out side {0}? ".format(title)
click.secho("{:=^62}".format(title), fg=self.colors.WHITE)
click.echo() | python | def title(self, title):
"""Prints the title"""
title = " What's it like out side {0}? ".format(title)
click.secho("{:=^62}".format(title), fg=self.colors.WHITE)
click.echo() | [
"def",
"title",
"(",
"self",
",",
"title",
")",
":",
"title",
"=",
"\" What's it like out side {0}? \"",
".",
"format",
"(",
"title",
")",
"click",
".",
"secho",
"(",
"\"{:=^62}\"",
".",
"format",
"(",
"title",
")",
",",
"fg",
"=",
"self",
".",
"colors",
".",
"WHITE",
")",
"click",
".",
"echo",
"(",
")"
] | Prints the title | [
"Prints",
"the",
"title"
] | 2c3da3589f685e95b4f73237a1bfe56373ea4574 | https://github.com/Aslan11/wilos-cli/blob/2c3da3589f685e95b4f73237a1bfe56373ea4574/wilos/writers.py#L49-L53 |
250,995 | henrysher/kotocore | kotocore/loader.py | ResourceJSONLoader.get_available_options | def get_available_options(self, service_name):
"""
Fetches a collection of all JSON files for a given service.
This checks user-created files (if present) as well as including the
default service files.
Example::
>>> loader.get_available_options('s3')
{
'2013-11-27': [
'~/.boto-overrides/s3-2013-11-27.json',
'/path/to/kotocore/data/aws/resources/s3-2013-11-27.json',
],
'2010-10-06': [
'/path/to/kotocore/data/aws/resources/s3-2010-10-06.json',
],
'2007-09-15': [
'~/.boto-overrides/s3-2007-09-15.json',
],
}
:param service_name: The name of the desired service
:type service_name: string
:returns: A dictionary of api_version keys, with a list of filepaths
for that version (in preferential order).
:rtype: dict
"""
options = {}
for data_dir in self.data_dirs:
# Traverse all the directories trying to find the best match.
service_glob = "{0}-*.json".format(service_name)
path = os.path.join(data_dir, service_glob)
found = glob.glob(path)
for match in found:
# Rip apart the path to determine the API version.
base = os.path.basename(match)
bits = os.path.splitext(base)[0].split('-', 1)
if len(bits) < 2:
continue
api_version = bits[1]
options.setdefault(api_version, [])
options[api_version].append(match)
return options | python | def get_available_options(self, service_name):
"""
Fetches a collection of all JSON files for a given service.
This checks user-created files (if present) as well as including the
default service files.
Example::
>>> loader.get_available_options('s3')
{
'2013-11-27': [
'~/.boto-overrides/s3-2013-11-27.json',
'/path/to/kotocore/data/aws/resources/s3-2013-11-27.json',
],
'2010-10-06': [
'/path/to/kotocore/data/aws/resources/s3-2010-10-06.json',
],
'2007-09-15': [
'~/.boto-overrides/s3-2007-09-15.json',
],
}
:param service_name: The name of the desired service
:type service_name: string
:returns: A dictionary of api_version keys, with a list of filepaths
for that version (in preferential order).
:rtype: dict
"""
options = {}
for data_dir in self.data_dirs:
# Traverse all the directories trying to find the best match.
service_glob = "{0}-*.json".format(service_name)
path = os.path.join(data_dir, service_glob)
found = glob.glob(path)
for match in found:
# Rip apart the path to determine the API version.
base = os.path.basename(match)
bits = os.path.splitext(base)[0].split('-', 1)
if len(bits) < 2:
continue
api_version = bits[1]
options.setdefault(api_version, [])
options[api_version].append(match)
return options | [
"def",
"get_available_options",
"(",
"self",
",",
"service_name",
")",
":",
"options",
"=",
"{",
"}",
"for",
"data_dir",
"in",
"self",
".",
"data_dirs",
":",
"# Traverse all the directories trying to find the best match.",
"service_glob",
"=",
"\"{0}-*.json\"",
".",
"format",
"(",
"service_name",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"service_glob",
")",
"found",
"=",
"glob",
".",
"glob",
"(",
"path",
")",
"for",
"match",
"in",
"found",
":",
"# Rip apart the path to determine the API version.",
"base",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"match",
")",
"bits",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"base",
")",
"[",
"0",
"]",
".",
"split",
"(",
"'-'",
",",
"1",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"continue",
"api_version",
"=",
"bits",
"[",
"1",
"]",
"options",
".",
"setdefault",
"(",
"api_version",
",",
"[",
"]",
")",
"options",
"[",
"api_version",
"]",
".",
"append",
"(",
"match",
")",
"return",
"options"
] | Fetches a collection of all JSON files for a given service.
This checks user-created files (if present) as well as including the
default service files.
Example::
>>> loader.get_available_options('s3')
{
'2013-11-27': [
'~/.boto-overrides/s3-2013-11-27.json',
'/path/to/kotocore/data/aws/resources/s3-2013-11-27.json',
],
'2010-10-06': [
'/path/to/kotocore/data/aws/resources/s3-2010-10-06.json',
],
'2007-09-15': [
'~/.boto-overrides/s3-2007-09-15.json',
],
}
:param service_name: The name of the desired service
:type service_name: string
:returns: A dictionary of api_version keys, with a list of filepaths
for that version (in preferential order).
:rtype: dict | [
"Fetches",
"a",
"collection",
"of",
"all",
"JSON",
"files",
"for",
"a",
"given",
"service",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/loader.py#L54-L104 |
250,996 | henrysher/kotocore | kotocore/loader.py | ResourceJSONLoader.get_best_match | def get_best_match(self, options, service_name, api_version=None):
"""
Given a collection of possible service options, selects the best match.
If no API version is provided, the path to the most recent API version
will be returned. If an API version is provided & there is an exact
match, the path to that version will be returned. If there is no exact
match, an attempt will be made to find a compatible (earlier) version.
In all cases, user-created files (if present) will be given preference
over the default included versions.
:param options: A dictionary of options. See
``.get_available_options(...)``.
:type options: dict
:param service_name: The name of the desired service
:type service_name: string
:param api_version: (Optional) The desired API version to load
:type service_name: string
:returns: The full path to the best matching JSON file
"""
if not options:
msg = "No JSON files provided. Please check your " + \
"configuration/install."
raise NoResourceJSONFound(msg)
if api_version is None:
# Give them the very latest option.
best_version = max(options.keys())
return options[best_version][0], best_version
# They've provided an api_version. Try to give them exactly what they
# requested, falling back to the best compatible match if no exact
# match can be found.
if api_version in options:
return options[api_version][0], api_version
# Find the best compatible match. Run through in descending order.
# When we find a version that's lexographically less than the provided
# one, run with it.
for key in sorted(options.keys(), reverse=True):
if key <= api_version:
return options[key][0], key
raise NoResourceJSONFound(
"No compatible JSON could be loaded for {0} ({1}).".format(
service_name,
api_version
)
) | python | def get_best_match(self, options, service_name, api_version=None):
"""
Given a collection of possible service options, selects the best match.
If no API version is provided, the path to the most recent API version
will be returned. If an API version is provided & there is an exact
match, the path to that version will be returned. If there is no exact
match, an attempt will be made to find a compatible (earlier) version.
In all cases, user-created files (if present) will be given preference
over the default included versions.
:param options: A dictionary of options. See
``.get_available_options(...)``.
:type options: dict
:param service_name: The name of the desired service
:type service_name: string
:param api_version: (Optional) The desired API version to load
:type service_name: string
:returns: The full path to the best matching JSON file
"""
if not options:
msg = "No JSON files provided. Please check your " + \
"configuration/install."
raise NoResourceJSONFound(msg)
if api_version is None:
# Give them the very latest option.
best_version = max(options.keys())
return options[best_version][0], best_version
# They've provided an api_version. Try to give them exactly what they
# requested, falling back to the best compatible match if no exact
# match can be found.
if api_version in options:
return options[api_version][0], api_version
# Find the best compatible match. Run through in descending order.
# When we find a version that's lexographically less than the provided
# one, run with it.
for key in sorted(options.keys(), reverse=True):
if key <= api_version:
return options[key][0], key
raise NoResourceJSONFound(
"No compatible JSON could be loaded for {0} ({1}).".format(
service_name,
api_version
)
) | [
"def",
"get_best_match",
"(",
"self",
",",
"options",
",",
"service_name",
",",
"api_version",
"=",
"None",
")",
":",
"if",
"not",
"options",
":",
"msg",
"=",
"\"No JSON files provided. Please check your \"",
"+",
"\"configuration/install.\"",
"raise",
"NoResourceJSONFound",
"(",
"msg",
")",
"if",
"api_version",
"is",
"None",
":",
"# Give them the very latest option.",
"best_version",
"=",
"max",
"(",
"options",
".",
"keys",
"(",
")",
")",
"return",
"options",
"[",
"best_version",
"]",
"[",
"0",
"]",
",",
"best_version",
"# They've provided an api_version. Try to give them exactly what they",
"# requested, falling back to the best compatible match if no exact",
"# match can be found.",
"if",
"api_version",
"in",
"options",
":",
"return",
"options",
"[",
"api_version",
"]",
"[",
"0",
"]",
",",
"api_version",
"# Find the best compatible match. Run through in descending order.",
"# When we find a version that's lexographically less than the provided",
"# one, run with it.",
"for",
"key",
"in",
"sorted",
"(",
"options",
".",
"keys",
"(",
")",
",",
"reverse",
"=",
"True",
")",
":",
"if",
"key",
"<=",
"api_version",
":",
"return",
"options",
"[",
"key",
"]",
"[",
"0",
"]",
",",
"key",
"raise",
"NoResourceJSONFound",
"(",
"\"No compatible JSON could be loaded for {0} ({1}).\"",
".",
"format",
"(",
"service_name",
",",
"api_version",
")",
")"
] | Given a collection of possible service options, selects the best match.
If no API version is provided, the path to the most recent API version
will be returned. If an API version is provided & there is an exact
match, the path to that version will be returned. If there is no exact
match, an attempt will be made to find a compatible (earlier) version.
In all cases, user-created files (if present) will be given preference
over the default included versions.
:param options: A dictionary of options. See
``.get_available_options(...)``.
:type options: dict
:param service_name: The name of the desired service
:type service_name: string
:param api_version: (Optional) The desired API version to load
:type service_name: string
:returns: The full path to the best matching JSON file | [
"Given",
"a",
"collection",
"of",
"possible",
"service",
"options",
"selects",
"the",
"best",
"match",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/loader.py#L106-L158 |
250,997 | mbodenhamer/syn.utils | syn/utils/cmdargs/args.py | render_args | def render_args(arglst, argdct):
'''Render arguments for command-line invocation.
arglst: A list of Argument objects (specifies order)
argdct: A mapping of argument names to values (specifies rendered values)
'''
out = ''
for arg in arglst:
if arg.name in argdct:
rendered = arg.render(argdct[arg.name])
if rendered:
out += ' '
out += rendered
return out | python | def render_args(arglst, argdct):
'''Render arguments for command-line invocation.
arglst: A list of Argument objects (specifies order)
argdct: A mapping of argument names to values (specifies rendered values)
'''
out = ''
for arg in arglst:
if arg.name in argdct:
rendered = arg.render(argdct[arg.name])
if rendered:
out += ' '
out += rendered
return out | [
"def",
"render_args",
"(",
"arglst",
",",
"argdct",
")",
":",
"out",
"=",
"''",
"for",
"arg",
"in",
"arglst",
":",
"if",
"arg",
".",
"name",
"in",
"argdct",
":",
"rendered",
"=",
"arg",
".",
"render",
"(",
"argdct",
"[",
"arg",
".",
"name",
"]",
")",
"if",
"rendered",
":",
"out",
"+=",
"' '",
"out",
"+=",
"rendered",
"return",
"out"
] | Render arguments for command-line invocation.
arglst: A list of Argument objects (specifies order)
argdct: A mapping of argument names to values (specifies rendered values) | [
"Render",
"arguments",
"for",
"command",
"-",
"line",
"invocation",
"."
] | 82b0dfa27d08858e802a166a44870db10a02a964 | https://github.com/mbodenhamer/syn.utils/blob/82b0dfa27d08858e802a166a44870db10a02a964/syn/utils/cmdargs/args.py#L155-L170 |
250,998 | jut-io/jut-python-tools | jut/api/integrations.py | get_webhook_url | def get_webhook_url(deployment_name,
space='default',
data_source='webhook',
token_manager=None,
app_url=defaults.APP_URL,
**fields):
"""
return the webhook URL for posting webhook data to
"""
import_url = data_engine.get_import_data_url(deployment_name,
app_url=app_url,
token_manager=token_manager)
api_key = deployments.get_apikey(deployment_name,
token_manager=token_manager,
app_url=app_url)
fields_string = '&'.join(['%s=%s' % (key, value)
for (key, value) in fields.items()])
return '%s/api/v1/import/webhook/?space=%s&data_source=%sk&apikey=%s&%s' % \
(import_url, space, data_source, api_key, fields_string) | python | def get_webhook_url(deployment_name,
space='default',
data_source='webhook',
token_manager=None,
app_url=defaults.APP_URL,
**fields):
"""
return the webhook URL for posting webhook data to
"""
import_url = data_engine.get_import_data_url(deployment_name,
app_url=app_url,
token_manager=token_manager)
api_key = deployments.get_apikey(deployment_name,
token_manager=token_manager,
app_url=app_url)
fields_string = '&'.join(['%s=%s' % (key, value)
for (key, value) in fields.items()])
return '%s/api/v1/import/webhook/?space=%s&data_source=%sk&apikey=%s&%s' % \
(import_url, space, data_source, api_key, fields_string) | [
"def",
"get_webhook_url",
"(",
"deployment_name",
",",
"space",
"=",
"'default'",
",",
"data_source",
"=",
"'webhook'",
",",
"token_manager",
"=",
"None",
",",
"app_url",
"=",
"defaults",
".",
"APP_URL",
",",
"*",
"*",
"fields",
")",
":",
"import_url",
"=",
"data_engine",
".",
"get_import_data_url",
"(",
"deployment_name",
",",
"app_url",
"=",
"app_url",
",",
"token_manager",
"=",
"token_manager",
")",
"api_key",
"=",
"deployments",
".",
"get_apikey",
"(",
"deployment_name",
",",
"token_manager",
"=",
"token_manager",
",",
"app_url",
"=",
"app_url",
")",
"fields_string",
"=",
"'&'",
".",
"join",
"(",
"[",
"'%s=%s'",
"%",
"(",
"key",
",",
"value",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"fields",
".",
"items",
"(",
")",
"]",
")",
"return",
"'%s/api/v1/import/webhook/?space=%s&data_source=%sk&apikey=%s&%s'",
"%",
"(",
"import_url",
",",
"space",
",",
"data_source",
",",
"api_key",
",",
"fields_string",
")"
] | return the webhook URL for posting webhook data to | [
"return",
"the",
"webhook",
"URL",
"for",
"posting",
"webhook",
"data",
"to"
] | 65574d23f51a7bbced9bb25010d02da5ca5d906f | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/api/integrations.py#L11-L33 |
250,999 | knagra/farnsworth | farnswiki/templatetags/truncatehtml.py | truncatehtml | def truncatehtml(string, length, ellipsis='...'):
"""Truncate HTML string, preserving tag structure and character entities."""
length = int(length)
output_length = 0
i = 0
pending_close_tags = {}
while output_length < length and i < len(string):
c = string[i]
if c == '<':
# probably some kind of tag
if i in pending_close_tags:
# just pop and skip if it's closing tag we already knew about
i += len(pending_close_tags.pop(i))
else:
# else maybe add tag
i += 1
match = tag_end_re.match(string[i:])
if match:
tag = match.groups()[0]
i += match.end()
# save the end tag for possible later use if there is one
match = re.search(r'(</' + tag + '[^>]*>)', string[i:], re.IGNORECASE)
if match:
pending_close_tags[i + match.start()] = match.groups()[0]
else:
output_length += 1 # some kind of garbage, but count it in
elif c == '&':
# possible character entity, we need to skip it
i += 1
match = entity_end_re.match(string[i:])
if match:
i += match.end()
# this is either a weird character or just '&', both count as 1
output_length += 1
else:
# plain old characters
skip_to = string.find('<', i, i + length)
if skip_to == -1:
skip_to = string.find('&', i, i + length)
if skip_to == -1:
skip_to = i + length
# clamp
delta = min(skip_to - i,
length - output_length,
len(string) - i)
output_length += delta
i += delta
output = [string[:i]]
if output_length == length:
output.append(ellipsis)
for k in sorted(pending_close_tags.keys()):
output.append(pending_close_tags[k])
return "".join(output) | python | def truncatehtml(string, length, ellipsis='...'):
"""Truncate HTML string, preserving tag structure and character entities."""
length = int(length)
output_length = 0
i = 0
pending_close_tags = {}
while output_length < length and i < len(string):
c = string[i]
if c == '<':
# probably some kind of tag
if i in pending_close_tags:
# just pop and skip if it's closing tag we already knew about
i += len(pending_close_tags.pop(i))
else:
# else maybe add tag
i += 1
match = tag_end_re.match(string[i:])
if match:
tag = match.groups()[0]
i += match.end()
# save the end tag for possible later use if there is one
match = re.search(r'(</' + tag + '[^>]*>)', string[i:], re.IGNORECASE)
if match:
pending_close_tags[i + match.start()] = match.groups()[0]
else:
output_length += 1 # some kind of garbage, but count it in
elif c == '&':
# possible character entity, we need to skip it
i += 1
match = entity_end_re.match(string[i:])
if match:
i += match.end()
# this is either a weird character or just '&', both count as 1
output_length += 1
else:
# plain old characters
skip_to = string.find('<', i, i + length)
if skip_to == -1:
skip_to = string.find('&', i, i + length)
if skip_to == -1:
skip_to = i + length
# clamp
delta = min(skip_to - i,
length - output_length,
len(string) - i)
output_length += delta
i += delta
output = [string[:i]]
if output_length == length:
output.append(ellipsis)
for k in sorted(pending_close_tags.keys()):
output.append(pending_close_tags[k])
return "".join(output) | [
"def",
"truncatehtml",
"(",
"string",
",",
"length",
",",
"ellipsis",
"=",
"'...'",
")",
":",
"length",
"=",
"int",
"(",
"length",
")",
"output_length",
"=",
"0",
"i",
"=",
"0",
"pending_close_tags",
"=",
"{",
"}",
"while",
"output_length",
"<",
"length",
"and",
"i",
"<",
"len",
"(",
"string",
")",
":",
"c",
"=",
"string",
"[",
"i",
"]",
"if",
"c",
"==",
"'<'",
":",
"# probably some kind of tag",
"if",
"i",
"in",
"pending_close_tags",
":",
"# just pop and skip if it's closing tag we already knew about",
"i",
"+=",
"len",
"(",
"pending_close_tags",
".",
"pop",
"(",
"i",
")",
")",
"else",
":",
"# else maybe add tag",
"i",
"+=",
"1",
"match",
"=",
"tag_end_re",
".",
"match",
"(",
"string",
"[",
"i",
":",
"]",
")",
"if",
"match",
":",
"tag",
"=",
"match",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"i",
"+=",
"match",
".",
"end",
"(",
")",
"# save the end tag for possible later use if there is one",
"match",
"=",
"re",
".",
"search",
"(",
"r'(</'",
"+",
"tag",
"+",
"'[^>]*>)'",
",",
"string",
"[",
"i",
":",
"]",
",",
"re",
".",
"IGNORECASE",
")",
"if",
"match",
":",
"pending_close_tags",
"[",
"i",
"+",
"match",
".",
"start",
"(",
")",
"]",
"=",
"match",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"else",
":",
"output_length",
"+=",
"1",
"# some kind of garbage, but count it in",
"elif",
"c",
"==",
"'&'",
":",
"# possible character entity, we need to skip it",
"i",
"+=",
"1",
"match",
"=",
"entity_end_re",
".",
"match",
"(",
"string",
"[",
"i",
":",
"]",
")",
"if",
"match",
":",
"i",
"+=",
"match",
".",
"end",
"(",
")",
"# this is either a weird character or just '&', both count as 1",
"output_length",
"+=",
"1",
"else",
":",
"# plain old characters",
"skip_to",
"=",
"string",
".",
"find",
"(",
"'<'",
",",
"i",
",",
"i",
"+",
"length",
")",
"if",
"skip_to",
"==",
"-",
"1",
":",
"skip_to",
"=",
"string",
".",
"find",
"(",
"'&'",
",",
"i",
",",
"i",
"+",
"length",
")",
"if",
"skip_to",
"==",
"-",
"1",
":",
"skip_to",
"=",
"i",
"+",
"length",
"# clamp",
"delta",
"=",
"min",
"(",
"skip_to",
"-",
"i",
",",
"length",
"-",
"output_length",
",",
"len",
"(",
"string",
")",
"-",
"i",
")",
"output_length",
"+=",
"delta",
"i",
"+=",
"delta",
"output",
"=",
"[",
"string",
"[",
":",
"i",
"]",
"]",
"if",
"output_length",
"==",
"length",
":",
"output",
".",
"append",
"(",
"ellipsis",
")",
"for",
"k",
"in",
"sorted",
"(",
"pending_close_tags",
".",
"keys",
"(",
")",
")",
":",
"output",
".",
"append",
"(",
"pending_close_tags",
"[",
"k",
"]",
")",
"return",
"\"\"",
".",
"join",
"(",
"output",
")"
] | Truncate HTML string, preserving tag structure and character entities. | [
"Truncate",
"HTML",
"string",
"preserving",
"tag",
"structure",
"and",
"character",
"entities",
"."
] | 1b6589f0d9fea154f0a1e2231ed906764ed26d26 | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/farnswiki/templatetags/truncatehtml.py#L12-L75 |
Subsets and Splits