id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
224,800 | PythonCharmers/python-future | src/future/backports/xmlrpc/server.py | ServerHTMLDoc.markup | def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
"""Mark up some plain text, given a context of symbols to look for.
Each context dictionary maps object names to anchor names."""
escape = escape or self.escape
results = []
here = 0
# XXX Note that this regular expression does not allow for the
# hyperlinking of arbitrary strings being used as method
# names. Only methods with names consisting of word characters
# and '.'s are hyperlinked.
pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
r'RFC[- ]?(\d+)|'
r'PEP[- ]?(\d+)|'
r'(self\.)?((?:\w|\.)+))\b')
while 1:
match = pattern.search(text, here)
if not match: break
start, end = match.span()
results.append(escape(text[here:start]))
all, scheme, rfc, pep, selfdot, name = match.groups()
if scheme:
url = escape(all).replace('"', '"')
results.append('<a href="%s">%s</a>' % (url, url))
elif rfc:
url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
results.append('<a href="%s">%s</a>' % (url, escape(all)))
elif pep:
url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
results.append('<a href="%s">%s</a>' % (url, escape(all)))
elif text[end:end+1] == '(':
results.append(self.namelink(name, methods, funcs, classes))
elif selfdot:
results.append('self.<strong>%s</strong>' % name)
else:
results.append(self.namelink(name, classes))
here = end
results.append(escape(text[here:]))
return ''.join(results) | python | def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
escape = escape or self.escape
results = []
here = 0
# XXX Note that this regular expression does not allow for the
# hyperlinking of arbitrary strings being used as method
# names. Only methods with names consisting of word characters
# and '.'s are hyperlinked.
pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
r'RFC[- ]?(\d+)|'
r'PEP[- ]?(\d+)|'
r'(self\.)?((?:\w|\.)+))\b')
while 1:
match = pattern.search(text, here)
if not match: break
start, end = match.span()
results.append(escape(text[here:start]))
all, scheme, rfc, pep, selfdot, name = match.groups()
if scheme:
url = escape(all).replace('"', '"')
results.append('<a href="%s">%s</a>' % (url, url))
elif rfc:
url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
results.append('<a href="%s">%s</a>' % (url, escape(all)))
elif pep:
url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
results.append('<a href="%s">%s</a>' % (url, escape(all)))
elif text[end:end+1] == '(':
results.append(self.namelink(name, methods, funcs, classes))
elif selfdot:
results.append('self.<strong>%s</strong>' % name)
else:
results.append(self.namelink(name, classes))
here = end
results.append(escape(text[here:]))
return ''.join(results) | [
"def",
"markup",
"(",
"self",
",",
"text",
",",
"escape",
"=",
"None",
",",
"funcs",
"=",
"{",
"}",
",",
"classes",
"=",
"{",
"}",
",",
"methods",
"=",
"{",
"}",
")",
":",
"escape",
"=",
"escape",
"or",
"self",
".",
"escape",
"results",
"=",
"[... | Mark up some plain text, given a context of symbols to look for.
Each context dictionary maps object names to anchor names. | [
"Mark",
"up",
"some",
"plain",
"text",
"given",
"a",
"context",
"of",
"symbols",
"to",
"look",
"for",
".",
"Each",
"context",
"dictionary",
"maps",
"object",
"names",
"to",
"anchor",
"names",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/xmlrpc/server.py#L713-L752 |
224,801 | PythonCharmers/python-future | src/future/backports/xmlrpc/server.py | ServerHTMLDoc.docroutine | def docroutine(self, object, name, mod=None,
funcs={}, classes={}, methods={}, cl=None):
"""Produce HTML documentation for a function or method object."""
anchor = (cl and cl.__name__ or '') + '-' + name
note = ''
title = '<a name="%s"><strong>%s</strong></a>' % (
self.escape(anchor), self.escape(name))
if inspect.ismethod(object):
args = inspect.getfullargspec(object)
# exclude the argument bound to the instance, it will be
# confusing to the non-Python user
argspec = inspect.formatargspec (
args.args[1:],
args.varargs,
args.varkw,
args.defaults,
annotations=args.annotations,
formatvalue=self.formatvalue
)
elif inspect.isfunction(object):
args = inspect.getfullargspec(object)
argspec = inspect.formatargspec(
args.args, args.varargs, args.varkw, args.defaults,
annotations=args.annotations,
formatvalue=self.formatvalue)
else:
argspec = '(...)'
if isinstance(object, tuple):
argspec = object[0] or argspec
docstring = object[1] or ""
else:
docstring = pydoc.getdoc(object)
decl = title + argspec + (note and self.grey(
'<font face="helvetica, arial">%s</font>' % note))
doc = self.markup(
docstring, self.preformat, funcs, classes, methods)
doc = doc and '<dd><tt>%s</tt></dd>' % doc
return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc) | python | def docroutine(self, object, name, mod=None,
funcs={}, classes={}, methods={}, cl=None):
anchor = (cl and cl.__name__ or '') + '-' + name
note = ''
title = '<a name="%s"><strong>%s</strong></a>' % (
self.escape(anchor), self.escape(name))
if inspect.ismethod(object):
args = inspect.getfullargspec(object)
# exclude the argument bound to the instance, it will be
# confusing to the non-Python user
argspec = inspect.formatargspec (
args.args[1:],
args.varargs,
args.varkw,
args.defaults,
annotations=args.annotations,
formatvalue=self.formatvalue
)
elif inspect.isfunction(object):
args = inspect.getfullargspec(object)
argspec = inspect.formatargspec(
args.args, args.varargs, args.varkw, args.defaults,
annotations=args.annotations,
formatvalue=self.formatvalue)
else:
argspec = '(...)'
if isinstance(object, tuple):
argspec = object[0] or argspec
docstring = object[1] or ""
else:
docstring = pydoc.getdoc(object)
decl = title + argspec + (note and self.grey(
'<font face="helvetica, arial">%s</font>' % note))
doc = self.markup(
docstring, self.preformat, funcs, classes, methods)
doc = doc and '<dd><tt>%s</tt></dd>' % doc
return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc) | [
"def",
"docroutine",
"(",
"self",
",",
"object",
",",
"name",
",",
"mod",
"=",
"None",
",",
"funcs",
"=",
"{",
"}",
",",
"classes",
"=",
"{",
"}",
",",
"methods",
"=",
"{",
"}",
",",
"cl",
"=",
"None",
")",
":",
"anchor",
"=",
"(",
"cl",
"and... | Produce HTML documentation for a function or method object. | [
"Produce",
"HTML",
"documentation",
"for",
"a",
"function",
"or",
"method",
"object",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/xmlrpc/server.py#L754-L797 |
224,802 | PythonCharmers/python-future | src/future/backports/xmlrpc/server.py | ServerHTMLDoc.docserver | def docserver(self, server_name, package_documentation, methods):
"""Produce HTML documentation for an XML-RPC server."""
fdict = {}
for key, value in methods.items():
fdict[key] = '#-' + key
fdict[value] = fdict[key]
server_name = self.escape(server_name)
head = '<big><big><strong>%s</strong></big></big>' % server_name
result = self.heading(head, '#ffffff', '#7799ee')
doc = self.markup(package_documentation, self.preformat, fdict)
doc = doc and '<tt>%s</tt>' % doc
result = result + '<p>%s</p>\n' % doc
contents = []
method_items = sorted(methods.items())
for key, value in method_items:
contents.append(self.docroutine(value, key, funcs=fdict))
result = result + self.bigsection(
'Methods', '#ffffff', '#eeaa77', ''.join(contents))
return result | python | def docserver(self, server_name, package_documentation, methods):
fdict = {}
for key, value in methods.items():
fdict[key] = '#-' + key
fdict[value] = fdict[key]
server_name = self.escape(server_name)
head = '<big><big><strong>%s</strong></big></big>' % server_name
result = self.heading(head, '#ffffff', '#7799ee')
doc = self.markup(package_documentation, self.preformat, fdict)
doc = doc and '<tt>%s</tt>' % doc
result = result + '<p>%s</p>\n' % doc
contents = []
method_items = sorted(methods.items())
for key, value in method_items:
contents.append(self.docroutine(value, key, funcs=fdict))
result = result + self.bigsection(
'Methods', '#ffffff', '#eeaa77', ''.join(contents))
return result | [
"def",
"docserver",
"(",
"self",
",",
"server_name",
",",
"package_documentation",
",",
"methods",
")",
":",
"fdict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"methods",
".",
"items",
"(",
")",
":",
"fdict",
"[",
"key",
"]",
"=",
"'#-'",
"+",... | Produce HTML documentation for an XML-RPC server. | [
"Produce",
"HTML",
"documentation",
"for",
"an",
"XML",
"-",
"RPC",
"server",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/xmlrpc/server.py#L799-L822 |
224,803 | PythonCharmers/python-future | src/libpasteurize/fixes/fix_kwargs.py | needs_fixing | def needs_fixing(raw_params, kwargs_default=_kwargs_default_name):
u"""
Returns string with the name of the kwargs dict if the params after the first star need fixing
Otherwise returns empty string
"""
found_kwargs = False
needs_fix = False
for t in raw_params[2:]:
if t.type == token.COMMA:
# Commas are irrelevant at this stage.
continue
elif t.type == token.NAME and not found_kwargs:
# Keyword-only argument: definitely need to fix.
needs_fix = True
elif t.type == token.NAME and found_kwargs:
# Return 'foobar' of **foobar, if needed.
return t.value if needs_fix else u''
elif t.type == token.DOUBLESTAR:
# Found either '*' from **foobar.
found_kwargs = True
else:
# Never found **foobar. Return a synthetic name, if needed.
return kwargs_default if needs_fix else u'' | python | def needs_fixing(raw_params, kwargs_default=_kwargs_default_name):
u"""
Returns string with the name of the kwargs dict if the params after the first star need fixing
Otherwise returns empty string
"""
found_kwargs = False
needs_fix = False
for t in raw_params[2:]:
if t.type == token.COMMA:
# Commas are irrelevant at this stage.
continue
elif t.type == token.NAME and not found_kwargs:
# Keyword-only argument: definitely need to fix.
needs_fix = True
elif t.type == token.NAME and found_kwargs:
# Return 'foobar' of **foobar, if needed.
return t.value if needs_fix else u''
elif t.type == token.DOUBLESTAR:
# Found either '*' from **foobar.
found_kwargs = True
else:
# Never found **foobar. Return a synthetic name, if needed.
return kwargs_default if needs_fix else u'' | [
"def",
"needs_fixing",
"(",
"raw_params",
",",
"kwargs_default",
"=",
"_kwargs_default_name",
")",
":",
"found_kwargs",
"=",
"False",
"needs_fix",
"=",
"False",
"for",
"t",
"in",
"raw_params",
"[",
"2",
":",
"]",
":",
"if",
"t",
".",
"type",
"==",
"token",... | u"""
Returns string with the name of the kwargs dict if the params after the first star need fixing
Otherwise returns empty string | [
"u",
"Returns",
"string",
"with",
"the",
"name",
"of",
"the",
"kwargs",
"dict",
"if",
"the",
"params",
"after",
"the",
"first",
"star",
"need",
"fixing",
"Otherwise",
"returns",
"empty",
"string"
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libpasteurize/fixes/fix_kwargs.py#L65-L88 |
224,804 | PythonCharmers/python-future | src/past/translation/__init__.py | common_substring | def common_substring(s1, s2):
"""
Returns the longest common substring to the two strings, starting from the
left.
"""
chunks = []
path1 = splitall(s1)
path2 = splitall(s2)
for (dir1, dir2) in zip(path1, path2):
if dir1 != dir2:
break
chunks.append(dir1)
return os.path.join(*chunks) | python | def common_substring(s1, s2):
chunks = []
path1 = splitall(s1)
path2 = splitall(s2)
for (dir1, dir2) in zip(path1, path2):
if dir1 != dir2:
break
chunks.append(dir1)
return os.path.join(*chunks) | [
"def",
"common_substring",
"(",
"s1",
",",
"s2",
")",
":",
"chunks",
"=",
"[",
"]",
"path1",
"=",
"splitall",
"(",
"s1",
")",
"path2",
"=",
"splitall",
"(",
"s2",
")",
"for",
"(",
"dir1",
",",
"dir2",
")",
"in",
"zip",
"(",
"path1",
",",
"path2",... | Returns the longest common substring to the two strings, starting from the
left. | [
"Returns",
"the",
"longest",
"common",
"substring",
"to",
"the",
"two",
"strings",
"starting",
"from",
"the",
"left",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/past/translation/__init__.py#L190-L202 |
224,805 | PythonCharmers/python-future | src/past/translation/__init__.py | detect_python2 | def detect_python2(source, pathname):
"""
Returns a bool indicating whether we think the code is Py2
"""
RTs.setup_detect_python2()
try:
tree = RTs._rt_py2_detect.refactor_string(source, pathname)
except ParseError as e:
if e.msg != 'bad input' or e.value != '=':
raise
tree = RTs._rtp.refactor_string(source, pathname)
if source != str(tree)[:-1]: # remove added newline
# The above fixers made changes, so we conclude it's Python 2 code
logger.debug('Detected Python 2 code: {0}'.format(pathname))
with open('/tmp/original_code.py', 'w') as f:
f.write('### Original code (detected as py2): %s\n%s' %
(pathname, source))
with open('/tmp/py2_detection_code.py', 'w') as f:
f.write('### Code after running py3 detection (from %s)\n%s' %
(pathname, str(tree)[:-1]))
return True
else:
logger.debug('Detected Python 3 code: {0}'.format(pathname))
with open('/tmp/original_code.py', 'w') as f:
f.write('### Original code (detected as py3): %s\n%s' %
(pathname, source))
try:
os.remove('/tmp/futurize_code.py')
except OSError:
pass
return False | python | def detect_python2(source, pathname):
RTs.setup_detect_python2()
try:
tree = RTs._rt_py2_detect.refactor_string(source, pathname)
except ParseError as e:
if e.msg != 'bad input' or e.value != '=':
raise
tree = RTs._rtp.refactor_string(source, pathname)
if source != str(tree)[:-1]: # remove added newline
# The above fixers made changes, so we conclude it's Python 2 code
logger.debug('Detected Python 2 code: {0}'.format(pathname))
with open('/tmp/original_code.py', 'w') as f:
f.write('### Original code (detected as py2): %s\n%s' %
(pathname, source))
with open('/tmp/py2_detection_code.py', 'w') as f:
f.write('### Code after running py3 detection (from %s)\n%s' %
(pathname, str(tree)[:-1]))
return True
else:
logger.debug('Detected Python 3 code: {0}'.format(pathname))
with open('/tmp/original_code.py', 'w') as f:
f.write('### Original code (detected as py3): %s\n%s' %
(pathname, source))
try:
os.remove('/tmp/futurize_code.py')
except OSError:
pass
return False | [
"def",
"detect_python2",
"(",
"source",
",",
"pathname",
")",
":",
"RTs",
".",
"setup_detect_python2",
"(",
")",
"try",
":",
"tree",
"=",
"RTs",
".",
"_rt_py2_detect",
".",
"refactor_string",
"(",
"source",
",",
"pathname",
")",
"except",
"ParseError",
"as",... | Returns a bool indicating whether we think the code is Py2 | [
"Returns",
"a",
"bool",
"indicating",
"whether",
"we",
"think",
"the",
"code",
"is",
"Py2"
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/past/translation/__init__.py#L207-L238 |
224,806 | PythonCharmers/python-future | src/libpasteurize/fixes/fix_imports.py | all_patterns | def all_patterns(name):
u"""
Accepts a string and returns a pattern of possible patterns involving that name
Called by simple_mapping_to_pattern for each name in the mapping it receives.
"""
# i_ denotes an import-like node
# u_ denotes a node that appears to be a usage of the name
if u'.' in name:
name, attr = name.split(u'.', 1)
simple_name = simple_name_match % (name)
simple_attr = subname_match % (attr)
dotted_name = dotted_name_match % (simple_name, simple_attr)
i_from = from_import_match % (dotted_name)
i_from_submod = from_import_submod_match % (simple_name, simple_attr, simple_attr, simple_attr, simple_attr)
i_name = name_import_match % (dotted_name, dotted_name)
u_name = power_twoname_match % (simple_name, simple_attr)
u_subname = power_subname_match % (simple_attr)
return u' | \n'.join((i_name, i_from, i_from_submod, u_name, u_subname))
else:
simple_name = simple_name_match % (name)
i_name = name_import_match % (simple_name, simple_name)
i_from = from_import_match % (simple_name)
u_name = power_onename_match % (simple_name)
return u' | \n'.join((i_name, i_from, u_name)) | python | def all_patterns(name):
u"""
Accepts a string and returns a pattern of possible patterns involving that name
Called by simple_mapping_to_pattern for each name in the mapping it receives.
"""
# i_ denotes an import-like node
# u_ denotes a node that appears to be a usage of the name
if u'.' in name:
name, attr = name.split(u'.', 1)
simple_name = simple_name_match % (name)
simple_attr = subname_match % (attr)
dotted_name = dotted_name_match % (simple_name, simple_attr)
i_from = from_import_match % (dotted_name)
i_from_submod = from_import_submod_match % (simple_name, simple_attr, simple_attr, simple_attr, simple_attr)
i_name = name_import_match % (dotted_name, dotted_name)
u_name = power_twoname_match % (simple_name, simple_attr)
u_subname = power_subname_match % (simple_attr)
return u' | \n'.join((i_name, i_from, i_from_submod, u_name, u_subname))
else:
simple_name = simple_name_match % (name)
i_name = name_import_match % (simple_name, simple_name)
i_from = from_import_match % (simple_name)
u_name = power_onename_match % (simple_name)
return u' | \n'.join((i_name, i_from, u_name)) | [
"def",
"all_patterns",
"(",
"name",
")",
":",
"# i_ denotes an import-like node",
"# u_ denotes a node that appears to be a usage of the name",
"if",
"u'.'",
"in",
"name",
":",
"name",
",",
"attr",
"=",
"name",
".",
"split",
"(",
"u'.'",
",",
"1",
")",
"simple_name"... | u"""
Accepts a string and returns a pattern of possible patterns involving that name
Called by simple_mapping_to_pattern for each name in the mapping it receives. | [
"u",
"Accepts",
"a",
"string",
"and",
"returns",
"a",
"pattern",
"of",
"possible",
"patterns",
"involving",
"that",
"name",
"Called",
"by",
"simple_mapping_to_pattern",
"for",
"each",
"name",
"in",
"the",
"mapping",
"it",
"receives",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libpasteurize/fixes/fix_imports.py#L79-L103 |
224,807 | PythonCharmers/python-future | src/libpasteurize/fixes/feature_base.py | Features.update_mapping | def update_mapping(self):
u"""
Called every time we care about the mapping of names to features.
"""
self.mapping = dict([(f.name, f) for f in iter(self)]) | python | def update_mapping(self):
u"""
Called every time we care about the mapping of names to features.
"""
self.mapping = dict([(f.name, f) for f in iter(self)]) | [
"def",
"update_mapping",
"(",
"self",
")",
":",
"self",
".",
"mapping",
"=",
"dict",
"(",
"[",
"(",
"f",
".",
"name",
",",
"f",
")",
"for",
"f",
"in",
"iter",
"(",
"self",
")",
"]",
")"
] | u"""
Called every time we care about the mapping of names to features. | [
"u",
"Called",
"every",
"time",
"we",
"care",
"about",
"the",
"mapping",
"of",
"names",
"to",
"features",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libpasteurize/fixes/feature_base.py#L38-L42 |
224,808 | PythonCharmers/python-future | src/libpasteurize/fixes/feature_base.py | Features.PATTERN | def PATTERN(self):
u"""
Uses the mapping of names to features to return a PATTERN suitable
for using the lib2to3 patcomp.
"""
self.update_mapping()
return u" |\n".join([pattern_unformatted % (f.name, f._pattern) for f in iter(self)]) | python | def PATTERN(self):
u"""
Uses the mapping of names to features to return a PATTERN suitable
for using the lib2to3 patcomp.
"""
self.update_mapping()
return u" |\n".join([pattern_unformatted % (f.name, f._pattern) for f in iter(self)]) | [
"def",
"PATTERN",
"(",
"self",
")",
":",
"self",
".",
"update_mapping",
"(",
")",
"return",
"u\" |\\n\"",
".",
"join",
"(",
"[",
"pattern_unformatted",
"%",
"(",
"f",
".",
"name",
",",
"f",
".",
"_pattern",
")",
"for",
"f",
"in",
"iter",
"(",
"self",... | u"""
Uses the mapping of names to features to return a PATTERN suitable
for using the lib2to3 patcomp. | [
"u",
"Uses",
"the",
"mapping",
"of",
"names",
"to",
"features",
"to",
"return",
"a",
"PATTERN",
"suitable",
"for",
"using",
"the",
"lib2to3",
"patcomp",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libpasteurize/fixes/feature_base.py#L45-L51 |
224,809 | PythonCharmers/python-future | src/libfuturize/fixer_util.py | indentation | def indentation(node):
"""
Returns the indentation for this node
Iff a node is in a suite, then it has indentation.
"""
while node.parent is not None and node.parent.type != syms.suite:
node = node.parent
if node.parent is None:
return u""
# The first three children of a suite are NEWLINE, INDENT, (some other node)
# INDENT.value contains the indentation for this suite
# anything after (some other node) has the indentation as its prefix.
if node.type == token.INDENT:
return node.value
elif node.prev_sibling is not None and node.prev_sibling.type == token.INDENT:
return node.prev_sibling.value
elif node.prev_sibling is None:
return u""
else:
return node.prefix | python | def indentation(node):
while node.parent is not None and node.parent.type != syms.suite:
node = node.parent
if node.parent is None:
return u""
# The first three children of a suite are NEWLINE, INDENT, (some other node)
# INDENT.value contains the indentation for this suite
# anything after (some other node) has the indentation as its prefix.
if node.type == token.INDENT:
return node.value
elif node.prev_sibling is not None and node.prev_sibling.type == token.INDENT:
return node.prev_sibling.value
elif node.prev_sibling is None:
return u""
else:
return node.prefix | [
"def",
"indentation",
"(",
"node",
")",
":",
"while",
"node",
".",
"parent",
"is",
"not",
"None",
"and",
"node",
".",
"parent",
".",
"type",
"!=",
"syms",
".",
"suite",
":",
"node",
"=",
"node",
".",
"parent",
"if",
"node",
".",
"parent",
"is",
"No... | Returns the indentation for this node
Iff a node is in a suite, then it has indentation. | [
"Returns",
"the",
"indentation",
"for",
"this",
"node",
"Iff",
"a",
"node",
"is",
"in",
"a",
"suite",
"then",
"it",
"has",
"indentation",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libfuturize/fixer_util.py#L75-L94 |
224,810 | PythonCharmers/python-future | src/libfuturize/fixer_util.py | suitify | def suitify(parent):
"""
Turn the stuff after the first colon in parent's children
into a suite, if it wasn't already
"""
for node in parent.children:
if node.type == syms.suite:
# already in the prefered format, do nothing
return
# One-liners have no suite node, we have to fake one up
for i, node in enumerate(parent.children):
if node.type == token.COLON:
break
else:
raise ValueError(u"No class suite and no ':'!")
# Move everything into a suite node
suite = Node(syms.suite, [Newline(), Leaf(token.INDENT, indentation(node) + indentation_step(node))])
one_node = parent.children[i+1]
one_node.remove()
one_node.prefix = u''
suite.append_child(one_node)
parent.append_child(suite) | python | def suitify(parent):
for node in parent.children:
if node.type == syms.suite:
# already in the prefered format, do nothing
return
# One-liners have no suite node, we have to fake one up
for i, node in enumerate(parent.children):
if node.type == token.COLON:
break
else:
raise ValueError(u"No class suite and no ':'!")
# Move everything into a suite node
suite = Node(syms.suite, [Newline(), Leaf(token.INDENT, indentation(node) + indentation_step(node))])
one_node = parent.children[i+1]
one_node.remove()
one_node.prefix = u''
suite.append_child(one_node)
parent.append_child(suite) | [
"def",
"suitify",
"(",
"parent",
")",
":",
"for",
"node",
"in",
"parent",
".",
"children",
":",
"if",
"node",
".",
"type",
"==",
"syms",
".",
"suite",
":",
"# already in the prefered format, do nothing",
"return",
"# One-liners have no suite node, we have to fake one ... | Turn the stuff after the first colon in parent's children
into a suite, if it wasn't already | [
"Turn",
"the",
"stuff",
"after",
"the",
"first",
"colon",
"in",
"parent",
"s",
"children",
"into",
"a",
"suite",
"if",
"it",
"wasn",
"t",
"already"
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libfuturize/fixer_util.py#L112-L134 |
224,811 | PythonCharmers/python-future | src/libfuturize/fixer_util.py | is_docstring | def is_docstring(node):
"""
Returns True if the node appears to be a docstring
"""
return (node.type == syms.simple_stmt and
len(node.children) > 0 and node.children[0].type == token.STRING) | python | def is_docstring(node):
return (node.type == syms.simple_stmt and
len(node.children) > 0 and node.children[0].type == token.STRING) | [
"def",
"is_docstring",
"(",
"node",
")",
":",
"return",
"(",
"node",
".",
"type",
"==",
"syms",
".",
"simple_stmt",
"and",
"len",
"(",
"node",
".",
"children",
")",
">",
"0",
"and",
"node",
".",
"children",
"[",
"0",
"]",
".",
"type",
"==",
"token"... | Returns True if the node appears to be a docstring | [
"Returns",
"True",
"if",
"the",
"node",
"appears",
"to",
"be",
"a",
"docstring"
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libfuturize/fixer_util.py#L222-L227 |
224,812 | PythonCharmers/python-future | src/libfuturize/fixer_util.py | future_import | def future_import(feature, node):
"""
This seems to work
"""
root = find_root(node)
if does_tree_import(u"__future__", feature, node):
return
# Look for a shebang or encoding line
shebang_encoding_idx = None
for idx, node in enumerate(root.children):
# Is it a shebang or encoding line?
if is_shebang_comment(node) or is_encoding_comment(node):
shebang_encoding_idx = idx
if is_docstring(node):
# skip over docstring
continue
names = check_future_import(node)
if not names:
# not a future statement; need to insert before this
break
if feature in names:
# already imported
return
import_ = FromImport(u'__future__', [Leaf(token.NAME, feature, prefix=" ")])
if shebang_encoding_idx == 0 and idx == 0:
# If this __future__ import would go on the first line,
# detach the shebang / encoding prefix from the current first line.
# and attach it to our new __future__ import node.
import_.prefix = root.children[0].prefix
root.children[0].prefix = u''
# End the __future__ import line with a newline and add a blank line
# afterwards:
children = [import_ , Newline()]
root.insert_child(idx, Node(syms.simple_stmt, children)) | python | def future_import(feature, node):
root = find_root(node)
if does_tree_import(u"__future__", feature, node):
return
# Look for a shebang or encoding line
shebang_encoding_idx = None
for idx, node in enumerate(root.children):
# Is it a shebang or encoding line?
if is_shebang_comment(node) or is_encoding_comment(node):
shebang_encoding_idx = idx
if is_docstring(node):
# skip over docstring
continue
names = check_future_import(node)
if not names:
# not a future statement; need to insert before this
break
if feature in names:
# already imported
return
import_ = FromImport(u'__future__', [Leaf(token.NAME, feature, prefix=" ")])
if shebang_encoding_idx == 0 and idx == 0:
# If this __future__ import would go on the first line,
# detach the shebang / encoding prefix from the current first line.
# and attach it to our new __future__ import node.
import_.prefix = root.children[0].prefix
root.children[0].prefix = u''
# End the __future__ import line with a newline and add a blank line
# afterwards:
children = [import_ , Newline()]
root.insert_child(idx, Node(syms.simple_stmt, children)) | [
"def",
"future_import",
"(",
"feature",
",",
"node",
")",
":",
"root",
"=",
"find_root",
"(",
"node",
")",
"if",
"does_tree_import",
"(",
"u\"__future__\"",
",",
"feature",
",",
"node",
")",
":",
"return",
"# Look for a shebang or encoding line",
"shebang_encoding... | This seems to work | [
"This",
"seems",
"to",
"work"
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libfuturize/fixer_util.py#L230-L267 |
224,813 | PythonCharmers/python-future | src/libfuturize/fixer_util.py | parse_args | def parse_args(arglist, scheme):
u"""
Parse a list of arguments into a dict
"""
arglist = [i for i in arglist if i.type != token.COMMA]
ret_mapping = dict([(k, None) for k in scheme])
for i, arg in enumerate(arglist):
if arg.type == syms.argument and arg.children[1].type == token.EQUAL:
# argument < NAME '=' any >
slot = arg.children[0].value
ret_mapping[slot] = arg.children[2]
else:
slot = scheme[i]
ret_mapping[slot] = arg
return ret_mapping | python | def parse_args(arglist, scheme):
u"""
Parse a list of arguments into a dict
"""
arglist = [i for i in arglist if i.type != token.COMMA]
ret_mapping = dict([(k, None) for k in scheme])
for i, arg in enumerate(arglist):
if arg.type == syms.argument and arg.children[1].type == token.EQUAL:
# argument < NAME '=' any >
slot = arg.children[0].value
ret_mapping[slot] = arg.children[2]
else:
slot = scheme[i]
ret_mapping[slot] = arg
return ret_mapping | [
"def",
"parse_args",
"(",
"arglist",
",",
"scheme",
")",
":",
"arglist",
"=",
"[",
"i",
"for",
"i",
"in",
"arglist",
"if",
"i",
".",
"type",
"!=",
"token",
".",
"COMMA",
"]",
"ret_mapping",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"None",
")",
"for"... | u"""
Parse a list of arguments into a dict | [
"u",
"Parse",
"a",
"list",
"of",
"arguments",
"into",
"a",
"dict"
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libfuturize/fixer_util.py#L302-L319 |
224,814 | PythonCharmers/python-future | src/libfuturize/fixer_util.py | check_future_import | def check_future_import(node):
"""If this is a future import, return set of symbols that are imported,
else return None."""
# node should be the import statement here
savenode = node
if not (node.type == syms.simple_stmt and node.children):
return set()
node = node.children[0]
# now node is the import_from node
if not (node.type == syms.import_from and
# node.type == token.NAME and # seems to break it
hasattr(node.children[1], 'value') and
node.children[1].value == u'__future__'):
return set()
if node.children[3].type == token.LPAR:
node = node.children[4]
else:
node = node.children[3]
# now node is the import_as_name[s]
# print(python_grammar.number2symbol[node.type]) # breaks sometimes
if node.type == syms.import_as_names:
result = set()
for n in node.children:
if n.type == token.NAME:
result.add(n.value)
elif n.type == syms.import_as_name:
n = n.children[0]
assert n.type == token.NAME
result.add(n.value)
return result
elif node.type == syms.import_as_name:
node = node.children[0]
assert node.type == token.NAME
return set([node.value])
elif node.type == token.NAME:
return set([node.value])
else:
# TODO: handle brackets like this:
# from __future__ import (absolute_import, division)
assert False, "strange import: %s" % savenode | python | def check_future_import(node):
# node should be the import statement here
savenode = node
if not (node.type == syms.simple_stmt and node.children):
return set()
node = node.children[0]
# now node is the import_from node
if not (node.type == syms.import_from and
# node.type == token.NAME and # seems to break it
hasattr(node.children[1], 'value') and
node.children[1].value == u'__future__'):
return set()
if node.children[3].type == token.LPAR:
node = node.children[4]
else:
node = node.children[3]
# now node is the import_as_name[s]
# print(python_grammar.number2symbol[node.type]) # breaks sometimes
if node.type == syms.import_as_names:
result = set()
for n in node.children:
if n.type == token.NAME:
result.add(n.value)
elif n.type == syms.import_as_name:
n = n.children[0]
assert n.type == token.NAME
result.add(n.value)
return result
elif node.type == syms.import_as_name:
node = node.children[0]
assert node.type == token.NAME
return set([node.value])
elif node.type == token.NAME:
return set([node.value])
else:
# TODO: handle brackets like this:
# from __future__ import (absolute_import, division)
assert False, "strange import: %s" % savenode | [
"def",
"check_future_import",
"(",
"node",
")",
":",
"# node should be the import statement here",
"savenode",
"=",
"node",
"if",
"not",
"(",
"node",
".",
"type",
"==",
"syms",
".",
"simple_stmt",
"and",
"node",
".",
"children",
")",
":",
"return",
"set",
"(",... | If this is a future import, return set of symbols that are imported,
else return None. | [
"If",
"this",
"is",
"a",
"future",
"import",
"return",
"set",
"of",
"symbols",
"that",
"are",
"imported",
"else",
"return",
"None",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libfuturize/fixer_util.py#L432-L471 |
224,815 | PythonCharmers/python-future | src/future/backports/datetime.py | date.replace | def replace(self, year=None, month=None, day=None):
"""Return a new date with new values for the specified fields."""
if year is None:
year = self._year
if month is None:
month = self._month
if day is None:
day = self._day
_check_date_fields(year, month, day)
return date(year, month, day) | python | def replace(self, year=None, month=None, day=None):
if year is None:
year = self._year
if month is None:
month = self._month
if day is None:
day = self._day
_check_date_fields(year, month, day)
return date(year, month, day) | [
"def",
"replace",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
")",
":",
"if",
"year",
"is",
"None",
":",
"year",
"=",
"self",
".",
"_year",
"if",
"month",
"is",
"None",
":",
"month",
"=",
"self",
"... | Return a new date with new values for the specified fields. | [
"Return",
"a",
"new",
"date",
"with",
"new",
"values",
"for",
"the",
"specified",
"fields",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/datetime.py#L784-L793 |
224,816 | PythonCharmers/python-future | src/future/backports/datetime.py | time.replace | def replace(self, hour=None, minute=None, second=None, microsecond=None,
tzinfo=True):
"""Return a new time with new values for the specified fields."""
if hour is None:
hour = self.hour
if minute is None:
minute = self.minute
if second is None:
second = self.second
if microsecond is None:
microsecond = self.microsecond
if tzinfo is True:
tzinfo = self.tzinfo
_check_time_fields(hour, minute, second, microsecond)
_check_tzinfo_arg(tzinfo)
return time(hour, minute, second, microsecond, tzinfo) | python | def replace(self, hour=None, minute=None, second=None, microsecond=None,
tzinfo=True):
if hour is None:
hour = self.hour
if minute is None:
minute = self.minute
if second is None:
second = self.second
if microsecond is None:
microsecond = self.microsecond
if tzinfo is True:
tzinfo = self.tzinfo
_check_time_fields(hour, minute, second, microsecond)
_check_tzinfo_arg(tzinfo)
return time(hour, minute, second, microsecond, tzinfo) | [
"def",
"replace",
"(",
"self",
",",
"hour",
"=",
"None",
",",
"minute",
"=",
"None",
",",
"second",
"=",
"None",
",",
"microsecond",
"=",
"None",
",",
"tzinfo",
"=",
"True",
")",
":",
"if",
"hour",
"is",
"None",
":",
"hour",
"=",
"self",
".",
"ho... | Return a new time with new values for the specified fields. | [
"Return",
"a",
"new",
"time",
"with",
"new",
"values",
"for",
"the",
"specified",
"fields",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/datetime.py#L1245-L1260 |
224,817 | PythonCharmers/python-future | src/future/backports/datetime.py | datetime.timestamp | def timestamp(self):
"Return POSIX timestamp as float"
if self._tzinfo is None:
return _time.mktime((self.year, self.month, self.day,
self.hour, self.minute, self.second,
-1, -1, -1)) + self.microsecond / 1e6
else:
return (self - _EPOCH).total_seconds() | python | def timestamp(self):
"Return POSIX timestamp as float"
if self._tzinfo is None:
return _time.mktime((self.year, self.month, self.day,
self.hour, self.minute, self.second,
-1, -1, -1)) + self.microsecond / 1e6
else:
return (self - _EPOCH).total_seconds() | [
"def",
"timestamp",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tzinfo",
"is",
"None",
":",
"return",
"_time",
".",
"mktime",
"(",
"(",
"self",
".",
"year",
",",
"self",
".",
"month",
",",
"self",
".",
"day",
",",
"self",
".",
"hour",
",",
"self"... | Return POSIX timestamp as float | [
"Return",
"POSIX",
"timestamp",
"as",
"float"
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/datetime.py#L1439-L1446 |
224,818 | PythonCharmers/python-future | src/future/backports/datetime.py | datetime.replace | def replace(self, year=None, month=None, day=None, hour=None,
minute=None, second=None, microsecond=None, tzinfo=True):
"""Return a new datetime with new values for the specified fields."""
if year is None:
year = self.year
if month is None:
month = self.month
if day is None:
day = self.day
if hour is None:
hour = self.hour
if minute is None:
minute = self.minute
if second is None:
second = self.second
if microsecond is None:
microsecond = self.microsecond
if tzinfo is True:
tzinfo = self.tzinfo
_check_date_fields(year, month, day)
_check_time_fields(hour, minute, second, microsecond)
_check_tzinfo_arg(tzinfo)
return datetime(year, month, day, hour, minute, second,
microsecond, tzinfo) | python | def replace(self, year=None, month=None, day=None, hour=None,
minute=None, second=None, microsecond=None, tzinfo=True):
if year is None:
year = self.year
if month is None:
month = self.month
if day is None:
day = self.day
if hour is None:
hour = self.hour
if minute is None:
minute = self.minute
if second is None:
second = self.second
if microsecond is None:
microsecond = self.microsecond
if tzinfo is True:
tzinfo = self.tzinfo
_check_date_fields(year, month, day)
_check_time_fields(hour, minute, second, microsecond)
_check_tzinfo_arg(tzinfo)
return datetime(year, month, day, hour, minute, second,
microsecond, tzinfo) | [
"def",
"replace",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
",",
"hour",
"=",
"None",
",",
"minute",
"=",
"None",
",",
"second",
"=",
"None",
",",
"microsecond",
"=",
"None",
",",
"tzinfo",
"=",
"T... | Return a new datetime with new values for the specified fields. | [
"Return",
"a",
"new",
"datetime",
"with",
"new",
"values",
"for",
"the",
"specified",
"fields",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/datetime.py#L1470-L1493 |
224,819 | PythonCharmers/python-future | src/future/backports/datetime.py | datetime.isoformat | def isoformat(self, sep='T'):
"""Return the time formatted according to ISO.
This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
self.microsecond == 0.
If self.tzinfo is not None, the UTC offset is also attached, giving
'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
Optional argument sep specifies the separator between date and
time, default 'T'.
"""
s = ("%04d-%02d-%02d%c" % (self._year, self._month, self._day,
sep) +
_format_time(self._hour, self._minute, self._second,
self._microsecond))
off = self.utcoffset()
if off is not None:
if off.days < 0:
sign = "-"
off = -off
else:
sign = "+"
hh, mm = divmod(off, timedelta(hours=1))
assert not mm % timedelta(minutes=1), "whole minute"
mm //= timedelta(minutes=1)
s += "%s%02d:%02d" % (sign, hh, mm)
return s | python | def isoformat(self, sep='T'):
s = ("%04d-%02d-%02d%c" % (self._year, self._month, self._day,
sep) +
_format_time(self._hour, self._minute, self._second,
self._microsecond))
off = self.utcoffset()
if off is not None:
if off.days < 0:
sign = "-"
off = -off
else:
sign = "+"
hh, mm = divmod(off, timedelta(hours=1))
assert not mm % timedelta(minutes=1), "whole minute"
mm //= timedelta(minutes=1)
s += "%s%02d:%02d" % (sign, hh, mm)
return s | [
"def",
"isoformat",
"(",
"self",
",",
"sep",
"=",
"'T'",
")",
":",
"s",
"=",
"(",
"\"%04d-%02d-%02d%c\"",
"%",
"(",
"self",
".",
"_year",
",",
"self",
".",
"_month",
",",
"self",
".",
"_day",
",",
"sep",
")",
"+",
"_format_time",
"(",
"self",
".",
... | Return the time formatted according to ISO.
This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
self.microsecond == 0.
If self.tzinfo is not None, the UTC offset is also attached, giving
'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
Optional argument sep specifies the separator between date and
time, default 'T'. | [
"Return",
"the",
"time",
"formatted",
"according",
"to",
"ISO",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/datetime.py#L1551-L1578 |
224,820 | PythonCharmers/python-future | src/future/backports/email/parser.py | Parser.parsestr | def parsestr(self, text, headersonly=False):
"""Create a message structure from a string.
Returns the root of the message structure. Optional headersonly is a
flag specifying whether to stop parsing after reading the headers or
not. The default is False, meaning it parses the entire contents of
the file.
"""
return self.parse(StringIO(text), headersonly=headersonly) | python | def parsestr(self, text, headersonly=False):
return self.parse(StringIO(text), headersonly=headersonly) | [
"def",
"parsestr",
"(",
"self",
",",
"text",
",",
"headersonly",
"=",
"False",
")",
":",
"return",
"self",
".",
"parse",
"(",
"StringIO",
"(",
"text",
")",
",",
"headersonly",
"=",
"headersonly",
")"
] | Create a message structure from a string.
Returns the root of the message structure. Optional headersonly is a
flag specifying whether to stop parsing after reading the headers or
not. The default is False, meaning it parses the entire contents of
the file. | [
"Create",
"a",
"message",
"structure",
"from",
"a",
"string",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/parser.py#L65-L73 |
224,821 | PythonCharmers/python-future | src/future/backports/email/parser.py | BytesParser.parse | def parse(self, fp, headersonly=False):
"""Create a message structure from the data in a binary file.
Reads all the data from the file and returns the root of the message
structure. Optional headersonly is a flag specifying whether to stop
parsing after reading the headers or not. The default is False,
meaning it parses the entire contents of the file.
"""
fp = TextIOWrapper(fp, encoding='ascii', errors='surrogateescape')
with fp:
return self.parser.parse(fp, headersonly) | python | def parse(self, fp, headersonly=False):
fp = TextIOWrapper(fp, encoding='ascii', errors='surrogateescape')
with fp:
return self.parser.parse(fp, headersonly) | [
"def",
"parse",
"(",
"self",
",",
"fp",
",",
"headersonly",
"=",
"False",
")",
":",
"fp",
"=",
"TextIOWrapper",
"(",
"fp",
",",
"encoding",
"=",
"'ascii'",
",",
"errors",
"=",
"'surrogateescape'",
")",
"with",
"fp",
":",
"return",
"self",
".",
"parser"... | Create a message structure from the data in a binary file.
Reads all the data from the file and returns the root of the message
structure. Optional headersonly is a flag specifying whether to stop
parsing after reading the headers or not. The default is False,
meaning it parses the entire contents of the file. | [
"Create",
"a",
"message",
"structure",
"from",
"the",
"data",
"in",
"a",
"binary",
"file",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/parser.py#L105-L115 |
224,822 | PythonCharmers/python-future | src/future/backports/email/parser.py | BytesParser.parsebytes | def parsebytes(self, text, headersonly=False):
"""Create a message structure from a byte string.
Returns the root of the message structure. Optional headersonly is a
flag specifying whether to stop parsing after reading the headers or
not. The default is False, meaning it parses the entire contents of
the file.
"""
text = text.decode('ASCII', errors='surrogateescape')
return self.parser.parsestr(text, headersonly) | python | def parsebytes(self, text, headersonly=False):
text = text.decode('ASCII', errors='surrogateescape')
return self.parser.parsestr(text, headersonly) | [
"def",
"parsebytes",
"(",
"self",
",",
"text",
",",
"headersonly",
"=",
"False",
")",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"'ASCII'",
",",
"errors",
"=",
"'surrogateescape'",
")",
"return",
"self",
".",
"parser",
".",
"parsestr",
"(",
"text",
... | Create a message structure from a byte string.
Returns the root of the message structure. Optional headersonly is a
flag specifying whether to stop parsing after reading the headers or
not. The default is False, meaning it parses the entire contents of
the file. | [
"Create",
"a",
"message",
"structure",
"from",
"a",
"byte",
"string",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/parser.py#L118-L127 |
224,823 | PythonCharmers/python-future | src/future/backports/email/__init__.py | message_from_string | def message_from_string(s, *args, **kws):
"""Parse a string into a Message object model.
Optional _class and strict are passed to the Parser constructor.
"""
from future.backports.email.parser import Parser
return Parser(*args, **kws).parsestr(s) | python | def message_from_string(s, *args, **kws):
from future.backports.email.parser import Parser
return Parser(*args, **kws).parsestr(s) | [
"def",
"message_from_string",
"(",
"s",
",",
"*",
"args",
",",
"*",
"*",
"kws",
")",
":",
"from",
"future",
".",
"backports",
".",
"email",
".",
"parser",
"import",
"Parser",
"return",
"Parser",
"(",
"*",
"args",
",",
"*",
"*",
"kws",
")",
".",
"pa... | Parse a string into a Message object model.
Optional _class and strict are passed to the Parser constructor. | [
"Parse",
"a",
"string",
"into",
"a",
"Message",
"object",
"model",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/__init__.py#L48-L54 |
224,824 | PythonCharmers/python-future | src/future/backports/email/__init__.py | message_from_bytes | def message_from_bytes(s, *args, **kws):
"""Parse a bytes string into a Message object model.
Optional _class and strict are passed to the Parser constructor.
"""
from future.backports.email.parser import BytesParser
return BytesParser(*args, **kws).parsebytes(s) | python | def message_from_bytes(s, *args, **kws):
from future.backports.email.parser import BytesParser
return BytesParser(*args, **kws).parsebytes(s) | [
"def",
"message_from_bytes",
"(",
"s",
",",
"*",
"args",
",",
"*",
"*",
"kws",
")",
":",
"from",
"future",
".",
"backports",
".",
"email",
".",
"parser",
"import",
"BytesParser",
"return",
"BytesParser",
"(",
"*",
"args",
",",
"*",
"*",
"kws",
")",
"... | Parse a bytes string into a Message object model.
Optional _class and strict are passed to the Parser constructor. | [
"Parse",
"a",
"bytes",
"string",
"into",
"a",
"Message",
"object",
"model",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/__init__.py#L56-L62 |
224,825 | PythonCharmers/python-future | src/future/backports/email/__init__.py | message_from_file | def message_from_file(fp, *args, **kws):
"""Read a file and parse its contents into a Message object model.
Optional _class and strict are passed to the Parser constructor.
"""
from future.backports.email.parser import Parser
return Parser(*args, **kws).parse(fp) | python | def message_from_file(fp, *args, **kws):
from future.backports.email.parser import Parser
return Parser(*args, **kws).parse(fp) | [
"def",
"message_from_file",
"(",
"fp",
",",
"*",
"args",
",",
"*",
"*",
"kws",
")",
":",
"from",
"future",
".",
"backports",
".",
"email",
".",
"parser",
"import",
"Parser",
"return",
"Parser",
"(",
"*",
"args",
",",
"*",
"*",
"kws",
")",
".",
"par... | Read a file and parse its contents into a Message object model.
Optional _class and strict are passed to the Parser constructor. | [
"Read",
"a",
"file",
"and",
"parse",
"its",
"contents",
"into",
"a",
"Message",
"object",
"model",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/__init__.py#L64-L70 |
224,826 | PythonCharmers/python-future | src/future/backports/email/__init__.py | message_from_binary_file | def message_from_binary_file(fp, *args, **kws):
"""Read a binary file and parse its contents into a Message object model.
Optional _class and strict are passed to the Parser constructor.
"""
from future.backports.email.parser import BytesParser
return BytesParser(*args, **kws).parse(fp) | python | def message_from_binary_file(fp, *args, **kws):
from future.backports.email.parser import BytesParser
return BytesParser(*args, **kws).parse(fp) | [
"def",
"message_from_binary_file",
"(",
"fp",
",",
"*",
"args",
",",
"*",
"*",
"kws",
")",
":",
"from",
"future",
".",
"backports",
".",
"email",
".",
"parser",
"import",
"BytesParser",
"return",
"BytesParser",
"(",
"*",
"args",
",",
"*",
"*",
"kws",
"... | Read a binary file and parse its contents into a Message object model.
Optional _class and strict are passed to the Parser constructor. | [
"Read",
"a",
"binary",
"file",
"and",
"parse",
"its",
"contents",
"into",
"a",
"Message",
"object",
"model",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/__init__.py#L72-L78 |
224,827 | PythonCharmers/python-future | src/future/backports/http/client.py | HTTPResponse._safe_read | def _safe_read(self, amt):
"""Read the number of bytes requested, compensating for partial reads.
Normally, we have a blocking socket, but a read() can be interrupted
by a signal (resulting in a partial read).
Note that we cannot distinguish between EOF and an interrupt when zero
bytes have been read. IncompleteRead() will be raised in this
situation.
This function should be used when <amt> bytes "should" be present for
reading. If the bytes are truly not available (due to EOF), then the
IncompleteRead exception can be used to detect the problem.
"""
s = []
while amt > 0:
chunk = self.fp.read(min(amt, MAXAMOUNT))
if not chunk:
raise IncompleteRead(bytes(b'').join(s), amt)
s.append(chunk)
amt -= len(chunk)
return bytes(b"").join(s) | python | def _safe_read(self, amt):
s = []
while amt > 0:
chunk = self.fp.read(min(amt, MAXAMOUNT))
if not chunk:
raise IncompleteRead(bytes(b'').join(s), amt)
s.append(chunk)
amt -= len(chunk)
return bytes(b"").join(s) | [
"def",
"_safe_read",
"(",
"self",
",",
"amt",
")",
":",
"s",
"=",
"[",
"]",
"while",
"amt",
">",
"0",
":",
"chunk",
"=",
"self",
".",
"fp",
".",
"read",
"(",
"min",
"(",
"amt",
",",
"MAXAMOUNT",
")",
")",
"if",
"not",
"chunk",
":",
"raise",
"... | Read the number of bytes requested, compensating for partial reads.
Normally, we have a blocking socket, but a read() can be interrupted
by a signal (resulting in a partial read).
Note that we cannot distinguish between EOF and an interrupt when zero
bytes have been read. IncompleteRead() will be raised in this
situation.
This function should be used when <amt> bytes "should" be present for
reading. If the bytes are truly not available (due to EOF), then the
IncompleteRead exception can be used to detect the problem. | [
"Read",
"the",
"number",
"of",
"bytes",
"requested",
"compensating",
"for",
"partial",
"reads",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/client.py#L669-L690 |
224,828 | PythonCharmers/python-future | src/future/backports/http/client.py | HTTPResponse._safe_readinto | def _safe_readinto(self, b):
"""Same as _safe_read, but for reading into a buffer."""
total_bytes = 0
mvb = memoryview(b)
while total_bytes < len(b):
if MAXAMOUNT < len(mvb):
temp_mvb = mvb[0:MAXAMOUNT]
n = self.fp.readinto(temp_mvb)
else:
n = self.fp.readinto(mvb)
if not n:
raise IncompleteRead(bytes(mvb[0:total_bytes]), len(b))
mvb = mvb[n:]
total_bytes += n
return total_bytes | python | def _safe_readinto(self, b):
total_bytes = 0
mvb = memoryview(b)
while total_bytes < len(b):
if MAXAMOUNT < len(mvb):
temp_mvb = mvb[0:MAXAMOUNT]
n = self.fp.readinto(temp_mvb)
else:
n = self.fp.readinto(mvb)
if not n:
raise IncompleteRead(bytes(mvb[0:total_bytes]), len(b))
mvb = mvb[n:]
total_bytes += n
return total_bytes | [
"def",
"_safe_readinto",
"(",
"self",
",",
"b",
")",
":",
"total_bytes",
"=",
"0",
"mvb",
"=",
"memoryview",
"(",
"b",
")",
"while",
"total_bytes",
"<",
"len",
"(",
"b",
")",
":",
"if",
"MAXAMOUNT",
"<",
"len",
"(",
"mvb",
")",
":",
"temp_mvb",
"="... | Same as _safe_read, but for reading into a buffer. | [
"Same",
"as",
"_safe_read",
"but",
"for",
"reading",
"into",
"a",
"buffer",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/client.py#L692-L706 |
224,829 | PythonCharmers/python-future | src/future/backports/http/client.py | HTTPConnection.set_tunnel | def set_tunnel(self, host, port=None, headers=None):
""" Sets up the host and the port for the HTTP CONNECT Tunnelling.
The headers argument should be a mapping of extra HTTP headers
to send with the CONNECT request.
"""
self._tunnel_host = host
self._tunnel_port = port
if headers:
self._tunnel_headers = headers
else:
self._tunnel_headers.clear() | python | def set_tunnel(self, host, port=None, headers=None):
self._tunnel_host = host
self._tunnel_port = port
if headers:
self._tunnel_headers = headers
else:
self._tunnel_headers.clear() | [
"def",
"set_tunnel",
"(",
"self",
",",
"host",
",",
"port",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"self",
".",
"_tunnel_host",
"=",
"host",
"self",
".",
"_tunnel_port",
"=",
"port",
"if",
"headers",
":",
"self",
".",
"_tunnel_headers",
"=... | Sets up the host and the port for the HTTP CONNECT Tunnelling.
The headers argument should be a mapping of extra HTTP headers
to send with the CONNECT request. | [
"Sets",
"up",
"the",
"host",
"and",
"the",
"port",
"for",
"the",
"HTTP",
"CONNECT",
"Tunnelling",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/client.py#L771-L782 |
224,830 | PythonCharmers/python-future | src/future/backports/http/client.py | HTTPConnection.close | def close(self):
"""Close the connection to the HTTP server."""
if self.sock:
self.sock.close() # close it manually... there may be other refs
self.sock = None
if self.__response:
self.__response.close()
self.__response = None
self.__state = _CS_IDLE | python | def close(self):
if self.sock:
self.sock.close() # close it manually... there may be other refs
self.sock = None
if self.__response:
self.__response.close()
self.__response = None
self.__state = _CS_IDLE | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"sock",
":",
"self",
".",
"sock",
".",
"close",
"(",
")",
"# close it manually... there may be other refs",
"self",
".",
"sock",
"=",
"None",
"if",
"self",
".",
"__response",
":",
"self",
".",
"__... | Close the connection to the HTTP server. | [
"Close",
"the",
"connection",
"to",
"the",
"HTTP",
"server",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/client.py#L842-L850 |
224,831 | PythonCharmers/python-future | src/future/backports/http/client.py | HTTPConnection._send_output | def _send_output(self, message_body=None):
"""Send the currently buffered request and clear the buffer.
Appends an extra \\r\\n to the buffer.
A message_body may be specified, to be appended to the request.
"""
self._buffer.extend((bytes(b""), bytes(b"")))
msg = bytes(b"\r\n").join(self._buffer)
del self._buffer[:]
# If msg and message_body are sent in a single send() call,
# it will avoid performance problems caused by the interaction
# between delayed ack and the Nagle algorithm.
if isinstance(message_body, bytes):
msg += message_body
message_body = None
self.send(msg)
if message_body is not None:
# message_body was not a string (i.e. it is a file), and
# we must run the risk of Nagle.
self.send(message_body) | python | def _send_output(self, message_body=None):
self._buffer.extend((bytes(b""), bytes(b"")))
msg = bytes(b"\r\n").join(self._buffer)
del self._buffer[:]
# If msg and message_body are sent in a single send() call,
# it will avoid performance problems caused by the interaction
# between delayed ack and the Nagle algorithm.
if isinstance(message_body, bytes):
msg += message_body
message_body = None
self.send(msg)
if message_body is not None:
# message_body was not a string (i.e. it is a file), and
# we must run the risk of Nagle.
self.send(message_body) | [
"def",
"_send_output",
"(",
"self",
",",
"message_body",
"=",
"None",
")",
":",
"self",
".",
"_buffer",
".",
"extend",
"(",
"(",
"bytes",
"(",
"b\"\"",
")",
",",
"bytes",
"(",
"b\"\"",
")",
")",
")",
"msg",
"=",
"bytes",
"(",
"b\"\\r\\n\"",
")",
".... | Send the currently buffered request and clear the buffer.
Appends an extra \\r\\n to the buffer.
A message_body may be specified, to be appended to the request. | [
"Send",
"the",
"currently",
"buffered",
"request",
"and",
"clear",
"the",
"buffer",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/client.py#L909-L928 |
224,832 | PythonCharmers/python-future | src/future/backports/http/client.py | HTTPConnection.putheader | def putheader(self, header, *values):
"""Send a request header line to the server.
For example: h.putheader('Accept', 'text/html')
"""
if self.__state != _CS_REQ_STARTED:
raise CannotSendHeader()
if hasattr(header, 'encode'):
header = header.encode('ascii')
values = list(values)
for i, one_value in enumerate(values):
if hasattr(one_value, 'encode'):
values[i] = one_value.encode('latin-1')
elif isinstance(one_value, int):
values[i] = str(one_value).encode('ascii')
value = bytes(b'\r\n\t').join(values)
header = header + bytes(b': ') + value
self._output(header) | python | def putheader(self, header, *values):
if self.__state != _CS_REQ_STARTED:
raise CannotSendHeader()
if hasattr(header, 'encode'):
header = header.encode('ascii')
values = list(values)
for i, one_value in enumerate(values):
if hasattr(one_value, 'encode'):
values[i] = one_value.encode('latin-1')
elif isinstance(one_value, int):
values[i] = str(one_value).encode('ascii')
value = bytes(b'\r\n\t').join(values)
header = header + bytes(b': ') + value
self._output(header) | [
"def",
"putheader",
"(",
"self",
",",
"header",
",",
"*",
"values",
")",
":",
"if",
"self",
".",
"__state",
"!=",
"_CS_REQ_STARTED",
":",
"raise",
"CannotSendHeader",
"(",
")",
"if",
"hasattr",
"(",
"header",
",",
"'encode'",
")",
":",
"header",
"=",
"... | Send a request header line to the server.
For example: h.putheader('Accept', 'text/html') | [
"Send",
"a",
"request",
"header",
"line",
"to",
"the",
"server",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/client.py#L1046-L1064 |
224,833 | PythonCharmers/python-future | src/future/backports/http/client.py | HTTPConnection.endheaders | def endheaders(self, message_body=None):
"""Indicate that the last header line has been sent to the server.
This method sends the request to the server. The optional message_body
argument can be used to pass a message body associated with the
request. The message body will be sent in the same packet as the
message headers if it is a string, otherwise it is sent as a separate
packet.
"""
if self.__state == _CS_REQ_STARTED:
self.__state = _CS_REQ_SENT
else:
raise CannotSendHeader()
self._send_output(message_body) | python | def endheaders(self, message_body=None):
if self.__state == _CS_REQ_STARTED:
self.__state = _CS_REQ_SENT
else:
raise CannotSendHeader()
self._send_output(message_body) | [
"def",
"endheaders",
"(",
"self",
",",
"message_body",
"=",
"None",
")",
":",
"if",
"self",
".",
"__state",
"==",
"_CS_REQ_STARTED",
":",
"self",
".",
"__state",
"=",
"_CS_REQ_SENT",
"else",
":",
"raise",
"CannotSendHeader",
"(",
")",
"self",
".",
"_send_o... | Indicate that the last header line has been sent to the server.
This method sends the request to the server. The optional message_body
argument can be used to pass a message body associated with the
request. The message body will be sent in the same packet as the
message headers if it is a string, otherwise it is sent as a separate
packet. | [
"Indicate",
"that",
"the",
"last",
"header",
"line",
"has",
"been",
"sent",
"to",
"the",
"server",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/client.py#L1066-L1079 |
224,834 | PythonCharmers/python-future | src/future/backports/http/client.py | HTTPConnection.request | def request(self, method, url, body=None, headers={}):
"""Send a complete request to the server."""
self._send_request(method, url, body, headers) | python | def request(self, method, url, body=None, headers={}):
self._send_request(method, url, body, headers) | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"{",
"}",
")",
":",
"self",
".",
"_send_request",
"(",
"method",
",",
"url",
",",
"body",
",",
"headers",
")"
] | Send a complete request to the server. | [
"Send",
"a",
"complete",
"request",
"to",
"the",
"server",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/client.py#L1081-L1083 |
224,835 | PythonCharmers/python-future | src/future/backports/http/client.py | HTTPConnection.getresponse | def getresponse(self):
"""Get the response from the server.
If the HTTPConnection is in the correct state, returns an
instance of HTTPResponse or of whatever object is returned by
class the response_class variable.
If a request has not been sent or if a previous response has
not be handled, ResponseNotReady is raised. If the HTTP
response indicates that the connection should be closed, then
it will be closed before the response is returned. When the
connection is closed, the underlying socket is closed.
"""
# if a prior response has been completed, then forget about it.
if self.__response and self.__response.isclosed():
self.__response = None
# if a prior response exists, then it must be completed (otherwise, we
# cannot read this response's header to determine the connection-close
# behavior)
#
# note: if a prior response existed, but was connection-close, then the
# socket and response were made independent of this HTTPConnection
# object since a new request requires that we open a whole new
# connection
#
# this means the prior response had one of two states:
# 1) will_close: this connection was reset and the prior socket and
# response operate independently
# 2) persistent: the response was retained and we await its
# isclosed() status to become true.
#
if self.__state != _CS_REQ_SENT or self.__response:
raise ResponseNotReady(self.__state)
if self.debuglevel > 0:
response = self.response_class(self.sock, self.debuglevel,
method=self._method)
else:
response = self.response_class(self.sock, method=self._method)
response.begin()
assert response.will_close != _UNKNOWN
self.__state = _CS_IDLE
if response.will_close:
# this effectively passes the connection to the response
self.close()
else:
# remember this, so we can tell when it is complete
self.__response = response
return response | python | def getresponse(self):
# if a prior response has been completed, then forget about it.
if self.__response and self.__response.isclosed():
self.__response = None
# if a prior response exists, then it must be completed (otherwise, we
# cannot read this response's header to determine the connection-close
# behavior)
#
# note: if a prior response existed, but was connection-close, then the
# socket and response were made independent of this HTTPConnection
# object since a new request requires that we open a whole new
# connection
#
# this means the prior response had one of two states:
# 1) will_close: this connection was reset and the prior socket and
# response operate independently
# 2) persistent: the response was retained and we await its
# isclosed() status to become true.
#
if self.__state != _CS_REQ_SENT or self.__response:
raise ResponseNotReady(self.__state)
if self.debuglevel > 0:
response = self.response_class(self.sock, self.debuglevel,
method=self._method)
else:
response = self.response_class(self.sock, method=self._method)
response.begin()
assert response.will_close != _UNKNOWN
self.__state = _CS_IDLE
if response.will_close:
# this effectively passes the connection to the response
self.close()
else:
# remember this, so we can tell when it is complete
self.__response = response
return response | [
"def",
"getresponse",
"(",
"self",
")",
":",
"# if a prior response has been completed, then forget about it.",
"if",
"self",
".",
"__response",
"and",
"self",
".",
"__response",
".",
"isclosed",
"(",
")",
":",
"self",
".",
"__response",
"=",
"None",
"# if a prior r... | Get the response from the server.
If the HTTPConnection is in the correct state, returns an
instance of HTTPResponse or of whatever object is returned by
class the response_class variable.
If a request has not been sent or if a previous response has
not be handled, ResponseNotReady is raised. If the HTTP
response indicates that the connection should be closed, then
it will be closed before the response is returned. When the
connection is closed, the underlying socket is closed. | [
"Get",
"the",
"response",
"from",
"the",
"server",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/client.py#L1123-L1176 |
224,836 | PythonCharmers/python-future | src/future/backports/email/_header_value_parser.py | _validate_xtext | def _validate_xtext(xtext):
"""If input token contains ASCII non-printables, register a defect."""
non_printables = _non_printable_finder(xtext)
if non_printables:
xtext.defects.append(errors.NonPrintableDefect(non_printables))
if utils._has_surrogates(xtext):
xtext.defects.append(errors.UndecodableBytesDefect(
"Non-ASCII characters found in header token")) | python | def _validate_xtext(xtext):
non_printables = _non_printable_finder(xtext)
if non_printables:
xtext.defects.append(errors.NonPrintableDefect(non_printables))
if utils._has_surrogates(xtext):
xtext.defects.append(errors.UndecodableBytesDefect(
"Non-ASCII characters found in header token")) | [
"def",
"_validate_xtext",
"(",
"xtext",
")",
":",
"non_printables",
"=",
"_non_printable_finder",
"(",
"xtext",
")",
"if",
"non_printables",
":",
"xtext",
".",
"defects",
".",
"append",
"(",
"errors",
".",
"NonPrintableDefect",
"(",
"non_printables",
")",
")",
... | If input token contains ASCII non-printables, register a defect. | [
"If",
"input",
"token",
"contains",
"ASCII",
"non",
"-",
"printables",
"register",
"a",
"defect",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_header_value_parser.py#L1359-L1367 |
224,837 | PythonCharmers/python-future | src/future/backports/email/_header_value_parser.py | _decode_ew_run | def _decode_ew_run(value):
""" Decode a run of RFC2047 encoded words.
_decode_ew_run(value) -> (text, value, defects)
Scans the supplied value for a run of tokens that look like they are RFC
2047 encoded words, decodes those words into text according to RFC 2047
rules (whitespace between encoded words is discarded), and returns the text
and the remaining value (including any leading whitespace on the remaining
value), as well as a list of any defects encountered while decoding. The
input value may not have any leading whitespace.
"""
res = []
defects = []
last_ws = ''
while value:
try:
tok, ws, value = _wsp_splitter(value, 1)
except ValueError:
tok, ws, value = value, '', ''
if not (tok.startswith('=?') and tok.endswith('?=')):
return ''.join(res), last_ws + tok + ws + value, defects
text, charset, lang, new_defects = _ew.decode(tok)
res.append(text)
defects.extend(new_defects)
last_ws = ws
return ''.join(res), last_ws, defects | python | def _decode_ew_run(value):
res = []
defects = []
last_ws = ''
while value:
try:
tok, ws, value = _wsp_splitter(value, 1)
except ValueError:
tok, ws, value = value, '', ''
if not (tok.startswith('=?') and tok.endswith('?=')):
return ''.join(res), last_ws + tok + ws + value, defects
text, charset, lang, new_defects = _ew.decode(tok)
res.append(text)
defects.extend(new_defects)
last_ws = ws
return ''.join(res), last_ws, defects | [
"def",
"_decode_ew_run",
"(",
"value",
")",
":",
"res",
"=",
"[",
"]",
"defects",
"=",
"[",
"]",
"last_ws",
"=",
"''",
"while",
"value",
":",
"try",
":",
"tok",
",",
"ws",
",",
"value",
"=",
"_wsp_splitter",
"(",
"value",
",",
"1",
")",
"except",
... | Decode a run of RFC2047 encoded words.
_decode_ew_run(value) -> (text, value, defects)
Scans the supplied value for a run of tokens that look like they are RFC
2047 encoded words, decodes those words into text according to RFC 2047
rules (whitespace between encoded words is discarded), and returns the text
and the remaining value (including any leading whitespace on the remaining
value), as well as a list of any defects encountered while decoding. The
input value may not have any leading whitespace. | [
"Decode",
"a",
"run",
"of",
"RFC2047",
"encoded",
"words",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_header_value_parser.py#L1400-L1427 |
224,838 | PythonCharmers/python-future | src/future/backports/email/_header_value_parser.py | get_encoded_word | def get_encoded_word(value):
""" encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
"""
ew = EncodedWord()
if not value.startswith('=?'):
raise errors.HeaderParseError(
"expected encoded word but found {}".format(value))
_3to2list1 = list(value[2:].split('?=', 1))
tok, remainder, = _3to2list1[:1] + [_3to2list1[1:]]
if tok == value[2:]:
raise errors.HeaderParseError(
"expected encoded word but found {}".format(value))
remstr = ''.join(remainder)
if remstr[:2].isdigit():
_3to2list3 = list(remstr.split('?=', 1))
rest, remainder, = _3to2list3[:1] + [_3to2list3[1:]]
tok = tok + '?=' + rest
if len(tok.split()) > 1:
ew.defects.append(errors.InvalidHeaderDefect(
"whitespace inside encoded word"))
ew.cte = value
value = ''.join(remainder)
try:
text, charset, lang, defects = _ew.decode('=?' + tok + '?=')
except ValueError:
raise errors.HeaderParseError(
"encoded word format invalid: '{}'".format(ew.cte))
ew.charset = charset
ew.lang = lang
ew.defects.extend(defects)
while text:
if text[0] in WSP:
token, text = get_fws(text)
ew.append(token)
continue
_3to2list5 = list(_wsp_splitter(text, 1))
chars, remainder, = _3to2list5[:1] + [_3to2list5[1:]]
vtext = ValueTerminal(chars, 'vtext')
_validate_xtext(vtext)
ew.append(vtext)
text = ''.join(remainder)
return ew, value | python | def get_encoded_word(value):
ew = EncodedWord()
if not value.startswith('=?'):
raise errors.HeaderParseError(
"expected encoded word but found {}".format(value))
_3to2list1 = list(value[2:].split('?=', 1))
tok, remainder, = _3to2list1[:1] + [_3to2list1[1:]]
if tok == value[2:]:
raise errors.HeaderParseError(
"expected encoded word but found {}".format(value))
remstr = ''.join(remainder)
if remstr[:2].isdigit():
_3to2list3 = list(remstr.split('?=', 1))
rest, remainder, = _3to2list3[:1] + [_3to2list3[1:]]
tok = tok + '?=' + rest
if len(tok.split()) > 1:
ew.defects.append(errors.InvalidHeaderDefect(
"whitespace inside encoded word"))
ew.cte = value
value = ''.join(remainder)
try:
text, charset, lang, defects = _ew.decode('=?' + tok + '?=')
except ValueError:
raise errors.HeaderParseError(
"encoded word format invalid: '{}'".format(ew.cte))
ew.charset = charset
ew.lang = lang
ew.defects.extend(defects)
while text:
if text[0] in WSP:
token, text = get_fws(text)
ew.append(token)
continue
_3to2list5 = list(_wsp_splitter(text, 1))
chars, remainder, = _3to2list5[:1] + [_3to2list5[1:]]
vtext = ValueTerminal(chars, 'vtext')
_validate_xtext(vtext)
ew.append(vtext)
text = ''.join(remainder)
return ew, value | [
"def",
"get_encoded_word",
"(",
"value",
")",
":",
"ew",
"=",
"EncodedWord",
"(",
")",
"if",
"not",
"value",
".",
"startswith",
"(",
"'=?'",
")",
":",
"raise",
"errors",
".",
"HeaderParseError",
"(",
"\"expected encoded word but found {}\"",
".",
"format",
"("... | encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" | [
"encoded",
"-",
"word",
"=",
"=",
"?",
"charset",
"?",
"encoding",
"?",
"encoded",
"-",
"text",
"?",
"="
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_header_value_parser.py#L1441-L1483 |
224,839 | PythonCharmers/python-future | src/future/backports/email/_header_value_parser.py | get_display_name | def get_display_name(value):
""" display-name = phrase
Because this is simply a name-rule, we don't return a display-name
token containing a phrase, but rather a display-name token with
the content of the phrase.
"""
display_name = DisplayName()
token, value = get_phrase(value)
display_name.extend(token[:])
display_name.defects = token.defects[:]
return display_name, value | python | def get_display_name(value):
display_name = DisplayName()
token, value = get_phrase(value)
display_name.extend(token[:])
display_name.defects = token.defects[:]
return display_name, value | [
"def",
"get_display_name",
"(",
"value",
")",
":",
"display_name",
"=",
"DisplayName",
"(",
")",
"token",
",",
"value",
"=",
"get_phrase",
"(",
"value",
")",
"display_name",
".",
"extend",
"(",
"token",
"[",
":",
"]",
")",
"display_name",
".",
"defects",
... | display-name = phrase
Because this is simply a name-rule, we don't return a display-name
token containing a phrase, but rather a display-name token with
the content of the phrase. | [
"display",
"-",
"name",
"=",
"phrase"
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_header_value_parser.py#L2081-L2093 |
224,840 | PythonCharmers/python-future | src/future/backports/email/_header_value_parser.py | get_invalid_mailbox | def get_invalid_mailbox(value, endchars):
""" Read everything up to one of the chars in endchars.
This is outside the formal grammar. The InvalidMailbox TokenList that is
returned acts like a Mailbox, but the data attributes are None.
"""
invalid_mailbox = InvalidMailbox()
while value and value[0] not in endchars:
if value[0] in PHRASE_ENDS:
invalid_mailbox.append(ValueTerminal(value[0],
'misplaced-special'))
value = value[1:]
else:
token, value = get_phrase(value)
invalid_mailbox.append(token)
return invalid_mailbox, value | python | def get_invalid_mailbox(value, endchars):
invalid_mailbox = InvalidMailbox()
while value and value[0] not in endchars:
if value[0] in PHRASE_ENDS:
invalid_mailbox.append(ValueTerminal(value[0],
'misplaced-special'))
value = value[1:]
else:
token, value = get_phrase(value)
invalid_mailbox.append(token)
return invalid_mailbox, value | [
"def",
"get_invalid_mailbox",
"(",
"value",
",",
"endchars",
")",
":",
"invalid_mailbox",
"=",
"InvalidMailbox",
"(",
")",
"while",
"value",
"and",
"value",
"[",
"0",
"]",
"not",
"in",
"endchars",
":",
"if",
"value",
"[",
"0",
"]",
"in",
"PHRASE_ENDS",
"... | Read everything up to one of the chars in endchars.
This is outside the formal grammar. The InvalidMailbox TokenList that is
returned acts like a Mailbox, but the data attributes are None. | [
"Read",
"everything",
"up",
"to",
"one",
"of",
"the",
"chars",
"in",
"endchars",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_header_value_parser.py#L2147-L2163 |
224,841 | PythonCharmers/python-future | src/future/backports/email/_header_value_parser.py | get_invalid_parameter | def get_invalid_parameter(value):
""" Read everything up to the next ';'.
This is outside the formal grammar. The InvalidParameter TokenList that is
returned acts like a Parameter, but the data attributes are None.
"""
invalid_parameter = InvalidParameter()
while value and value[0] != ';':
if value[0] in PHRASE_ENDS:
invalid_parameter.append(ValueTerminal(value[0],
'misplaced-special'))
value = value[1:]
else:
token, value = get_phrase(value)
invalid_parameter.append(token)
return invalid_parameter, value | python | def get_invalid_parameter(value):
invalid_parameter = InvalidParameter()
while value and value[0] != ';':
if value[0] in PHRASE_ENDS:
invalid_parameter.append(ValueTerminal(value[0],
'misplaced-special'))
value = value[1:]
else:
token, value = get_phrase(value)
invalid_parameter.append(token)
return invalid_parameter, value | [
"def",
"get_invalid_parameter",
"(",
"value",
")",
":",
"invalid_parameter",
"=",
"InvalidParameter",
"(",
")",
"while",
"value",
"and",
"value",
"[",
"0",
"]",
"!=",
"';'",
":",
"if",
"value",
"[",
"0",
"]",
"in",
"PHRASE_ENDS",
":",
"invalid_parameter",
... | Read everything up to the next ';'.
This is outside the formal grammar. The InvalidParameter TokenList that is
returned acts like a Parameter, but the data attributes are None. | [
"Read",
"everything",
"up",
"to",
"the",
"next",
";",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_header_value_parser.py#L2448-L2464 |
224,842 | PythonCharmers/python-future | src/future/backports/email/_header_value_parser.py | _find_mime_parameters | def _find_mime_parameters(tokenlist, value):
"""Do our best to find the parameters in an invalid MIME header
"""
while value and value[0] != ';':
if value[0] in PHRASE_ENDS:
tokenlist.append(ValueTerminal(value[0], 'misplaced-special'))
value = value[1:]
else:
token, value = get_phrase(value)
tokenlist.append(token)
if not value:
return
tokenlist.append(ValueTerminal(';', 'parameter-separator'))
tokenlist.append(parse_mime_parameters(value[1:])) | python | def _find_mime_parameters(tokenlist, value):
while value and value[0] != ';':
if value[0] in PHRASE_ENDS:
tokenlist.append(ValueTerminal(value[0], 'misplaced-special'))
value = value[1:]
else:
token, value = get_phrase(value)
tokenlist.append(token)
if not value:
return
tokenlist.append(ValueTerminal(';', 'parameter-separator'))
tokenlist.append(parse_mime_parameters(value[1:])) | [
"def",
"_find_mime_parameters",
"(",
"tokenlist",
",",
"value",
")",
":",
"while",
"value",
"and",
"value",
"[",
"0",
"]",
"!=",
"';'",
":",
"if",
"value",
"[",
"0",
"]",
"in",
"PHRASE_ENDS",
":",
"tokenlist",
".",
"append",
"(",
"ValueTerminal",
"(",
... | Do our best to find the parameters in an invalid MIME header | [
"Do",
"our",
"best",
"to",
"find",
"the",
"parameters",
"in",
"an",
"invalid",
"MIME",
"header"
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_header_value_parser.py#L2833-L2847 |
224,843 | PythonCharmers/python-future | src/future/backports/email/base64mime.py | header_length | def header_length(bytearray):
"""Return the length of s when it is encoded with base64."""
groups_of_3, leftover = divmod(len(bytearray), 3)
# 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.
n = groups_of_3 * 4
if leftover:
n += 4
return n | python | def header_length(bytearray):
groups_of_3, leftover = divmod(len(bytearray), 3)
# 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.
n = groups_of_3 * 4
if leftover:
n += 4
return n | [
"def",
"header_length",
"(",
"bytearray",
")",
":",
"groups_of_3",
",",
"leftover",
"=",
"divmod",
"(",
"len",
"(",
"bytearray",
")",
",",
"3",
")",
"# 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.",
"n",
"=",
"groups_of_3",
"*",
"4",
"if",
"lefto... | Return the length of s when it is encoded with base64. | [
"Return",
"the",
"length",
"of",
"s",
"when",
"it",
"is",
"encoded",
"with",
"base64",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/base64mime.py#L54-L61 |
224,844 | PythonCharmers/python-future | src/future/backports/email/base64mime.py | header_encode | def header_encode(header_bytes, charset='iso-8859-1'):
"""Encode a single header line with Base64 encoding in a given charset.
charset names the character set to use to encode the header. It defaults
to iso-8859-1. Base64 encoding is defined in RFC 2045.
"""
if not header_bytes:
return ""
if isinstance(header_bytes, str):
header_bytes = header_bytes.encode(charset)
encoded = b64encode(header_bytes).decode("ascii")
return '=?%s?b?%s?=' % (charset, encoded) | python | def header_encode(header_bytes, charset='iso-8859-1'):
if not header_bytes:
return ""
if isinstance(header_bytes, str):
header_bytes = header_bytes.encode(charset)
encoded = b64encode(header_bytes).decode("ascii")
return '=?%s?b?%s?=' % (charset, encoded) | [
"def",
"header_encode",
"(",
"header_bytes",
",",
"charset",
"=",
"'iso-8859-1'",
")",
":",
"if",
"not",
"header_bytes",
":",
"return",
"\"\"",
"if",
"isinstance",
"(",
"header_bytes",
",",
"str",
")",
":",
"header_bytes",
"=",
"header_bytes",
".",
"encode",
... | Encode a single header line with Base64 encoding in a given charset.
charset names the character set to use to encode the header. It defaults
to iso-8859-1. Base64 encoding is defined in RFC 2045. | [
"Encode",
"a",
"single",
"header",
"line",
"with",
"Base64",
"encoding",
"in",
"a",
"given",
"charset",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/base64mime.py#L64-L75 |
224,845 | PythonCharmers/python-future | src/future/backports/email/base64mime.py | body_encode | def body_encode(s, maxlinelen=76, eol=NL):
r"""Encode a string with base64.
Each line will be wrapped at, at most, maxlinelen characters (defaults to
76 characters).
Each line of encoded text will end with eol, which defaults to "\n". Set
this to "\r\n" if you will be using the result of this function directly
in an email.
"""
if not s:
return s
encvec = []
max_unencoded = maxlinelen * 3 // 4
for i in range(0, len(s), max_unencoded):
# BAW: should encode() inherit b2a_base64()'s dubious behavior in
# adding a newline to the encoded string?
enc = b2a_base64(s[i:i + max_unencoded]).decode("ascii")
if enc.endswith(NL) and eol != NL:
enc = enc[:-1] + eol
encvec.append(enc)
return EMPTYSTRING.join(encvec) | python | def body_encode(s, maxlinelen=76, eol=NL):
r"""Encode a string with base64.
Each line will be wrapped at, at most, maxlinelen characters (defaults to
76 characters).
Each line of encoded text will end with eol, which defaults to "\n". Set
this to "\r\n" if you will be using the result of this function directly
in an email.
"""
if not s:
return s
encvec = []
max_unencoded = maxlinelen * 3 // 4
for i in range(0, len(s), max_unencoded):
# BAW: should encode() inherit b2a_base64()'s dubious behavior in
# adding a newline to the encoded string?
enc = b2a_base64(s[i:i + max_unencoded]).decode("ascii")
if enc.endswith(NL) and eol != NL:
enc = enc[:-1] + eol
encvec.append(enc)
return EMPTYSTRING.join(encvec) | [
"def",
"body_encode",
"(",
"s",
",",
"maxlinelen",
"=",
"76",
",",
"eol",
"=",
"NL",
")",
":",
"if",
"not",
"s",
":",
"return",
"s",
"encvec",
"=",
"[",
"]",
"max_unencoded",
"=",
"maxlinelen",
"*",
"3",
"//",
"4",
"for",
"i",
"in",
"range",
"(",... | r"""Encode a string with base64.
Each line will be wrapped at, at most, maxlinelen characters (defaults to
76 characters).
Each line of encoded text will end with eol, which defaults to "\n". Set
this to "\r\n" if you will be using the result of this function directly
in an email. | [
"r",
"Encode",
"a",
"string",
"with",
"base64",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/base64mime.py#L78-L100 |
224,846 | PythonCharmers/python-future | src/future/backports/email/base64mime.py | decode | def decode(string):
"""Decode a raw base64 string, returning a bytes object.
This function does not parse a full MIME header value encoded with
base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
level email.header class for that functionality.
"""
if not string:
return bytes()
elif isinstance(string, str):
return a2b_base64(string.encode('raw-unicode-escape'))
else:
return a2b_base64(string) | python | def decode(string):
if not string:
return bytes()
elif isinstance(string, str):
return a2b_base64(string.encode('raw-unicode-escape'))
else:
return a2b_base64(string) | [
"def",
"decode",
"(",
"string",
")",
":",
"if",
"not",
"string",
":",
"return",
"bytes",
"(",
")",
"elif",
"isinstance",
"(",
"string",
",",
"str",
")",
":",
"return",
"a2b_base64",
"(",
"string",
".",
"encode",
"(",
"'raw-unicode-escape'",
")",
")",
"... | Decode a raw base64 string, returning a bytes object.
This function does not parse a full MIME header value encoded with
base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
level email.header class for that functionality. | [
"Decode",
"a",
"raw",
"base64",
"string",
"returning",
"a",
"bytes",
"object",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/base64mime.py#L103-L115 |
224,847 | PythonCharmers/python-future | src/future/backports/urllib/parse.py | urldefrag | def urldefrag(url):
"""Removes any existing fragment from URL.
Returns a tuple of the defragmented URL and the fragment. If
the URL contained no fragments, the second element is the
empty string.
"""
url, _coerce_result = _coerce_args(url)
if '#' in url:
s, n, p, a, q, frag = urlparse(url)
defrag = urlunparse((s, n, p, a, q, ''))
else:
frag = ''
defrag = url
return _coerce_result(DefragResult(defrag, frag)) | python | def urldefrag(url):
url, _coerce_result = _coerce_args(url)
if '#' in url:
s, n, p, a, q, frag = urlparse(url)
defrag = urlunparse((s, n, p, a, q, ''))
else:
frag = ''
defrag = url
return _coerce_result(DefragResult(defrag, frag)) | [
"def",
"urldefrag",
"(",
"url",
")",
":",
"url",
",",
"_coerce_result",
"=",
"_coerce_args",
"(",
"url",
")",
"if",
"'#'",
"in",
"url",
":",
"s",
",",
"n",
",",
"p",
",",
"a",
",",
"q",
",",
"frag",
"=",
"urlparse",
"(",
"url",
")",
"defrag",
"... | Removes any existing fragment from URL.
Returns a tuple of the defragmented URL and the fragment. If
the URL contained no fragments, the second element is the
empty string. | [
"Removes",
"any",
"existing",
"fragment",
"from",
"URL",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/parse.py#L464-L478 |
224,848 | PythonCharmers/python-future | src/future/backports/email/quoprimime.py | body_encode | def body_encode(body, maxlinelen=76, eol=NL):
"""Encode with quoted-printable, wrapping at maxlinelen characters.
Each line of encoded text will end with eol, which defaults to "\\n". Set
this to "\\r\\n" if you will be using the result of this function directly
in an email.
Each line will be wrapped at, at most, maxlinelen characters before the
eol string (maxlinelen defaults to 76 characters, the maximum value
permitted by RFC 2045). Long lines will have the 'soft line break'
quoted-printable character "=" appended to them, so the decoded text will
be identical to the original text.
The minimum maxlinelen is 4 to have room for a quoted character ("=XX")
followed by a soft line break. Smaller values will generate a
ValueError.
"""
if maxlinelen < 4:
raise ValueError("maxlinelen must be at least 4")
if not body:
return body
# The last line may or may not end in eol, but all other lines do.
last_has_eol = (body[-1] in '\r\n')
# This accumulator will make it easier to build the encoded body.
encoded_body = _body_accumulator(maxlinelen, eol)
lines = body.splitlines()
last_line_no = len(lines) - 1
for line_no, line in enumerate(lines):
last_char_index = len(line) - 1
for i, c in enumerate(line):
if body_check(ord(c)):
c = quote(c)
encoded_body.write_char(c, i==last_char_index)
# Add an eol if input line had eol. All input lines have eol except
# possibly the last one.
if line_no < last_line_no or last_has_eol:
encoded_body.newline()
return encoded_body.getvalue() | python | def body_encode(body, maxlinelen=76, eol=NL):
if maxlinelen < 4:
raise ValueError("maxlinelen must be at least 4")
if not body:
return body
# The last line may or may not end in eol, but all other lines do.
last_has_eol = (body[-1] in '\r\n')
# This accumulator will make it easier to build the encoded body.
encoded_body = _body_accumulator(maxlinelen, eol)
lines = body.splitlines()
last_line_no = len(lines) - 1
for line_no, line in enumerate(lines):
last_char_index = len(line) - 1
for i, c in enumerate(line):
if body_check(ord(c)):
c = quote(c)
encoded_body.write_char(c, i==last_char_index)
# Add an eol if input line had eol. All input lines have eol except
# possibly the last one.
if line_no < last_line_no or last_has_eol:
encoded_body.newline()
return encoded_body.getvalue() | [
"def",
"body_encode",
"(",
"body",
",",
"maxlinelen",
"=",
"76",
",",
"eol",
"=",
"NL",
")",
":",
"if",
"maxlinelen",
"<",
"4",
":",
"raise",
"ValueError",
"(",
"\"maxlinelen must be at least 4\"",
")",
"if",
"not",
"body",
":",
"return",
"body",
"# The la... | Encode with quoted-printable, wrapping at maxlinelen characters.
Each line of encoded text will end with eol, which defaults to "\\n". Set
this to "\\r\\n" if you will be using the result of this function directly
in an email.
Each line will be wrapped at, at most, maxlinelen characters before the
eol string (maxlinelen defaults to 76 characters, the maximum value
permitted by RFC 2045). Long lines will have the 'soft line break'
quoted-printable character "=" appended to them, so the decoded text will
be identical to the original text.
The minimum maxlinelen is 4 to have room for a quoted character ("=XX")
followed by a soft line break. Smaller values will generate a
ValueError. | [
"Encode",
"with",
"quoted",
"-",
"printable",
"wrapping",
"at",
"maxlinelen",
"characters",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/quoprimime.py#L209-L252 |
224,849 | PythonCharmers/python-future | src/future/backports/email/quoprimime.py | decode | def decode(encoded, eol=NL):
"""Decode a quoted-printable string.
Lines are separated with eol, which defaults to \\n.
"""
if not encoded:
return encoded
# BAW: see comment in encode() above. Again, we're building up the
# decoded string with string concatenation, which could be done much more
# efficiently.
decoded = ''
for line in encoded.splitlines():
line = line.rstrip()
if not line:
decoded += eol
continue
i = 0
n = len(line)
while i < n:
c = line[i]
if c != '=':
decoded += c
i += 1
# Otherwise, c == "=". Are we at the end of the line? If so, add
# a soft line break.
elif i+1 == n:
i += 1
continue
# Decode if in form =AB
elif i+2 < n and line[i+1] in hexdigits and line[i+2] in hexdigits:
decoded += unquote(line[i:i+3])
i += 3
# Otherwise, not in form =AB, pass literally
else:
decoded += c
i += 1
if i == n:
decoded += eol
# Special case if original string did not end with eol
if encoded[-1] not in '\r\n' and decoded.endswith(eol):
decoded = decoded[:-1]
return decoded | python | def decode(encoded, eol=NL):
if not encoded:
return encoded
# BAW: see comment in encode() above. Again, we're building up the
# decoded string with string concatenation, which could be done much more
# efficiently.
decoded = ''
for line in encoded.splitlines():
line = line.rstrip()
if not line:
decoded += eol
continue
i = 0
n = len(line)
while i < n:
c = line[i]
if c != '=':
decoded += c
i += 1
# Otherwise, c == "=". Are we at the end of the line? If so, add
# a soft line break.
elif i+1 == n:
i += 1
continue
# Decode if in form =AB
elif i+2 < n and line[i+1] in hexdigits and line[i+2] in hexdigits:
decoded += unquote(line[i:i+3])
i += 3
# Otherwise, not in form =AB, pass literally
else:
decoded += c
i += 1
if i == n:
decoded += eol
# Special case if original string did not end with eol
if encoded[-1] not in '\r\n' and decoded.endswith(eol):
decoded = decoded[:-1]
return decoded | [
"def",
"decode",
"(",
"encoded",
",",
"eol",
"=",
"NL",
")",
":",
"if",
"not",
"encoded",
":",
"return",
"encoded",
"# BAW: see comment in encode() above. Again, we're building up the",
"# decoded string with string concatenation, which could be done much more",
"# efficiently."... | Decode a quoted-printable string.
Lines are separated with eol, which defaults to \\n. | [
"Decode",
"a",
"quoted",
"-",
"printable",
"string",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/quoprimime.py#L258-L302 |
224,850 | PythonCharmers/python-future | src/future/backports/email/quoprimime.py | header_decode | def header_decode(s):
"""Decode a string encoded with RFC 2045 MIME header `Q' encoding.
This function does not parse a full MIME header value encoded with
quoted-printable (like =?iso-8895-1?q?Hello_World?=) -- please use
the high level email.header class for that functionality.
"""
s = s.replace('_', ' ')
return re.sub(r'=[a-fA-F0-9]{2}', _unquote_match, s, re.ASCII) | python | def header_decode(s):
s = s.replace('_', ' ')
return re.sub(r'=[a-fA-F0-9]{2}', _unquote_match, s, re.ASCII) | [
"def",
"header_decode",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
"return",
"re",
".",
"sub",
"(",
"r'=[a-fA-F0-9]{2}'",
",",
"_unquote_match",
",",
"s",
",",
"re",
".",
"ASCII",
")"
] | Decode a string encoded with RFC 2045 MIME header `Q' encoding.
This function does not parse a full MIME header value encoded with
quoted-printable (like =?iso-8895-1?q?Hello_World?=) -- please use
the high level email.header class for that functionality. | [
"Decode",
"a",
"string",
"encoded",
"with",
"RFC",
"2045",
"MIME",
"header",
"Q",
"encoding",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/quoprimime.py#L318-L326 |
224,851 | PythonCharmers/python-future | src/future/backports/email/quoprimime.py | _body_accumulator.write_str | def write_str(self, s):
"""Add string s to the accumulated body."""
self.write(s)
self.room -= len(s) | python | def write_str(self, s):
self.write(s)
self.room -= len(s) | [
"def",
"write_str",
"(",
"self",
",",
"s",
")",
":",
"self",
".",
"write",
"(",
"s",
")",
"self",
".",
"room",
"-=",
"len",
"(",
"s",
")"
] | Add string s to the accumulated body. | [
"Add",
"string",
"s",
"to",
"the",
"accumulated",
"body",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/quoprimime.py#L162-L165 |
224,852 | PythonCharmers/python-future | src/future/backports/email/quoprimime.py | _body_accumulator.newline | def newline(self):
"""Write eol, then start new line."""
self.write_str(self.eol)
self.room = self.maxlinelen | python | def newline(self):
self.write_str(self.eol)
self.room = self.maxlinelen | [
"def",
"newline",
"(",
"self",
")",
":",
"self",
".",
"write_str",
"(",
"self",
".",
"eol",
")",
"self",
".",
"room",
"=",
"self",
".",
"maxlinelen"
] | Write eol, then start new line. | [
"Write",
"eol",
"then",
"start",
"new",
"line",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/quoprimime.py#L167-L170 |
224,853 | PythonCharmers/python-future | src/future/backports/email/quoprimime.py | _body_accumulator.write_wrapped | def write_wrapped(self, s, extra_room=0):
"""Add a soft line break if needed, then write s."""
if self.room < len(s) + extra_room:
self.write_soft_break()
self.write_str(s) | python | def write_wrapped(self, s, extra_room=0):
if self.room < len(s) + extra_room:
self.write_soft_break()
self.write_str(s) | [
"def",
"write_wrapped",
"(",
"self",
",",
"s",
",",
"extra_room",
"=",
"0",
")",
":",
"if",
"self",
".",
"room",
"<",
"len",
"(",
"s",
")",
"+",
"extra_room",
":",
"self",
".",
"write_soft_break",
"(",
")",
"self",
".",
"write_str",
"(",
"s",
")"
] | Add a soft line break if needed, then write s. | [
"Add",
"a",
"soft",
"line",
"break",
"if",
"needed",
"then",
"write",
"s",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/quoprimime.py#L177-L181 |
224,854 | PythonCharmers/python-future | src/future/backports/html/parser.py | HTMLParser.reset | def reset(self):
"""Reset this instance. Loses all unprocessed data."""
self.rawdata = ''
self.lasttag = '???'
self.interesting = interesting_normal
self.cdata_elem = None
_markupbase.ParserBase.reset(self) | python | def reset(self):
self.rawdata = ''
self.lasttag = '???'
self.interesting = interesting_normal
self.cdata_elem = None
_markupbase.ParserBase.reset(self) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"rawdata",
"=",
"''",
"self",
".",
"lasttag",
"=",
"'???'",
"self",
".",
"interesting",
"=",
"interesting_normal",
"self",
".",
"cdata_elem",
"=",
"None",
"_markupbase",
".",
"ParserBase",
".",
"reset",
... | Reset this instance. Loses all unprocessed data. | [
"Reset",
"this",
"instance",
".",
"Loses",
"all",
"unprocessed",
"data",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/html/parser.py#L135-L141 |
224,855 | PythonCharmers/python-future | src/future/backports/html/parser.py | HTMLParser.feed | def feed(self, data):
r"""Feed data to the parser.
Call this as often as you want, with as little or as much text
as you want (may include '\n').
"""
self.rawdata = self.rawdata + data
self.goahead(0) | python | def feed(self, data):
r"""Feed data to the parser.
Call this as often as you want, with as little or as much text
as you want (may include '\n').
"""
self.rawdata = self.rawdata + data
self.goahead(0) | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"rawdata",
"=",
"self",
".",
"rawdata",
"+",
"data",
"self",
".",
"goahead",
"(",
"0",
")"
] | r"""Feed data to the parser.
Call this as often as you want, with as little or as much text
as you want (may include '\n'). | [
"r",
"Feed",
"data",
"to",
"the",
"parser",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/html/parser.py#L143-L150 |
224,856 | PythonCharmers/python-future | src/future/backports/email/encoders.py | encode_base64 | def encode_base64(msg):
"""Encode the message's payload in Base64.
Also, add an appropriate Content-Transfer-Encoding header.
"""
orig = msg.get_payload()
encdata = str(_bencode(orig), 'ascii')
msg.set_payload(encdata)
msg['Content-Transfer-Encoding'] = 'base64' | python | def encode_base64(msg):
orig = msg.get_payload()
encdata = str(_bencode(orig), 'ascii')
msg.set_payload(encdata)
msg['Content-Transfer-Encoding'] = 'base64' | [
"def",
"encode_base64",
"(",
"msg",
")",
":",
"orig",
"=",
"msg",
".",
"get_payload",
"(",
")",
"encdata",
"=",
"str",
"(",
"_bencode",
"(",
"orig",
")",
",",
"'ascii'",
")",
"msg",
".",
"set_payload",
"(",
"encdata",
")",
"msg",
"[",
"'Content-Transfe... | Encode the message's payload in Base64.
Also, add an appropriate Content-Transfer-Encoding header. | [
"Encode",
"the",
"message",
"s",
"payload",
"in",
"Base64",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/encoders.py#L33-L41 |
224,857 | PythonCharmers/python-future | src/future/backports/email/encoders.py | encode_quopri | def encode_quopri(msg):
"""Encode the message's payload in quoted-printable.
Also, add an appropriate Content-Transfer-Encoding header.
"""
orig = msg.get_payload()
encdata = _qencode(orig)
msg.set_payload(encdata)
msg['Content-Transfer-Encoding'] = 'quoted-printable' | python | def encode_quopri(msg):
orig = msg.get_payload()
encdata = _qencode(orig)
msg.set_payload(encdata)
msg['Content-Transfer-Encoding'] = 'quoted-printable' | [
"def",
"encode_quopri",
"(",
"msg",
")",
":",
"orig",
"=",
"msg",
".",
"get_payload",
"(",
")",
"encdata",
"=",
"_qencode",
"(",
"orig",
")",
"msg",
".",
"set_payload",
"(",
"encdata",
")",
"msg",
"[",
"'Content-Transfer-Encoding'",
"]",
"=",
"'quoted-prin... | Encode the message's payload in quoted-printable.
Also, add an appropriate Content-Transfer-Encoding header. | [
"Encode",
"the",
"message",
"s",
"payload",
"in",
"quoted",
"-",
"printable",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/encoders.py#L44-L52 |
224,858 | PythonCharmers/python-future | src/future/backports/email/encoders.py | encode_7or8bit | def encode_7or8bit(msg):
"""Set the Content-Transfer-Encoding header to 7bit or 8bit."""
orig = msg.get_payload()
if orig is None:
# There's no payload. For backwards compatibility we use 7bit
msg['Content-Transfer-Encoding'] = '7bit'
return
# We play a trick to make this go fast. If encoding/decode to ASCII
# succeeds, we know the data must be 7bit, otherwise treat it as 8bit.
try:
if isinstance(orig, str):
orig.encode('ascii')
else:
orig.decode('ascii')
except UnicodeError:
charset = msg.get_charset()
output_cset = charset and charset.output_charset
# iso-2022-* is non-ASCII but encodes to a 7-bit representation
if output_cset and output_cset.lower().startswith('iso-2022-'):
msg['Content-Transfer-Encoding'] = '7bit'
else:
msg['Content-Transfer-Encoding'] = '8bit'
else:
msg['Content-Transfer-Encoding'] = '7bit'
if not isinstance(orig, str):
msg.set_payload(orig.decode('ascii', 'surrogateescape')) | python | def encode_7or8bit(msg):
orig = msg.get_payload()
if orig is None:
# There's no payload. For backwards compatibility we use 7bit
msg['Content-Transfer-Encoding'] = '7bit'
return
# We play a trick to make this go fast. If encoding/decode to ASCII
# succeeds, we know the data must be 7bit, otherwise treat it as 8bit.
try:
if isinstance(orig, str):
orig.encode('ascii')
else:
orig.decode('ascii')
except UnicodeError:
charset = msg.get_charset()
output_cset = charset and charset.output_charset
# iso-2022-* is non-ASCII but encodes to a 7-bit representation
if output_cset and output_cset.lower().startswith('iso-2022-'):
msg['Content-Transfer-Encoding'] = '7bit'
else:
msg['Content-Transfer-Encoding'] = '8bit'
else:
msg['Content-Transfer-Encoding'] = '7bit'
if not isinstance(orig, str):
msg.set_payload(orig.decode('ascii', 'surrogateescape')) | [
"def",
"encode_7or8bit",
"(",
"msg",
")",
":",
"orig",
"=",
"msg",
".",
"get_payload",
"(",
")",
"if",
"orig",
"is",
"None",
":",
"# There's no payload. For backwards compatibility we use 7bit",
"msg",
"[",
"'Content-Transfer-Encoding'",
"]",
"=",
"'7bit'",
"return... | Set the Content-Transfer-Encoding header to 7bit or 8bit. | [
"Set",
"the",
"Content",
"-",
"Transfer",
"-",
"Encoding",
"header",
"to",
"7bit",
"or",
"8bit",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/encoders.py#L55-L80 |
224,859 | PythonCharmers/python-future | src/future/backports/email/encoders.py | encode_noop | def encode_noop(msg):
"""Do nothing."""
# Well, not quite *nothing*: in Python3 we have to turn bytes into a string
# in our internal surrogateescaped form in order to keep the model
# consistent.
orig = msg.get_payload()
if not isinstance(orig, str):
msg.set_payload(orig.decode('ascii', 'surrogateescape')) | python | def encode_noop(msg):
# Well, not quite *nothing*: in Python3 we have to turn bytes into a string
# in our internal surrogateescaped form in order to keep the model
# consistent.
orig = msg.get_payload()
if not isinstance(orig, str):
msg.set_payload(orig.decode('ascii', 'surrogateescape')) | [
"def",
"encode_noop",
"(",
"msg",
")",
":",
"# Well, not quite *nothing*: in Python3 we have to turn bytes into a string",
"# in our internal surrogateescaped form in order to keep the model",
"# consistent.",
"orig",
"=",
"msg",
".",
"get_payload",
"(",
")",
"if",
"not",
"isinst... | Do nothing. | [
"Do",
"nothing",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/encoders.py#L83-L90 |
224,860 | PythonCharmers/python-future | src/future/standard_library/__init__.py | is_py2_stdlib_module | def is_py2_stdlib_module(m):
"""
Tries to infer whether the module m is from the Python 2 standard library.
This may not be reliable on all systems.
"""
if PY3:
return False
if not 'stdlib_path' in is_py2_stdlib_module.__dict__:
stdlib_files = [contextlib.__file__, os.__file__, copy.__file__]
stdlib_paths = [os.path.split(f)[0] for f in stdlib_files]
if not len(set(stdlib_paths)) == 1:
# This seems to happen on travis-ci.org. Very strange. We'll try to
# ignore it.
flog.warn('Multiple locations found for the Python standard '
'library: %s' % stdlib_paths)
# Choose the first one arbitrarily
is_py2_stdlib_module.stdlib_path = stdlib_paths[0]
if m.__name__ in sys.builtin_module_names:
return True
if hasattr(m, '__file__'):
modpath = os.path.split(m.__file__)
if (modpath[0].startswith(is_py2_stdlib_module.stdlib_path) and
'site-packages' not in modpath[0]):
return True
return False | python | def is_py2_stdlib_module(m):
if PY3:
return False
if not 'stdlib_path' in is_py2_stdlib_module.__dict__:
stdlib_files = [contextlib.__file__, os.__file__, copy.__file__]
stdlib_paths = [os.path.split(f)[0] for f in stdlib_files]
if not len(set(stdlib_paths)) == 1:
# This seems to happen on travis-ci.org. Very strange. We'll try to
# ignore it.
flog.warn('Multiple locations found for the Python standard '
'library: %s' % stdlib_paths)
# Choose the first one arbitrarily
is_py2_stdlib_module.stdlib_path = stdlib_paths[0]
if m.__name__ in sys.builtin_module_names:
return True
if hasattr(m, '__file__'):
modpath = os.path.split(m.__file__)
if (modpath[0].startswith(is_py2_stdlib_module.stdlib_path) and
'site-packages' not in modpath[0]):
return True
return False | [
"def",
"is_py2_stdlib_module",
"(",
"m",
")",
":",
"if",
"PY3",
":",
"return",
"False",
"if",
"not",
"'stdlib_path'",
"in",
"is_py2_stdlib_module",
".",
"__dict__",
":",
"stdlib_files",
"=",
"[",
"contextlib",
".",
"__file__",
",",
"os",
".",
"__file__",
","... | Tries to infer whether the module m is from the Python 2 standard library.
This may not be reliable on all systems. | [
"Tries",
"to",
"infer",
"whether",
"the",
"module",
"m",
"is",
"from",
"the",
"Python",
"2",
"standard",
"library",
".",
"This",
"may",
"not",
"be",
"reliable",
"on",
"all",
"systems",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/standard_library/__init__.py#L342-L369 |
224,861 | PythonCharmers/python-future | src/future/standard_library/__init__.py | restore_sys_modules | def restore_sys_modules(scrubbed):
"""
Add any previously scrubbed modules back to the sys.modules cache,
but only if it's safe to do so.
"""
clash = set(sys.modules) & set(scrubbed)
if len(clash) != 0:
# If several, choose one arbitrarily to raise an exception about
first = list(clash)[0]
raise ImportError('future module {} clashes with Py2 module'
.format(first))
sys.modules.update(scrubbed) | python | def restore_sys_modules(scrubbed):
clash = set(sys.modules) & set(scrubbed)
if len(clash) != 0:
# If several, choose one arbitrarily to raise an exception about
first = list(clash)[0]
raise ImportError('future module {} clashes with Py2 module'
.format(first))
sys.modules.update(scrubbed) | [
"def",
"restore_sys_modules",
"(",
"scrubbed",
")",
":",
"clash",
"=",
"set",
"(",
"sys",
".",
"modules",
")",
"&",
"set",
"(",
"scrubbed",
")",
"if",
"len",
"(",
"clash",
")",
"!=",
"0",
":",
"# If several, choose one arbitrarily to raise an exception about",
... | Add any previously scrubbed modules back to the sys.modules cache,
but only if it's safe to do so. | [
"Add",
"any",
"previously",
"scrubbed",
"modules",
"back",
"to",
"the",
"sys",
".",
"modules",
"cache",
"but",
"only",
"if",
"it",
"s",
"safe",
"to",
"do",
"so",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/standard_library/__init__.py#L429-L440 |
224,862 | PythonCharmers/python-future | src/future/standard_library/__init__.py | install_hooks | def install_hooks():
"""
This function installs the future.standard_library import hook into
sys.meta_path.
"""
if PY3:
return
install_aliases()
flog.debug('sys.meta_path was: {0}'.format(sys.meta_path))
flog.debug('Installing hooks ...')
# Add it unless it's there already
newhook = RenameImport(RENAMES)
if not detect_hooks():
sys.meta_path.append(newhook)
flog.debug('sys.meta_path is now: {0}'.format(sys.meta_path)) | python | def install_hooks():
if PY3:
return
install_aliases()
flog.debug('sys.meta_path was: {0}'.format(sys.meta_path))
flog.debug('Installing hooks ...')
# Add it unless it's there already
newhook = RenameImport(RENAMES)
if not detect_hooks():
sys.meta_path.append(newhook)
flog.debug('sys.meta_path is now: {0}'.format(sys.meta_path)) | [
"def",
"install_hooks",
"(",
")",
":",
"if",
"PY3",
":",
"return",
"install_aliases",
"(",
")",
"flog",
".",
"debug",
"(",
"'sys.meta_path was: {0}'",
".",
"format",
"(",
"sys",
".",
"meta_path",
")",
")",
"flog",
".",
"debug",
"(",
"'Installing hooks ...'",... | This function installs the future.standard_library import hook into
sys.meta_path. | [
"This",
"function",
"installs",
"the",
"future",
".",
"standard_library",
"import",
"hook",
"into",
"sys",
".",
"meta_path",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/standard_library/__init__.py#L523-L540 |
224,863 | PythonCharmers/python-future | src/future/standard_library/__init__.py | remove_hooks | def remove_hooks(scrub_sys_modules=False):
"""
This function removes the import hook from sys.meta_path.
"""
if PY3:
return
flog.debug('Uninstalling hooks ...')
# Loop backwards, so deleting items keeps the ordering:
for i, hook in list(enumerate(sys.meta_path))[::-1]:
if hasattr(hook, 'RENAMER'):
del sys.meta_path[i]
# Explicit is better than implicit. In the future the interface should
# probably change so that scrubbing the import hooks requires a separate
# function call. Left as is for now for backward compatibility with
# v0.11.x.
if scrub_sys_modules:
scrub_future_sys_modules() | python | def remove_hooks(scrub_sys_modules=False):
if PY3:
return
flog.debug('Uninstalling hooks ...')
# Loop backwards, so deleting items keeps the ordering:
for i, hook in list(enumerate(sys.meta_path))[::-1]:
if hasattr(hook, 'RENAMER'):
del sys.meta_path[i]
# Explicit is better than implicit. In the future the interface should
# probably change so that scrubbing the import hooks requires a separate
# function call. Left as is for now for backward compatibility with
# v0.11.x.
if scrub_sys_modules:
scrub_future_sys_modules() | [
"def",
"remove_hooks",
"(",
"scrub_sys_modules",
"=",
"False",
")",
":",
"if",
"PY3",
":",
"return",
"flog",
".",
"debug",
"(",
"'Uninstalling hooks ...'",
")",
"# Loop backwards, so deleting items keeps the ordering:",
"for",
"i",
",",
"hook",
"in",
"list",
"(",
... | This function removes the import hook from sys.meta_path. | [
"This",
"function",
"removes",
"the",
"import",
"hook",
"from",
"sys",
".",
"meta_path",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/standard_library/__init__.py#L551-L568 |
224,864 | PythonCharmers/python-future | src/future/standard_library/__init__.py | detect_hooks | def detect_hooks():
"""
Returns True if the import hooks are installed, False if not.
"""
flog.debug('Detecting hooks ...')
present = any([hasattr(hook, 'RENAMER') for hook in sys.meta_path])
if present:
flog.debug('Detected.')
else:
flog.debug('Not detected.')
return present | python | def detect_hooks():
flog.debug('Detecting hooks ...')
present = any([hasattr(hook, 'RENAMER') for hook in sys.meta_path])
if present:
flog.debug('Detected.')
else:
flog.debug('Not detected.')
return present | [
"def",
"detect_hooks",
"(",
")",
":",
"flog",
".",
"debug",
"(",
"'Detecting hooks ...'",
")",
"present",
"=",
"any",
"(",
"[",
"hasattr",
"(",
"hook",
",",
"'RENAMER'",
")",
"for",
"hook",
"in",
"sys",
".",
"meta_path",
"]",
")",
"if",
"present",
":",... | Returns True if the import hooks are installed, False if not. | [
"Returns",
"True",
"if",
"the",
"import",
"hooks",
"are",
"installed",
"False",
"if",
"not",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/standard_library/__init__.py#L579-L589 |
224,865 | PythonCharmers/python-future | src/future/standard_library/__init__.py | RenameImport._find_and_load_module | def _find_and_load_module(self, name, path=None):
"""
Finds and loads it. But if there's a . in the name, handles it
properly.
"""
bits = name.split('.')
while len(bits) > 1:
# Treat the first bit as a package
packagename = bits.pop(0)
package = self._find_and_load_module(packagename, path)
try:
path = package.__path__
except AttributeError:
# This could be e.g. moves.
flog.debug('Package {0} has no __path__.'.format(package))
if name in sys.modules:
return sys.modules[name]
flog.debug('What to do here?')
name = bits[0]
module_info = imp.find_module(name, path)
return imp.load_module(name, *module_info) | python | def _find_and_load_module(self, name, path=None):
bits = name.split('.')
while len(bits) > 1:
# Treat the first bit as a package
packagename = bits.pop(0)
package = self._find_and_load_module(packagename, path)
try:
path = package.__path__
except AttributeError:
# This could be e.g. moves.
flog.debug('Package {0} has no __path__.'.format(package))
if name in sys.modules:
return sys.modules[name]
flog.debug('What to do here?')
name = bits[0]
module_info = imp.find_module(name, path)
return imp.load_module(name, *module_info) | [
"def",
"_find_and_load_module",
"(",
"self",
",",
"name",
",",
"path",
"=",
"None",
")",
":",
"bits",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"while",
"len",
"(",
"bits",
")",
">",
"1",
":",
"# Treat the first bit as a package",
"packagename",
"=",
"... | Finds and loads it. But if there's a . in the name, handles it
properly. | [
"Finds",
"and",
"loads",
"it",
".",
"But",
"if",
"there",
"s",
"a",
".",
"in",
"the",
"name",
"handles",
"it",
"properly",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/standard_library/__init__.py#L280-L301 |
224,866 | PythonCharmers/python-future | src/future/backports/email/utils.py | format_datetime | def format_datetime(dt, usegmt=False):
"""Turn a datetime into a date string as specified in RFC 2822.
If usegmt is True, dt must be an aware datetime with an offset of zero. In
this case 'GMT' will be rendered instead of the normal +0000 required by
RFC2822. This is to support HTTP headers involving date stamps.
"""
now = dt.timetuple()
if usegmt:
if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
raise ValueError("usegmt option requires a UTC datetime")
zone = 'GMT'
elif dt.tzinfo is None:
zone = '-0000'
else:
zone = dt.strftime("%z")
return _format_timetuple_and_zone(now, zone) | python | def format_datetime(dt, usegmt=False):
now = dt.timetuple()
if usegmt:
if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
raise ValueError("usegmt option requires a UTC datetime")
zone = 'GMT'
elif dt.tzinfo is None:
zone = '-0000'
else:
zone = dt.strftime("%z")
return _format_timetuple_and_zone(now, zone) | [
"def",
"format_datetime",
"(",
"dt",
",",
"usegmt",
"=",
"False",
")",
":",
"now",
"=",
"dt",
".",
"timetuple",
"(",
")",
"if",
"usegmt",
":",
"if",
"dt",
".",
"tzinfo",
"is",
"None",
"or",
"dt",
".",
"tzinfo",
"!=",
"datetime",
".",
"timezone",
".... | Turn a datetime into a date string as specified in RFC 2822.
If usegmt is True, dt must be an aware datetime with an offset of zero. In
this case 'GMT' will be rendered instead of the normal +0000 required by
RFC2822. This is to support HTTP headers involving date stamps. | [
"Turn",
"a",
"datetime",
"into",
"a",
"date",
"string",
"as",
"specified",
"in",
"RFC",
"2822",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/utils.py#L187-L203 |
224,867 | PythonCharmers/python-future | src/future/backports/email/utils.py | unquote | def unquote(str):
"""Remove quotes from a string."""
if len(str) > 1:
if str.startswith('"') and str.endswith('"'):
return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
if str.startswith('<') and str.endswith('>'):
return str[1:-1]
return str | python | def unquote(str):
if len(str) > 1:
if str.startswith('"') and str.endswith('"'):
return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
if str.startswith('<') and str.endswith('>'):
return str[1:-1]
return str | [
"def",
"unquote",
"(",
"str",
")",
":",
"if",
"len",
"(",
"str",
")",
">",
"1",
":",
"if",
"str",
".",
"startswith",
"(",
"'\"'",
")",
"and",
"str",
".",
"endswith",
"(",
"'\"'",
")",
":",
"return",
"str",
"[",
"1",
":",
"-",
"1",
"]",
".",
... | Remove quotes from a string. | [
"Remove",
"quotes",
"from",
"a",
"string",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/utils.py#L247-L254 |
224,868 | PythonCharmers/python-future | src/future/backports/email/utils.py | decode_rfc2231 | def decode_rfc2231(s):
"""Decode string according to RFC 2231"""
parts = s.split(TICK, 2)
if len(parts) <= 2:
return None, None, s
return parts | python | def decode_rfc2231(s):
parts = s.split(TICK, 2)
if len(parts) <= 2:
return None, None, s
return parts | [
"def",
"decode_rfc2231",
"(",
"s",
")",
":",
"parts",
"=",
"s",
".",
"split",
"(",
"TICK",
",",
"2",
")",
"if",
"len",
"(",
"parts",
")",
"<=",
"2",
":",
"return",
"None",
",",
"None",
",",
"s",
"return",
"parts"
] | Decode string according to RFC 2231 | [
"Decode",
"string",
"according",
"to",
"RFC",
"2231"
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/utils.py#L259-L264 |
224,869 | PythonCharmers/python-future | src/future/backports/email/utils.py | encode_rfc2231 | def encode_rfc2231(s, charset=None, language=None):
"""Encode string according to RFC 2231.
If neither charset nor language is given, then s is returned as-is. If
charset is given but not language, the string is encoded using the empty
string for language.
"""
s = url_quote(s, safe='', encoding=charset or 'ascii')
if charset is None and language is None:
return s
if language is None:
language = ''
return "%s'%s'%s" % (charset, language, s) | python | def encode_rfc2231(s, charset=None, language=None):
s = url_quote(s, safe='', encoding=charset or 'ascii')
if charset is None and language is None:
return s
if language is None:
language = ''
return "%s'%s'%s" % (charset, language, s) | [
"def",
"encode_rfc2231",
"(",
"s",
",",
"charset",
"=",
"None",
",",
"language",
"=",
"None",
")",
":",
"s",
"=",
"url_quote",
"(",
"s",
",",
"safe",
"=",
"''",
",",
"encoding",
"=",
"charset",
"or",
"'ascii'",
")",
"if",
"charset",
"is",
"None",
"... | Encode string according to RFC 2231.
If neither charset nor language is given, then s is returned as-is. If
charset is given but not language, the string is encoded using the empty
string for language. | [
"Encode",
"string",
"according",
"to",
"RFC",
"2231",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/utils.py#L267-L279 |
224,870 | PythonCharmers/python-future | src/future/backports/email/utils.py | decode_params | def decode_params(params):
"""Decode parameters list according to RFC 2231.
params is a sequence of 2-tuples containing (param name, string value).
"""
# Copy params so we don't mess with the original
params = params[:]
new_params = []
# Map parameter's name to a list of continuations. The values are a
# 3-tuple of the continuation number, the string value, and a flag
# specifying whether a particular segment is %-encoded.
rfc2231_params = {}
name, value = params.pop(0)
new_params.append((name, value))
while params:
name, value = params.pop(0)
if name.endswith('*'):
encoded = True
else:
encoded = False
value = unquote(value)
mo = rfc2231_continuation.match(name)
if mo:
name, num = mo.group('name', 'num')
if num is not None:
num = int(num)
rfc2231_params.setdefault(name, []).append((num, value, encoded))
else:
new_params.append((name, '"%s"' % quote(value)))
if rfc2231_params:
for name, continuations in rfc2231_params.items():
value = []
extended = False
# Sort by number
continuations.sort()
# And now append all values in numerical order, converting
# %-encodings for the encoded segments. If any of the
# continuation names ends in a *, then the entire string, after
# decoding segments and concatenating, must have the charset and
# language specifiers at the beginning of the string.
for num, s, encoded in continuations:
if encoded:
# Decode as "latin-1", so the characters in s directly
# represent the percent-encoded octet values.
# collapse_rfc2231_value treats this as an octet sequence.
s = url_unquote(s, encoding="latin-1")
extended = True
value.append(s)
value = quote(EMPTYSTRING.join(value))
if extended:
charset, language, value = decode_rfc2231(value)
new_params.append((name, (charset, language, '"%s"' % value)))
else:
new_params.append((name, '"%s"' % value))
return new_params | python | def decode_params(params):
# Copy params so we don't mess with the original
params = params[:]
new_params = []
# Map parameter's name to a list of continuations. The values are a
# 3-tuple of the continuation number, the string value, and a flag
# specifying whether a particular segment is %-encoded.
rfc2231_params = {}
name, value = params.pop(0)
new_params.append((name, value))
while params:
name, value = params.pop(0)
if name.endswith('*'):
encoded = True
else:
encoded = False
value = unquote(value)
mo = rfc2231_continuation.match(name)
if mo:
name, num = mo.group('name', 'num')
if num is not None:
num = int(num)
rfc2231_params.setdefault(name, []).append((num, value, encoded))
else:
new_params.append((name, '"%s"' % quote(value)))
if rfc2231_params:
for name, continuations in rfc2231_params.items():
value = []
extended = False
# Sort by number
continuations.sort()
# And now append all values in numerical order, converting
# %-encodings for the encoded segments. If any of the
# continuation names ends in a *, then the entire string, after
# decoding segments and concatenating, must have the charset and
# language specifiers at the beginning of the string.
for num, s, encoded in continuations:
if encoded:
# Decode as "latin-1", so the characters in s directly
# represent the percent-encoded octet values.
# collapse_rfc2231_value treats this as an octet sequence.
s = url_unquote(s, encoding="latin-1")
extended = True
value.append(s)
value = quote(EMPTYSTRING.join(value))
if extended:
charset, language, value = decode_rfc2231(value)
new_params.append((name, (charset, language, '"%s"' % value)))
else:
new_params.append((name, '"%s"' % value))
return new_params | [
"def",
"decode_params",
"(",
"params",
")",
":",
"# Copy params so we don't mess with the original",
"params",
"=",
"params",
"[",
":",
"]",
"new_params",
"=",
"[",
"]",
"# Map parameter's name to a list of continuations. The values are a",
"# 3-tuple of the continuation number,... | Decode parameters list according to RFC 2231.
params is a sequence of 2-tuples containing (param name, string value). | [
"Decode",
"parameters",
"list",
"according",
"to",
"RFC",
"2231",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/utils.py#L285-L339 |
224,871 | PythonCharmers/python-future | src/future/backports/email/utils.py | localtime | def localtime(dt=None, isdst=-1):
"""Return local time as an aware datetime object.
If called without arguments, return current time. Otherwise *dt*
argument should be a datetime instance, and it is converted to the
local time zone according to the system time zone database. If *dt* is
naive (that is, dt.tzinfo is None), it is assumed to be in local time.
In this case, a positive or zero value for *isdst* causes localtime to
presume initially that summer time (for example, Daylight Saving Time)
is or is not (respectively) in effect for the specified time. A
negative value for *isdst* causes the localtime() function to attempt
to divine whether summer time is in effect for the specified time.
"""
if dt is None:
return datetime.datetime.now(datetime.timezone.utc).astimezone()
if dt.tzinfo is not None:
return dt.astimezone()
# We have a naive datetime. Convert to a (localtime) timetuple and pass to
# system mktime together with the isdst hint. System mktime will return
# seconds since epoch.
tm = dt.timetuple()[:-1] + (isdst,)
seconds = time.mktime(tm)
localtm = time.localtime(seconds)
try:
delta = datetime.timedelta(seconds=localtm.tm_gmtoff)
tz = datetime.timezone(delta, localtm.tm_zone)
except AttributeError:
# Compute UTC offset and compare with the value implied by tm_isdst.
# If the values match, use the zone name implied by tm_isdst.
delta = dt - datetime.datetime(*time.gmtime(seconds)[:6])
dst = time.daylight and localtm.tm_isdst > 0
gmtoff = -(time.altzone if dst else time.timezone)
if delta == datetime.timedelta(seconds=gmtoff):
tz = datetime.timezone(delta, time.tzname[dst])
else:
tz = datetime.timezone(delta)
return dt.replace(tzinfo=tz) | python | def localtime(dt=None, isdst=-1):
if dt is None:
return datetime.datetime.now(datetime.timezone.utc).astimezone()
if dt.tzinfo is not None:
return dt.astimezone()
# We have a naive datetime. Convert to a (localtime) timetuple and pass to
# system mktime together with the isdst hint. System mktime will return
# seconds since epoch.
tm = dt.timetuple()[:-1] + (isdst,)
seconds = time.mktime(tm)
localtm = time.localtime(seconds)
try:
delta = datetime.timedelta(seconds=localtm.tm_gmtoff)
tz = datetime.timezone(delta, localtm.tm_zone)
except AttributeError:
# Compute UTC offset and compare with the value implied by tm_isdst.
# If the values match, use the zone name implied by tm_isdst.
delta = dt - datetime.datetime(*time.gmtime(seconds)[:6])
dst = time.daylight and localtm.tm_isdst > 0
gmtoff = -(time.altzone if dst else time.timezone)
if delta == datetime.timedelta(seconds=gmtoff):
tz = datetime.timezone(delta, time.tzname[dst])
else:
tz = datetime.timezone(delta)
return dt.replace(tzinfo=tz) | [
"def",
"localtime",
"(",
"dt",
"=",
"None",
",",
"isdst",
"=",
"-",
"1",
")",
":",
"if",
"dt",
"is",
"None",
":",
"return",
"datetime",
".",
"datetime",
".",
"now",
"(",
"datetime",
".",
"timezone",
".",
"utc",
")",
".",
"astimezone",
"(",
")",
"... | Return local time as an aware datetime object.
If called without arguments, return current time. Otherwise *dt*
argument should be a datetime instance, and it is converted to the
local time zone according to the system time zone database. If *dt* is
naive (that is, dt.tzinfo is None), it is assumed to be in local time.
In this case, a positive or zero value for *isdst* causes localtime to
presume initially that summer time (for example, Daylight Saving Time)
is or is not (respectively) in effect for the specified time. A
negative value for *isdst* causes the localtime() function to attempt
to divine whether summer time is in effect for the specified time. | [
"Return",
"local",
"time",
"as",
"an",
"aware",
"datetime",
"object",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/utils.py#L363-L400 |
224,872 | PythonCharmers/python-future | docs/3rd-party-py3k-compat-code/django_utils_encoding.py | filepath_to_uri | def filepath_to_uri(path):
"""Convert a file system path to a URI portion that is suitable for
inclusion in a URL.
We are assuming input is either UTF-8 or unicode already.
This method will encode certain chars that would normally be recognized as
special chars for URIs. Note that this method does not encode the '
character, as it is a valid character within URIs. See
encodeURIComponent() JavaScript function for more details.
Returns an ASCII string containing the encoded result.
"""
if path is None:
return path
# I know about `os.sep` and `os.altsep` but I want to leave
# some flexibility for hardcoding separators.
return quote(force_bytes(path).replace(b"\\", b"/"), safe=b"/~!*()'") | python | def filepath_to_uri(path):
if path is None:
return path
# I know about `os.sep` and `os.altsep` but I want to leave
# some flexibility for hardcoding separators.
return quote(force_bytes(path).replace(b"\\", b"/"), safe=b"/~!*()'") | [
"def",
"filepath_to_uri",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"path",
"# I know about `os.sep` and `os.altsep` but I want to leave",
"# some flexibility for hardcoding separators.",
"return",
"quote",
"(",
"force_bytes",
"(",
"path",
")",
"."... | Convert a file system path to a URI portion that is suitable for
inclusion in a URL.
We are assuming input is either UTF-8 or unicode already.
This method will encode certain chars that would normally be recognized as
special chars for URIs. Note that this method does not encode the '
character, as it is a valid character within URIs. See
encodeURIComponent() JavaScript function for more details.
Returns an ASCII string containing the encoded result. | [
"Convert",
"a",
"file",
"system",
"path",
"to",
"a",
"URI",
"portion",
"that",
"is",
"suitable",
"for",
"inclusion",
"in",
"a",
"URL",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/docs/3rd-party-py3k-compat-code/django_utils_encoding.py#L196-L213 |
224,873 | PythonCharmers/python-future | src/future/backports/email/_encoded_words.py | encode | def encode(string, charset='utf-8', encoding=None, lang=''):
"""Encode string using the CTE encoding that produces the shorter result.
Produces an RFC 2047/2243 encoded word of the form:
=?charset*lang?cte?encoded_string?=
where '*lang' is omitted unless the 'lang' parameter is given a value.
Optional argument charset (defaults to utf-8) specifies the charset to use
to encode the string to binary before CTE encoding it. Optional argument
'encoding' is the cte specifier for the encoding that should be used ('q'
or 'b'); if it is None (the default) the encoding which produces the
shortest encoded sequence is used, except that 'q' is preferred if it is up
to five characters longer. Optional argument 'lang' (default '') gives the
RFC 2243 language string to specify in the encoded word.
"""
string = str(string)
if charset == 'unknown-8bit':
bstring = string.encode('ascii', 'surrogateescape')
else:
bstring = string.encode(charset)
if encoding is None:
qlen = _cte_encode_length['q'](bstring)
blen = _cte_encode_length['b'](bstring)
# Bias toward q. 5 is arbitrary.
encoding = 'q' if qlen - blen < 5 else 'b'
encoded = _cte_encoders[encoding](bstring)
if lang:
lang = '*' + lang
return "=?{0}{1}?{2}?{3}?=".format(charset, lang, encoding, encoded) | python | def encode(string, charset='utf-8', encoding=None, lang=''):
string = str(string)
if charset == 'unknown-8bit':
bstring = string.encode('ascii', 'surrogateescape')
else:
bstring = string.encode(charset)
if encoding is None:
qlen = _cte_encode_length['q'](bstring)
blen = _cte_encode_length['b'](bstring)
# Bias toward q. 5 is arbitrary.
encoding = 'q' if qlen - blen < 5 else 'b'
encoded = _cte_encoders[encoding](bstring)
if lang:
lang = '*' + lang
return "=?{0}{1}?{2}?{3}?=".format(charset, lang, encoding, encoded) | [
"def",
"encode",
"(",
"string",
",",
"charset",
"=",
"'utf-8'",
",",
"encoding",
"=",
"None",
",",
"lang",
"=",
"''",
")",
":",
"string",
"=",
"str",
"(",
"string",
")",
"if",
"charset",
"==",
"'unknown-8bit'",
":",
"bstring",
"=",
"string",
".",
"en... | Encode string using the CTE encoding that produces the shorter result.
Produces an RFC 2047/2243 encoded word of the form:
=?charset*lang?cte?encoded_string?=
where '*lang' is omitted unless the 'lang' parameter is given a value.
Optional argument charset (defaults to utf-8) specifies the charset to use
to encode the string to binary before CTE encoding it. Optional argument
'encoding' is the cte specifier for the encoding that should be used ('q'
or 'b'); if it is None (the default) the encoding which produces the
shortest encoded sequence is used, except that 'q' is preferred if it is up
to five characters longer. Optional argument 'lang' (default '') gives the
RFC 2243 language string to specify in the encoded word. | [
"Encode",
"string",
"using",
"the",
"CTE",
"encoding",
"that",
"produces",
"the",
"shorter",
"result",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_encoded_words.py#L202-L232 |
224,874 | PythonCharmers/python-future | docs/3rd-party-py3k-compat-code/pandas_py3k.py | bind_method | def bind_method(cls, name, func):
"""Bind a method to class, python 2 and python 3 compatible.
Parameters
----------
cls : type
class to receive bound method
name : basestring
name of method on class instance
func : function
function to be bound as method
Returns
-------
None
"""
# only python 2 has bound/unbound method issue
if not PY3:
setattr(cls, name, types.MethodType(func, None, cls))
else:
setattr(cls, name, func) | python | def bind_method(cls, name, func):
# only python 2 has bound/unbound method issue
if not PY3:
setattr(cls, name, types.MethodType(func, None, cls))
else:
setattr(cls, name, func) | [
"def",
"bind_method",
"(",
"cls",
",",
"name",
",",
"func",
")",
":",
"# only python 2 has bound/unbound method issue",
"if",
"not",
"PY3",
":",
"setattr",
"(",
"cls",
",",
"name",
",",
"types",
".",
"MethodType",
"(",
"func",
",",
"None",
",",
"cls",
")",... | Bind a method to class, python 2 and python 3 compatible.
Parameters
----------
cls : type
class to receive bound method
name : basestring
name of method on class instance
func : function
function to be bound as method
Returns
-------
None | [
"Bind",
"a",
"method",
"to",
"class",
"python",
"2",
"and",
"python",
"3",
"compatible",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/docs/3rd-party-py3k-compat-code/pandas_py3k.py#L139-L161 |
224,875 | PythonCharmers/python-future | src/future/backports/email/_policybase.py | _PolicyBase.clone | def clone(self, **kw):
"""Return a new instance with specified attributes changed.
The new instance has the same attribute values as the current object,
except for the changes passed in as keyword arguments.
"""
newpolicy = self.__class__.__new__(self.__class__)
for attr, value in self.__dict__.items():
object.__setattr__(newpolicy, attr, value)
for attr, value in kw.items():
if not hasattr(self, attr):
raise TypeError(
"{!r} is an invalid keyword argument for {}".format(
attr, self.__class__.__name__))
object.__setattr__(newpolicy, attr, value)
return newpolicy | python | def clone(self, **kw):
newpolicy = self.__class__.__new__(self.__class__)
for attr, value in self.__dict__.items():
object.__setattr__(newpolicy, attr, value)
for attr, value in kw.items():
if not hasattr(self, attr):
raise TypeError(
"{!r} is an invalid keyword argument for {}".format(
attr, self.__class__.__name__))
object.__setattr__(newpolicy, attr, value)
return newpolicy | [
"def",
"clone",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"newpolicy",
"=",
"self",
".",
"__class__",
".",
"__new__",
"(",
"self",
".",
"__class__",
")",
"for",
"attr",
",",
"value",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"... | Return a new instance with specified attributes changed.
The new instance has the same attribute values as the current object,
except for the changes passed in as keyword arguments. | [
"Return",
"a",
"new",
"instance",
"with",
"specified",
"attributes",
"changed",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_policybase.py#L67-L83 |
224,876 | PythonCharmers/python-future | src/future/backports/email/_policybase.py | Policy.handle_defect | def handle_defect(self, obj, defect):
"""Based on policy, either raise defect or call register_defect.
handle_defect(obj, defect)
defect should be a Defect subclass, but in any case must be an
Exception subclass. obj is the object on which the defect should be
registered if it is not raised. If the raise_on_defect is True, the
defect is raised as an error, otherwise the object and the defect are
passed to register_defect.
This method is intended to be called by parsers that discover defects.
The email package parsers always call it with Defect instances.
"""
if self.raise_on_defect:
raise defect
self.register_defect(obj, defect) | python | def handle_defect(self, obj, defect):
if self.raise_on_defect:
raise defect
self.register_defect(obj, defect) | [
"def",
"handle_defect",
"(",
"self",
",",
"obj",
",",
"defect",
")",
":",
"if",
"self",
".",
"raise_on_defect",
":",
"raise",
"defect",
"self",
".",
"register_defect",
"(",
"obj",
",",
"defect",
")"
] | Based on policy, either raise defect or call register_defect.
handle_defect(obj, defect)
defect should be a Defect subclass, but in any case must be an
Exception subclass. obj is the object on which the defect should be
registered if it is not raised. If the raise_on_defect is True, the
defect is raised as an error, otherwise the object and the defect are
passed to register_defect.
This method is intended to be called by parsers that discover defects.
The email package parsers always call it with Defect instances. | [
"Based",
"on",
"policy",
"either",
"raise",
"defect",
"or",
"call",
"register_defect",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_policybase.py#L166-L183 |
224,877 | PythonCharmers/python-future | src/future/backports/http/cookies.py | _quote | def _quote(str, LegalChars=_LegalChars):
r"""Quote a string for use in a cookie header.
If the string does not need to be double-quoted, then just return the
string. Otherwise, surround the string in doublequotes and quote
(with a \) special characters.
"""
if all(c in LegalChars for c in str):
return str
else:
return '"' + _nulljoin(_Translator.get(s, s) for s in str) + '"' | python | def _quote(str, LegalChars=_LegalChars):
r"""Quote a string for use in a cookie header.
If the string does not need to be double-quoted, then just return the
string. Otherwise, surround the string in doublequotes and quote
(with a \) special characters.
"""
if all(c in LegalChars for c in str):
return str
else:
return '"' + _nulljoin(_Translator.get(s, s) for s in str) + '"' | [
"def",
"_quote",
"(",
"str",
",",
"LegalChars",
"=",
"_LegalChars",
")",
":",
"if",
"all",
"(",
"c",
"in",
"LegalChars",
"for",
"c",
"in",
"str",
")",
":",
"return",
"str",
"else",
":",
"return",
"'\"'",
"+",
"_nulljoin",
"(",
"_Translator",
".",
"ge... | r"""Quote a string for use in a cookie header.
If the string does not need to be double-quoted, then just return the
string. Otherwise, surround the string in doublequotes and quote
(with a \) special characters. | [
"r",
"Quote",
"a",
"string",
"for",
"use",
"in",
"a",
"cookie",
"header",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookies.py#L235-L245 |
224,878 | PythonCharmers/python-future | src/future/backports/http/cookies.py | BaseCookie.output | def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
"""Return a string suitable for HTTP."""
result = []
items = sorted(self.items())
for key, value in items:
result.append(value.output(attrs, header))
return sep.join(result) | python | def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
result = []
items = sorted(self.items())
for key, value in items:
result.append(value.output(attrs, header))
return sep.join(result) | [
"def",
"output",
"(",
"self",
",",
"attrs",
"=",
"None",
",",
"header",
"=",
"\"Set-Cookie:\"",
",",
"sep",
"=",
"\"\\015\\012\"",
")",
":",
"result",
"=",
"[",
"]",
"items",
"=",
"sorted",
"(",
"self",
".",
"items",
"(",
")",
")",
"for",
"key",
",... | Return a string suitable for HTTP. | [
"Return",
"a",
"string",
"suitable",
"for",
"HTTP",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookies.py#L506-L512 |
224,879 | PythonCharmers/python-future | src/future/backports/http/cookies.py | BaseCookie.js_output | def js_output(self, attrs=None):
"""Return a string suitable for JavaScript."""
result = []
items = sorted(self.items())
for key, value in items:
result.append(value.js_output(attrs))
return _nulljoin(result) | python | def js_output(self, attrs=None):
result = []
items = sorted(self.items())
for key, value in items:
result.append(value.js_output(attrs))
return _nulljoin(result) | [
"def",
"js_output",
"(",
"self",
",",
"attrs",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"items",
"=",
"sorted",
"(",
"self",
".",
"items",
"(",
")",
")",
"for",
"key",
",",
"value",
"in",
"items",
":",
"result",
".",
"append",
"(",
"value"... | Return a string suitable for JavaScript. | [
"Return",
"a",
"string",
"suitable",
"for",
"JavaScript",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookies.py#L528-L534 |
224,880 | PythonCharmers/python-future | src/future/backports/email/mime/audio.py | _whatsnd | def _whatsnd(data):
"""Try to identify a sound file type.
sndhdr.what() has a pretty cruddy interface, unfortunately. This is why
we re-do it here. It would be easier to reverse engineer the Unix 'file'
command and use the standard 'magic' file, as shipped with a modern Unix.
"""
hdr = data[:512]
fakefile = BytesIO(hdr)
for testfn in sndhdr.tests:
res = testfn(hdr, fakefile)
if res is not None:
return _sndhdr_MIMEmap.get(res[0])
return None | python | def _whatsnd(data):
hdr = data[:512]
fakefile = BytesIO(hdr)
for testfn in sndhdr.tests:
res = testfn(hdr, fakefile)
if res is not None:
return _sndhdr_MIMEmap.get(res[0])
return None | [
"def",
"_whatsnd",
"(",
"data",
")",
":",
"hdr",
"=",
"data",
"[",
":",
"512",
"]",
"fakefile",
"=",
"BytesIO",
"(",
"hdr",
")",
"for",
"testfn",
"in",
"sndhdr",
".",
"tests",
":",
"res",
"=",
"testfn",
"(",
"hdr",
",",
"fakefile",
")",
"if",
"re... | Try to identify a sound file type.
sndhdr.what() has a pretty cruddy interface, unfortunately. This is why
we re-do it here. It would be easier to reverse engineer the Unix 'file'
command and use the standard 'magic' file, as shipped with a modern Unix. | [
"Try",
"to",
"identify",
"a",
"sound",
"file",
"type",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/mime/audio.py#L27-L40 |
224,881 | PythonCharmers/python-future | src/libfuturize/fixes/fix_metaclass.py | fixup_parse_tree | def fixup_parse_tree(cls_node):
""" one-line classes don't get a suite in the parse tree so we add
one to normalize the tree
"""
for node in cls_node.children:
if node.type == syms.suite:
# already in the preferred format, do nothing
return
# !%@#! oneliners have no suite node, we have to fake one up
for i, node in enumerate(cls_node.children):
if node.type == token.COLON:
break
else:
raise ValueError("No class suite and no ':'!")
# move everything into a suite node
suite = Node(syms.suite, [])
while cls_node.children[i+1:]:
move_node = cls_node.children[i+1]
suite.append_child(move_node.clone())
move_node.remove()
cls_node.append_child(suite)
node = suite | python | def fixup_parse_tree(cls_node):
for node in cls_node.children:
if node.type == syms.suite:
# already in the preferred format, do nothing
return
# !%@#! oneliners have no suite node, we have to fake one up
for i, node in enumerate(cls_node.children):
if node.type == token.COLON:
break
else:
raise ValueError("No class suite and no ':'!")
# move everything into a suite node
suite = Node(syms.suite, [])
while cls_node.children[i+1:]:
move_node = cls_node.children[i+1]
suite.append_child(move_node.clone())
move_node.remove()
cls_node.append_child(suite)
node = suite | [
"def",
"fixup_parse_tree",
"(",
"cls_node",
")",
":",
"for",
"node",
"in",
"cls_node",
".",
"children",
":",
"if",
"node",
".",
"type",
"==",
"syms",
".",
"suite",
":",
"# already in the preferred format, do nothing",
"return",
"# !%@#! oneliners have no suite node, w... | one-line classes don't get a suite in the parse tree so we add
one to normalize the tree | [
"one",
"-",
"line",
"classes",
"don",
"t",
"get",
"a",
"suite",
"in",
"the",
"parse",
"tree",
"so",
"we",
"add",
"one",
"to",
"normalize",
"the",
"tree"
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libfuturize/fixes/fix_metaclass.py#L57-L80 |
224,882 | PythonCharmers/python-future | src/future/types/newbytes.py | newbytes.index | def index(self, sub, *args):
'''
Returns index of sub in bytes.
Raises ValueError if byte is not in bytes and TypeError if can't
be converted bytes or its length is not 1.
'''
if isinstance(sub, int):
if len(args) == 0:
start, end = 0, len(self)
elif len(args) == 1:
start = args[0]
elif len(args) == 2:
start, end = args
else:
raise TypeError('takes at most 3 arguments')
return list(self)[start:end].index(sub)
if not isinstance(sub, bytes):
try:
sub = self.__class__(sub)
except (TypeError, ValueError):
raise TypeError("can't convert sub to bytes")
try:
return super(newbytes, self).index(sub, *args)
except ValueError:
raise ValueError('substring not found') | python | def index(self, sub, *args):
'''
Returns index of sub in bytes.
Raises ValueError if byte is not in bytes and TypeError if can't
be converted bytes or its length is not 1.
'''
if isinstance(sub, int):
if len(args) == 0:
start, end = 0, len(self)
elif len(args) == 1:
start = args[0]
elif len(args) == 2:
start, end = args
else:
raise TypeError('takes at most 3 arguments')
return list(self)[start:end].index(sub)
if not isinstance(sub, bytes):
try:
sub = self.__class__(sub)
except (TypeError, ValueError):
raise TypeError("can't convert sub to bytes")
try:
return super(newbytes, self).index(sub, *args)
except ValueError:
raise ValueError('substring not found') | [
"def",
"index",
"(",
"self",
",",
"sub",
",",
"*",
"args",
")",
":",
"if",
"isinstance",
"(",
"sub",
",",
"int",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"start",
",",
"end",
"=",
"0",
",",
"len",
"(",
"self",
")",
"elif",
"... | Returns index of sub in bytes.
Raises ValueError if byte is not in bytes and TypeError if can't
be converted bytes or its length is not 1. | [
"Returns",
"index",
"of",
"sub",
"in",
"bytes",
".",
"Raises",
"ValueError",
"if",
"byte",
"is",
"not",
"in",
"bytes",
"and",
"TypeError",
"if",
"can",
"t",
"be",
"converted",
"bytes",
"or",
"its",
"length",
"is",
"not",
"1",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/types/newbytes.py#L335-L359 |
224,883 | PythonCharmers/python-future | src/future/utils/__init__.py | isidentifier | def isidentifier(s, dotted=False):
'''
A function equivalent to the str.isidentifier method on Py3
'''
if dotted:
return all(isidentifier(a) for a in s.split('.'))
if PY3:
return s.isidentifier()
else:
import re
_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
return bool(_name_re.match(s)) | python | def isidentifier(s, dotted=False):
'''
A function equivalent to the str.isidentifier method on Py3
'''
if dotted:
return all(isidentifier(a) for a in s.split('.'))
if PY3:
return s.isidentifier()
else:
import re
_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
return bool(_name_re.match(s)) | [
"def",
"isidentifier",
"(",
"s",
",",
"dotted",
"=",
"False",
")",
":",
"if",
"dotted",
":",
"return",
"all",
"(",
"isidentifier",
"(",
"a",
")",
"for",
"a",
"in",
"s",
".",
"split",
"(",
"'.'",
")",
")",
"if",
"PY3",
":",
"return",
"s",
".",
"... | A function equivalent to the str.isidentifier method on Py3 | [
"A",
"function",
"equivalent",
"to",
"the",
"str",
".",
"isidentifier",
"method",
"on",
"Py3"
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/utils/__init__.py#L252-L263 |
224,884 | PythonCharmers/python-future | src/future/utils/__init__.py | viewitems | def viewitems(obj, **kwargs):
"""
Function for iterating over dictionary items with the same set-like
behaviour on Py2.7 as on Py3.
Passes kwargs to method."""
func = getattr(obj, "viewitems", None)
if not func:
func = obj.items
return func(**kwargs) | python | def viewitems(obj, **kwargs):
func = getattr(obj, "viewitems", None)
if not func:
func = obj.items
return func(**kwargs) | [
"def",
"viewitems",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"getattr",
"(",
"obj",
",",
"\"viewitems\"",
",",
"None",
")",
"if",
"not",
"func",
":",
"func",
"=",
"obj",
".",
"items",
"return",
"func",
"(",
"*",
"*",
"kwargs",
... | Function for iterating over dictionary items with the same set-like
behaviour on Py2.7 as on Py3.
Passes kwargs to method. | [
"Function",
"for",
"iterating",
"over",
"dictionary",
"items",
"with",
"the",
"same",
"set",
"-",
"like",
"behaviour",
"on",
"Py2",
".",
"7",
"as",
"on",
"Py3",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/utils/__init__.py#L266-L275 |
224,885 | PythonCharmers/python-future | src/future/utils/__init__.py | viewkeys | def viewkeys(obj, **kwargs):
"""
Function for iterating over dictionary keys with the same set-like
behaviour on Py2.7 as on Py3.
Passes kwargs to method."""
func = getattr(obj, "viewkeys", None)
if not func:
func = obj.keys
return func(**kwargs) | python | def viewkeys(obj, **kwargs):
func = getattr(obj, "viewkeys", None)
if not func:
func = obj.keys
return func(**kwargs) | [
"def",
"viewkeys",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"getattr",
"(",
"obj",
",",
"\"viewkeys\"",
",",
"None",
")",
"if",
"not",
"func",
":",
"func",
"=",
"obj",
".",
"keys",
"return",
"func",
"(",
"*",
"*",
"kwargs",
")"... | Function for iterating over dictionary keys with the same set-like
behaviour on Py2.7 as on Py3.
Passes kwargs to method. | [
"Function",
"for",
"iterating",
"over",
"dictionary",
"keys",
"with",
"the",
"same",
"set",
"-",
"like",
"behaviour",
"on",
"Py2",
".",
"7",
"as",
"on",
"Py3",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/utils/__init__.py#L278-L287 |
224,886 | PythonCharmers/python-future | src/future/utils/__init__.py | viewvalues | def viewvalues(obj, **kwargs):
"""
Function for iterating over dictionary values with the same set-like
behaviour on Py2.7 as on Py3.
Passes kwargs to method."""
func = getattr(obj, "viewvalues", None)
if not func:
func = obj.values
return func(**kwargs) | python | def viewvalues(obj, **kwargs):
func = getattr(obj, "viewvalues", None)
if not func:
func = obj.values
return func(**kwargs) | [
"def",
"viewvalues",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"getattr",
"(",
"obj",
",",
"\"viewvalues\"",
",",
"None",
")",
"if",
"not",
"func",
":",
"func",
"=",
"obj",
".",
"values",
"return",
"func",
"(",
"*",
"*",
"kwargs",... | Function for iterating over dictionary values with the same set-like
behaviour on Py2.7 as on Py3.
Passes kwargs to method. | [
"Function",
"for",
"iterating",
"over",
"dictionary",
"values",
"with",
"the",
"same",
"set",
"-",
"like",
"behaviour",
"on",
"Py2",
".",
"7",
"as",
"on",
"Py3",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/utils/__init__.py#L290-L299 |
224,887 | PythonCharmers/python-future | src/future/utils/__init__.py | _get_caller_globals_and_locals | def _get_caller_globals_and_locals():
"""
Returns the globals and locals of the calling frame.
Is there an alternative to frame hacking here?
"""
caller_frame = inspect.stack()[2]
myglobals = caller_frame[0].f_globals
mylocals = caller_frame[0].f_locals
return myglobals, mylocals | python | def _get_caller_globals_and_locals():
caller_frame = inspect.stack()[2]
myglobals = caller_frame[0].f_globals
mylocals = caller_frame[0].f_locals
return myglobals, mylocals | [
"def",
"_get_caller_globals_and_locals",
"(",
")",
":",
"caller_frame",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"2",
"]",
"myglobals",
"=",
"caller_frame",
"[",
"0",
"]",
".",
"f_globals",
"mylocals",
"=",
"caller_frame",
"[",
"0",
"]",
".",
"f_locals... | Returns the globals and locals of the calling frame.
Is there an alternative to frame hacking here? | [
"Returns",
"the",
"globals",
"and",
"locals",
"of",
"the",
"calling",
"frame",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/utils/__init__.py#L360-L369 |
224,888 | PythonCharmers/python-future | src/future/utils/__init__.py | _repr_strip | def _repr_strip(mystring):
"""
Returns the string without any initial or final quotes.
"""
r = repr(mystring)
if r.startswith("'") and r.endswith("'"):
return r[1:-1]
else:
return r | python | def _repr_strip(mystring):
r = repr(mystring)
if r.startswith("'") and r.endswith("'"):
return r[1:-1]
else:
return r | [
"def",
"_repr_strip",
"(",
"mystring",
")",
":",
"r",
"=",
"repr",
"(",
"mystring",
")",
"if",
"r",
".",
"startswith",
"(",
"\"'\"",
")",
"and",
"r",
".",
"endswith",
"(",
"\"'\"",
")",
":",
"return",
"r",
"[",
"1",
":",
"-",
"1",
"]",
"else",
... | Returns the string without any initial or final quotes. | [
"Returns",
"the",
"string",
"without",
"any",
"initial",
"or",
"final",
"quotes",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/utils/__init__.py#L372-L380 |
224,889 | PythonCharmers/python-future | src/future/utils/__init__.py | as_native_str | def as_native_str(encoding='utf-8'):
'''
A decorator to turn a function or method call that returns text, i.e.
unicode, into one that returns a native platform str.
Use it as a decorator like this::
from __future__ import unicode_literals
class MyClass(object):
@as_native_str(encoding='ascii')
def __repr__(self):
return next(self._iter).upper()
'''
if PY3:
return lambda f: f
else:
def encoder(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs).encode(encoding=encoding)
return wrapper
return encoder | python | def as_native_str(encoding='utf-8'):
'''
A decorator to turn a function or method call that returns text, i.e.
unicode, into one that returns a native platform str.
Use it as a decorator like this::
from __future__ import unicode_literals
class MyClass(object):
@as_native_str(encoding='ascii')
def __repr__(self):
return next(self._iter).upper()
'''
if PY3:
return lambda f: f
else:
def encoder(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs).encode(encoding=encoding)
return wrapper
return encoder | [
"def",
"as_native_str",
"(",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"PY3",
":",
"return",
"lambda",
"f",
":",
"f",
"else",
":",
"def",
"encoder",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
... | A decorator to turn a function or method call that returns text, i.e.
unicode, into one that returns a native platform str.
Use it as a decorator like this::
from __future__ import unicode_literals
class MyClass(object):
@as_native_str(encoding='ascii')
def __repr__(self):
return next(self._iter).upper() | [
"A",
"decorator",
"to",
"turn",
"a",
"function",
"or",
"method",
"call",
"that",
"returns",
"text",
"i",
".",
"e",
".",
"unicode",
"into",
"one",
"that",
"returns",
"a",
"native",
"platform",
"str",
"."
] | c423752879acc05eebc29b0bb9909327bd5c7308 | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/utils/__init__.py#L654-L676 |
224,890 | graphistry/pygraphistry | graphistry/plotter.py | Plotter.bind | def bind(self, source=None, destination=None, node=None,
edge_title=None, edge_label=None, edge_color=None, edge_weight=None,
point_title=None, point_label=None, point_color=None, point_size=None):
"""Relate data attributes to graph structure and visual representation.
To facilitate reuse and replayable notebooks, the binding call is chainable. Invocation does not effect the old binding: it instead returns a new Plotter instance with the new bindings added to the existing ones. Both the old and new bindings can then be used for different graphs.
:param source: Attribute containing an edge's source ID
:type source: String.
:param destination: Attribute containing an edge's destination ID
:type destination: String.
:param node: Attribute containing a node's ID
:type node: String.
:param edge_title: Attribute overriding edge's minimized label text. By default, the edge source and destination is used.
:type edge_title: HtmlString.
:param edge_label: Attribute overriding edge's expanded label text. By default, scrollable list of attribute/value mappings.
:type edge_label: HtmlString.
:param edge_color: Attribute overriding edge's color. `See palette definitions <https://graphistry.github.io/docs/legacy/api/0.9.2/api.html#extendedpalette>`_ for values. Based on Color Brewer.
:type edge_color: String.
:param edge_weight: Attribute overriding edge weight. Default is 1. Advanced layout controls will relayout edges based on this value.
:type edge_weight: String.
:param point_title: Attribute overriding node's minimized label text. By default, the node ID is used.
:type point_title: HtmlString.
:param point_label: Attribute overriding node's expanded label text. By default, scrollable list of attribute/value mappings.
:type point_label: HtmlString.
:param point_color: Attribute overriding node's color. `See palette definitions <https://graphistry.github.io/docs/legacy/api/0.9.2/api.html#extendedpalette>`_ for values. Based on Color Brewer.
:type point_color: Integer.
:param point_size: Attribute overriding node's size. By default, uses the node degree. The visualization will normalize point sizes and adjust dynamically using semantic zoom.
:type point_size: HtmlString.
:returns: Plotter.
:rtype: Plotter.
**Example: Minimal**
::
import graphistry
g = graphistry.bind()
g = g.bind(source='src', destination='dst')
**Example: Node colors**
::
import graphistry
g = graphistry.bind()
g = g.bind(source='src', destination='dst',
node='id', point_color='color')
**Example: Chaining**
::
import graphistry
g = graphistry.bind(source='src', destination='dst', node='id')
g1 = g.bind(point_color='color1', point_size='size1')
g.bind(point_color='color1b')
g2a = g1.bind(point_color='color2a')
g2b = g1.bind(point_color='color2b', point_size='size2b')
g3a = g2a.bind(point_size='size3a')
g3b = g2b.bind(point_size='size3b')
In the above **Chaining** example, all bindings use src/dst/id. Colors and sizes bind to:
::
g: default/default
g1: color1/size1
g2a: color2a/size1
g2b: color2b/size2b
g3a: color2a/size3a
g3b: color2b/size3b
"""
res = copy.copy(self)
res._source = source or self._source
res._destination = destination or self._destination
res._node = node or self._node
res._edge_title = edge_title or self._edge_title
res._edge_label = edge_label or self._edge_label
res._edge_color = edge_color or self._edge_color
res._edge_weight = edge_weight or self._edge_weight
res._point_title = point_title or self._point_title
res._point_label = point_label or self._point_label
res._point_color = point_color or self._point_color
res._point_size = point_size or self._point_size
return res | python | def bind(self, source=None, destination=None, node=None,
edge_title=None, edge_label=None, edge_color=None, edge_weight=None,
point_title=None, point_label=None, point_color=None, point_size=None):
res = copy.copy(self)
res._source = source or self._source
res._destination = destination or self._destination
res._node = node or self._node
res._edge_title = edge_title or self._edge_title
res._edge_label = edge_label or self._edge_label
res._edge_color = edge_color or self._edge_color
res._edge_weight = edge_weight or self._edge_weight
res._point_title = point_title or self._point_title
res._point_label = point_label or self._point_label
res._point_color = point_color or self._point_color
res._point_size = point_size or self._point_size
return res | [
"def",
"bind",
"(",
"self",
",",
"source",
"=",
"None",
",",
"destination",
"=",
"None",
",",
"node",
"=",
"None",
",",
"edge_title",
"=",
"None",
",",
"edge_label",
"=",
"None",
",",
"edge_color",
"=",
"None",
",",
"edge_weight",
"=",
"None",
",",
"... | Relate data attributes to graph structure and visual representation.
To facilitate reuse and replayable notebooks, the binding call is chainable. Invocation does not effect the old binding: it instead returns a new Plotter instance with the new bindings added to the existing ones. Both the old and new bindings can then be used for different graphs.
:param source: Attribute containing an edge's source ID
:type source: String.
:param destination: Attribute containing an edge's destination ID
:type destination: String.
:param node: Attribute containing a node's ID
:type node: String.
:param edge_title: Attribute overriding edge's minimized label text. By default, the edge source and destination is used.
:type edge_title: HtmlString.
:param edge_label: Attribute overriding edge's expanded label text. By default, scrollable list of attribute/value mappings.
:type edge_label: HtmlString.
:param edge_color: Attribute overriding edge's color. `See palette definitions <https://graphistry.github.io/docs/legacy/api/0.9.2/api.html#extendedpalette>`_ for values. Based on Color Brewer.
:type edge_color: String.
:param edge_weight: Attribute overriding edge weight. Default is 1. Advanced layout controls will relayout edges based on this value.
:type edge_weight: String.
:param point_title: Attribute overriding node's minimized label text. By default, the node ID is used.
:type point_title: HtmlString.
:param point_label: Attribute overriding node's expanded label text. By default, scrollable list of attribute/value mappings.
:type point_label: HtmlString.
:param point_color: Attribute overriding node's color. `See palette definitions <https://graphistry.github.io/docs/legacy/api/0.9.2/api.html#extendedpalette>`_ for values. Based on Color Brewer.
:type point_color: Integer.
:param point_size: Attribute overriding node's size. By default, uses the node degree. The visualization will normalize point sizes and adjust dynamically using semantic zoom.
:type point_size: HtmlString.
:returns: Plotter.
:rtype: Plotter.
**Example: Minimal**
::
import graphistry
g = graphistry.bind()
g = g.bind(source='src', destination='dst')
**Example: Node colors**
::
import graphistry
g = graphistry.bind()
g = g.bind(source='src', destination='dst',
node='id', point_color='color')
**Example: Chaining**
::
import graphistry
g = graphistry.bind(source='src', destination='dst', node='id')
g1 = g.bind(point_color='color1', point_size='size1')
g.bind(point_color='color1b')
g2a = g1.bind(point_color='color2a')
g2b = g1.bind(point_color='color2b', point_size='size2b')
g3a = g2a.bind(point_size='size3a')
g3b = g2b.bind(point_size='size3b')
In the above **Chaining** example, all bindings use src/dst/id. Colors and sizes bind to:
::
g: default/default
g1: color1/size1
g2a: color2a/size1
g2b: color2b/size2b
g3a: color2a/size3a
g3b: color2b/size3b | [
"Relate",
"data",
"attributes",
"to",
"graph",
"structure",
"and",
"visual",
"representation",
"."
] | 3dfc50e60232c6f5fedd6e5fa9d3048b606944b8 | https://github.com/graphistry/pygraphistry/blob/3dfc50e60232c6f5fedd6e5fa9d3048b606944b8/graphistry/plotter.py#L68-L170 |
224,891 | graphistry/pygraphistry | graphistry/plotter.py | Plotter.nodes | def nodes(self, nodes):
"""Specify the set of nodes and associated data.
Must include any nodes referenced in the edge list.
:param nodes: Nodes and their attributes.
:type point_size: Pandas dataframe
:returns: Plotter.
:rtype: Plotter.
**Example**
::
import graphistry
es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
g = graphistry
.bind(source='src', destination='dst')
.edges(es)
vs = pandas.DataFrame({'v': [0,1,2], 'lbl': ['a', 'b', 'c']})
g = g.bind(node='v').nodes(vs)
g.plot()
"""
res = copy.copy(self)
res._nodes = nodes
return res | python | def nodes(self, nodes):
res = copy.copy(self)
res._nodes = nodes
return res | [
"def",
"nodes",
"(",
"self",
",",
"nodes",
")",
":",
"res",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"res",
".",
"_nodes",
"=",
"nodes",
"return",
"res"
] | Specify the set of nodes and associated data.
Must include any nodes referenced in the edge list.
:param nodes: Nodes and their attributes.
:type point_size: Pandas dataframe
:returns: Plotter.
:rtype: Plotter.
**Example**
::
import graphistry
es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
g = graphistry
.bind(source='src', destination='dst')
.edges(es)
vs = pandas.DataFrame({'v': [0,1,2], 'lbl': ['a', 'b', 'c']})
g = g.bind(node='v').nodes(vs)
g.plot() | [
"Specify",
"the",
"set",
"of",
"nodes",
"and",
"associated",
"data",
"."
] | 3dfc50e60232c6f5fedd6e5fa9d3048b606944b8 | https://github.com/graphistry/pygraphistry/blob/3dfc50e60232c6f5fedd6e5fa9d3048b606944b8/graphistry/plotter.py#L173-L204 |
224,892 | graphistry/pygraphistry | graphistry/plotter.py | Plotter.edges | def edges(self, edges):
"""Specify edge list data and associated edge attribute values.
:param edges: Edges and their attributes.
:type point_size: Pandas dataframe, NetworkX graph, or IGraph graph.
:returns: Plotter.
:rtype: Plotter.
**Example**
::
import graphistry
df = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
graphistry
.bind(source='src', destination='dst')
.edges(df)
.plot()
"""
res = copy.copy(self)
res._edges = edges
return res | python | def edges(self, edges):
res = copy.copy(self)
res._edges = edges
return res | [
"def",
"edges",
"(",
"self",
",",
"edges",
")",
":",
"res",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"res",
".",
"_edges",
"=",
"edges",
"return",
"res"
] | Specify edge list data and associated edge attribute values.
:param edges: Edges and their attributes.
:type point_size: Pandas dataframe, NetworkX graph, or IGraph graph.
:returns: Plotter.
:rtype: Plotter.
**Example**
::
import graphistry
df = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
graphistry
.bind(source='src', destination='dst')
.edges(df)
.plot() | [
"Specify",
"edge",
"list",
"data",
"and",
"associated",
"edge",
"attribute",
"values",
"."
] | 3dfc50e60232c6f5fedd6e5fa9d3048b606944b8 | https://github.com/graphistry/pygraphistry/blob/3dfc50e60232c6f5fedd6e5fa9d3048b606944b8/graphistry/plotter.py#L207-L230 |
224,893 | graphistry/pygraphistry | graphistry/plotter.py | Plotter.graph | def graph(self, ig):
"""Specify the node and edge data.
:param ig: Graph with node and edge attributes.
:type ig: NetworkX graph or an IGraph graph.
:returns: Plotter.
:rtype: Plotter.
"""
res = copy.copy(self)
res._edges = ig
res._nodes = None
return res | python | def graph(self, ig):
res = copy.copy(self)
res._edges = ig
res._nodes = None
return res | [
"def",
"graph",
"(",
"self",
",",
"ig",
")",
":",
"res",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"res",
".",
"_edges",
"=",
"ig",
"res",
".",
"_nodes",
"=",
"None",
"return",
"res"
] | Specify the node and edge data.
:param ig: Graph with node and edge attributes.
:type ig: NetworkX graph or an IGraph graph.
:returns: Plotter.
:rtype: Plotter. | [
"Specify",
"the",
"node",
"and",
"edge",
"data",
"."
] | 3dfc50e60232c6f5fedd6e5fa9d3048b606944b8 | https://github.com/graphistry/pygraphistry/blob/3dfc50e60232c6f5fedd6e5fa9d3048b606944b8/graphistry/plotter.py#L233-L246 |
224,894 | graphistry/pygraphistry | graphistry/plotter.py | Plotter.settings | def settings(self, height=None, url_params={}, render=None):
"""Specify iframe height and add URL parameter dictionary.
The library takes care of URI component encoding for the dictionary.
:param height: Height in pixels.
:type height: Integer.
:param url_params: Dictionary of querystring parameters to append to the URL.
:type url_params: Dictionary
:param render: Whether to render the visualization using the native notebook environment (default True), or return the visualization URL
:type render: Boolean
"""
res = copy.copy(self)
res._height = height or self._height
res._url_params = dict(self._url_params, **url_params)
res._render = self._render if render == None else render
return res | python | def settings(self, height=None, url_params={}, render=None):
res = copy.copy(self)
res._height = height or self._height
res._url_params = dict(self._url_params, **url_params)
res._render = self._render if render == None else render
return res | [
"def",
"settings",
"(",
"self",
",",
"height",
"=",
"None",
",",
"url_params",
"=",
"{",
"}",
",",
"render",
"=",
"None",
")",
":",
"res",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"res",
".",
"_height",
"=",
"height",
"or",
"self",
".",
"_heig... | Specify iframe height and add URL parameter dictionary.
The library takes care of URI component encoding for the dictionary.
:param height: Height in pixels.
:type height: Integer.
:param url_params: Dictionary of querystring parameters to append to the URL.
:type url_params: Dictionary
:param render: Whether to render the visualization using the native notebook environment (default True), or return the visualization URL
:type render: Boolean | [
"Specify",
"iframe",
"height",
"and",
"add",
"URL",
"parameter",
"dictionary",
"."
] | 3dfc50e60232c6f5fedd6e5fa9d3048b606944b8 | https://github.com/graphistry/pygraphistry/blob/3dfc50e60232c6f5fedd6e5fa9d3048b606944b8/graphistry/plotter.py#L249-L269 |
224,895 | graphistry/pygraphistry | graphistry/plotter.py | Plotter.plot | def plot(self, graph=None, nodes=None, name=None, render=None, skip_upload=False):
"""Upload data to the Graphistry server and show as an iframe of it.
name, Uses the currently bound schema structure and visual encodings.
Optional parameters override the current bindings.
When used in a notebook environment, will also show an iframe of the visualization.
:param graph: Edge table or graph.
:type graph: Pandas dataframe, NetworkX graph, or IGraph graph.
:param nodes: Nodes table.
:type nodes: Pandas dataframe.
:param render: Whether to render the visualization using the native notebook environment (default True), or return the visualization URL
:type render: Boolean
:param skip_upload: Return node/edge/bindings that would have been uploaded. By default, upload happens.
:type skip_upload: Boolean.
**Example: Simple**
::
import graphistry
es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
graphistry
.bind(source='src', destination='dst')
.edges(es)
.plot()
**Example: Shorthand**
::
import graphistry
es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
graphistry
.bind(source='src', destination='dst')
.plot(es)
"""
if graph is None:
if self._edges is None:
util.error('Graph/edges must be specified.')
g = self._edges
else:
g = graph
n = self._nodes if nodes is None else nodes
name = name or util.random_string(10)
self._check_mandatory_bindings(not isinstance(n, type(None)))
api_version = PyGraphistry.api_version()
if (api_version == 1):
dataset = self._plot_dispatch(g, n, name, 'json')
if skip_upload:
return dataset
info = PyGraphistry._etl1(dataset)
elif (api_version == 2):
dataset = self._plot_dispatch(g, n, name, 'vgraph')
if skip_upload:
return dataset
info = PyGraphistry._etl2(dataset)
viz_url = PyGraphistry._viz_url(info, self._url_params)
full_url = '%s:%s' % (PyGraphistry._config['protocol'], viz_url)
if render == False or (render == None and not self._render):
return full_url
elif util.in_ipython():
from IPython.core.display import HTML
return HTML(util.make_iframe(viz_url, self._height, PyGraphistry._config['protocol']))
else:
import webbrowser
webbrowser.open(full_url)
return full_url | python | def plot(self, graph=None, nodes=None, name=None, render=None, skip_upload=False):
if graph is None:
if self._edges is None:
util.error('Graph/edges must be specified.')
g = self._edges
else:
g = graph
n = self._nodes if nodes is None else nodes
name = name or util.random_string(10)
self._check_mandatory_bindings(not isinstance(n, type(None)))
api_version = PyGraphistry.api_version()
if (api_version == 1):
dataset = self._plot_dispatch(g, n, name, 'json')
if skip_upload:
return dataset
info = PyGraphistry._etl1(dataset)
elif (api_version == 2):
dataset = self._plot_dispatch(g, n, name, 'vgraph')
if skip_upload:
return dataset
info = PyGraphistry._etl2(dataset)
viz_url = PyGraphistry._viz_url(info, self._url_params)
full_url = '%s:%s' % (PyGraphistry._config['protocol'], viz_url)
if render == False or (render == None and not self._render):
return full_url
elif util.in_ipython():
from IPython.core.display import HTML
return HTML(util.make_iframe(viz_url, self._height, PyGraphistry._config['protocol']))
else:
import webbrowser
webbrowser.open(full_url)
return full_url | [
"def",
"plot",
"(",
"self",
",",
"graph",
"=",
"None",
",",
"nodes",
"=",
"None",
",",
"name",
"=",
"None",
",",
"render",
"=",
"None",
",",
"skip_upload",
"=",
"False",
")",
":",
"if",
"graph",
"is",
"None",
":",
"if",
"self",
".",
"_edges",
"is... | Upload data to the Graphistry server and show as an iframe of it.
name, Uses the currently bound schema structure and visual encodings.
Optional parameters override the current bindings.
When used in a notebook environment, will also show an iframe of the visualization.
:param graph: Edge table or graph.
:type graph: Pandas dataframe, NetworkX graph, or IGraph graph.
:param nodes: Nodes table.
:type nodes: Pandas dataframe.
:param render: Whether to render the visualization using the native notebook environment (default True), or return the visualization URL
:type render: Boolean
:param skip_upload: Return node/edge/bindings that would have been uploaded. By default, upload happens.
:type skip_upload: Boolean.
**Example: Simple**
::
import graphistry
es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
graphistry
.bind(source='src', destination='dst')
.edges(es)
.plot()
**Example: Shorthand**
::
import graphistry
es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
graphistry
.bind(source='src', destination='dst')
.plot(es) | [
"Upload",
"data",
"to",
"the",
"Graphistry",
"server",
"and",
"show",
"as",
"an",
"iframe",
"of",
"it",
"."
] | 3dfc50e60232c6f5fedd6e5fa9d3048b606944b8 | https://github.com/graphistry/pygraphistry/blob/3dfc50e60232c6f5fedd6e5fa9d3048b606944b8/graphistry/plotter.py#L272-L347 |
224,896 | graphistry/pygraphistry | graphistry/plotter.py | Plotter.pandas2igraph | def pandas2igraph(self, edges, directed=True):
"""Convert a pandas edge dataframe to an IGraph graph.
Uses current bindings. Defaults to treating edges as directed.
**Example**
::
import graphistry
g = graphistry.bind()
es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
g = g.bind(source='src', destination='dst')
ig = g.pandas2igraph(es)
ig.vs['community'] = ig.community_infomap().membership
g.bind(point_color='community').plot(ig)
"""
import igraph
self._check_mandatory_bindings(False)
self._check_bound_attribs(edges, ['source', 'destination'], 'Edge')
self._node = self._node or Plotter._defaultNodeId
eattribs = edges.columns.values.tolist()
eattribs.remove(self._source)
eattribs.remove(self._destination)
cols = [self._source, self._destination] + eattribs
etuples = [tuple(x) for x in edges[cols].values]
return igraph.Graph.TupleList(etuples, directed=directed, edge_attrs=eattribs,
vertex_name_attr=self._node) | python | def pandas2igraph(self, edges, directed=True):
import igraph
self._check_mandatory_bindings(False)
self._check_bound_attribs(edges, ['source', 'destination'], 'Edge')
self._node = self._node or Plotter._defaultNodeId
eattribs = edges.columns.values.tolist()
eattribs.remove(self._source)
eattribs.remove(self._destination)
cols = [self._source, self._destination] + eattribs
etuples = [tuple(x) for x in edges[cols].values]
return igraph.Graph.TupleList(etuples, directed=directed, edge_attrs=eattribs,
vertex_name_attr=self._node) | [
"def",
"pandas2igraph",
"(",
"self",
",",
"edges",
",",
"directed",
"=",
"True",
")",
":",
"import",
"igraph",
"self",
".",
"_check_mandatory_bindings",
"(",
"False",
")",
"self",
".",
"_check_bound_attribs",
"(",
"edges",
",",
"[",
"'source'",
",",
"'destin... | Convert a pandas edge dataframe to an IGraph graph.
Uses current bindings. Defaults to treating edges as directed.
**Example**
::
import graphistry
g = graphistry.bind()
es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
g = g.bind(source='src', destination='dst')
ig = g.pandas2igraph(es)
ig.vs['community'] = ig.community_infomap().membership
g.bind(point_color='community').plot(ig) | [
"Convert",
"a",
"pandas",
"edge",
"dataframe",
"to",
"an",
"IGraph",
"graph",
"."
] | 3dfc50e60232c6f5fedd6e5fa9d3048b606944b8 | https://github.com/graphistry/pygraphistry/blob/3dfc50e60232c6f5fedd6e5fa9d3048b606944b8/graphistry/plotter.py#L350-L381 |
224,897 | graphistry/pygraphistry | graphistry/plotter.py | Plotter.igraph2pandas | def igraph2pandas(self, ig):
"""Under current bindings, transform an IGraph into a pandas edges dataframe and a nodes dataframe.
**Example**
::
import graphistry
g = graphistry.bind()
es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
g = g.bind(source='src', destination='dst').edges(es)
ig = g.pandas2igraph(es)
ig.vs['community'] = ig.community_infomap().membership
(es2, vs2) = g.igraph2pandas(ig)
g.nodes(vs2).bind(point_color='community').plot()
"""
def get_edgelist(ig):
idmap = dict(enumerate(ig.vs[self._node]))
for e in ig.es:
t = e.tuple
yield dict({self._source: idmap[t[0]], self._destination: idmap[t[1]]},
**e.attributes())
self._check_mandatory_bindings(False)
if self._node is None:
ig.vs[Plotter._defaultNodeId] = [v.index for v in ig.vs]
self._node = Plotter._defaultNodeId
elif self._node not in ig.vs.attributes():
util.error('Vertex attribute "%s" bound to "node" does not exist.' % self._node)
edata = get_edgelist(ig)
ndata = [v.attributes() for v in ig.vs]
nodes = pandas.DataFrame(ndata, columns=ig.vs.attributes())
cols = [self._source, self._destination] + ig.es.attributes()
edges = pandas.DataFrame(edata, columns=cols)
return (edges, nodes) | python | def igraph2pandas(self, ig):
def get_edgelist(ig):
idmap = dict(enumerate(ig.vs[self._node]))
for e in ig.es:
t = e.tuple
yield dict({self._source: idmap[t[0]], self._destination: idmap[t[1]]},
**e.attributes())
self._check_mandatory_bindings(False)
if self._node is None:
ig.vs[Plotter._defaultNodeId] = [v.index for v in ig.vs]
self._node = Plotter._defaultNodeId
elif self._node not in ig.vs.attributes():
util.error('Vertex attribute "%s" bound to "node" does not exist.' % self._node)
edata = get_edgelist(ig)
ndata = [v.attributes() for v in ig.vs]
nodes = pandas.DataFrame(ndata, columns=ig.vs.attributes())
cols = [self._source, self._destination] + ig.es.attributes()
edges = pandas.DataFrame(edata, columns=cols)
return (edges, nodes) | [
"def",
"igraph2pandas",
"(",
"self",
",",
"ig",
")",
":",
"def",
"get_edgelist",
"(",
"ig",
")",
":",
"idmap",
"=",
"dict",
"(",
"enumerate",
"(",
"ig",
".",
"vs",
"[",
"self",
".",
"_node",
"]",
")",
")",
"for",
"e",
"in",
"ig",
".",
"es",
":"... | Under current bindings, transform an IGraph into a pandas edges dataframe and a nodes dataframe.
**Example**
::
import graphistry
g = graphistry.bind()
es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
g = g.bind(source='src', destination='dst').edges(es)
ig = g.pandas2igraph(es)
ig.vs['community'] = ig.community_infomap().membership
(es2, vs2) = g.igraph2pandas(ig)
g.nodes(vs2).bind(point_color='community').plot() | [
"Under",
"current",
"bindings",
"transform",
"an",
"IGraph",
"into",
"a",
"pandas",
"edges",
"dataframe",
"and",
"a",
"nodes",
"dataframe",
"."
] | 3dfc50e60232c6f5fedd6e5fa9d3048b606944b8 | https://github.com/graphistry/pygraphistry/blob/3dfc50e60232c6f5fedd6e5fa9d3048b606944b8/graphistry/plotter.py#L384-L422 |
224,898 | graphistry/pygraphistry | graphistry/pygraphistry.py | PyGraphistry.authenticate | def authenticate():
"""Authenticate via already provided configuration.
This is called once automatically per session when uploading and rendering a visualization."""
key = PyGraphistry.api_key()
#Mocks may set to True, so bypass in that case
if (key is None) and PyGraphistry._is_authenticated == False:
util.error('API key not set explicitly in `register()` or available at ' + EnvVarNames['api_key'])
if not PyGraphistry._is_authenticated:
PyGraphistry._check_key_and_version()
PyGraphistry._is_authenticated = True | python | def authenticate():
key = PyGraphistry.api_key()
#Mocks may set to True, so bypass in that case
if (key is None) and PyGraphistry._is_authenticated == False:
util.error('API key not set explicitly in `register()` or available at ' + EnvVarNames['api_key'])
if not PyGraphistry._is_authenticated:
PyGraphistry._check_key_and_version()
PyGraphistry._is_authenticated = True | [
"def",
"authenticate",
"(",
")",
":",
"key",
"=",
"PyGraphistry",
".",
"api_key",
"(",
")",
"#Mocks may set to True, so bypass in that case",
"if",
"(",
"key",
"is",
"None",
")",
"and",
"PyGraphistry",
".",
"_is_authenticated",
"==",
"False",
":",
"util",
".",
... | Authenticate via already provided configuration.
This is called once automatically per session when uploading and rendering a visualization. | [
"Authenticate",
"via",
"already",
"provided",
"configuration",
".",
"This",
"is",
"called",
"once",
"automatically",
"per",
"session",
"when",
"uploading",
"and",
"rendering",
"a",
"visualization",
"."
] | 3dfc50e60232c6f5fedd6e5fa9d3048b606944b8 | https://github.com/graphistry/pygraphistry/blob/3dfc50e60232c6f5fedd6e5fa9d3048b606944b8/graphistry/pygraphistry.py#L84-L93 |
224,899 | graphistry/pygraphistry | graphistry/pygraphistry.py | PyGraphistry.api_key | def api_key(value=None):
"""Set or get the API key.
Also set via environment variable GRAPHISTRY_API_KEY."""
if value is None:
return PyGraphistry._config['api_key']
# setter
if value is not PyGraphistry._config['api_key']:
PyGraphistry._config['api_key'] = value.strip()
PyGraphistry._is_authenticated = False | python | def api_key(value=None):
if value is None:
return PyGraphistry._config['api_key']
# setter
if value is not PyGraphistry._config['api_key']:
PyGraphistry._config['api_key'] = value.strip()
PyGraphistry._is_authenticated = False | [
"def",
"api_key",
"(",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"PyGraphistry",
".",
"_config",
"[",
"'api_key'",
"]",
"# setter",
"if",
"value",
"is",
"not",
"PyGraphistry",
".",
"_config",
"[",
"'api_key'",
"]",
":",
... | Set or get the API key.
Also set via environment variable GRAPHISTRY_API_KEY. | [
"Set",
"or",
"get",
"the",
"API",
"key",
".",
"Also",
"set",
"via",
"environment",
"variable",
"GRAPHISTRY_API_KEY",
"."
] | 3dfc50e60232c6f5fedd6e5fa9d3048b606944b8 | https://github.com/graphistry/pygraphistry/blob/3dfc50e60232c6f5fedd6e5fa9d3048b606944b8/graphistry/pygraphistry.py#L117-L127 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.