repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
jeffrimko/Qprompt
lib/qprompt.py
ask_yesno
def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+n...
python
def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+n...
[ "def", "ask_yesno", "(", "msg", "=", "\"Proceed?\"", ",", "dft", "=", "None", ")", ":", "yes", "=", "[", "\"y\"", ",", "\"yes\"", ",", "\"Y\"", ",", "\"YES\"", "]", "no", "=", "[", "\"n\"", ",", "\"no\"", ",", "\"N\"", ",", "\"NO\"", "]", "if", "...
Prompts the user for a yes or no answer. Returns True for yes, False for no.
[ "Prompts", "the", "user", "for", "a", "yes", "or", "no", "answer", ".", "Returns", "True", "for", "yes", "False", "for", "no", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L519-L526
jeffrimko/Qprompt
lib/qprompt.py
ask_int
def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp)
python
def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp)
[ "def", "ask_int", "(", "msg", "=", "\"Enter an integer\"", ",", "dft", "=", "None", ",", "vld", "=", "None", ",", "hlp", "=", "None", ")", ":", "vld", "=", "vld", "or", "[", "int", "]", "return", "ask", "(", "msg", ",", "dft", "=", "dft", ",", ...
Prompts the user for an integer.
[ "Prompts", "the", "user", "for", "an", "integer", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L529-L532
jeffrimko/Qprompt
lib/qprompt.py
ask_float
def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp)
python
def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp)
[ "def", "ask_float", "(", "msg", "=", "\"Enter a float\"", ",", "dft", "=", "None", ",", "vld", "=", "None", ",", "hlp", "=", "None", ")", ":", "vld", "=", "vld", "or", "[", "float", "]", "return", "ask", "(", "msg", ",", "dft", "=", "dft", ",", ...
Prompts the user for a float.
[ "Prompts", "the", "user", "for", "a", "float", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L535-L538
jeffrimko/Qprompt
lib/qprompt.py
ask_str
def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp)
python
def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp)
[ "def", "ask_str", "(", "msg", "=", "\"Enter a string\"", ",", "dft", "=", "None", ",", "vld", "=", "None", ",", "shw", "=", "True", ",", "blk", "=", "True", ",", "hlp", "=", "None", ")", ":", "vld", "=", "vld", "or", "[", "str", "]", "return", ...
Prompts the user for a string.
[ "Prompts", "the", "user", "for", "a", "string", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L541-L544
jeffrimko/Qprompt
lib/qprompt.py
ask_captcha
def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False)
python
def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False)
[ "def", "ask_captcha", "(", "length", "=", "4", ")", ":", "captcha", "=", "\"\"", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_lowercase", ")", "for", "_", "in", "range", "(", "length", ")", ")", "ask_str", "(", "'Enter the foll...
Prompts the user for a random string.
[ "Prompts", "the", "user", "for", "a", "random", "string", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L549-L552
jeffrimko/Qprompt
lib/qprompt.py
clear
def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True)
python
def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True)
[ "def", "clear", "(", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "call", "(", "\"cls\"", ",", "shell", "=", "True", ")", "else", ":", "call", "(", "\"clear\"", ",", "shell", "=", "True", ")" ]
Clears the console.
[ "Clears", "the", "console", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L558-L563
jeffrimko/Qprompt
lib/qprompt.py
status
def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: ...
python
def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: ...
[ "def", "status", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "decor", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "krgs", ")", ":", "echo", "(", "\"[!] \"", "+", "m...
Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to prin...
[ "Prints", "a", "status", "message", "at", "the", "start", "and", "finish", "of", "an", "associated", "function", ".", "Can", "be", "used", "as", "a", "function", "decorator", "or", "as", "a", "function", "that", "accepts", "another", "function", "as", "the...
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L565-L616
jeffrimko/Qprompt
lib/qprompt.py
fatal
def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FA...
python
def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FA...
[ "def", "fatal", "(", "msg", ",", "exitcode", "=", "1", ",", "*", "*", "kwargs", ")", ":", "# NOTE: Can't use normal arg named `pause` since function has same name.", "pause_before_exit", "=", "kwargs", ".", "pop", "(", "\"pause\"", ")", "if", "\"pause\"", "in", "k...
Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.
[ "Prints", "a", "message", "then", "exits", "the", "program", ".", "Optionally", "pause", "before", "exit", "with", "pause", "=", "True", "kwarg", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L618-L626
jeffrimko/Qprompt
lib/qprompt.py
hrule
def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width))
python
def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width))
[ "def", "hrule", "(", "width", "=", "None", ",", "char", "=", "None", ")", ":", "width", "=", "width", "or", "HRWIDTH", "char", "=", "char", "or", "HRCHAR", "return", "echo", "(", "getline", "(", "char", ",", "width", ")", ")" ]
Outputs or returns a horizontal line of the given character and width. Returns printed string.
[ "Outputs", "or", "returns", "a", "horizontal", "line", "of", "the", "given", "character", "and", "width", ".", "Returns", "printed", "string", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L644-L649
jeffrimko/Qprompt
lib/qprompt.py
title
def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))
python
def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))
[ "def", "title", "(", "msg", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "ctypes", ".", "windll", ".", "kernel32", ".", "SetConsoleTitleW", "(", "tounicode", "(", "msg", ")", ")" ]
Sets the title of the console window.
[ "Sets", "the", "title", "of", "the", "console", "window", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L651-L654
jeffrimko/Qprompt
lib/qprompt.py
wrap
def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. "...
python
def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. "...
[ "def", "wrap", "(", "item", ",", "args", "=", "None", ",", "krgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "with", "Wrap", "(", "*", "*", "kwargs", ")", ":", "if", "callable", "(", "item", ")", ":", "args", "=", "args", "or", "[", "]"...
Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item.
[ "Wraps", "the", "given", "item", "content", "between", "horizontal", "lines", ".", "Item", "can", "be", "a", "string", "or", "a", "function", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L657-L672
jeffrimko/Qprompt
lib/qprompt.py
_guess_name
def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue ...
python
def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue ...
[ "def", "_guess_name", "(", "desc", ",", "taken", "=", "None", ")", ":", "taken", "=", "taken", "or", "[", "]", "name", "=", "\"\"", "# Try to find the shortest name based on the given description.", "for", "word", "in", "desc", ".", "split", "(", ")", ":", "...
Attempts to guess the menu entry name from the function name.
[ "Attempts", "to", "guess", "the", "menu", "entry", "name", "from", "the", "function", "name", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L674-L691
jeffrimko/Qprompt
lib/qprompt.py
Menu.add
def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
python
def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
[ "def", "add", "(", "self", ",", "name", ",", "desc", ",", "func", "=", "None", ",", "args", "=", "None", ",", "krgs", "=", "None", ")", ":", "self", ".", "entries", ".", "append", "(", "MenuEntry", "(", "name", ",", "desc", ",", "func", ",", "a...
Add a menu entry.
[ "Add", "a", "menu", "entry", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L141-L143
jeffrimko/Qprompt
lib/qprompt.py
Menu.enum
def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
python
def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
[ "def", "enum", "(", "self", ",", "desc", ",", "func", "=", "None", ",", "args", "=", "None", ",", "krgs", "=", "None", ")", ":", "name", "=", "str", "(", "len", "(", "self", ".", "entries", ")", "+", "1", ")", "self", ".", "entries", ".", "ap...
Add a menu entry whose name will be an auto indexed number.
[ "Add", "a", "menu", "entry", "whose", "name", "will", "be", "an", "auto", "indexed", "number", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L144-L147
jeffrimko/Qprompt
lib/qprompt.py
Menu.show
def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs)
python
def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs)
[ "def", "show", "(", "self", ",", "*", "*", "kwargs", ")", ":", "show_kwargs", "=", "copy", ".", "deepcopy", "(", "self", ".", "_show_kwargs", ")", "show_kwargs", ".", "update", "(", "kwargs", ")", "return", "show_menu", "(", "self", ".", "entries", ","...
Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.
[ "Shows", "the", "menu", ".", "Any", "kwargs", "supplied", "will", "be", "passed", "to", "show_menu", "()", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L148-L153
jeffrimko/Qprompt
lib/qprompt.py
Menu.run
def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break
python
def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break
[ "def", "run", "(", "self", ",", "name", ")", ":", "for", "entry", "in", "self", ".", "entries", ":", "if", "entry", ".", "name", "==", "name", ":", "run_func", "(", "entry", ")", "break" ]
Runs the function associated with the given entry `name`.
[ "Runs", "the", "function", "associated", "with", "the", "given", "entry", "name", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L154-L159
jeffrimko/Qprompt
lib/qprompt.py
Menu.main
def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provide...
python
def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provide...
[ "def", "main", "(", "self", ",", "auto", "=", "None", ",", "loop", "=", "False", ",", "quit", "=", "(", "\"q\"", ",", "\"Quit\"", ")", ",", "*", "*", "kwargs", ")", ":", "def", "_main", "(", ")", ":", "global", "_AUTO", "if", "quit", ":", "if",...
Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. ...
[ "Runs", "the", "standard", "menu", "main", "logic", ".", "Any", "kwargs", "supplied", "will", "be", "pass", "to", "Menu", ".", "show", "()", ".", "If", "argv", "is", "provided", "to", "the", "script", "it", "will", "be", "used", "as", "the", "auto", ...
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L160-L199
ucsb-cs-education/hairball
hairball/plugins/initialization.py
partition_scripts
def partition_scripts(scripts, start_type1, start_type2): """Return two lists of scripts out of the original `scripts` list. Scripts that begin with a `start_type1` or `start_type2` blocks are returned first. All other scripts are returned second. """ match, other = [], [] for script in scrip...
python
def partition_scripts(scripts, start_type1, start_type2): """Return two lists of scripts out of the original `scripts` list. Scripts that begin with a `start_type1` or `start_type2` blocks are returned first. All other scripts are returned second. """ match, other = [], [] for script in scrip...
[ "def", "partition_scripts", "(", "scripts", ",", "start_type1", ",", "start_type2", ")", ":", "match", ",", "other", "=", "[", "]", ",", "[", "]", "for", "script", "in", "scripts", ":", "if", "(", "HairballPlugin", ".", "script_start_type", "(", "script", ...
Return two lists of scripts out of the original `scripts` list. Scripts that begin with a `start_type1` or `start_type2` blocks are returned first. All other scripts are returned second.
[ "Return", "two", "lists", "of", "scripts", "out", "of", "the", "original", "scripts", "list", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L7-L21
ucsb-cs-education/hairball
hairball/plugins/initialization.py
AttributeInitialization.attribute_result
def attribute_result(cls, sprites): """Return mapping of attributes to if they were initialized or not.""" retval = dict((x, True) for x in cls.ATTRIBUTES) for properties in sprites.values(): for attribute, state in properties.items(): retval[attribute] &= state != cl...
python
def attribute_result(cls, sprites): """Return mapping of attributes to if they were initialized or not.""" retval = dict((x, True) for x in cls.ATTRIBUTES) for properties in sprites.values(): for attribute, state in properties.items(): retval[attribute] &= state != cl...
[ "def", "attribute_result", "(", "cls", ",", "sprites", ")", ":", "retval", "=", "dict", "(", "(", "x", ",", "True", ")", "for", "x", "in", "cls", ".", "ATTRIBUTES", ")", "for", "properties", "in", "sprites", ".", "values", "(", ")", ":", "for", "at...
Return mapping of attributes to if they were initialized or not.
[ "Return", "mapping", "of", "attributes", "to", "if", "they", "were", "initialized", "or", "not", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L36-L42
ucsb-cs-education/hairball
hairball/plugins/initialization.py
AttributeInitialization.attribute_state
def attribute_state(cls, scripts, attribute): """Return the state of the scripts for the given attribute. If there is more than one 'when green flag clicked' script and they both modify the attribute, then the attribute is considered to not be initialized. """ green_fla...
python
def attribute_state(cls, scripts, attribute): """Return the state of the scripts for the given attribute. If there is more than one 'when green flag clicked' script and they both modify the attribute, then the attribute is considered to not be initialized. """ green_fla...
[ "def", "attribute_state", "(", "cls", ",", "scripts", ",", "attribute", ")", ":", "green_flag", ",", "other", "=", "partition_scripts", "(", "scripts", ",", "cls", ".", "HAT_GREEN_FLAG", ",", "cls", ".", "HAT_CLONE", ")", "block_set", "=", "cls", ".", "BLO...
Return the state of the scripts for the given attribute. If there is more than one 'when green flag clicked' script and they both modify the attribute, then the attribute is considered to not be initialized.
[ "Return", "the", "state", "of", "the", "scripts", "for", "the", "given", "attribute", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L45-L86
ucsb-cs-education/hairball
hairball/plugins/initialization.py
AttributeInitialization.output_results
def output_results(cls, sprites): """Output whether or not each attribute was correctly initialized. Attributes that were not modified at all are considered to be properly initialized. """ print(' '.join(cls.ATTRIBUTES)) format_strs = ['{{{}!s:^{}}}'.format(x, len(x)) f...
python
def output_results(cls, sprites): """Output whether or not each attribute was correctly initialized. Attributes that were not modified at all are considered to be properly initialized. """ print(' '.join(cls.ATTRIBUTES)) format_strs = ['{{{}!s:^{}}}'.format(x, len(x)) f...
[ "def", "output_results", "(", "cls", ",", "sprites", ")", ":", "print", "(", "' '", ".", "join", "(", "cls", ".", "ATTRIBUTES", ")", ")", "format_strs", "=", "[", "'{{{}!s:^{}}}'", ".", "format", "(", "x", ",", "len", "(", "x", ")", ")", "for", "x"...
Output whether or not each attribute was correctly initialized. Attributes that were not modified at all are considered to be properly initialized.
[ "Output", "whether", "or", "not", "each", "attribute", "was", "correctly", "initialized", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L89-L99
ucsb-cs-education/hairball
hairball/plugins/initialization.py
AttributeInitialization.sprite_changes
def sprite_changes(cls, sprite): """Return a mapping of attributes to their initilization state.""" retval = dict((x, cls.attribute_state(sprite.scripts, x)) for x in (x for x in cls.ATTRIBUTES if x != 'background')) return retval
python
def sprite_changes(cls, sprite): """Return a mapping of attributes to their initilization state.""" retval = dict((x, cls.attribute_state(sprite.scripts, x)) for x in (x for x in cls.ATTRIBUTES if x != 'background')) return retval
[ "def", "sprite_changes", "(", "cls", ",", "sprite", ")", ":", "retval", "=", "dict", "(", "(", "x", ",", "cls", ".", "attribute_state", "(", "sprite", ".", "scripts", ",", "x", ")", ")", "for", "x", "in", "(", "x", "for", "x", "in", "cls", ".", ...
Return a mapping of attributes to their initilization state.
[ "Return", "a", "mapping", "of", "attributes", "to", "their", "initilization", "state", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L102-L106
ucsb-cs-education/hairball
hairball/plugins/initialization.py
AttributeInitialization.analyze
def analyze(self, scratch, **kwargs): """Run and return the results of the AttributeInitialization plugin.""" changes = dict((x.name, self.sprite_changes(x)) for x in scratch.sprites) changes['stage'] = { 'background': self.attribute_state(scratch.stage.scripts...
python
def analyze(self, scratch, **kwargs): """Run and return the results of the AttributeInitialization plugin.""" changes = dict((x.name, self.sprite_changes(x)) for x in scratch.sprites) changes['stage'] = { 'background': self.attribute_state(scratch.stage.scripts...
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "changes", "=", "dict", "(", "(", "x", ".", "name", ",", "self", ".", "sprite_changes", "(", "x", ")", ")", "for", "x", "in", "scratch", ".", "sprites", ")", "chang...
Run and return the results of the AttributeInitialization plugin.
[ "Run", "and", "return", "the", "results", "of", "the", "AttributeInitialization", "plugin", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L108-L116
ucsb-cs-education/hairball
hairball/plugins/initialization.py
VariableInitialization.variable_state
def variable_state(cls, scripts, variables): """Return the initialization state for each variable in variables. The state is determined based on the scripts passed in via the scripts parameter. If there is more than one 'when green flag clicked' script and they both modify the ...
python
def variable_state(cls, scripts, variables): """Return the initialization state for each variable in variables. The state is determined based on the scripts passed in via the scripts parameter. If there is more than one 'when green flag clicked' script and they both modify the ...
[ "def", "variable_state", "(", "cls", ",", "scripts", ",", "variables", ")", ":", "def", "conditionally_set_not_modified", "(", ")", ":", "\"\"\"Set the variable to modified if it hasn't been altered.\"\"\"", "state", "=", "variables", ".", "get", "(", "block", ".", "a...
Return the initialization state for each variable in variables. The state is determined based on the scripts passed in via the scripts parameter. If there is more than one 'when green flag clicked' script and they both modify the attribute, then the attribute is considered to not be ...
[ "Return", "the", "initialization", "state", "for", "each", "variable", "in", "variables", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L128-L175
ucsb-cs-education/hairball
hairball/plugins/initialization.py
VariableInitialization.analyze
def analyze(self, scratch, **kwargs): """Run and return the results of the VariableInitialization plugin.""" variables = dict((x, self.variable_state(x.scripts, x.variables)) for x in scratch.sprites) variables['global'] = self.variable_state(self.iter_scripts(scratch), ...
python
def analyze(self, scratch, **kwargs): """Run and return the results of the VariableInitialization plugin.""" variables = dict((x, self.variable_state(x.scripts, x.variables)) for x in scratch.sprites) variables['global'] = self.variable_state(self.iter_scripts(scratch), ...
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "variables", "=", "dict", "(", "(", "x", ",", "self", ".", "variable_state", "(", "x", ".", "scripts", ",", "x", ".", "variables", ")", ")", "for", "x", "in", "scra...
Run and return the results of the VariableInitialization plugin.
[ "Run", "and", "return", "the", "results", "of", "the", "VariableInitialization", "plugin", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L177-L186
ucsb-cs-education/hairball
hairball/plugins/convention.py
SpriteNaming.finalize
def finalize(self): """Output the default sprite names found in the project.""" print('{} default sprite names found:'.format(self.total_default)) for name in self.list_default: print(name)
python
def finalize(self): """Output the default sprite names found in the project.""" print('{} default sprite names found:'.format(self.total_default)) for name in self.list_default: print(name)
[ "def", "finalize", "(", "self", ")", ":", "print", "(", "'{} default sprite names found:'", ".", "format", "(", "self", ".", "total_default", ")", ")", "for", "name", "in", "self", ".", "list_default", ":", "print", "(", "name", ")" ]
Output the default sprite names found in the project.
[ "Output", "the", "default", "sprite", "names", "found", "in", "the", "project", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/convention.py#L22-L26
ucsb-cs-education/hairball
hairball/plugins/convention.py
SpriteNaming.analyze
def analyze(self, scratch, **kwargs): """Run and return the results from the SpriteNaming plugin.""" for sprite in self.iter_sprites(scratch): for default in self.default_names: if default in sprite.name: self.total_default += 1 self.li...
python
def analyze(self, scratch, **kwargs): """Run and return the results from the SpriteNaming plugin.""" for sprite in self.iter_sprites(scratch): for default in self.default_names: if default in sprite.name: self.total_default += 1 self.li...
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "for", "sprite", "in", "self", ".", "iter_sprites", "(", "scratch", ")", ":", "for", "default", "in", "self", ".", "default_names", ":", "if", "default", "in", "sprite", ...
Run and return the results from the SpriteNaming plugin.
[ "Run", "and", "return", "the", "results", "from", "the", "SpriteNaming", "plugin", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/convention.py#L28-L34
ramses-tech/nefertari
nefertari/tweens.py
get_tunneling
def get_tunneling(handler, registry): """ Allows all methods to be tunneled via GET for dev/debuging purposes. """ log.info('get_tunneling enabled') def get_tunneling(request): if request.method == 'GET': method = request.GET.pop('_m', 'GET') request.method = method ...
python
def get_tunneling(handler, registry): """ Allows all methods to be tunneled via GET for dev/debuging purposes. """ log.info('get_tunneling enabled') def get_tunneling(request): if request.method == 'GET': method = request.GET.pop('_m', 'GET') request.method = method ...
[ "def", "get_tunneling", "(", "handler", ",", "registry", ")", ":", "log", ".", "info", "(", "'get_tunneling enabled'", ")", "def", "get_tunneling", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'GET'", ":", "method", "=", "request", ".",...
Allows all methods to be tunneled via GET for dev/debuging purposes.
[ "Allows", "all", "methods", "to", "be", "tunneled", "via", "GET", "for", "dev", "/", "debuging", "purposes", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/tweens.py#L34-L54
ramses-tech/nefertari
nefertari/tweens.py
enable_selfalias
def enable_selfalias(config, id_name): """ This allows replacing id_name with "self". e.g. /users/joe/account == /users/self/account if joe is in the session as an authorized user """ def context_found_subscriber(event): request = event.request user = getattr(request, 'user', No...
python
def enable_selfalias(config, id_name): """ This allows replacing id_name with "self". e.g. /users/joe/account == /users/self/account if joe is in the session as an authorized user """ def context_found_subscriber(event): request = event.request user = getattr(request, 'user', No...
[ "def", "enable_selfalias", "(", "config", ",", "id_name", ")", ":", "def", "context_found_subscriber", "(", "event", ")", ":", "request", "=", "event", ".", "request", "user", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "if", "(", "r...
This allows replacing id_name with "self". e.g. /users/joe/account == /users/self/account if joe is in the session as an authorized user
[ "This", "allows", "replacing", "id_name", "with", "self", ".", "e", ".", "g", ".", "/", "users", "/", "joe", "/", "account", "==", "/", "users", "/", "self", "/", "account", "if", "joe", "is", "in", "the", "session", "as", "an", "authorized", "user" ...
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/tweens.py#L136-L151
ramses-tech/nefertari
nefertari/view.py
BaseView.convert_dotted
def convert_dotted(params): """ Convert dotted keys in :params: dictset to a nested dictset. E.g. {'settings.foo': 'bar'} -> {'settings': {'foo': 'bar'}} """ if not isinstance(params, dictset): params = dictset(params) dotted_items = {k: v for k, v in params.items()...
python
def convert_dotted(params): """ Convert dotted keys in :params: dictset to a nested dictset. E.g. {'settings.foo': 'bar'} -> {'settings': {'foo': 'bar'}} """ if not isinstance(params, dictset): params = dictset(params) dotted_items = {k: v for k, v in params.items()...
[ "def", "convert_dotted", "(", "params", ")", ":", "if", "not", "isinstance", "(", "params", ",", "dictset", ")", ":", "params", "=", "dictset", "(", "params", ")", "dotted_items", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "params", ".", ...
Convert dotted keys in :params: dictset to a nested dictset. E.g. {'settings.foo': 'bar'} -> {'settings': {'foo': 'bar'}}
[ "Convert", "dotted", "keys", "in", ":", "params", ":", "dictset", "to", "a", "nested", "dictset", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view.py#L79-L95
ramses-tech/nefertari
nefertari/view.py
BaseView.prepare_request_params
def prepare_request_params(self, _query_params, _json_params): """ Prepare query and update params. """ self._query_params = dictset( _query_params or self.request.params.mixed()) self._json_params = dictset(_json_params) ctype = self.request.content_type if self.req...
python
def prepare_request_params(self, _query_params, _json_params): """ Prepare query and update params. """ self._query_params = dictset( _query_params or self.request.params.mixed()) self._json_params = dictset(_json_params) ctype = self.request.content_type if self.req...
[ "def", "prepare_request_params", "(", "self", ",", "_query_params", ",", "_json_params", ")", ":", "self", ".", "_query_params", "=", "dictset", "(", "_query_params", "or", "self", ".", "request", ".", "params", ".", "mixed", "(", ")", ")", "self", ".", "_...
Prepare query and update params.
[ "Prepare", "query", "and", "update", "params", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view.py#L136-L158
ramses-tech/nefertari
nefertari/view.py
BaseView.set_override_rendered
def set_override_rendered(self): """ Set self.request.override_renderer if needed. """ if '' in self.request.accept: self.request.override_renderer = self._default_renderer elif 'application/json' in self.request.accept: self.request.override_renderer = 'nefertari_json' ...
python
def set_override_rendered(self): """ Set self.request.override_renderer if needed. """ if '' in self.request.accept: self.request.override_renderer = self._default_renderer elif 'application/json' in self.request.accept: self.request.override_renderer = 'nefertari_json' ...
[ "def", "set_override_rendered", "(", "self", ")", ":", "if", "''", "in", "self", ".", "request", ".", "accept", ":", "self", ".", "request", ".", "override_renderer", "=", "self", ".", "_default_renderer", "elif", "'application/json'", "in", "self", ".", "re...
Set self.request.override_renderer if needed.
[ "Set", "self", ".", "request", ".", "override_renderer", "if", "needed", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view.py#L160-L167
ramses-tech/nefertari
nefertari/view.py
BaseView._setup_aggregation
def _setup_aggregation(self, aggregator=None): """ Wrap `self.index` method with ESAggregator. This makes `self.index` to first try to run aggregation and only on fail original method is run. Method is wrapped only if it is defined and `elasticsearch.enable_aggregations` setting is true...
python
def _setup_aggregation(self, aggregator=None): """ Wrap `self.index` method with ESAggregator. This makes `self.index` to first try to run aggregation and only on fail original method is run. Method is wrapped only if it is defined and `elasticsearch.enable_aggregations` setting is true...
[ "def", "_setup_aggregation", "(", "self", ",", "aggregator", "=", "None", ")", ":", "from", "nefertari", ".", "elasticsearch", "import", "ES", "if", "aggregator", "is", "None", ":", "aggregator", "=", "ESAggregator", "aggregations_enabled", "=", "(", "ES", "."...
Wrap `self.index` method with ESAggregator. This makes `self.index` to first try to run aggregation and only on fail original method is run. Method is wrapped only if it is defined and `elasticsearch.enable_aggregations` setting is true.
[ "Wrap", "self", ".", "index", "method", "with", "ESAggregator", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view.py#L169-L188
ramses-tech/nefertari
nefertari/view.py
BaseView.get_collection_es
def get_collection_es(self): """ Query ES collection and return results. This is default implementation of querying ES collection with `self._query_params`. It must return found ES collection results for default response renderers to work properly. """ from nefertari.ela...
python
def get_collection_es(self): """ Query ES collection and return results. This is default implementation of querying ES collection with `self._query_params`. It must return found ES collection results for default response renderers to work properly. """ from nefertari.ela...
[ "def", "get_collection_es", "(", "self", ")", ":", "from", "nefertari", ".", "elasticsearch", "import", "ES", "return", "ES", "(", "self", ".", "Model", ".", "__name__", ")", ".", "get_collection", "(", "*", "*", "self", ".", "_query_params", ")" ]
Query ES collection and return results. This is default implementation of querying ES collection with `self._query_params`. It must return found ES collection results for default response renderers to work properly.
[ "Query", "ES", "collection", "and", "return", "results", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view.py#L190-L198
ramses-tech/nefertari
nefertari/view.py
BaseView.fill_null_values
def fill_null_values(self): """ Fill missing model fields in JSON with {key: null value}. Only run for PUT requests. """ if not self.Model: log.info("%s has no model defined" % self.__class__.__name__) return empty_values = self.Model.get_null_values() ...
python
def fill_null_values(self): """ Fill missing model fields in JSON with {key: null value}. Only run for PUT requests. """ if not self.Model: log.info("%s has no model defined" % self.__class__.__name__) return empty_values = self.Model.get_null_values() ...
[ "def", "fill_null_values", "(", "self", ")", ":", "if", "not", "self", ".", "Model", ":", "log", ".", "info", "(", "\"%s has no model defined\"", "%", "self", ".", "__class__", ".", "__name__", ")", "return", "empty_values", "=", "self", ".", "Model", ".",...
Fill missing model fields in JSON with {key: null value}. Only run for PUT requests.
[ "Fill", "missing", "model", "fields", "in", "JSON", "with", "{", "key", ":", "null", "value", "}", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view.py#L200-L212
ramses-tech/nefertari
nefertari/view.py
BaseView.set_public_limits
def set_public_limits(self): """ Set public limits if auth is enabled and user is not authenticated. Also sets default limit for GET, HEAD requests. """ if self.request.method.upper() in ['GET', 'HEAD']: self._query_params.process_int_param('_limit', 20) if s...
python
def set_public_limits(self): """ Set public limits if auth is enabled and user is not authenticated. Also sets default limit for GET, HEAD requests. """ if self.request.method.upper() in ['GET', 'HEAD']: self._query_params.process_int_param('_limit', 20) if s...
[ "def", "set_public_limits", "(", "self", ")", ":", "if", "self", ".", "request", ".", "method", ".", "upper", "(", ")", "in", "[", "'GET'", ",", "'HEAD'", "]", ":", "self", ".", "_query_params", ".", "process_int_param", "(", "'_limit'", ",", "20", ")"...
Set public limits if auth is enabled and user is not authenticated. Also sets default limit for GET, HEAD requests.
[ "Set", "public", "limits", "if", "auth", "is", "enabled", "and", "user", "is", "not", "authenticated", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view.py#L214-L223
ramses-tech/nefertari
nefertari/view.py
BaseView.convert_ids2objects
def convert_ids2objects(self): """ Convert object IDs from `self._json_params` to objects if needed. Only IDs that belong to relationship field of `self.Model` are converted. """ if not self.Model: log.info("%s has no model defined" % self.__class__.__name__) ...
python
def convert_ids2objects(self): """ Convert object IDs from `self._json_params` to objects if needed. Only IDs that belong to relationship field of `self.Model` are converted. """ if not self.Model: log.info("%s has no model defined" % self.__class__.__name__) ...
[ "def", "convert_ids2objects", "(", "self", ")", ":", "if", "not", "self", ".", "Model", ":", "log", ".", "info", "(", "\"%s has no model defined\"", "%", "self", ".", "__class__", ".", "__name__", ")", "return", "for", "field", "in", "self", ".", "_json_pa...
Convert object IDs from `self._json_params` to objects if needed. Only IDs that belong to relationship field of `self.Model` are converted.
[ "Convert", "object", "IDs", "from", "self", ".", "_json_params", "to", "objects", "if", "needed", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view.py#L225-L239
ramses-tech/nefertari
nefertari/view.py
BaseView.setup_default_wrappers
def setup_default_wrappers(self): """ Setup defaulf wrappers. Wrappers are applied when view method does not return instance of Response. In this case nefertari renderers call wrappers and handle response generation. """ # Index self._after_calls['index'] = [ ...
python
def setup_default_wrappers(self): """ Setup defaulf wrappers. Wrappers are applied when view method does not return instance of Response. In this case nefertari renderers call wrappers and handle response generation. """ # Index self._after_calls['index'] = [ ...
[ "def", "setup_default_wrappers", "(", "self", ")", ":", "# Index", "self", ".", "_after_calls", "[", "'index'", "]", "=", "[", "wrappers", ".", "wrap_in_dict", "(", "self", ".", "request", ")", ",", "wrappers", ".", "add_meta", "(", "self", ".", "request",...
Setup defaulf wrappers. Wrappers are applied when view method does not return instance of Response. In this case nefertari renderers call wrappers and handle response generation.
[ "Setup", "defaulf", "wrappers", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view.py#L241-L293
turicas/mongodict
migrate_data.py
migrate_codec
def migrate_codec(config_old, config_new): '''Migrate data from mongodict <= 0.2.1 to 0.3.0 `config_old` and `config_new` should be dictionaries with the keys regarding to MongoDB server: - `host` - `port` - `database` - `collection` ''' assert mongodict.__version__ i...
python
def migrate_codec(config_old, config_new): '''Migrate data from mongodict <= 0.2.1 to 0.3.0 `config_old` and `config_new` should be dictionaries with the keys regarding to MongoDB server: - `host` - `port` - `database` - `collection` ''' assert mongodict.__version__ i...
[ "def", "migrate_codec", "(", "config_old", ",", "config_new", ")", ":", "assert", "mongodict", ".", "__version__", "in", "[", "(", "0", ",", "3", ",", "0", ")", ",", "(", "0", ",", "3", ",", "1", ")", "]", "connection", "=", "pymongo", ".", "Connec...
Migrate data from mongodict <= 0.2.1 to 0.3.0 `config_old` and `config_new` should be dictionaries with the keys regarding to MongoDB server: - `host` - `port` - `database` - `collection`
[ "Migrate", "data", "from", "mongodict", "<", "=", "0", ".", "2", ".", "1", "to", "0", ".", "3", ".", "0", "config_old", "and", "config_new", "should", "be", "dictionaries", "with", "the", "keys", "regarding", "to", "MongoDB", "server", ":", "-", "host"...
train
https://github.com/turicas/mongodict/blob/596211a57f68cc0574eededc5cb2a4be8f9ce098/migrate_data.py#L40-L64
ramses-tech/nefertari
nefertari/utils/data.py
FieldData.from_dict
def from_dict(cls, data, model): """ Generate map of `fieldName: clsInstance` from dict. :param data: Dict where keys are field names and values are new values of field. :param model: Model class to which fields from :data: belong. """ model_provided = model is not N...
python
def from_dict(cls, data, model): """ Generate map of `fieldName: clsInstance` from dict. :param data: Dict where keys are field names and values are new values of field. :param model: Model class to which fields from :data: belong. """ model_provided = model is not N...
[ "def", "from_dict", "(", "cls", ",", "data", ",", "model", ")", ":", "model_provided", "=", "model", "is", "not", "None", "result", "=", "{", "}", "for", "name", ",", "new_value", "in", "data", ".", "items", "(", ")", ":", "kwargs", "=", "{", "'nam...
Generate map of `fieldName: clsInstance` from dict. :param data: Dict where keys are field names and values are new values of field. :param model: Model class to which fields from :data: belong.
[ "Generate", "map", "of", "fieldName", ":", "clsInstance", "from", "dict", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/data.py#L119-L136
ramses-tech/nefertari
nefertari/authentication/views.py
TicketAuthViewMixin.register
def register(self): """ Register new user by POSTing all required data. """ user, created = self.Model.create_account( self._json_params) if not created: raise JHTTPConflict('Looks like you already have an account.') self.request._user = user pk_field = ...
python
def register(self): """ Register new user by POSTing all required data. """ user, created = self.Model.create_account( self._json_params) if not created: raise JHTTPConflict('Looks like you already have an account.') self.request._user = user pk_field = ...
[ "def", "register", "(", "self", ")", ":", "user", ",", "created", "=", "self", ".", "Model", ".", "create_account", "(", "self", ".", "_json_params", ")", "if", "not", "created", ":", "raise", "JHTTPConflict", "(", "'Looks like you already have an account.'", ...
Register new user by POSTing all required data.
[ "Register", "new", "user", "by", "POSTing", "all", "required", "data", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/views.py#L15-L26
ramses-tech/nefertari
nefertari/authentication/views.py
TokenAuthViewMixin.register
def register(self): """ Register a new user by POSTing all required data. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ user, created = self.Model.create_account(self._json_params) if user.api_key is None: raise JHTTPBadReq...
python
def register(self): """ Register a new user by POSTing all required data. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ user, created = self.Model.create_account(self._json_params) if user.api_key is None: raise JHTTPBadReq...
[ "def", "register", "(", "self", ")", ":", "user", ",", "created", "=", "self", ".", "Model", ".", "create_account", "(", "self", ".", "_json_params", ")", "if", "user", ".", "api_key", "is", "None", ":", "raise", "JHTTPBadRequest", "(", "'Failed to generat...
Register a new user by POSTing all required data. User's `Authorization` header value is returned in `WWW-Authenticate` header.
[ "Register", "a", "new", "user", "by", "POSTing", "all", "required", "data", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/views.py#L109-L124
ramses-tech/nefertari
nefertari/authentication/views.py
TokenAuthViewMixin.claim_token
def claim_token(self, **params): """Claim current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ self._json_params.update(params) success, self.user = self.Model.authenticate_by_password( ...
python
def claim_token(self, **params): """Claim current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ self._json_params.update(params) success, self.user = self.Model.authenticate_by_password( ...
[ "def", "claim_token", "(", "self", ",", "*", "*", "params", ")", ":", "self", ".", "_json_params", ".", "update", "(", "params", ")", "success", ",", "self", ".", "user", "=", "self", ".", "Model", ".", "authenticate_by_password", "(", "self", ".", "_j...
Claim current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` header.
[ "Claim", "current", "token", "by", "POSTing", "login", "and", "password", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/views.py#L126-L142
ramses-tech/nefertari
nefertari/authentication/views.py
TokenAuthViewMixin.reset_token
def reset_token(self, **params): """ Reset current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ response = self.claim_token(**params) if not self.user: return response self...
python
def reset_token(self, **params): """ Reset current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ response = self.claim_token(**params) if not self.user: return response self...
[ "def", "reset_token", "(", "self", ",", "*", "*", "params", ")", ":", "response", "=", "self", ".", "claim_token", "(", "*", "*", "params", ")", "if", "not", "self", ".", "user", ":", "return", "response", "self", ".", "user", ".", "api_key", ".", ...
Reset current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` header.
[ "Reset", "current", "token", "by", "POSTing", "login", "and", "password", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/views.py#L144-L156
ramses-tech/nefertari
nefertari/wrappers.py
apply_privacy._apply_nested_privacy
def _apply_nested_privacy(self, data): """ Apply privacy to nested documents. :param data: Dict of data to which privacy is already applied. """ kw = { 'is_admin': self.is_admin, 'drop_hidden': self.drop_hidden, } for key, val in data.items(): ...
python
def _apply_nested_privacy(self, data): """ Apply privacy to nested documents. :param data: Dict of data to which privacy is already applied. """ kw = { 'is_admin': self.is_admin, 'drop_hidden': self.drop_hidden, } for key, val in data.items(): ...
[ "def", "_apply_nested_privacy", "(", "self", ",", "data", ")", ":", "kw", "=", "{", "'is_admin'", ":", "self", ".", "is_admin", ",", "'drop_hidden'", ":", "self", ".", "drop_hidden", ",", "}", "for", "key", ",", "val", "in", "data", ".", "items", "(", ...
Apply privacy to nested documents. :param data: Dict of data to which privacy is already applied.
[ "Apply", "privacy", "to", "nested", "documents", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/wrappers.py#L191-L206
ramses-tech/nefertari
nefertari/wrappers.py
add_object_url._set_object_self
def _set_object_self(self, obj): """ Add '_self' key value to :obj: dict. """ from nefertari.elasticsearch import ES location = self.request.path_url route_kwargs = {} """ Check for parents """ if self.request.matchdict: route_kwargs.update(self.request.match...
python
def _set_object_self(self, obj): """ Add '_self' key value to :obj: dict. """ from nefertari.elasticsearch import ES location = self.request.path_url route_kwargs = {} """ Check for parents """ if self.request.matchdict: route_kwargs.update(self.request.match...
[ "def", "_set_object_self", "(", "self", ",", "obj", ")", ":", "from", "nefertari", ".", "elasticsearch", "import", "ES", "location", "=", "self", ".", "request", ".", "path_url", "route_kwargs", "=", "{", "}", "\"\"\" Check for parents \"\"\"", "if", "self", "...
Add '_self' key value to :obj: dict.
[ "Add", "_self", "key", "value", "to", ":", "obj", ":", "dict", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/wrappers.py#L300-L319
ramses-tech/nefertari
nefertari/resource.py
get_root_resource
def get_root_resource(config): """Returns the root resource.""" app_package_name = get_app_package_name(config) return config.registry._root_resources.setdefault( app_package_name, Resource(config))
python
def get_root_resource(config): """Returns the root resource.""" app_package_name = get_app_package_name(config) return config.registry._root_resources.setdefault( app_package_name, Resource(config))
[ "def", "get_root_resource", "(", "config", ")", ":", "app_package_name", "=", "get_app_package_name", "(", "config", ")", "return", "config", ".", "registry", ".", "_root_resources", ".", "setdefault", "(", "app_package_name", ",", "Resource", "(", "config", ")", ...
Returns the root resource.
[ "Returns", "the", "root", "resource", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/resource.py#L46-L50
ramses-tech/nefertari
nefertari/resource.py
add_resource_routes
def add_resource_routes(config, view, member_name, collection_name, **kwargs): """ ``view`` is a dotted name of (or direct reference to) a Python view class, e.g. ``'my.package.views.MyView'``. ``member_name`` should be the appropriate singular version of the resource given your locale and used...
python
def add_resource_routes(config, view, member_name, collection_name, **kwargs): """ ``view`` is a dotted name of (or direct reference to) a Python view class, e.g. ``'my.package.views.MyView'``. ``member_name`` should be the appropriate singular version of the resource given your locale and used...
[ "def", "add_resource_routes", "(", "config", ",", "view", ",", "member_name", ",", "collection_name", ",", "*", "*", "kwargs", ")", ":", "view", "=", "maybe_dotted", "(", "view", ")", "path_prefix", "=", "kwargs", ".", "pop", "(", "'path_prefix'", ",", "''...
``view`` is a dotted name of (or direct reference to) a Python view class, e.g. ``'my.package.views.MyView'``. ``member_name`` should be the appropriate singular version of the resource given your locale and used with members of the collection. ``collection_name`` will be used to refer to the reso...
[ "view", "is", "a", "dotted", "name", "of", "(", "or", "direct", "reference", "to", ")", "a", "Python", "view", "class", "e", ".", "g", ".", "my", ".", "package", ".", "views", ".", "MyView", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/resource.py#L57-L190
ramses-tech/nefertari
nefertari/resource.py
get_default_view_path
def get_default_view_path(resource): "Returns the dotted path to the default view class." parts = [a.member_name for a in resource.ancestors] +\ [resource.collection_name or resource.member_name] if resource.prefix: parts.insert(-1, resource.prefix) view_file = '%s' % '_'.join(par...
python
def get_default_view_path(resource): "Returns the dotted path to the default view class." parts = [a.member_name for a in resource.ancestors] +\ [resource.collection_name or resource.member_name] if resource.prefix: parts.insert(-1, resource.prefix) view_file = '%s' % '_'.join(par...
[ "def", "get_default_view_path", "(", "resource", ")", ":", "parts", "=", "[", "a", ".", "member_name", "for", "a", "in", "resource", ".", "ancestors", "]", "+", "[", "resource", ".", "collection_name", "or", "resource", ".", "member_name", "]", "if", "reso...
Returns the dotted path to the default view class.
[ "Returns", "the", "dotted", "path", "to", "the", "default", "view", "class", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/resource.py#L193-L206
ramses-tech/nefertari
nefertari/resource.py
Resource.get_ancestors
def get_ancestors(self): "Returns the list of ancestor resources." if self._ancestors: return self._ancestors if not self.parent: return [] obj = self.resource_map.get(self.parent.uid) while obj and obj.member_name: self._ancestors.append(o...
python
def get_ancestors(self): "Returns the list of ancestor resources." if self._ancestors: return self._ancestors if not self.parent: return [] obj = self.resource_map.get(self.parent.uid) while obj and obj.member_name: self._ancestors.append(o...
[ "def", "get_ancestors", "(", "self", ")", ":", "if", "self", ".", "_ancestors", ":", "return", "self", ".", "_ancestors", "if", "not", "self", ".", "parent", ":", "return", "[", "]", "obj", "=", "self", ".", "resource_map", ".", "get", "(", "self", "...
Returns the list of ancestor resources.
[ "Returns", "the", "list", "of", "ancestor", "resources", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/resource.py#L231-L247
ramses-tech/nefertari
nefertari/resource.py
Resource.add
def add(self, member_name, collection_name='', parent=None, uid='', **kwargs): """ :param member_name: singular name of the resource. It should be the appropriate singular version of the resource given your locale and used with members of the collection. :par...
python
def add(self, member_name, collection_name='', parent=None, uid='', **kwargs): """ :param member_name: singular name of the resource. It should be the appropriate singular version of the resource given your locale and used with members of the collection. :par...
[ "def", "add", "(", "self", ",", "member_name", ",", "collection_name", "=", "''", ",", "parent", "=", "None", ",", "uid", "=", "''", ",", "*", "*", "kwargs", ")", ":", "# self is the parent resource on which this method is called.", "parent", "=", "(", "self",...
:param member_name: singular name of the resource. It should be the appropriate singular version of the resource given your locale and used with members of the collection. :param collection_name: plural name of the resource. It will be used to refer to the resource collectio...
[ ":", "param", "member_name", ":", "singular", "name", "of", "the", "resource", ".", "It", "should", "be", "the", "appropriate", "singular", "version", "of", "the", "resource", "given", "your", "locale", "and", "used", "with", "members", "of", "the", "collect...
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/resource.py#L257-L379
ramses-tech/nefertari
nefertari/resource.py
Resource.add_from_child
def add_from_child(self, resource, **kwargs): """ Add a resource with its all children resources to the current resource. """ new_resource = self.add( resource.member_name, resource.collection_name, **kwargs) for child in resource.children: new_resource.a...
python
def add_from_child(self, resource, **kwargs): """ Add a resource with its all children resources to the current resource. """ new_resource = self.add( resource.member_name, resource.collection_name, **kwargs) for child in resource.children: new_resource.a...
[ "def", "add_from_child", "(", "self", ",", "resource", ",", "*", "*", "kwargs", ")", ":", "new_resource", "=", "self", ".", "add", "(", "resource", ".", "member_name", ",", "resource", ".", "collection_name", ",", "*", "*", "kwargs", ")", "for", "child",...
Add a resource with its all children resources to the current resource.
[ "Add", "a", "resource", "with", "its", "all", "children", "resources", "to", "the", "current", "resource", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/resource.py#L381-L389
opengridcc/opengrid
opengrid/datasets/datasets.py
DatasetContainer.add
def add(self, path): """ Add the path of a data set to the list of available sets NOTE: a data set is assumed to be a pickled and gzip compressed Pandas DataFrame Parameters ---------- path : str """ name_with_ext = os.path.split(path)[1] # spli...
python
def add(self, path): """ Add the path of a data set to the list of available sets NOTE: a data set is assumed to be a pickled and gzip compressed Pandas DataFrame Parameters ---------- path : str """ name_with_ext = os.path.split(path)[1] # spli...
[ "def", "add", "(", "self", ",", "path", ")", ":", "name_with_ext", "=", "os", ".", "path", ".", "split", "(", "path", ")", "[", "1", "]", "# split directory and filename", "name", "=", "name_with_ext", ".", "split", "(", "'.'", ")", "[", "0", "]", "#...
Add the path of a data set to the list of available sets NOTE: a data set is assumed to be a pickled and gzip compressed Pandas DataFrame Parameters ---------- path : str
[ "Add", "the", "path", "of", "a", "data", "set", "to", "the", "list", "of", "available", "sets" ]
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/datasets/datasets.py#L27-L40
opengridcc/opengrid
opengrid/datasets/datasets.py
DatasetContainer.unpack
def unpack(self, name): """ Unpacks a data set to a Pandas DataFrame Parameters ---------- name : str call `.list` to see all availble datasets Returns ------- pd.DataFrame """ path = self.list[name] df = pd.read_pickl...
python
def unpack(self, name): """ Unpacks a data set to a Pandas DataFrame Parameters ---------- name : str call `.list` to see all availble datasets Returns ------- pd.DataFrame """ path = self.list[name] df = pd.read_pickl...
[ "def", "unpack", "(", "self", ",", "name", ")", ":", "path", "=", "self", ".", "list", "[", "name", "]", "df", "=", "pd", ".", "read_pickle", "(", "path", ",", "compression", "=", "'gzip'", ")", "return", "df" ]
Unpacks a data set to a Pandas DataFrame Parameters ---------- name : str call `.list` to see all availble datasets Returns ------- pd.DataFrame
[ "Unpacks", "a", "data", "set", "to", "a", "Pandas", "DataFrame" ]
train
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/datasets/datasets.py#L42-L57
christophertbrown/bioscripts
ctbBio/sixframe.py
six_frame
def six_frame(genome, table, minimum = 10): """ translate each sequence into six reading frames """ for seq in parse_fasta(genome): dna = Seq(seq[1].upper().replace('U', 'T'), IUPAC.ambiguous_dna) counter = 0 for sequence in ['f', dna], ['rc', dna.reverse_complement()]: ...
python
def six_frame(genome, table, minimum = 10): """ translate each sequence into six reading frames """ for seq in parse_fasta(genome): dna = Seq(seq[1].upper().replace('U', 'T'), IUPAC.ambiguous_dna) counter = 0 for sequence in ['f', dna], ['rc', dna.reverse_complement()]: ...
[ "def", "six_frame", "(", "genome", ",", "table", ",", "minimum", "=", "10", ")", ":", "for", "seq", "in", "parse_fasta", "(", "genome", ")", ":", "dna", "=", "Seq", "(", "seq", "[", "1", "]", ".", "upper", "(", ")", ".", "replace", "(", "'U'", ...
translate each sequence into six reading frames
[ "translate", "each", "sequence", "into", "six", "reading", "frames" ]
train
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/sixframe.py#L13-L32
jay-johnson/network-pipeline
network_pipeline/scripts/network_agent.py
publish_processed_network_packets
def publish_processed_network_packets( name="not-set", task_queue=None, result_queue=None, need_response=False, shutdown_msg="SHUTDOWN"): """ # Redis/RabbitMQ/SQS messaging endpoints for pub-sub routing_key = ev("PUBLISH_EXCHANGE", "reporting.acc...
python
def publish_processed_network_packets( name="not-set", task_queue=None, result_queue=None, need_response=False, shutdown_msg="SHUTDOWN"): """ # Redis/RabbitMQ/SQS messaging endpoints for pub-sub routing_key = ev("PUBLISH_EXCHANGE", "reporting.acc...
[ "def", "publish_processed_network_packets", "(", "name", "=", "\"not-set\"", ",", "task_queue", "=", "None", ",", "result_queue", "=", "None", ",", "need_response", "=", "False", ",", "shutdown_msg", "=", "\"SHUTDOWN\"", ")", ":", "# these keys need to be cycled to pr...
# Redis/RabbitMQ/SQS messaging endpoints for pub-sub routing_key = ev("PUBLISH_EXCHANGE", "reporting.accounts") queue_name = ev("PUBLISH_QUEUE", "reporting.accounts") auth_url = ev("PUB_BROKER_URL", "redis://localhost:6379/15") serializer = "jso...
[ "#", "Redis", "/", "RabbitMQ", "/", "SQS", "messaging", "endpoints", "for", "pub", "-", "sub", "routing_key", "=", "ev", "(", "PUBLISH_EXCHANGE", "reporting", ".", "accounts", ")", "queue_name", "=", "ev", "(", "PUBLISH_QUEUE", "reporting", ".", "accounts", ...
train
https://github.com/jay-johnson/network-pipeline/blob/4e53ae13fe12085e0cf2e5e1aff947368f4f1ffa/network_pipeline/scripts/network_agent.py#L35-L244
jay-johnson/network-pipeline
network_pipeline/scripts/network_agent.py
run_main
def run_main( need_response=False, callback=None): """run_main start the packet consumers and the packet processors :param need_response: should send response back to publisher :param callback: handler method """ stop_file = ev("STOP_FILE", "/opt/stop_record...
python
def run_main( need_response=False, callback=None): """run_main start the packet consumers and the packet processors :param need_response: should send response back to publisher :param callback: handler method """ stop_file = ev("STOP_FILE", "/opt/stop_record...
[ "def", "run_main", "(", "need_response", "=", "False", ",", "callback", "=", "None", ")", ":", "stop_file", "=", "ev", "(", "\"STOP_FILE\"", ",", "\"/opt/stop_recording\"", ")", "num_workers", "=", "int", "(", "ev", "(", "\"NUM_WORKERS\"", ",", "\"1\"", ")",...
run_main start the packet consumers and the packet processors :param need_response: should send response back to publisher :param callback: handler method
[ "run_main" ]
train
https://github.com/jay-johnson/network-pipeline/blob/4e53ae13fe12085e0cf2e5e1aff947368f4f1ffa/network_pipeline/scripts/network_agent.py#L248-L341
christophertbrown/bioscripts
ctbBio/16SfromHMM.py
best_model
def best_model(seq2hmm): """ determine the best model: archaea, bacteria, eukarya (best score) """ for seq in seq2hmm: best = [] for model in seq2hmm[seq]: best.append([model, sorted([i[-1] for i in seq2hmm[seq][model]], reverse = True)[0]]) best_model = sorted(best, ...
python
def best_model(seq2hmm): """ determine the best model: archaea, bacteria, eukarya (best score) """ for seq in seq2hmm: best = [] for model in seq2hmm[seq]: best.append([model, sorted([i[-1] for i in seq2hmm[seq][model]], reverse = True)[0]]) best_model = sorted(best, ...
[ "def", "best_model", "(", "seq2hmm", ")", ":", "for", "seq", "in", "seq2hmm", ":", "best", "=", "[", "]", "for", "model", "in", "seq2hmm", "[", "seq", "]", ":", "best", ".", "append", "(", "[", "model", ",", "sorted", "(", "[", "i", "[", "-", "...
determine the best model: archaea, bacteria, eukarya (best score)
[ "determine", "the", "best", "model", ":", "archaea", "bacteria", "eukarya", "(", "best", "score", ")" ]
train
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L21-L31
christophertbrown/bioscripts
ctbBio/16SfromHMM.py
check_gaps
def check_gaps(matches, gap_threshold = 0): """ check for large gaps between alignment windows """ gaps = [] prev = None for match in sorted(matches, key = itemgetter(0)): if prev is None: prev = match continue if match[0] - prev[1] >= gap_threshold: ...
python
def check_gaps(matches, gap_threshold = 0): """ check for large gaps between alignment windows """ gaps = [] prev = None for match in sorted(matches, key = itemgetter(0)): if prev is None: prev = match continue if match[0] - prev[1] >= gap_threshold: ...
[ "def", "check_gaps", "(", "matches", ",", "gap_threshold", "=", "0", ")", ":", "gaps", "=", "[", "]", "prev", "=", "None", "for", "match", "in", "sorted", "(", "matches", ",", "key", "=", "itemgetter", "(", "0", ")", ")", ":", "if", "prev", "is", ...
check for large gaps between alignment windows
[ "check", "for", "large", "gaps", "between", "alignment", "windows" ]
train
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L33-L46
christophertbrown/bioscripts
ctbBio/16SfromHMM.py
check_overlap
def check_overlap(current, hit, overlap = 200): """ determine if sequence has already hit the same part of the model, indicating that this hit is for another 16S rRNA gene """ for prev in current: p_coords = prev[2:4] coords = hit[2:4] if get_overlap(coords, p_coords) >= over...
python
def check_overlap(current, hit, overlap = 200): """ determine if sequence has already hit the same part of the model, indicating that this hit is for another 16S rRNA gene """ for prev in current: p_coords = prev[2:4] coords = hit[2:4] if get_overlap(coords, p_coords) >= over...
[ "def", "check_overlap", "(", "current", ",", "hit", ",", "overlap", "=", "200", ")", ":", "for", "prev", "in", "current", ":", "p_coords", "=", "prev", "[", "2", ":", "4", "]", "coords", "=", "hit", "[", "2", ":", "4", "]", "if", "get_overlap", "...
determine if sequence has already hit the same part of the model, indicating that this hit is for another 16S rRNA gene
[ "determine", "if", "sequence", "has", "already", "hit", "the", "same", "part", "of", "the", "model", "indicating", "that", "this", "hit", "is", "for", "another", "16S", "rRNA", "gene" ]
train
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L51-L61
christophertbrown/bioscripts
ctbBio/16SfromHMM.py
check_order
def check_order(current, hit, overlap = 200): """ determine if hits are sequential on model and on the same strand * if not, they should be split into different groups """ prev_model = current[-1][2:4] prev_strand = current[-1][-2] hit_model = hit[2:4] hit_strand = hit[-2] # ...
python
def check_order(current, hit, overlap = 200): """ determine if hits are sequential on model and on the same strand * if not, they should be split into different groups """ prev_model = current[-1][2:4] prev_strand = current[-1][-2] hit_model = hit[2:4] hit_strand = hit[-2] # ...
[ "def", "check_order", "(", "current", ",", "hit", ",", "overlap", "=", "200", ")", ":", "prev_model", "=", "current", "[", "-", "1", "]", "[", "2", ":", "4", "]", "prev_strand", "=", "current", "[", "-", "1", "]", "[", "-", "2", "]", "hit_model",...
determine if hits are sequential on model and on the same strand * if not, they should be split into different groups
[ "determine", "if", "hits", "are", "sequential", "on", "model", "and", "on", "the", "same", "strand", "*", "if", "not", "they", "should", "be", "split", "into", "different", "groups" ]
train
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L63-L83
christophertbrown/bioscripts
ctbBio/16SfromHMM.py
hit_groups
def hit_groups(hits): """ * each sequence may have more than one 16S rRNA gene * group hits for each gene """ groups = [] current = False for hit in sorted(hits, key = itemgetter(0)): if current is False: current = [hit] elif check_overlap(current, hit) is True or...
python
def hit_groups(hits): """ * each sequence may have more than one 16S rRNA gene * group hits for each gene """ groups = [] current = False for hit in sorted(hits, key = itemgetter(0)): if current is False: current = [hit] elif check_overlap(current, hit) is True or...
[ "def", "hit_groups", "(", "hits", ")", ":", "groups", "=", "[", "]", "current", "=", "False", "for", "hit", "in", "sorted", "(", "hits", ",", "key", "=", "itemgetter", "(", "0", ")", ")", ":", "if", "current", "is", "False", ":", "current", "=", ...
* each sequence may have more than one 16S rRNA gene * group hits for each gene
[ "*", "each", "sequence", "may", "have", "more", "than", "one", "16S", "rRNA", "gene", "*", "group", "hits", "for", "each", "gene" ]
train
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L85-L101
christophertbrown/bioscripts
ctbBio/16SfromHMM.py
find_coordinates
def find_coordinates(hmms, bit_thresh): """ find 16S rRNA gene sequence coordinates """ # get coordinates from cmsearch output seq2hmm = parse_hmm(hmms, bit_thresh) seq2hmm = best_model(seq2hmm) group2hmm = {} # group2hmm[seq][group] = [model, strand, coordinates, matches, gaps] for seq,...
python
def find_coordinates(hmms, bit_thresh): """ find 16S rRNA gene sequence coordinates """ # get coordinates from cmsearch output seq2hmm = parse_hmm(hmms, bit_thresh) seq2hmm = best_model(seq2hmm) group2hmm = {} # group2hmm[seq][group] = [model, strand, coordinates, matches, gaps] for seq,...
[ "def", "find_coordinates", "(", "hmms", ",", "bit_thresh", ")", ":", "# get coordinates from cmsearch output", "seq2hmm", "=", "parse_hmm", "(", "hmms", ",", "bit_thresh", ")", "seq2hmm", "=", "best_model", "(", "seq2hmm", ")", "group2hmm", "=", "{", "}", "# gro...
find 16S rRNA gene sequence coordinates
[ "find", "16S", "rRNA", "gene", "sequence", "coordinates" ]
train
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L103-L126
christophertbrown/bioscripts
ctbBio/16SfromHMM.py
get_info
def get_info(line, bit_thresh): """ get info from either ssu-cmsearch or cmsearch output """ if len(line) >= 18: # output is from cmsearch id, model, bit, inc = line[0].split()[0], line[2], float(line[14]), line[16] sstart, send, strand = int(line[7]), int(line[8]), line[9] mstar...
python
def get_info(line, bit_thresh): """ get info from either ssu-cmsearch or cmsearch output """ if len(line) >= 18: # output is from cmsearch id, model, bit, inc = line[0].split()[0], line[2], float(line[14]), line[16] sstart, send, strand = int(line[7]), int(line[8]), line[9] mstar...
[ "def", "get_info", "(", "line", ",", "bit_thresh", ")", ":", "if", "len", "(", "line", ")", ">=", "18", ":", "# output is from cmsearch", "id", ",", "model", ",", "bit", ",", "inc", "=", "line", "[", "0", "]", ".", "split", "(", ")", "[", "0", "]...
get info from either ssu-cmsearch or cmsearch output
[ "get", "info", "from", "either", "ssu", "-", "cmsearch", "or", "cmsearch", "output" ]
train
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L128-L157
christophertbrown/bioscripts
ctbBio/16SfromHMM.py
check_buffer
def check_buffer(coords, length, buffer): """ check to see how much of the buffer is being used """ s = min(coords[0], buffer) e = min(length - coords[1], buffer) return [s, e]
python
def check_buffer(coords, length, buffer): """ check to see how much of the buffer is being used """ s = min(coords[0], buffer) e = min(length - coords[1], buffer) return [s, e]
[ "def", "check_buffer", "(", "coords", ",", "length", ",", "buffer", ")", ":", "s", "=", "min", "(", "coords", "[", "0", "]", ",", "buffer", ")", "e", "=", "min", "(", "length", "-", "coords", "[", "1", "]", ",", "buffer", ")", "return", "[", "s...
check to see how much of the buffer is being used
[ "check", "to", "see", "how", "much", "of", "the", "buffer", "is", "being", "used" ]
train
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L189-L195
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
convert_parser_to
def convert_parser_to(parser, parser_or_type, metadata_props=None): """ :return: a parser of type parser_or_type, initialized with the properties of parser. If parser_or_type is a type, an instance of it must contain a update method. The update method must also process the set of properties supported by...
python
def convert_parser_to(parser, parser_or_type, metadata_props=None): """ :return: a parser of type parser_or_type, initialized with the properties of parser. If parser_or_type is a type, an instance of it must contain a update method. The update method must also process the set of properties supported by...
[ "def", "convert_parser_to", "(", "parser", ",", "parser_or_type", ",", "metadata_props", "=", "None", ")", ":", "old_parser", "=", "parser", "if", "isinstance", "(", "parser", ",", "MetadataParser", ")", "else", "get_metadata_parser", "(", "parser", ")", "new_pa...
:return: a parser of type parser_or_type, initialized with the properties of parser. If parser_or_type is a type, an instance of it must contain a update method. The update method must also process the set of properties supported by MetadataParser for the conversion to have any affect. :param parser: the pa...
[ ":", "return", ":", "a", "parser", "of", "type", "parser_or_type", "initialized", "with", "the", "properties", "of", "parser", ".", "If", "parser_or_type", "is", "a", "type", "an", "instance", "of", "it", "must", "contain", "a", "update", "method", ".", "T...
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L30-L48
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
get_metadata_parser
def get_metadata_parser(metadata_container, **metadata_defaults): """ Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file. :return: a new instance of a parser corresponding to the standard represented by metadata_container :see: get_parsed_content(metdata_con...
python
def get_metadata_parser(metadata_container, **metadata_defaults): """ Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file. :return: a new instance of a parser corresponding to the standard represented by metadata_container :see: get_parsed_content(metdata_con...
[ "def", "get_metadata_parser", "(", "metadata_container", ",", "*", "*", "metadata_defaults", ")", ":", "parser_type", "=", "None", "if", "isinstance", "(", "metadata_container", ",", "MetadataParser", ")", ":", "parser_type", "=", "type", "(", "metadata_container", ...
Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file. :return: a new instance of a parser corresponding to the standard represented by metadata_container :see: get_parsed_content(metdata_content) for more on types of content that can be parsed
[ "Takes", "a", "metadata_container", "which", "may", "be", "a", "type", "or", "instance", "of", "a", "parser", "a", "dict", "string", "or", "file", ".", ":", "return", ":", "a", "new", "instance", "of", "a", "parser", "corresponding", "to", "the", "standa...
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L51-L85
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
get_parsed_content
def get_parsed_content(metadata_content): """ Parses any of the following types of content: 1. XML string or file object: parses XML content 2. MetadataParser instance: deep copies xml_tree 3. Dictionary with nested objects containing: - name (required): the name of the element tag -...
python
def get_parsed_content(metadata_content): """ Parses any of the following types of content: 1. XML string or file object: parses XML content 2. MetadataParser instance: deep copies xml_tree 3. Dictionary with nested objects containing: - name (required): the name of the element tag -...
[ "def", "get_parsed_content", "(", "metadata_content", ")", ":", "_import_parsers", "(", ")", "# Prevents circular dependencies between modules", "xml_tree", "=", "None", "if", "metadata_content", "is", "None", ":", "raise", "NoContent", "(", "'Metadata has no data'", ")",...
Parses any of the following types of content: 1. XML string or file object: parses XML content 2. MetadataParser instance: deep copies xml_tree 3. Dictionary with nested objects containing: - name (required): the name of the element tag - text: the text contained by element - tail: t...
[ "Parses", "any", "of", "the", "following", "types", "of", "content", ":", "1", ".", "XML", "string", "or", "file", "object", ":", "parses", "XML", "content", "2", ".", "MetadataParser", "instance", ":", "deep", "copies", "xml_tree", "3", ".", "Dictionary",...
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L88-L138
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
_import_parsers
def _import_parsers(): """ Lazy imports to prevent circular dependencies between this module and utils """ global ARCGIS_NODES global ARCGIS_ROOTS global ArcGISParser global FGDC_ROOT global FgdcParser global ISO_ROOTS global IsoParser global VALID_ROOTS if ARCGIS_NODES is N...
python
def _import_parsers(): """ Lazy imports to prevent circular dependencies between this module and utils """ global ARCGIS_NODES global ARCGIS_ROOTS global ArcGISParser global FGDC_ROOT global FgdcParser global ISO_ROOTS global IsoParser global VALID_ROOTS if ARCGIS_NODES is N...
[ "def", "_import_parsers", "(", ")", ":", "global", "ARCGIS_NODES", "global", "ARCGIS_ROOTS", "global", "ArcGISParser", "global", "FGDC_ROOT", "global", "FgdcParser", "global", "ISO_ROOTS", "global", "IsoParser", "global", "VALID_ROOTS", "if", "ARCGIS_NODES", "is", "No...
Lazy imports to prevent circular dependencies between this module and utils
[ "Lazy", "imports", "to", "prevent", "circular", "dependencies", "between", "this", "module", "and", "utils" ]
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L141-L170
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
MetadataParser._init_metadata
def _init_metadata(self): """ Dynamically sets attributes from a Dictionary passed in by children. The Dictionary will contain the name of each attribute as keys, and either an XPATH mapping to a text value in _xml_tree, or a function that takes no parameters and returns the inte...
python
def _init_metadata(self): """ Dynamically sets attributes from a Dictionary passed in by children. The Dictionary will contain the name of each attribute as keys, and either an XPATH mapping to a text value in _xml_tree, or a function that takes no parameters and returns the inte...
[ "def", "_init_metadata", "(", "self", ")", ":", "if", "self", ".", "_data_map", "is", "None", ":", "self", ".", "_init_data_map", "(", ")", "validate_properties", "(", "self", ".", "_data_map", ",", "self", ".", "_metadata_props", ")", "# Parse attribute value...
Dynamically sets attributes from a Dictionary passed in by children. The Dictionary will contain the name of each attribute as keys, and either an XPATH mapping to a text value in _xml_tree, or a function that takes no parameters and returns the intended value.
[ "Dynamically", "sets", "attributes", "from", "a", "Dictionary", "passed", "in", "by", "children", ".", "The", "Dictionary", "will", "contain", "the", "name", "of", "each", "attribute", "as", "keys", "and", "either", "an", "XPATH", "mapping", "to", "a", "text...
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L236-L254
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
MetadataParser._init_data_map
def _init_data_map(self): """ Default data map initialization: MUST be overridden in children """ if self._data_map is None: self._data_map = {'_root': None} self._data_map.update({}.fromkeys(self._metadata_props))
python
def _init_data_map(self): """ Default data map initialization: MUST be overridden in children """ if self._data_map is None: self._data_map = {'_root': None} self._data_map.update({}.fromkeys(self._metadata_props))
[ "def", "_init_data_map", "(", "self", ")", ":", "if", "self", ".", "_data_map", "is", "None", ":", "self", ".", "_data_map", "=", "{", "'_root'", ":", "None", "}", "self", ".", "_data_map", ".", "update", "(", "{", "}", ".", "fromkeys", "(", "self", ...
Default data map initialization: MUST be overridden in children
[ "Default", "data", "map", "initialization", ":", "MUST", "be", "overridden", "in", "children" ]
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L256-L261
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
MetadataParser._get_template
def _get_template(self, root=None, **metadata_defaults): """ Iterate over items metadata_defaults {prop: val, ...} to populate template """ if root is None: if self._data_map is None: self._init_data_map() root = self._xml_root = self._data_map['_root'] ...
python
def _get_template(self, root=None, **metadata_defaults): """ Iterate over items metadata_defaults {prop: val, ...} to populate template """ if root is None: if self._data_map is None: self._init_data_map() root = self._xml_root = self._data_map['_root'] ...
[ "def", "_get_template", "(", "self", ",", "root", "=", "None", ",", "*", "*", "metadata_defaults", ")", ":", "if", "root", "is", "None", ":", "if", "self", ".", "_data_map", "is", "None", ":", "self", ".", "_init_data_map", "(", ")", "root", "=", "se...
Iterate over items metadata_defaults {prop: val, ...} to populate template
[ "Iterate", "over", "items", "metadata_defaults", "{", "prop", ":", "val", "...", "}", "to", "populate", "template" ]
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L263-L280
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
MetadataParser._get_xpath_for
def _get_xpath_for(self, prop): """ :return: the configured xpath for a given property """ xpath = self._data_map.get(prop) return getattr(xpath, 'xpath', xpath)
python
def _get_xpath_for(self, prop): """ :return: the configured xpath for a given property """ xpath = self._data_map.get(prop) return getattr(xpath, 'xpath', xpath)
[ "def", "_get_xpath_for", "(", "self", ",", "prop", ")", ":", "xpath", "=", "self", ".", "_data_map", ".", "get", "(", "prop", ")", "return", "getattr", "(", "xpath", ",", "'xpath'", ",", "xpath", ")" ]
:return: the configured xpath for a given property
[ ":", "return", ":", "the", "configured", "xpath", "for", "a", "given", "property" ]
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L282-L286
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
MetadataParser._parse_complex
def _parse_complex(self, prop): """ Default parsing operation for a complex struct """ xpath_root = None xpath_map = self._data_structures[prop] return parse_complex(self._xml_tree, xpath_root, xpath_map, prop)
python
def _parse_complex(self, prop): """ Default parsing operation for a complex struct """ xpath_root = None xpath_map = self._data_structures[prop] return parse_complex(self._xml_tree, xpath_root, xpath_map, prop)
[ "def", "_parse_complex", "(", "self", ",", "prop", ")", ":", "xpath_root", "=", "None", "xpath_map", "=", "self", ".", "_data_structures", "[", "prop", "]", "return", "parse_complex", "(", "self", ".", "_xml_tree", ",", "xpath_root", ",", "xpath_map", ",", ...
Default parsing operation for a complex struct
[ "Default", "parsing", "operation", "for", "a", "complex", "struct" ]
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L293-L299
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
MetadataParser._parse_complex_list
def _parse_complex_list(self, prop): """ Default parsing operation for lists of complex structs """ xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return parse_complex_list(self._xml_tree, xpath_root, xpath_map, prop)
python
def _parse_complex_list(self, prop): """ Default parsing operation for lists of complex structs """ xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return parse_complex_list(self._xml_tree, xpath_root, xpath_map, prop)
[ "def", "_parse_complex_list", "(", "self", ",", "prop", ")", ":", "xpath_root", "=", "self", ".", "_get_xroot_for", "(", "prop", ")", "xpath_map", "=", "self", ".", "_data_structures", "[", "prop", "]", "return", "parse_complex_list", "(", "self", ".", "_xml...
Default parsing operation for lists of complex structs
[ "Default", "parsing", "operation", "for", "lists", "of", "complex", "structs" ]
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L301-L307
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
MetadataParser._parse_dates
def _parse_dates(self, prop=DATES): """ Creates and returns a Date Types data structure parsed from the metadata """ return parse_dates(self._xml_tree, self._data_structures[prop])
python
def _parse_dates(self, prop=DATES): """ Creates and returns a Date Types data structure parsed from the metadata """ return parse_dates(self._xml_tree, self._data_structures[prop])
[ "def", "_parse_dates", "(", "self", ",", "prop", "=", "DATES", ")", ":", "return", "parse_dates", "(", "self", ".", "_xml_tree", ",", "self", ".", "_data_structures", "[", "prop", "]", ")" ]
Creates and returns a Date Types data structure parsed from the metadata
[ "Creates", "and", "returns", "a", "Date", "Types", "data", "structure", "parsed", "from", "the", "metadata" ]
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L309-L312
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
MetadataParser._update_complex
def _update_complex(self, **update_props): """ Default update operation for a complex struct """ prop = update_props['prop'] xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return update_complex(xpath_root=xpath_root, xpath_map=xpath_map, **update...
python
def _update_complex(self, **update_props): """ Default update operation for a complex struct """ prop = update_props['prop'] xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return update_complex(xpath_root=xpath_root, xpath_map=xpath_map, **update...
[ "def", "_update_complex", "(", "self", ",", "*", "*", "update_props", ")", ":", "prop", "=", "update_props", "[", "'prop'", "]", "xpath_root", "=", "self", ".", "_get_xroot_for", "(", "prop", ")", "xpath_map", "=", "self", ".", "_data_structures", "[", "pr...
Default update operation for a complex struct
[ "Default", "update", "operation", "for", "a", "complex", "struct" ]
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L314-L321
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
MetadataParser._update_complex_list
def _update_complex_list(self, **update_props): """ Default update operation for lists of complex structs """ prop = update_props['prop'] xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return update_complex_list(xpath_root=xpath_root, xpath_map=x...
python
def _update_complex_list(self, **update_props): """ Default update operation for lists of complex structs """ prop = update_props['prop'] xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return update_complex_list(xpath_root=xpath_root, xpath_map=x...
[ "def", "_update_complex_list", "(", "self", ",", "*", "*", "update_props", ")", ":", "prop", "=", "update_props", "[", "'prop'", "]", "xpath_root", "=", "self", ".", "_get_xroot_for", "(", "prop", ")", "xpath_map", "=", "self", ".", "_data_structures", "[", ...
Default update operation for lists of complex structs
[ "Default", "update", "operation", "for", "lists", "of", "complex", "structs" ]
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L323-L330
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
MetadataParser._update_dates
def _update_dates(self, xpath_root=None, **update_props): """ Default update operation for Dates metadata :see: gis_metadata.utils._complex_definitions[DATES] """ tree_to_update = update_props['tree_to_update'] prop = update_props['prop'] values = (update_props['...
python
def _update_dates(self, xpath_root=None, **update_props): """ Default update operation for Dates metadata :see: gis_metadata.utils._complex_definitions[DATES] """ tree_to_update = update_props['tree_to_update'] prop = update_props['prop'] values = (update_props['...
[ "def", "_update_dates", "(", "self", ",", "xpath_root", "=", "None", ",", "*", "*", "update_props", ")", ":", "tree_to_update", "=", "update_props", "[", "'tree_to_update'", "]", "prop", "=", "update_props", "[", "'prop'", "]", "values", "=", "(", "update_pr...
Default update operation for Dates metadata :see: gis_metadata.utils._complex_definitions[DATES]
[ "Default", "update", "operation", "for", "Dates", "metadata", ":", "see", ":", "gis_metadata", ".", "utils", ".", "_complex_definitions", "[", "DATES", "]" ]
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L332-L356
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
MetadataParser.write
def write(self, use_template=False, out_file_or_path=None, encoding=DEFAULT_ENCODING): """ Validates instance properties, updates an XML tree with them, and writes the content to a file. :param use_template: if True, updates a new template XML tree; otherwise the original XML tree :param...
python
def write(self, use_template=False, out_file_or_path=None, encoding=DEFAULT_ENCODING): """ Validates instance properties, updates an XML tree with them, and writes the content to a file. :param use_template: if True, updates a new template XML tree; otherwise the original XML tree :param...
[ "def", "write", "(", "self", ",", "use_template", "=", "False", ",", "out_file_or_path", "=", "None", ",", "encoding", "=", "DEFAULT_ENCODING", ")", ":", "if", "not", "out_file_or_path", ":", "out_file_or_path", "=", "self", ".", "out_file_or_path", "if", "not...
Validates instance properties, updates an XML tree with them, and writes the content to a file. :param use_template: if True, updates a new template XML tree; otherwise the original XML tree :param out_file_or_path: optionally override self.out_file_or_path with a custom file path :param encodin...
[ "Validates", "instance", "properties", "updates", "an", "XML", "tree", "with", "them", "and", "writes", "the", "content", "to", "a", "file", ".", ":", "param", "use_template", ":", "if", "True", "updates", "a", "new", "template", "XML", "tree", ";", "other...
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L373-L388
consbio/gis-metadata-parser
gis_metadata/metadata_parser.py
MetadataParser.validate
def validate(self): """ Default validation for updated properties: MAY be overridden in children """ validate_properties(self._data_map, self._metadata_props) for prop in self._data_map: validate_any(prop, getattr(self, prop), self._data_structures.get(prop)) return self
python
def validate(self): """ Default validation for updated properties: MAY be overridden in children """ validate_properties(self._data_map, self._metadata_props) for prop in self._data_map: validate_any(prop, getattr(self, prop), self._data_structures.get(prop)) return self
[ "def", "validate", "(", "self", ")", ":", "validate_properties", "(", "self", ".", "_data_map", ",", "self", ".", "_metadata_props", ")", "for", "prop", "in", "self", ".", "_data_map", ":", "validate_any", "(", "prop", ",", "getattr", "(", "self", ",", "...
Default validation for updated properties: MAY be overridden in children
[ "Default", "validation", "for", "updated", "properties", ":", "MAY", "be", "overridden", "in", "children" ]
train
https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L410-L418
kiwi0fruit/sugartex
sugartex/sugartex_filter.py
_search_regex
def _search_regex(ops: dict, regex_pat: str): """ Search order: * specified regexps * operators sorted from longer to shorter """ custom_regexps = list(filter(None, [dic['regex'] for op, dic in ops.items() if 'regex' in dic])) op_names = [op for op, dic in ops.items() if 'regex' not in d...
python
def _search_regex(ops: dict, regex_pat: str): """ Search order: * specified regexps * operators sorted from longer to shorter """ custom_regexps = list(filter(None, [dic['regex'] for op, dic in ops.items() if 'regex' in dic])) op_names = [op for op, dic in ops.items() if 'regex' not in d...
[ "def", "_search_regex", "(", "ops", ":", "dict", ",", "regex_pat", ":", "str", ")", ":", "custom_regexps", "=", "list", "(", "filter", "(", "None", ",", "[", "dic", "[", "'regex'", "]", "for", "op", ",", "dic", "in", "ops", ".", "items", "(", ")", ...
Search order: * specified regexps * operators sorted from longer to shorter
[ "Search", "order", ":", "*", "specified", "regexps", "*", "operators", "sorted", "from", "longer", "to", "shorter" ]
train
https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L165-L174
kiwi0fruit/sugartex
sugartex/sugartex_filter.py
Styles.spec
def spec(self, postf_un_ops: str) -> list: """Return prefix unary operators list""" spec = [(l + op, {'pat': self.pat(pat), 'postf': self.postf(r, postf_un_ops), 'regex': None}) for op, pat in self.styles.items() for l, ...
python
def spec(self, postf_un_ops: str) -> list: """Return prefix unary operators list""" spec = [(l + op, {'pat': self.pat(pat), 'postf': self.postf(r, postf_un_ops), 'regex': None}) for op, pat in self.styles.items() for l, ...
[ "def", "spec", "(", "self", ",", "postf_un_ops", ":", "str", ")", "->", "list", ":", "spec", "=", "[", "(", "l", "+", "op", ",", "{", "'pat'", ":", "self", ".", "pat", "(", "pat", ")", ",", "'postf'", ":", "self", ".", "postf", "(", "r", ",",...
Return prefix unary operators list
[ "Return", "prefix", "unary", "operators", "list" ]
train
https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L216-L227
kiwi0fruit/sugartex
sugartex/sugartex_filter.py
PrefUnGreedy.spec
def spec(self) -> list: """Returns prefix unary operators list. Sets only one regex for all items in the dict.""" spec = [item for op, pat in self.ops.items() for item in [('{' + op, {'pat': pat, 'postf': self.postf, 'regex': None}), (...
python
def spec(self) -> list: """Returns prefix unary operators list. Sets only one regex for all items in the dict.""" spec = [item for op, pat in self.ops.items() for item in [('{' + op, {'pat': pat, 'postf': self.postf, 'regex': None}), (...
[ "def", "spec", "(", "self", ")", "->", "list", ":", "spec", "=", "[", "item", "for", "op", ",", "pat", "in", "self", ".", "ops", ".", "items", "(", ")", "for", "item", "in", "[", "(", "'{'", "+", "op", ",", "{", "'pat'", ":", "pat", ",", "'...
Returns prefix unary operators list. Sets only one regex for all items in the dict.
[ "Returns", "prefix", "unary", "operators", "list", ".", "Sets", "only", "one", "regex", "for", "all", "items", "in", "the", "dict", "." ]
train
https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L242-L251
kiwi0fruit/sugartex
sugartex/sugartex_filter.py
PrefUnOps.fill
def fill(self, postf_un_ops: str): """ Insert: * math styles * other styles * unary prefix operators without brackets * defaults """ for op, dic in self.ops.items(): if 'postf' not in dic: dic['postf'] = self.postf ...
python
def fill(self, postf_un_ops: str): """ Insert: * math styles * other styles * unary prefix operators without brackets * defaults """ for op, dic in self.ops.items(): if 'postf' not in dic: dic['postf'] = self.postf ...
[ "def", "fill", "(", "self", ",", "postf_un_ops", ":", "str", ")", ":", "for", "op", ",", "dic", "in", "self", ".", "ops", ".", "items", "(", ")", ":", "if", "'postf'", "not", "in", "dic", ":", "dic", "[", "'postf'", "]", "=", "self", ".", "post...
Insert: * math styles * other styles * unary prefix operators without brackets * defaults
[ "Insert", ":", "*", "math", "styles", "*", "other", "styles", "*", "unary", "prefix", "operators", "without", "brackets", "*", "defaults" ]
train
https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L325-L344
kiwi0fruit/sugartex
sugartex/sugartex_filter.py
PostfUnOps.one_symbol_ops_str
def one_symbol_ops_str(self) -> str: """Regex-escaped string with all one-symbol operators""" return re.escape(''.join((key for key in self.ops.keys() if len(key) == 1)))
python
def one_symbol_ops_str(self) -> str: """Regex-escaped string with all one-symbol operators""" return re.escape(''.join((key for key in self.ops.keys() if len(key) == 1)))
[ "def", "one_symbol_ops_str", "(", "self", ")", "->", "str", ":", "return", "re", ".", "escape", "(", "''", ".", "join", "(", "(", "key", "for", "key", "in", "self", ".", "ops", ".", "keys", "(", ")", "if", "len", "(", "key", ")", "==", "1", ")"...
Regex-escaped string with all one-symbol operators
[ "Regex", "-", "escaped", "string", "with", "all", "one", "-", "symbol", "operators" ]
train
https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L389-L391
kiwi0fruit/sugartex
sugartex/sugartex_filter.py
SugarTeX._su_scripts_regex
def _su_scripts_regex(self): """ :return: [compiled regex, function] """ sups = re.escape(''.join([k for k in self.superscripts.keys()])) subs = re.escape(''.join([k for k in self.subscripts.keys()])) # language=PythonRegExp su_regex = (r'\\([{su_}])|([{sub}]...
python
def _su_scripts_regex(self): """ :return: [compiled regex, function] """ sups = re.escape(''.join([k for k in self.superscripts.keys()])) subs = re.escape(''.join([k for k in self.subscripts.keys()])) # language=PythonRegExp su_regex = (r'\\([{su_}])|([{sub}]...
[ "def", "_su_scripts_regex", "(", "self", ")", ":", "sups", "=", "re", ".", "escape", "(", "''", ".", "join", "(", "[", "k", "for", "k", "in", "self", ".", "superscripts", ".", "keys", "(", ")", "]", ")", ")", "subs", "=", "re", ".", "escape", "...
:return: [compiled regex, function]
[ ":", "return", ":", "[", "compiled", "regex", "function", "]" ]
train
https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L671-L696
kiwi0fruit/sugartex
sugartex/sugartex_filter.py
SugarTeX._local_map
def _local_map(match, loc: str = 'lr') -> list: """ :param match: :param loc: str "l" or "r" or "lr" turns on/off left/right local area calculation :return: list list of the same size as the string + 2 it's the local map that counted { and ...
python
def _local_map(match, loc: str = 'lr') -> list: """ :param match: :param loc: str "l" or "r" or "lr" turns on/off left/right local area calculation :return: list list of the same size as the string + 2 it's the local map that counted { and ...
[ "def", "_local_map", "(", "match", ",", "loc", ":", "str", "=", "'lr'", ")", "->", "list", ":", "s", "=", "match", ".", "string", "map_", "=", "[", "None", "]", "*", "(", "len", "(", "s", ")", "+", "2", ")", "if", "loc", "==", "'l'", "or", ...
:param match: :param loc: str "l" or "r" or "lr" turns on/off left/right local area calculation :return: list list of the same size as the string + 2 it's the local map that counted { and } list can contain: None or int>=0 from the ...
[ ":", "param", "match", ":", ":", "param", "loc", ":", "str", "l", "or", "r", "or", "lr", "turns", "on", "/", "off", "left", "/", "right", "local", "area", "calculation", ":", "return", ":", "list", "list", "of", "the", "same", "size", "as", "the", ...
train
https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L708-L753
kiwi0fruit/sugartex
sugartex/sugartex_filter.py
SugarTeX._operators_replace
def _operators_replace(self, string: str) -> str: """ Searches for first unary or binary operator (via self.op_regex that has only one group that contain operator) then replaces it (or escapes it if brackets do not match). Everything until: * space ' ' * begin...
python
def _operators_replace(self, string: str) -> str: """ Searches for first unary or binary operator (via self.op_regex that has only one group that contain operator) then replaces it (or escapes it if brackets do not match). Everything until: * space ' ' * begin...
[ "def", "_operators_replace", "(", "self", ",", "string", ":", "str", ")", "->", "str", ":", "# noinspection PyShadowingNames", "def", "replace", "(", "string", ":", "str", ",", "start", ":", "int", ",", "end", ":", "int", ",", "substring", ":", "str", ")...
Searches for first unary or binary operator (via self.op_regex that has only one group that contain operator) then replaces it (or escapes it if brackets do not match). Everything until: * space ' ' * begin/end of the string * bracket from outer scope (like '{a/b}':...
[ "Searches", "for", "first", "unary", "or", "binary", "operator", "(", "via", "self", ".", "op_regex", "that", "has", "only", "one", "group", "that", "contain", "operator", ")", "then", "replaces", "it", "(", "or", "escapes", "it", "if", "brackets", "do", ...
train
https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L755-L849
kiwi0fruit/sugartex
sugartex/sugartex_filter.py
SugarTeX.replace
def replace(self, src: str) -> str: """ Extends LaTeX syntax via regex preprocess :param src: str LaTeX string :return: str New LaTeX string """ if not self.readied: self.ready() # Brackets + simple pre replacements: sr...
python
def replace(self, src: str) -> str: """ Extends LaTeX syntax via regex preprocess :param src: str LaTeX string :return: str New LaTeX string """ if not self.readied: self.ready() # Brackets + simple pre replacements: sr...
[ "def", "replace", "(", "self", ",", "src", ":", "str", ")", "->", "str", ":", "if", "not", "self", ".", "readied", ":", "self", ".", "ready", "(", ")", "# Brackets + simple pre replacements:", "src", "=", "self", ".", "_dict_replace", "(", "self", ".", ...
Extends LaTeX syntax via regex preprocess :param src: str LaTeX string :return: str New LaTeX string
[ "Extends", "LaTeX", "syntax", "via", "regex", "preprocess", ":", "param", "src", ":", "str", "LaTeX", "string", ":", "return", ":", "str", "New", "LaTeX", "string" ]
train
https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L863-L904
christophertbrown/bioscripts
ctbBio/strip_align.py
plot_gaps
def plot_gaps(plot, columns): """ plot % of gaps at each position """ from plot_window import window_plot_convolve as plot_window # plot_window([columns], len(columns)*.01, plot) plot_window([[100 - i for i in columns]], len(columns)*.01, plot)
python
def plot_gaps(plot, columns): """ plot % of gaps at each position """ from plot_window import window_plot_convolve as plot_window # plot_window([columns], len(columns)*.01, plot) plot_window([[100 - i for i in columns]], len(columns)*.01, plot)
[ "def", "plot_gaps", "(", "plot", ",", "columns", ")", ":", "from", "plot_window", "import", "window_plot_convolve", "as", "plot_window", "#\tplot_window([columns], len(columns)*.01, plot)", "plot_window", "(", "[", "[", "100", "-", "i", "for", "i", "in", "columns", ...
plot % of gaps at each position
[ "plot", "%", "of", "gaps", "at", "each", "position" ]
train
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/strip_align.py#L11-L17
christophertbrown/bioscripts
ctbBio/strip_align.py
strip_msa_100
def strip_msa_100(msa, threshold, plot = False): """ strip out columns of a MSA that represent gaps for X percent (threshold) of sequences """ msa = [seq for seq in parse_fasta(msa)] columns = [[0, 0] for pos in msa[0][1]] # [[#bases, #gaps], [#bases, #gaps], ...] for seq in msa: for position, base in enumerate...
python
def strip_msa_100(msa, threshold, plot = False): """ strip out columns of a MSA that represent gaps for X percent (threshold) of sequences """ msa = [seq for seq in parse_fasta(msa)] columns = [[0, 0] for pos in msa[0][1]] # [[#bases, #gaps], [#bases, #gaps], ...] for seq in msa: for position, base in enumerate...
[ "def", "strip_msa_100", "(", "msa", ",", "threshold", ",", "plot", "=", "False", ")", ":", "msa", "=", "[", "seq", "for", "seq", "in", "parse_fasta", "(", "msa", ")", "]", "columns", "=", "[", "[", "0", ",", "0", "]", "for", "pos", "in", "msa", ...
strip out columns of a MSA that represent gaps for X percent (threshold) of sequences
[ "strip", "out", "columns", "of", "a", "MSA", "that", "represent", "gaps", "for", "X", "percent", "(", "threshold", ")", "of", "sequences" ]
train
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/strip_align.py#L19-L39
smdabdoub/phylotoast
bin/extract_shared_or_unique_otuids.py
sample_group
def sample_group(sid, groups): """ Iterate through all categories in an OrderedDict and return category name if SampleID present in that category. :type sid: str :param sid: SampleID from dataset. :type groups: OrderedDict :param groups: Returned dict from phylotoast.util.gather_categories...
python
def sample_group(sid, groups): """ Iterate through all categories in an OrderedDict and return category name if SampleID present in that category. :type sid: str :param sid: SampleID from dataset. :type groups: OrderedDict :param groups: Returned dict from phylotoast.util.gather_categories...
[ "def", "sample_group", "(", "sid", ",", "groups", ")", ":", "for", "name", "in", "groups", ":", "if", "sid", "in", "groups", "[", "name", "]", ".", "sids", ":", "return", "name" ]
Iterate through all categories in an OrderedDict and return category name if SampleID present in that category. :type sid: str :param sid: SampleID from dataset. :type groups: OrderedDict :param groups: Returned dict from phylotoast.util.gather_categories() function. :return type: str :re...
[ "Iterate", "through", "all", "categories", "in", "an", "OrderedDict", "and", "return", "category", "name", "if", "SampleID", "present", "in", "that", "category", "." ]
train
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/bin/extract_shared_or_unique_otuids.py#L22-L38
smdabdoub/phylotoast
bin/extract_shared_or_unique_otuids.py
combine_sets
def combine_sets(*sets): """ Combine multiple sets to create a single larger set. """ combined = set() for s in sets: combined.update(s) return combined
python
def combine_sets(*sets): """ Combine multiple sets to create a single larger set. """ combined = set() for s in sets: combined.update(s) return combined
[ "def", "combine_sets", "(", "*", "sets", ")", ":", "combined", "=", "set", "(", ")", "for", "s", "in", "sets", ":", "combined", ".", "update", "(", "s", ")", "return", "combined" ]
Combine multiple sets to create a single larger set.
[ "Combine", "multiple", "sets", "to", "create", "a", "single", "larger", "set", "." ]
train
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/bin/extract_shared_or_unique_otuids.py#L41-L48
smdabdoub/phylotoast
bin/extract_shared_or_unique_otuids.py
unique_otuids
def unique_otuids(groups): """ Get unique OTUIDs of each category. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on category name and unique OTUIDs as values. """ uniques = {key: set() for key in groups} for i, group in...
python
def unique_otuids(groups): """ Get unique OTUIDs of each category. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on category name and unique OTUIDs as values. """ uniques = {key: set() for key in groups} for i, group in...
[ "def", "unique_otuids", "(", "groups", ")", ":", "uniques", "=", "{", "key", ":", "set", "(", ")", "for", "key", "in", "groups", "}", "for", "i", ",", "group", "in", "enumerate", "(", "groups", ")", ":", "to_combine", "=", "groups", ".", "values", ...
Get unique OTUIDs of each category. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on category name and unique OTUIDs as values.
[ "Get", "unique", "OTUIDs", "of", "each", "category", "." ]
train
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/bin/extract_shared_or_unique_otuids.py#L51-L66
smdabdoub/phylotoast
bin/extract_shared_or_unique_otuids.py
shared_otuids
def shared_otuids(groups): """ Get shared OTUIDs between all unique combinations of groups. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on group combination and their shared OTUIDs as values. """ for g in sorted(groups): ...
python
def shared_otuids(groups): """ Get shared OTUIDs between all unique combinations of groups. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on group combination and their shared OTUIDs as values. """ for g in sorted(groups): ...
[ "def", "shared_otuids", "(", "groups", ")", ":", "for", "g", "in", "sorted", "(", "groups", ")", ":", "print", "(", "\"Number of OTUs in {0}: {1}\"", ".", "format", "(", "g", ",", "len", "(", "groups", "[", "g", "]", ".", "results", "[", "\"otuids\"", ...
Get shared OTUIDs between all unique combinations of groups. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on group combination and their shared OTUIDs as values.
[ "Get", "shared", "OTUIDs", "between", "all", "unique", "combinations", "of", "groups", "." ]
train
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/bin/extract_shared_or_unique_otuids.py#L69-L93
smdabdoub/phylotoast
bin/extract_shared_or_unique_otuids.py
write_uniques
def write_uniques(path, prefix, uniques): """ Given a path, the method writes out one file for each group name in the uniques dictionary with the file name in the pattern PATH/prefix_group.txt with each file containing the unique OTUIDs found when comparing that group to all the other grou...
python
def write_uniques(path, prefix, uniques): """ Given a path, the method writes out one file for each group name in the uniques dictionary with the file name in the pattern PATH/prefix_group.txt with each file containing the unique OTUIDs found when comparing that group to all the other grou...
[ "def", "write_uniques", "(", "path", ",", "prefix", ",", "uniques", ")", ":", "for", "group", "in", "uniques", ":", "fp", "=", "osp", ".", "join", "(", "path", ",", "\"{}_{}.txt\"", ".", "format", "(", "prefix", ",", "group", ")", ")", "with", "open"...
Given a path, the method writes out one file for each group name in the uniques dictionary with the file name in the pattern PATH/prefix_group.txt with each file containing the unique OTUIDs found when comparing that group to all the other groups in uniques. :type path: str :param path: O...
[ "Given", "a", "path", "the", "method", "writes", "out", "one", "file", "for", "each", "group", "name", "in", "the", "uniques", "dictionary", "with", "the", "file", "name", "in", "the", "pattern" ]
train
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/bin/extract_shared_or_unique_otuids.py#L96-L118
smdabdoub/phylotoast
phylotoast/util.py
storeFASTA
def storeFASTA(fastaFNH): """ Parse the records in a FASTA-format file by first reading the entire file into memory. :type source: path to FAST file or open file handle :param source: The data source from which to parse the FASTA records. Expects the input to resolve to a collection ...
python
def storeFASTA(fastaFNH): """ Parse the records in a FASTA-format file by first reading the entire file into memory. :type source: path to FAST file or open file handle :param source: The data source from which to parse the FASTA records. Expects the input to resolve to a collection ...
[ "def", "storeFASTA", "(", "fastaFNH", ")", ":", "fasta", "=", "file_handle", "(", "fastaFNH", ")", ".", "read", "(", ")", "return", "[", "FASTARecord", "(", "rec", "[", "0", "]", ".", "split", "(", ")", "[", "0", "]", ",", "rec", "[", "0", "]", ...
Parse the records in a FASTA-format file by first reading the entire file into memory. :type source: path to FAST file or open file handle :param source: The data source from which to parse the FASTA records. Expects the input to resolve to a collection that can be iterated through, such as ...
[ "Parse", "the", "records", "in", "a", "FASTA", "-", "format", "file", "by", "first", "reading", "the", "entire", "file", "into", "memory", "." ]
train
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L20-L34
smdabdoub/phylotoast
phylotoast/util.py
parseFASTA
def parseFASTA(fastaFNH): """ Parse the records in a FASTA-format file keeping the file open, and reading through one line at a time. :type source: path to FAST file or open file handle :param source: The data source from which to parse the FASTA records. Expects the input to res...
python
def parseFASTA(fastaFNH): """ Parse the records in a FASTA-format file keeping the file open, and reading through one line at a time. :type source: path to FAST file or open file handle :param source: The data source from which to parse the FASTA records. Expects the input to res...
[ "def", "parseFASTA", "(", "fastaFNH", ")", ":", "recs", "=", "[", "]", "seq", "=", "[", "]", "seqID", "=", "\"\"", "descr", "=", "\"\"", "for", "line", "in", "file_handle", "(", "fastaFNH", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "...
Parse the records in a FASTA-format file keeping the file open, and reading through one line at a time. :type source: path to FAST file or open file handle :param source: The data source from which to parse the FASTA records. Expects the input to resolve to a collection that can be itera...
[ "Parse", "the", "records", "in", "a", "FASTA", "-", "format", "file", "keeping", "the", "file", "open", "and", "reading", "through", "one", "line", "at", "a", "time", "." ]
train
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L37-L73
smdabdoub/phylotoast
phylotoast/util.py
parse_map_file
def parse_map_file(mapFNH): """ Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID (default) or a user-supplied one. The only required fields are SampleID, BarcodeSequence, LinkerPrimerSequence (in that order), and Description (which must be the final field). :...
python
def parse_map_file(mapFNH): """ Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID (default) or a user-supplied one. The only required fields are SampleID, BarcodeSequence, LinkerPrimerSequence (in that order), and Description (which must be the final field). :...
[ "def", "parse_map_file", "(", "mapFNH", ")", ":", "m", "=", "OrderedDict", "(", ")", "map_header", "=", "None", "with", "file_handle", "(", "mapFNH", ")", "as", "mapF", ":", "for", "line", "in", "mapF", ":", "if", "line", ".", "startswith", "(", "\"#Sa...
Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID (default) or a user-supplied one. The only required fields are SampleID, BarcodeSequence, LinkerPrimerSequence (in that order), and Description (which must be the final field). :type mapFNH: str :param mapFNH: Eith...
[ "Opens", "a", "QIIME", "mapping", "file", "and", "stores", "the", "contents", "in", "a", "dictionary", "keyed", "on", "SampleID", "(", "default", ")", "or", "a", "user", "-", "supplied", "one", ".", "The", "only", "required", "fields", "are", "SampleID", ...
train
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L76-L108