repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
thespacedoctor/polyglot
polyglot/markdown/translate.py
translate.header
def header( self, text, level): """*convert plain-text to MMD header* **Key Arguments:** - ``text`` -- the text to convert to MMD header - ``level`` -- the header level to convert the text to **Return:** - ``header`` -- th...
python
def header( self, text, level): """*convert plain-text to MMD header* **Key Arguments:** - ``text`` -- the text to convert to MMD header - ``level`` -- the header level to convert the text to **Return:** - ``header`` -- th...
[ "def", "header", "(", "self", ",", "text", ",", "level", ")", ":", "m", "=", "self", ".", "reWS", ".", "match", "(", "text", ")", "prefix", "=", "m", ".", "group", "(", "1", ")", "text", "=", "m", ".", "group", "(", "2", ")", "suffix", "=", ...
*convert plain-text to MMD header* **Key Arguments:** - ``text`` -- the text to convert to MMD header - ``level`` -- the header level to convert the text to **Return:** - ``header`` -- the MMD header **Usage:** To convert a text MMD header: ...
[ "*", "convert", "plain", "-", "text", "to", "MMD", "header", "*" ]
98038d746aa67e343b73b3ccee1e02d31dab81ec
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/markdown/translate.py#L461-L493
train
convert plain - text to MMD header
thespacedoctor/polyglot
polyglot/markdown/translate.py
translate.definition
def definition( self, text, definition): """*genarate a MMD definition* **Key Arguments:** - ``text`` -- the text to define - ``definition`` -- the definition **Return:** - ``definition`` -- the MMD style definition ...
python
def definition( self, text, definition): """*genarate a MMD definition* **Key Arguments:** - ``text`` -- the text to define - ``definition`` -- the definition **Return:** - ``definition`` -- the MMD style definition ...
[ "def", "definition", "(", "self", ",", "text", ",", "definition", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "definition", "=", "definition", ".", "strip", "(", ")", "regex", "=", "re", ".", "compile", "(", "r'\\n(\\S)'", ")", "definition",...
*genarate a MMD definition* **Key Arguments:** - ``text`` -- the text to define - ``definition`` -- the definition **Return:** - ``definition`` -- the MMD style definition **Usage:** To genarate a MMD definition: .. code-block:: py...
[ "*", "genarate", "a", "MMD", "definition", "*" ]
98038d746aa67e343b73b3ccee1e02d31dab81ec
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/markdown/translate.py#L495-L531
train
This function generates a MMD definition for the specified entry in the specified text.
thespacedoctor/polyglot
polyglot/markdown/translate.py
translate.headerLink
def headerLink( self, headerText, text=False): """*generate a link to a MMD header* **Key Arguments:** - ``headerText`` -- the header text (or anchor tag) - ``text`` -- the doc text to link. Default *False* **Return:** - `...
python
def headerLink( self, headerText, text=False): """*generate a link to a MMD header* **Key Arguments:** - ``headerText`` -- the header text (or anchor tag) - ``text`` -- the doc text to link. Default *False* **Return:** - `...
[ "def", "headerLink", "(", "self", ",", "headerText", ",", "text", "=", "False", ")", ":", "headerText", "=", "headerText", ".", "strip", "(", ")", "if", "text", ":", "return", "self", ".", "_surround", "(", "text", ",", "\"[\"", ",", "\"][%(headerText)s]...
*generate a link to a MMD header* **Key Arguments:** - ``headerText`` -- the header text (or anchor tag) - ``text`` -- the doc text to link. Default *False* **Return:** - ``link`` -- the link to the header **Usage:** To generate a MMD header li...
[ "*", "generate", "a", "link", "to", "a", "MMD", "header", "*" ]
98038d746aa67e343b73b3ccee1e02d31dab81ec
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/markdown/translate.py#L533-L564
train
generate a link to a header in a MMD
thespacedoctor/polyglot
polyglot/markdown/translate.py
translate.image
def image( self, url, title="", width=800): """*create MMD image link* **Key Arguments:** - ``title`` -- the title for the image - ``url`` -- the image URL - ``width`` -- the width in pixels of the image. Default *800* ...
python
def image( self, url, title="", width=800): """*create MMD image link* **Key Arguments:** - ``title`` -- the title for the image - ``url`` -- the image URL - ``width`` -- the width in pixels of the image. Default *800* ...
[ "def", "image", "(", "self", ",", "url", ",", "title", "=", "\"\"", ",", "width", "=", "800", ")", ":", "title", "=", "title", ".", "strip", "(", ")", "caption", "=", "title", "now", "=", "datetime", ".", "now", "(", ")", "figId", "=", "now", "...
*create MMD image link* **Key Arguments:** - ``title`` -- the title for the image - ``url`` -- the image URL - ``width`` -- the width in pixels of the image. Default *800* **Return:** - ``imageLink`` -- the MMD image link **Usage:** ...
[ "*", "create", "MMD", "image", "link", "*" ]
98038d746aa67e343b73b3ccee1e02d31dab81ec
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/markdown/translate.py#L566-L610
train
create an image link for a specific object
thespacedoctor/polyglot
polyglot/markdown/translate.py
translate.blockquote
def blockquote( self, text): """*convert plain-text to MMD blockquote* **Key Arguments:** - ``text`` -- the text to convert to MMD blockquote **Return:** - ``blockquote`` -- the MMD blockquote **Usage:** To convert a text to...
python
def blockquote( self, text): """*convert plain-text to MMD blockquote* **Key Arguments:** - ``text`` -- the text to convert to MMD blockquote **Return:** - ``blockquote`` -- the MMD blockquote **Usage:** To convert a text to...
[ "def", "blockquote", "(", "self", ",", "text", ")", ":", "m", "=", "self", ".", "reWS", ".", "match", "(", "text", ")", "return", "\"\\n> \"", "+", "(", "\"\\n> \"", ")", ".", "join", "(", "m", ".", "group", "(", "2", ")", ".", "split", "(", "\...
*convert plain-text to MMD blockquote* **Key Arguments:** - ``text`` -- the text to convert to MMD blockquote **Return:** - ``blockquote`` -- the MMD blockquote **Usage:** To convert a text to a MMD blockquote: .. code-block:: python ...
[ "*", "convert", "plain", "-", "text", "to", "MMD", "blockquote", "*" ]
98038d746aa67e343b73b3ccee1e02d31dab81ec
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/markdown/translate.py#L612-L637
train
convert plain - text to MMD blockquote
thespacedoctor/polyglot
polyglot/markdown/translate.py
translate.ul
def ul( self, text): """*convert plain-text to MMD unordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD unordered list **Return:** - ``ul`` -- the MMD unordered list **Usage:** To convert text to a MMD...
python
def ul( self, text): """*convert plain-text to MMD unordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD unordered list **Return:** - ``ul`` -- the MMD unordered list **Usage:** To convert text to a MMD...
[ "def", "ul", "(", "self", ",", "text", ")", ":", "m", "=", "self", ".", "reWS", ".", "match", "(", "text", ")", "ul", "=", "[", "]", "for", "l", "in", "m", ".", "group", "(", "2", ")", ".", "split", "(", "\"\\n\"", ")", ":", "prefix", ",", ...
*convert plain-text to MMD unordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD unordered list **Return:** - ``ul`` -- the MMD unordered list **Usage:** To convert text to a MMD unordered list: .. code-block:: python ...
[ "*", "convert", "plain", "-", "text", "to", "MMD", "unordered", "list", "*" ]
98038d746aa67e343b73b3ccee1e02d31dab81ec
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/markdown/translate.py#L639-L669
train
convert plain - text to MMD unordered list
thespacedoctor/polyglot
polyglot/markdown/translate.py
translate.ol
def ol( self, text): """*convert plain-text to MMD ordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD ordered list **Return:** - ``ol`` -- the MMD ordered list **Usage:** To convert text to MMD ordered...
python
def ol( self, text): """*convert plain-text to MMD ordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD ordered list **Return:** - ``ol`` -- the MMD ordered list **Usage:** To convert text to MMD ordered...
[ "def", "ol", "(", "self", ",", "text", ")", ":", "m", "=", "self", ".", "reWS", ".", "match", "(", "text", ")", "ol", "=", "[", "]", "for", "thisIndex", ",", "l", "in", "enumerate", "(", "m", ".", "group", "(", "2", ")", ".", "split", "(", ...
*convert plain-text to MMD ordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD ordered list **Return:** - ``ol`` -- the MMD ordered list **Usage:** To convert text to MMD ordered list: .. code-block:: python ...
[ "*", "convert", "plain", "-", "text", "to", "MMD", "ordered", "list", "*" ]
98038d746aa67e343b73b3ccee1e02d31dab81ec
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/markdown/translate.py#L671-L702
train
convert plain - text to MMD ordered list
thespacedoctor/polyglot
polyglot/markdown/translate.py
translate.codeblock
def codeblock( self, text, lang=""): """*convert plain-text to MMD fenced codeblock* **Key Arguments:** - ``text`` -- the text to convert to MMD fenced codeblock - ``lang`` -- the code language for syntax highlighting. Default *''* **...
python
def codeblock( self, text, lang=""): """*convert plain-text to MMD fenced codeblock* **Key Arguments:** - ``text`` -- the text to convert to MMD fenced codeblock - ``lang`` -- the code language for syntax highlighting. Default *''* **...
[ "def", "codeblock", "(", "self", ",", "text", ",", "lang", "=", "\"\"", ")", ":", "reRemoveNewline", "=", "re", ".", "compile", "(", "r'^(\\s*\\n)?([^\\n].*?)\\s*$'", ",", "re", ".", "S", ")", "m", "=", "reRemoveNewline", ".", "match", "(", "text", ")", ...
*convert plain-text to MMD fenced codeblock* **Key Arguments:** - ``text`` -- the text to convert to MMD fenced codeblock - ``lang`` -- the code language for syntax highlighting. Default *''* **Return:** - ``text`` -- the MMD fenced codeblock **Usage:** ...
[ "*", "convert", "plain", "-", "text", "to", "MMD", "fenced", "codeblock", "*" ]
98038d746aa67e343b73b3ccee1e02d31dab81ec
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/markdown/translate.py#L704-L735
train
convert plain - text to MMD fenced codeblock
thespacedoctor/polyglot
polyglot/markdown/translate.py
translate.inline_link
def inline_link( self, text, url): """*generate a MMD sytle link* **Key Arguments:** - ``text`` -- the text to link from - ``url`` -- the url to link to **Return:** - ``text`` -- the linked text **Usage:** ...
python
def inline_link( self, text, url): """*generate a MMD sytle link* **Key Arguments:** - ``text`` -- the text to link from - ``url`` -- the url to link to **Return:** - ``text`` -- the linked text **Usage:** ...
[ "def", "inline_link", "(", "self", ",", "text", ",", "url", ")", ":", "m", "=", "self", ".", "reWS", ".", "match", "(", "text", ")", "prefix", "=", "m", ".", "group", "(", "1", ")", "text", "=", "m", ".", "group", "(", "2", ")", "suffix", "="...
*generate a MMD sytle link* **Key Arguments:** - ``text`` -- the text to link from - ``url`` -- the url to link to **Return:** - ``text`` -- the linked text **Usage:** To convert a text and url to MMD link: .. code-block:: python ...
[ "*", "generate", "a", "MMD", "sytle", "link", "*" ]
98038d746aa67e343b73b3ccee1e02d31dab81ec
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/markdown/translate.py#L737-L770
train
inline_link - inline a MMD sytle link from a text and url
thespacedoctor/polyglot
polyglot/markdown/translate.py
translate._snip_whitespace
def _snip_whitespace( self, text): """*snip the whitespace at the start and end of the text* **Key Arguments:** - ``text`` -- the text to snip **Return:** - ``prefix``, ``text``, ``suffix`` -- the starting whitespace, text and endding whitespace ...
python
def _snip_whitespace( self, text): """*snip the whitespace at the start and end of the text* **Key Arguments:** - ``text`` -- the text to snip **Return:** - ``prefix``, ``text``, ``suffix`` -- the starting whitespace, text and endding whitespace ...
[ "def", "_snip_whitespace", "(", "self", ",", "text", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_snip_whitespace`` method'", ")", "m", "=", "self", ".", "reWS", ".", "match", "(", "text", ")", "prefix", "=", "m", ".", "group", "(",...
*snip the whitespace at the start and end of the text* **Key Arguments:** - ``text`` -- the text to snip **Return:** - ``prefix``, ``text``, ``suffix`` -- the starting whitespace, text and endding whitespace
[ "*", "snip", "the", "whitespace", "at", "the", "start", "and", "end", "of", "the", "text", "*" ]
98038d746aa67e343b73b3ccee1e02d31dab81ec
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/markdown/translate.py#L772-L792
train
snip the whitespace at the start and end of the text
thespacedoctor/polyglot
polyglot/markdown/translate.py
translate._surround
def _surround( self, text, left, right): """*surround text with given characters* **Key Arguments:** - ``text`` -- the text to surround. - ``left`` -- characters to the left of text - ``right`` -- characters to the righ...
python
def _surround( self, text, left, right): """*surround text with given characters* **Key Arguments:** - ``text`` -- the text to surround. - ``left`` -- characters to the left of text - ``right`` -- characters to the righ...
[ "def", "_surround", "(", "self", ",", "text", ",", "left", ",", "right", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_surround`` method'", ")", "prefix", ",", "text", ",", "suffix", "=", "self", ".", "_snip_whitespace", "(", "text", ...
*surround text with given characters* **Key Arguments:** - ``text`` -- the text to surround. - ``left`` -- characters to the left of text - ``right`` -- characters to the right of text **Return:** - ``text`` -- the surronded text
[ "*", "surround", "text", "with", "given", "characters", "*" ]
98038d746aa67e343b73b3ccee1e02d31dab81ec
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/markdown/translate.py#L794-L819
train
surround text with given characters
TkTech/Jawa
jawa/util/shell.py
start_shell
def start_shell(local_ns: Dict=None, banner: str=''): """Create and immediately drop into a Python shell. If IPython version 5 or greater is available it will be used instead of the built-in python shell. :param local_ns: An optional dict containing the global namespace of the n...
python
def start_shell(local_ns: Dict=None, banner: str=''): """Create and immediately drop into a Python shell. If IPython version 5 or greater is available it will be used instead of the built-in python shell. :param local_ns: An optional dict containing the global namespace of the n...
[ "def", "start_shell", "(", "local_ns", ":", "Dict", "=", "None", ",", "banner", ":", "str", "=", "''", ")", ":", "if", "IPYTHON_SHELL_AVAILABLE", ":", "# Don't try to stop IPython from displaying its banner, since", "# it's different in every major version", "terminal", "...
Create and immediately drop into a Python shell. If IPython version 5 or greater is available it will be used instead of the built-in python shell. :param local_ns: An optional dict containing the global namespace of the newly created shell. :param banner: An optional banner to ...
[ "Create", "and", "immediately", "drop", "into", "a", "Python", "shell", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/shell.py#L13-L29
train
Create and immediately drop into a Python shell.
TkTech/Jawa
jawa/transforms.py
expand_constants
def expand_constants(ins: Instruction, *, cf) -> Instruction: """Replace CONSTANT_INDEX operands with the literal Constant object from the constant pool. :param ins: Instruction to potentially modify. :param cf: The ClassFile instance used to resolve Constants. :return: Potentially modified instruc...
python
def expand_constants(ins: Instruction, *, cf) -> Instruction: """Replace CONSTANT_INDEX operands with the literal Constant object from the constant pool. :param ins: Instruction to potentially modify. :param cf: The ClassFile instance used to resolve Constants. :return: Potentially modified instruc...
[ "def", "expand_constants", "(", "ins", ":", "Instruction", ",", "*", ",", "cf", ")", "->", "Instruction", ":", "for", "i", ",", "operand", "in", "enumerate", "(", "ins", ".", "operands", ")", ":", "if", "not", "isinstance", "(", "operand", ",", "Operan...
Replace CONSTANT_INDEX operands with the literal Constant object from the constant pool. :param ins: Instruction to potentially modify. :param cf: The ClassFile instance used to resolve Constants. :return: Potentially modified instruction.
[ "Replace", "CONSTANT_INDEX", "operands", "with", "the", "literal", "Constant", "object", "from", "the", "constant", "pool", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/transforms.py#L9-L24
train
Replace CONSTANT_INDEX operands with the literal Constant object from the constant pool.
TkTech/Jawa
jawa/transforms.py
simple_swap
def simple_swap(ins: Instruction) -> Instruction: """Replaces one instruction with another based on the transform rules in the bytecode definitions. This can help simplify your code as it reduces the overall number of instructions. For example, `aload_0` will become `aload 0`. :param ins: Instructi...
python
def simple_swap(ins: Instruction) -> Instruction: """Replaces one instruction with another based on the transform rules in the bytecode definitions. This can help simplify your code as it reduces the overall number of instructions. For example, `aload_0` will become `aload 0`. :param ins: Instructi...
[ "def", "simple_swap", "(", "ins", ":", "Instruction", ")", "->", "Instruction", ":", "try", ":", "rule", "=", "ins", ".", "details", "[", "'transform'", "]", "[", "'simple_swap'", "]", "except", "KeyError", ":", "return", "ins", "replacement_ins", "=", "op...
Replaces one instruction with another based on the transform rules in the bytecode definitions. This can help simplify your code as it reduces the overall number of instructions. For example, `aload_0` will become `aload 0`. :param ins: Instruction to potentially modify. :return: Potentially modifi...
[ "Replaces", "one", "instruction", "with", "another", "based", "on", "the", "transform", "rules", "in", "the", "bytecode", "definitions", ".", "This", "can", "help", "simplify", "your", "code", "as", "it", "reduces", "the", "overall", "number", "of", "instructi...
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/transforms.py#L27-L51
train
Replaces one instruction with another based on the transform rules in .
samastur/Impostor
impostor/backend.py
find_request
def find_request(): ''' Inspect running environment for request object. There should be one, but don't rely on it. ''' frame = inspect.currentframe() request = None f = frame while not request and f: if 'request' in f.f_locals and isinstance(f.f_locals['request'], HttpRequest): request = f.f_locals['reque...
python
def find_request(): ''' Inspect running environment for request object. There should be one, but don't rely on it. ''' frame = inspect.currentframe() request = None f = frame while not request and f: if 'request' in f.f_locals and isinstance(f.f_locals['request'], HttpRequest): request = f.f_locals['reque...
[ "def", "find_request", "(", ")", ":", "frame", "=", "inspect", ".", "currentframe", "(", ")", "request", "=", "None", "f", "=", "frame", "while", "not", "request", "and", "f", ":", "if", "'request'", "in", "f", ".", "f_locals", "and", "isinstance", "("...
Inspect running environment for request object. There should be one, but don't rely on it.
[ "Inspect", "running", "environment", "for", "request", "object", ".", "There", "should", "be", "one", "but", "don", "t", "rely", "on", "it", "." ]
1a9b1cf1568d5d657b069af5fdf882f2d9bfefce
https://github.com/samastur/Impostor/blob/1a9b1cf1568d5d657b069af5fdf882f2d9bfefce/impostor/backend.py#L15-L30
train
Find the request object that is currently running.
mardix/pylot
pylot/component/views.py
with_user_roles
def with_user_roles(roles): """ with_user_roles(roles) It allows to check if a user has access to a view by adding the decorator with_user_roles([]) Requires flask-login In your model, you must have a property 'role', which will be invoked to be compared to the roles provided. If cur...
python
def with_user_roles(roles): """ with_user_roles(roles) It allows to check if a user has access to a view by adding the decorator with_user_roles([]) Requires flask-login In your model, you must have a property 'role', which will be invoked to be compared to the roles provided. If cur...
[ "def", "with_user_roles", "(", "roles", ")", ":", "def", "wrapper", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "current_user", ".", "is_authenticated...
with_user_roles(roles) It allows to check if a user has access to a view by adding the decorator with_user_roles([]) Requires flask-login In your model, you must have a property 'role', which will be invoked to be compared to the roles provided. If current_user doesn't have a role, it will t...
[ "with_user_roles", "(", "roles", ")" ]
506a33a56ebdfc0925b94015e8cf98ccb16a143c
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/component/views.py#L101-L139
train
Decorator to add a decorator to check if a user has access to a page.
mardix/pylot
pylot/component/views.py
user_admin_view
def user_admin_view(model, login_view="Login", template_dir=None): """ :param UserStruct: The User model structure containing other classes :param login_view: The login view interface :param template_dir: The directory containing the view pages :return: UserAdmin Doc: User Admin is a view t...
python
def user_admin_view(model, login_view="Login", template_dir=None): """ :param UserStruct: The User model structure containing other classes :param login_view: The login view interface :param template_dir: The directory containing the view pages :return: UserAdmin Doc: User Admin is a view t...
[ "def", "user_admin_view", "(", "model", ",", "login_view", "=", "\"Login\"", ",", "template_dir", "=", "None", ")", ":", "Pylot", ".", "context_", "(", "COMPONENT_USER_ADMIN", "=", "True", ")", "User", "=", "model", ".", "UserStruct", ".", "User", "LoginView...
:param UserStruct: The User model structure containing other classes :param login_view: The login view interface :param template_dir: The directory containing the view pages :return: UserAdmin Doc: User Admin is a view that allows you to admin users. You must create a Pylot view called `UserAdm...
[ ":", "param", "UserStruct", ":", "The", "User", "model", "structure", "containing", "other", "classes", ":", "param", "login_view", ":", "The", "login", "view", "interface", ":", "param", "template_dir", ":", "The", "directory", "containing", "the", "view", "p...
506a33a56ebdfc0925b94015e8cf98ccb16a143c
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/component/views.py#L1080-L1254
train
A function that creates a user admin view that allows you to admin users.
mardix/pylot
pylot/component/views.py
post_manager_view
def post_manager_view(model, view="PostManager", template_dir=None): """ :param PostStruct: """ PostStruct = model.PostStruct Pylot.context_(COMPONENT_POST_MANAGER=True) if not template_dir: template_dir = "Pylot/PostManager" template_page = template_dir + "/%s.html" class Po...
python
def post_manager_view(model, view="PostManager", template_dir=None): """ :param PostStruct: """ PostStruct = model.PostStruct Pylot.context_(COMPONENT_POST_MANAGER=True) if not template_dir: template_dir = "Pylot/PostManager" template_page = template_dir + "/%s.html" class Po...
[ "def", "post_manager_view", "(", "model", ",", "view", "=", "\"PostManager\"", ",", "template_dir", "=", "None", ")", ":", "PostStruct", "=", "model", ".", "PostStruct", "Pylot", ".", "context_", "(", "COMPONENT_POST_MANAGER", "=", "True", ")", "if", "not", ...
:param PostStruct:
[ ":", "param", "PostStruct", ":" ]
506a33a56ebdfc0925b94015e8cf98ccb16a143c
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/component/views.py#L1257-L1582
train
A view that returns a single object that can be used to view posts in a single page.
mardix/pylot
pylot/component/views.py
maintenance_view
def maintenance_view(template=None): """ Create the Maintenance view Must be instantiated import maintenance_view MaintenanceView = maintenance_view() :param view_template: The directory containing the view pages :return: """ if not template: template = "Pylot/Maintenance/i...
python
def maintenance_view(template=None): """ Create the Maintenance view Must be instantiated import maintenance_view MaintenanceView = maintenance_view() :param view_template: The directory containing the view pages :return: """ if not template: template = "Pylot/Maintenance/i...
[ "def", "maintenance_view", "(", "template", "=", "None", ")", ":", "if", "not", "template", ":", "template", "=", "\"Pylot/Maintenance/index.html\"", "class", "Maintenance", "(", "Pylot", ")", ":", "@", "classmethod", "def", "register", "(", "cls", ",", "app",...
Create the Maintenance view Must be instantiated import maintenance_view MaintenanceView = maintenance_view() :param view_template: The directory containing the view pages :return:
[ "Create", "the", "Maintenance", "view", "Must", "be", "instantiated" ]
506a33a56ebdfc0925b94015e8cf98ccb16a143c
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/component/views.py#L1653-L1676
train
Create the Maintenance view
mardix/pylot
pylot/component/views.py
error_view
def error_view(template_dir=None): """ Create the Error view Must be instantiated import error_view ErrorView = error_view() :param template_dir: The directory containing the view pages :return: """ if not template_dir: template_dir = "Pylot/Error" template_page = "%s/...
python
def error_view(template_dir=None): """ Create the Error view Must be instantiated import error_view ErrorView = error_view() :param template_dir: The directory containing the view pages :return: """ if not template_dir: template_dir = "Pylot/Error" template_page = "%s/...
[ "def", "error_view", "(", "template_dir", "=", "None", ")", ":", "if", "not", "template_dir", ":", "template_dir", "=", "\"Pylot/Error\"", "template_page", "=", "\"%s/index.html\"", "%", "template_dir", "class", "Error", "(", "Pylot", ")", ":", "\"\"\"\n Er...
Create the Error view Must be instantiated import error_view ErrorView = error_view() :param template_dir: The directory containing the view pages :return:
[ "Create", "the", "Error", "view", "Must", "be", "instantiated" ]
506a33a56ebdfc0925b94015e8cf98ccb16a143c
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/component/views.py#L1680-L1733
train
Create the Error view
mardix/pylot
pylot/component/views.py
nl2br
def nl2br(s): """ {{ s|nl2br }} Convert newlines into <p> and <br />s. """ if not isinstance(s, basestring): s = str(s) s = re.sub(r'\r\n|\r|\n', '\n', s) paragraphs = re.split('\n{2,}', s) paragraphs = ['<p>%s</p>' % p.strip().replace('\n', '<br />') for p in paragraphs] re...
python
def nl2br(s): """ {{ s|nl2br }} Convert newlines into <p> and <br />s. """ if not isinstance(s, basestring): s = str(s) s = re.sub(r'\r\n|\r|\n', '\n', s) paragraphs = re.split('\n{2,}', s) paragraphs = ['<p>%s</p>' % p.strip().replace('\n', '<br />') for p in paragraphs] re...
[ "def", "nl2br", "(", "s", ")", ":", "if", "not", "isinstance", "(", "s", ",", "basestring", ")", ":", "s", "=", "str", "(", "s", ")", "s", "=", "re", ".", "sub", "(", "r'\\r\\n|\\r|\\n'", ",", "'\\n'", ",", "s", ")", "paragraphs", "=", "re", "....
{{ s|nl2br }} Convert newlines into <p> and <br />s.
[ "{{", "s|nl2br", "}}" ]
506a33a56ebdfc0925b94015e8cf98ccb16a143c
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/component/views.py#L1757-L1768
train
Convert newlines into <p > and <br />s.
mardix/pylot
pylot/component/views.py
StorageUploadView.sign_s3_upload
def sign_s3_upload(self): """ Allow to create Signed object to upload to S3 via JS """ AWS_ACCESS_KEY = self.config_('AWS_ACCESS_KEY_ID') AWS_SECRET_KEY = self.config_('AWS_SECRET_ACCESS_KEY') S3_BUCKET = self.config_('AWS_S3_BUCKET_NAME') object_name = request.a...
python
def sign_s3_upload(self): """ Allow to create Signed object to upload to S3 via JS """ AWS_ACCESS_KEY = self.config_('AWS_ACCESS_KEY_ID') AWS_SECRET_KEY = self.config_('AWS_SECRET_ACCESS_KEY') S3_BUCKET = self.config_('AWS_S3_BUCKET_NAME') object_name = request.a...
[ "def", "sign_s3_upload", "(", "self", ")", ":", "AWS_ACCESS_KEY", "=", "self", ".", "config_", "(", "'AWS_ACCESS_KEY_ID'", ")", "AWS_SECRET_KEY", "=", "self", ".", "config_", "(", "'AWS_SECRET_ACCESS_KEY'", ")", "S3_BUCKET", "=", "self", ".", "config_", "(", "...
Allow to create Signed object to upload to S3 via JS
[ "Allow", "to", "create", "Signed", "object", "to", "upload", "to", "S3", "via", "JS" ]
506a33a56ebdfc0925b94015e8cf98ccb16a143c
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/component/views.py#L148-L167
train
Create a signed object to S3
mardix/pylot
pylot/component/model.py
post_struct
def post_struct(UserStruct): """ Post Model """ db = UserStruct.User.db class SlugNameMixin(object): name = db.Column(db.String(250)) slug = db.Column(db.String(250), index=True, unique=True) @classmethod def get_by_slug(cls, slug): """ Ret...
python
def post_struct(UserStruct): """ Post Model """ db = UserStruct.User.db class SlugNameMixin(object): name = db.Column(db.String(250)) slug = db.Column(db.String(250), index=True, unique=True) @classmethod def get_by_slug(cls, slug): """ Ret...
[ "def", "post_struct", "(", "UserStruct", ")", ":", "db", "=", "UserStruct", ".", "User", ".", "db", "class", "SlugNameMixin", "(", "object", ")", ":", "name", "=", "db", ".", "Column", "(", "db", ".", "String", "(", "250", ")", ")", "slug", "=", "d...
Post Model
[ "Post", "Model" ]
506a33a56ebdfc0925b94015e8cf98ccb16a143c
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/component/model.py#L337-L584
train
Return a new post model that represents the user s post.
mezz64/pyEmby
pyemby/server.py
EmbyServer.add_new_devices_callback
def add_new_devices_callback(self, callback): """Register as callback for when new devices are added. """ self._new_devices_callbacks.append(callback) _LOGGER.debug('Added new devices callback to %s', callback)
python
def add_new_devices_callback(self, callback): """Register as callback for when new devices are added. """ self._new_devices_callbacks.append(callback) _LOGGER.debug('Added new devices callback to %s', callback)
[ "def", "add_new_devices_callback", "(", "self", ",", "callback", ")", ":", "self", ".", "_new_devices_callbacks", ".", "append", "(", "callback", ")", "_LOGGER", ".", "debug", "(", "'Added new devices callback to %s'", ",", "callback", ")" ]
Register as callback for when new devices are added.
[ "Register", "as", "callback", "for", "when", "new", "devices", "are", "added", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L114-L117
train
Register as callback for when new devices are added.
mezz64/pyEmby
pyemby/server.py
EmbyServer._do_new_devices_callback
def _do_new_devices_callback(self, msg): """Call registered callback functions.""" for callback in self._new_devices_callbacks: _LOGGER.debug('Devices callback %s', callback) self._event_loop.call_soon(callback, msg)
python
def _do_new_devices_callback(self, msg): """Call registered callback functions.""" for callback in self._new_devices_callbacks: _LOGGER.debug('Devices callback %s', callback) self._event_loop.call_soon(callback, msg)
[ "def", "_do_new_devices_callback", "(", "self", ",", "msg", ")", ":", "for", "callback", "in", "self", ".", "_new_devices_callbacks", ":", "_LOGGER", ".", "debug", "(", "'Devices callback %s'", ",", "callback", ")", "self", ".", "_event_loop", ".", "call_soon", ...
Call registered callback functions.
[ "Call", "registered", "callback", "functions", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L119-L123
train
Call registered callback functions.
mezz64/pyEmby
pyemby/server.py
EmbyServer.add_stale_devices_callback
def add_stale_devices_callback(self, callback): """Register as callback for when stale devices exist. """ self._stale_devices_callbacks.append(callback) _LOGGER.debug('Added stale devices callback to %s', callback)
python
def add_stale_devices_callback(self, callback): """Register as callback for when stale devices exist. """ self._stale_devices_callbacks.append(callback) _LOGGER.debug('Added stale devices callback to %s', callback)
[ "def", "add_stale_devices_callback", "(", "self", ",", "callback", ")", ":", "self", ".", "_stale_devices_callbacks", ".", "append", "(", "callback", ")", "_LOGGER", ".", "debug", "(", "'Added stale devices callback to %s'", ",", "callback", ")" ]
Register as callback for when stale devices exist.
[ "Register", "as", "callback", "for", "when", "stale", "devices", "exist", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L125-L128
train
Register as callback for when stale devices exist.
mezz64/pyEmby
pyemby/server.py
EmbyServer._do_stale_devices_callback
def _do_stale_devices_callback(self, msg): """Call registered callback functions.""" for callback in self._stale_devices_callbacks: _LOGGER.debug('Stale Devices callback %s', callback) self._event_loop.call_soon(callback, msg)
python
def _do_stale_devices_callback(self, msg): """Call registered callback functions.""" for callback in self._stale_devices_callbacks: _LOGGER.debug('Stale Devices callback %s', callback) self._event_loop.call_soon(callback, msg)
[ "def", "_do_stale_devices_callback", "(", "self", ",", "msg", ")", ":", "for", "callback", "in", "self", ".", "_stale_devices_callbacks", ":", "_LOGGER", ".", "debug", "(", "'Stale Devices callback %s'", ",", "callback", ")", "self", ".", "_event_loop", ".", "ca...
Call registered callback functions.
[ "Call", "registered", "callback", "functions", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L130-L134
train
Call registered callback functions.
mezz64/pyEmby
pyemby/server.py
EmbyServer.add_update_callback
def add_update_callback(self, callback, device): """Register as callback for when a matching device changes.""" self._update_callbacks.append([callback, device]) _LOGGER.debug('Added update callback to %s on %s', callback, device)
python
def add_update_callback(self, callback, device): """Register as callback for when a matching device changes.""" self._update_callbacks.append([callback, device]) _LOGGER.debug('Added update callback to %s on %s', callback, device)
[ "def", "add_update_callback", "(", "self", ",", "callback", ",", "device", ")", ":", "self", ".", "_update_callbacks", ".", "append", "(", "[", "callback", ",", "device", "]", ")", "_LOGGER", ".", "debug", "(", "'Added update callback to %s on %s'", ",", "call...
Register as callback for when a matching device changes.
[ "Register", "as", "callback", "for", "when", "a", "matching", "device", "changes", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L136-L139
train
Register as callback for when a matching device changes.
mezz64/pyEmby
pyemby/server.py
EmbyServer.remove_update_callback
def remove_update_callback(self, callback, device): """ Remove a registered update callback. """ if [callback, device] in self._update_callbacks: self._update_callbacks.remove([callback, device]) _LOGGER.debug('Removed update callback %s for %s', callbac...
python
def remove_update_callback(self, callback, device): """ Remove a registered update callback. """ if [callback, device] in self._update_callbacks: self._update_callbacks.remove([callback, device]) _LOGGER.debug('Removed update callback %s for %s', callbac...
[ "def", "remove_update_callback", "(", "self", ",", "callback", ",", "device", ")", ":", "if", "[", "callback", ",", "device", "]", "in", "self", ".", "_update_callbacks", ":", "self", ".", "_update_callbacks", ".", "remove", "(", "[", "callback", ",", "dev...
Remove a registered update callback.
[ "Remove", "a", "registered", "update", "callback", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L141-L146
train
Remove a registered update callback.
mezz64/pyEmby
pyemby/server.py
EmbyServer._do_update_callback
def _do_update_callback(self, msg): """Call registered callback functions.""" for callback, device in self._update_callbacks: if device == msg: _LOGGER.debug('Update callback %s for device %s by %s', callback, device, msg) self._e...
python
def _do_update_callback(self, msg): """Call registered callback functions.""" for callback, device in self._update_callbacks: if device == msg: _LOGGER.debug('Update callback %s for device %s by %s', callback, device, msg) self._e...
[ "def", "_do_update_callback", "(", "self", ",", "msg", ")", ":", "for", "callback", ",", "device", "in", "self", ".", "_update_callbacks", ":", "if", "device", "==", "msg", ":", "_LOGGER", ".", "debug", "(", "'Update callback %s for device %s by %s'", ",", "ca...
Call registered callback functions.
[ "Call", "registered", "callback", "functions", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L148-L154
train
Call registered callback functions.
mezz64/pyEmby
pyemby/server.py
EmbyServer.start
def start(self): """Public method for initiating connectivity with the emby server.""" asyncio.ensure_future(self.register(), loop=self._event_loop) if self._own_loop: _LOGGER.info("Starting up our own event loop.") self._event_loop.run_forever() self._event_...
python
def start(self): """Public method for initiating connectivity with the emby server.""" asyncio.ensure_future(self.register(), loop=self._event_loop) if self._own_loop: _LOGGER.info("Starting up our own event loop.") self._event_loop.run_forever() self._event_...
[ "def", "start", "(", "self", ")", ":", "asyncio", ".", "ensure_future", "(", "self", ".", "register", "(", ")", ",", "loop", "=", "self", ".", "_event_loop", ")", "if", "self", ".", "_own_loop", ":", "_LOGGER", ".", "info", "(", "\"Starting up our own ev...
Public method for initiating connectivity with the emby server.
[ "Public", "method", "for", "initiating", "connectivity", "with", "the", "emby", "server", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L156-L164
train
Public method for initiating connectivity with the emby server.
mezz64/pyEmby
pyemby/server.py
EmbyServer.stop
async def stop(self): """Async method for stopping connectivity with the emby server.""" self._shutdown = True if self.wsck: _LOGGER.info('Closing Emby server websocket.') await self.wsck.close() self.wsck = None if self._own_loop: _LOGGE...
python
async def stop(self): """Async method for stopping connectivity with the emby server.""" self._shutdown = True if self.wsck: _LOGGER.info('Closing Emby server websocket.') await self.wsck.close() self.wsck = None if self._own_loop: _LOGGE...
[ "async", "def", "stop", "(", "self", ")", ":", "self", ".", "_shutdown", "=", "True", "if", "self", ".", "wsck", ":", "_LOGGER", ".", "info", "(", "'Closing Emby server websocket.'", ")", "await", "self", ".", "wsck", ".", "close", "(", ")", "self", "....
Async method for stopping connectivity with the emby server.
[ "Async", "method", "for", "stopping", "connectivity", "with", "the", "emby", "server", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L166-L177
train
Async method for stopping connectivity with the emby server.
mezz64/pyEmby
pyemby/server.py
EmbyServer.construct_url
def construct_url(self, style): """ Return http/https or ws/wss url. """ if style is API_URL: if self._ssl: return 'https://{}:{}'.format(self._host, self._port) else: return 'http://{}:{}'.format(self._host, self._port) elif style is SOCKE...
python
def construct_url(self, style): """ Return http/https or ws/wss url. """ if style is API_URL: if self._ssl: return 'https://{}:{}'.format(self._host, self._port) else: return 'http://{}:{}'.format(self._host, self._port) elif style is SOCKE...
[ "def", "construct_url", "(", "self", ",", "style", ")", ":", "if", "style", "is", "API_URL", ":", "if", "self", ".", "_ssl", ":", "return", "'https://{}:{}'", ".", "format", "(", "self", ".", "_host", ",", "self", ".", "_port", ")", "else", ":", "ret...
Return http/https or ws/wss url.
[ "Return", "http", "/", "https", "or", "ws", "/", "wss", "url", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L179-L192
train
Construct the URL for the specified style.
mezz64/pyEmby
pyemby/server.py
EmbyServer.register
async def register(self): """Register library device id and get initial device list. """ url = '{}/Sessions'.format(self.construct_url(API_URL)) params = {'api_key': self._api_key} reg = await self.api_request(url, params) if reg is None: self._registered = False ...
python
async def register(self): """Register library device id and get initial device list. """ url = '{}/Sessions'.format(self.construct_url(API_URL)) params = {'api_key': self._api_key} reg = await self.api_request(url, params) if reg is None: self._registered = False ...
[ "async", "def", "register", "(", "self", ")", ":", "url", "=", "'{}/Sessions'", ".", "format", "(", "self", ".", "construct_url", "(", "API_URL", ")", ")", "params", "=", "{", "'api_key'", ":", "self", ".", "_api_key", "}", "reg", "=", "await", "self",...
Register library device id and get initial device list.
[ "Register", "library", "device", "id", "and", "get", "initial", "device", "list", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L194-L211
train
Register library device id and get initial device list.
mezz64/pyEmby
pyemby/server.py
EmbyServer.api_post
async def api_post(self, url, params): """Make api post request.""" post = None try: with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop): post = await self._api_session.post( url, params=params) if post.status != 204: ...
python
async def api_post(self, url, params): """Make api post request.""" post = None try: with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop): post = await self._api_session.post( url, params=params) if post.status != 204: ...
[ "async", "def", "api_post", "(", "self", ",", "url", ",", "params", ")", ":", "post", "=", "None", "try", ":", "with", "async_timeout", ".", "timeout", "(", "DEFAULT_TIMEOUT", ",", "loop", "=", "self", ".", "_event_loop", ")", ":", "post", "=", "await"...
Make api post request.
[ "Make", "api", "post", "request", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L213-L230
train
Make api post request.
mezz64/pyEmby
pyemby/server.py
EmbyServer.api_request
async def api_request(self, url, params): """Make api fetch request.""" request = None try: with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop): request = await self._api_session.get( url, params=params) if request.status...
python
async def api_request(self, url, params): """Make api fetch request.""" request = None try: with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop): request = await self._api_session.get( url, params=params) if request.status...
[ "async", "def", "api_request", "(", "self", ",", "url", ",", "params", ")", ":", "request", "=", "None", "try", ":", "with", "async_timeout", ".", "timeout", "(", "DEFAULT_TIMEOUT", ",", "loop", "=", "self", ".", "_event_loop", ")", ":", "request", "=", ...
Make api fetch request.
[ "Make", "api", "fetch", "request", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L232-L253
train
Make api fetch request.
mezz64/pyEmby
pyemby/server.py
EmbyServer.socket_connection
async def socket_connection(self): """ Open websocket connection. """ if not self._registered: _LOGGER.error('Client not registered, cannot start socket.') return url = '{}?DeviceID={}&api_key={}'.format( self.construct_url(SOCKET_URL), self._api_id, self._ap...
python
async def socket_connection(self): """ Open websocket connection. """ if not self._registered: _LOGGER.error('Client not registered, cannot start socket.') return url = '{}?DeviceID={}&api_key={}'.format( self.construct_url(SOCKET_URL), self._api_id, self._ap...
[ "async", "def", "socket_connection", "(", "self", ")", ":", "if", "not", "self", ".", "_registered", ":", "_LOGGER", ".", "error", "(", "'Client not registered, cannot start socket.'", ")", "return", "url", "=", "'{}?DeviceID={}&api_key={}'", ".", "format", "(", "...
Open websocket connection.
[ "Open", "websocket", "connection", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L255-L307
train
Open websocket connection.
mezz64/pyEmby
pyemby/server.py
EmbyServer.process_msg
def process_msg(self, msg): """Process messages from the event stream.""" jmsg = json.loads(msg) msgtype = jmsg['MessageType'] msgdata = jmsg['Data'] _LOGGER.debug('New websocket message recieved of type: %s', msgtype) if msgtype == 'Sessions': self._sessions...
python
def process_msg(self, msg): """Process messages from the event stream.""" jmsg = json.loads(msg) msgtype = jmsg['MessageType'] msgdata = jmsg['Data'] _LOGGER.debug('New websocket message recieved of type: %s', msgtype) if msgtype == 'Sessions': self._sessions...
[ "def", "process_msg", "(", "self", ",", "msg", ")", ":", "jmsg", "=", "json", ".", "loads", "(", "msg", ")", "msgtype", "=", "jmsg", "[", "'MessageType'", "]", "msgdata", "=", "jmsg", "[", "'Data'", "]", "_LOGGER", ".", "debug", "(", "'New websocket me...
Process messages from the event stream.
[ "Process", "messages", "from", "the", "event", "stream", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L309-L326
train
Process a single message from the event stream.
mezz64/pyEmby
pyemby/server.py
EmbyServer.update_device_list
def update_device_list(self, sessions): """ Update device list. """ if sessions is None: _LOGGER.error('Error updating Emby devices.') return new_devices = [] active_devices = [] dev_update = False for device in sessions: dev_name = '{...
python
def update_device_list(self, sessions): """ Update device list. """ if sessions is None: _LOGGER.error('Error updating Emby devices.') return new_devices = [] active_devices = [] dev_update = False for device in sessions: dev_name = '{...
[ "def", "update_device_list", "(", "self", ",", "sessions", ")", ":", "if", "sessions", "is", "None", ":", "_LOGGER", ".", "error", "(", "'Error updating Emby devices.'", ")", "return", "new_devices", "=", "[", "]", "active_devices", "=", "[", "]", "dev_update"...
Update device list.
[ "Update", "device", "list", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L328-L384
train
Update the list of devices.
mezz64/pyEmby
pyemby/server.py
EmbyServer.update_check
def update_check(self, existing, new): """ Check device state to see if we need to fire the callback. True if either state is 'Playing' False if both states are: 'Paused', 'Idle', or 'Off' True on any state transition. """ old_state = existing.state if 'NowPlayin...
python
def update_check(self, existing, new): """ Check device state to see if we need to fire the callback. True if either state is 'Playing' False if both states are: 'Paused', 'Idle', or 'Off' True on any state transition. """ old_state = existing.state if 'NowPlayin...
[ "def", "update_check", "(", "self", ",", "existing", ",", "new", ")", ":", "old_state", "=", "existing", ".", "state", "if", "'NowPlayingItem'", "in", "existing", ".", "session_raw", ":", "try", ":", "old_theme", "=", "existing", ".", "session_raw", "[", "...
Check device state to see if we need to fire the callback. True if either state is 'Playing' False if both states are: 'Paused', 'Idle', or 'Off' True on any state transition.
[ "Check", "device", "state", "to", "see", "if", "we", "need", "to", "fire", "the", "callback", "." ]
6bb621e4e25bf1b9b0aba2c38b588e68f8816226
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L386-L424
train
Update the state of a device.
JarryShaw/f2format
src/__main__.py
main
def main(): """Entry point for f2format.""" parser = get_parser() args = parser.parse_args() # set up variables ARCHIVE = args.archive_path archive = (not args.no_archive) os.environ['F2FORMAT_VERSION'] = args.python os.environ['F2FORMAT_ENCODING'] = args.encoding def find(root): ...
python
def main(): """Entry point for f2format.""" parser = get_parser() args = parser.parse_args() # set up variables ARCHIVE = args.archive_path archive = (not args.no_archive) os.environ['F2FORMAT_VERSION'] = args.python os.environ['F2FORMAT_ENCODING'] = args.encoding def find(root): ...
[ "def", "main", "(", ")", ":", "parser", "=", "get_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "# set up variables", "ARCHIVE", "=", "args", ".", "archive_path", "archive", "=", "(", "not", "args", ".", "no_archive", ")", "os", ...
Entry point for f2format.
[ "Entry", "point", "for", "f2format", "." ]
a144250268247ce0a98d734a26d53faadff7a6f8
https://github.com/JarryShaw/f2format/blob/a144250268247ce0a98d734a26d53faadff7a6f8/src/__main__.py#L64-L124
train
Entry point for f2format.
TkTech/Jawa
jawa/cf.py
ClassFile.create
def create(cls, this: str, super_: str=u'java/lang/Object') -> 'ClassFile': """ A utility which sets up reasonable defaults for a new public class. :param this: The name of this class. :param super_: The name of this class's superclass. """ cf = ClassFile() cf.ac...
python
def create(cls, this: str, super_: str=u'java/lang/Object') -> 'ClassFile': """ A utility which sets up reasonable defaults for a new public class. :param this: The name of this class. :param super_: The name of this class's superclass. """ cf = ClassFile() cf.ac...
[ "def", "create", "(", "cls", ",", "this", ":", "str", ",", "super_", ":", "str", "=", "u'java/lang/Object'", ")", "->", "'ClassFile'", ":", "cf", "=", "ClassFile", "(", ")", "cf", ".", "access_flags", ".", "acc_public", "=", "True", "cf", ".", "access_...
A utility which sets up reasonable defaults for a new public class. :param this: The name of this class. :param super_: The name of this class's superclass.
[ "A", "utility", "which", "sets", "up", "reasonable", "defaults", "for", "a", "new", "public", "class", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/cf.py#L97-L111
train
A utility which sets up reasonable defaults for a new public class.
TkTech/Jawa
jawa/cf.py
ClassFile.save
def save(self, source: IO): """ Saves the class to the file-like object `source`. :param source: Any file-like object providing write(). """ write = source.write write(pack( '>IHH', ClassFile.MAGIC, self.version.minor, sel...
python
def save(self, source: IO): """ Saves the class to the file-like object `source`. :param source: Any file-like object providing write(). """ write = source.write write(pack( '>IHH', ClassFile.MAGIC, self.version.minor, sel...
[ "def", "save", "(", "self", ",", "source", ":", "IO", ")", ":", "write", "=", "source", ".", "write", "write", "(", "pack", "(", "'>IHH'", ",", "ClassFile", ".", "MAGIC", ",", "self", ".", "version", ".", "minor", ",", "self", ".", "version", ".", ...
Saves the class to the file-like object `source`. :param source: Any file-like object providing write().
[ "Saves", "the", "class", "to", "the", "file", "-", "like", "object", "source", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/cf.py#L113-L141
train
Saves the class to the file - like object source.
TkTech/Jawa
jawa/cf.py
ClassFile._from_io
def _from_io(self, source: IO): """ Loads an existing JVM ClassFile from any file-like object. """ read = source.read if unpack('>I', source.read(4))[0] != ClassFile.MAGIC: raise ValueError('invalid magic number') # The version is swapped on disk to (minor, ...
python
def _from_io(self, source: IO): """ Loads an existing JVM ClassFile from any file-like object. """ read = source.read if unpack('>I', source.read(4))[0] != ClassFile.MAGIC: raise ValueError('invalid magic number') # The version is swapped on disk to (minor, ...
[ "def", "_from_io", "(", "self", ",", "source", ":", "IO", ")", ":", "read", "=", "source", ".", "read", "if", "unpack", "(", "'>I'", ",", "source", ".", "read", "(", "4", ")", ")", "[", "0", "]", "!=", "ClassFile", ".", "MAGIC", ":", "raise", "...
Loads an existing JVM ClassFile from any file-like object.
[ "Loads", "an", "existing", "JVM", "ClassFile", "from", "any", "file", "-", "like", "object", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/cf.py#L143-L170
train
Loads an existing JVM ClassFile from any file - like object.
TkTech/Jawa
jawa/cf.py
ClassFile.interfaces
def interfaces(self) -> Iterable[ConstantClass]: """ A list of direct superinterfaces of this class as indexes into the constant pool, in left-to-right order. """ return [self._constants[idx] for idx in self._interfaces]
python
def interfaces(self) -> Iterable[ConstantClass]: """ A list of direct superinterfaces of this class as indexes into the constant pool, in left-to-right order. """ return [self._constants[idx] for idx in self._interfaces]
[ "def", "interfaces", "(", "self", ")", "->", "Iterable", "[", "ConstantClass", "]", ":", "return", "[", "self", ".", "_constants", "[", "idx", "]", "for", "idx", "in", "self", ".", "_interfaces", "]" ]
A list of direct superinterfaces of this class as indexes into the constant pool, in left-to-right order.
[ "A", "list", "of", "direct", "superinterfaces", "of", "this", "class", "as", "indexes", "into", "the", "constant", "pool", "in", "left", "-", "to", "-", "right", "order", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/cf.py#L223-L228
train
A list of all the interfaces of this class in left - to - right order.
TkTech/Jawa
jawa/cf.py
ClassFile.bootstrap_methods
def bootstrap_methods(self) -> BootstrapMethod: """ Returns the bootstrap methods table from the BootstrapMethods attribute, if one exists. If it does not, one will be created. :returns: Table of `BootstrapMethod` objects. """ bootstrap = self.attributes.find_one(name='B...
python
def bootstrap_methods(self) -> BootstrapMethod: """ Returns the bootstrap methods table from the BootstrapMethods attribute, if one exists. If it does not, one will be created. :returns: Table of `BootstrapMethod` objects. """ bootstrap = self.attributes.find_one(name='B...
[ "def", "bootstrap_methods", "(", "self", ")", "->", "BootstrapMethod", ":", "bootstrap", "=", "self", ".", "attributes", ".", "find_one", "(", "name", "=", "'BootstrapMethods'", ")", "if", "bootstrap", "is", "None", ":", "bootstrap", "=", "self", ".", "attri...
Returns the bootstrap methods table from the BootstrapMethods attribute, if one exists. If it does not, one will be created. :returns: Table of `BootstrapMethod` objects.
[ "Returns", "the", "bootstrap", "methods", "table", "from", "the", "BootstrapMethods", "attribute", "if", "one", "exists", ".", "If", "it", "does", "not", "one", "will", "be", "created", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/cf.py#L231-L245
train
Returns the bootstrap methods table from the BootstrapMethods attribute.
TkTech/Jawa
jawa/cli.py
attributes
def attributes(): """List enabled Attributes. Prints a list of all enabled ClassFile Attributes. """ attribute_classes = get_attribute_classes() for name, class_ in attribute_classes.items(): click.echo( u'{name} - Added in: {ai} ({cv})'.format( name=click.style(...
python
def attributes(): """List enabled Attributes. Prints a list of all enabled ClassFile Attributes. """ attribute_classes = get_attribute_classes() for name, class_ in attribute_classes.items(): click.echo( u'{name} - Added in: {ai} ({cv})'.format( name=click.style(...
[ "def", "attributes", "(", ")", ":", "attribute_classes", "=", "get_attribute_classes", "(", ")", "for", "name", ",", "class_", "in", "attribute_classes", ".", "items", "(", ")", ":", "click", ".", "echo", "(", "u'{name} - Added in: {ai} ({cv})'", ".", "format", ...
List enabled Attributes. Prints a list of all enabled ClassFile Attributes.
[ "List", "enabled", "Attributes", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/cli.py#L20-L36
train
List enabled Attributes. Prints a list of all enabled ClassFile Attributes. Prints a list of all enabled ClassFile Attributes. Prints a list of all enabled ClassFile Attributes. Prints a list of all enabled ClassFile Attributes. Prints a list of all enabled ClassFile Attributes.
TkTech/Jawa
jawa/cli.py
ins
def ins(mnemonic): """Lookup instruction information. Lookup an instruction by its mnemonic. """ try: opcode = bytecode.opcode_table[mnemonic] except KeyError: click.secho(u'No definition found.', fg='red') return click.echo(u'{mnemonic} (0x{op})'.format( mnemon...
python
def ins(mnemonic): """Lookup instruction information. Lookup an instruction by its mnemonic. """ try: opcode = bytecode.opcode_table[mnemonic] except KeyError: click.secho(u'No definition found.', fg='red') return click.echo(u'{mnemonic} (0x{op})'.format( mnemon...
[ "def", "ins", "(", "mnemonic", ")", ":", "try", ":", "opcode", "=", "bytecode", ".", "opcode_table", "[", "mnemonic", "]", "except", "KeyError", ":", "click", ".", "secho", "(", "u'No definition found.'", ",", "fg", "=", "'red'", ")", "return", "click", ...
Lookup instruction information. Lookup an instruction by its mnemonic.
[ "Lookup", "instruction", "information", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/cli.py#L41-L83
train
Lookup an instruction by its mnemonic.
TkTech/Jawa
jawa/cli.py
shell_command
def shell_command(class_path): """Drop into a debugging shell.""" loader = ClassLoader(*class_path) shell.start_shell(local_ns={ 'ClassFile': ClassFile, 'loader': loader, 'constants': importlib.import_module('jawa.constants'), })
python
def shell_command(class_path): """Drop into a debugging shell.""" loader = ClassLoader(*class_path) shell.start_shell(local_ns={ 'ClassFile': ClassFile, 'loader': loader, 'constants': importlib.import_module('jawa.constants'), })
[ "def", "shell_command", "(", "class_path", ")", ":", "loader", "=", "ClassLoader", "(", "*", "class_path", ")", "shell", ".", "start_shell", "(", "local_ns", "=", "{", "'ClassFile'", ":", "ClassFile", ",", "'loader'", ":", "loader", ",", "'constants'", ":", ...
Drop into a debugging shell.
[ "Drop", "into", "a", "debugging", "shell", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/cli.py#L88-L95
train
Drop into a debugging shell.
TkTech/Jawa
jawa/cli.py
definition_to_json
def definition_to_json(source): """Convert a bytecode.yaml file into a prepared bytecode.json. Jawa internally uses a YAML file to define all bytecode opcodes, operands, runtime exceptions, default transforms, etc... However since JSON is available in the python stdlib and YAML is not, we process ...
python
def definition_to_json(source): """Convert a bytecode.yaml file into a prepared bytecode.json. Jawa internally uses a YAML file to define all bytecode opcodes, operands, runtime exceptions, default transforms, etc... However since JSON is available in the python stdlib and YAML is not, we process ...
[ "def", "definition_to_json", "(", "source", ")", ":", "try", ":", "import", "yaml", "except", "ImportError", ":", "click", ".", "echo", "(", "'The pyyaml module could not be found and is required'", "' to use this command.'", ",", "err", "=", "True", ")", "return", ...
Convert a bytecode.yaml file into a prepared bytecode.json. Jawa internally uses a YAML file to define all bytecode opcodes, operands, runtime exceptions, default transforms, etc... However since JSON is available in the python stdlib and YAML is not, we process this YAML file before distribution to p...
[ "Convert", "a", "bytecode", ".", "yaml", "file", "into", "a", "prepared", "bytecode", ".", "json", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/cli.py#L100-L130
train
Convert a bytecode. yaml file into a prepared bytecode. json file.
TkTech/Jawa
jawa/cli.py
dependencies
def dependencies(source): """Output a list of all classes referenced by the given source.""" loader = ClassLoader(source, max_cache=-1) all_dependencies = set() for klass in loader.classes: new_dependencies = loader.dependencies(klass) - all_dependencies all_dependencies.update(new_depen...
python
def dependencies(source): """Output a list of all classes referenced by the given source.""" loader = ClassLoader(source, max_cache=-1) all_dependencies = set() for klass in loader.classes: new_dependencies = loader.dependencies(klass) - all_dependencies all_dependencies.update(new_depen...
[ "def", "dependencies", "(", "source", ")", ":", "loader", "=", "ClassLoader", "(", "source", ",", "max_cache", "=", "-", "1", ")", "all_dependencies", "=", "set", "(", ")", "for", "klass", "in", "loader", ".", "classes", ":", "new_dependencies", "=", "lo...
Output a list of all classes referenced by the given source.
[ "Output", "a", "list", "of", "all", "classes", "referenced", "by", "the", "given", "source", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/cli.py#L135-L143
train
Output a list of all classes referenced by the given source.
TkTech/Jawa
jawa/cli.py
grep
def grep(source, regex, stop_on_first=False): """Grep the constant pool of all classes in source.""" loader = ClassLoader(source, max_cache=-1) r = re.compile(regex) def _matches(constant): return r.match(constant.value) for klass in loader.classes: it = loader.search_constant_pool...
python
def grep(source, regex, stop_on_first=False): """Grep the constant pool of all classes in source.""" loader = ClassLoader(source, max_cache=-1) r = re.compile(regex) def _matches(constant): return r.match(constant.value) for klass in loader.classes: it = loader.search_constant_pool...
[ "def", "grep", "(", "source", ",", "regex", ",", "stop_on_first", "=", "False", ")", ":", "loader", "=", "ClassLoader", "(", "source", ",", "max_cache", "=", "-", "1", ")", "r", "=", "re", ".", "compile", "(", "regex", ")", "def", "_matches", "(", ...
Grep the constant pool of all classes in source.
[ "Grep", "the", "constant", "pool", "of", "all", "classes", "in", "source", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/cli.py#L155-L168
train
Grep the constant pool of all classes in source.
ifduyue/urlfetch
urlfetch.py
fetch
def fetch(*args, **kwargs): """fetch an URL. :func:`~urlfetch.fetch` is a wrapper of :func:`~urlfetch.request`. It calls :func:`~urlfetch.get` by default. If one of parameter ``data`` or parameter ``files`` is supplied, :func:`~urlfetch.post` is called. """ data = kwargs.get('data', None) f...
python
def fetch(*args, **kwargs): """fetch an URL. :func:`~urlfetch.fetch` is a wrapper of :func:`~urlfetch.request`. It calls :func:`~urlfetch.get` by default. If one of parameter ``data`` or parameter ``files`` is supplied, :func:`~urlfetch.post` is called. """ data = kwargs.get('data', None) f...
[ "def", "fetch", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "kwargs", ".", "get", "(", "'data'", ",", "None", ")", "files", "=", "kwargs", ".", "get", "(", "'files'", ",", "{", "}", ")", "if", "data", "and", "isinstance", ...
fetch an URL. :func:`~urlfetch.fetch` is a wrapper of :func:`~urlfetch.request`. It calls :func:`~urlfetch.get` by default. If one of parameter ``data`` or parameter ``files`` is supplied, :func:`~urlfetch.post` is called.
[ "fetch", "an", "URL", "." ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L528-L540
train
fetch an URL.
ifduyue/urlfetch
urlfetch.py
request
def request(url, method="GET", params=None, data=None, headers={}, timeout=None, files={}, randua=False, auth=None, length_limit=None, proxies=None, trust_env=True, max_redirects=0, source_address=None, **kwargs): """request an URL :arg string url: URL to be fetched. :ar...
python
def request(url, method="GET", params=None, data=None, headers={}, timeout=None, files={}, randua=False, auth=None, length_limit=None, proxies=None, trust_env=True, max_redirects=0, source_address=None, **kwargs): """request an URL :arg string url: URL to be fetched. :ar...
[ "def", "request", "(", "url", ",", "method", "=", "\"GET\"", ",", "params", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "{", "}", ",", "timeout", "=", "None", ",", "files", "=", "{", "}", ",", "randua", "=", "False", ",", "auth", ...
request an URL :arg string url: URL to be fetched. :arg string method: (optional) HTTP method, one of ``GET``, ``DELETE``, ``HEAD``, ``OPTIONS``, ``PUT``, ``POST``, ``TRACE``, ``PATCH``. ``GET`` is the default. :arg dict/string params: (optional) Dict or stri...
[ "request", "an", "URL" ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L558-L763
train
This function is used to make a request to a URL.
ifduyue/urlfetch
urlfetch.py
parse_url
def parse_url(url): """Return a dictionary of parsed url Including scheme, netloc, path, params, query, fragment, uri, username, password, host, port and http_host """ try: url = unicode(url) except UnicodeDecodeError: pass if py3k: make_utf8 = lambda x: x else:...
python
def parse_url(url): """Return a dictionary of parsed url Including scheme, netloc, path, params, query, fragment, uri, username, password, host, port and http_host """ try: url = unicode(url) except UnicodeDecodeError: pass if py3k: make_utf8 = lambda x: x else:...
[ "def", "parse_url", "(", "url", ")", ":", "try", ":", "url", "=", "unicode", "(", "url", ")", "except", "UnicodeDecodeError", ":", "pass", "if", "py3k", ":", "make_utf8", "=", "lambda", "x", ":", "x", "else", ":", "make_utf8", "=", "lambda", "x", ":"...
Return a dictionary of parsed url Including scheme, netloc, path, params, query, fragment, uri, username, password, host, port and http_host
[ "Return", "a", "dictionary", "of", "parsed", "url" ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L801-L845
train
Parse a url and return a dictionary of parsed url
ifduyue/urlfetch
urlfetch.py
get_proxies_from_environ
def get_proxies_from_environ(): """Get proxies from os.environ.""" proxies = {} http_proxy = os.getenv('http_proxy') or os.getenv('HTTP_PROXY') https_proxy = os.getenv('https_proxy') or os.getenv('HTTPS_PROXY') if http_proxy: proxies['http'] = http_proxy if https_proxy: proxies['...
python
def get_proxies_from_environ(): """Get proxies from os.environ.""" proxies = {} http_proxy = os.getenv('http_proxy') or os.getenv('HTTP_PROXY') https_proxy = os.getenv('https_proxy') or os.getenv('HTTPS_PROXY') if http_proxy: proxies['http'] = http_proxy if https_proxy: proxies['...
[ "def", "get_proxies_from_environ", "(", ")", ":", "proxies", "=", "{", "}", "http_proxy", "=", "os", ".", "getenv", "(", "'http_proxy'", ")", "or", "os", ".", "getenv", "(", "'HTTP_PROXY'", ")", "https_proxy", "=", "os", ".", "getenv", "(", "'https_proxy'"...
Get proxies from os.environ.
[ "Get", "proxies", "from", "os", ".", "environ", "." ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L848-L857
train
Get proxies from os. environ.
ifduyue/urlfetch
urlfetch.py
mb_code
def mb_code(s, coding=None, errors='replace'): """encoding/decoding helper.""" if isinstance(s, unicode): return s if coding is None else s.encode(coding, errors=errors) for c in ('utf-8', 'gb2312', 'gbk', 'gb18030', 'big5'): try: s = s.decode(c) return s if coding is...
python
def mb_code(s, coding=None, errors='replace'): """encoding/decoding helper.""" if isinstance(s, unicode): return s if coding is None else s.encode(coding, errors=errors) for c in ('utf-8', 'gb2312', 'gbk', 'gb18030', 'big5'): try: s = s.decode(c) return s if coding is...
[ "def", "mb_code", "(", "s", ",", "coding", "=", "None", ",", "errors", "=", "'replace'", ")", ":", "if", "isinstance", "(", "s", ",", "unicode", ")", ":", "return", "s", "if", "coding", "is", "None", "else", "s", ".", "encode", "(", "coding", ",", ...
encoding/decoding helper.
[ "encoding", "/", "decoding", "helper", "." ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L860-L870
train
encoding and decoding helper.
ifduyue/urlfetch
urlfetch.py
random_useragent
def random_useragent(filename=True): """Returns a User-Agent string randomly from file. :arg string filename: (Optional) Path to the file from which a random useragent is generated. By default it's ``True``, a file shipped with this module will be used. :returns: An user-agent string. "...
python
def random_useragent(filename=True): """Returns a User-Agent string randomly from file. :arg string filename: (Optional) Path to the file from which a random useragent is generated. By default it's ``True``, a file shipped with this module will be used. :returns: An user-agent string. "...
[ "def", "random_useragent", "(", "filename", "=", "True", ")", ":", "import", "random", "default_ua", "=", "'urlfetch/%s'", "%", "__version__", "if", "isinstance", "(", "filename", ",", "basestring", ")", ":", "filenames", "=", "[", "filename", "]", "else", "...
Returns a User-Agent string randomly from file. :arg string filename: (Optional) Path to the file from which a random useragent is generated. By default it's ``True``, a file shipped with this module will be used. :returns: An user-agent string.
[ "Returns", "a", "User", "-", "Agent", "string", "randomly", "from", "file", "." ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L873-L929
train
Returns a User - Agent string randomly from a file.
ifduyue/urlfetch
urlfetch.py
url_concat
def url_concat(url, args, keep_existing=True): """Concatenate url and argument dictionary >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' :arg string url: URL being concat to. :arg dict args: Args being concat. :arg bool keep_existing: (Optional) Whet...
python
def url_concat(url, args, keep_existing=True): """Concatenate url and argument dictionary >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' :arg string url: URL being concat to. :arg dict args: Args being concat. :arg bool keep_existing: (Optional) Whet...
[ "def", "url_concat", "(", "url", ",", "args", ",", "keep_existing", "=", "True", ")", ":", "if", "not", "args", ":", "return", "url", "if", "keep_existing", ":", "if", "url", "[", "-", "1", "]", "not", "in", "(", "'?'", ",", "'&'", ")", ":", "url...
Concatenate url and argument dictionary >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' :arg string url: URL being concat to. :arg dict args: Args being concat. :arg bool keep_existing: (Optional) Whether to keep the args which are ...
[ "Concatenate", "url", "and", "argument", "dictionary" ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L932-L954
train
Concatenate url and argument dictionary
ifduyue/urlfetch
urlfetch.py
choose_boundary
def choose_boundary(): """Generate a multipart boundry. :returns: A boundary string """ global BOUNDARY_PREFIX if BOUNDARY_PREFIX is None: BOUNDARY_PREFIX = "urlfetch" try: uid = repr(os.getuid()) BOUNDARY_PREFIX += "." + uid except AttributeError: ...
python
def choose_boundary(): """Generate a multipart boundry. :returns: A boundary string """ global BOUNDARY_PREFIX if BOUNDARY_PREFIX is None: BOUNDARY_PREFIX = "urlfetch" try: uid = repr(os.getuid()) BOUNDARY_PREFIX += "." + uid except AttributeError: ...
[ "def", "choose_boundary", "(", ")", ":", "global", "BOUNDARY_PREFIX", "if", "BOUNDARY_PREFIX", "is", "None", ":", "BOUNDARY_PREFIX", "=", "\"urlfetch\"", "try", ":", "uid", "=", "repr", "(", "os", ".", "getuid", "(", ")", ")", "BOUNDARY_PREFIX", "+=", "\".\"...
Generate a multipart boundry. :returns: A boundary string
[ "Generate", "a", "multipart", "boundry", "." ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L957-L976
train
Generate a multipart boundry.
ifduyue/urlfetch
urlfetch.py
encode_multipart
def encode_multipart(data, files): """Encode multipart. :arg dict data: Data to be encoded :arg dict files: Files to be encoded :returns: Encoded binary string :raises: :class:`UrlfetchException` """ body = BytesIO() boundary = choose_boundary() part_boundary = b('--%s\r\n' % bounda...
python
def encode_multipart(data, files): """Encode multipart. :arg dict data: Data to be encoded :arg dict files: Files to be encoded :returns: Encoded binary string :raises: :class:`UrlfetchException` """ body = BytesIO() boundary = choose_boundary() part_boundary = b('--%s\r\n' % bounda...
[ "def", "encode_multipart", "(", "data", ",", "files", ")", ":", "body", "=", "BytesIO", "(", ")", "boundary", "=", "choose_boundary", "(", ")", "part_boundary", "=", "b", "(", "'--%s\\r\\n'", "%", "boundary", ")", "writer", "=", "codecs", ".", "lookup", ...
Encode multipart. :arg dict data: Data to be encoded :arg dict files: Files to be encoded :returns: Encoded binary string :raises: :class:`UrlfetchException`
[ "Encode", "multipart", "." ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L979-L1046
train
Encode a multipart request.
ifduyue/urlfetch
urlfetch.py
Response.body
def body(self): """Response body. :raises: :class:`ContentLimitExceeded`, :class:`ContentDecodingError` """ content = [] length = 0 for chunk in self: content.append(chunk) length += len(chunk) if self.length_limit and length > self.le...
python
def body(self): """Response body. :raises: :class:`ContentLimitExceeded`, :class:`ContentDecodingError` """ content = [] length = 0 for chunk in self: content.append(chunk) length += len(chunk) if self.length_limit and length > self.le...
[ "def", "body", "(", "self", ")", ":", "content", "=", "[", "]", "length", "=", "0", "for", "chunk", "in", "self", ":", "content", ".", "append", "(", "chunk", ")", "length", "+=", "len", "(", "chunk", ")", "if", "self", ".", "length_limit", "and", ...
Response body. :raises: :class:`ContentLimitExceeded`, :class:`ContentDecodingError`
[ "Response", "body", "." ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L285-L300
train
Return the response body as a string.
ifduyue/urlfetch
urlfetch.py
Response.json
def json(self): """Load response body as json. :raises: :class:`ContentDecodingError` """ try: return json.loads(self.text) except Exception as e: raise ContentDecodingError(e)
python
def json(self): """Load response body as json. :raises: :class:`ContentDecodingError` """ try: return json.loads(self.text) except Exception as e: raise ContentDecodingError(e)
[ "def", "json", "(", "self", ")", ":", "try", ":", "return", "json", ".", "loads", "(", "self", ".", "text", ")", "except", "Exception", "as", "e", ":", "raise", "ContentDecodingError", "(", "e", ")" ]
Load response body as json. :raises: :class:`ContentDecodingError`
[ "Load", "response", "body", "as", "json", "." ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L314-L322
train
Load response body as json.
ifduyue/urlfetch
urlfetch.py
Response.headers
def headers(self): """Response headers. Response headers is a dict with all keys in lower case. >>> import urlfetch >>> response = urlfetch.get("http://docs.python.org/") >>> response.headers { 'content-length': '8719', 'x-cache': 'MISS from loca...
python
def headers(self): """Response headers. Response headers is a dict with all keys in lower case. >>> import urlfetch >>> response = urlfetch.get("http://docs.python.org/") >>> response.headers { 'content-length': '8719', 'x-cache': 'MISS from loca...
[ "def", "headers", "(", "self", ")", ":", "if", "py3k", ":", "return", "dict", "(", "(", "k", ".", "lower", "(", ")", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "getheaders", "(", ")", ")", "else", ":", "return", "dict", "(", "sel...
Response headers. Response headers is a dict with all keys in lower case. >>> import urlfetch >>> response = urlfetch.get("http://docs.python.org/") >>> response.headers { 'content-length': '8719', 'x-cache': 'MISS from localhost', 'accept-ra...
[ "Response", "headers", "." ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L325-L350
train
Response headers.
ifduyue/urlfetch
urlfetch.py
Response.cookies
def cookies(self): """Cookies in dict""" c = Cookie.SimpleCookie(self.getheader('set-cookie')) return dict((i.key, i.value) for i in c.values())
python
def cookies(self): """Cookies in dict""" c = Cookie.SimpleCookie(self.getheader('set-cookie')) return dict((i.key, i.value) for i in c.values())
[ "def", "cookies", "(", "self", ")", ":", "c", "=", "Cookie", ".", "SimpleCookie", "(", "self", ".", "getheader", "(", "'set-cookie'", ")", ")", "return", "dict", "(", "(", "i", ".", "key", ",", "i", ".", "value", ")", "for", "i", "in", "c", ".", ...
Cookies in dict
[ "Cookies", "in", "dict" ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L353-L356
train
Returns a dict of cookies in the response.
ifduyue/urlfetch
urlfetch.py
Response.cookiestring
def cookiestring(self): """Cookie string""" return '; '.join('%s=%s' % (k, v) for k, v in self.cookies.items())
python
def cookiestring(self): """Cookie string""" return '; '.join('%s=%s' % (k, v) for k, v in self.cookies.items())
[ "def", "cookiestring", "(", "self", ")", ":", "return", "'; '", ".", "join", "(", "'%s=%s'", "%", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "cookies", ".", "items", "(", ")", ")" ]
Cookie string
[ "Cookie", "string" ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L359-L361
train
Return a string representation of the cookies.
ifduyue/urlfetch
urlfetch.py
Response.links
def links(self): """Links parsed from HTTP Link header""" ret = [] linkheader = self.getheader('link') if not linkheader: return ret for i in linkheader.split(','): try: url, params = i.split(';', 1) except ValueError: ...
python
def links(self): """Links parsed from HTTP Link header""" ret = [] linkheader = self.getheader('link') if not linkheader: return ret for i in linkheader.split(','): try: url, params = i.split(';', 1) except ValueError: ...
[ "def", "links", "(", "self", ")", ":", "ret", "=", "[", "]", "linkheader", "=", "self", ".", "getheader", "(", "'link'", ")", "if", "not", "linkheader", ":", "return", "ret", "for", "i", "in", "linkheader", ".", "split", "(", "','", ")", ":", "try"...
Links parsed from HTTP Link header
[ "Links", "parsed", "from", "HTTP", "Link", "header" ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L364-L384
train
Returns a list of links parsed from HTTP Link header
ifduyue/urlfetch
urlfetch.py
Session.cookiestring
def cookiestring(self, value): """"Cookie string setter""" c = Cookie.SimpleCookie(value) sc = [(i.key, i.value) for i in c.values()] self.cookies = dict(sc)
python
def cookiestring(self, value): """"Cookie string setter""" c = Cookie.SimpleCookie(value) sc = [(i.key, i.value) for i in c.values()] self.cookies = dict(sc)
[ "def", "cookiestring", "(", "self", ",", "value", ")", ":", "c", "=", "Cookie", ".", "SimpleCookie", "(", "value", ")", "sc", "=", "[", "(", "i", ".", "key", ",", "i", ".", "value", ")", "for", "i", "in", "c", ".", "values", "(", ")", "]", "s...
Cookie string setter
[ "Cookie", "string", "setter" ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L452-L456
train
"Cookie string setter"""
ifduyue/urlfetch
urlfetch.py
Session.request
def request(self, *args, **kwargs): """Issue a request.""" headers = self.headers.copy() if self.cookiestring: headers['Cookie'] = self.cookiestring headers.update(kwargs.get('headers', {})) kwargs['headers'] = headers r = request(*args, **kwargs) sel...
python
def request(self, *args, **kwargs): """Issue a request.""" headers = self.headers.copy() if self.cookiestring: headers['Cookie'] = self.cookiestring headers.update(kwargs.get('headers', {})) kwargs['headers'] = headers r = request(*args, **kwargs) sel...
[ "def", "request", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "headers", "=", "self", ".", "headers", ".", "copy", "(", ")", "if", "self", ".", "cookiestring", ":", "headers", "[", "'Cookie'", "]", "=", "self", ".", "cookiestr...
Issue a request.
[ "Issue", "a", "request", "." ]
e0ea4673367c157eb832ba4ba2635306c81a61be
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L465-L476
train
Issue a request.
networks-lab/tidyextractors
tidyextractors/tidygit/get_log.py
handle_object
def handle_object(name, obj): """ This helper function handles incoming test_data for make_object_dict. If thereis a special handler in git_object_handlers_lookup, this is used. Otherwise, the given name:obj pair is returned as-is. :param name: String :param obj: The object to be processed. ...
python
def handle_object(name, obj): """ This helper function handles incoming test_data for make_object_dict. If thereis a special handler in git_object_handlers_lookup, this is used. Otherwise, the given name:obj pair is returned as-is. :param name: String :param obj: The object to be processed. ...
[ "def", "handle_object", "(", "name", ",", "obj", ")", ":", "if", "type", "(", "obj", ")", "in", "git_object_handlers_lookup", ":", "return", "git_object_handlers_lookup", "[", "type", "(", "obj", ")", "]", "(", "name", ",", "obj", ")", "else", ":", "retu...
This helper function handles incoming test_data for make_object_dict. If thereis a special handler in git_object_handlers_lookup, this is used. Otherwise, the given name:obj pair is returned as-is. :param name: String :param obj: The object to be processed. :return: A dictionary of attributes.
[ "This", "helper", "function", "handles", "incoming", "test_data", "for", "make_object_dict", ".", "If", "thereis", "a", "special", "handler", "in", "git_object_handlers_lookup", "this", "is", "used", ".", "Otherwise", "the", "given", "name", ":", "obj", "pair", ...
658448ed533beecf32adcc188fc64d1068d15ca6
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/tidygit/get_log.py#L39-L52
train
This helper function handles incoming test_data for make_object_dict.
networks-lab/tidyextractors
tidyextractors/tidygit/get_log.py
make_object_dict
def make_object_dict(obj, keep=[]): """ Processes an object, exporting its data as a nested dictionary. Individual objects are handled using handle_object. :param obj: The object to be processed. :param keep: Object attributes to be kept. Defaults to all attributes. :return: A dictionary of attr...
python
def make_object_dict(obj, keep=[]): """ Processes an object, exporting its data as a nested dictionary. Individual objects are handled using handle_object. :param obj: The object to be processed. :param keep: Object attributes to be kept. Defaults to all attributes. :return: A dictionary of attr...
[ "def", "make_object_dict", "(", "obj", ",", "keep", "=", "[", "]", ")", ":", "data", "=", "{", "}", "if", "keep", "==", "[", "]", ":", "get_attrs", "=", "dir", "(", "obj", ")", "else", ":", "get_attrs", "=", "keep", "for", "attr", "in", "get_attr...
Processes an object, exporting its data as a nested dictionary. Individual objects are handled using handle_object. :param obj: The object to be processed. :param keep: Object attributes to be kept. Defaults to all attributes. :return: A dictionary of attributes.
[ "Processes", "an", "object", "exporting", "its", "data", "as", "a", "nested", "dictionary", ".", "Individual", "objects", "are", "handled", "using", "handle_object", ".", ":", "param", "obj", ":", "The", "object", "to", "be", "processed", ".", ":", "param", ...
658448ed533beecf32adcc188fc64d1068d15ca6
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/tidygit/get_log.py#L55-L72
train
Processes an object and returns a nested dictionary.
networks-lab/tidyextractors
tidyextractors/tidygit/get_log.py
extract_log
def extract_log(rpath,extract=simple_attributes): """ Extracts Git commit test_data from a local repository. :param rpath: The path to a local Git repo. :param extract: A list of attribute name strings. :return: A Pandas dataframe containing Git commit test_data. """ # Get repo m_repo = ...
python
def extract_log(rpath,extract=simple_attributes): """ Extracts Git commit test_data from a local repository. :param rpath: The path to a local Git repo. :param extract: A list of attribute name strings. :return: A Pandas dataframe containing Git commit test_data. """ # Get repo m_repo = ...
[ "def", "extract_log", "(", "rpath", ",", "extract", "=", "simple_attributes", ")", ":", "# Get repo", "m_repo", "=", "git", ".", "Repo", "(", "rpath", ")", "# Count commits", "count", "=", "0", "m_commits", "=", "m_repo", ".", "iter_commits", "(", ")", "fo...
Extracts Git commit test_data from a local repository. :param rpath: The path to a local Git repo. :param extract: A list of attribute name strings. :return: A Pandas dataframe containing Git commit test_data.
[ "Extracts", "Git", "commit", "test_data", "from", "a", "local", "repository", ".", ":", "param", "rpath", ":", "The", "path", "to", "a", "local", "Git", "repo", ".", ":", "param", "extract", ":", "A", "list", "of", "attribute", "name", "strings", ".", ...
658448ed533beecf32adcc188fc64d1068d15ca6
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/tidygit/get_log.py#L75-L119
train
Extracts Git commit test_data from a local Git repo.
JarryShaw/f2format
src/core.py
convert
def convert(string, lineno): """The main conversion process. Args: - string -- str, context to be converted - lineno -- dict<int: int>, line number to actual offset mapping Returns: - str -- converted string """ def parse(string): try: return parso.parse(string,...
python
def convert(string, lineno): """The main conversion process. Args: - string -- str, context to be converted - lineno -- dict<int: int>, line number to actual offset mapping Returns: - str -- converted string """ def parse(string): try: return parso.parse(string,...
[ "def", "convert", "(", "string", ",", "lineno", ")", ":", "def", "parse", "(", "string", ")", ":", "try", ":", "return", "parso", ".", "parse", "(", "string", ",", "error_recovery", "=", "False", ",", "version", "=", "os", ".", "getenv", "(", "'F2FOR...
The main conversion process. Args: - string -- str, context to be converted - lineno -- dict<int: int>, line number to actual offset mapping Returns: - str -- converted string
[ "The", "main", "conversion", "process", "." ]
a144250268247ce0a98d734a26d53faadff7a6f8
https://github.com/JarryShaw/f2format/blob/a144250268247ce0a98d734a26d53faadff7a6f8/src/core.py#L65-L196
train
The main function for the conversion process.
JarryShaw/f2format
src/core.py
f2format
def f2format(filename): """Wrapper works for conversion. Args: - filename -- str, file to be converted """ print('Now converting %r...' % filename) # fetch encoding encoding = os.getenv('F2FORMAT_ENCODING', LOCALE_ENCODING) lineno = dict() # line number -> file offset conten...
python
def f2format(filename): """Wrapper works for conversion. Args: - filename -- str, file to be converted """ print('Now converting %r...' % filename) # fetch encoding encoding = os.getenv('F2FORMAT_ENCODING', LOCALE_ENCODING) lineno = dict() # line number -> file offset conten...
[ "def", "f2format", "(", "filename", ")", ":", "print", "(", "'Now converting %r...'", "%", "filename", ")", "# fetch encoding", "encoding", "=", "os", ".", "getenv", "(", "'F2FORMAT_ENCODING'", ",", "LOCALE_ENCODING", ")", "lineno", "=", "dict", "(", ")", "# l...
Wrapper works for conversion. Args: - filename -- str, file to be converted
[ "Wrapper", "works", "for", "conversion", "." ]
a144250268247ce0a98d734a26d53faadff7a6f8
https://github.com/JarryShaw/f2format/blob/a144250268247ce0a98d734a26d53faadff7a6f8/src/core.py#L199-L225
train
Wrapper works for conversion.
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
exception_to_github
def exception_to_github(github_obj_to_comment, summary=""): """If any exception comes, log them in the given Github obj. """ context = ExceptionContext() try: yield context except Exception: # pylint: disable=broad-except if summary: summary = ": ({})".format(summary) ...
python
def exception_to_github(github_obj_to_comment, summary=""): """If any exception comes, log them in the given Github obj. """ context = ExceptionContext() try: yield context except Exception: # pylint: disable=broad-except if summary: summary = ": ({})".format(summary) ...
[ "def", "exception_to_github", "(", "github_obj_to_comment", ",", "summary", "=", "\"\"", ")", ":", "context", "=", "ExceptionContext", "(", ")", "try", ":", "yield", "context", "except", "Exception", ":", "# pylint: disable=broad-except", "if", "summary", ":", "su...
If any exception comes, log them in the given Github obj.
[ "If", "any", "exception", "comes", "log", "them", "in", "the", "given", "Github", "obj", "." ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L28-L56
train
A generator that yields the exception context.
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
create_comment
def create_comment(github_object, body): """Create a comment, whatever the object is a PR, a commit or an issue. """ try: return github_object.create_issue_comment(body) # It's a PR except AttributeError: return github_object.create_comment(body)
python
def create_comment(github_object, body): """Create a comment, whatever the object is a PR, a commit or an issue. """ try: return github_object.create_issue_comment(body) # It's a PR except AttributeError: return github_object.create_comment(body)
[ "def", "create_comment", "(", "github_object", ",", "body", ")", ":", "try", ":", "return", "github_object", ".", "create_issue_comment", "(", "body", ")", "# It's a PR", "except", "AttributeError", ":", "return", "github_object", ".", "create_comment", "(", "body...
Create a comment, whatever the object is a PR, a commit or an issue.
[ "Create", "a", "comment", "whatever", "the", "object", "is", "a", "PR", "a", "commit", "or", "an", "issue", "." ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L63-L69
train
Create a comment that is a PR a commit or an issue.
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
configure_user
def configure_user(gh_token, repo): """git config --global user.email "you@example.com" git config --global user.name "Your Name" """ user = user_from_token(gh_token) repo.git.config('user.email', user.email or 'aspysdk2@microsoft.com') repo.git.config('user.name', user.name or 'SwaggerToSDK ...
python
def configure_user(gh_token, repo): """git config --global user.email "you@example.com" git config --global user.name "Your Name" """ user = user_from_token(gh_token) repo.git.config('user.email', user.email or 'aspysdk2@microsoft.com') repo.git.config('user.name', user.name or 'SwaggerToSDK ...
[ "def", "configure_user", "(", "gh_token", ",", "repo", ")", ":", "user", "=", "user_from_token", "(", "gh_token", ")", "repo", ".", "git", ".", "config", "(", "'user.email'", ",", "user", ".", "email", "or", "'aspysdk2@microsoft.com'", ")", "repo", ".", "g...
git config --global user.email "you@example.com" git config --global user.name "Your Name"
[ "git", "config", "--", "global", "user", ".", "email", "you" ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L87-L93
train
Configure user with GitHub token
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
get_full_sdk_id
def get_full_sdk_id(gh_token, sdk_git_id): """If the SDK git id is incomplete, try to complete it with user login""" if not '/' in sdk_git_id: login = user_from_token(gh_token).login return '{}/{}'.format(login, sdk_git_id) return sdk_git_id
python
def get_full_sdk_id(gh_token, sdk_git_id): """If the SDK git id is incomplete, try to complete it with user login""" if not '/' in sdk_git_id: login = user_from_token(gh_token).login return '{}/{}'.format(login, sdk_git_id) return sdk_git_id
[ "def", "get_full_sdk_id", "(", "gh_token", ",", "sdk_git_id", ")", ":", "if", "not", "'/'", "in", "sdk_git_id", ":", "login", "=", "user_from_token", "(", "gh_token", ")", ".", "login", "return", "'{}/{}'", ".", "format", "(", "login", ",", "sdk_git_id", "...
If the SDK git id is incomplete, try to complete it with user login
[ "If", "the", "SDK", "git", "id", "is", "incomplete", "try", "to", "complete", "it", "with", "user", "login" ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L95-L100
train
Try to complete the SDK git id with user login
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
sync_fork
def sync_fork(gh_token, github_repo_id, repo, push=True): """Sync the current branch in this fork against the direct parent on Github""" if not gh_token: _LOGGER.warning('Skipping the upstream repo sync, no token') return _LOGGER.info('Check if repo has to be sync with upstream') github_...
python
def sync_fork(gh_token, github_repo_id, repo, push=True): """Sync the current branch in this fork against the direct parent on Github""" if not gh_token: _LOGGER.warning('Skipping the upstream repo sync, no token') return _LOGGER.info('Check if repo has to be sync with upstream') github_...
[ "def", "sync_fork", "(", "gh_token", ",", "github_repo_id", ",", "repo", ",", "push", "=", "True", ")", ":", "if", "not", "gh_token", ":", "_LOGGER", ".", "warning", "(", "'Skipping the upstream repo sync, no token'", ")", "return", "_LOGGER", ".", "info", "("...
Sync the current branch in this fork against the direct parent on Github
[ "Sync", "the", "current", "branch", "in", "this", "fork", "against", "the", "direct", "parent", "on", "Github" ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L102-L128
train
Sync the current branch in this fork against the direct parent on Github
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
get_or_create_pull
def get_or_create_pull(github_repo, title, body, head, base, *, none_if_no_commit=False): """Try to create the PR. If the PR exists, try to find it instead. Raises otherwise. You should always use the complete head syntax "org:branch", since the syntax is required in case of listing. if "none_if_no_co...
python
def get_or_create_pull(github_repo, title, body, head, base, *, none_if_no_commit=False): """Try to create the PR. If the PR exists, try to find it instead. Raises otherwise. You should always use the complete head syntax "org:branch", since the syntax is required in case of listing. if "none_if_no_co...
[ "def", "get_or_create_pull", "(", "github_repo", ",", "title", ",", "body", ",", "head", ",", "base", ",", "*", ",", "none_if_no_commit", "=", "False", ")", ":", "try", ":", "# Try to create or get a PR", "return", "github_repo", ".", "create_pull", "(", "titl...
Try to create the PR. If the PR exists, try to find it instead. Raises otherwise. You should always use the complete head syntax "org:branch", since the syntax is required in case of listing. if "none_if_no_commit" is set, return None instead of raising exception if the problem is that head and base a...
[ "Try", "to", "create", "the", "PR", ".", "If", "the", "PR", "exists", "try", "to", "find", "it", "instead", ".", "Raises", "otherwise", "." ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L130-L165
train
Try to create a PR.
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
clone_to_path
def clone_to_path(gh_token, folder, sdk_git_id, branch_or_commit=None, *, pr_number=None): """Clone the given repo_id to the folder. If PR number is specified fetch the magic branches pull/<id>/head or pull/<id>/merge from Github. "merge" is tried first, and fallback to "head". Beware that pr_number im...
python
def clone_to_path(gh_token, folder, sdk_git_id, branch_or_commit=None, *, pr_number=None): """Clone the given repo_id to the folder. If PR number is specified fetch the magic branches pull/<id>/head or pull/<id>/merge from Github. "merge" is tried first, and fallback to "head". Beware that pr_number im...
[ "def", "clone_to_path", "(", "gh_token", ",", "folder", ",", "sdk_git_id", ",", "branch_or_commit", "=", "None", ",", "*", ",", "pr_number", "=", "None", ")", ":", "_LOGGER", ".", "info", "(", "\"Clone SDK repository %s\"", ",", "sdk_git_id", ")", "url_parsing...
Clone the given repo_id to the folder. If PR number is specified fetch the magic branches pull/<id>/head or pull/<id>/merge from Github. "merge" is tried first, and fallback to "head". Beware that pr_number implies detached head, and then no push is possible. If branch is specified, checkout this bran...
[ "Clone", "the", "given", "repo_id", "to", "the", "folder", "." ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L167-L212
train
Clone the given repo_id to the given folder.
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
do_pr
def do_pr(gh_token, sdk_git_id, sdk_pr_target_repo_id, branch_name, base_branch, pr_body=""): # pylint: disable=too-many-arguments "Do the PR" if not gh_token: _LOGGER.info('Skipping the PR, no token found') return None if not sdk_pr_target_repo_id: _LOGGER.info('Skipping the PR, no...
python
def do_pr(gh_token, sdk_git_id, sdk_pr_target_repo_id, branch_name, base_branch, pr_body=""): # pylint: disable=too-many-arguments "Do the PR" if not gh_token: _LOGGER.info('Skipping the PR, no token found') return None if not sdk_pr_target_repo_id: _LOGGER.info('Skipping the PR, no...
[ "def", "do_pr", "(", "gh_token", ",", "sdk_git_id", ",", "sdk_pr_target_repo_id", ",", "branch_name", ",", "base_branch", ",", "pr_body", "=", "\"\"", ")", ":", "# pylint: disable=too-many-arguments", "if", "not", "gh_token", ":", "_LOGGER", ".", "info", "(", "'...
Do the PR
[ "Do", "the", "PR" ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L214-L250
train
Do the PR from the sdk_pr_target_repo_id.
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
remove_readonly
def remove_readonly(func, path, _): "Clear the readonly bit and reattempt the removal" os.chmod(path, stat.S_IWRITE) func(path)
python
def remove_readonly(func, path, _): "Clear the readonly bit and reattempt the removal" os.chmod(path, stat.S_IWRITE) func(path)
[ "def", "remove_readonly", "(", "func", ",", "path", ",", "_", ")", ":", "os", ".", "chmod", "(", "path", ",", "stat", ".", "S_IWRITE", ")", "func", "(", "path", ")" ]
Clear the readonly bit and reattempt the removal
[ "Clear", "the", "readonly", "bit", "and", "reattempt", "the", "removal" ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L253-L256
train
Clear the readonly bit and reattempt the removal
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
manage_git_folder
def manage_git_folder(gh_token, temp_dir, git_id, *, pr_number=None): """Context manager to avoid readonly problem while cleanup the temp dir. If PR number is given, use magic branches "pull" from Github. """ _LOGGER.debug("Git ID %s", git_id) if Path(git_id).exists(): yield git_id ...
python
def manage_git_folder(gh_token, temp_dir, git_id, *, pr_number=None): """Context manager to avoid readonly problem while cleanup the temp dir. If PR number is given, use magic branches "pull" from Github. """ _LOGGER.debug("Git ID %s", git_id) if Path(git_id).exists(): yield git_id ...
[ "def", "manage_git_folder", "(", "gh_token", ",", "temp_dir", ",", "git_id", ",", "*", ",", "pr_number", "=", "None", ")", ":", "_LOGGER", ".", "debug", "(", "\"Git ID %s\"", ",", "git_id", ")", "if", "Path", "(", "git_id", ")", ".", "exists", "(", ")"...
Context manager to avoid readonly problem while cleanup the temp dir. If PR number is given, use magic branches "pull" from Github.
[ "Context", "manager", "to", "avoid", "readonly", "problem", "while", "cleanup", "the", "temp", "dir", "." ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L259-L278
train
Context manager to avoid readonly problem while cleanup the temp dir.
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
GithubLink.as_raw_link
def as_raw_link(self): """Returns a GithubLink to a raw content. """ if self.link_type == "raw": return self # Can be discussed if we need an hard copy, or fail if self.link_type != "blob": raise ValueError("Cannot get a download link from a tree link") re...
python
def as_raw_link(self): """Returns a GithubLink to a raw content. """ if self.link_type == "raw": return self # Can be discussed if we need an hard copy, or fail if self.link_type != "blob": raise ValueError("Cannot get a download link from a tree link") re...
[ "def", "as_raw_link", "(", "self", ")", ":", "if", "self", ".", "link_type", "==", "\"raw\"", ":", "return", "self", "# Can be discussed if we need an hard copy, or fail", "if", "self", ".", "link_type", "!=", "\"blob\"", ":", "raise", "ValueError", "(", "\"Cannot...
Returns a GithubLink to a raw content.
[ "Returns", "a", "GithubLink", "to", "a", "raw", "content", "." ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L316-L329
train
Returns a GithubLink to a raw content.
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
DashboardCommentableObject.create_comment
def create_comment(self, text): """Mimic issue API, so we can use it everywhere. Return dashboard comment. """ return DashboardComment.get_or_create(self._issue_or_pr, self._header, text)
python
def create_comment(self, text): """Mimic issue API, so we can use it everywhere. Return dashboard comment. """ return DashboardComment.get_or_create(self._issue_or_pr, self._header, text)
[ "def", "create_comment", "(", "self", ",", "text", ")", ":", "return", "DashboardComment", ".", "get_or_create", "(", "self", ".", "_issue_or_pr", ",", "self", ".", "_header", ",", "text", ")" ]
Mimic issue API, so we can use it everywhere. Return dashboard comment.
[ "Mimic", "issue", "API", "so", "we", "can", "use", "it", "everywhere", ".", "Return", "dashboard", "comment", "." ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L336-L340
train
Create a comment.
Azure/azure-python-devtools
src/azure_devtools/ci_tools/github_tools.py
DashboardComment.get_or_create
def get_or_create(cls, issue, header, text=None): """Get or create the dashboard comment in this issue. """ for comment in get_comments(issue): try: if comment.body.splitlines()[0] == header: obj = cls(comment, header) break ...
python
def get_or_create(cls, issue, header, text=None): """Get or create the dashboard comment in this issue. """ for comment in get_comments(issue): try: if comment.body.splitlines()[0] == header: obj = cls(comment, header) break ...
[ "def", "get_or_create", "(", "cls", ",", "issue", ",", "header", ",", "text", "=", "None", ")", ":", "for", "comment", "in", "get_comments", "(", "issue", ")", ":", "try", ":", "if", "comment", ".", "body", ".", "splitlines", "(", ")", "[", "0", "]...
Get or create the dashboard comment in this issue.
[ "Get", "or", "create", "the", "dashboard", "comment", "in", "this", "issue", "." ]
2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/github_tools.py#L348-L364
train
Get or create a dashboard comment in this issue.
nitely/django-hooks
hooks/signalhook.py
Hook.register
def register(self, name): """ Register a new hook. Not required (see :py:func:`.connect` method) :param str name: The hook name :return: Django signal :rtype: :py:class:`django.dispatch.Signal` """ signal = Signal(providing_args=['args', 'kwargs']) self._...
python
def register(self, name): """ Register a new hook. Not required (see :py:func:`.connect` method) :param str name: The hook name :return: Django signal :rtype: :py:class:`django.dispatch.Signal` """ signal = Signal(providing_args=['args', 'kwargs']) self._...
[ "def", "register", "(", "self", ",", "name", ")", ":", "signal", "=", "Signal", "(", "providing_args", "=", "[", "'args'", ",", "'kwargs'", "]", ")", "self", ".", "_registry", "[", "name", "]", "=", "signal", "return", "signal" ]
Register a new hook. Not required (see :py:func:`.connect` method) :param str name: The hook name :return: Django signal :rtype: :py:class:`django.dispatch.Signal`
[ "Register", "a", "new", "hook", ".", "Not", "required", "(", "see", ":", "py", ":", "func", ":", ".", "connect", "method", ")" ]
26ea2150c9be110e90b9ee60fbfd1065ac30ab1d
https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/signalhook.py#L25-L35
train
Register a new hook. Not required.
nitely/django-hooks
hooks/signalhook.py
Hook.connect
def connect(self, name, func, sender=None, dispatch_uid=None): """ Connects a function to a hook.\ Creates the hook (name) if it does not exists :param str name: The hook name :param callable func: A function reference used as a callback :param class sender: Optional sen...
python
def connect(self, name, func, sender=None, dispatch_uid=None): """ Connects a function to a hook.\ Creates the hook (name) if it does not exists :param str name: The hook name :param callable func: A function reference used as a callback :param class sender: Optional sen...
[ "def", "connect", "(", "self", ",", "name", ",", "func", ",", "sender", "=", "None", ",", "dispatch_uid", "=", "None", ")", ":", "try", ":", "signal", "=", "self", ".", "_registry", "[", "name", "]", "except", "KeyError", ":", "signal", "=", "self", ...
Connects a function to a hook.\ Creates the hook (name) if it does not exists :param str name: The hook name :param callable func: A function reference used as a callback :param class sender: Optional sender __class__ to which the\ func should respond. Default will match all ...
[ "Connects", "a", "function", "to", "a", "hook", ".", "\\", "Creates", "the", "hook", "(", "name", ")", "if", "it", "does", "not", "exists" ]
26ea2150c9be110e90b9ee60fbfd1065ac30ab1d
https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/signalhook.py#L37-L54
train
Connects a function to a hook.
nitely/django-hooks
hooks/signalhook.py
Hook.disconnect
def disconnect(self, name, func, dispatch_uid=None): """ Disconnects a function from a hook :param str name: The hook name :param callable func: A function reference registered previously :param str dispatch_uid: optional unique id,\ see :py:class:`django.dispatch.Signal...
python
def disconnect(self, name, func, dispatch_uid=None): """ Disconnects a function from a hook :param str name: The hook name :param callable func: A function reference registered previously :param str dispatch_uid: optional unique id,\ see :py:class:`django.dispatch.Signal...
[ "def", "disconnect", "(", "self", ",", "name", ",", "func", ",", "dispatch_uid", "=", "None", ")", ":", "try", ":", "signal", "=", "self", ".", "_registry", "[", "name", "]", "except", "KeyError", ":", "return", "signal", ".", "disconnect", "(", "func"...
Disconnects a function from a hook :param str name: The hook name :param callable func: A function reference registered previously :param str dispatch_uid: optional unique id,\ see :py:class:`django.dispatch.Signal` for more info.
[ "Disconnects", "a", "function", "from", "a", "hook" ]
26ea2150c9be110e90b9ee60fbfd1065ac30ab1d
https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/signalhook.py#L56-L70
train
Disconnects a function from a previously registered hook.
nitely/django-hooks
hooks/signalhook.py
Hook.send
def send(self, name, sender=None, **kwargs): """ Sends the signal. Return every function response\ that was hooked to hook-name as a list: [(func, response), ] :param str name: The hook name :param class sender: Optional sender __class__ to which\ registered callback sho...
python
def send(self, name, sender=None, **kwargs): """ Sends the signal. Return every function response\ that was hooked to hook-name as a list: [(func, response), ] :param str name: The hook name :param class sender: Optional sender __class__ to which\ registered callback sho...
[ "def", "send", "(", "self", ",", "name", ",", "sender", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "signal", "=", "self", ".", "_registry", "[", "name", "]", "except", "KeyError", ":", "return", "[", "]", "return", "signal", ".", ...
Sends the signal. Return every function response\ that was hooked to hook-name as a list: [(func, response), ] :param str name: The hook name :param class sender: Optional sender __class__ to which\ registered callback should match (see :py:func:`.connect` method) :return: Signa...
[ "Sends", "the", "signal", ".", "Return", "every", "function", "response", "\\", "that", "was", "hooked", "to", "hook", "-", "name", "as", "a", "list", ":", "[", "(", "func", "response", ")", "]" ]
26ea2150c9be110e90b9ee60fbfd1065ac30ab1d
https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/signalhook.py#L72-L88
train
Send the signal to the given sender.
piotr-rusin/spam-lists
spam_lists/structures.py
create_host
def create_host(factories, value): """Use the factories to create a host object. :param factories: a list of functions that return host objects (Hostname, IPv4Address, IPv6Address) for valid arguments :param value: a value to be passed as argument to factories :returns: an object representing the v...
python
def create_host(factories, value): """Use the factories to create a host object. :param factories: a list of functions that return host objects (Hostname, IPv4Address, IPv6Address) for valid arguments :param value: a value to be passed as argument to factories :returns: an object representing the v...
[ "def", "create_host", "(", "factories", ",", "value", ")", ":", "data", "=", "[", "value", "]", "for", "func", "in", "factories", ":", "try", ":", "return", "func", "(", "value", ")", "except", "InvalidHostError", "as", "ex", ":", "data", ".", "append"...
Use the factories to create a host object. :param factories: a list of functions that return host objects (Hostname, IPv4Address, IPv6Address) for valid arguments :param value: a value to be passed as argument to factories :returns: an object representing the value, created by one of the factories....
[ "Use", "the", "factories", "to", "create", "a", "host", "object", "." ]
fd616e8761b28f3eaa503fee5e45f7748e8f88f2
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/structures.py#L190-L216
train
Create a host object for the given value.
piotr-rusin/spam-lists
spam_lists/structures.py
Hostname.is_subdomain
def is_subdomain(self, other): """Test if the object is a subdomain of the other. :param other: the object to which we compare this instance :returns: True if this instance is a subdomain of the other """ compared = other.value if hasattr(other, 'value') else other try: ...
python
def is_subdomain(self, other): """Test if the object is a subdomain of the other. :param other: the object to which we compare this instance :returns: True if this instance is a subdomain of the other """ compared = other.value if hasattr(other, 'value') else other try: ...
[ "def", "is_subdomain", "(", "self", ",", "other", ")", ":", "compared", "=", "other", ".", "value", "if", "hasattr", "(", "other", ",", "'value'", ")", "else", "other", "try", ":", "return", "self", ".", "value", ".", "is_subdomain", "(", "compared", "...
Test if the object is a subdomain of the other. :param other: the object to which we compare this instance :returns: True if this instance is a subdomain of the other
[ "Test", "if", "the", "object", "is", "a", "subdomain", "of", "the", "other", "." ]
fd616e8761b28f3eaa503fee5e45f7748e8f88f2
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/structures.py#L84-L94
train
Test if the object is a subdomain of the other.
TkTech/Jawa
jawa/assemble.py
assemble
def assemble(code): """ Assemble the given iterable of mnemonics, operands, and lables. A convienience over constructing individual Instruction and Operand objects, the output of this function can be directly piped to :class:`~jawa.attributes.code.CodeAttribute.assemble()` to produce executable...
python
def assemble(code): """ Assemble the given iterable of mnemonics, operands, and lables. A convienience over constructing individual Instruction and Operand objects, the output of this function can be directly piped to :class:`~jawa.attributes.code.CodeAttribute.assemble()` to produce executable...
[ "def", "assemble", "(", "code", ")", ":", "final", "=", "[", "]", "# We need to make three passes, because we cannot know the offset for", "# jump labels until after we've figured out the PC for each instructions,", "# which is complicated by the variable-width instructions set and", "# al...
Assemble the given iterable of mnemonics, operands, and lables. A convienience over constructing individual Instruction and Operand objects, the output of this function can be directly piped to :class:`~jawa.attributes.code.CodeAttribute.assemble()` to produce executable bytecode. As a simple exam...
[ "Assemble", "the", "given", "iterable", "of", "mnemonics", "operands", "and", "lables", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/assemble.py#L15-L115
train
Assemble the given iterable of mnemonics operands and lables and return a list of Instruction and Operand objects.
nitely/django-hooks
hooks/viewhook.py
Hook.register
def register(self, hook): """ Register a hook. @hook: a HookBase subclass reference. """ assert callable(hook), \ "Hook must be a callable" assert issubclass(hook, HookBase), \ "The hook does not inherit from HookBase" self._registry.appe...
python
def register(self, hook): """ Register a hook. @hook: a HookBase subclass reference. """ assert callable(hook), \ "Hook must be a callable" assert issubclass(hook, HookBase), \ "The hook does not inherit from HookBase" self._registry.appe...
[ "def", "register", "(", "self", ",", "hook", ")", ":", "assert", "callable", "(", "hook", ")", ",", "\"Hook must be a callable\"", "assert", "issubclass", "(", "hook", ",", "HookBase", ")", ",", "\"The hook does not inherit from HookBase\"", "self", ".", "_registr...
Register a hook. @hook: a HookBase subclass reference.
[ "Register", "a", "hook", "." ]
26ea2150c9be110e90b9ee60fbfd1065ac30ab1d
https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/viewhook.py#L101-L112
train
Register a hook.
nitely/django-hooks
hooks/formhook.py
HookFactory.save
def save(self, *args, **kwargs): """ Save all the forms :param \*args: Positional arguments passed to the forms :param \*\*kwargs: Keyword arguments passed to the forms :return: Sequence of returned values by all the forms as tuples of (instance, result) :rtype: list ...
python
def save(self, *args, **kwargs): """ Save all the forms :param \*args: Positional arguments passed to the forms :param \*\*kwargs: Keyword arguments passed to the forms :return: Sequence of returned values by all the forms as tuples of (instance, result) :rtype: list ...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "[", "(", "form", ",", "form", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "for", "form", "in", "self", ".", "instances", "]" ]
Save all the forms :param \*args: Positional arguments passed to the forms :param \*\*kwargs: Keyword arguments passed to the forms :return: Sequence of returned values by all the forms as tuples of (instance, result) :rtype: list
[ "Save", "all", "the", "forms" ]
26ea2150c9be110e90b9ee60fbfd1065ac30ab1d
https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/formhook.py#L41-L53
train
Save all the forms in the current set of keys and return the result of all the forms in the set.
networks-lab/tidyextractors
tidyextractors/tidymbox/mbox_to_pandas.py
clean_addresses
def clean_addresses(addresses): """ Cleans email address. :param addresses: List of strings (email addresses) :return: List of strings (cleaned email addresses) """ if addresses is None: return [] addresses = addresses.replace("\'", "") address_list = re.split('[,;]', addresses) ...
python
def clean_addresses(addresses): """ Cleans email address. :param addresses: List of strings (email addresses) :return: List of strings (cleaned email addresses) """ if addresses is None: return [] addresses = addresses.replace("\'", "") address_list = re.split('[,;]', addresses) ...
[ "def", "clean_addresses", "(", "addresses", ")", ":", "if", "addresses", "is", "None", ":", "return", "[", "]", "addresses", "=", "addresses", ".", "replace", "(", "\"\\'\"", ",", "\"\"", ")", "address_list", "=", "re", ".", "split", "(", "'[,;]'", ",", ...
Cleans email address. :param addresses: List of strings (email addresses) :return: List of strings (cleaned email addresses)
[ "Cleans", "email", "address", ".", ":", "param", "addresses", ":", "List", "of", "strings", "(", "email", "addresses", ")", ":", "return", ":", "List", "of", "strings", "(", "cleaned", "email", "addresses", ")" ]
658448ed533beecf32adcc188fc64d1068d15ca6
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/tidymbox/mbox_to_pandas.py#L31-L45
train
Cleans email addresses.
networks-lab/tidyextractors
tidyextractors/tidymbox/mbox_to_pandas.py
clean_address
def clean_address(address): """ Cleans a single email address. :param address: String (email address) :return: String (clean email address) """ if isinstance(address, header.Header): return clean_address(address.encode('ascii')) elif isinstance(address, str): address = addre...
python
def clean_address(address): """ Cleans a single email address. :param address: String (email address) :return: String (clean email address) """ if isinstance(address, header.Header): return clean_address(address.encode('ascii')) elif isinstance(address, str): address = addre...
[ "def", "clean_address", "(", "address", ")", ":", "if", "isinstance", "(", "address", ",", "header", ".", "Header", ")", ":", "return", "clean_address", "(", "address", ".", "encode", "(", "'ascii'", ")", ")", "elif", "isinstance", "(", "address", ",", "...
Cleans a single email address. :param address: String (email address) :return: String (clean email address)
[ "Cleans", "a", "single", "email", "address", ".", ":", "param", "address", ":", "String", "(", "email", "address", ")", ":", "return", ":", "String", "(", "clean", "email", "address", ")" ]
658448ed533beecf32adcc188fc64d1068d15ca6
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/tidymbox/mbox_to_pandas.py#L48-L88
train
Cleans a single email address.
networks-lab/tidyextractors
tidyextractors/tidymbox/mbox_to_pandas.py
get_body
def get_body(message): """ Extracts body text from an mbox message. :param message: Mbox message :return: String """ try: sm = str(message) body_start = sm.find('iamunique', sm.find('iamunique')+1) body_start = sm.find('Content-Transfer-Encoding', body_start+1) bo...
python
def get_body(message): """ Extracts body text from an mbox message. :param message: Mbox message :return: String """ try: sm = str(message) body_start = sm.find('iamunique', sm.find('iamunique')+1) body_start = sm.find('Content-Transfer-Encoding', body_start+1) bo...
[ "def", "get_body", "(", "message", ")", ":", "try", ":", "sm", "=", "str", "(", "message", ")", "body_start", "=", "sm", ".", "find", "(", "'iamunique'", ",", "sm", ".", "find", "(", "'iamunique'", ")", "+", "1", ")", "body_start", "=", "sm", ".", ...
Extracts body text from an mbox message. :param message: Mbox message :return: String
[ "Extracts", "body", "text", "from", "an", "mbox", "message", ".", ":", "param", "message", ":", "Mbox", "message", ":", "return", ":", "String" ]
658448ed533beecf32adcc188fc64d1068d15ca6
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/tidymbox/mbox_to_pandas.py#L91-L125
train
Extracts the body text from an mbox message.
networks-lab/tidyextractors
tidyextractors/tidymbox/mbox_to_pandas.py
write_table
def write_table(mboxfile, mailTable): """ Takes a list and extends it with lists of data, which is extracted from mbox messages. :param mboxfile: Mbox file name/path :param mailTable: A list (of lists) :return: An extended list of lists """ mail_box_contents = mailbox.mbox(mboxfile) ...
python
def write_table(mboxfile, mailTable): """ Takes a list and extends it with lists of data, which is extracted from mbox messages. :param mboxfile: Mbox file name/path :param mailTable: A list (of lists) :return: An extended list of lists """ mail_box_contents = mailbox.mbox(mboxfile) ...
[ "def", "write_table", "(", "mboxfile", ",", "mailTable", ")", ":", "mail_box_contents", "=", "mailbox", ".", "mbox", "(", "mboxfile", ")", "m_pbar", "=", "tqdm", ".", "tqdm", "(", "range", "(", "0", ",", "len", "(", "mail_box_contents", ")", ")", ")", ...
Takes a list and extends it with lists of data, which is extracted from mbox messages. :param mboxfile: Mbox file name/path :param mailTable: A list (of lists) :return: An extended list of lists
[ "Takes", "a", "list", "and", "extends", "it", "with", "lists", "of", "data", "which", "is", "extracted", "from", "mbox", "messages", ".", ":", "param", "mboxfile", ":", "Mbox", "file", "name", "/", "path", ":", "param", "mailTable", ":", "A", "list", "...
658448ed533beecf32adcc188fc64d1068d15ca6
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/tidymbox/mbox_to_pandas.py#L128-L164
train
Takes a list and extends it with lists of data which is extracted from mbox messages.