repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
TkTech/Jawa | jawa/fields.py | Field.pack | def pack(self, out: IO):
"""
Write the Field to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()`
"""
out.write(self.access_flags.pack())
out.write(pack('>HH', self._name_index, self._descriptor_index))
self.attributes.pack(out) | python | def pack(self, out: IO):
"""
Write the Field to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()`
"""
out.write(self.access_flags.pack())
out.write(pack('>HH', self._name_index, self._descriptor_index))
self.attributes.pack(out) | [
"def",
"pack",
"(",
"self",
",",
"out",
":",
"IO",
")",
":",
"out",
".",
"write",
"(",
"self",
".",
"access_flags",
".",
"pack",
"(",
")",
")",
"out",
".",
"write",
"(",
"pack",
"(",
"'>HH'",
",",
"self",
".",
"_name_index",
",",
"self",
".",
"_descriptor_index",
")",
")",
"self",
".",
"attributes",
".",
"pack",
"(",
"out",
")"
] | Write the Field to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()` | [
"Write",
"the",
"Field",
"to",
"the",
"file",
"-",
"like",
"object",
"out",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/fields.py#L74-L87 | train |
TkTech/Jawa | jawa/fields.py | FieldTable.remove | def remove(self, field: Field):
"""
Removes a `Field` from the table by identity.
"""
self._table = [fld for fld in self._table if fld is not field] | python | def remove(self, field: Field):
"""
Removes a `Field` from the table by identity.
"""
self._table = [fld for fld in self._table if fld is not field] | [
"def",
"remove",
"(",
"self",
",",
"field",
":",
"Field",
")",
":",
"self",
".",
"_table",
"=",
"[",
"fld",
"for",
"fld",
"in",
"self",
".",
"_table",
"if",
"fld",
"is",
"not",
"field",
"]"
] | Removes a `Field` from the table by identity. | [
"Removes",
"a",
"Field",
"from",
"the",
"table",
"by",
"identity",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/fields.py#L104-L108 | train |
TkTech/Jawa | jawa/fields.py | FieldTable.unpack | def unpack(self, source: IO):
"""
Read the FieldTable from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like object providing `read()`
"""
field_count = unpack('>H', source.read(2))[0]
for _ in repeat(None, field_count):
field = Field(self._cf)
field.unpack(source)
self.append(field) | python | def unpack(self, source: IO):
"""
Read the FieldTable from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like object providing `read()`
"""
field_count = unpack('>H', source.read(2))[0]
for _ in repeat(None, field_count):
field = Field(self._cf)
field.unpack(source)
self.append(field) | [
"def",
"unpack",
"(",
"self",
",",
"source",
":",
"IO",
")",
":",
"field_count",
"=",
"unpack",
"(",
"'>H'",
",",
"source",
".",
"read",
"(",
"2",
")",
")",
"[",
"0",
"]",
"for",
"_",
"in",
"repeat",
"(",
"None",
",",
"field_count",
")",
":",
"field",
"=",
"Field",
"(",
"self",
".",
"_cf",
")",
"field",
".",
"unpack",
"(",
"source",
")",
"self",
".",
"append",
"(",
"field",
")"
] | Read the FieldTable from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like object providing `read()` | [
"Read",
"the",
"FieldTable",
"from",
"the",
"file",
"-",
"like",
"object",
"source",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/fields.py#L150-L165 | train |
TkTech/Jawa | jawa/fields.py | FieldTable.pack | def pack(self, out: IO):
"""
Write the FieldTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()`
"""
out.write(pack('>H', len(self)))
for field in self._table:
field.pack(out) | python | def pack(self, out: IO):
"""
Write the FieldTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()`
"""
out.write(pack('>H', len(self)))
for field in self._table:
field.pack(out) | [
"def",
"pack",
"(",
"self",
",",
"out",
":",
"IO",
")",
":",
"out",
".",
"write",
"(",
"pack",
"(",
"'>H'",
",",
"len",
"(",
"self",
")",
")",
")",
"for",
"field",
"in",
"self",
".",
"_table",
":",
"field",
".",
"pack",
"(",
"out",
")"
] | Write the FieldTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()` | [
"Write",
"the",
"FieldTable",
"to",
"the",
"file",
"-",
"like",
"object",
"out",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/fields.py#L167-L180 | train |
TkTech/Jawa | jawa/fields.py | FieldTable.find | def find(self, *, name: str=None, type_: str=None,
f: Callable=None) -> Iterator[Field]:
"""
Iterates over the fields table, yielding each matching method. Calling
without any arguments is equivalent to iterating over the table.
:param name: The name of the field(s) to find.
:param type_: The field descriptor (Ex: 'I')
:param f: Any callable which takes one argument (the field).
"""
for field in self._table:
if name is not None and field.name.value != name:
continue
descriptor = field.descriptor.value
if type_ is not None and type_ != descriptor:
continue
if f is not None and not f(field):
continue
yield field | python | def find(self, *, name: str=None, type_: str=None,
f: Callable=None) -> Iterator[Field]:
"""
Iterates over the fields table, yielding each matching method. Calling
without any arguments is equivalent to iterating over the table.
:param name: The name of the field(s) to find.
:param type_: The field descriptor (Ex: 'I')
:param f: Any callable which takes one argument (the field).
"""
for field in self._table:
if name is not None and field.name.value != name:
continue
descriptor = field.descriptor.value
if type_ is not None and type_ != descriptor:
continue
if f is not None and not f(field):
continue
yield field | [
"def",
"find",
"(",
"self",
",",
"*",
",",
"name",
":",
"str",
"=",
"None",
",",
"type_",
":",
"str",
"=",
"None",
",",
"f",
":",
"Callable",
"=",
"None",
")",
"->",
"Iterator",
"[",
"Field",
"]",
":",
"for",
"field",
"in",
"self",
".",
"_table",
":",
"if",
"name",
"is",
"not",
"None",
"and",
"field",
".",
"name",
".",
"value",
"!=",
"name",
":",
"continue",
"descriptor",
"=",
"field",
".",
"descriptor",
".",
"value",
"if",
"type_",
"is",
"not",
"None",
"and",
"type_",
"!=",
"descriptor",
":",
"continue",
"if",
"f",
"is",
"not",
"None",
"and",
"not",
"f",
"(",
"field",
")",
":",
"continue",
"yield",
"field"
] | Iterates over the fields table, yielding each matching method. Calling
without any arguments is equivalent to iterating over the table.
:param name: The name of the field(s) to find.
:param type_: The field descriptor (Ex: 'I')
:param f: Any callable which takes one argument (the field). | [
"Iterates",
"over",
"the",
"fields",
"table",
"yielding",
"each",
"matching",
"method",
".",
"Calling",
"without",
"any",
"arguments",
"is",
"equivalent",
"to",
"iterating",
"over",
"the",
"table",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/fields.py#L185-L206 | train |
piotr-rusin/spam-lists | spam_lists/validation.py | is_valid_host | def is_valid_host(value):
"""Check if given value is a valid host string.
:param value: a value to test
:returns: True if the value is valid
"""
host_validators = validators.ipv4, validators.ipv6, validators.domain
return any(f(value) for f in host_validators) | python | def is_valid_host(value):
"""Check if given value is a valid host string.
:param value: a value to test
:returns: True if the value is valid
"""
host_validators = validators.ipv4, validators.ipv6, validators.domain
return any(f(value) for f in host_validators) | [
"def",
"is_valid_host",
"(",
"value",
")",
":",
"host_validators",
"=",
"validators",
".",
"ipv4",
",",
"validators",
".",
"ipv6",
",",
"validators",
".",
"domain",
"return",
"any",
"(",
"f",
"(",
"value",
")",
"for",
"f",
"in",
"host_validators",
")"
] | Check if given value is a valid host string.
:param value: a value to test
:returns: True if the value is valid | [
"Check",
"if",
"given",
"value",
"is",
"a",
"valid",
"host",
"string",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/validation.py#L15-L22 | train |
piotr-rusin/spam-lists | spam_lists/validation.py | is_valid_url | def is_valid_url(value):
"""Check if given value is a valid URL string.
:param value: a value to test
:returns: True if the value is valid
"""
match = URL_REGEX.match(value)
host_str = urlparse(value).hostname
return match and is_valid_host(host_str) | python | def is_valid_url(value):
"""Check if given value is a valid URL string.
:param value: a value to test
:returns: True if the value is valid
"""
match = URL_REGEX.match(value)
host_str = urlparse(value).hostname
return match and is_valid_host(host_str) | [
"def",
"is_valid_url",
"(",
"value",
")",
":",
"match",
"=",
"URL_REGEX",
".",
"match",
"(",
"value",
")",
"host_str",
"=",
"urlparse",
"(",
"value",
")",
".",
"hostname",
"return",
"match",
"and",
"is_valid_host",
"(",
"host_str",
")"
] | Check if given value is a valid URL string.
:param value: a value to test
:returns: True if the value is valid | [
"Check",
"if",
"given",
"value",
"is",
"a",
"valid",
"URL",
"string",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/validation.py#L33-L41 | train |
piotr-rusin/spam-lists | spam_lists/validation.py | accepts_valid_host | def accepts_valid_host(func):
"""Return a wrapper that runs given method only for valid hosts.
:param func: a method to be wrapped
:returns: a wrapper that adds argument validation
"""
@functools.wraps(func)
def wrapper(obj, value, *args, **kwargs):
"""Run the function and return a value for a valid host.
:param obj: an object in whose class the func is defined
:param value: a value expected to be a valid host string
:returns: a return value of the function func
:raises InvalidHostError: if the value is not valid
"""
if not is_valid_host(value):
raise InvalidHostError
return func(obj, value, *args, **kwargs)
return wrapper | python | def accepts_valid_host(func):
"""Return a wrapper that runs given method only for valid hosts.
:param func: a method to be wrapped
:returns: a wrapper that adds argument validation
"""
@functools.wraps(func)
def wrapper(obj, value, *args, **kwargs):
"""Run the function and return a value for a valid host.
:param obj: an object in whose class the func is defined
:param value: a value expected to be a valid host string
:returns: a return value of the function func
:raises InvalidHostError: if the value is not valid
"""
if not is_valid_host(value):
raise InvalidHostError
return func(obj, value, *args, **kwargs)
return wrapper | [
"def",
"accepts_valid_host",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"obj",
",",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Run the function and return a value for a valid host.\n\n :param obj: an object in whose class the func is defined\n :param value: a value expected to be a valid host string\n :returns: a return value of the function func\n :raises InvalidHostError: if the value is not valid\n \"\"\"",
"if",
"not",
"is_valid_host",
"(",
"value",
")",
":",
"raise",
"InvalidHostError",
"return",
"func",
"(",
"obj",
",",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | Return a wrapper that runs given method only for valid hosts.
:param func: a method to be wrapped
:returns: a wrapper that adds argument validation | [
"Return",
"a",
"wrapper",
"that",
"runs",
"given",
"method",
"only",
"for",
"valid",
"hosts",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/validation.py#L44-L62 | train |
piotr-rusin/spam-lists | spam_lists/validation.py | accepts_valid_urls | def accepts_valid_urls(func):
"""Return a wrapper that runs given method only for valid URLs.
:param func: a method to be wrapped
:returns: a wrapper that adds argument validation
"""
@functools.wraps(func)
def wrapper(obj, urls, *args, **kwargs):
"""Run the function and return a value for valid URLs.
:param obj: an object in whose class f is defined
:param urls: an iterable containing URLs
:returns: a return value of the function f
:raises InvalidURLError: if the iterable contains invalid URLs
"""
invalid_urls = [u for u in urls if not is_valid_url(u)]
if invalid_urls:
msg_tpl = 'The values: {} are not valid URLs'
msg = msg_tpl.format(','.join(invalid_urls))
raise InvalidURLError(msg)
return func(obj, urls, *args, **kwargs)
return wrapper | python | def accepts_valid_urls(func):
"""Return a wrapper that runs given method only for valid URLs.
:param func: a method to be wrapped
:returns: a wrapper that adds argument validation
"""
@functools.wraps(func)
def wrapper(obj, urls, *args, **kwargs):
"""Run the function and return a value for valid URLs.
:param obj: an object in whose class f is defined
:param urls: an iterable containing URLs
:returns: a return value of the function f
:raises InvalidURLError: if the iterable contains invalid URLs
"""
invalid_urls = [u for u in urls if not is_valid_url(u)]
if invalid_urls:
msg_tpl = 'The values: {} are not valid URLs'
msg = msg_tpl.format(','.join(invalid_urls))
raise InvalidURLError(msg)
return func(obj, urls, *args, **kwargs)
return wrapper | [
"def",
"accepts_valid_urls",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"obj",
",",
"urls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Run the function and return a value for valid URLs.\n\n :param obj: an object in whose class f is defined\n :param urls: an iterable containing URLs\n :returns: a return value of the function f\n :raises InvalidURLError: if the iterable contains invalid URLs\n \"\"\"",
"invalid_urls",
"=",
"[",
"u",
"for",
"u",
"in",
"urls",
"if",
"not",
"is_valid_url",
"(",
"u",
")",
"]",
"if",
"invalid_urls",
":",
"msg_tpl",
"=",
"'The values: {} are not valid URLs'",
"msg",
"=",
"msg_tpl",
".",
"format",
"(",
"','",
".",
"join",
"(",
"invalid_urls",
")",
")",
"raise",
"InvalidURLError",
"(",
"msg",
")",
"return",
"func",
"(",
"obj",
",",
"urls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | Return a wrapper that runs given method only for valid URLs.
:param func: a method to be wrapped
:returns: a wrapper that adds argument validation | [
"Return",
"a",
"wrapper",
"that",
"runs",
"given",
"method",
"only",
"for",
"valid",
"URLs",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/validation.py#L65-L86 | train |
TkTech/Jawa | jawa/constants.py | ConstantPool.get | def get(self, index):
"""
Returns the `Constant` at `index`, raising a KeyError if it
does not exist.
"""
constant = self._pool[index]
if not isinstance(constant, Constant):
constant = _constant_types[constant[0]](self, index, *constant[1:])
self._pool[index] = constant
return constant | python | def get(self, index):
"""
Returns the `Constant` at `index`, raising a KeyError if it
does not exist.
"""
constant = self._pool[index]
if not isinstance(constant, Constant):
constant = _constant_types[constant[0]](self, index, *constant[1:])
self._pool[index] = constant
return constant | [
"def",
"get",
"(",
"self",
",",
"index",
")",
":",
"constant",
"=",
"self",
".",
"_pool",
"[",
"index",
"]",
"if",
"not",
"isinstance",
"(",
"constant",
",",
"Constant",
")",
":",
"constant",
"=",
"_constant_types",
"[",
"constant",
"[",
"0",
"]",
"]",
"(",
"self",
",",
"index",
",",
"*",
"constant",
"[",
"1",
":",
"]",
")",
"self",
".",
"_pool",
"[",
"index",
"]",
"=",
"constant",
"return",
"constant"
] | Returns the `Constant` at `index`, raising a KeyError if it
does not exist. | [
"Returns",
"the",
"Constant",
"at",
"index",
"raising",
"a",
"KeyError",
"if",
"it",
"does",
"not",
"exist",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/constants.py#L352-L361 | train |
TkTech/Jawa | jawa/constants.py | ConstantPool.find | def find(self, type_=None, f=None):
"""
Iterates over the pool, yielding each matching ``Constant``. Calling
without any arguments is equivalent to iterating over the pool.
:param type_: Any subclass of :class:`Constant` or ``None``.
:param f: Any callable which takes one argument (the constant).
"""
for constant in self:
if type_ is not None and not isinstance(constant, type_):
continue
if f is not None and not f(constant):
continue
yield constant | python | def find(self, type_=None, f=None):
"""
Iterates over the pool, yielding each matching ``Constant``. Calling
without any arguments is equivalent to iterating over the pool.
:param type_: Any subclass of :class:`Constant` or ``None``.
:param f: Any callable which takes one argument (the constant).
"""
for constant in self:
if type_ is not None and not isinstance(constant, type_):
continue
if f is not None and not f(constant):
continue
yield constant | [
"def",
"find",
"(",
"self",
",",
"type_",
"=",
"None",
",",
"f",
"=",
"None",
")",
":",
"for",
"constant",
"in",
"self",
":",
"if",
"type_",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"constant",
",",
"type_",
")",
":",
"continue",
"if",
"f",
"is",
"not",
"None",
"and",
"not",
"f",
"(",
"constant",
")",
":",
"continue",
"yield",
"constant"
] | Iterates over the pool, yielding each matching ``Constant``. Calling
without any arguments is equivalent to iterating over the pool.
:param type_: Any subclass of :class:`Constant` or ``None``.
:param f: Any callable which takes one argument (the constant). | [
"Iterates",
"over",
"the",
"pool",
"yielding",
"each",
"matching",
"Constant",
".",
"Calling",
"without",
"any",
"arguments",
"is",
"equivalent",
"to",
"iterating",
"over",
"the",
"pool",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/constants.py#L369-L384 | train |
TkTech/Jawa | jawa/constants.py | ConstantPool.pack | def pack(self, fout):
"""
Write the ConstantPool to the file-like object `fout`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be calle=d for you when saving a ClassFile.
:param fout: Any file-like object providing `write()`
"""
write = fout.write
write(pack('>H', self.raw_count))
for constant in self:
write(constant.pack()) | python | def pack(self, fout):
"""
Write the ConstantPool to the file-like object `fout`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be calle=d for you when saving a ClassFile.
:param fout: Any file-like object providing `write()`
"""
write = fout.write
write(pack('>H', self.raw_count))
for constant in self:
write(constant.pack()) | [
"def",
"pack",
"(",
"self",
",",
"fout",
")",
":",
"write",
"=",
"fout",
".",
"write",
"write",
"(",
"pack",
"(",
"'>H'",
",",
"self",
".",
"raw_count",
")",
")",
"for",
"constant",
"in",
"self",
":",
"write",
"(",
"constant",
".",
"pack",
"(",
")",
")"
] | Write the ConstantPool to the file-like object `fout`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be calle=d for you when saving a ClassFile.
:param fout: Any file-like object providing `write()` | [
"Write",
"the",
"ConstantPool",
"to",
"the",
"file",
"-",
"like",
"object",
"fout",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/constants.py#L583-L598 | train |
Azure/azure-python-devtools | src/azure_devtools/ci_tools/git_tools.py | checkout_and_create_branch | def checkout_and_create_branch(repo, name):
"""Checkout branch. Create it if necessary"""
local_branch = repo.branches[name] if name in repo.branches else None
if not local_branch:
if name in repo.remotes.origin.refs:
# If origin branch exists but not local, git.checkout is the fatest way
# to create local branch with origin link automatically
msg = repo.git.checkout(name)
_LOGGER.debug(msg)
return
# Create local branch, will be link to origin later
local_branch = repo.create_head(name)
local_branch.checkout() | python | def checkout_and_create_branch(repo, name):
"""Checkout branch. Create it if necessary"""
local_branch = repo.branches[name] if name in repo.branches else None
if not local_branch:
if name in repo.remotes.origin.refs:
# If origin branch exists but not local, git.checkout is the fatest way
# to create local branch with origin link automatically
msg = repo.git.checkout(name)
_LOGGER.debug(msg)
return
# Create local branch, will be link to origin later
local_branch = repo.create_head(name)
local_branch.checkout() | [
"def",
"checkout_and_create_branch",
"(",
"repo",
",",
"name",
")",
":",
"local_branch",
"=",
"repo",
".",
"branches",
"[",
"name",
"]",
"if",
"name",
"in",
"repo",
".",
"branches",
"else",
"None",
"if",
"not",
"local_branch",
":",
"if",
"name",
"in",
"repo",
".",
"remotes",
".",
"origin",
".",
"refs",
":",
"# If origin branch exists but not local, git.checkout is the fatest way",
"# to create local branch with origin link automatically",
"msg",
"=",
"repo",
".",
"git",
".",
"checkout",
"(",
"name",
")",
"_LOGGER",
".",
"debug",
"(",
"msg",
")",
"return",
"# Create local branch, will be link to origin later",
"local_branch",
"=",
"repo",
".",
"create_head",
"(",
"name",
")",
"local_branch",
".",
"checkout",
"(",
")"
] | Checkout branch. Create it if necessary | [
"Checkout",
"branch",
".",
"Create",
"it",
"if",
"necessary"
] | 2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936 | https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/git_tools.py#L9-L21 | train |
Azure/azure-python-devtools | src/azure_devtools/ci_tools/git_tools.py | checkout_create_push_branch | def checkout_create_push_branch(repo, name):
"""Checkout this branch. Create it if necessary, and push it to origin.
"""
try:
repo.git.checkout(name)
_LOGGER.info("Checkout %s success", name)
except GitCommandError:
_LOGGER.info("Checkout %s was impossible (branch does not exist). Creating it and push it.", name)
checkout_and_create_branch(repo, name)
repo.git.push('origin', name, set_upstream=True) | python | def checkout_create_push_branch(repo, name):
"""Checkout this branch. Create it if necessary, and push it to origin.
"""
try:
repo.git.checkout(name)
_LOGGER.info("Checkout %s success", name)
except GitCommandError:
_LOGGER.info("Checkout %s was impossible (branch does not exist). Creating it and push it.", name)
checkout_and_create_branch(repo, name)
repo.git.push('origin', name, set_upstream=True) | [
"def",
"checkout_create_push_branch",
"(",
"repo",
",",
"name",
")",
":",
"try",
":",
"repo",
".",
"git",
".",
"checkout",
"(",
"name",
")",
"_LOGGER",
".",
"info",
"(",
"\"Checkout %s success\"",
",",
"name",
")",
"except",
"GitCommandError",
":",
"_LOGGER",
".",
"info",
"(",
"\"Checkout %s was impossible (branch does not exist). Creating it and push it.\"",
",",
"name",
")",
"checkout_and_create_branch",
"(",
"repo",
",",
"name",
")",
"repo",
".",
"git",
".",
"push",
"(",
"'origin'",
",",
"name",
",",
"set_upstream",
"=",
"True",
")"
] | Checkout this branch. Create it if necessary, and push it to origin. | [
"Checkout",
"this",
"branch",
".",
"Create",
"it",
"if",
"necessary",
"and",
"push",
"it",
"to",
"origin",
"."
] | 2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936 | https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/git_tools.py#L23-L32 | train |
Azure/azure-python-devtools | src/azure_devtools/ci_tools/git_tools.py | get_repo_hexsha | def get_repo_hexsha(git_folder):
"""Get the SHA1 of the current repo"""
repo = Repo(str(git_folder))
if repo.bare:
not_git_hexsha = "notgitrepo"
_LOGGER.warning("Not a git repo, SHA1 used will be: %s", not_git_hexsha)
return not_git_hexsha
hexsha = repo.head.commit.hexsha
_LOGGER.info("Found REST API repo SHA1: %s", hexsha)
return hexsha | python | def get_repo_hexsha(git_folder):
"""Get the SHA1 of the current repo"""
repo = Repo(str(git_folder))
if repo.bare:
not_git_hexsha = "notgitrepo"
_LOGGER.warning("Not a git repo, SHA1 used will be: %s", not_git_hexsha)
return not_git_hexsha
hexsha = repo.head.commit.hexsha
_LOGGER.info("Found REST API repo SHA1: %s", hexsha)
return hexsha | [
"def",
"get_repo_hexsha",
"(",
"git_folder",
")",
":",
"repo",
"=",
"Repo",
"(",
"str",
"(",
"git_folder",
")",
")",
"if",
"repo",
".",
"bare",
":",
"not_git_hexsha",
"=",
"\"notgitrepo\"",
"_LOGGER",
".",
"warning",
"(",
"\"Not a git repo, SHA1 used will be: %s\"",
",",
"not_git_hexsha",
")",
"return",
"not_git_hexsha",
"hexsha",
"=",
"repo",
".",
"head",
".",
"commit",
".",
"hexsha",
"_LOGGER",
".",
"info",
"(",
"\"Found REST API repo SHA1: %s\"",
",",
"hexsha",
")",
"return",
"hexsha"
] | Get the SHA1 of the current repo | [
"Get",
"the",
"SHA1",
"of",
"the",
"current",
"repo"
] | 2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936 | https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/git_tools.py#L49-L58 | train |
Azure/azure-python-devtools | src/azure_devtools/ci_tools/git_tools.py | checkout_with_fetch | def checkout_with_fetch(git_folder, refspec, repository="origin"):
"""Fetch the refspec, and checkout FETCH_HEAD.
Beware that you will ne in detached head mode.
"""
_LOGGER.info("Trying to fetch and checkout %s", refspec)
repo = Repo(str(git_folder))
repo.git.fetch(repository, refspec) # FETCH_HEAD should be set
repo.git.checkout("FETCH_HEAD")
_LOGGER.info("Fetch and checkout success for %s", refspec) | python | def checkout_with_fetch(git_folder, refspec, repository="origin"):
"""Fetch the refspec, and checkout FETCH_HEAD.
Beware that you will ne in detached head mode.
"""
_LOGGER.info("Trying to fetch and checkout %s", refspec)
repo = Repo(str(git_folder))
repo.git.fetch(repository, refspec) # FETCH_HEAD should be set
repo.git.checkout("FETCH_HEAD")
_LOGGER.info("Fetch and checkout success for %s", refspec) | [
"def",
"checkout_with_fetch",
"(",
"git_folder",
",",
"refspec",
",",
"repository",
"=",
"\"origin\"",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Trying to fetch and checkout %s\"",
",",
"refspec",
")",
"repo",
"=",
"Repo",
"(",
"str",
"(",
"git_folder",
")",
")",
"repo",
".",
"git",
".",
"fetch",
"(",
"repository",
",",
"refspec",
")",
"# FETCH_HEAD should be set",
"repo",
".",
"git",
".",
"checkout",
"(",
"\"FETCH_HEAD\"",
")",
"_LOGGER",
".",
"info",
"(",
"\"Fetch and checkout success for %s\"",
",",
"refspec",
")"
] | Fetch the refspec, and checkout FETCH_HEAD.
Beware that you will ne in detached head mode. | [
"Fetch",
"the",
"refspec",
"and",
"checkout",
"FETCH_HEAD",
".",
"Beware",
"that",
"you",
"will",
"ne",
"in",
"detached",
"head",
"mode",
"."
] | 2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936 | https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/git_tools.py#L60-L68 | train |
Azure/azure-python-devtools | src/azure_devtools/ci_tools/git_tools.py | clone_to_path | def clone_to_path(https_authenticated_url, folder, branch_or_commit=None):
"""Clone the given URL to the folder.
:param str branch_or_commit: If specified, switch to this branch. Branch must exist.
"""
_LOGGER.info("Cloning repo")
repo = Repo.clone_from(https_authenticated_url, str(folder))
# Do NOT clone and set branch at the same time, since we allow branch to be a SHA1
# And you can't clone a SHA1
if branch_or_commit:
_LOGGER.info("Checkout branch_or_commit %s", branch_or_commit)
repo.git.checkout(branch_or_commit)
_LOGGER.info("Clone success") | python | def clone_to_path(https_authenticated_url, folder, branch_or_commit=None):
"""Clone the given URL to the folder.
:param str branch_or_commit: If specified, switch to this branch. Branch must exist.
"""
_LOGGER.info("Cloning repo")
repo = Repo.clone_from(https_authenticated_url, str(folder))
# Do NOT clone and set branch at the same time, since we allow branch to be a SHA1
# And you can't clone a SHA1
if branch_or_commit:
_LOGGER.info("Checkout branch_or_commit %s", branch_or_commit)
repo.git.checkout(branch_or_commit)
_LOGGER.info("Clone success") | [
"def",
"clone_to_path",
"(",
"https_authenticated_url",
",",
"folder",
",",
"branch_or_commit",
"=",
"None",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Cloning repo\"",
")",
"repo",
"=",
"Repo",
".",
"clone_from",
"(",
"https_authenticated_url",
",",
"str",
"(",
"folder",
")",
")",
"# Do NOT clone and set branch at the same time, since we allow branch to be a SHA1",
"# And you can't clone a SHA1",
"if",
"branch_or_commit",
":",
"_LOGGER",
".",
"info",
"(",
"\"Checkout branch_or_commit %s\"",
",",
"branch_or_commit",
")",
"repo",
".",
"git",
".",
"checkout",
"(",
"branch_or_commit",
")",
"_LOGGER",
".",
"info",
"(",
"\"Clone success\"",
")"
] | Clone the given URL to the folder.
:param str branch_or_commit: If specified, switch to this branch. Branch must exist. | [
"Clone",
"the",
"given",
"URL",
"to",
"the",
"folder",
"."
] | 2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936 | https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/git_tools.py#L70-L83 | train |
Azure/azure-python-devtools | src/azure_devtools/ci_tools/git_tools.py | get_files_in_commit | def get_files_in_commit(git_folder, commit_id="HEAD"):
"""List of files in HEAD commit.
"""
repo = Repo(str(git_folder))
output = repo.git.diff("--name-only", commit_id+"^", commit_id)
return output.splitlines() | python | def get_files_in_commit(git_folder, commit_id="HEAD"):
"""List of files in HEAD commit.
"""
repo = Repo(str(git_folder))
output = repo.git.diff("--name-only", commit_id+"^", commit_id)
return output.splitlines() | [
"def",
"get_files_in_commit",
"(",
"git_folder",
",",
"commit_id",
"=",
"\"HEAD\"",
")",
":",
"repo",
"=",
"Repo",
"(",
"str",
"(",
"git_folder",
")",
")",
"output",
"=",
"repo",
".",
"git",
".",
"diff",
"(",
"\"--name-only\"",
",",
"commit_id",
"+",
"\"^\"",
",",
"commit_id",
")",
"return",
"output",
".",
"splitlines",
"(",
")"
] | List of files in HEAD commit. | [
"List",
"of",
"files",
"in",
"HEAD",
"commit",
"."
] | 2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936 | https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/git_tools.py#L85-L90 | train |
qwiglydee/drf-mongo-filters | drf_mongo_filters/filtersets.py | BaseFilterset.parse_values | def parse_values(self, query):
"""
extract values from query
"""
values = {}
for name, filt in self.filters.items():
val = filt.parse_value(query)
if val is None:
continue
values[name] = val
return values | python | def parse_values(self, query):
"""
extract values from query
"""
values = {}
for name, filt in self.filters.items():
val = filt.parse_value(query)
if val is None:
continue
values[name] = val
return values | [
"def",
"parse_values",
"(",
"self",
",",
"query",
")",
":",
"values",
"=",
"{",
"}",
"for",
"name",
",",
"filt",
"in",
"self",
".",
"filters",
".",
"items",
"(",
")",
":",
"val",
"=",
"filt",
".",
"parse_value",
"(",
"query",
")",
"if",
"val",
"is",
"None",
":",
"continue",
"values",
"[",
"name",
"]",
"=",
"val",
"return",
"values"
] | extract values from query | [
"extract",
"values",
"from",
"query"
] | f7e397c329bac6d7b8cbb1df70d96eccdcfbc1ec | https://github.com/qwiglydee/drf-mongo-filters/blob/f7e397c329bac6d7b8cbb1df70d96eccdcfbc1ec/drf_mongo_filters/filtersets.py#L49-L59 | train |
qwiglydee/drf-mongo-filters | drf_mongo_filters/filtersets.py | BaseFilterset.filter_queryset | def filter_queryset(self, queryset):
"""
convert values to filtering params and apply to queryset
"""
for name, filt in self.filters.items():
val = self.values.get(name, None)
if name is None:
continue
params = filt.filter_params(val)
if not params:
continue
if isinstance(params, dict):
queryset = queryset.filter(**params)
if isinstance(params, QNode):
queryset = queryset.filter(params)
return queryset | python | def filter_queryset(self, queryset):
"""
convert values to filtering params and apply to queryset
"""
for name, filt in self.filters.items():
val = self.values.get(name, None)
if name is None:
continue
params = filt.filter_params(val)
if not params:
continue
if isinstance(params, dict):
queryset = queryset.filter(**params)
if isinstance(params, QNode):
queryset = queryset.filter(params)
return queryset | [
"def",
"filter_queryset",
"(",
"self",
",",
"queryset",
")",
":",
"for",
"name",
",",
"filt",
"in",
"self",
".",
"filters",
".",
"items",
"(",
")",
":",
"val",
"=",
"self",
".",
"values",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"name",
"is",
"None",
":",
"continue",
"params",
"=",
"filt",
".",
"filter_params",
"(",
"val",
")",
"if",
"not",
"params",
":",
"continue",
"if",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"*",
"*",
"params",
")",
"if",
"isinstance",
"(",
"params",
",",
"QNode",
")",
":",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"params",
")",
"return",
"queryset"
] | convert values to filtering params and apply to queryset | [
"convert",
"values",
"to",
"filtering",
"params",
"and",
"apply",
"to",
"queryset"
] | f7e397c329bac6d7b8cbb1df70d96eccdcfbc1ec | https://github.com/qwiglydee/drf-mongo-filters/blob/f7e397c329bac6d7b8cbb1df70d96eccdcfbc1ec/drf_mongo_filters/filtersets.py#L61-L76 | train |
mezz64/pyEmby | pyemby/device.py | EmbyDevice.media_image_url | def media_image_url(self):
"""Image url of current playing media."""
if self.is_nowplaying:
base = self.server.construct_url(API_URL)
try:
image_id = self.session['NowPlayingItem']['ImageTags']['Thumb']
image_type = 'Thumb'
except KeyError:
try:
image_id = self.session[
'NowPlayingItem']['ImageTags']['Primary']
image_type = 'Primary'
except KeyError:
return None
url = '{0}/Items/{1}/Images/{2}?width=500&tag={3}&api_key={4}'.format(
base, self.media_id, image_type, image_id, self.server.api_key)
return url
else:
return None | python | def media_image_url(self):
"""Image url of current playing media."""
if self.is_nowplaying:
base = self.server.construct_url(API_URL)
try:
image_id = self.session['NowPlayingItem']['ImageTags']['Thumb']
image_type = 'Thumb'
except KeyError:
try:
image_id = self.session[
'NowPlayingItem']['ImageTags']['Primary']
image_type = 'Primary'
except KeyError:
return None
url = '{0}/Items/{1}/Images/{2}?width=500&tag={3}&api_key={4}'.format(
base, self.media_id, image_type, image_id, self.server.api_key)
return url
else:
return None | [
"def",
"media_image_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_nowplaying",
":",
"base",
"=",
"self",
".",
"server",
".",
"construct_url",
"(",
"API_URL",
")",
"try",
":",
"image_id",
"=",
"self",
".",
"session",
"[",
"'NowPlayingItem'",
"]",
"[",
"'ImageTags'",
"]",
"[",
"'Thumb'",
"]",
"image_type",
"=",
"'Thumb'",
"except",
"KeyError",
":",
"try",
":",
"image_id",
"=",
"self",
".",
"session",
"[",
"'NowPlayingItem'",
"]",
"[",
"'ImageTags'",
"]",
"[",
"'Primary'",
"]",
"image_type",
"=",
"'Primary'",
"except",
"KeyError",
":",
"return",
"None",
"url",
"=",
"'{0}/Items/{1}/Images/{2}?width=500&tag={3}&api_key={4}'",
".",
"format",
"(",
"base",
",",
"self",
".",
"media_id",
",",
"image_type",
",",
"image_id",
",",
"self",
".",
"server",
".",
"api_key",
")",
"return",
"url",
"else",
":",
"return",
"None"
] | Image url of current playing media. | [
"Image",
"url",
"of",
"current",
"playing",
"media",
"."
] | 6bb621e4e25bf1b9b0aba2c38b588e68f8816226 | https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/device.py#L178-L196 | train |
mezz64/pyEmby | pyemby/device.py | EmbyDevice.state | def state(self):
""" Return current playstate of the device. """
if self.is_active:
if 'NowPlayingItem' in self.session:
if self.session['PlayState']['IsPaused']:
return STATE_PAUSED
else:
return STATE_PLAYING
else:
return STATE_IDLE
else:
return STATE_OFF | python | def state(self):
""" Return current playstate of the device. """
if self.is_active:
if 'NowPlayingItem' in self.session:
if self.session['PlayState']['IsPaused']:
return STATE_PAUSED
else:
return STATE_PLAYING
else:
return STATE_IDLE
else:
return STATE_OFF | [
"def",
"state",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_active",
":",
"if",
"'NowPlayingItem'",
"in",
"self",
".",
"session",
":",
"if",
"self",
".",
"session",
"[",
"'PlayState'",
"]",
"[",
"'IsPaused'",
"]",
":",
"return",
"STATE_PAUSED",
"else",
":",
"return",
"STATE_PLAYING",
"else",
":",
"return",
"STATE_IDLE",
"else",
":",
"return",
"STATE_OFF"
] | Return current playstate of the device. | [
"Return",
"current",
"playstate",
"of",
"the",
"device",
"."
] | 6bb621e4e25bf1b9b0aba2c38b588e68f8816226 | https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/device.py#L224-L235 | train |
mezz64/pyEmby | pyemby/device.py | EmbyDevice.set_playstate | async def set_playstate(self, state, pos=0):
""" Send media commands to server. """
url = '{}/Sessions/{}/Playing/{}'.format(
self.server.construct_url(API_URL), self.session_id, state)
params = {'api_key': self.server.api_key}
if state == 'seek':
params['SeekPositionTicks'] = int(pos * 10000000)
params['static'] = 'true'
_LOGGER.debug('Playstate URL: %s', url)
post = await self.server.api_post(url, params)
if post is None:
_LOGGER.debug('Error sending command.')
else:
_LOGGER.debug('Post response: %s', post) | python | async def set_playstate(self, state, pos=0):
""" Send media commands to server. """
url = '{}/Sessions/{}/Playing/{}'.format(
self.server.construct_url(API_URL), self.session_id, state)
params = {'api_key': self.server.api_key}
if state == 'seek':
params['SeekPositionTicks'] = int(pos * 10000000)
params['static'] = 'true'
_LOGGER.debug('Playstate URL: %s', url)
post = await self.server.api_post(url, params)
if post is None:
_LOGGER.debug('Error sending command.')
else:
_LOGGER.debug('Post response: %s', post) | [
"async",
"def",
"set_playstate",
"(",
"self",
",",
"state",
",",
"pos",
"=",
"0",
")",
":",
"url",
"=",
"'{}/Sessions/{}/Playing/{}'",
".",
"format",
"(",
"self",
".",
"server",
".",
"construct_url",
"(",
"API_URL",
")",
",",
"self",
".",
"session_id",
",",
"state",
")",
"params",
"=",
"{",
"'api_key'",
":",
"self",
".",
"server",
".",
"api_key",
"}",
"if",
"state",
"==",
"'seek'",
":",
"params",
"[",
"'SeekPositionTicks'",
"]",
"=",
"int",
"(",
"pos",
"*",
"10000000",
")",
"params",
"[",
"'static'",
"]",
"=",
"'true'",
"_LOGGER",
".",
"debug",
"(",
"'Playstate URL: %s'",
",",
"url",
")",
"post",
"=",
"await",
"self",
".",
"server",
".",
"api_post",
"(",
"url",
",",
"params",
")",
"if",
"post",
"is",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"'Error sending command.'",
")",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"'Post response: %s'",
",",
"post",
")"
] | Send media commands to server. | [
"Send",
"media",
"commands",
"to",
"server",
"."
] | 6bb621e4e25bf1b9b0aba2c38b588e68f8816226 | https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/device.py#L250-L266 | train |
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 newly created shell.
:param banner: An optional banner to render when terminal starts.
"""
if IPYTHON_SHELL_AVAILABLE:
# Don't try to stop IPython from displaying its banner, since
# it's different in every major version
terminal = embed.InteractiveShellEmbed(user_ns={})
terminal.mainloop(local_ns=local_ns)
else:
code.interact(banner=banner, local=local_ns) | 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 newly created shell.
:param banner: An optional banner to render when terminal starts.
"""
if IPYTHON_SHELL_AVAILABLE:
# Don't try to stop IPython from displaying its banner, since
# it's different in every major version
terminal = embed.InteractiveShellEmbed(user_ns={})
terminal.mainloop(local_ns=local_ns)
else:
code.interact(banner=banner, local=local_ns) | [
"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",
"=",
"embed",
".",
"InteractiveShellEmbed",
"(",
"user_ns",
"=",
"{",
"}",
")",
"terminal",
".",
"mainloop",
"(",
"local_ns",
"=",
"local_ns",
")",
"else",
":",
"code",
".",
"interact",
"(",
"banner",
"=",
"banner",
",",
"local",
"=",
"local_ns",
")"
] | 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 render when terminal starts. | [
"Create",
"and",
"immediately",
"drop",
"into",
"a",
"Python",
"shell",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/shell.py#L13-L29 | train |
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 instruction.
"""
for i, operand in enumerate(ins.operands):
if not isinstance(operand, Operand):
continue
if operand.op_type == OperandTypes.CONSTANT_INDEX:
ins.operands[i] = cf.constants[operand.value]
return ins | 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 instruction.
"""
for i, operand in enumerate(ins.operands):
if not isinstance(operand, Operand):
continue
if operand.op_type == OperandTypes.CONSTANT_INDEX:
ins.operands[i] = cf.constants[operand.value]
return ins | [
"def",
"expand_constants",
"(",
"ins",
":",
"Instruction",
",",
"*",
",",
"cf",
")",
"->",
"Instruction",
":",
"for",
"i",
",",
"operand",
"in",
"enumerate",
"(",
"ins",
".",
"operands",
")",
":",
"if",
"not",
"isinstance",
"(",
"operand",
",",
"Operand",
")",
":",
"continue",
"if",
"operand",
".",
"op_type",
"==",
"OperandTypes",
".",
"CONSTANT_INDEX",
":",
"ins",
".",
"operands",
"[",
"i",
"]",
"=",
"cf",
".",
"constants",
"[",
"operand",
".",
"value",
"]",
"return",
"ins"
] | 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 |
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: Instruction to potentially modify.
:return: Potentially modified instruction.
"""
try:
rule = ins.details['transform']['simple_swap']
except KeyError:
return ins
replacement_ins = opcode_table[rule['op']]
return Instruction(
replacement_ins['mnemonic'],
replacement_ins['op'],
[Operand(
replacement_ins['operands'][i][1],
r
) for i, r in enumerate(rule['operands'])],
ins.pos
) | 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: Instruction to potentially modify.
:return: Potentially modified instruction.
"""
try:
rule = ins.details['transform']['simple_swap']
except KeyError:
return ins
replacement_ins = opcode_table[rule['op']]
return Instruction(
replacement_ins['mnemonic'],
replacement_ins['op'],
[Operand(
replacement_ins['operands'][i][1],
r
) for i, r in enumerate(rule['operands'])],
ins.pos
) | [
"def",
"simple_swap",
"(",
"ins",
":",
"Instruction",
")",
"->",
"Instruction",
":",
"try",
":",
"rule",
"=",
"ins",
".",
"details",
"[",
"'transform'",
"]",
"[",
"'simple_swap'",
"]",
"except",
"KeyError",
":",
"return",
"ins",
"replacement_ins",
"=",
"opcode_table",
"[",
"rule",
"[",
"'op'",
"]",
"]",
"return",
"Instruction",
"(",
"replacement_ins",
"[",
"'mnemonic'",
"]",
",",
"replacement_ins",
"[",
"'op'",
"]",
",",
"[",
"Operand",
"(",
"replacement_ins",
"[",
"'operands'",
"]",
"[",
"i",
"]",
"[",
"1",
"]",
",",
"r",
")",
"for",
"i",
",",
"r",
"in",
"enumerate",
"(",
"rule",
"[",
"'operands'",
"]",
")",
"]",
",",
"ins",
".",
"pos",
")"
] | 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 modified 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",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/transforms.py#L27-L51 | train |
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['request']
f = f.f_back
del frame
return request | 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['request']
f = f.f_back
del frame
return request | [
"def",
"find_request",
"(",
")",
":",
"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",
"[",
"'request'",
"]",
"f",
"=",
"f",
".",
"f_back",
"del",
"frame",
"return",
"request"
] | 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 |
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/index.html" % template_dir
class Error(Pylot):
"""
Error Views
"""
@classmethod
def register(cls, app, **kwargs):
super(cls, cls).register(app, **kwargs)
@app.errorhandler(400)
def error_400(error):
return cls.index(error, 400)
@app.errorhandler(401)
def error_401(error):
return cls.index(error, 401)
@app.errorhandler(403)
def error_403(error):
return cls.index(error, 403)
@app.errorhandler(404)
def error_404(error):
return cls.index(error, 404)
@app.errorhandler(500)
def error_500(error):
return cls.index(error, 500)
@app.errorhandler(503)
def error_503(error):
return cls.index(error, 503)
@classmethod
def index(cls, error, code):
cls.meta_(title="Error %s" % code)
return cls.render(error=error, view_template=template_page), code
return Error | 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/index.html" % template_dir
class Error(Pylot):
"""
Error Views
"""
@classmethod
def register(cls, app, **kwargs):
super(cls, cls).register(app, **kwargs)
@app.errorhandler(400)
def error_400(error):
return cls.index(error, 400)
@app.errorhandler(401)
def error_401(error):
return cls.index(error, 401)
@app.errorhandler(403)
def error_403(error):
return cls.index(error, 403)
@app.errorhandler(404)
def error_404(error):
return cls.index(error, 404)
@app.errorhandler(500)
def error_500(error):
return cls.index(error, 500)
@app.errorhandler(503)
def error_503(error):
return cls.index(error, 503)
@classmethod
def index(cls, error, code):
cls.meta_(title="Error %s" % code)
return cls.render(error=error, view_template=template_page), code
return Error | [
"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 Error Views\n \"\"\"",
"@",
"classmethod",
"def",
"register",
"(",
"cls",
",",
"app",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"cls",
",",
"cls",
")",
".",
"register",
"(",
"app",
",",
"*",
"*",
"kwargs",
")",
"@",
"app",
".",
"errorhandler",
"(",
"400",
")",
"def",
"error_400",
"(",
"error",
")",
":",
"return",
"cls",
".",
"index",
"(",
"error",
",",
"400",
")",
"@",
"app",
".",
"errorhandler",
"(",
"401",
")",
"def",
"error_401",
"(",
"error",
")",
":",
"return",
"cls",
".",
"index",
"(",
"error",
",",
"401",
")",
"@",
"app",
".",
"errorhandler",
"(",
"403",
")",
"def",
"error_403",
"(",
"error",
")",
":",
"return",
"cls",
".",
"index",
"(",
"error",
",",
"403",
")",
"@",
"app",
".",
"errorhandler",
"(",
"404",
")",
"def",
"error_404",
"(",
"error",
")",
":",
"return",
"cls",
".",
"index",
"(",
"error",
",",
"404",
")",
"@",
"app",
".",
"errorhandler",
"(",
"500",
")",
"def",
"error_500",
"(",
"error",
")",
":",
"return",
"cls",
".",
"index",
"(",
"error",
",",
"500",
")",
"@",
"app",
".",
"errorhandler",
"(",
"503",
")",
"def",
"error_503",
"(",
"error",
")",
":",
"return",
"cls",
".",
"index",
"(",
"error",
",",
"503",
")",
"@",
"classmethod",
"def",
"index",
"(",
"cls",
",",
"error",
",",
"code",
")",
":",
"cls",
".",
"meta_",
"(",
"title",
"=",
"\"Error %s\"",
"%",
"code",
")",
"return",
"cls",
".",
"render",
"(",
"error",
"=",
"error",
",",
"view_template",
"=",
"template_page",
")",
",",
"code",
"return",
"Error"
] | 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 |
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.args.get('s3_object_name')
mime_type = request.args.get('s3_object_type')
expires = long(time.time()+10)
amz_headers = "x-amz-acl:public-read"
put_request = "PUT\n\n%s\n%d\n%s\n/%s/%s" % (mime_type, expires, amz_headers, S3_BUCKET, object_name)
signature = base64.encodestring(hmac.new(AWS_SECRET_KEY, put_request, sha1).digest())
signature = urllib.quote(urllib.quote_plus(signature.strip()))
url = 'https://s3.amazonaws.com/%s/%s' % (S3_BUCKET, object_name)
return jsonify({
'signed_request': '%s?AWSAccessKeyId=%s&Expires=%d&Signature=%s' % (url, AWS_ACCESS_KEY, expires, signature),
'url': url
}) | 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.args.get('s3_object_name')
mime_type = request.args.get('s3_object_type')
expires = long(time.time()+10)
amz_headers = "x-amz-acl:public-read"
put_request = "PUT\n\n%s\n%d\n%s\n/%s/%s" % (mime_type, expires, amz_headers, S3_BUCKET, object_name)
signature = base64.encodestring(hmac.new(AWS_SECRET_KEY, put_request, sha1).digest())
signature = urllib.quote(urllib.quote_plus(signature.strip()))
url = 'https://s3.amazonaws.com/%s/%s' % (S3_BUCKET, object_name)
return jsonify({
'signed_request': '%s?AWSAccessKeyId=%s&Expires=%d&Signature=%s' % (url, AWS_ACCESS_KEY, expires, signature),
'url': url
}) | [
"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_",
"(",
"'AWS_S3_BUCKET_NAME'",
")",
"object_name",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'s3_object_name'",
")",
"mime_type",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'s3_object_type'",
")",
"expires",
"=",
"long",
"(",
"time",
".",
"time",
"(",
")",
"+",
"10",
")",
"amz_headers",
"=",
"\"x-amz-acl:public-read\"",
"put_request",
"=",
"\"PUT\\n\\n%s\\n%d\\n%s\\n/%s/%s\"",
"%",
"(",
"mime_type",
",",
"expires",
",",
"amz_headers",
",",
"S3_BUCKET",
",",
"object_name",
")",
"signature",
"=",
"base64",
".",
"encodestring",
"(",
"hmac",
".",
"new",
"(",
"AWS_SECRET_KEY",
",",
"put_request",
",",
"sha1",
")",
".",
"digest",
"(",
")",
")",
"signature",
"=",
"urllib",
".",
"quote",
"(",
"urllib",
".",
"quote_plus",
"(",
"signature",
".",
"strip",
"(",
")",
")",
")",
"url",
"=",
"'https://s3.amazonaws.com/%s/%s'",
"%",
"(",
"S3_BUCKET",
",",
"object_name",
")",
"return",
"jsonify",
"(",
"{",
"'signed_request'",
":",
"'%s?AWSAccessKeyId=%s&Expires=%d&Signature=%s'",
"%",
"(",
"url",
",",
"AWS_ACCESS_KEY",
",",
"expires",
",",
"signature",
")",
",",
"'url'",
":",
"url",
"}",
")"
] | 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 |
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 |
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 |
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'",
",",
"callback",
",",
"device",
")"
] | 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 |
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',
callback, device) | 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',
callback, device) | [
"def",
"remove_update_callback",
"(",
"self",
",",
"callback",
",",
"device",
")",
":",
"if",
"[",
"callback",
",",
"device",
"]",
"in",
"self",
".",
"_update_callbacks",
":",
"self",
".",
"_update_callbacks",
".",
"remove",
"(",
"[",
"callback",
",",
"device",
"]",
")",
"_LOGGER",
".",
"debug",
"(",
"'Removed update callback %s for %s'",
",",
"callback",
",",
"device",
")"
] | Remove a registered update callback. | [
"Remove",
"a",
"registered",
"update",
"callback",
"."
] | 6bb621e4e25bf1b9b0aba2c38b588e68f8816226 | https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L141-L146 | train |
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_loop.close()
_LOGGER.info("Connection shut down.") | 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_loop.close()
_LOGGER.info("Connection shut down.") | [
"def",
"start",
"(",
"self",
")",
":",
"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_loop",
".",
"close",
"(",
")",
"_LOGGER",
".",
"info",
"(",
"\"Connection shut down.\"",
")"
] | 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 |
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:
_LOGGER.info("Shutting down Emby server loop...")
self._event_loop.call_soon_threadsafe(self._event_loop.stop) | 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:
_LOGGER.info("Shutting down Emby server loop...")
self._event_loop.call_soon_threadsafe(self._event_loop.stop) | [
"async",
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_shutdown",
"=",
"True",
"if",
"self",
".",
"wsck",
":",
"_LOGGER",
".",
"info",
"(",
"'Closing Emby server websocket.'",
")",
"await",
"self",
".",
"wsck",
".",
"close",
"(",
")",
"self",
".",
"wsck",
"=",
"None",
"if",
"self",
".",
"_own_loop",
":",
"_LOGGER",
".",
"info",
"(",
"\"Shutting down Emby server loop...\"",
")",
"self",
".",
"_event_loop",
".",
"call_soon_threadsafe",
"(",
"self",
".",
"_event_loop",
".",
"stop",
")"
] | 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 |
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
_LOGGER.error('Unable to register emby client.')
else:
self._registered = True
_LOGGER.info('Emby client registered!, Id: %s', self.unique_id)
self._sessions = reg
# Build initial device list.
self.update_device_list(self._sessions)
asyncio.ensure_future(self.socket_connection(), loop=self._event_loop) | 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
_LOGGER.error('Unable to register emby client.')
else:
self._registered = True
_LOGGER.info('Emby client registered!, Id: %s', self.unique_id)
self._sessions = reg
# Build initial device list.
self.update_device_list(self._sessions)
asyncio.ensure_future(self.socket_connection(), loop=self._event_loop) | [
"async",
"def",
"register",
"(",
"self",
")",
":",
"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",
"_LOGGER",
".",
"error",
"(",
"'Unable to register emby client.'",
")",
"else",
":",
"self",
".",
"_registered",
"=",
"True",
"_LOGGER",
".",
"info",
"(",
"'Emby client registered!, Id: %s'",
",",
"self",
".",
"unique_id",
")",
"self",
".",
"_sessions",
"=",
"reg",
"# Build initial device list.",
"self",
".",
"update_device_list",
"(",
"self",
".",
"_sessions",
")",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"socket_connection",
"(",
")",
",",
"loop",
"=",
"self",
".",
"_event_loop",
")"
] | 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 |
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._api_key)
fail_count = 0
while True:
_LOGGER.debug('Attempting Socket Connection.')
try:
with async_timeout.timeout(DEFAULT_TIMEOUT,
loop=self._event_loop):
self.wsck = await self._api_session.ws_connect(url)
# Enable sever session updates:
try:
msg = await self.wsck.send_str(
'{"MessageType":"SessionsStart", "Data": "0,1500"}')
except Exception as err:
# Catch all for now
_LOGGER.error('Failure setting session updates: %s', err)
raise ValueError('Session updates error.')
_LOGGER.debug('Socket Connected!')
fail_count = 0
while True:
msg = await self.wsck.receive()
if msg.type == aiohttp.WSMsgType.text:
# Process data
self.process_msg(msg.data)
elif msg.type == aiohttp.WSMsgType.closed:
raise ValueError('Websocket was closed.')
elif msg.type == aiohttp.WSMsgType.error:
_LOGGER.debug(
'Websocket encountered an error: %s', msg)
raise ValueError('Websocket error.')
except (aiohttp.ClientError, asyncio.TimeoutError,
aiohttp.WSServerHandshakeError,
ConnectionRefusedError, OSError, ValueError) as err:
if not self._shutdown:
fail_count += 1
_LOGGER.debug('Websocket unintentionally closed.'
' Trying reconnect in %ss. Error: %s',
(fail_count * 5) + 5, err)
await asyncio.sleep(15, self._event_loop)
continue
else:
break | 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._api_key)
fail_count = 0
while True:
_LOGGER.debug('Attempting Socket Connection.')
try:
with async_timeout.timeout(DEFAULT_TIMEOUT,
loop=self._event_loop):
self.wsck = await self._api_session.ws_connect(url)
# Enable sever session updates:
try:
msg = await self.wsck.send_str(
'{"MessageType":"SessionsStart", "Data": "0,1500"}')
except Exception as err:
# Catch all for now
_LOGGER.error('Failure setting session updates: %s', err)
raise ValueError('Session updates error.')
_LOGGER.debug('Socket Connected!')
fail_count = 0
while True:
msg = await self.wsck.receive()
if msg.type == aiohttp.WSMsgType.text:
# Process data
self.process_msg(msg.data)
elif msg.type == aiohttp.WSMsgType.closed:
raise ValueError('Websocket was closed.')
elif msg.type == aiohttp.WSMsgType.error:
_LOGGER.debug(
'Websocket encountered an error: %s', msg)
raise ValueError('Websocket error.')
except (aiohttp.ClientError, asyncio.TimeoutError,
aiohttp.WSServerHandshakeError,
ConnectionRefusedError, OSError, ValueError) as err:
if not self._shutdown:
fail_count += 1
_LOGGER.debug('Websocket unintentionally closed.'
' Trying reconnect in %ss. Error: %s',
(fail_count * 5) + 5, err)
await asyncio.sleep(15, self._event_loop)
continue
else:
break | [
"async",
"def",
"socket_connection",
"(",
"self",
")",
":",
"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",
".",
"_api_key",
")",
"fail_count",
"=",
"0",
"while",
"True",
":",
"_LOGGER",
".",
"debug",
"(",
"'Attempting Socket Connection.'",
")",
"try",
":",
"with",
"async_timeout",
".",
"timeout",
"(",
"DEFAULT_TIMEOUT",
",",
"loop",
"=",
"self",
".",
"_event_loop",
")",
":",
"self",
".",
"wsck",
"=",
"await",
"self",
".",
"_api_session",
".",
"ws_connect",
"(",
"url",
")",
"# Enable sever session updates:",
"try",
":",
"msg",
"=",
"await",
"self",
".",
"wsck",
".",
"send_str",
"(",
"'{\"MessageType\":\"SessionsStart\", \"Data\": \"0,1500\"}'",
")",
"except",
"Exception",
"as",
"err",
":",
"# Catch all for now",
"_LOGGER",
".",
"error",
"(",
"'Failure setting session updates: %s'",
",",
"err",
")",
"raise",
"ValueError",
"(",
"'Session updates error.'",
")",
"_LOGGER",
".",
"debug",
"(",
"'Socket Connected!'",
")",
"fail_count",
"=",
"0",
"while",
"True",
":",
"msg",
"=",
"await",
"self",
".",
"wsck",
".",
"receive",
"(",
")",
"if",
"msg",
".",
"type",
"==",
"aiohttp",
".",
"WSMsgType",
".",
"text",
":",
"# Process data",
"self",
".",
"process_msg",
"(",
"msg",
".",
"data",
")",
"elif",
"msg",
".",
"type",
"==",
"aiohttp",
".",
"WSMsgType",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"'Websocket was closed.'",
")",
"elif",
"msg",
".",
"type",
"==",
"aiohttp",
".",
"WSMsgType",
".",
"error",
":",
"_LOGGER",
".",
"debug",
"(",
"'Websocket encountered an error: %s'",
",",
"msg",
")",
"raise",
"ValueError",
"(",
"'Websocket error.'",
")",
"except",
"(",
"aiohttp",
".",
"ClientError",
",",
"asyncio",
".",
"TimeoutError",
",",
"aiohttp",
".",
"WSServerHandshakeError",
",",
"ConnectionRefusedError",
",",
"OSError",
",",
"ValueError",
")",
"as",
"err",
":",
"if",
"not",
"self",
".",
"_shutdown",
":",
"fail_count",
"+=",
"1",
"_LOGGER",
".",
"debug",
"(",
"'Websocket unintentionally closed.'",
"' Trying reconnect in %ss. Error: %s'",
",",
"(",
"fail_count",
"*",
"5",
")",
"+",
"5",
",",
"err",
")",
"await",
"asyncio",
".",
"sleep",
"(",
"15",
",",
"self",
".",
"_event_loop",
")",
"continue",
"else",
":",
"break"
] | Open websocket connection. | [
"Open",
"websocket",
"connection",
"."
] | 6bb621e4e25bf1b9b0aba2c38b588e68f8816226 | https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L255-L307 | train |
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 = msgdata
# Check for new devices and update as needed.
self.update_device_list(self._sessions)
"""
May process other message types in the future.
Other known types are:
- PlaybackStarted
- PlaybackStopped
- SessionEnded
""" | 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 = msgdata
# Check for new devices and update as needed.
self.update_device_list(self._sessions)
"""
May process other message types in the future.
Other known types are:
- PlaybackStarted
- PlaybackStopped
- SessionEnded
""" | [
"def",
"process_msg",
"(",
"self",
",",
"msg",
")",
":",
"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",
"=",
"msgdata",
"# Check for new devices and update as needed.",
"self",
".",
"update_device_list",
"(",
"self",
".",
"_sessions",
")",
"\"\"\"\n May process other message types in the future.\n Other known types are:\n - PlaybackStarted\n - PlaybackStopped\n - SessionEnded\n \"\"\""
] | 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 |
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 = '{}.{}'.format(device['DeviceId'], device['Client'])
try:
_LOGGER.debug('Session msg on %s of type: %s, themeflag: %s',
dev_name, device['NowPlayingItem']['Type'],
device['NowPlayingItem']['IsThemeMedia'])
except KeyError:
pass
active_devices.append(dev_name)
if dev_name not in self._devices and \
device['DeviceId'] != str(self._api_id):
_LOGGER.debug('New Emby DeviceID: %s. Adding to device list.',
dev_name)
new = EmbyDevice(device, self)
self._devices[dev_name] = new
new_devices.append(new)
elif device['DeviceId'] != str(self._api_id):
# Before we send in new data check for changes to state
# to decide if we need to fire the update callback
if not self._devices[dev_name].is_active:
# Device wasn't active on the last update
# We need to fire a device callback to let subs now
dev_update = True
do_update = self.update_check(
self._devices[dev_name], device)
self._devices[dev_name].update_data(device)
self._devices[dev_name].set_active(True)
if dev_update:
self._do_new_devices_callback(0)
dev_update = False
if do_update:
self._do_update_callback(dev_name)
# Need to check for new inactive devices and flag
for dev_id in self._devices:
if dev_id not in active_devices:
# Device no longer active
if self._devices[dev_id].is_active:
self._devices[dev_id].set_active(False)
self._do_update_callback(dev_id)
self._do_stale_devices_callback(dev_id)
# Call device callback if new devices were found.
if new_devices:
self._do_new_devices_callback(0) | 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 = '{}.{}'.format(device['DeviceId'], device['Client'])
try:
_LOGGER.debug('Session msg on %s of type: %s, themeflag: %s',
dev_name, device['NowPlayingItem']['Type'],
device['NowPlayingItem']['IsThemeMedia'])
except KeyError:
pass
active_devices.append(dev_name)
if dev_name not in self._devices and \
device['DeviceId'] != str(self._api_id):
_LOGGER.debug('New Emby DeviceID: %s. Adding to device list.',
dev_name)
new = EmbyDevice(device, self)
self._devices[dev_name] = new
new_devices.append(new)
elif device['DeviceId'] != str(self._api_id):
# Before we send in new data check for changes to state
# to decide if we need to fire the update callback
if not self._devices[dev_name].is_active:
# Device wasn't active on the last update
# We need to fire a device callback to let subs now
dev_update = True
do_update = self.update_check(
self._devices[dev_name], device)
self._devices[dev_name].update_data(device)
self._devices[dev_name].set_active(True)
if dev_update:
self._do_new_devices_callback(0)
dev_update = False
if do_update:
self._do_update_callback(dev_name)
# Need to check for new inactive devices and flag
for dev_id in self._devices:
if dev_id not in active_devices:
# Device no longer active
if self._devices[dev_id].is_active:
self._devices[dev_id].set_active(False)
self._do_update_callback(dev_id)
self._do_stale_devices_callback(dev_id)
# Call device callback if new devices were found.
if new_devices:
self._do_new_devices_callback(0) | [
"def",
"update_device_list",
"(",
"self",
",",
"sessions",
")",
":",
"if",
"sessions",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"'Error updating Emby devices.'",
")",
"return",
"new_devices",
"=",
"[",
"]",
"active_devices",
"=",
"[",
"]",
"dev_update",
"=",
"False",
"for",
"device",
"in",
"sessions",
":",
"dev_name",
"=",
"'{}.{}'",
".",
"format",
"(",
"device",
"[",
"'DeviceId'",
"]",
",",
"device",
"[",
"'Client'",
"]",
")",
"try",
":",
"_LOGGER",
".",
"debug",
"(",
"'Session msg on %s of type: %s, themeflag: %s'",
",",
"dev_name",
",",
"device",
"[",
"'NowPlayingItem'",
"]",
"[",
"'Type'",
"]",
",",
"device",
"[",
"'NowPlayingItem'",
"]",
"[",
"'IsThemeMedia'",
"]",
")",
"except",
"KeyError",
":",
"pass",
"active_devices",
".",
"append",
"(",
"dev_name",
")",
"if",
"dev_name",
"not",
"in",
"self",
".",
"_devices",
"and",
"device",
"[",
"'DeviceId'",
"]",
"!=",
"str",
"(",
"self",
".",
"_api_id",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"'New Emby DeviceID: %s. Adding to device list.'",
",",
"dev_name",
")",
"new",
"=",
"EmbyDevice",
"(",
"device",
",",
"self",
")",
"self",
".",
"_devices",
"[",
"dev_name",
"]",
"=",
"new",
"new_devices",
".",
"append",
"(",
"new",
")",
"elif",
"device",
"[",
"'DeviceId'",
"]",
"!=",
"str",
"(",
"self",
".",
"_api_id",
")",
":",
"# Before we send in new data check for changes to state",
"# to decide if we need to fire the update callback",
"if",
"not",
"self",
".",
"_devices",
"[",
"dev_name",
"]",
".",
"is_active",
":",
"# Device wasn't active on the last update",
"# We need to fire a device callback to let subs now",
"dev_update",
"=",
"True",
"do_update",
"=",
"self",
".",
"update_check",
"(",
"self",
".",
"_devices",
"[",
"dev_name",
"]",
",",
"device",
")",
"self",
".",
"_devices",
"[",
"dev_name",
"]",
".",
"update_data",
"(",
"device",
")",
"self",
".",
"_devices",
"[",
"dev_name",
"]",
".",
"set_active",
"(",
"True",
")",
"if",
"dev_update",
":",
"self",
".",
"_do_new_devices_callback",
"(",
"0",
")",
"dev_update",
"=",
"False",
"if",
"do_update",
":",
"self",
".",
"_do_update_callback",
"(",
"dev_name",
")",
"# Need to check for new inactive devices and flag",
"for",
"dev_id",
"in",
"self",
".",
"_devices",
":",
"if",
"dev_id",
"not",
"in",
"active_devices",
":",
"# Device no longer active",
"if",
"self",
".",
"_devices",
"[",
"dev_id",
"]",
".",
"is_active",
":",
"self",
".",
"_devices",
"[",
"dev_id",
"]",
".",
"set_active",
"(",
"False",
")",
"self",
".",
"_do_update_callback",
"(",
"dev_id",
")",
"self",
".",
"_do_stale_devices_callback",
"(",
"dev_id",
")",
"# Call device callback if new devices were found.",
"if",
"new_devices",
":",
"self",
".",
"_do_new_devices_callback",
"(",
"0",
")"
] | Update device list. | [
"Update",
"device",
"list",
"."
] | 6bb621e4e25bf1b9b0aba2c38b588e68f8816226 | https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L328-L384 | train |
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 'NowPlayingItem' in existing.session_raw:
try:
old_theme = existing.session_raw['NowPlayingItem']['IsThemeMedia']
except KeyError:
old_theme = False
else:
old_theme = False
if 'NowPlayingItem' in new:
if new['PlayState']['IsPaused']:
new_state = STATE_PAUSED
else:
new_state = STATE_PLAYING
try:
new_theme = new['NowPlayingItem']['IsThemeMedia']
except KeyError:
new_theme = False
else:
new_state = STATE_IDLE
new_theme = False
if old_theme or new_theme:
return False
elif old_state == STATE_PLAYING or new_state == STATE_PLAYING:
return True
elif old_state != new_state:
return True
else:
return False | 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 'NowPlayingItem' in existing.session_raw:
try:
old_theme = existing.session_raw['NowPlayingItem']['IsThemeMedia']
except KeyError:
old_theme = False
else:
old_theme = False
if 'NowPlayingItem' in new:
if new['PlayState']['IsPaused']:
new_state = STATE_PAUSED
else:
new_state = STATE_PLAYING
try:
new_theme = new['NowPlayingItem']['IsThemeMedia']
except KeyError:
new_theme = False
else:
new_state = STATE_IDLE
new_theme = False
if old_theme or new_theme:
return False
elif old_state == STATE_PLAYING or new_state == STATE_PLAYING:
return True
elif old_state != new_state:
return True
else:
return False | [
"def",
"update_check",
"(",
"self",
",",
"existing",
",",
"new",
")",
":",
"old_state",
"=",
"existing",
".",
"state",
"if",
"'NowPlayingItem'",
"in",
"existing",
".",
"session_raw",
":",
"try",
":",
"old_theme",
"=",
"existing",
".",
"session_raw",
"[",
"'NowPlayingItem'",
"]",
"[",
"'IsThemeMedia'",
"]",
"except",
"KeyError",
":",
"old_theme",
"=",
"False",
"else",
":",
"old_theme",
"=",
"False",
"if",
"'NowPlayingItem'",
"in",
"new",
":",
"if",
"new",
"[",
"'PlayState'",
"]",
"[",
"'IsPaused'",
"]",
":",
"new_state",
"=",
"STATE_PAUSED",
"else",
":",
"new_state",
"=",
"STATE_PLAYING",
"try",
":",
"new_theme",
"=",
"new",
"[",
"'NowPlayingItem'",
"]",
"[",
"'IsThemeMedia'",
"]",
"except",
"KeyError",
":",
"new_theme",
"=",
"False",
"else",
":",
"new_state",
"=",
"STATE_IDLE",
"new_theme",
"=",
"False",
"if",
"old_theme",
"or",
"new_theme",
":",
"return",
"False",
"elif",
"old_state",
"==",
"STATE_PLAYING",
"or",
"new_state",
"==",
"STATE_PLAYING",
":",
"return",
"True",
"elif",
"old_state",
"!=",
"new_state",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | 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 |
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):
"""Recursively find all files under root."""
flst = list()
temp = os.listdir(root)
for file in temp:
path = os.path.join(root, file)
if os.path.isdir(path):
flst.extend(find(path))
elif os.path.isfile(path):
flst.append(path)
elif os.path.islink(path): # exclude symbolic links
continue
yield from flst
def rename(path):
stem, ext = os.path.splitext(path)
name = '%s-%s%s' % (stem, uuid.uuid4(), ext)
return os.path.join(ARCHIVE, name)
# make archive directory
if archive:
os.makedirs(ARCHIVE, exist_ok=True)
# fetch file list
filelist = list()
for path in sys.argv[1:]:
if os.path.isfile(path):
if archive:
dest = rename(path)
os.makedirs(os.path.dirname(dest), exist_ok=True)
shutil.copy(path, dest)
filelist.append(path)
if os.path.isdir(path):
if archive:
shutil.copytree(path, rename(path))
filelist.extend(find(path))
# check if file is Python source code
def ispy(file): return (os.path.isfile(file) and (os.path.splitext(file)[1] in ('.py', '.pyw')))
filelist = sorted(filter(ispy, filelist))
# if no file supplied
if len(filelist) == 0:
parser.error('argument PATH: no valid source file found')
# process files
if mp is None or CPU_CNT <= 1:
[f2format(filename) for filename in filelist]
else:
mp.Pool(processes=CPU_CNT).map(f2format, filelist) | 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):
"""Recursively find all files under root."""
flst = list()
temp = os.listdir(root)
for file in temp:
path = os.path.join(root, file)
if os.path.isdir(path):
flst.extend(find(path))
elif os.path.isfile(path):
flst.append(path)
elif os.path.islink(path): # exclude symbolic links
continue
yield from flst
def rename(path):
stem, ext = os.path.splitext(path)
name = '%s-%s%s' % (stem, uuid.uuid4(), ext)
return os.path.join(ARCHIVE, name)
# make archive directory
if archive:
os.makedirs(ARCHIVE, exist_ok=True)
# fetch file list
filelist = list()
for path in sys.argv[1:]:
if os.path.isfile(path):
if archive:
dest = rename(path)
os.makedirs(os.path.dirname(dest), exist_ok=True)
shutil.copy(path, dest)
filelist.append(path)
if os.path.isdir(path):
if archive:
shutil.copytree(path, rename(path))
filelist.extend(find(path))
# check if file is Python source code
def ispy(file): return (os.path.isfile(file) and (os.path.splitext(file)[1] in ('.py', '.pyw')))
filelist = sorted(filter(ispy, filelist))
# if no file supplied
if len(filelist) == 0:
parser.error('argument PATH: no valid source file found')
# process files
if mp is None or CPU_CNT <= 1:
[f2format(filename) for filename in filelist]
else:
mp.Pool(processes=CPU_CNT).map(f2format, filelist) | [
"def",
"main",
"(",
")",
":",
"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",
")",
":",
"\"\"\"Recursively find all files under root.\"\"\"",
"flst",
"=",
"list",
"(",
")",
"temp",
"=",
"os",
".",
"listdir",
"(",
"root",
")",
"for",
"file",
"in",
"temp",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"file",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"flst",
".",
"extend",
"(",
"find",
"(",
"path",
")",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"flst",
".",
"append",
"(",
"path",
")",
"elif",
"os",
".",
"path",
".",
"islink",
"(",
"path",
")",
":",
"# exclude symbolic links",
"continue",
"yield",
"from",
"flst",
"def",
"rename",
"(",
"path",
")",
":",
"stem",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"name",
"=",
"'%s-%s%s'",
"%",
"(",
"stem",
",",
"uuid",
".",
"uuid4",
"(",
")",
",",
"ext",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"ARCHIVE",
",",
"name",
")",
"# make archive directory",
"if",
"archive",
":",
"os",
".",
"makedirs",
"(",
"ARCHIVE",
",",
"exist_ok",
"=",
"True",
")",
"# fetch file list",
"filelist",
"=",
"list",
"(",
")",
"for",
"path",
"in",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"if",
"archive",
":",
"dest",
"=",
"rename",
"(",
"path",
")",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"dest",
")",
",",
"exist_ok",
"=",
"True",
")",
"shutil",
".",
"copy",
"(",
"path",
",",
"dest",
")",
"filelist",
".",
"append",
"(",
"path",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"if",
"archive",
":",
"shutil",
".",
"copytree",
"(",
"path",
",",
"rename",
"(",
"path",
")",
")",
"filelist",
".",
"extend",
"(",
"find",
"(",
"path",
")",
")",
"# check if file is Python source code",
"def",
"ispy",
"(",
"file",
")",
":",
"return",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"file",
")",
"and",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"file",
")",
"[",
"1",
"]",
"in",
"(",
"'.py'",
",",
"'.pyw'",
")",
")",
")",
"filelist",
"=",
"sorted",
"(",
"filter",
"(",
"ispy",
",",
"filelist",
")",
")",
"# if no file supplied",
"if",
"len",
"(",
"filelist",
")",
"==",
"0",
":",
"parser",
".",
"error",
"(",
"'argument PATH: no valid source file found'",
")",
"# process files",
"if",
"mp",
"is",
"None",
"or",
"CPU_CNT",
"<=",
"1",
":",
"[",
"f2format",
"(",
"filename",
")",
"for",
"filename",
"in",
"filelist",
"]",
"else",
":",
"mp",
".",
"Pool",
"(",
"processes",
"=",
"CPU_CNT",
")",
".",
"map",
"(",
"f2format",
",",
"filelist",
")"
] | Entry point for f2format. | [
"Entry",
"point",
"for",
"f2format",
"."
] | a144250268247ce0a98d734a26d53faadff7a6f8 | https://github.com/JarryShaw/f2format/blob/a144250268247ce0a98d734a26d53faadff7a6f8/src/__main__.py#L64-L124 | train |
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.access_flags.acc_public = True
cf.access_flags.acc_super = True
cf.this = cf.constants.create_class(this)
cf.super_ = cf.constants.create_class(super_)
return cf | 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.access_flags.acc_public = True
cf.access_flags.acc_super = True
cf.this = cf.constants.create_class(this)
cf.super_ = cf.constants.create_class(super_)
return cf | [
"def",
"create",
"(",
"cls",
",",
"this",
":",
"str",
",",
"super_",
":",
"str",
"=",
"u'java/lang/Object'",
")",
"->",
"'ClassFile'",
":",
"cf",
"=",
"ClassFile",
"(",
")",
"cf",
".",
"access_flags",
".",
"acc_public",
"=",
"True",
"cf",
".",
"access_flags",
".",
"acc_super",
"=",
"True",
"cf",
".",
"this",
"=",
"cf",
".",
"constants",
".",
"create_class",
"(",
"this",
")",
"cf",
".",
"super_",
"=",
"cf",
".",
"constants",
".",
"create_class",
"(",
"super_",
")",
"return",
"cf"
] | 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 |
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,
self.version.major
))
self._constants.pack(source)
write(self.access_flags.pack())
write(pack(
f'>HHH{len(self._interfaces)}H',
self._this,
self._super,
len(self._interfaces),
*self._interfaces
))
self.fields.pack(source)
self.methods.pack(source)
self.attributes.pack(source) | 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,
self.version.major
))
self._constants.pack(source)
write(self.access_flags.pack())
write(pack(
f'>HHH{len(self._interfaces)}H',
self._this,
self._super,
len(self._interfaces),
*self._interfaces
))
self.fields.pack(source)
self.methods.pack(source)
self.attributes.pack(source) | [
"def",
"save",
"(",
"self",
",",
"source",
":",
"IO",
")",
":",
"write",
"=",
"source",
".",
"write",
"write",
"(",
"pack",
"(",
"'>IHH'",
",",
"ClassFile",
".",
"MAGIC",
",",
"self",
".",
"version",
".",
"minor",
",",
"self",
".",
"version",
".",
"major",
")",
")",
"self",
".",
"_constants",
".",
"pack",
"(",
"source",
")",
"write",
"(",
"self",
".",
"access_flags",
".",
"pack",
"(",
")",
")",
"write",
"(",
"pack",
"(",
"f'>HHH{len(self._interfaces)}H'",
",",
"self",
".",
"_this",
",",
"self",
".",
"_super",
",",
"len",
"(",
"self",
".",
"_interfaces",
")",
",",
"*",
"self",
".",
"_interfaces",
")",
")",
"self",
".",
"fields",
".",
"pack",
"(",
"source",
")",
"self",
".",
"methods",
".",
"pack",
"(",
"source",
")",
"self",
".",
"attributes",
".",
"pack",
"(",
"source",
")"
] | 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 |
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, major), so swap it back.
self.version = unpack('>HH', source.read(4))[::-1]
self._constants.unpack(source)
# ClassFile access_flags, see section #4.1 of the JVM specs.
self.access_flags.unpack(read(2))
# The CONSTANT_Class indexes for "this" class and its superclass.
# Interfaces are a simple list of CONSTANT_Class indexes.
self._this, self._super, interfaces_count = unpack('>HHH', read(6))
self._interfaces = unpack(
f'>{interfaces_count}H',
read(2 * interfaces_count)
)
self.fields.unpack(source)
self.methods.unpack(source)
self.attributes.unpack(source) | 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, major), so swap it back.
self.version = unpack('>HH', source.read(4))[::-1]
self._constants.unpack(source)
# ClassFile access_flags, see section #4.1 of the JVM specs.
self.access_flags.unpack(read(2))
# The CONSTANT_Class indexes for "this" class and its superclass.
# Interfaces are a simple list of CONSTANT_Class indexes.
self._this, self._super, interfaces_count = unpack('>HHH', read(6))
self._interfaces = unpack(
f'>{interfaces_count}H',
read(2 * interfaces_count)
)
self.fields.unpack(source)
self.methods.unpack(source)
self.attributes.unpack(source) | [
"def",
"_from_io",
"(",
"self",
",",
"source",
":",
"IO",
")",
":",
"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, major), so swap it back.",
"self",
".",
"version",
"=",
"unpack",
"(",
"'>HH'",
",",
"source",
".",
"read",
"(",
"4",
")",
")",
"[",
":",
":",
"-",
"1",
"]",
"self",
".",
"_constants",
".",
"unpack",
"(",
"source",
")",
"# ClassFile access_flags, see section #4.1 of the JVM specs.",
"self",
".",
"access_flags",
".",
"unpack",
"(",
"read",
"(",
"2",
")",
")",
"# The CONSTANT_Class indexes for \"this\" class and its superclass.",
"# Interfaces are a simple list of CONSTANT_Class indexes.",
"self",
".",
"_this",
",",
"self",
".",
"_super",
",",
"interfaces_count",
"=",
"unpack",
"(",
"'>HHH'",
",",
"read",
"(",
"6",
")",
")",
"self",
".",
"_interfaces",
"=",
"unpack",
"(",
"f'>{interfaces_count}H'",
",",
"read",
"(",
"2",
"*",
"interfaces_count",
")",
")",
"self",
".",
"fields",
".",
"unpack",
"(",
"source",
")",
"self",
".",
"methods",
".",
"unpack",
"(",
"source",
")",
"self",
".",
"attributes",
".",
"unpack",
"(",
"source",
")"
] | 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 |
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 |
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='BootstrapMethods')
if bootstrap is None:
bootstrap = self.attributes.create(
ATTRIBUTE_CLASSES['BootstrapMethods']
)
return bootstrap.table | 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='BootstrapMethods')
if bootstrap is None:
bootstrap = self.attributes.create(
ATTRIBUTE_CLASSES['BootstrapMethods']
)
return bootstrap.table | [
"def",
"bootstrap_methods",
"(",
"self",
")",
"->",
"BootstrapMethod",
":",
"bootstrap",
"=",
"self",
".",
"attributes",
".",
"find_one",
"(",
"name",
"=",
"'BootstrapMethods'",
")",
"if",
"bootstrap",
"is",
"None",
":",
"bootstrap",
"=",
"self",
".",
"attributes",
".",
"create",
"(",
"ATTRIBUTE_CLASSES",
"[",
"'BootstrapMethods'",
"]",
")",
"return",
"bootstrap",
".",
"table"
] | 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 |
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(name, fg='green'),
ai=click.style(class_.ADDED_IN, fg='yellow'),
cv=click.style(
ClassVersion(*class_.MINIMUM_CLASS_VERSION).human,
fg='yellow'
)
)
) | 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(name, fg='green'),
ai=click.style(class_.ADDED_IN, fg='yellow'),
cv=click.style(
ClassVersion(*class_.MINIMUM_CLASS_VERSION).human,
fg='yellow'
)
)
) | [
"def",
"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",
"(",
"name",
",",
"fg",
"=",
"'green'",
")",
",",
"ai",
"=",
"click",
".",
"style",
"(",
"class_",
".",
"ADDED_IN",
",",
"fg",
"=",
"'yellow'",
")",
",",
"cv",
"=",
"click",
".",
"style",
"(",
"ClassVersion",
"(",
"*",
"class_",
".",
"MINIMUM_CLASS_VERSION",
")",
".",
"human",
",",
"fg",
"=",
"'yellow'",
")",
")",
")"
] | 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 |
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(
mnemonic=click.style(opcode['mnemonic'], fg='green', underline=True),
op=click.style(format(opcode['op'], '02x'), fg='green')
))
if opcode.get('desc'):
click.secho('Description:', fg='yellow')
click.echo(opcode['desc'])
if opcode['can_be_wide']:
click.echo(u'This instruction can be prefixed by the WIDE opcode.')
if opcode.get('runtime'):
click.secho('Possible runtime exceptions:', fg='yellow')
for runtime_exception in opcode['runtime']:
click.echo('- {runtime_exception}'.format(
runtime_exception=click.style(runtime_exception, fg='red')
))
if opcode['operands']:
click.secho(u'Operand Format:', fg='yellow')
for operand_fmt, operand_type in opcode['operands']:
click.echo(u'- {ty} as a {fmt}'.format(
ty=click.style(operand_type.name, fg='yellow'),
fmt=click.style(operand_fmt.name, fg='yellow')
))
elif opcode['op'] in (0xAB, 0xAA, 0xC4):
# lookup[table|switch] and WIDE.
click.secho(u'\nOperand Format:', fg='yellow')
click.echo(
u'This is a special-case opcode with variable operand parsing.'
) | 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(
mnemonic=click.style(opcode['mnemonic'], fg='green', underline=True),
op=click.style(format(opcode['op'], '02x'), fg='green')
))
if opcode.get('desc'):
click.secho('Description:', fg='yellow')
click.echo(opcode['desc'])
if opcode['can_be_wide']:
click.echo(u'This instruction can be prefixed by the WIDE opcode.')
if opcode.get('runtime'):
click.secho('Possible runtime exceptions:', fg='yellow')
for runtime_exception in opcode['runtime']:
click.echo('- {runtime_exception}'.format(
runtime_exception=click.style(runtime_exception, fg='red')
))
if opcode['operands']:
click.secho(u'Operand Format:', fg='yellow')
for operand_fmt, operand_type in opcode['operands']:
click.echo(u'- {ty} as a {fmt}'.format(
ty=click.style(operand_type.name, fg='yellow'),
fmt=click.style(operand_fmt.name, fg='yellow')
))
elif opcode['op'] in (0xAB, 0xAA, 0xC4):
# lookup[table|switch] and WIDE.
click.secho(u'\nOperand Format:', fg='yellow')
click.echo(
u'This is a special-case opcode with variable operand parsing.'
) | [
"def",
"ins",
"(",
"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",
"(",
"mnemonic",
"=",
"click",
".",
"style",
"(",
"opcode",
"[",
"'mnemonic'",
"]",
",",
"fg",
"=",
"'green'",
",",
"underline",
"=",
"True",
")",
",",
"op",
"=",
"click",
".",
"style",
"(",
"format",
"(",
"opcode",
"[",
"'op'",
"]",
",",
"'02x'",
")",
",",
"fg",
"=",
"'green'",
")",
")",
")",
"if",
"opcode",
".",
"get",
"(",
"'desc'",
")",
":",
"click",
".",
"secho",
"(",
"'Description:'",
",",
"fg",
"=",
"'yellow'",
")",
"click",
".",
"echo",
"(",
"opcode",
"[",
"'desc'",
"]",
")",
"if",
"opcode",
"[",
"'can_be_wide'",
"]",
":",
"click",
".",
"echo",
"(",
"u'This instruction can be prefixed by the WIDE opcode.'",
")",
"if",
"opcode",
".",
"get",
"(",
"'runtime'",
")",
":",
"click",
".",
"secho",
"(",
"'Possible runtime exceptions:'",
",",
"fg",
"=",
"'yellow'",
")",
"for",
"runtime_exception",
"in",
"opcode",
"[",
"'runtime'",
"]",
":",
"click",
".",
"echo",
"(",
"'- {runtime_exception}'",
".",
"format",
"(",
"runtime_exception",
"=",
"click",
".",
"style",
"(",
"runtime_exception",
",",
"fg",
"=",
"'red'",
")",
")",
")",
"if",
"opcode",
"[",
"'operands'",
"]",
":",
"click",
".",
"secho",
"(",
"u'Operand Format:'",
",",
"fg",
"=",
"'yellow'",
")",
"for",
"operand_fmt",
",",
"operand_type",
"in",
"opcode",
"[",
"'operands'",
"]",
":",
"click",
".",
"echo",
"(",
"u'- {ty} as a {fmt}'",
".",
"format",
"(",
"ty",
"=",
"click",
".",
"style",
"(",
"operand_type",
".",
"name",
",",
"fg",
"=",
"'yellow'",
")",
",",
"fmt",
"=",
"click",
".",
"style",
"(",
"operand_fmt",
".",
"name",
",",
"fg",
"=",
"'yellow'",
")",
")",
")",
"elif",
"opcode",
"[",
"'op'",
"]",
"in",
"(",
"0xAB",
",",
"0xAA",
",",
"0xC4",
")",
":",
"# lookup[table|switch] and WIDE.",
"click",
".",
"secho",
"(",
"u'\\nOperand Format:'",
",",
"fg",
"=",
"'yellow'",
")",
"click",
".",
"echo",
"(",
"u'This is a special-case opcode with variable operand parsing.'",
")"
] | 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 |
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'",
":",
"importlib",
".",
"import_module",
"(",
"'jawa.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 |
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 this YAML file before distribution to prevent adding an unnecessary
dependency.
"""
try:
import yaml
except ImportError:
click.echo(
'The pyyaml module could not be found and is required'
' to use this command.',
err=True
)
return
y = yaml.load(source)
for k, v in y.items():
# We guarantee some keys should always exist to make life easier for
# developers.
v.setdefault('operands', None)
v.setdefault('can_be_wide', False)
v.setdefault('transform', {})
v['mnemonic'] = k
click.echo(json.dumps(y, indent=4, sort_keys=True)) | 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 this YAML file before distribution to prevent adding an unnecessary
dependency.
"""
try:
import yaml
except ImportError:
click.echo(
'The pyyaml module could not be found and is required'
' to use this command.',
err=True
)
return
y = yaml.load(source)
for k, v in y.items():
# We guarantee some keys should always exist to make life easier for
# developers.
v.setdefault('operands', None)
v.setdefault('can_be_wide', False)
v.setdefault('transform', {})
v['mnemonic'] = k
click.echo(json.dumps(y, indent=4, sort_keys=True)) | [
"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",
"y",
"=",
"yaml",
".",
"load",
"(",
"source",
")",
"for",
"k",
",",
"v",
"in",
"y",
".",
"items",
"(",
")",
":",
"# We guarantee some keys should always exist to make life easier for",
"# developers.",
"v",
".",
"setdefault",
"(",
"'operands'",
",",
"None",
")",
"v",
".",
"setdefault",
"(",
"'can_be_wide'",
",",
"False",
")",
"v",
".",
"setdefault",
"(",
"'transform'",
",",
"{",
"}",
")",
"v",
"[",
"'mnemonic'",
"]",
"=",
"k",
"click",
".",
"echo",
"(",
"json",
".",
"dumps",
"(",
"y",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")",
")"
] | 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 prevent adding an unnecessary
dependency. | [
"Convert",
"a",
"bytecode",
".",
"yaml",
"file",
"into",
"a",
"prepared",
"bytecode",
".",
"json",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/cli.py#L100-L130 | train |
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_dependencies)
for new_dep in new_dependencies:
click.echo(new_dep) | 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_dependencies)
for new_dep in new_dependencies:
click.echo(new_dep) | [
"def",
"dependencies",
"(",
"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_dependencies",
")",
"for",
"new_dep",
"in",
"new_dependencies",
":",
"click",
".",
"echo",
"(",
"new_dep",
")"
] | 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 |
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(path=klass, type_=UTF8, f=_matches)
if next(it, None):
print(klass)
if stop_on_first:
break | 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(path=klass, type_=UTF8, f=_matches)
if next(it, None):
print(klass)
if stop_on_first:
break | [
"def",
"grep",
"(",
"source",
",",
"regex",
",",
"stop_on_first",
"=",
"False",
")",
":",
"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",
"(",
"path",
"=",
"klass",
",",
"type_",
"=",
"UTF8",
",",
"f",
"=",
"_matches",
")",
"if",
"next",
"(",
"it",
",",
"None",
")",
":",
"print",
"(",
"klass",
")",
"if",
"stop_on_first",
":",
"break"
] | 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 |
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)
files = kwargs.get('files', {})
if data and isinstance(data, (basestring, dict)) or files:
return post(*args, **kwargs)
return get(*args, **kwargs) | 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)
files = kwargs.get('files', {})
if data and isinstance(data, (basestring, dict)) or files:
return post(*args, **kwargs)
return get(*args, **kwargs) | [
"def",
"fetch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"kwargs",
".",
"get",
"(",
"'data'",
",",
"None",
")",
"files",
"=",
"kwargs",
".",
"get",
"(",
"'files'",
",",
"{",
"}",
")",
"if",
"data",
"and",
"isinstance",
"(",
"data",
",",
"(",
"basestring",
",",
"dict",
")",
")",
"or",
"files",
":",
"return",
"post",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"get",
"(",
"*",
"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. | [
"fetch",
"an",
"URL",
"."
] | e0ea4673367c157eb832ba4ba2635306c81a61be | https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L528-L540 | train |
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:
make_utf8 = lambda x: isinstance(x, unicode) and x.encode('utf-8') or x
if '://' in url:
scheme, url = url.split('://', 1)
else:
scheme = 'http'
url = 'http://' + url
parsed = urlparse.urlsplit(url)
r = ObjectDict()
r['scheme'] = make_utf8(scheme)
r['netloc'] = make_utf8(parsed.netloc)
r['path'] = make_utf8(parsed.path)
r['query'] = make_utf8(parsed.query)
r['fragment'] = make_utf8(parsed.fragment)
r['uri'] = make_utf8(parsed.path)
if parsed.query:
r['uri'] += '?' + make_utf8(parsed.query)
r['username'] = make_utf8(parsed.username)
r['password'] = make_utf8(parsed.password)
host = make_utf8(parsed.hostname.encode('idna').decode('utf-8'))
r['host'] = r['hostname'] = host
try:
r['port'] = parsed.port
except ValueError:
r['port'] = None
if r['port']:
r['http_host'] = '%s:%d' % (r['host'], r['port'])
else:
r['http_host'] = r['host']
return r | 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:
make_utf8 = lambda x: isinstance(x, unicode) and x.encode('utf-8') or x
if '://' in url:
scheme, url = url.split('://', 1)
else:
scheme = 'http'
url = 'http://' + url
parsed = urlparse.urlsplit(url)
r = ObjectDict()
r['scheme'] = make_utf8(scheme)
r['netloc'] = make_utf8(parsed.netloc)
r['path'] = make_utf8(parsed.path)
r['query'] = make_utf8(parsed.query)
r['fragment'] = make_utf8(parsed.fragment)
r['uri'] = make_utf8(parsed.path)
if parsed.query:
r['uri'] += '?' + make_utf8(parsed.query)
r['username'] = make_utf8(parsed.username)
r['password'] = make_utf8(parsed.password)
host = make_utf8(parsed.hostname.encode('idna').decode('utf-8'))
r['host'] = r['hostname'] = host
try:
r['port'] = parsed.port
except ValueError:
r['port'] = None
if r['port']:
r['http_host'] = '%s:%d' % (r['host'], r['port'])
else:
r['http_host'] = r['host']
return r | [
"def",
"parse_url",
"(",
"url",
")",
":",
"try",
":",
"url",
"=",
"unicode",
"(",
"url",
")",
"except",
"UnicodeDecodeError",
":",
"pass",
"if",
"py3k",
":",
"make_utf8",
"=",
"lambda",
"x",
":",
"x",
"else",
":",
"make_utf8",
"=",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"unicode",
")",
"and",
"x",
".",
"encode",
"(",
"'utf-8'",
")",
"or",
"x",
"if",
"'://'",
"in",
"url",
":",
"scheme",
",",
"url",
"=",
"url",
".",
"split",
"(",
"'://'",
",",
"1",
")",
"else",
":",
"scheme",
"=",
"'http'",
"url",
"=",
"'http://'",
"+",
"url",
"parsed",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
")",
"r",
"=",
"ObjectDict",
"(",
")",
"r",
"[",
"'scheme'",
"]",
"=",
"make_utf8",
"(",
"scheme",
")",
"r",
"[",
"'netloc'",
"]",
"=",
"make_utf8",
"(",
"parsed",
".",
"netloc",
")",
"r",
"[",
"'path'",
"]",
"=",
"make_utf8",
"(",
"parsed",
".",
"path",
")",
"r",
"[",
"'query'",
"]",
"=",
"make_utf8",
"(",
"parsed",
".",
"query",
")",
"r",
"[",
"'fragment'",
"]",
"=",
"make_utf8",
"(",
"parsed",
".",
"fragment",
")",
"r",
"[",
"'uri'",
"]",
"=",
"make_utf8",
"(",
"parsed",
".",
"path",
")",
"if",
"parsed",
".",
"query",
":",
"r",
"[",
"'uri'",
"]",
"+=",
"'?'",
"+",
"make_utf8",
"(",
"parsed",
".",
"query",
")",
"r",
"[",
"'username'",
"]",
"=",
"make_utf8",
"(",
"parsed",
".",
"username",
")",
"r",
"[",
"'password'",
"]",
"=",
"make_utf8",
"(",
"parsed",
".",
"password",
")",
"host",
"=",
"make_utf8",
"(",
"parsed",
".",
"hostname",
".",
"encode",
"(",
"'idna'",
")",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"r",
"[",
"'host'",
"]",
"=",
"r",
"[",
"'hostname'",
"]",
"=",
"host",
"try",
":",
"r",
"[",
"'port'",
"]",
"=",
"parsed",
".",
"port",
"except",
"ValueError",
":",
"r",
"[",
"'port'",
"]",
"=",
"None",
"if",
"r",
"[",
"'port'",
"]",
":",
"r",
"[",
"'http_host'",
"]",
"=",
"'%s:%d'",
"%",
"(",
"r",
"[",
"'host'",
"]",
",",
"r",
"[",
"'port'",
"]",
")",
"else",
":",
"r",
"[",
"'http_host'",
"]",
"=",
"r",
"[",
"'host'",
"]",
"return",
"r"
] | 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 |
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['https'] = https_proxy
return 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['https'] = https_proxy
return proxies | [
"def",
"get_proxies_from_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",
"[",
"'https'",
"]",
"=",
"https_proxy",
"return",
"proxies"
] | Get proxies from os.environ. | [
"Get",
"proxies",
"from",
"os",
".",
"environ",
"."
] | e0ea4673367c157eb832ba4ba2635306c81a61be | https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L848-L857 | train |
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.
"""
import random
default_ua = 'urlfetch/%s' % __version__
if isinstance(filename, basestring):
filenames = [filename]
else:
filenames = []
if filename and UAFILE:
filenames.append(UAFILE)
for filename in filenames:
try:
st = os.stat(filename)
if stat.S_ISREG(st.st_mode) and os.access(filename, os.R_OK):
break
except:
pass
else:
return default_ua
with open(filename, 'rb') as f:
filesize = st.st_size
pos = 0
r = random.Random()
# try getting a valid line for no more than 3 times
for i in range(3):
pos += r.randint(0, filesize)
pos %= filesize
f.seek(pos)
# in case we are in middle of a line
f.readline()
line = f.readline()
if not line:
if f.tell() == filesize:
# end of file
f.seek(0)
line = f.readline()
line = line.strip()
if line and line[0] != '#':
return line
return default_ua | 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.
"""
import random
default_ua = 'urlfetch/%s' % __version__
if isinstance(filename, basestring):
filenames = [filename]
else:
filenames = []
if filename and UAFILE:
filenames.append(UAFILE)
for filename in filenames:
try:
st = os.stat(filename)
if stat.S_ISREG(st.st_mode) and os.access(filename, os.R_OK):
break
except:
pass
else:
return default_ua
with open(filename, 'rb') as f:
filesize = st.st_size
pos = 0
r = random.Random()
# try getting a valid line for no more than 3 times
for i in range(3):
pos += r.randint(0, filesize)
pos %= filesize
f.seek(pos)
# in case we are in middle of a line
f.readline()
line = f.readline()
if not line:
if f.tell() == filesize:
# end of file
f.seek(0)
line = f.readline()
line = line.strip()
if line and line[0] != '#':
return line
return default_ua | [
"def",
"random_useragent",
"(",
"filename",
"=",
"True",
")",
":",
"import",
"random",
"default_ua",
"=",
"'urlfetch/%s'",
"%",
"__version__",
"if",
"isinstance",
"(",
"filename",
",",
"basestring",
")",
":",
"filenames",
"=",
"[",
"filename",
"]",
"else",
":",
"filenames",
"=",
"[",
"]",
"if",
"filename",
"and",
"UAFILE",
":",
"filenames",
".",
"append",
"(",
"UAFILE",
")",
"for",
"filename",
"in",
"filenames",
":",
"try",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"filename",
")",
"if",
"stat",
".",
"S_ISREG",
"(",
"st",
".",
"st_mode",
")",
"and",
"os",
".",
"access",
"(",
"filename",
",",
"os",
".",
"R_OK",
")",
":",
"break",
"except",
":",
"pass",
"else",
":",
"return",
"default_ua",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"filesize",
"=",
"st",
".",
"st_size",
"pos",
"=",
"0",
"r",
"=",
"random",
".",
"Random",
"(",
")",
"# try getting a valid line for no more than 3 times",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"pos",
"+=",
"r",
".",
"randint",
"(",
"0",
",",
"filesize",
")",
"pos",
"%=",
"filesize",
"f",
".",
"seek",
"(",
"pos",
")",
"# in case we are in middle of a line",
"f",
".",
"readline",
"(",
")",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"if",
"f",
".",
"tell",
"(",
")",
"==",
"filesize",
":",
"# end of file",
"f",
".",
"seek",
"(",
"0",
")",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
"and",
"line",
"[",
"0",
"]",
"!=",
"'#'",
":",
"return",
"line",
"return",
"default_ua"
] | 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 |
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) Whether to keep the args which are
alreay in url, default is ``True``.
"""
if not args:
return url
if keep_existing:
if url[-1] not in ('?', '&'):
url += '&' if ('?' in url) else '?'
return url + urlencode(args, 1)
else:
url, seq, query = url.partition('?')
query = urlparse.parse_qs(query, True)
query.update(args)
return url + '?' + urlencode(query, 1) | 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) Whether to keep the args which are
alreay in url, default is ``True``.
"""
if not args:
return url
if keep_existing:
if url[-1] not in ('?', '&'):
url += '&' if ('?' in url) else '?'
return url + urlencode(args, 1)
else:
url, seq, query = url.partition('?')
query = urlparse.parse_qs(query, True)
query.update(args)
return url + '?' + urlencode(query, 1) | [
"def",
"url_concat",
"(",
"url",
",",
"args",
",",
"keep_existing",
"=",
"True",
")",
":",
"if",
"not",
"args",
":",
"return",
"url",
"if",
"keep_existing",
":",
"if",
"url",
"[",
"-",
"1",
"]",
"not",
"in",
"(",
"'?'",
",",
"'&'",
")",
":",
"url",
"+=",
"'&'",
"if",
"(",
"'?'",
"in",
"url",
")",
"else",
"'?'",
"return",
"url",
"+",
"urlencode",
"(",
"args",
",",
"1",
")",
"else",
":",
"url",
",",
"seq",
",",
"query",
"=",
"url",
".",
"partition",
"(",
"'?'",
")",
"query",
"=",
"urlparse",
".",
"parse_qs",
"(",
"query",
",",
"True",
")",
"query",
".",
"update",
"(",
"args",
")",
"return",
"url",
"+",
"'?'",
"+",
"urlencode",
"(",
"query",
",",
"1",
")"
] | 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
alreay in url, default is ``True``. | [
"Concatenate",
"url",
"and",
"argument",
"dictionary"
] | e0ea4673367c157eb832ba4ba2635306c81a61be | https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L932-L954 | train |
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:
pass
try:
pid = repr(os.getpid())
BOUNDARY_PREFIX += "." + pid
except AttributeError:
pass
return "%s.%s" % (BOUNDARY_PREFIX, uuid.uuid4().hex) | 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:
pass
try:
pid = repr(os.getpid())
BOUNDARY_PREFIX += "." + pid
except AttributeError:
pass
return "%s.%s" % (BOUNDARY_PREFIX, uuid.uuid4().hex) | [
"def",
"choose_boundary",
"(",
")",
":",
"global",
"BOUNDARY_PREFIX",
"if",
"BOUNDARY_PREFIX",
"is",
"None",
":",
"BOUNDARY_PREFIX",
"=",
"\"urlfetch\"",
"try",
":",
"uid",
"=",
"repr",
"(",
"os",
".",
"getuid",
"(",
")",
")",
"BOUNDARY_PREFIX",
"+=",
"\".\"",
"+",
"uid",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"pid",
"=",
"repr",
"(",
"os",
".",
"getpid",
"(",
")",
")",
"BOUNDARY_PREFIX",
"+=",
"\".\"",
"+",
"pid",
"except",
"AttributeError",
":",
"pass",
"return",
"\"%s.%s\"",
"%",
"(",
"BOUNDARY_PREFIX",
",",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
")"
] | 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 |
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' % boundary)
writer = codecs.lookup('utf-8')[3]
if isinstance(data, dict):
for name, values in data.items():
if not isinstance(values, (list, tuple, set)):
# behave like urllib.urlencode(dict, 1)
values = (values, )
for value in values:
body.write(part_boundary)
writer(body).write('Content-Disposition: form-data; '
'name="%s"\r\n' % name)
body.write(b'Content-Type: text/plain\r\n\r\n')
if isinstance(value, int):
value = str(value)
if py3k and isinstance(value, str):
writer(body).write(value)
else:
body.write(value)
body.write(b'\r\n')
for fieldname, f in files.items():
if isinstance(f, tuple):
filename, f = f
elif hasattr(f, 'name'):
filename = basename(f.name)
else:
filename = None
raise UrlfetchException("file must has filename")
if hasattr(f, 'read'):
value = f.read()
elif isinstance(f, basestring):
value = f
else:
value = str(f)
body.write(part_boundary)
if filename:
writer(body).write('Content-Disposition: form-data; name="%s"; '
'filename="%s"\r\n' % (fieldname, filename))
body.write(b'Content-Type: application/octet-stream\r\n\r\n')
else:
writer(body).write('Content-Disposition: form-data; name="%s"'
'\r\n' % name)
body.write(b'Content-Type: text/plain\r\n\r\n')
if py3k and isinstance(value, str):
writer(body).write(value)
else:
body.write(value)
body.write(b'\r\n')
body.write(b('--' + boundary + '--\r\n'))
content_type = 'multipart/form-data; boundary=%s' % boundary
return content_type, body.getvalue() | 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' % boundary)
writer = codecs.lookup('utf-8')[3]
if isinstance(data, dict):
for name, values in data.items():
if not isinstance(values, (list, tuple, set)):
# behave like urllib.urlencode(dict, 1)
values = (values, )
for value in values:
body.write(part_boundary)
writer(body).write('Content-Disposition: form-data; '
'name="%s"\r\n' % name)
body.write(b'Content-Type: text/plain\r\n\r\n')
if isinstance(value, int):
value = str(value)
if py3k and isinstance(value, str):
writer(body).write(value)
else:
body.write(value)
body.write(b'\r\n')
for fieldname, f in files.items():
if isinstance(f, tuple):
filename, f = f
elif hasattr(f, 'name'):
filename = basename(f.name)
else:
filename = None
raise UrlfetchException("file must has filename")
if hasattr(f, 'read'):
value = f.read()
elif isinstance(f, basestring):
value = f
else:
value = str(f)
body.write(part_boundary)
if filename:
writer(body).write('Content-Disposition: form-data; name="%s"; '
'filename="%s"\r\n' % (fieldname, filename))
body.write(b'Content-Type: application/octet-stream\r\n\r\n')
else:
writer(body).write('Content-Disposition: form-data; name="%s"'
'\r\n' % name)
body.write(b'Content-Type: text/plain\r\n\r\n')
if py3k and isinstance(value, str):
writer(body).write(value)
else:
body.write(value)
body.write(b'\r\n')
body.write(b('--' + boundary + '--\r\n'))
content_type = 'multipart/form-data; boundary=%s' % boundary
return content_type, body.getvalue() | [
"def",
"encode_multipart",
"(",
"data",
",",
"files",
")",
":",
"body",
"=",
"BytesIO",
"(",
")",
"boundary",
"=",
"choose_boundary",
"(",
")",
"part_boundary",
"=",
"b",
"(",
"'--%s\\r\\n'",
"%",
"boundary",
")",
"writer",
"=",
"codecs",
".",
"lookup",
"(",
"'utf-8'",
")",
"[",
"3",
"]",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"for",
"name",
",",
"values",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"values",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
":",
"# behave like urllib.urlencode(dict, 1)",
"values",
"=",
"(",
"values",
",",
")",
"for",
"value",
"in",
"values",
":",
"body",
".",
"write",
"(",
"part_boundary",
")",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"'Content-Disposition: form-data; '",
"'name=\"%s\"\\r\\n'",
"%",
"name",
")",
"body",
".",
"write",
"(",
"b'Content-Type: text/plain\\r\\n\\r\\n'",
")",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"py3k",
"and",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"value",
")",
"else",
":",
"body",
".",
"write",
"(",
"value",
")",
"body",
".",
"write",
"(",
"b'\\r\\n'",
")",
"for",
"fieldname",
",",
"f",
"in",
"files",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"tuple",
")",
":",
"filename",
",",
"f",
"=",
"f",
"elif",
"hasattr",
"(",
"f",
",",
"'name'",
")",
":",
"filename",
"=",
"basename",
"(",
"f",
".",
"name",
")",
"else",
":",
"filename",
"=",
"None",
"raise",
"UrlfetchException",
"(",
"\"file must has filename\"",
")",
"if",
"hasattr",
"(",
"f",
",",
"'read'",
")",
":",
"value",
"=",
"f",
".",
"read",
"(",
")",
"elif",
"isinstance",
"(",
"f",
",",
"basestring",
")",
":",
"value",
"=",
"f",
"else",
":",
"value",
"=",
"str",
"(",
"f",
")",
"body",
".",
"write",
"(",
"part_boundary",
")",
"if",
"filename",
":",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"'Content-Disposition: form-data; name=\"%s\"; '",
"'filename=\"%s\"\\r\\n'",
"%",
"(",
"fieldname",
",",
"filename",
")",
")",
"body",
".",
"write",
"(",
"b'Content-Type: application/octet-stream\\r\\n\\r\\n'",
")",
"else",
":",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"'Content-Disposition: form-data; name=\"%s\"'",
"'\\r\\n'",
"%",
"name",
")",
"body",
".",
"write",
"(",
"b'Content-Type: text/plain\\r\\n\\r\\n'",
")",
"if",
"py3k",
"and",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"value",
")",
"else",
":",
"body",
".",
"write",
"(",
"value",
")",
"body",
".",
"write",
"(",
"b'\\r\\n'",
")",
"body",
".",
"write",
"(",
"b",
"(",
"'--'",
"+",
"boundary",
"+",
"'--\\r\\n'",
")",
")",
"content_type",
"=",
"'multipart/form-data; boundary=%s'",
"%",
"boundary",
"return",
"content_type",
",",
"body",
".",
"getvalue",
"(",
")"
] | 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 |
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.length_limit:
self.close()
raise ContentLimitExceeded("Content length is more than %d "
"bytes" % self.length_limit)
return b("").join(content) | 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.length_limit:
self.close()
raise ContentLimitExceeded("Content length is more than %d "
"bytes" % self.length_limit)
return b("").join(content) | [
"def",
"body",
"(",
"self",
")",
":",
"content",
"=",
"[",
"]",
"length",
"=",
"0",
"for",
"chunk",
"in",
"self",
":",
"content",
".",
"append",
"(",
"chunk",
")",
"length",
"+=",
"len",
"(",
"chunk",
")",
"if",
"self",
".",
"length_limit",
"and",
"length",
">",
"self",
".",
"length_limit",
":",
"self",
".",
"close",
"(",
")",
"raise",
"ContentLimitExceeded",
"(",
"\"Content length is more than %d \"",
"\"bytes\"",
"%",
"self",
".",
"length_limit",
")",
"return",
"b",
"(",
"\"\"",
")",
".",
"join",
"(",
"content",
")"
] | Response body.
:raises: :class:`ContentLimitExceeded`, :class:`ContentDecodingError` | [
"Response",
"body",
"."
] | e0ea4673367c157eb832ba4ba2635306c81a61be | https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L285-L300 | train |
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 |
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 localhost',
'accept-ranges': 'bytes',
'vary': 'Accept-Encoding',
'server': 'Apache/2.2.16 (Debian)',
'last-modified': 'Tue, 26 Jun 2012 19:23:18 GMT',
'connection': 'close',
'etag': '"13cc5e4-220f-4c36507ded580"',
'date': 'Wed, 27 Jun 2012 06:50:30 GMT',
'content-type': 'text/html',
'x-cache-lookup': 'MISS from localhost:8080'
}
"""
if py3k:
return dict((k.lower(), v) for k, v in self.getheaders())
else:
return dict(self.getheaders()) | 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 localhost',
'accept-ranges': 'bytes',
'vary': 'Accept-Encoding',
'server': 'Apache/2.2.16 (Debian)',
'last-modified': 'Tue, 26 Jun 2012 19:23:18 GMT',
'connection': 'close',
'etag': '"13cc5e4-220f-4c36507ded580"',
'date': 'Wed, 27 Jun 2012 06:50:30 GMT',
'content-type': 'text/html',
'x-cache-lookup': 'MISS from localhost:8080'
}
"""
if py3k:
return dict((k.lower(), v) for k, v in self.getheaders())
else:
return dict(self.getheaders()) | [
"def",
"headers",
"(",
"self",
")",
":",
"if",
"py3k",
":",
"return",
"dict",
"(",
"(",
"k",
".",
"lower",
"(",
")",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"getheaders",
"(",
")",
")",
"else",
":",
"return",
"dict",
"(",
"self",
".",
"getheaders",
"(",
")",
")"
] | 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-ranges': 'bytes',
'vary': 'Accept-Encoding',
'server': 'Apache/2.2.16 (Debian)',
'last-modified': 'Tue, 26 Jun 2012 19:23:18 GMT',
'connection': 'close',
'etag': '"13cc5e4-220f-4c36507ded580"',
'date': 'Wed, 27 Jun 2012 06:50:30 GMT',
'content-type': 'text/html',
'x-cache-lookup': 'MISS from localhost:8080'
} | [
"Response",
"headers",
"."
] | e0ea4673367c157eb832ba4ba2635306c81a61be | https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L325-L350 | train |
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",
".",
"values",
"(",
")",
")"
] | Cookies in dict | [
"Cookies",
"in",
"dict"
] | e0ea4673367c157eb832ba4ba2635306c81a61be | https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L353-L356 | train |
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:
url, params = i, ''
link = {}
link['url'] = url.strip('''<> '"''')
for param in params.split(';'):
try:
k, v = param.split('=')
except ValueError:
break
link[k.strip(''' '"''')] = v.strip(''' '"''')
ret.append(link)
return ret | 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:
url, params = i, ''
link = {}
link['url'] = url.strip('''<> '"''')
for param in params.split(';'):
try:
k, v = param.split('=')
except ValueError:
break
link[k.strip(''' '"''')] = v.strip(''' '"''')
ret.append(link)
return ret | [
"def",
"links",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"linkheader",
"=",
"self",
".",
"getheader",
"(",
"'link'",
")",
"if",
"not",
"linkheader",
":",
"return",
"ret",
"for",
"i",
"in",
"linkheader",
".",
"split",
"(",
"','",
")",
":",
"try",
":",
"url",
",",
"params",
"=",
"i",
".",
"split",
"(",
"';'",
",",
"1",
")",
"except",
"ValueError",
":",
"url",
",",
"params",
"=",
"i",
",",
"''",
"link",
"=",
"{",
"}",
"link",
"[",
"'url'",
"]",
"=",
"url",
".",
"strip",
"(",
"'''<> '\"'''",
")",
"for",
"param",
"in",
"params",
".",
"split",
"(",
"';'",
")",
":",
"try",
":",
"k",
",",
"v",
"=",
"param",
".",
"split",
"(",
"'='",
")",
"except",
"ValueError",
":",
"break",
"link",
"[",
"k",
".",
"strip",
"(",
"''' '\"'''",
")",
"]",
"=",
"v",
".",
"strip",
"(",
"''' '\"'''",
")",
"ret",
".",
"append",
"(",
"link",
")",
"return",
"ret"
] | 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 |
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",
"(",
")",
"]",
"self",
".",
"cookies",
"=",
"dict",
"(",
"sc",
")"
] | Cookie string setter | [
"Cookie",
"string",
"setter"
] | e0ea4673367c157eb832ba4ba2635306c81a61be | https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L452-L456 | train |
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)
self.cookies.update(r.cookies)
return r | 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)
self.cookies.update(r.cookies)
return r | [
"def",
"request",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"self",
".",
"headers",
".",
"copy",
"(",
")",
"if",
"self",
".",
"cookiestring",
":",
"headers",
"[",
"'Cookie'",
"]",
"=",
"self",
".",
"cookiestring",
"headers",
".",
"update",
"(",
"kwargs",
".",
"get",
"(",
"'headers'",
",",
"{",
"}",
")",
")",
"kwargs",
"[",
"'headers'",
"]",
"=",
"headers",
"r",
"=",
"request",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"cookies",
".",
"update",
"(",
"r",
".",
"cookies",
")",
"return",
"r"
] | Issue a request. | [
"Issue",
"a",
"request",
"."
] | e0ea4673367c157eb832ba4ba2635306c81a61be | https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L465-L476 | train |
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
content = list() # file content
with open(filename, 'r', encoding=encoding) as file:
lineno[1] = 0
for lnum, line in enumerate(file, start=1):
content.append(line)
lineno[lnum+1] = lineno[lnum] + len(line)
# now, do the dirty works
string = ''.join(content)
text = convert(string, lineno)
# dump back to the file
with open(filename, 'w', encoding=encoding) as file:
file.write(text) | 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
content = list() # file content
with open(filename, 'r', encoding=encoding) as file:
lineno[1] = 0
for lnum, line in enumerate(file, start=1):
content.append(line)
lineno[lnum+1] = lineno[lnum] + len(line)
# now, do the dirty works
string = ''.join(content)
text = convert(string, lineno)
# dump back to the file
with open(filename, 'w', encoding=encoding) as file:
file.write(text) | [
"def",
"f2format",
"(",
"filename",
")",
":",
"print",
"(",
"'Now converting %r...'",
"%",
"filename",
")",
"# fetch encoding",
"encoding",
"=",
"os",
".",
"getenv",
"(",
"'F2FORMAT_ENCODING'",
",",
"LOCALE_ENCODING",
")",
"lineno",
"=",
"dict",
"(",
")",
"# line number -> file offset",
"content",
"=",
"list",
"(",
")",
"# file content",
"with",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"file",
":",
"lineno",
"[",
"1",
"]",
"=",
"0",
"for",
"lnum",
",",
"line",
"in",
"enumerate",
"(",
"file",
",",
"start",
"=",
"1",
")",
":",
"content",
".",
"append",
"(",
"line",
")",
"lineno",
"[",
"lnum",
"+",
"1",
"]",
"=",
"lineno",
"[",
"lnum",
"]",
"+",
"len",
"(",
"line",
")",
"# now, do the dirty works",
"string",
"=",
"''",
".",
"join",
"(",
"content",
")",
"text",
"=",
"convert",
"(",
"string",
",",
"lineno",
")",
"# dump back to the file",
"with",
"open",
"(",
"filename",
",",
"'w'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"file",
":",
"file",
".",
"write",
"(",
"text",
")"
] | 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 |
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)
error_type = "an unknown error"
try:
raise
except CalledProcessError as err:
error_type = "a Subprocess error"
content = "Command: {}\n".format(err.cmd)
content += "Finished with return code {}\n".format(err.returncode)
if err.output:
content += "and output:\n```shell\n{}\n```".format(err.output)
else:
content += "and no output"
except Exception: # pylint: disable=broad-except
content = "```python\n{}\n```".format(traceback.format_exc())
response = "<details><summary>Encountered {}{}</summary><p>\n\n".format(
error_type,
summary
)
response += content
response += "\n\n</p></details>"
context.comment = create_comment(github_obj_to_comment, response) | 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)
error_type = "an unknown error"
try:
raise
except CalledProcessError as err:
error_type = "a Subprocess error"
content = "Command: {}\n".format(err.cmd)
content += "Finished with return code {}\n".format(err.returncode)
if err.output:
content += "and output:\n```shell\n{}\n```".format(err.output)
else:
content += "and no output"
except Exception: # pylint: disable=broad-except
content = "```python\n{}\n```".format(traceback.format_exc())
response = "<details><summary>Encountered {}{}</summary><p>\n\n".format(
error_type,
summary
)
response += content
response += "\n\n</p></details>"
context.comment = create_comment(github_obj_to_comment, response) | [
"def",
"exception_to_github",
"(",
"github_obj_to_comment",
",",
"summary",
"=",
"\"\"",
")",
":",
"context",
"=",
"ExceptionContext",
"(",
")",
"try",
":",
"yield",
"context",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"if",
"summary",
":",
"summary",
"=",
"\": ({})\"",
".",
"format",
"(",
"summary",
")",
"error_type",
"=",
"\"an unknown error\"",
"try",
":",
"raise",
"except",
"CalledProcessError",
"as",
"err",
":",
"error_type",
"=",
"\"a Subprocess error\"",
"content",
"=",
"\"Command: {}\\n\"",
".",
"format",
"(",
"err",
".",
"cmd",
")",
"content",
"+=",
"\"Finished with return code {}\\n\"",
".",
"format",
"(",
"err",
".",
"returncode",
")",
"if",
"err",
".",
"output",
":",
"content",
"+=",
"\"and output:\\n```shell\\n{}\\n```\"",
".",
"format",
"(",
"err",
".",
"output",
")",
"else",
":",
"content",
"+=",
"\"and no output\"",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"content",
"=",
"\"```python\\n{}\\n```\"",
".",
"format",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"response",
"=",
"\"<details><summary>Encountered {}{}</summary><p>\\n\\n\"",
".",
"format",
"(",
"error_type",
",",
"summary",
")",
"response",
"+=",
"content",
"response",
"+=",
"\"\\n\\n</p></details>\"",
"context",
".",
"comment",
"=",
"create_comment",
"(",
"github_obj_to_comment",
",",
"response",
")"
] | 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 |
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 |
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",
")",
"return",
"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 |
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_con = Github(gh_token)
github_repo = github_con.get_repo(github_repo_id)
if not github_repo.parent:
_LOGGER.warning('This repo has no upstream')
return
upstream_url = 'https://github.com/{}.git'.format(github_repo.parent.full_name)
upstream = repo.create_remote('upstream', url=upstream_url)
upstream.fetch()
active_branch_name = repo.active_branch.name
if not active_branch_name in repo.remotes.upstream.refs:
_LOGGER.info('Upstream has no branch %s to merge from', active_branch_name)
return
else:
_LOGGER.info('Merge from upstream')
msg = repo.git.rebase('upstream/{}'.format(repo.active_branch.name))
_LOGGER.debug(msg)
if push:
msg = repo.git.push()
_LOGGER.debug(msg) | 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_con = Github(gh_token)
github_repo = github_con.get_repo(github_repo_id)
if not github_repo.parent:
_LOGGER.warning('This repo has no upstream')
return
upstream_url = 'https://github.com/{}.git'.format(github_repo.parent.full_name)
upstream = repo.create_remote('upstream', url=upstream_url)
upstream.fetch()
active_branch_name = repo.active_branch.name
if not active_branch_name in repo.remotes.upstream.refs:
_LOGGER.info('Upstream has no branch %s to merge from', active_branch_name)
return
else:
_LOGGER.info('Merge from upstream')
msg = repo.git.rebase('upstream/{}'.format(repo.active_branch.name))
_LOGGER.debug(msg)
if push:
msg = repo.git.push()
_LOGGER.debug(msg) | [
"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",
"(",
"'Check if repo has to be sync with upstream'",
")",
"github_con",
"=",
"Github",
"(",
"gh_token",
")",
"github_repo",
"=",
"github_con",
".",
"get_repo",
"(",
"github_repo_id",
")",
"if",
"not",
"github_repo",
".",
"parent",
":",
"_LOGGER",
".",
"warning",
"(",
"'This repo has no upstream'",
")",
"return",
"upstream_url",
"=",
"'https://github.com/{}.git'",
".",
"format",
"(",
"github_repo",
".",
"parent",
".",
"full_name",
")",
"upstream",
"=",
"repo",
".",
"create_remote",
"(",
"'upstream'",
",",
"url",
"=",
"upstream_url",
")",
"upstream",
".",
"fetch",
"(",
")",
"active_branch_name",
"=",
"repo",
".",
"active_branch",
".",
"name",
"if",
"not",
"active_branch_name",
"in",
"repo",
".",
"remotes",
".",
"upstream",
".",
"refs",
":",
"_LOGGER",
".",
"info",
"(",
"'Upstream has no branch %s to merge from'",
",",
"active_branch_name",
")",
"return",
"else",
":",
"_LOGGER",
".",
"info",
"(",
"'Merge from upstream'",
")",
"msg",
"=",
"repo",
".",
"git",
".",
"rebase",
"(",
"'upstream/{}'",
".",
"format",
"(",
"repo",
".",
"active_branch",
".",
"name",
")",
")",
"_LOGGER",
".",
"debug",
"(",
"msg",
")",
"if",
"push",
":",
"msg",
"=",
"repo",
".",
"git",
".",
"push",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"msg",
")"
] | 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 |
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_commit" is set, return None instead of raising exception if the problem
is that head and base are the same.
"""
try: # Try to create or get a PR
return github_repo.create_pull(
title=title,
body=body,
head=head,
base=base
)
except GithubException as err:
err_message = err.data['errors'][0].get('message', '')
if err.status == 422 and err_message.startswith('A pull request already exists'):
_LOGGER.info('PR already exists, get this PR')
return list(github_repo.get_pulls(
head=head,
base=base
))[0]
elif none_if_no_commit and err.status == 422 and err_message.startswith('No commits between'):
_LOGGER.info('No PR possible since head %s and base %s are the same',
head,
base)
return None
else:
_LOGGER.warning("Unable to create PR:\n%s", err.data)
raise
except Exception as err:
response = traceback.format_exc()
_LOGGER.warning("Unable to create PR:\n%s", response)
raise | 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_commit" is set, return None instead of raising exception if the problem
is that head and base are the same.
"""
try: # Try to create or get a PR
return github_repo.create_pull(
title=title,
body=body,
head=head,
base=base
)
except GithubException as err:
err_message = err.data['errors'][0].get('message', '')
if err.status == 422 and err_message.startswith('A pull request already exists'):
_LOGGER.info('PR already exists, get this PR')
return list(github_repo.get_pulls(
head=head,
base=base
))[0]
elif none_if_no_commit and err.status == 422 and err_message.startswith('No commits between'):
_LOGGER.info('No PR possible since head %s and base %s are the same',
head,
base)
return None
else:
_LOGGER.warning("Unable to create PR:\n%s", err.data)
raise
except Exception as err:
response = traceback.format_exc()
_LOGGER.warning("Unable to create PR:\n%s", response)
raise | [
"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",
"(",
"title",
"=",
"title",
",",
"body",
"=",
"body",
",",
"head",
"=",
"head",
",",
"base",
"=",
"base",
")",
"except",
"GithubException",
"as",
"err",
":",
"err_message",
"=",
"err",
".",
"data",
"[",
"'errors'",
"]",
"[",
"0",
"]",
".",
"get",
"(",
"'message'",
",",
"''",
")",
"if",
"err",
".",
"status",
"==",
"422",
"and",
"err_message",
".",
"startswith",
"(",
"'A pull request already exists'",
")",
":",
"_LOGGER",
".",
"info",
"(",
"'PR already exists, get this PR'",
")",
"return",
"list",
"(",
"github_repo",
".",
"get_pulls",
"(",
"head",
"=",
"head",
",",
"base",
"=",
"base",
")",
")",
"[",
"0",
"]",
"elif",
"none_if_no_commit",
"and",
"err",
".",
"status",
"==",
"422",
"and",
"err_message",
".",
"startswith",
"(",
"'No commits between'",
")",
":",
"_LOGGER",
".",
"info",
"(",
"'No PR possible since head %s and base %s are the same'",
",",
"head",
",",
"base",
")",
"return",
"None",
"else",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Unable to create PR:\\n%s\"",
",",
"err",
".",
"data",
")",
"raise",
"except",
"Exception",
"as",
"err",
":",
"response",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"_LOGGER",
".",
"warning",
"(",
"\"Unable to create PR:\\n%s\"",
",",
"response",
")",
"raise"
] | 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 are the same. | [
"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 |
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 implies detached head, and then no push is possible.
If branch is specified, checkout this branch or commit finally.
:param str branch_or_commit: If specified, switch to this branch/commit.
:param int pr_number: PR number.
"""
_LOGGER.info("Clone SDK repository %s", sdk_git_id)
url_parsing = urlsplit(sdk_git_id)
sdk_git_id = url_parsing.path
if sdk_git_id.startswith("/"):
sdk_git_id = sdk_git_id[1:]
credentials_part = ''
if gh_token:
login = user_from_token(gh_token).login
credentials_part = '{user}:{token}@'.format(
user=login,
token=gh_token
)
else:
_LOGGER.warning('Will clone the repo without writing credentials')
https_authenticated_url = 'https://{credentials}github.com/{sdk_git_id}.git'.format(
credentials=credentials_part,
sdk_git_id=sdk_git_id
)
# Clone the repo
_git_clone_to_path(https_authenticated_url, folder)
# If this is a PR, do some fetch to improve the number of SHA1 available
if pr_number:
try:
checkout_with_fetch(folder, "pull/{}/merge".format(pr_number))
return
except Exception: # pylint: disable=broad-except
pass # Assume "merge" doesn't exist anymore, fetch "head"
checkout_with_fetch(folder, "pull/{}/head".format(pr_number))
# If there is SHA1, checkout it. If PR number was given, SHA1 could be inside that PR.
if branch_or_commit:
repo = Repo(str(folder))
repo.git.checkout(branch_or_commit) | 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 implies detached head, and then no push is possible.
If branch is specified, checkout this branch or commit finally.
:param str branch_or_commit: If specified, switch to this branch/commit.
:param int pr_number: PR number.
"""
_LOGGER.info("Clone SDK repository %s", sdk_git_id)
url_parsing = urlsplit(sdk_git_id)
sdk_git_id = url_parsing.path
if sdk_git_id.startswith("/"):
sdk_git_id = sdk_git_id[1:]
credentials_part = ''
if gh_token:
login = user_from_token(gh_token).login
credentials_part = '{user}:{token}@'.format(
user=login,
token=gh_token
)
else:
_LOGGER.warning('Will clone the repo without writing credentials')
https_authenticated_url = 'https://{credentials}github.com/{sdk_git_id}.git'.format(
credentials=credentials_part,
sdk_git_id=sdk_git_id
)
# Clone the repo
_git_clone_to_path(https_authenticated_url, folder)
# If this is a PR, do some fetch to improve the number of SHA1 available
if pr_number:
try:
checkout_with_fetch(folder, "pull/{}/merge".format(pr_number))
return
except Exception: # pylint: disable=broad-except
pass # Assume "merge" doesn't exist anymore, fetch "head"
checkout_with_fetch(folder, "pull/{}/head".format(pr_number))
# If there is SHA1, checkout it. If PR number was given, SHA1 could be inside that PR.
if branch_or_commit:
repo = Repo(str(folder))
repo.git.checkout(branch_or_commit) | [
"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",
"=",
"urlsplit",
"(",
"sdk_git_id",
")",
"sdk_git_id",
"=",
"url_parsing",
".",
"path",
"if",
"sdk_git_id",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"sdk_git_id",
"=",
"sdk_git_id",
"[",
"1",
":",
"]",
"credentials_part",
"=",
"''",
"if",
"gh_token",
":",
"login",
"=",
"user_from_token",
"(",
"gh_token",
")",
".",
"login",
"credentials_part",
"=",
"'{user}:{token}@'",
".",
"format",
"(",
"user",
"=",
"login",
",",
"token",
"=",
"gh_token",
")",
"else",
":",
"_LOGGER",
".",
"warning",
"(",
"'Will clone the repo without writing credentials'",
")",
"https_authenticated_url",
"=",
"'https://{credentials}github.com/{sdk_git_id}.git'",
".",
"format",
"(",
"credentials",
"=",
"credentials_part",
",",
"sdk_git_id",
"=",
"sdk_git_id",
")",
"# Clone the repo",
"_git_clone_to_path",
"(",
"https_authenticated_url",
",",
"folder",
")",
"# If this is a PR, do some fetch to improve the number of SHA1 available",
"if",
"pr_number",
":",
"try",
":",
"checkout_with_fetch",
"(",
"folder",
",",
"\"pull/{}/merge\"",
".",
"format",
"(",
"pr_number",
")",
")",
"return",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"pass",
"# Assume \"merge\" doesn't exist anymore, fetch \"head\"",
"checkout_with_fetch",
"(",
"folder",
",",
"\"pull/{}/head\"",
".",
"format",
"(",
"pr_number",
")",
")",
"# If there is SHA1, checkout it. If PR number was given, SHA1 could be inside that PR.",
"if",
"branch_or_commit",
":",
"repo",
"=",
"Repo",
"(",
"str",
"(",
"folder",
")",
")",
"repo",
".",
"git",
".",
"checkout",
"(",
"branch_or_commit",
")"
] | 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 branch or commit finally.
:param str branch_or_commit: If specified, switch to this branch/commit.
:param int pr_number: PR number. | [
"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 |
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 target repo id')
return None
github_con = Github(gh_token)
sdk_pr_target_repo = github_con.get_repo(sdk_pr_target_repo_id)
if '/' in sdk_git_id:
sdk_git_owner = sdk_git_id.split('/')[0]
_LOGGER.info("Do the PR from %s", sdk_git_owner)
head_name = "{}:{}".format(sdk_git_owner, branch_name)
else:
head_name = branch_name
sdk_git_repo = github_con.get_repo(sdk_git_id)
sdk_git_owner = sdk_git_repo.owner.login
try:
github_pr = sdk_pr_target_repo.create_pull(
title='Automatic PR from {}'.format(branch_name),
body=pr_body,
head=head_name,
base=base_branch
)
except GithubException as err:
if err.status == 422 and err.data['errors'][0].get('message', '').startswith('A pull request already exists'):
matching_pulls = sdk_pr_target_repo.get_pulls(base=base_branch, head=sdk_git_owner+":"+head_name)
matching_pull = matching_pulls[0]
_LOGGER.info('PR already exists: %s', matching_pull.html_url)
return matching_pull
raise
_LOGGER.info("Made PR %s", github_pr.html_url)
return github_pr | 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 target repo id')
return None
github_con = Github(gh_token)
sdk_pr_target_repo = github_con.get_repo(sdk_pr_target_repo_id)
if '/' in sdk_git_id:
sdk_git_owner = sdk_git_id.split('/')[0]
_LOGGER.info("Do the PR from %s", sdk_git_owner)
head_name = "{}:{}".format(sdk_git_owner, branch_name)
else:
head_name = branch_name
sdk_git_repo = github_con.get_repo(sdk_git_id)
sdk_git_owner = sdk_git_repo.owner.login
try:
github_pr = sdk_pr_target_repo.create_pull(
title='Automatic PR from {}'.format(branch_name),
body=pr_body,
head=head_name,
base=base_branch
)
except GithubException as err:
if err.status == 422 and err.data['errors'][0].get('message', '').startswith('A pull request already exists'):
matching_pulls = sdk_pr_target_repo.get_pulls(base=base_branch, head=sdk_git_owner+":"+head_name)
matching_pull = matching_pulls[0]
_LOGGER.info('PR already exists: %s', matching_pull.html_url)
return matching_pull
raise
_LOGGER.info("Made PR %s", github_pr.html_url)
return github_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",
"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 target repo id'",
")",
"return",
"None",
"github_con",
"=",
"Github",
"(",
"gh_token",
")",
"sdk_pr_target_repo",
"=",
"github_con",
".",
"get_repo",
"(",
"sdk_pr_target_repo_id",
")",
"if",
"'/'",
"in",
"sdk_git_id",
":",
"sdk_git_owner",
"=",
"sdk_git_id",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"_LOGGER",
".",
"info",
"(",
"\"Do the PR from %s\"",
",",
"sdk_git_owner",
")",
"head_name",
"=",
"\"{}:{}\"",
".",
"format",
"(",
"sdk_git_owner",
",",
"branch_name",
")",
"else",
":",
"head_name",
"=",
"branch_name",
"sdk_git_repo",
"=",
"github_con",
".",
"get_repo",
"(",
"sdk_git_id",
")",
"sdk_git_owner",
"=",
"sdk_git_repo",
".",
"owner",
".",
"login",
"try",
":",
"github_pr",
"=",
"sdk_pr_target_repo",
".",
"create_pull",
"(",
"title",
"=",
"'Automatic PR from {}'",
".",
"format",
"(",
"branch_name",
")",
",",
"body",
"=",
"pr_body",
",",
"head",
"=",
"head_name",
",",
"base",
"=",
"base_branch",
")",
"except",
"GithubException",
"as",
"err",
":",
"if",
"err",
".",
"status",
"==",
"422",
"and",
"err",
".",
"data",
"[",
"'errors'",
"]",
"[",
"0",
"]",
".",
"get",
"(",
"'message'",
",",
"''",
")",
".",
"startswith",
"(",
"'A pull request already exists'",
")",
":",
"matching_pulls",
"=",
"sdk_pr_target_repo",
".",
"get_pulls",
"(",
"base",
"=",
"base_branch",
",",
"head",
"=",
"sdk_git_owner",
"+",
"\":\"",
"+",
"head_name",
")",
"matching_pull",
"=",
"matching_pulls",
"[",
"0",
"]",
"_LOGGER",
".",
"info",
"(",
"'PR already exists: %s'",
",",
"matching_pull",
".",
"html_url",
")",
"return",
"matching_pull",
"raise",
"_LOGGER",
".",
"info",
"(",
"\"Made PR %s\"",
",",
"github_pr",
".",
"html_url",
")",
"return",
"github_pr"
] | 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 |
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 |
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
return # Do not erase a local folder, just skip here
# Clone the specific branch
split_git_id = git_id.split("@")
branch = split_git_id[1] if len(split_git_id) > 1 else None
clone_to_path(gh_token, temp_dir, split_git_id[0], branch_or_commit=branch, pr_number=pr_number)
try:
yield temp_dir
# Pre-cleanup for Windows http://bugs.python.org/issue26660
finally:
_LOGGER.debug("Preclean Rest folder")
shutil.rmtree(temp_dir, onerror=remove_readonly) | 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
return # Do not erase a local folder, just skip here
# Clone the specific branch
split_git_id = git_id.split("@")
branch = split_git_id[1] if len(split_git_id) > 1 else None
clone_to_path(gh_token, temp_dir, split_git_id[0], branch_or_commit=branch, pr_number=pr_number)
try:
yield temp_dir
# Pre-cleanup for Windows http://bugs.python.org/issue26660
finally:
_LOGGER.debug("Preclean Rest folder")
shutil.rmtree(temp_dir, onerror=remove_readonly) | [
"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",
"(",
")",
":",
"yield",
"git_id",
"return",
"# Do not erase a local folder, just skip here",
"# Clone the specific branch",
"split_git_id",
"=",
"git_id",
".",
"split",
"(",
"\"@\"",
")",
"branch",
"=",
"split_git_id",
"[",
"1",
"]",
"if",
"len",
"(",
"split_git_id",
")",
">",
"1",
"else",
"None",
"clone_to_path",
"(",
"gh_token",
",",
"temp_dir",
",",
"split_git_id",
"[",
"0",
"]",
",",
"branch_or_commit",
"=",
"branch",
",",
"pr_number",
"=",
"pr_number",
")",
"try",
":",
"yield",
"temp_dir",
"# Pre-cleanup for Windows http://bugs.python.org/issue26660",
"finally",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Preclean Rest folder\"",
")",
"shutil",
".",
"rmtree",
"(",
"temp_dir",
",",
"onerror",
"=",
"remove_readonly",
")"
] | 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 |
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")
return self.__class__(
self.gitid,
"raw",
self.branch_or_commit,
self.path,
self.token
) | 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")
return self.__class__(
self.gitid,
"raw",
self.branch_or_commit,
self.path,
self.token
) | [
"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 get a download link from a tree link\"",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"gitid",
",",
"\"raw\"",
",",
"self",
".",
"branch_or_commit",
",",
"self",
".",
"path",
",",
"self",
".",
"token",
")"
] | 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 |
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 |
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
except IndexError: # The comment body is empty
pass
# Hooooooo, no dashboard comment, let's create one
else:
comment = create_comment(issue, header)
obj = cls(comment, header)
if text:
obj.edit(text)
return obj | 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
except IndexError: # The comment body is empty
pass
# Hooooooo, no dashboard comment, let's create one
else:
comment = create_comment(issue, header)
obj = cls(comment, header)
if text:
obj.edit(text)
return obj | [
"def",
"get_or_create",
"(",
"cls",
",",
"issue",
",",
"header",
",",
"text",
"=",
"None",
")",
":",
"for",
"comment",
"in",
"get_comments",
"(",
"issue",
")",
":",
"try",
":",
"if",
"comment",
".",
"body",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
"==",
"header",
":",
"obj",
"=",
"cls",
"(",
"comment",
",",
"header",
")",
"break",
"except",
"IndexError",
":",
"# The comment body is empty",
"pass",
"# Hooooooo, no dashboard comment, let's create one",
"else",
":",
"comment",
"=",
"create_comment",
"(",
"issue",
",",
"header",
")",
"obj",
"=",
"cls",
"(",
"comment",
",",
"header",
")",
"if",
"text",
":",
"obj",
".",
"edit",
"(",
"text",
")",
"return",
"obj"
] | 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 |
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` for more info.
"""
try:
signal = self._registry[name]
except KeyError:
return
signal.disconnect(func, dispatch_uid=dispatch_uid) | 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` for more info.
"""
try:
signal = self._registry[name]
except KeyError:
return
signal.disconnect(func, dispatch_uid=dispatch_uid) | [
"def",
"disconnect",
"(",
"self",
",",
"name",
",",
"func",
",",
"dispatch_uid",
"=",
"None",
")",
":",
"try",
":",
"signal",
"=",
"self",
".",
"_registry",
"[",
"name",
"]",
"except",
"KeyError",
":",
"return",
"signal",
".",
"disconnect",
"(",
"func",
",",
"dispatch_uid",
"=",
"dispatch_uid",
")"
] | 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 |
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 value, created by one of
the factories.
It is a return value of the first factory that could create it for
the given argument.
:raises InvalidHostError: if the value is not a valid input for any
factory used by this function
"""
data = [value]
for func in factories:
try:
return func(value)
except InvalidHostError as ex:
data.append(str(ex))
msg_tpl = (
"Failed to create a host object for '{}', raising the following errors"
" in the process:" + "\n".join(data)
)
raise InvalidHostError(msg_tpl.format(value)) | 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 value, created by one of
the factories.
It is a return value of the first factory that could create it for
the given argument.
:raises InvalidHostError: if the value is not a valid input for any
factory used by this function
"""
data = [value]
for func in factories:
try:
return func(value)
except InvalidHostError as ex:
data.append(str(ex))
msg_tpl = (
"Failed to create a host object for '{}', raising the following errors"
" in the process:" + "\n".join(data)
)
raise InvalidHostError(msg_tpl.format(value)) | [
"def",
"create_host",
"(",
"factories",
",",
"value",
")",
":",
"data",
"=",
"[",
"value",
"]",
"for",
"func",
"in",
"factories",
":",
"try",
":",
"return",
"func",
"(",
"value",
")",
"except",
"InvalidHostError",
"as",
"ex",
":",
"data",
".",
"append",
"(",
"str",
"(",
"ex",
")",
")",
"msg_tpl",
"=",
"(",
"\"Failed to create a host object for '{}', raising the following errors\"",
"\" in the process:\"",
"+",
"\"\\n\"",
".",
"join",
"(",
"data",
")",
")",
"raise",
"InvalidHostError",
"(",
"msg_tpl",
".",
"format",
"(",
"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 value, created by one of
the factories.
It is a return value of the first factory that could create it for
the given argument.
:raises InvalidHostError: if the value is not a valid input for any
factory used by this function | [
"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 |
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:
return self.value.is_subdomain(compared)
except AttributeError:
return False | 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:
return self.value.is_subdomain(compared)
except AttributeError:
return False | [
"def",
"is_subdomain",
"(",
"self",
",",
"other",
")",
":",
"compared",
"=",
"other",
".",
"value",
"if",
"hasattr",
"(",
"other",
",",
"'value'",
")",
"else",
"other",
"try",
":",
"return",
"self",
".",
"value",
".",
"is_subdomain",
"(",
"compared",
")",
"except",
"AttributeError",
":",
"return",
"False"
] | 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 |
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 bytecode.
As a simple example, lets produce an infinite loop:
>>> from jawa.assemble import assemble, Label
>>> print(list(assemble((
... Label('start'),
... ('goto', Label('start'))
... ))))
[Instruction(mnemonic='goto', opcode=167, operands=[
Operand(op_type=40, value=0)], pos=0)]
For a more complex example, see examples/hello_world.py.
"""
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
# alignment padding.
for line in code:
if isinstance(line, Label):
final.append(line)
continue
mnemonic, operands = line[0], line[1:]
operand_fmts = opcode_table[mnemonic]['operands']
# We need to coerce each opcodes operands into their
# final `Operand` form.
final_operands = []
for i, operand in enumerate(operands):
if isinstance(operand, Operand):
# Already in Operand form.
final_operands.append(operand)
elif isinstance(operand, Constant):
# Convert constants into CONSTANT_INDEX'es
final_operands.append(Operand(
OperandTypes.CONSTANT_INDEX,
operand.index
))
elif isinstance(operand, dict):
# lookupswitch's operand is a dict as
# a special usability case.
final_operands.append(operand)
elif isinstance(operand, Label):
final_operands.append(operand)
else:
# For anything else, lookup that opcode's operand
# type from its definition.
final_operands.append(Operand(
operand_fmts[i][1],
operand
))
# Build the final, immutable `Instruction`.
final.append(Instruction.create(mnemonic, final_operands))
label_pcs = {}
# The second pass, find the absolute PC for each label.
current_pc = 0
for ins in final:
if isinstance(ins, Label):
label_pcs[ins.name] = current_pc
continue
# size_on_disk must know the current pc because of alignment on
# tableswitch and lookupswitch.
current_pc += ins.size_on_disk(current_pc)
# The third pass, now that we know where each label is we can figure
# out the offset for each jump.
current_pc = 0
for ins in final:
if isinstance(ins, Label):
continue
for i, operand in enumerate(ins.operands):
if isinstance(operand, dict):
# lookupswitch is a special case
for k, v in operand.items():
if isinstance(v, Label):
operand[k] = Operand(40, label_pcs[v.name] - current_pc)
elif isinstance(operand, Label):
ins.operands[i] = Operand(
40,
label_pcs[operand.name] - current_pc
)
current_pc += ins.size_on_disk(current_pc)
yield ins | 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 bytecode.
As a simple example, lets produce an infinite loop:
>>> from jawa.assemble import assemble, Label
>>> print(list(assemble((
... Label('start'),
... ('goto', Label('start'))
... ))))
[Instruction(mnemonic='goto', opcode=167, operands=[
Operand(op_type=40, value=0)], pos=0)]
For a more complex example, see examples/hello_world.py.
"""
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
# alignment padding.
for line in code:
if isinstance(line, Label):
final.append(line)
continue
mnemonic, operands = line[0], line[1:]
operand_fmts = opcode_table[mnemonic]['operands']
# We need to coerce each opcodes operands into their
# final `Operand` form.
final_operands = []
for i, operand in enumerate(operands):
if isinstance(operand, Operand):
# Already in Operand form.
final_operands.append(operand)
elif isinstance(operand, Constant):
# Convert constants into CONSTANT_INDEX'es
final_operands.append(Operand(
OperandTypes.CONSTANT_INDEX,
operand.index
))
elif isinstance(operand, dict):
# lookupswitch's operand is a dict as
# a special usability case.
final_operands.append(operand)
elif isinstance(operand, Label):
final_operands.append(operand)
else:
# For anything else, lookup that opcode's operand
# type from its definition.
final_operands.append(Operand(
operand_fmts[i][1],
operand
))
# Build the final, immutable `Instruction`.
final.append(Instruction.create(mnemonic, final_operands))
label_pcs = {}
# The second pass, find the absolute PC for each label.
current_pc = 0
for ins in final:
if isinstance(ins, Label):
label_pcs[ins.name] = current_pc
continue
# size_on_disk must know the current pc because of alignment on
# tableswitch and lookupswitch.
current_pc += ins.size_on_disk(current_pc)
# The third pass, now that we know where each label is we can figure
# out the offset for each jump.
current_pc = 0
for ins in final:
if isinstance(ins, Label):
continue
for i, operand in enumerate(ins.operands):
if isinstance(operand, dict):
# lookupswitch is a special case
for k, v in operand.items():
if isinstance(v, Label):
operand[k] = Operand(40, label_pcs[v.name] - current_pc)
elif isinstance(operand, Label):
ins.operands[i] = Operand(
40,
label_pcs[operand.name] - current_pc
)
current_pc += ins.size_on_disk(current_pc)
yield ins | [
"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",
"# alignment padding.",
"for",
"line",
"in",
"code",
":",
"if",
"isinstance",
"(",
"line",
",",
"Label",
")",
":",
"final",
".",
"append",
"(",
"line",
")",
"continue",
"mnemonic",
",",
"operands",
"=",
"line",
"[",
"0",
"]",
",",
"line",
"[",
"1",
":",
"]",
"operand_fmts",
"=",
"opcode_table",
"[",
"mnemonic",
"]",
"[",
"'operands'",
"]",
"# We need to coerce each opcodes operands into their",
"# final `Operand` form.",
"final_operands",
"=",
"[",
"]",
"for",
"i",
",",
"operand",
"in",
"enumerate",
"(",
"operands",
")",
":",
"if",
"isinstance",
"(",
"operand",
",",
"Operand",
")",
":",
"# Already in Operand form.",
"final_operands",
".",
"append",
"(",
"operand",
")",
"elif",
"isinstance",
"(",
"operand",
",",
"Constant",
")",
":",
"# Convert constants into CONSTANT_INDEX'es",
"final_operands",
".",
"append",
"(",
"Operand",
"(",
"OperandTypes",
".",
"CONSTANT_INDEX",
",",
"operand",
".",
"index",
")",
")",
"elif",
"isinstance",
"(",
"operand",
",",
"dict",
")",
":",
"# lookupswitch's operand is a dict as",
"# a special usability case.",
"final_operands",
".",
"append",
"(",
"operand",
")",
"elif",
"isinstance",
"(",
"operand",
",",
"Label",
")",
":",
"final_operands",
".",
"append",
"(",
"operand",
")",
"else",
":",
"# For anything else, lookup that opcode's operand",
"# type from its definition.",
"final_operands",
".",
"append",
"(",
"Operand",
"(",
"operand_fmts",
"[",
"i",
"]",
"[",
"1",
"]",
",",
"operand",
")",
")",
"# Build the final, immutable `Instruction`.",
"final",
".",
"append",
"(",
"Instruction",
".",
"create",
"(",
"mnemonic",
",",
"final_operands",
")",
")",
"label_pcs",
"=",
"{",
"}",
"# The second pass, find the absolute PC for each label.",
"current_pc",
"=",
"0",
"for",
"ins",
"in",
"final",
":",
"if",
"isinstance",
"(",
"ins",
",",
"Label",
")",
":",
"label_pcs",
"[",
"ins",
".",
"name",
"]",
"=",
"current_pc",
"continue",
"# size_on_disk must know the current pc because of alignment on",
"# tableswitch and lookupswitch.",
"current_pc",
"+=",
"ins",
".",
"size_on_disk",
"(",
"current_pc",
")",
"# The third pass, now that we know where each label is we can figure",
"# out the offset for each jump.",
"current_pc",
"=",
"0",
"for",
"ins",
"in",
"final",
":",
"if",
"isinstance",
"(",
"ins",
",",
"Label",
")",
":",
"continue",
"for",
"i",
",",
"operand",
"in",
"enumerate",
"(",
"ins",
".",
"operands",
")",
":",
"if",
"isinstance",
"(",
"operand",
",",
"dict",
")",
":",
"# lookupswitch is a special case",
"for",
"k",
",",
"v",
"in",
"operand",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"Label",
")",
":",
"operand",
"[",
"k",
"]",
"=",
"Operand",
"(",
"40",
",",
"label_pcs",
"[",
"v",
".",
"name",
"]",
"-",
"current_pc",
")",
"elif",
"isinstance",
"(",
"operand",
",",
"Label",
")",
":",
"ins",
".",
"operands",
"[",
"i",
"]",
"=",
"Operand",
"(",
"40",
",",
"label_pcs",
"[",
"operand",
".",
"name",
"]",
"-",
"current_pc",
")",
"current_pc",
"+=",
"ins",
".",
"size_on_disk",
"(",
"current_pc",
")",
"yield",
"ins"
] | 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 example, lets produce an infinite loop:
>>> from jawa.assemble import assemble, Label
>>> print(list(assemble((
... Label('start'),
... ('goto', Label('start'))
... ))))
[Instruction(mnemonic='goto', opcode=167, operands=[
Operand(op_type=40, value=0)], pos=0)]
For a more complex example, see examples/hello_world.py. | [
"Assemble",
"the",
"given",
"iterable",
"of",
"mnemonics",
"operands",
"and",
"lables",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/assemble.py#L15-L115 | train |
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.append(hook) | 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.append(hook) | [
"def",
"register",
"(",
"self",
",",
"hook",
")",
":",
"assert",
"callable",
"(",
"hook",
")",
",",
"\"Hook must be a callable\"",
"assert",
"issubclass",
"(",
"hook",
",",
"HookBase",
")",
",",
"\"The hook does not inherit from HookBase\"",
"self",
".",
"_registry",
".",
"append",
"(",
"hook",
")"
] | 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 |
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
"""
return [
(form, form.save(*args, **kwargs))
for form in self.instances
] | 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
"""
return [
(form, form.save(*args, **kwargs))
for form in self.instances
] | [
"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 |
TkTech/Jawa | jawa/attribute.py | get_attribute_classes | def get_attribute_classes() -> Dict[str, Attribute]:
"""
Lookup all builtin Attribute subclasses, load them, and return a dict
"""
attribute_children = pkgutil.iter_modules(
importlib.import_module('jawa.attributes').__path__,
prefix='jawa.attributes.'
)
result = {}
for _, name, _ in attribute_children:
classes = inspect.getmembers(
importlib.import_module(name),
lambda c: (
inspect.isclass(c) and issubclass(c, Attribute) and
c is not Attribute
)
)
for class_name, class_ in classes:
attribute_name = getattr(class_, 'ATTRIBUTE_NAME', class_name[:-9])
result[attribute_name] = class_
return result | python | def get_attribute_classes() -> Dict[str, Attribute]:
"""
Lookup all builtin Attribute subclasses, load them, and return a dict
"""
attribute_children = pkgutil.iter_modules(
importlib.import_module('jawa.attributes').__path__,
prefix='jawa.attributes.'
)
result = {}
for _, name, _ in attribute_children:
classes = inspect.getmembers(
importlib.import_module(name),
lambda c: (
inspect.isclass(c) and issubclass(c, Attribute) and
c is not Attribute
)
)
for class_name, class_ in classes:
attribute_name = getattr(class_, 'ATTRIBUTE_NAME', class_name[:-9])
result[attribute_name] = class_
return result | [
"def",
"get_attribute_classes",
"(",
")",
"->",
"Dict",
"[",
"str",
",",
"Attribute",
"]",
":",
"attribute_children",
"=",
"pkgutil",
".",
"iter_modules",
"(",
"importlib",
".",
"import_module",
"(",
"'jawa.attributes'",
")",
".",
"__path__",
",",
"prefix",
"=",
"'jawa.attributes.'",
")",
"result",
"=",
"{",
"}",
"for",
"_",
",",
"name",
",",
"_",
"in",
"attribute_children",
":",
"classes",
"=",
"inspect",
".",
"getmembers",
"(",
"importlib",
".",
"import_module",
"(",
"name",
")",
",",
"lambda",
"c",
":",
"(",
"inspect",
".",
"isclass",
"(",
"c",
")",
"and",
"issubclass",
"(",
"c",
",",
"Attribute",
")",
"and",
"c",
"is",
"not",
"Attribute",
")",
")",
"for",
"class_name",
",",
"class_",
"in",
"classes",
":",
"attribute_name",
"=",
"getattr",
"(",
"class_",
",",
"'ATTRIBUTE_NAME'",
",",
"class_name",
"[",
":",
"-",
"9",
"]",
")",
"result",
"[",
"attribute_name",
"]",
"=",
"class_",
"return",
"result"
] | Lookup all builtin Attribute subclasses, load them, and return a dict | [
"Lookup",
"all",
"builtin",
"Attribute",
"subclasses",
"load",
"them",
"and",
"return",
"a",
"dict"
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/attribute.py#L161-L184 | train |
TkTech/Jawa | jawa/attribute.py | AttributeTable.unpack | def unpack(self, source: IO):
"""
Read the ConstantPool from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like object providing `read()`
"""
count = unpack('>H', source.read(2))[0]
for _ in repeat(None, count):
name_index, length = unpack('>HI', source.read(6))
info_blob = source.read(length)
self._table.append((name_index, info_blob)) | python | def unpack(self, source: IO):
"""
Read the ConstantPool from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like object providing `read()`
"""
count = unpack('>H', source.read(2))[0]
for _ in repeat(None, count):
name_index, length = unpack('>HI', source.read(6))
info_blob = source.read(length)
self._table.append((name_index, info_blob)) | [
"def",
"unpack",
"(",
"self",
",",
"source",
":",
"IO",
")",
":",
"count",
"=",
"unpack",
"(",
"'>H'",
",",
"source",
".",
"read",
"(",
"2",
")",
")",
"[",
"0",
"]",
"for",
"_",
"in",
"repeat",
"(",
"None",
",",
"count",
")",
":",
"name_index",
",",
"length",
"=",
"unpack",
"(",
"'>HI'",
",",
"source",
".",
"read",
"(",
"6",
")",
")",
"info_blob",
"=",
"source",
".",
"read",
"(",
"length",
")",
"self",
".",
"_table",
".",
"append",
"(",
"(",
"name_index",
",",
"info_blob",
")",
")"
] | Read the ConstantPool from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like object providing `read()` | [
"Read",
"the",
"ConstantPool",
"from",
"the",
"file",
"-",
"like",
"object",
"source",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/attribute.py#L67-L82 | train |
TkTech/Jawa | jawa/attribute.py | AttributeTable.pack | def pack(self, out: IO):
"""
Write the AttributeTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()`
"""
out.write(pack('>H', len(self._table)))
for attribute in self:
info = attribute.pack()
out.write(pack(
'>HI',
attribute.name.index,
len(info)
))
out.write(info) | python | def pack(self, out: IO):
"""
Write the AttributeTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()`
"""
out.write(pack('>H', len(self._table)))
for attribute in self:
info = attribute.pack()
out.write(pack(
'>HI',
attribute.name.index,
len(info)
))
out.write(info) | [
"def",
"pack",
"(",
"self",
",",
"out",
":",
"IO",
")",
":",
"out",
".",
"write",
"(",
"pack",
"(",
"'>H'",
",",
"len",
"(",
"self",
".",
"_table",
")",
")",
")",
"for",
"attribute",
"in",
"self",
":",
"info",
"=",
"attribute",
".",
"pack",
"(",
")",
"out",
".",
"write",
"(",
"pack",
"(",
"'>HI'",
",",
"attribute",
".",
"name",
".",
"index",
",",
"len",
"(",
"info",
")",
")",
")",
"out",
".",
"write",
"(",
"info",
")"
] | Write the AttributeTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()` | [
"Write",
"the",
"AttributeTable",
"to",
"the",
"file",
"-",
"like",
"object",
"out",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/attribute.py#L103-L122 | train |
TkTech/Jawa | jawa/attribute.py | AttributeTable.create | def create(self, type_, *args, **kwargs) -> Any:
"""
Creates a new attribute of `type_`, appending it to the attribute
table and returning it.
"""
attribute = type_(self, *args, **kwargs)
self._table.append(attribute)
return attribute | python | def create(self, type_, *args, **kwargs) -> Any:
"""
Creates a new attribute of `type_`, appending it to the attribute
table and returning it.
"""
attribute = type_(self, *args, **kwargs)
self._table.append(attribute)
return attribute | [
"def",
"create",
"(",
"self",
",",
"type_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Any",
":",
"attribute",
"=",
"type_",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_table",
".",
"append",
"(",
"attribute",
")",
"return",
"attribute"
] | Creates a new attribute of `type_`, appending it to the attribute
table and returning it. | [
"Creates",
"a",
"new",
"attribute",
"of",
"type_",
"appending",
"it",
"to",
"the",
"attribute",
"table",
"and",
"returning",
"it",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/attribute.py#L124-L131 | train |
piotr-rusin/spam-lists | spam_lists/composites.py | RedirectURLResolver.get_locations | def get_locations(self, url):
"""Get valid location header values from responses.
:param url: a URL address. If a HEAD request sent to it
fails because the address has invalid schema, times out
or there is a connection error, the generator yields nothing.
:returns: valid redirection addresses. If a request for
a redirection address fails, and the address is still a valid
URL string, it's included as the last yielded value. If it's
not, the previous value is the last one.
:raises ValuError: if the argument is not a valid URL
"""
if not is_valid_url(url):
raise InvalidURLError('{} is not a valid URL'.format(url))
try:
response = self.session.head(url)
except (ConnectionError, InvalidSchema, Timeout):
raise StopIteration
try:
generator = self.session.resolve_redirects(
response,
response.request
)
for response in generator:
yield response.url
except InvalidURL:
pass
except (ConnectionError, InvalidSchema, Timeout) as error:
last_url = response.headers['location']
if isinstance(error, Timeout) or is_valid_url(last_url):
yield last_url | python | def get_locations(self, url):
"""Get valid location header values from responses.
:param url: a URL address. If a HEAD request sent to it
fails because the address has invalid schema, times out
or there is a connection error, the generator yields nothing.
:returns: valid redirection addresses. If a request for
a redirection address fails, and the address is still a valid
URL string, it's included as the last yielded value. If it's
not, the previous value is the last one.
:raises ValuError: if the argument is not a valid URL
"""
if not is_valid_url(url):
raise InvalidURLError('{} is not a valid URL'.format(url))
try:
response = self.session.head(url)
except (ConnectionError, InvalidSchema, Timeout):
raise StopIteration
try:
generator = self.session.resolve_redirects(
response,
response.request
)
for response in generator:
yield response.url
except InvalidURL:
pass
except (ConnectionError, InvalidSchema, Timeout) as error:
last_url = response.headers['location']
if isinstance(error, Timeout) or is_valid_url(last_url):
yield last_url | [
"def",
"get_locations",
"(",
"self",
",",
"url",
")",
":",
"if",
"not",
"is_valid_url",
"(",
"url",
")",
":",
"raise",
"InvalidURLError",
"(",
"'{} is not a valid URL'",
".",
"format",
"(",
"url",
")",
")",
"try",
":",
"response",
"=",
"self",
".",
"session",
".",
"head",
"(",
"url",
")",
"except",
"(",
"ConnectionError",
",",
"InvalidSchema",
",",
"Timeout",
")",
":",
"raise",
"StopIteration",
"try",
":",
"generator",
"=",
"self",
".",
"session",
".",
"resolve_redirects",
"(",
"response",
",",
"response",
".",
"request",
")",
"for",
"response",
"in",
"generator",
":",
"yield",
"response",
".",
"url",
"except",
"InvalidURL",
":",
"pass",
"except",
"(",
"ConnectionError",
",",
"InvalidSchema",
",",
"Timeout",
")",
"as",
"error",
":",
"last_url",
"=",
"response",
".",
"headers",
"[",
"'location'",
"]",
"if",
"isinstance",
"(",
"error",
",",
"Timeout",
")",
"or",
"is_valid_url",
"(",
"last_url",
")",
":",
"yield",
"last_url"
] | Get valid location header values from responses.
:param url: a URL address. If a HEAD request sent to it
fails because the address has invalid schema, times out
or there is a connection error, the generator yields nothing.
:returns: valid redirection addresses. If a request for
a redirection address fails, and the address is still a valid
URL string, it's included as the last yielded value. If it's
not, the previous value is the last one.
:raises ValuError: if the argument is not a valid URL | [
"Get",
"valid",
"location",
"header",
"values",
"from",
"responses",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/composites.py#L68-L98 | train |
piotr-rusin/spam-lists | spam_lists/composites.py | RedirectURLResolver.get_new_locations | def get_new_locations(self, urls):
"""Get valid location header values for all given URLs.
The returned values are new, that is: they do not repeat any
value contained in the original input. Only unique values
are yielded.
:param urls: a list of URL addresses
:returns: valid location header values from responses
to the URLs
"""
seen = set(urls)
for i in urls:
for k in self.get_locations(i):
if k not in seen:
seen.add(k)
yield k | python | def get_new_locations(self, urls):
"""Get valid location header values for all given URLs.
The returned values are new, that is: they do not repeat any
value contained in the original input. Only unique values
are yielded.
:param urls: a list of URL addresses
:returns: valid location header values from responses
to the URLs
"""
seen = set(urls)
for i in urls:
for k in self.get_locations(i):
if k not in seen:
seen.add(k)
yield k | [
"def",
"get_new_locations",
"(",
"self",
",",
"urls",
")",
":",
"seen",
"=",
"set",
"(",
"urls",
")",
"for",
"i",
"in",
"urls",
":",
"for",
"k",
"in",
"self",
".",
"get_locations",
"(",
"i",
")",
":",
"if",
"k",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"k",
")",
"yield",
"k"
] | Get valid location header values for all given URLs.
The returned values are new, that is: they do not repeat any
value contained in the original input. Only unique values
are yielded.
:param urls: a list of URL addresses
:returns: valid location header values from responses
to the URLs | [
"Get",
"valid",
"location",
"header",
"values",
"for",
"all",
"given",
"URLs",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/composites.py#L100-L116 | train |
piotr-rusin/spam-lists | spam_lists/composites.py | RedirectURLResolver.get_urls_and_locations | def get_urls_and_locations(self, urls):
"""Get URLs and their redirection addresses.
:param urls: a list of URL addresses
:returns: an instance of CachedIterable containing given URLs
and valid location header values of their responses
"""
location_generator = self.get_new_locations(urls)
initial_cache = list(set(urls))
return CachedIterable(location_generator, initial_cache) | python | def get_urls_and_locations(self, urls):
"""Get URLs and their redirection addresses.
:param urls: a list of URL addresses
:returns: an instance of CachedIterable containing given URLs
and valid location header values of their responses
"""
location_generator = self.get_new_locations(urls)
initial_cache = list(set(urls))
return CachedIterable(location_generator, initial_cache) | [
"def",
"get_urls_and_locations",
"(",
"self",
",",
"urls",
")",
":",
"location_generator",
"=",
"self",
".",
"get_new_locations",
"(",
"urls",
")",
"initial_cache",
"=",
"list",
"(",
"set",
"(",
"urls",
")",
")",
"return",
"CachedIterable",
"(",
"location_generator",
",",
"initial_cache",
")"
] | Get URLs and their redirection addresses.
:param urls: a list of URL addresses
:returns: an instance of CachedIterable containing given URLs
and valid location header values of their responses | [
"Get",
"URLs",
"and",
"their",
"redirection",
"addresses",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/composites.py#L118-L127 | train |
threema-ch/ocspresponder | ocspresponder/__init__.py | OCSPResponder._handle_get | def _handle_get(self, request_data):
"""
An OCSP GET request contains the DER-in-base64 encoded OCSP request in the
HTTP request URL.
"""
der = base64.b64decode(request_data)
ocsp_request = self._parse_ocsp_request(der)
return self._build_http_response(ocsp_request) | python | def _handle_get(self, request_data):
"""
An OCSP GET request contains the DER-in-base64 encoded OCSP request in the
HTTP request URL.
"""
der = base64.b64decode(request_data)
ocsp_request = self._parse_ocsp_request(der)
return self._build_http_response(ocsp_request) | [
"def",
"_handle_get",
"(",
"self",
",",
"request_data",
")",
":",
"der",
"=",
"base64",
".",
"b64decode",
"(",
"request_data",
")",
"ocsp_request",
"=",
"self",
".",
"_parse_ocsp_request",
"(",
"der",
")",
"return",
"self",
".",
"_build_http_response",
"(",
"ocsp_request",
")"
] | An OCSP GET request contains the DER-in-base64 encoded OCSP request in the
HTTP request URL. | [
"An",
"OCSP",
"GET",
"request",
"contains",
"the",
"DER",
"-",
"in",
"-",
"base64",
"encoded",
"OCSP",
"request",
"in",
"the",
"HTTP",
"request",
"URL",
"."
] | b9486af68dd02b84e01bedabe4f6843a6ff0f698 | https://github.com/threema-ch/ocspresponder/blob/b9486af68dd02b84e01bedabe4f6843a6ff0f698/ocspresponder/__init__.py#L111-L118 | train |
threema-ch/ocspresponder | ocspresponder/__init__.py | OCSPResponder._handle_post | def _handle_post(self):
"""
An OCSP POST request contains the DER encoded OCSP request in the HTTP
request body.
"""
der = request.body.read()
ocsp_request = self._parse_ocsp_request(der)
return self._build_http_response(ocsp_request) | python | def _handle_post(self):
"""
An OCSP POST request contains the DER encoded OCSP request in the HTTP
request body.
"""
der = request.body.read()
ocsp_request = self._parse_ocsp_request(der)
return self._build_http_response(ocsp_request) | [
"def",
"_handle_post",
"(",
"self",
")",
":",
"der",
"=",
"request",
".",
"body",
".",
"read",
"(",
")",
"ocsp_request",
"=",
"self",
".",
"_parse_ocsp_request",
"(",
"der",
")",
"return",
"self",
".",
"_build_http_response",
"(",
"ocsp_request",
")"
] | An OCSP POST request contains the DER encoded OCSP request in the HTTP
request body. | [
"An",
"OCSP",
"POST",
"request",
"contains",
"the",
"DER",
"encoded",
"OCSP",
"request",
"in",
"the",
"HTTP",
"request",
"body",
"."
] | b9486af68dd02b84e01bedabe4f6843a6ff0f698 | https://github.com/threema-ch/ocspresponder/blob/b9486af68dd02b84e01bedabe4f6843a6ff0f698/ocspresponder/__init__.py#L120-L127 | train |
threema-ch/ocspresponder | ocspresponder/__init__.py | OCSPResponder._build_ocsp_response | def _build_ocsp_response(self, ocsp_request: OCSPRequest) -> OCSPResponse:
"""
Create and return an OCSP response from an OCSP request.
"""
# Get the certificate serial
tbs_request = ocsp_request['tbs_request']
request_list = tbs_request['request_list']
if len(request_list) != 1:
logger.warning('Received OCSP request with multiple sub requests')
raise NotImplemented('Combined requests not yet supported')
single_request = request_list[0] # TODO: Support more than one request
req_cert = single_request['req_cert']
serial = req_cert['serial_number'].native
# Check certificate status
try:
certificate_status, revocation_date = self._validate(serial)
except Exception as e:
logger.exception('Could not determine certificate status: %s', e)
return self._fail(ResponseStatus.internal_error)
# Retrieve certificate
try:
subject_cert_contents = self._cert_retrieve(serial)
except Exception as e:
logger.exception('Could not retrieve certificate with serial %s: %s', serial, e)
return self._fail(ResponseStatus.internal_error)
# Parse certificate
try:
subject_cert = asymmetric.load_certificate(subject_cert_contents.encode('utf8'))
except Exception as e:
logger.exception('Returned certificate with serial %s is invalid: %s', serial, e)
return self._fail(ResponseStatus.internal_error)
# Build the response
builder = OCSPResponseBuilder(**{
'response_status': ResponseStatus.successful.value,
'certificate': subject_cert,
'certificate_status': certificate_status.value,
'revocation_date': revocation_date,
})
# Parse extensions
for extension in tbs_request['request_extensions']:
extn_id = extension['extn_id'].native
critical = extension['critical'].native
value = extension['extn_value'].parsed
# This variable tracks whether any unknown extensions were encountered
unknown = False
# Handle nonce extension
if extn_id == 'nonce':
builder.nonce = value.native
# That's all we know
else:
unknown = True
# If an unknown critical extension is encountered (which should not
# usually happen, according to RFC 6960 4.1.2), we should throw our
# hands up in despair and run.
if unknown is True and critical is True:
logger.warning('Could not parse unknown critical extension: %r',
dict(extension.native))
return self._fail(ResponseStatus.internal_error)
# If it's an unknown non-critical extension, we can safely ignore it.
elif unknown is True:
logger.info('Ignored unknown non-critical extension: %r', dict(extension.native))
# Set certificate issuer
builder.certificate_issuer = self._issuer_cert
# Set next update date
builder.next_update = datetime.now(timezone.utc) + timedelta(days=self._next_update_days)
return builder.build(self._responder_key, self._responder_cert) | python | def _build_ocsp_response(self, ocsp_request: OCSPRequest) -> OCSPResponse:
"""
Create and return an OCSP response from an OCSP request.
"""
# Get the certificate serial
tbs_request = ocsp_request['tbs_request']
request_list = tbs_request['request_list']
if len(request_list) != 1:
logger.warning('Received OCSP request with multiple sub requests')
raise NotImplemented('Combined requests not yet supported')
single_request = request_list[0] # TODO: Support more than one request
req_cert = single_request['req_cert']
serial = req_cert['serial_number'].native
# Check certificate status
try:
certificate_status, revocation_date = self._validate(serial)
except Exception as e:
logger.exception('Could not determine certificate status: %s', e)
return self._fail(ResponseStatus.internal_error)
# Retrieve certificate
try:
subject_cert_contents = self._cert_retrieve(serial)
except Exception as e:
logger.exception('Could not retrieve certificate with serial %s: %s', serial, e)
return self._fail(ResponseStatus.internal_error)
# Parse certificate
try:
subject_cert = asymmetric.load_certificate(subject_cert_contents.encode('utf8'))
except Exception as e:
logger.exception('Returned certificate with serial %s is invalid: %s', serial, e)
return self._fail(ResponseStatus.internal_error)
# Build the response
builder = OCSPResponseBuilder(**{
'response_status': ResponseStatus.successful.value,
'certificate': subject_cert,
'certificate_status': certificate_status.value,
'revocation_date': revocation_date,
})
# Parse extensions
for extension in tbs_request['request_extensions']:
extn_id = extension['extn_id'].native
critical = extension['critical'].native
value = extension['extn_value'].parsed
# This variable tracks whether any unknown extensions were encountered
unknown = False
# Handle nonce extension
if extn_id == 'nonce':
builder.nonce = value.native
# That's all we know
else:
unknown = True
# If an unknown critical extension is encountered (which should not
# usually happen, according to RFC 6960 4.1.2), we should throw our
# hands up in despair and run.
if unknown is True and critical is True:
logger.warning('Could not parse unknown critical extension: %r',
dict(extension.native))
return self._fail(ResponseStatus.internal_error)
# If it's an unknown non-critical extension, we can safely ignore it.
elif unknown is True:
logger.info('Ignored unknown non-critical extension: %r', dict(extension.native))
# Set certificate issuer
builder.certificate_issuer = self._issuer_cert
# Set next update date
builder.next_update = datetime.now(timezone.utc) + timedelta(days=self._next_update_days)
return builder.build(self._responder_key, self._responder_cert) | [
"def",
"_build_ocsp_response",
"(",
"self",
",",
"ocsp_request",
":",
"OCSPRequest",
")",
"->",
"OCSPResponse",
":",
"# Get the certificate serial",
"tbs_request",
"=",
"ocsp_request",
"[",
"'tbs_request'",
"]",
"request_list",
"=",
"tbs_request",
"[",
"'request_list'",
"]",
"if",
"len",
"(",
"request_list",
")",
"!=",
"1",
":",
"logger",
".",
"warning",
"(",
"'Received OCSP request with multiple sub requests'",
")",
"raise",
"NotImplemented",
"(",
"'Combined requests not yet supported'",
")",
"single_request",
"=",
"request_list",
"[",
"0",
"]",
"# TODO: Support more than one request",
"req_cert",
"=",
"single_request",
"[",
"'req_cert'",
"]",
"serial",
"=",
"req_cert",
"[",
"'serial_number'",
"]",
".",
"native",
"# Check certificate status",
"try",
":",
"certificate_status",
",",
"revocation_date",
"=",
"self",
".",
"_validate",
"(",
"serial",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"exception",
"(",
"'Could not determine certificate status: %s'",
",",
"e",
")",
"return",
"self",
".",
"_fail",
"(",
"ResponseStatus",
".",
"internal_error",
")",
"# Retrieve certificate",
"try",
":",
"subject_cert_contents",
"=",
"self",
".",
"_cert_retrieve",
"(",
"serial",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"exception",
"(",
"'Could not retrieve certificate with serial %s: %s'",
",",
"serial",
",",
"e",
")",
"return",
"self",
".",
"_fail",
"(",
"ResponseStatus",
".",
"internal_error",
")",
"# Parse certificate",
"try",
":",
"subject_cert",
"=",
"asymmetric",
".",
"load_certificate",
"(",
"subject_cert_contents",
".",
"encode",
"(",
"'utf8'",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"exception",
"(",
"'Returned certificate with serial %s is invalid: %s'",
",",
"serial",
",",
"e",
")",
"return",
"self",
".",
"_fail",
"(",
"ResponseStatus",
".",
"internal_error",
")",
"# Build the response",
"builder",
"=",
"OCSPResponseBuilder",
"(",
"*",
"*",
"{",
"'response_status'",
":",
"ResponseStatus",
".",
"successful",
".",
"value",
",",
"'certificate'",
":",
"subject_cert",
",",
"'certificate_status'",
":",
"certificate_status",
".",
"value",
",",
"'revocation_date'",
":",
"revocation_date",
",",
"}",
")",
"# Parse extensions",
"for",
"extension",
"in",
"tbs_request",
"[",
"'request_extensions'",
"]",
":",
"extn_id",
"=",
"extension",
"[",
"'extn_id'",
"]",
".",
"native",
"critical",
"=",
"extension",
"[",
"'critical'",
"]",
".",
"native",
"value",
"=",
"extension",
"[",
"'extn_value'",
"]",
".",
"parsed",
"# This variable tracks whether any unknown extensions were encountered",
"unknown",
"=",
"False",
"# Handle nonce extension",
"if",
"extn_id",
"==",
"'nonce'",
":",
"builder",
".",
"nonce",
"=",
"value",
".",
"native",
"# That's all we know",
"else",
":",
"unknown",
"=",
"True",
"# If an unknown critical extension is encountered (which should not",
"# usually happen, according to RFC 6960 4.1.2), we should throw our",
"# hands up in despair and run.",
"if",
"unknown",
"is",
"True",
"and",
"critical",
"is",
"True",
":",
"logger",
".",
"warning",
"(",
"'Could not parse unknown critical extension: %r'",
",",
"dict",
"(",
"extension",
".",
"native",
")",
")",
"return",
"self",
".",
"_fail",
"(",
"ResponseStatus",
".",
"internal_error",
")",
"# If it's an unknown non-critical extension, we can safely ignore it.",
"elif",
"unknown",
"is",
"True",
":",
"logger",
".",
"info",
"(",
"'Ignored unknown non-critical extension: %r'",
",",
"dict",
"(",
"extension",
".",
"native",
")",
")",
"# Set certificate issuer",
"builder",
".",
"certificate_issuer",
"=",
"self",
".",
"_issuer_cert",
"# Set next update date",
"builder",
".",
"next_update",
"=",
"datetime",
".",
"now",
"(",
"timezone",
".",
"utc",
")",
"+",
"timedelta",
"(",
"days",
"=",
"self",
".",
"_next_update_days",
")",
"return",
"builder",
".",
"build",
"(",
"self",
".",
"_responder_key",
",",
"self",
".",
"_responder_cert",
")"
] | Create and return an OCSP response from an OCSP request. | [
"Create",
"and",
"return",
"an",
"OCSP",
"response",
"from",
"an",
"OCSP",
"request",
"."
] | b9486af68dd02b84e01bedabe4f6843a6ff0f698 | https://github.com/threema-ch/ocspresponder/blob/b9486af68dd02b84e01bedabe4f6843a6ff0f698/ocspresponder/__init__.py#L139-L217 | train |
nitely/django-hooks | hooks/templatetags/hooks_tags.py | hook_tag | def hook_tag(context, name, *args, **kwargs):
"""
Hook tag to call within templates
:param dict context: This is automatically passed,\
contains the template state/variables
:param str name: The hook which will be dispatched
:param \*args: Positional arguments, will be passed to hook callbacks
:param \*\*kwargs: Keyword arguments, will be passed to hook callbacks
:return: A concatenation of all callbacks\
responses marked as safe (conditionally)
:rtype: str
"""
return format_html_join(
sep="\n",
format_string="{}",
args_generator=(
(response, )
for response in hook(name, context, *args, **kwargs)
)
) | python | def hook_tag(context, name, *args, **kwargs):
"""
Hook tag to call within templates
:param dict context: This is automatically passed,\
contains the template state/variables
:param str name: The hook which will be dispatched
:param \*args: Positional arguments, will be passed to hook callbacks
:param \*\*kwargs: Keyword arguments, will be passed to hook callbacks
:return: A concatenation of all callbacks\
responses marked as safe (conditionally)
:rtype: str
"""
return format_html_join(
sep="\n",
format_string="{}",
args_generator=(
(response, )
for response in hook(name, context, *args, **kwargs)
)
) | [
"def",
"hook_tag",
"(",
"context",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"format_html_join",
"(",
"sep",
"=",
"\"\\n\"",
",",
"format_string",
"=",
"\"{}\"",
",",
"args_generator",
"=",
"(",
"(",
"response",
",",
")",
"for",
"response",
"in",
"hook",
"(",
"name",
",",
"context",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
")"
] | Hook tag to call within templates
:param dict context: This is automatically passed,\
contains the template state/variables
:param str name: The hook which will be dispatched
:param \*args: Positional arguments, will be passed to hook callbacks
:param \*\*kwargs: Keyword arguments, will be passed to hook callbacks
:return: A concatenation of all callbacks\
responses marked as safe (conditionally)
:rtype: str | [
"Hook",
"tag",
"to",
"call",
"within",
"templates"
] | 26ea2150c9be110e90b9ee60fbfd1065ac30ab1d | https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/templatetags/hooks_tags.py#L15-L35 | train |
nitely/django-hooks | hooks/templatetags/hooks_tags.py | template_hook_collect | def template_hook_collect(module, hook_name, *args, **kwargs):
"""
Helper to include in your own templatetag, for static TemplateHooks
Example::
import myhooks
from hooks.templatetags import template_hook_collect
@register.simple_tag(takes_context=True)
def hook(context, name, *args, **kwargs):
return template_hook_collect(myhooks, name, context, *args, **kwargs)
:param module module: Module containing the template hook definitions
:param str hook_name: The hook name to be dispatched
:param \*args: Positional arguments, will be passed to hook callbacks
:param \*\*kwargs: Keyword arguments, will be passed to hook callbacks
:return: A concatenation of all callbacks\
responses marked as safe (conditionally)
:rtype: str
"""
try:
templatehook = getattr(module, hook_name)
except AttributeError:
return ""
return format_html_join(
sep="\n",
format_string="{}",
args_generator=(
(response, )
for response in templatehook(*args, **kwargs)
)
) | python | def template_hook_collect(module, hook_name, *args, **kwargs):
"""
Helper to include in your own templatetag, for static TemplateHooks
Example::
import myhooks
from hooks.templatetags import template_hook_collect
@register.simple_tag(takes_context=True)
def hook(context, name, *args, **kwargs):
return template_hook_collect(myhooks, name, context, *args, **kwargs)
:param module module: Module containing the template hook definitions
:param str hook_name: The hook name to be dispatched
:param \*args: Positional arguments, will be passed to hook callbacks
:param \*\*kwargs: Keyword arguments, will be passed to hook callbacks
:return: A concatenation of all callbacks\
responses marked as safe (conditionally)
:rtype: str
"""
try:
templatehook = getattr(module, hook_name)
except AttributeError:
return ""
return format_html_join(
sep="\n",
format_string="{}",
args_generator=(
(response, )
for response in templatehook(*args, **kwargs)
)
) | [
"def",
"template_hook_collect",
"(",
"module",
",",
"hook_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"templatehook",
"=",
"getattr",
"(",
"module",
",",
"hook_name",
")",
"except",
"AttributeError",
":",
"return",
"\"\"",
"return",
"format_html_join",
"(",
"sep",
"=",
"\"\\n\"",
",",
"format_string",
"=",
"\"{}\"",
",",
"args_generator",
"=",
"(",
"(",
"response",
",",
")",
"for",
"response",
"in",
"templatehook",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
")"
] | Helper to include in your own templatetag, for static TemplateHooks
Example::
import myhooks
from hooks.templatetags import template_hook_collect
@register.simple_tag(takes_context=True)
def hook(context, name, *args, **kwargs):
return template_hook_collect(myhooks, name, context, *args, **kwargs)
:param module module: Module containing the template hook definitions
:param str hook_name: The hook name to be dispatched
:param \*args: Positional arguments, will be passed to hook callbacks
:param \*\*kwargs: Keyword arguments, will be passed to hook callbacks
:return: A concatenation of all callbacks\
responses marked as safe (conditionally)
:rtype: str | [
"Helper",
"to",
"include",
"in",
"your",
"own",
"templatetag",
"for",
"static",
"TemplateHooks"
] | 26ea2150c9be110e90b9ee60fbfd1065ac30ab1d | https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/templatetags/hooks_tags.py#L38-L71 | train |
networks-lab/tidyextractors | tidyextractors/tidymbox/mbox_extractor.py | MboxExtractor._extract | def _extract(self, source, *args, **kwargs):
"""
Extracts data from mbox files. Mutates _data.
:param str source: The path to one or more mbox files.
:param args: Arbitrary arguments for extensibility.
:param kwargs: Arbitrary keyword arguments for extensibility.
:return: None
"""
# Extract data
self._data = mbox_to_pandas(source)
self._data['MessageID'] = pd.Series(range(0,len(self._data))) | python | def _extract(self, source, *args, **kwargs):
"""
Extracts data from mbox files. Mutates _data.
:param str source: The path to one or more mbox files.
:param args: Arbitrary arguments for extensibility.
:param kwargs: Arbitrary keyword arguments for extensibility.
:return: None
"""
# Extract data
self._data = mbox_to_pandas(source)
self._data['MessageID'] = pd.Series(range(0,len(self._data))) | [
"def",
"_extract",
"(",
"self",
",",
"source",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Extract data",
"self",
".",
"_data",
"=",
"mbox_to_pandas",
"(",
"source",
")",
"self",
".",
"_data",
"[",
"'MessageID'",
"]",
"=",
"pd",
".",
"Series",
"(",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"_data",
")",
")",
")"
] | Extracts data from mbox files. Mutates _data.
:param str source: The path to one or more mbox files.
:param args: Arbitrary arguments for extensibility.
:param kwargs: Arbitrary keyword arguments for extensibility.
:return: None | [
"Extracts",
"data",
"from",
"mbox",
"files",
".",
"Mutates",
"_data",
"."
] | 658448ed533beecf32adcc188fc64d1068d15ca6 | https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/tidymbox/mbox_extractor.py#L36-L47 | train |
Azure/azure-python-devtools | src/azure_devtools/ci_tools/bot_framework.py | build_from_issue_comment | def build_from_issue_comment(gh_token, body):
"""Create a WebhookMetadata from a comment added to an issue.
"""
if body["action"] in ["created", "edited"]:
github_con = Github(gh_token)
repo = github_con.get_repo(body['repository']['full_name'])
issue = repo.get_issue(body['issue']['number'])
text = body['comment']['body']
try:
comment = issue.get_comment(body['comment']['id'])
except UnknownObjectException:
# If the comment has already disapeared, skip the command
return None
return WebhookMetadata(repo, issue, text, comment)
return None | python | def build_from_issue_comment(gh_token, body):
"""Create a WebhookMetadata from a comment added to an issue.
"""
if body["action"] in ["created", "edited"]:
github_con = Github(gh_token)
repo = github_con.get_repo(body['repository']['full_name'])
issue = repo.get_issue(body['issue']['number'])
text = body['comment']['body']
try:
comment = issue.get_comment(body['comment']['id'])
except UnknownObjectException:
# If the comment has already disapeared, skip the command
return None
return WebhookMetadata(repo, issue, text, comment)
return None | [
"def",
"build_from_issue_comment",
"(",
"gh_token",
",",
"body",
")",
":",
"if",
"body",
"[",
"\"action\"",
"]",
"in",
"[",
"\"created\"",
",",
"\"edited\"",
"]",
":",
"github_con",
"=",
"Github",
"(",
"gh_token",
")",
"repo",
"=",
"github_con",
".",
"get_repo",
"(",
"body",
"[",
"'repository'",
"]",
"[",
"'full_name'",
"]",
")",
"issue",
"=",
"repo",
".",
"get_issue",
"(",
"body",
"[",
"'issue'",
"]",
"[",
"'number'",
"]",
")",
"text",
"=",
"body",
"[",
"'comment'",
"]",
"[",
"'body'",
"]",
"try",
":",
"comment",
"=",
"issue",
".",
"get_comment",
"(",
"body",
"[",
"'comment'",
"]",
"[",
"'id'",
"]",
")",
"except",
"UnknownObjectException",
":",
"# If the comment has already disapeared, skip the command",
"return",
"None",
"return",
"WebhookMetadata",
"(",
"repo",
",",
"issue",
",",
"text",
",",
"comment",
")",
"return",
"None"
] | Create a WebhookMetadata from a comment added to an issue. | [
"Create",
"a",
"WebhookMetadata",
"from",
"a",
"comment",
"added",
"to",
"an",
"issue",
"."
] | 2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936 | https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/bot_framework.py#L25-L39 | train |
Azure/azure-python-devtools | src/azure_devtools/ci_tools/bot_framework.py | build_from_issues | def build_from_issues(gh_token, body):
"""Create a WebhookMetadata from an opening issue text.
"""
if body["action"] in ["opened", "edited"]:
github_con = Github(gh_token)
repo = github_con.get_repo(body['repository']['full_name'])
issue = repo.get_issue(body['issue']['number'])
text = body['issue']['body']
comment = issue # It's where we update the comment: in the issue itself
return WebhookMetadata(repo, issue, text, comment)
return None | python | def build_from_issues(gh_token, body):
"""Create a WebhookMetadata from an opening issue text.
"""
if body["action"] in ["opened", "edited"]:
github_con = Github(gh_token)
repo = github_con.get_repo(body['repository']['full_name'])
issue = repo.get_issue(body['issue']['number'])
text = body['issue']['body']
comment = issue # It's where we update the comment: in the issue itself
return WebhookMetadata(repo, issue, text, comment)
return None | [
"def",
"build_from_issues",
"(",
"gh_token",
",",
"body",
")",
":",
"if",
"body",
"[",
"\"action\"",
"]",
"in",
"[",
"\"opened\"",
",",
"\"edited\"",
"]",
":",
"github_con",
"=",
"Github",
"(",
"gh_token",
")",
"repo",
"=",
"github_con",
".",
"get_repo",
"(",
"body",
"[",
"'repository'",
"]",
"[",
"'full_name'",
"]",
")",
"issue",
"=",
"repo",
".",
"get_issue",
"(",
"body",
"[",
"'issue'",
"]",
"[",
"'number'",
"]",
")",
"text",
"=",
"body",
"[",
"'issue'",
"]",
"[",
"'body'",
"]",
"comment",
"=",
"issue",
"# It's where we update the comment: in the issue itself",
"return",
"WebhookMetadata",
"(",
"repo",
",",
"issue",
",",
"text",
",",
"comment",
")",
"return",
"None"
] | Create a WebhookMetadata from an opening issue text. | [
"Create",
"a",
"WebhookMetadata",
"from",
"an",
"opening",
"issue",
"text",
"."
] | 2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936 | https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/bot_framework.py#L41-L51 | train |
Subsets and Splits