repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
eonpatapon/contrail-api-cli | contrail_api_cli/utils.py | continue_prompt | def continue_prompt(message=""):
"""Prompt the user to continue or not
Returns True when the user type Yes.
:param message: message to display
:type message: str
:rtype: bool
"""
answer = False
message = message + "\n'Yes' or 'No' to continue: "
while answer not in ('Yes', 'No'):
answer = prompt(message, eventloop=eventloop())
if answer == "Yes":
answer = True
break
if answer == "No":
answer = False
break
return answer | python | def continue_prompt(message=""):
"""Prompt the user to continue or not
Returns True when the user type Yes.
:param message: message to display
:type message: str
:rtype: bool
"""
answer = False
message = message + "\n'Yes' or 'No' to continue: "
while answer not in ('Yes', 'No'):
answer = prompt(message, eventloop=eventloop())
if answer == "Yes":
answer = True
break
if answer == "No":
answer = False
break
return answer | [
"def",
"continue_prompt",
"(",
"message",
"=",
"\"\"",
")",
":",
"answer",
"=",
"False",
"message",
"=",
"message",
"+",
"\"\\n'Yes' or 'No' to continue: \"",
"while",
"answer",
"not",
"in",
"(",
"'Yes'",
",",
"'No'",
")",
":",
"answer",
"=",
"prompt",
"(",
"message",
",",
"eventloop",
"=",
"eventloop",
"(",
")",
")",
"if",
"answer",
"==",
"\"Yes\"",
":",
"answer",
"=",
"True",
"break",
"if",
"answer",
"==",
"\"No\"",
":",
"answer",
"=",
"False",
"break",
"return",
"answer"
] | Prompt the user to continue or not
Returns True when the user type Yes.
:param message: message to display
:type message: str
:rtype: bool | [
"Prompt",
"the",
"user",
"to",
"continue",
"or",
"not"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/utils.py#L216-L236 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/utils.py | printo | def printo(msg, encoding=None, errors='replace', std_type='stdout'):
"""Write msg on stdout. If no encoding is specified
the detected encoding of stdout is used. If the encoding
can't encode some chars they are replaced by '?'
:param msg: message
:type msg: unicode on python2 | str on python3
"""
std = getattr(sys, std_type, sys.stdout)
if encoding is None:
try:
encoding = std.encoding
except AttributeError:
encoding = None
# Fallback to ascii if no encoding is found
if encoding is None:
encoding = 'ascii'
# https://docs.python.org/3/library/sys.html#sys.stdout
# write in the binary buffer directly in python3
if hasattr(std, 'buffer'):
std = std.buffer
std.write(msg.encode(encoding, errors=errors))
std.write(b'\n')
std.flush() | python | def printo(msg, encoding=None, errors='replace', std_type='stdout'):
"""Write msg on stdout. If no encoding is specified
the detected encoding of stdout is used. If the encoding
can't encode some chars they are replaced by '?'
:param msg: message
:type msg: unicode on python2 | str on python3
"""
std = getattr(sys, std_type, sys.stdout)
if encoding is None:
try:
encoding = std.encoding
except AttributeError:
encoding = None
# Fallback to ascii if no encoding is found
if encoding is None:
encoding = 'ascii'
# https://docs.python.org/3/library/sys.html#sys.stdout
# write in the binary buffer directly in python3
if hasattr(std, 'buffer'):
std = std.buffer
std.write(msg.encode(encoding, errors=errors))
std.write(b'\n')
std.flush() | [
"def",
"printo",
"(",
"msg",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'replace'",
",",
"std_type",
"=",
"'stdout'",
")",
":",
"std",
"=",
"getattr",
"(",
"sys",
",",
"std_type",
",",
"sys",
".",
"stdout",
")",
"if",
"encoding",
"is",
"None",
":",
"try",
":",
"encoding",
"=",
"std",
".",
"encoding",
"except",
"AttributeError",
":",
"encoding",
"=",
"None",
"# Fallback to ascii if no encoding is found",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"'ascii'",
"# https://docs.python.org/3/library/sys.html#sys.stdout",
"# write in the binary buffer directly in python3",
"if",
"hasattr",
"(",
"std",
",",
"'buffer'",
")",
":",
"std",
"=",
"std",
".",
"buffer",
"std",
".",
"write",
"(",
"msg",
".",
"encode",
"(",
"encoding",
",",
"errors",
"=",
"errors",
")",
")",
"std",
".",
"write",
"(",
"b'\\n'",
")",
"std",
".",
"flush",
"(",
")"
] | Write msg on stdout. If no encoding is specified
the detected encoding of stdout is used. If the encoding
can't encode some chars they are replaced by '?'
:param msg: message
:type msg: unicode on python2 | str on python3 | [
"Write",
"msg",
"on",
"stdout",
".",
"If",
"no",
"encoding",
"is",
"specified",
"the",
"detected",
"encoding",
"of",
"stdout",
"is",
"used",
".",
"If",
"the",
"encoding",
"can",
"t",
"encode",
"some",
"chars",
"they",
"are",
"replaced",
"by",
"?"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/utils.py#L281-L304 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/utils.py | format_tree | def format_tree(tree):
"""Format a python tree structure
Given the python tree::
tree = {
'node': ['ROOT', 'This is the root of the tree'],
'childs': [{
'node': 'A1',
'childs': [{
'node': 'B1',
'childs': [{
'node': 'C1'
}]
},
{
'node': 'B2'
}]
},
{
'node': 'A2',
'childs': [{
'node': 'B3',
'childs': [{
'node': ['C2', 'This is a leaf']
},
{
'node': 'C3'
}]
}]
},
{
'node': ['A3', 'This is a node'],
'childs': [{
'node': 'B2'
}]
}]
}
`format_tree` will return::
ROOT This is the root of the tree
βββ A1
β βββ B1
β β βββ C1
β βββ B2
βββ A2
β βββ B3
β βββ C2 This is a leaf
β βββ C3
βββ A3 This is a node
βββ B2
"""
def _traverse_tree(tree, parents=None):
tree['parents'] = parents
childs = tree.get('childs', [])
nb_childs = len(childs)
for index, child in enumerate(childs):
child_parents = list(parents) + [index == nb_childs - 1]
tree['childs'][index] = _traverse_tree(
tree['childs'][index],
parents=child_parents)
return tree
tree = _traverse_tree(tree, parents=[])
def _get_rows_data(tree, rows):
prefix = ''
for p in tree['parents'][:-1]:
if p is False:
prefix += 'β '
else:
prefix += ' '
if not tree['parents']:
pass
elif tree['parents'][-1] is True:
prefix += 'βββ '
else:
prefix += 'βββ '
if isinstance(tree['node'], string_types):
tree['node'] = [tree['node']]
rows.append([prefix + tree['node'][0]] + tree['node'][1:])
for child in tree.get('childs', []):
rows = _get_rows_data(child, rows)
return rows
rows = _get_rows_data(tree, [])
return format_table(rows) | python | def format_tree(tree):
"""Format a python tree structure
Given the python tree::
tree = {
'node': ['ROOT', 'This is the root of the tree'],
'childs': [{
'node': 'A1',
'childs': [{
'node': 'B1',
'childs': [{
'node': 'C1'
}]
},
{
'node': 'B2'
}]
},
{
'node': 'A2',
'childs': [{
'node': 'B3',
'childs': [{
'node': ['C2', 'This is a leaf']
},
{
'node': 'C3'
}]
}]
},
{
'node': ['A3', 'This is a node'],
'childs': [{
'node': 'B2'
}]
}]
}
`format_tree` will return::
ROOT This is the root of the tree
βββ A1
β βββ B1
β β βββ C1
β βββ B2
βββ A2
β βββ B3
β βββ C2 This is a leaf
β βββ C3
βββ A3 This is a node
βββ B2
"""
def _traverse_tree(tree, parents=None):
tree['parents'] = parents
childs = tree.get('childs', [])
nb_childs = len(childs)
for index, child in enumerate(childs):
child_parents = list(parents) + [index == nb_childs - 1]
tree['childs'][index] = _traverse_tree(
tree['childs'][index],
parents=child_parents)
return tree
tree = _traverse_tree(tree, parents=[])
def _get_rows_data(tree, rows):
prefix = ''
for p in tree['parents'][:-1]:
if p is False:
prefix += 'β '
else:
prefix += ' '
if not tree['parents']:
pass
elif tree['parents'][-1] is True:
prefix += 'βββ '
else:
prefix += 'βββ '
if isinstance(tree['node'], string_types):
tree['node'] = [tree['node']]
rows.append([prefix + tree['node'][0]] + tree['node'][1:])
for child in tree.get('childs', []):
rows = _get_rows_data(child, rows)
return rows
rows = _get_rows_data(tree, [])
return format_table(rows) | [
"def",
"format_tree",
"(",
"tree",
")",
":",
"def",
"_traverse_tree",
"(",
"tree",
",",
"parents",
"=",
"None",
")",
":",
"tree",
"[",
"'parents'",
"]",
"=",
"parents",
"childs",
"=",
"tree",
".",
"get",
"(",
"'childs'",
",",
"[",
"]",
")",
"nb_childs",
"=",
"len",
"(",
"childs",
")",
"for",
"index",
",",
"child",
"in",
"enumerate",
"(",
"childs",
")",
":",
"child_parents",
"=",
"list",
"(",
"parents",
")",
"+",
"[",
"index",
"==",
"nb_childs",
"-",
"1",
"]",
"tree",
"[",
"'childs'",
"]",
"[",
"index",
"]",
"=",
"_traverse_tree",
"(",
"tree",
"[",
"'childs'",
"]",
"[",
"index",
"]",
",",
"parents",
"=",
"child_parents",
")",
"return",
"tree",
"tree",
"=",
"_traverse_tree",
"(",
"tree",
",",
"parents",
"=",
"[",
"]",
")",
"def",
"_get_rows_data",
"(",
"tree",
",",
"rows",
")",
":",
"prefix",
"=",
"''",
"for",
"p",
"in",
"tree",
"[",
"'parents'",
"]",
"[",
":",
"-",
"1",
"]",
":",
"if",
"p",
"is",
"False",
":",
"prefix",
"+=",
"'β '",
"else",
":",
"prefix",
"+=",
"' '",
"if",
"not",
"tree",
"[",
"'parents'",
"]",
":",
"pass",
"elif",
"tree",
"[",
"'parents'",
"]",
"[",
"-",
"1",
"]",
"is",
"True",
":",
"prefix",
"+=",
"'βββ '",
"else",
":",
"prefix",
"+=",
"'βββ '",
"if",
"isinstance",
"(",
"tree",
"[",
"'node'",
"]",
",",
"string_types",
")",
":",
"tree",
"[",
"'node'",
"]",
"=",
"[",
"tree",
"[",
"'node'",
"]",
"]",
"rows",
".",
"append",
"(",
"[",
"prefix",
"+",
"tree",
"[",
"'node'",
"]",
"[",
"0",
"]",
"]",
"+",
"tree",
"[",
"'node'",
"]",
"[",
"1",
":",
"]",
")",
"for",
"child",
"in",
"tree",
".",
"get",
"(",
"'childs'",
",",
"[",
"]",
")",
":",
"rows",
"=",
"_get_rows_data",
"(",
"child",
",",
"rows",
")",
"return",
"rows",
"rows",
"=",
"_get_rows_data",
"(",
"tree",
",",
"[",
"]",
")",
"return",
"format_table",
"(",
"rows",
")"
] | Format a python tree structure
Given the python tree::
tree = {
'node': ['ROOT', 'This is the root of the tree'],
'childs': [{
'node': 'A1',
'childs': [{
'node': 'B1',
'childs': [{
'node': 'C1'
}]
},
{
'node': 'B2'
}]
},
{
'node': 'A2',
'childs': [{
'node': 'B3',
'childs': [{
'node': ['C2', 'This is a leaf']
},
{
'node': 'C3'
}]
}]
},
{
'node': ['A3', 'This is a node'],
'childs': [{
'node': 'B2'
}]
}]
}
`format_tree` will return::
ROOT This is the root of the tree
βββ A1
β βββ B1
β β βββ C1
β βββ B2
βββ A2
β βββ B3
β βββ C2 This is a leaf
β βββ C3
βββ A3 This is a node
βββ B2 | [
"Format",
"a",
"python",
"tree",
"structure"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/utils.py#L345-L434 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/utils.py | parallel_map | def parallel_map(func, iterable, args=None, kwargs=None, workers=None):
"""Map func on a list using gevent greenlets.
:param func: function applied on iterable elements
:type func: function
:param iterable: elements to map the function over
:type iterable: iterable
:param args: arguments of func
:type args: tuple
:param kwargs: keyword arguments of func
:type kwargs: dict
:param workers: limit the number of greenlets
running in parrallel
:type workers: int
"""
if args is None:
args = ()
if kwargs is None:
kwargs = {}
if workers is not None:
pool = Pool(workers)
else:
pool = Group()
iterable = [pool.spawn(func, i, *args, **kwargs) for i in iterable]
pool.join(raise_error=True)
for idx, i in enumerate(iterable):
i_type = type(i.get())
i_value = i.get()
if issubclass(i_type, BaseException):
raise i_value
iterable[idx] = i_value
return iterable | python | def parallel_map(func, iterable, args=None, kwargs=None, workers=None):
"""Map func on a list using gevent greenlets.
:param func: function applied on iterable elements
:type func: function
:param iterable: elements to map the function over
:type iterable: iterable
:param args: arguments of func
:type args: tuple
:param kwargs: keyword arguments of func
:type kwargs: dict
:param workers: limit the number of greenlets
running in parrallel
:type workers: int
"""
if args is None:
args = ()
if kwargs is None:
kwargs = {}
if workers is not None:
pool = Pool(workers)
else:
pool = Group()
iterable = [pool.spawn(func, i, *args, **kwargs) for i in iterable]
pool.join(raise_error=True)
for idx, i in enumerate(iterable):
i_type = type(i.get())
i_value = i.get()
if issubclass(i_type, BaseException):
raise i_value
iterable[idx] = i_value
return iterable | [
"def",
"parallel_map",
"(",
"func",
",",
"iterable",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"workers",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"(",
")",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"if",
"workers",
"is",
"not",
"None",
":",
"pool",
"=",
"Pool",
"(",
"workers",
")",
"else",
":",
"pool",
"=",
"Group",
"(",
")",
"iterable",
"=",
"[",
"pool",
".",
"spawn",
"(",
"func",
",",
"i",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"i",
"in",
"iterable",
"]",
"pool",
".",
"join",
"(",
"raise_error",
"=",
"True",
")",
"for",
"idx",
",",
"i",
"in",
"enumerate",
"(",
"iterable",
")",
":",
"i_type",
"=",
"type",
"(",
"i",
".",
"get",
"(",
")",
")",
"i_value",
"=",
"i",
".",
"get",
"(",
")",
"if",
"issubclass",
"(",
"i_type",
",",
"BaseException",
")",
":",
"raise",
"i_value",
"iterable",
"[",
"idx",
"]",
"=",
"i_value",
"return",
"iterable"
] | Map func on a list using gevent greenlets.
:param func: function applied on iterable elements
:type func: function
:param iterable: elements to map the function over
:type iterable: iterable
:param args: arguments of func
:type args: tuple
:param kwargs: keyword arguments of func
:type kwargs: dict
:param workers: limit the number of greenlets
running in parrallel
:type workers: int | [
"Map",
"func",
"on",
"a",
"list",
"using",
"gevent",
"greenlets",
"."
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/utils.py#L437-L468 | train |
crm416/semantic | semantic/numbers.py | NumberService.parse | def parse(self, words):
"""A general method for parsing word-representations of numbers.
Supports floats and integers.
Args:
words (str): Description of an arbitrary number.
Returns:
A double representation of the words.
"""
def exact(words):
"""If already represented as float or int, convert."""
try:
return float(words)
except:
return None
guess = exact(words)
if guess is not None:
return guess
split = words.split(' ')
# Replace final ordinal/fraction with number
if split[-1] in self.__fractions__:
split[-1] = self.__fractions__[split[-1]]
elif split[-1] in self.__ordinals__:
split[-1] = self.__ordinals__[split[-1]]
parsed_ordinals = ' '.join(split)
return self.parseFloat(parsed_ordinals) | python | def parse(self, words):
"""A general method for parsing word-representations of numbers.
Supports floats and integers.
Args:
words (str): Description of an arbitrary number.
Returns:
A double representation of the words.
"""
def exact(words):
"""If already represented as float or int, convert."""
try:
return float(words)
except:
return None
guess = exact(words)
if guess is not None:
return guess
split = words.split(' ')
# Replace final ordinal/fraction with number
if split[-1] in self.__fractions__:
split[-1] = self.__fractions__[split[-1]]
elif split[-1] in self.__ordinals__:
split[-1] = self.__ordinals__[split[-1]]
parsed_ordinals = ' '.join(split)
return self.parseFloat(parsed_ordinals) | [
"def",
"parse",
"(",
"self",
",",
"words",
")",
":",
"def",
"exact",
"(",
"words",
")",
":",
"\"\"\"If already represented as float or int, convert.\"\"\"",
"try",
":",
"return",
"float",
"(",
"words",
")",
"except",
":",
"return",
"None",
"guess",
"=",
"exact",
"(",
"words",
")",
"if",
"guess",
"is",
"not",
"None",
":",
"return",
"guess",
"split",
"=",
"words",
".",
"split",
"(",
"' '",
")",
"# Replace final ordinal/fraction with number",
"if",
"split",
"[",
"-",
"1",
"]",
"in",
"self",
".",
"__fractions__",
":",
"split",
"[",
"-",
"1",
"]",
"=",
"self",
".",
"__fractions__",
"[",
"split",
"[",
"-",
"1",
"]",
"]",
"elif",
"split",
"[",
"-",
"1",
"]",
"in",
"self",
".",
"__ordinals__",
":",
"split",
"[",
"-",
"1",
"]",
"=",
"self",
".",
"__ordinals__",
"[",
"split",
"[",
"-",
"1",
"]",
"]",
"parsed_ordinals",
"=",
"' '",
".",
"join",
"(",
"split",
")",
"return",
"self",
".",
"parseFloat",
"(",
"parsed_ordinals",
")"
] | A general method for parsing word-representations of numbers.
Supports floats and integers.
Args:
words (str): Description of an arbitrary number.
Returns:
A double representation of the words. | [
"A",
"general",
"method",
"for",
"parsing",
"word",
"-",
"representations",
"of",
"numbers",
".",
"Supports",
"floats",
"and",
"integers",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/numbers.py#L91-L122 | train |
crm416/semantic | semantic/numbers.py | NumberService.parseFloat | def parseFloat(self, words):
"""Convert a floating-point number described in words to a double.
Supports two kinds of descriptions: those with a 'point' (e.g.,
"one point two five") and those with a fraction (e.g., "one and
a quarter").
Args:
words (str): Description of the floating-point number.
Returns:
A double representation of the words.
"""
def pointFloat(words):
m = re.search(r'(.*) point (.*)', words)
if m:
whole = m.group(1)
frac = m.group(2)
total = 0.0
coeff = 0.10
for digit in frac.split(' '):
total += coeff * self.parse(digit)
coeff /= 10.0
return self.parseInt(whole) + total
return None
def fractionFloat(words):
m = re.search(r'(.*) and (.*)', words)
if m:
whole = self.parseInt(m.group(1))
frac = m.group(2)
# Replace plurals
frac = re.sub(r'(\w+)s(\b)', '\g<1>\g<2>', frac)
# Convert 'a' to 'one' (e.g., 'a third' to 'one third')
frac = re.sub(r'(\b)a(\b)', '\g<1>one\g<2>', frac)
split = frac.split(' ')
# Split fraction into num (regular integer), denom (ordinal)
num = split[:1]
denom = split[1:]
while denom:
try:
# Test for valid num, denom
num_value = self.parse(' '.join(num))
denom_value = self.parse(' '.join(denom))
return whole + float(num_value) / denom_value
except:
# Add another word to num
num += denom[:1]
denom = denom[1:]
return None
# Extract "one point two five"-type float
result = pointFloat(words)
if result:
return result
# Extract "one and a quarter"-type float
result = fractionFloat(words)
if result:
return result
# Parse as integer
return self.parseInt(words) | python | def parseFloat(self, words):
"""Convert a floating-point number described in words to a double.
Supports two kinds of descriptions: those with a 'point' (e.g.,
"one point two five") and those with a fraction (e.g., "one and
a quarter").
Args:
words (str): Description of the floating-point number.
Returns:
A double representation of the words.
"""
def pointFloat(words):
m = re.search(r'(.*) point (.*)', words)
if m:
whole = m.group(1)
frac = m.group(2)
total = 0.0
coeff = 0.10
for digit in frac.split(' '):
total += coeff * self.parse(digit)
coeff /= 10.0
return self.parseInt(whole) + total
return None
def fractionFloat(words):
m = re.search(r'(.*) and (.*)', words)
if m:
whole = self.parseInt(m.group(1))
frac = m.group(2)
# Replace plurals
frac = re.sub(r'(\w+)s(\b)', '\g<1>\g<2>', frac)
# Convert 'a' to 'one' (e.g., 'a third' to 'one third')
frac = re.sub(r'(\b)a(\b)', '\g<1>one\g<2>', frac)
split = frac.split(' ')
# Split fraction into num (regular integer), denom (ordinal)
num = split[:1]
denom = split[1:]
while denom:
try:
# Test for valid num, denom
num_value = self.parse(' '.join(num))
denom_value = self.parse(' '.join(denom))
return whole + float(num_value) / denom_value
except:
# Add another word to num
num += denom[:1]
denom = denom[1:]
return None
# Extract "one point two five"-type float
result = pointFloat(words)
if result:
return result
# Extract "one and a quarter"-type float
result = fractionFloat(words)
if result:
return result
# Parse as integer
return self.parseInt(words) | [
"def",
"parseFloat",
"(",
"self",
",",
"words",
")",
":",
"def",
"pointFloat",
"(",
"words",
")",
":",
"m",
"=",
"re",
".",
"search",
"(",
"r'(.*) point (.*)'",
",",
"words",
")",
"if",
"m",
":",
"whole",
"=",
"m",
".",
"group",
"(",
"1",
")",
"frac",
"=",
"m",
".",
"group",
"(",
"2",
")",
"total",
"=",
"0.0",
"coeff",
"=",
"0.10",
"for",
"digit",
"in",
"frac",
".",
"split",
"(",
"' '",
")",
":",
"total",
"+=",
"coeff",
"*",
"self",
".",
"parse",
"(",
"digit",
")",
"coeff",
"/=",
"10.0",
"return",
"self",
".",
"parseInt",
"(",
"whole",
")",
"+",
"total",
"return",
"None",
"def",
"fractionFloat",
"(",
"words",
")",
":",
"m",
"=",
"re",
".",
"search",
"(",
"r'(.*) and (.*)'",
",",
"words",
")",
"if",
"m",
":",
"whole",
"=",
"self",
".",
"parseInt",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"frac",
"=",
"m",
".",
"group",
"(",
"2",
")",
"# Replace plurals",
"frac",
"=",
"re",
".",
"sub",
"(",
"r'(\\w+)s(\\b)'",
",",
"'\\g<1>\\g<2>'",
",",
"frac",
")",
"# Convert 'a' to 'one' (e.g., 'a third' to 'one third')",
"frac",
"=",
"re",
".",
"sub",
"(",
"r'(\\b)a(\\b)'",
",",
"'\\g<1>one\\g<2>'",
",",
"frac",
")",
"split",
"=",
"frac",
".",
"split",
"(",
"' '",
")",
"# Split fraction into num (regular integer), denom (ordinal)",
"num",
"=",
"split",
"[",
":",
"1",
"]",
"denom",
"=",
"split",
"[",
"1",
":",
"]",
"while",
"denom",
":",
"try",
":",
"# Test for valid num, denom",
"num_value",
"=",
"self",
".",
"parse",
"(",
"' '",
".",
"join",
"(",
"num",
")",
")",
"denom_value",
"=",
"self",
".",
"parse",
"(",
"' '",
".",
"join",
"(",
"denom",
")",
")",
"return",
"whole",
"+",
"float",
"(",
"num_value",
")",
"/",
"denom_value",
"except",
":",
"# Add another word to num",
"num",
"+=",
"denom",
"[",
":",
"1",
"]",
"denom",
"=",
"denom",
"[",
"1",
":",
"]",
"return",
"None",
"# Extract \"one point two five\"-type float",
"result",
"=",
"pointFloat",
"(",
"words",
")",
"if",
"result",
":",
"return",
"result",
"# Extract \"one and a quarter\"-type float",
"result",
"=",
"fractionFloat",
"(",
"words",
")",
"if",
"result",
":",
"return",
"result",
"# Parse as integer",
"return",
"self",
".",
"parseInt",
"(",
"words",
")"
] | Convert a floating-point number described in words to a double.
Supports two kinds of descriptions: those with a 'point' (e.g.,
"one point two five") and those with a fraction (e.g., "one and
a quarter").
Args:
words (str): Description of the floating-point number.
Returns:
A double representation of the words. | [
"Convert",
"a",
"floating",
"-",
"point",
"number",
"described",
"in",
"words",
"to",
"a",
"double",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/numbers.py#L124-L192 | train |
crm416/semantic | semantic/numbers.py | NumberService.parseInt | def parseInt(self, words):
"""Parses words to the integer they describe.
Args:
words (str): Description of the integer.
Returns:
An integer representation of the words.
"""
# Remove 'and', case-sensitivity
words = words.replace(" and ", " ").lower()
# 'a' -> 'one'
words = re.sub(r'(\b)a(\b)', '\g<1>one\g<2>', words)
def textToNumber(s):
"""
Converts raw number string to an integer.
Based on text2num.py by Greg Hewill.
"""
a = re.split(r"[\s-]+", s)
n = 0
g = 0
for w in a:
x = NumberService.__small__.get(w, None)
if x is not None:
g += x
elif w == "hundred":
g *= 100
else:
x = NumberService.__magnitude__.get(w, None)
if x is not None:
n += g * x
g = 0
else:
raise NumberService.NumberException(
"Unknown number: " + w)
return n + g
return textToNumber(words) | python | def parseInt(self, words):
"""Parses words to the integer they describe.
Args:
words (str): Description of the integer.
Returns:
An integer representation of the words.
"""
# Remove 'and', case-sensitivity
words = words.replace(" and ", " ").lower()
# 'a' -> 'one'
words = re.sub(r'(\b)a(\b)', '\g<1>one\g<2>', words)
def textToNumber(s):
"""
Converts raw number string to an integer.
Based on text2num.py by Greg Hewill.
"""
a = re.split(r"[\s-]+", s)
n = 0
g = 0
for w in a:
x = NumberService.__small__.get(w, None)
if x is not None:
g += x
elif w == "hundred":
g *= 100
else:
x = NumberService.__magnitude__.get(w, None)
if x is not None:
n += g * x
g = 0
else:
raise NumberService.NumberException(
"Unknown number: " + w)
return n + g
return textToNumber(words) | [
"def",
"parseInt",
"(",
"self",
",",
"words",
")",
":",
"# Remove 'and', case-sensitivity",
"words",
"=",
"words",
".",
"replace",
"(",
"\" and \"",
",",
"\" \"",
")",
".",
"lower",
"(",
")",
"# 'a' -> 'one'",
"words",
"=",
"re",
".",
"sub",
"(",
"r'(\\b)a(\\b)'",
",",
"'\\g<1>one\\g<2>'",
",",
"words",
")",
"def",
"textToNumber",
"(",
"s",
")",
":",
"\"\"\"\n Converts raw number string to an integer.\n Based on text2num.py by Greg Hewill.\n \"\"\"",
"a",
"=",
"re",
".",
"split",
"(",
"r\"[\\s-]+\"",
",",
"s",
")",
"n",
"=",
"0",
"g",
"=",
"0",
"for",
"w",
"in",
"a",
":",
"x",
"=",
"NumberService",
".",
"__small__",
".",
"get",
"(",
"w",
",",
"None",
")",
"if",
"x",
"is",
"not",
"None",
":",
"g",
"+=",
"x",
"elif",
"w",
"==",
"\"hundred\"",
":",
"g",
"*=",
"100",
"else",
":",
"x",
"=",
"NumberService",
".",
"__magnitude__",
".",
"get",
"(",
"w",
",",
"None",
")",
"if",
"x",
"is",
"not",
"None",
":",
"n",
"+=",
"g",
"*",
"x",
"g",
"=",
"0",
"else",
":",
"raise",
"NumberService",
".",
"NumberException",
"(",
"\"Unknown number: \"",
"+",
"w",
")",
"return",
"n",
"+",
"g",
"return",
"textToNumber",
"(",
"words",
")"
] | Parses words to the integer they describe.
Args:
words (str): Description of the integer.
Returns:
An integer representation of the words. | [
"Parses",
"words",
"to",
"the",
"integer",
"they",
"describe",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/numbers.py#L194-L232 | train |
crm416/semantic | semantic/numbers.py | NumberService.parseMagnitude | def parseMagnitude(m):
"""Parses a number m into a human-ready string representation.
For example, crops off floats if they're too accurate.
Arguments:
m (float): Floating-point number to be cleaned.
Returns:
Human-ready string description of the number.
"""
m = NumberService().parse(m)
def toDecimalPrecision(n, k):
return float("%.*f" % (k, round(n, k)))
# Cast to two digits of precision
digits = 2
magnitude = toDecimalPrecision(m, digits)
# If value is really small, keep going
while not magnitude:
digits += 1
magnitude = toDecimalPrecision(m, digits)
# If item is less than one, go one beyond 'necessary' number of digits
if m < 1.0:
magnitude = toDecimalPrecision(m, digits + 1)
# Ignore decimal accuracy if irrelevant
if int(magnitude) == magnitude:
magnitude = int(magnitude)
# Adjust for scientific notation
magString = str(magnitude)
magString = re.sub(r'(\d)e-(\d+)',
'\g<1> times ten to the negative \g<2>', magString)
magString = re.sub(r'(\d)e\+(\d+)',
'\g<1> times ten to the \g<2>', magString)
magString = re.sub(r'-(\d+)', 'negative \g<1>', magString)
magString = re.sub(r'\b0(\d+)', '\g<1>', magString)
return magString | python | def parseMagnitude(m):
"""Parses a number m into a human-ready string representation.
For example, crops off floats if they're too accurate.
Arguments:
m (float): Floating-point number to be cleaned.
Returns:
Human-ready string description of the number.
"""
m = NumberService().parse(m)
def toDecimalPrecision(n, k):
return float("%.*f" % (k, round(n, k)))
# Cast to two digits of precision
digits = 2
magnitude = toDecimalPrecision(m, digits)
# If value is really small, keep going
while not magnitude:
digits += 1
magnitude = toDecimalPrecision(m, digits)
# If item is less than one, go one beyond 'necessary' number of digits
if m < 1.0:
magnitude = toDecimalPrecision(m, digits + 1)
# Ignore decimal accuracy if irrelevant
if int(magnitude) == magnitude:
magnitude = int(magnitude)
# Adjust for scientific notation
magString = str(magnitude)
magString = re.sub(r'(\d)e-(\d+)',
'\g<1> times ten to the negative \g<2>', magString)
magString = re.sub(r'(\d)e\+(\d+)',
'\g<1> times ten to the \g<2>', magString)
magString = re.sub(r'-(\d+)', 'negative \g<1>', magString)
magString = re.sub(r'\b0(\d+)', '\g<1>', magString)
return magString | [
"def",
"parseMagnitude",
"(",
"m",
")",
":",
"m",
"=",
"NumberService",
"(",
")",
".",
"parse",
"(",
"m",
")",
"def",
"toDecimalPrecision",
"(",
"n",
",",
"k",
")",
":",
"return",
"float",
"(",
"\"%.*f\"",
"%",
"(",
"k",
",",
"round",
"(",
"n",
",",
"k",
")",
")",
")",
"# Cast to two digits of precision",
"digits",
"=",
"2",
"magnitude",
"=",
"toDecimalPrecision",
"(",
"m",
",",
"digits",
")",
"# If value is really small, keep going",
"while",
"not",
"magnitude",
":",
"digits",
"+=",
"1",
"magnitude",
"=",
"toDecimalPrecision",
"(",
"m",
",",
"digits",
")",
"# If item is less than one, go one beyond 'necessary' number of digits",
"if",
"m",
"<",
"1.0",
":",
"magnitude",
"=",
"toDecimalPrecision",
"(",
"m",
",",
"digits",
"+",
"1",
")",
"# Ignore decimal accuracy if irrelevant",
"if",
"int",
"(",
"magnitude",
")",
"==",
"magnitude",
":",
"magnitude",
"=",
"int",
"(",
"magnitude",
")",
"# Adjust for scientific notation",
"magString",
"=",
"str",
"(",
"magnitude",
")",
"magString",
"=",
"re",
".",
"sub",
"(",
"r'(\\d)e-(\\d+)'",
",",
"'\\g<1> times ten to the negative \\g<2>'",
",",
"magString",
")",
"magString",
"=",
"re",
".",
"sub",
"(",
"r'(\\d)e\\+(\\d+)'",
",",
"'\\g<1> times ten to the \\g<2>'",
",",
"magString",
")",
"magString",
"=",
"re",
".",
"sub",
"(",
"r'-(\\d+)'",
",",
"'negative \\g<1>'",
",",
"magString",
")",
"magString",
"=",
"re",
".",
"sub",
"(",
"r'\\b0(\\d+)'",
",",
"'\\g<1>'",
",",
"magString",
")",
"return",
"magString"
] | Parses a number m into a human-ready string representation.
For example, crops off floats if they're too accurate.
Arguments:
m (float): Floating-point number to be cleaned.
Returns:
Human-ready string description of the number. | [
"Parses",
"a",
"number",
"m",
"into",
"a",
"human",
"-",
"ready",
"string",
"representation",
".",
"For",
"example",
"crops",
"off",
"floats",
"if",
"they",
"re",
"too",
"accurate",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/numbers.py#L242-L282 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_keys.py | PrivateKey.serialize | def serialize(self, raw=False):
'''Encode the private part of the key in a base64 format by default,
but when raw is True it will return hex encoded bytes.
@return: bytes
'''
if raw:
return self._key.encode()
return self._key.encode(nacl.encoding.Base64Encoder) | python | def serialize(self, raw=False):
'''Encode the private part of the key in a base64 format by default,
but when raw is True it will return hex encoded bytes.
@return: bytes
'''
if raw:
return self._key.encode()
return self._key.encode(nacl.encoding.Base64Encoder) | [
"def",
"serialize",
"(",
"self",
",",
"raw",
"=",
"False",
")",
":",
"if",
"raw",
":",
"return",
"self",
".",
"_key",
".",
"encode",
"(",
")",
"return",
"self",
".",
"_key",
".",
"encode",
"(",
"nacl",
".",
"encoding",
".",
"Base64Encoder",
")"
] | Encode the private part of the key in a base64 format by default,
but when raw is True it will return hex encoded bytes.
@return: bytes | [
"Encode",
"the",
"private",
"part",
"of",
"the",
"key",
"in",
"a",
"base64",
"format",
"by",
"default",
"but",
"when",
"raw",
"is",
"True",
"it",
"will",
"return",
"hex",
"encoded",
"bytes",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_keys.py#L37-L44 | train |
swevm/scaleio-py | scaleiopy/api/scaleio/common/connection.py | Connection._do_get | def _do_get(self, url, **kwargs):
"""
Convenient method for GET requests
Returns http request status value from a POST request
"""
#TODO:
# Add error handling. Check for HTTP status here would be much more conveinent than in each calling method
scaleioapi_post_headers = {'Content-type':'application/json','Version':'1.0'}
try:
#response = self._session.get("{}/{}".format(self._api_url, uri)).json()
response = self._session.get(url)
if response.status_code == requests.codes.ok:
self.conn.logger.debug('_do_get() - HTTP response OK, data: %s', response.text)
return response
else:
self.conn.logger.error('_do_get() - HTTP response error: %s', response.status_code)
self.conn.logger.error('_do_get() - HTTP response error, data: %s', response.text)
raise RuntimeError("_do_get() - HTTP response error" + response.status_code)
except Exception as e:
self.conn.logger.error("_do_get() - Unhandled Error Occurred: %s" % str(e))
raise RuntimeError("_do_get() - Communication error with ScaleIO gateway")
return response | python | def _do_get(self, url, **kwargs):
"""
Convenient method for GET requests
Returns http request status value from a POST request
"""
#TODO:
# Add error handling. Check for HTTP status here would be much more conveinent than in each calling method
scaleioapi_post_headers = {'Content-type':'application/json','Version':'1.0'}
try:
#response = self._session.get("{}/{}".format(self._api_url, uri)).json()
response = self._session.get(url)
if response.status_code == requests.codes.ok:
self.conn.logger.debug('_do_get() - HTTP response OK, data: %s', response.text)
return response
else:
self.conn.logger.error('_do_get() - HTTP response error: %s', response.status_code)
self.conn.logger.error('_do_get() - HTTP response error, data: %s', response.text)
raise RuntimeError("_do_get() - HTTP response error" + response.status_code)
except Exception as e:
self.conn.logger.error("_do_get() - Unhandled Error Occurred: %s" % str(e))
raise RuntimeError("_do_get() - Communication error with ScaleIO gateway")
return response | [
"def",
"_do_get",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"#TODO:",
"# Add error handling. Check for HTTP status here would be much more conveinent than in each calling method",
"scaleioapi_post_headers",
"=",
"{",
"'Content-type'",
":",
"'application/json'",
",",
"'Version'",
":",
"'1.0'",
"}",
"try",
":",
"#response = self._session.get(\"{}/{}\".format(self._api_url, uri)).json()",
"response",
"=",
"self",
".",
"_session",
".",
"get",
"(",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"ok",
":",
"self",
".",
"conn",
".",
"logger",
".",
"debug",
"(",
"'_do_get() - HTTP response OK, data: %s'",
",",
"response",
".",
"text",
")",
"return",
"response",
"else",
":",
"self",
".",
"conn",
".",
"logger",
".",
"error",
"(",
"'_do_get() - HTTP response error: %s'",
",",
"response",
".",
"status_code",
")",
"self",
".",
"conn",
".",
"logger",
".",
"error",
"(",
"'_do_get() - HTTP response error, data: %s'",
",",
"response",
".",
"text",
")",
"raise",
"RuntimeError",
"(",
"\"_do_get() - HTTP response error\"",
"+",
"response",
".",
"status_code",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"conn",
".",
"logger",
".",
"error",
"(",
"\"_do_get() - Unhandled Error Occurred: %s\"",
"%",
"str",
"(",
"e",
")",
")",
"raise",
"RuntimeError",
"(",
"\"_do_get() - Communication error with ScaleIO gateway\"",
")",
"return",
"response"
] | Convenient method for GET requests
Returns http request status value from a POST request | [
"Convenient",
"method",
"for",
"GET",
"requests",
"Returns",
"http",
"request",
"status",
"value",
"from",
"a",
"POST",
"request"
] | d043a0137cb925987fd5c895a3210968ce1d9028 | https://github.com/swevm/scaleio-py/blob/d043a0137cb925987fd5c895a3210968ce1d9028/scaleiopy/api/scaleio/common/connection.py#L104-L125 | train |
swevm/scaleio-py | scaleiopy/api/scaleio/common/connection.py | Connection._do_post | def _do_post(self, url, **kwargs):
"""
Convenient method for POST requests
Returns http request status value from a POST request
"""
#TODO:
# Add error handling. Check for HTTP status here would be much more conveinent than in each calling method
scaleioapi_post_headers = {'Content-type':'application/json','Version':'1.0'}
try:
response = self._session.post(url, headers=scaleioapi_post_headers, **kwargs)
self.conn.logger.debug('_do_post() - HTTP response: %s', response.text)
if response.status_code == requests.codes.ok:
self.conn.logger.debug('_do_post() - HTTP response OK, data: %s', response.text)
return response
else:
self.conn.logger.error('_do_post() - HTTP response error: %s', response.status_code)
self.conn.logger.error('_do_post() - HTTP response error, data: %s', response.text)
raise RuntimeError("_do_post() - HTTP response error" + response.status_code)
except Exception as e:
self.conn.logger.error("_do_post() - Unhandled Error Occurred: %s" % str(e))
raise RuntimeError("_do_post() - Communication error with ScaleIO gateway")
return response | python | def _do_post(self, url, **kwargs):
"""
Convenient method for POST requests
Returns http request status value from a POST request
"""
#TODO:
# Add error handling. Check for HTTP status here would be much more conveinent than in each calling method
scaleioapi_post_headers = {'Content-type':'application/json','Version':'1.0'}
try:
response = self._session.post(url, headers=scaleioapi_post_headers, **kwargs)
self.conn.logger.debug('_do_post() - HTTP response: %s', response.text)
if response.status_code == requests.codes.ok:
self.conn.logger.debug('_do_post() - HTTP response OK, data: %s', response.text)
return response
else:
self.conn.logger.error('_do_post() - HTTP response error: %s', response.status_code)
self.conn.logger.error('_do_post() - HTTP response error, data: %s', response.text)
raise RuntimeError("_do_post() - HTTP response error" + response.status_code)
except Exception as e:
self.conn.logger.error("_do_post() - Unhandled Error Occurred: %s" % str(e))
raise RuntimeError("_do_post() - Communication error with ScaleIO gateway")
return response | [
"def",
"_do_post",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"#TODO:",
"# Add error handling. Check for HTTP status here would be much more conveinent than in each calling method",
"scaleioapi_post_headers",
"=",
"{",
"'Content-type'",
":",
"'application/json'",
",",
"'Version'",
":",
"'1.0'",
"}",
"try",
":",
"response",
"=",
"self",
".",
"_session",
".",
"post",
"(",
"url",
",",
"headers",
"=",
"scaleioapi_post_headers",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"conn",
".",
"logger",
".",
"debug",
"(",
"'_do_post() - HTTP response: %s'",
",",
"response",
".",
"text",
")",
"if",
"response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"ok",
":",
"self",
".",
"conn",
".",
"logger",
".",
"debug",
"(",
"'_do_post() - HTTP response OK, data: %s'",
",",
"response",
".",
"text",
")",
"return",
"response",
"else",
":",
"self",
".",
"conn",
".",
"logger",
".",
"error",
"(",
"'_do_post() - HTTP response error: %s'",
",",
"response",
".",
"status_code",
")",
"self",
".",
"conn",
".",
"logger",
".",
"error",
"(",
"'_do_post() - HTTP response error, data: %s'",
",",
"response",
".",
"text",
")",
"raise",
"RuntimeError",
"(",
"\"_do_post() - HTTP response error\"",
"+",
"response",
".",
"status_code",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"conn",
".",
"logger",
".",
"error",
"(",
"\"_do_post() - Unhandled Error Occurred: %s\"",
"%",
"str",
"(",
"e",
")",
")",
"raise",
"RuntimeError",
"(",
"\"_do_post() - Communication error with ScaleIO gateway\"",
")",
"return",
"response"
] | Convenient method for POST requests
Returns http request status value from a POST request | [
"Convenient",
"method",
"for",
"POST",
"requests",
"Returns",
"http",
"request",
"status",
"value",
"from",
"a",
"POST",
"request"
] | d043a0137cb925987fd5c895a3210968ce1d9028 | https://github.com/swevm/scaleio-py/blob/d043a0137cb925987fd5c895a3210968ce1d9028/scaleiopy/api/scaleio/common/connection.py#L127-L148 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_error.py | discharge_required_response | def discharge_required_response(macaroon, path, cookie_suffix_name,
message=None):
''' Get response content and headers from a discharge macaroons error.
@param macaroon may hold a macaroon that, when discharged, may
allow access to a service.
@param path holds the URL path to be associated with the macaroon.
The macaroon is potentially valid for all URLs under the given path.
@param cookie_suffix_name holds the desired cookie name suffix to be
associated with the macaroon. The actual name used will be
("macaroon-" + CookieName). Clients may ignore this field -
older clients will always use ("macaroon-" + macaroon.signature() in hex)
@return content(bytes) and the headers to set on the response(dict).
'''
if message is None:
message = 'discharge required'
content = json.dumps(
{
'Code': 'macaroon discharge required',
'Message': message,
'Info': {
'Macaroon': macaroon.to_dict(),
'MacaroonPath': path,
'CookieNameSuffix': cookie_suffix_name
},
}
).encode('utf-8')
return content, {
'WWW-Authenticate': 'Macaroon',
'Content-Type': 'application/json'
} | python | def discharge_required_response(macaroon, path, cookie_suffix_name,
message=None):
''' Get response content and headers from a discharge macaroons error.
@param macaroon may hold a macaroon that, when discharged, may
allow access to a service.
@param path holds the URL path to be associated with the macaroon.
The macaroon is potentially valid for all URLs under the given path.
@param cookie_suffix_name holds the desired cookie name suffix to be
associated with the macaroon. The actual name used will be
("macaroon-" + CookieName). Clients may ignore this field -
older clients will always use ("macaroon-" + macaroon.signature() in hex)
@return content(bytes) and the headers to set on the response(dict).
'''
if message is None:
message = 'discharge required'
content = json.dumps(
{
'Code': 'macaroon discharge required',
'Message': message,
'Info': {
'Macaroon': macaroon.to_dict(),
'MacaroonPath': path,
'CookieNameSuffix': cookie_suffix_name
},
}
).encode('utf-8')
return content, {
'WWW-Authenticate': 'Macaroon',
'Content-Type': 'application/json'
} | [
"def",
"discharge_required_response",
"(",
"macaroon",
",",
"path",
",",
"cookie_suffix_name",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"'discharge required'",
"content",
"=",
"json",
".",
"dumps",
"(",
"{",
"'Code'",
":",
"'macaroon discharge required'",
",",
"'Message'",
":",
"message",
",",
"'Info'",
":",
"{",
"'Macaroon'",
":",
"macaroon",
".",
"to_dict",
"(",
")",
",",
"'MacaroonPath'",
":",
"path",
",",
"'CookieNameSuffix'",
":",
"cookie_suffix_name",
"}",
",",
"}",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"content",
",",
"{",
"'WWW-Authenticate'",
":",
"'Macaroon'",
",",
"'Content-Type'",
":",
"'application/json'",
"}"
] | Get response content and headers from a discharge macaroons error.
@param macaroon may hold a macaroon that, when discharged, may
allow access to a service.
@param path holds the URL path to be associated with the macaroon.
The macaroon is potentially valid for all URLs under the given path.
@param cookie_suffix_name holds the desired cookie name suffix to be
associated with the macaroon. The actual name used will be
("macaroon-" + CookieName). Clients may ignore this field -
older clients will always use ("macaroon-" + macaroon.signature() in hex)
@return content(bytes) and the headers to set on the response(dict). | [
"Get",
"response",
"content",
"and",
"headers",
"from",
"a",
"discharge",
"macaroons",
"error",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_error.py#L35-L65 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_error.py | request_version | def request_version(req_headers):
''' Determines the bakery protocol version from a client request.
If the protocol cannot be determined, or is invalid, the original version
of the protocol is used. If a later version is found, the latest known
version is used, which is OK because versions are backwardly compatible.
@param req_headers: the request headers as a dict.
@return: bakery protocol version (for example macaroonbakery.VERSION_1)
'''
vs = req_headers.get(BAKERY_PROTOCOL_HEADER)
if vs is None:
# No header - use backward compatibility mode.
return bakery.VERSION_1
try:
x = int(vs)
except ValueError:
# Badly formed header - use backward compatibility mode.
return bakery.VERSION_1
if x > bakery.LATEST_VERSION:
# Later version than we know about - use the
# latest version that we can.
return bakery.LATEST_VERSION
return x | python | def request_version(req_headers):
''' Determines the bakery protocol version from a client request.
If the protocol cannot be determined, or is invalid, the original version
of the protocol is used. If a later version is found, the latest known
version is used, which is OK because versions are backwardly compatible.
@param req_headers: the request headers as a dict.
@return: bakery protocol version (for example macaroonbakery.VERSION_1)
'''
vs = req_headers.get(BAKERY_PROTOCOL_HEADER)
if vs is None:
# No header - use backward compatibility mode.
return bakery.VERSION_1
try:
x = int(vs)
except ValueError:
# Badly formed header - use backward compatibility mode.
return bakery.VERSION_1
if x > bakery.LATEST_VERSION:
# Later version than we know about - use the
# latest version that we can.
return bakery.LATEST_VERSION
return x | [
"def",
"request_version",
"(",
"req_headers",
")",
":",
"vs",
"=",
"req_headers",
".",
"get",
"(",
"BAKERY_PROTOCOL_HEADER",
")",
"if",
"vs",
"is",
"None",
":",
"# No header - use backward compatibility mode.",
"return",
"bakery",
".",
"VERSION_1",
"try",
":",
"x",
"=",
"int",
"(",
"vs",
")",
"except",
"ValueError",
":",
"# Badly formed header - use backward compatibility mode.",
"return",
"bakery",
".",
"VERSION_1",
"if",
"x",
">",
"bakery",
".",
"LATEST_VERSION",
":",
"# Later version than we know about - use the",
"# latest version that we can.",
"return",
"bakery",
".",
"LATEST_VERSION",
"return",
"x"
] | Determines the bakery protocol version from a client request.
If the protocol cannot be determined, or is invalid, the original version
of the protocol is used. If a later version is found, the latest known
version is used, which is OK because versions are backwardly compatible.
@param req_headers: the request headers as a dict.
@return: bakery protocol version (for example macaroonbakery.VERSION_1) | [
"Determines",
"the",
"bakery",
"protocol",
"version",
"from",
"a",
"client",
"request",
".",
"If",
"the",
"protocol",
"cannot",
"be",
"determined",
"or",
"is",
"invalid",
"the",
"original",
"version",
"of",
"the",
"protocol",
"is",
"used",
".",
"If",
"a",
"later",
"version",
"is",
"found",
"the",
"latest",
"known",
"version",
"is",
"used",
"which",
"is",
"OK",
"because",
"versions",
"are",
"backwardly",
"compatible",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_error.py#L75-L97 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_error.py | Error.from_dict | def from_dict(cls, serialized):
'''Create an error from a JSON-deserialized object
@param serialized the object holding the serialized error {dict}
'''
# Some servers return lower case field names for message and code.
# The Go client is tolerant of this, so be similarly tolerant here.
def field(name):
return serialized.get(name) or serialized.get(name.lower())
return Error(
code=field('Code'),
message=field('Message'),
info=ErrorInfo.from_dict(field('Info')),
version=bakery.LATEST_VERSION,
) | python | def from_dict(cls, serialized):
'''Create an error from a JSON-deserialized object
@param serialized the object holding the serialized error {dict}
'''
# Some servers return lower case field names for message and code.
# The Go client is tolerant of this, so be similarly tolerant here.
def field(name):
return serialized.get(name) or serialized.get(name.lower())
return Error(
code=field('Code'),
message=field('Message'),
info=ErrorInfo.from_dict(field('Info')),
version=bakery.LATEST_VERSION,
) | [
"def",
"from_dict",
"(",
"cls",
",",
"serialized",
")",
":",
"# Some servers return lower case field names for message and code.",
"# The Go client is tolerant of this, so be similarly tolerant here.",
"def",
"field",
"(",
"name",
")",
":",
"return",
"serialized",
".",
"get",
"(",
"name",
")",
"or",
"serialized",
".",
"get",
"(",
"name",
".",
"lower",
"(",
")",
")",
"return",
"Error",
"(",
"code",
"=",
"field",
"(",
"'Code'",
")",
",",
"message",
"=",
"field",
"(",
"'Message'",
")",
",",
"info",
"=",
"ErrorInfo",
".",
"from_dict",
"(",
"field",
"(",
"'Info'",
")",
")",
",",
"version",
"=",
"bakery",
".",
"LATEST_VERSION",
",",
")"
] | Create an error from a JSON-deserialized object
@param serialized the object holding the serialized error {dict} | [
"Create",
"an",
"error",
"from",
"a",
"JSON",
"-",
"deserialized",
"object"
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_error.py#L105-L118 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_error.py | Error.interaction_method | def interaction_method(self, kind, x):
''' Checks whether the error is an InteractionRequired error
that implements the method with the given name, and JSON-unmarshals the
method-specific data into x by calling its from_dict method
with the deserialized JSON object.
@param kind The interaction method kind (string).
@param x A class with a class method from_dict that returns a new
instance of the interaction info for the given kind.
@return The result of x.from_dict.
'''
if self.info is None or self.code != ERR_INTERACTION_REQUIRED:
raise InteractionError(
'not an interaction-required error (code {})'.format(
self.code)
)
entry = self.info.interaction_methods.get(kind)
if entry is None:
raise InteractionMethodNotFound(
'interaction method {} not found'.format(kind)
)
return x.from_dict(entry) | python | def interaction_method(self, kind, x):
''' Checks whether the error is an InteractionRequired error
that implements the method with the given name, and JSON-unmarshals the
method-specific data into x by calling its from_dict method
with the deserialized JSON object.
@param kind The interaction method kind (string).
@param x A class with a class method from_dict that returns a new
instance of the interaction info for the given kind.
@return The result of x.from_dict.
'''
if self.info is None or self.code != ERR_INTERACTION_REQUIRED:
raise InteractionError(
'not an interaction-required error (code {})'.format(
self.code)
)
entry = self.info.interaction_methods.get(kind)
if entry is None:
raise InteractionMethodNotFound(
'interaction method {} not found'.format(kind)
)
return x.from_dict(entry) | [
"def",
"interaction_method",
"(",
"self",
",",
"kind",
",",
"x",
")",
":",
"if",
"self",
".",
"info",
"is",
"None",
"or",
"self",
".",
"code",
"!=",
"ERR_INTERACTION_REQUIRED",
":",
"raise",
"InteractionError",
"(",
"'not an interaction-required error (code {})'",
".",
"format",
"(",
"self",
".",
"code",
")",
")",
"entry",
"=",
"self",
".",
"info",
".",
"interaction_methods",
".",
"get",
"(",
"kind",
")",
"if",
"entry",
"is",
"None",
":",
"raise",
"InteractionMethodNotFound",
"(",
"'interaction method {} not found'",
".",
"format",
"(",
"kind",
")",
")",
"return",
"x",
".",
"from_dict",
"(",
"entry",
")"
] | Checks whether the error is an InteractionRequired error
that implements the method with the given name, and JSON-unmarshals the
method-specific data into x by calling its from_dict method
with the deserialized JSON object.
@param kind The interaction method kind (string).
@param x A class with a class method from_dict that returns a new
instance of the interaction info for the given kind.
@return The result of x.from_dict. | [
"Checks",
"whether",
"the",
"error",
"is",
"an",
"InteractionRequired",
"error",
"that",
"implements",
"the",
"method",
"with",
"the",
"given",
"name",
"and",
"JSON",
"-",
"unmarshals",
"the",
"method",
"-",
"specific",
"data",
"into",
"x",
"by",
"calling",
"its",
"from_dict",
"method",
"with",
"the",
"deserialized",
"JSON",
"object",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_error.py#L120-L140 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_error.py | ErrorInfo.from_dict | def from_dict(cls, serialized):
'''Create a new ErrorInfo object from a JSON deserialized
dictionary
@param serialized The JSON object {dict}
@return ErrorInfo object
'''
if serialized is None:
return None
macaroon = serialized.get('Macaroon')
if macaroon is not None:
macaroon = bakery.Macaroon.from_dict(macaroon)
path = serialized.get('MacaroonPath')
cookie_name_suffix = serialized.get('CookieNameSuffix')
visit_url = serialized.get('VisitURL')
wait_url = serialized.get('WaitURL')
interaction_methods = serialized.get('InteractionMethods')
return ErrorInfo(macaroon=macaroon, macaroon_path=path,
cookie_name_suffix=cookie_name_suffix,
visit_url=visit_url, wait_url=wait_url,
interaction_methods=interaction_methods) | python | def from_dict(cls, serialized):
'''Create a new ErrorInfo object from a JSON deserialized
dictionary
@param serialized The JSON object {dict}
@return ErrorInfo object
'''
if serialized is None:
return None
macaroon = serialized.get('Macaroon')
if macaroon is not None:
macaroon = bakery.Macaroon.from_dict(macaroon)
path = serialized.get('MacaroonPath')
cookie_name_suffix = serialized.get('CookieNameSuffix')
visit_url = serialized.get('VisitURL')
wait_url = serialized.get('WaitURL')
interaction_methods = serialized.get('InteractionMethods')
return ErrorInfo(macaroon=macaroon, macaroon_path=path,
cookie_name_suffix=cookie_name_suffix,
visit_url=visit_url, wait_url=wait_url,
interaction_methods=interaction_methods) | [
"def",
"from_dict",
"(",
"cls",
",",
"serialized",
")",
":",
"if",
"serialized",
"is",
"None",
":",
"return",
"None",
"macaroon",
"=",
"serialized",
".",
"get",
"(",
"'Macaroon'",
")",
"if",
"macaroon",
"is",
"not",
"None",
":",
"macaroon",
"=",
"bakery",
".",
"Macaroon",
".",
"from_dict",
"(",
"macaroon",
")",
"path",
"=",
"serialized",
".",
"get",
"(",
"'MacaroonPath'",
")",
"cookie_name_suffix",
"=",
"serialized",
".",
"get",
"(",
"'CookieNameSuffix'",
")",
"visit_url",
"=",
"serialized",
".",
"get",
"(",
"'VisitURL'",
")",
"wait_url",
"=",
"serialized",
".",
"get",
"(",
"'WaitURL'",
")",
"interaction_methods",
"=",
"serialized",
".",
"get",
"(",
"'InteractionMethods'",
")",
"return",
"ErrorInfo",
"(",
"macaroon",
"=",
"macaroon",
",",
"macaroon_path",
"=",
"path",
",",
"cookie_name_suffix",
"=",
"cookie_name_suffix",
",",
"visit_url",
"=",
"visit_url",
",",
"wait_url",
"=",
"wait_url",
",",
"interaction_methods",
"=",
"interaction_methods",
")"
] | Create a new ErrorInfo object from a JSON deserialized
dictionary
@param serialized The JSON object {dict}
@return ErrorInfo object | [
"Create",
"a",
"new",
"ErrorInfo",
"object",
"from",
"a",
"JSON",
"deserialized",
"dictionary"
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_error.py#L178-L197 | train |
ph4r05/monero-serialize | monero_serialize/xmrobj.py | dump_blob | async def dump_blob(elem, elem_type=None):
"""
Dumps blob message.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return:
"""
elem_is_blob = isinstance(elem, x.BlobType)
data = getattr(elem, x.BlobType.DATA_ATTR) if elem_is_blob else elem
if data is None or len(data) == 0:
return b''
if isinstance(data, (bytes, bytearray, list)):
return base64.b16encode(bytes(data))
else:
raise ValueError('Unknown blob type') | python | async def dump_blob(elem, elem_type=None):
"""
Dumps blob message.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return:
"""
elem_is_blob = isinstance(elem, x.BlobType)
data = getattr(elem, x.BlobType.DATA_ATTR) if elem_is_blob else elem
if data is None or len(data) == 0:
return b''
if isinstance(data, (bytes, bytearray, list)):
return base64.b16encode(bytes(data))
else:
raise ValueError('Unknown blob type') | [
"async",
"def",
"dump_blob",
"(",
"elem",
",",
"elem_type",
"=",
"None",
")",
":",
"elem_is_blob",
"=",
"isinstance",
"(",
"elem",
",",
"x",
".",
"BlobType",
")",
"data",
"=",
"getattr",
"(",
"elem",
",",
"x",
".",
"BlobType",
".",
"DATA_ATTR",
")",
"if",
"elem_is_blob",
"else",
"elem",
"if",
"data",
"is",
"None",
"or",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"b''",
"if",
"isinstance",
"(",
"data",
",",
"(",
"bytes",
",",
"bytearray",
",",
"list",
")",
")",
":",
"return",
"base64",
".",
"b16encode",
"(",
"bytes",
"(",
"data",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown blob type'",
")"
] | Dumps blob message.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return: | [
"Dumps",
"blob",
"message",
".",
"Supports",
"both",
"blob",
"and",
"raw",
"value",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrobj.py#L70-L88 | train |
ph4r05/monero-serialize | monero_serialize/xmrobj.py | dump_container | async def dump_container(obj, container, container_type, params=None, field_archiver=None):
"""
Serializes container as popo
:param obj:
:param container:
:param container_type:
:param params:
:param field_archiver:
:return:
"""
field_archiver = field_archiver if field_archiver else dump_field
elem_type = params[0] if params else None
if elem_type is None:
elem_type = container_type.ELEM_TYPE
obj = [] if obj is None else get_elem(obj)
if container is None:
return None
for elem in container:
fvalue = await field_archiver(None, elem, elem_type, params[1:] if params else None)
obj.append(fvalue)
return obj | python | async def dump_container(obj, container, container_type, params=None, field_archiver=None):
"""
Serializes container as popo
:param obj:
:param container:
:param container_type:
:param params:
:param field_archiver:
:return:
"""
field_archiver = field_archiver if field_archiver else dump_field
elem_type = params[0] if params else None
if elem_type is None:
elem_type = container_type.ELEM_TYPE
obj = [] if obj is None else get_elem(obj)
if container is None:
return None
for elem in container:
fvalue = await field_archiver(None, elem, elem_type, params[1:] if params else None)
obj.append(fvalue)
return obj | [
"async",
"def",
"dump_container",
"(",
"obj",
",",
"container",
",",
"container_type",
",",
"params",
"=",
"None",
",",
"field_archiver",
"=",
"None",
")",
":",
"field_archiver",
"=",
"field_archiver",
"if",
"field_archiver",
"else",
"dump_field",
"elem_type",
"=",
"params",
"[",
"0",
"]",
"if",
"params",
"else",
"None",
"if",
"elem_type",
"is",
"None",
":",
"elem_type",
"=",
"container_type",
".",
"ELEM_TYPE",
"obj",
"=",
"[",
"]",
"if",
"obj",
"is",
"None",
"else",
"get_elem",
"(",
"obj",
")",
"if",
"container",
"is",
"None",
":",
"return",
"None",
"for",
"elem",
"in",
"container",
":",
"fvalue",
"=",
"await",
"field_archiver",
"(",
"None",
",",
"elem",
",",
"elem_type",
",",
"params",
"[",
"1",
":",
"]",
"if",
"params",
"else",
"None",
")",
"obj",
".",
"append",
"(",
"fvalue",
")",
"return",
"obj"
] | Serializes container as popo
:param obj:
:param container:
:param container_type:
:param params:
:param field_archiver:
:return: | [
"Serializes",
"container",
"as",
"popo"
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrobj.py#L102-L124 | train |
ph4r05/monero-serialize | monero_serialize/xmrobj.py | load_container | async def load_container(obj, container_type, params=None, container=None, field_archiver=None):
"""
Loads container of elements from the object representation. Supports the container ref.
Returns loaded container.
:param reader:
:param container_type:
:param params:
:param container:
:param field_archiver:
:return:
"""
field_archiver = field_archiver if field_archiver else load_field
if obj is None:
return None
c_len = len(obj)
elem_type = params[0] if params else None
if elem_type is None:
elem_type = container_type.ELEM_TYPE
res = container if container else []
for i in range(c_len):
fvalue = await field_archiver(obj[i], elem_type,
params[1:] if params else None,
eref(res, i) if container else None)
if not container:
res.append(fvalue)
return res | python | async def load_container(obj, container_type, params=None, container=None, field_archiver=None):
"""
Loads container of elements from the object representation. Supports the container ref.
Returns loaded container.
:param reader:
:param container_type:
:param params:
:param container:
:param field_archiver:
:return:
"""
field_archiver = field_archiver if field_archiver else load_field
if obj is None:
return None
c_len = len(obj)
elem_type = params[0] if params else None
if elem_type is None:
elem_type = container_type.ELEM_TYPE
res = container if container else []
for i in range(c_len):
fvalue = await field_archiver(obj[i], elem_type,
params[1:] if params else None,
eref(res, i) if container else None)
if not container:
res.append(fvalue)
return res | [
"async",
"def",
"load_container",
"(",
"obj",
",",
"container_type",
",",
"params",
"=",
"None",
",",
"container",
"=",
"None",
",",
"field_archiver",
"=",
"None",
")",
":",
"field_archiver",
"=",
"field_archiver",
"if",
"field_archiver",
"else",
"load_field",
"if",
"obj",
"is",
"None",
":",
"return",
"None",
"c_len",
"=",
"len",
"(",
"obj",
")",
"elem_type",
"=",
"params",
"[",
"0",
"]",
"if",
"params",
"else",
"None",
"if",
"elem_type",
"is",
"None",
":",
"elem_type",
"=",
"container_type",
".",
"ELEM_TYPE",
"res",
"=",
"container",
"if",
"container",
"else",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"c_len",
")",
":",
"fvalue",
"=",
"await",
"field_archiver",
"(",
"obj",
"[",
"i",
"]",
",",
"elem_type",
",",
"params",
"[",
"1",
":",
"]",
"if",
"params",
"else",
"None",
",",
"eref",
"(",
"res",
",",
"i",
")",
"if",
"container",
"else",
"None",
")",
"if",
"not",
"container",
":",
"res",
".",
"append",
"(",
"fvalue",
")",
"return",
"res"
] | Loads container of elements from the object representation. Supports the container ref.
Returns loaded container.
:param reader:
:param container_type:
:param params:
:param container:
:param field_archiver:
:return: | [
"Loads",
"container",
"of",
"elements",
"from",
"the",
"object",
"representation",
".",
"Supports",
"the",
"container",
"ref",
".",
"Returns",
"loaded",
"container",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrobj.py#L127-L155 | train |
ph4r05/monero-serialize | monero_serialize/xmrobj.py | dump_message_field | async def dump_message_field(obj, msg, field, field_archiver=None):
"""
Dumps a message field to the object. Field is defined by the message field specification.
:param obj:
:param msg:
:param field:
:param field_archiver:
:return:
"""
fname, ftype, params = field[0], field[1], field[2:]
fvalue = getattr(msg, fname, None)
field_archiver = field_archiver if field_archiver else dump_field
return await field_archiver(eref(obj, fname, True), fvalue, ftype, params) | python | async def dump_message_field(obj, msg, field, field_archiver=None):
"""
Dumps a message field to the object. Field is defined by the message field specification.
:param obj:
:param msg:
:param field:
:param field_archiver:
:return:
"""
fname, ftype, params = field[0], field[1], field[2:]
fvalue = getattr(msg, fname, None)
field_archiver = field_archiver if field_archiver else dump_field
return await field_archiver(eref(obj, fname, True), fvalue, ftype, params) | [
"async",
"def",
"dump_message_field",
"(",
"obj",
",",
"msg",
",",
"field",
",",
"field_archiver",
"=",
"None",
")",
":",
"fname",
",",
"ftype",
",",
"params",
"=",
"field",
"[",
"0",
"]",
",",
"field",
"[",
"1",
"]",
",",
"field",
"[",
"2",
":",
"]",
"fvalue",
"=",
"getattr",
"(",
"msg",
",",
"fname",
",",
"None",
")",
"field_archiver",
"=",
"field_archiver",
"if",
"field_archiver",
"else",
"dump_field",
"return",
"await",
"field_archiver",
"(",
"eref",
"(",
"obj",
",",
"fname",
",",
"True",
")",
",",
"fvalue",
",",
"ftype",
",",
"params",
")"
] | Dumps a message field to the object. Field is defined by the message field specification.
:param obj:
:param msg:
:param field:
:param field_archiver:
:return: | [
"Dumps",
"a",
"message",
"field",
"to",
"the",
"object",
".",
"Field",
"is",
"defined",
"by",
"the",
"message",
"field",
"specification",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrobj.py#L158-L171 | train |
ph4r05/monero-serialize | monero_serialize/xmrobj.py | load_message_field | async def load_message_field(obj, msg, field, field_archiver=None):
"""
Loads message field from the object. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:param field_archiver:
:return:
"""
fname, ftype, params = field[0], field[1], field[2:]
field_archiver = field_archiver if field_archiver else load_field
await field_archiver(obj[fname], ftype, params, eref(msg, fname)) | python | async def load_message_field(obj, msg, field, field_archiver=None):
"""
Loads message field from the object. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:param field_archiver:
:return:
"""
fname, ftype, params = field[0], field[1], field[2:]
field_archiver = field_archiver if field_archiver else load_field
await field_archiver(obj[fname], ftype, params, eref(msg, fname)) | [
"async",
"def",
"load_message_field",
"(",
"obj",
",",
"msg",
",",
"field",
",",
"field_archiver",
"=",
"None",
")",
":",
"fname",
",",
"ftype",
",",
"params",
"=",
"field",
"[",
"0",
"]",
",",
"field",
"[",
"1",
"]",
",",
"field",
"[",
"2",
":",
"]",
"field_archiver",
"=",
"field_archiver",
"if",
"field_archiver",
"else",
"load_field",
"await",
"field_archiver",
"(",
"obj",
"[",
"fname",
"]",
",",
"ftype",
",",
"params",
",",
"eref",
"(",
"msg",
",",
"fname",
")",
")"
] | Loads message field from the object. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:param field_archiver:
:return: | [
"Loads",
"message",
"field",
"from",
"the",
"object",
".",
"Field",
"is",
"defined",
"by",
"the",
"message",
"field",
"specification",
".",
"Returns",
"loaded",
"value",
"supports",
"field",
"reference",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrobj.py#L174-L187 | train |
ph4r05/monero-serialize | monero_serialize/xmrobj.py | dump_message | async def dump_message(obj, msg, field_archiver=None):
"""
Dumps message to the object.
Returns message popo representation.
:param obj:
:param msg:
:param field_archiver:
:return:
"""
mtype = msg.__class__
fields = mtype.f_specs()
obj = collections.OrderedDict() if obj is None else get_elem(obj)
for field in fields:
await dump_message_field(obj, msg=msg, field=field, field_archiver=field_archiver)
return obj | python | async def dump_message(obj, msg, field_archiver=None):
"""
Dumps message to the object.
Returns message popo representation.
:param obj:
:param msg:
:param field_archiver:
:return:
"""
mtype = msg.__class__
fields = mtype.f_specs()
obj = collections.OrderedDict() if obj is None else get_elem(obj)
for field in fields:
await dump_message_field(obj, msg=msg, field=field, field_archiver=field_archiver)
return obj | [
"async",
"def",
"dump_message",
"(",
"obj",
",",
"msg",
",",
"field_archiver",
"=",
"None",
")",
":",
"mtype",
"=",
"msg",
".",
"__class__",
"fields",
"=",
"mtype",
".",
"f_specs",
"(",
")",
"obj",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"if",
"obj",
"is",
"None",
"else",
"get_elem",
"(",
"obj",
")",
"for",
"field",
"in",
"fields",
":",
"await",
"dump_message_field",
"(",
"obj",
",",
"msg",
"=",
"msg",
",",
"field",
"=",
"field",
",",
"field_archiver",
"=",
"field_archiver",
")",
"return",
"obj"
] | Dumps message to the object.
Returns message popo representation.
:param obj:
:param msg:
:param field_archiver:
:return: | [
"Dumps",
"message",
"to",
"the",
"object",
".",
"Returns",
"message",
"popo",
"representation",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrobj.py#L190-L206 | train |
ph4r05/monero-serialize | monero_serialize/xmrobj.py | load_message | async def load_message(obj, msg_type, msg=None, field_archiver=None):
"""
Loads message if the given type from the object.
Supports reading directly to existing message.
:param obj:
:param msg_type:
:param msg:
:param field_archiver:
:return:
"""
msg = msg_type() if msg is None else msg
fields = msg_type.f_specs() if msg_type else msg.__class__.f_specs()
for field in fields:
await load_message_field(obj, msg, field, field_archiver=field_archiver)
return msg | python | async def load_message(obj, msg_type, msg=None, field_archiver=None):
"""
Loads message if the given type from the object.
Supports reading directly to existing message.
:param obj:
:param msg_type:
:param msg:
:param field_archiver:
:return:
"""
msg = msg_type() if msg is None else msg
fields = msg_type.f_specs() if msg_type else msg.__class__.f_specs()
for field in fields:
await load_message_field(obj, msg, field, field_archiver=field_archiver)
return msg | [
"async",
"def",
"load_message",
"(",
"obj",
",",
"msg_type",
",",
"msg",
"=",
"None",
",",
"field_archiver",
"=",
"None",
")",
":",
"msg",
"=",
"msg_type",
"(",
")",
"if",
"msg",
"is",
"None",
"else",
"msg",
"fields",
"=",
"msg_type",
".",
"f_specs",
"(",
")",
"if",
"msg_type",
"else",
"msg",
".",
"__class__",
".",
"f_specs",
"(",
")",
"for",
"field",
"in",
"fields",
":",
"await",
"load_message_field",
"(",
"obj",
",",
"msg",
",",
"field",
",",
"field_archiver",
"=",
"field_archiver",
")",
"return",
"msg"
] | Loads message if the given type from the object.
Supports reading directly to existing message.
:param obj:
:param msg_type:
:param msg:
:param field_archiver:
:return: | [
"Loads",
"message",
"if",
"the",
"given",
"type",
"from",
"the",
"object",
".",
"Supports",
"reading",
"directly",
"to",
"existing",
"message",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrobj.py#L209-L226 | train |
ph4r05/monero-serialize | monero_serialize/xmrobj.py | dump_variant | async def dump_variant(obj, elem, elem_type=None, params=None, field_archiver=None):
"""
Transform variant to the popo object representation.
:param obj:
:param elem:
:param elem_type:
:param params:
:param field_archiver:
:return:
"""
field_archiver = field_archiver if field_archiver else dump_field
if isinstance(elem, x.VariantType) or elem_type.WRAPS_VALUE:
return {
elem.variant_elem: await field_archiver(None, getattr(elem, elem.variant_elem), elem.variant_elem_type)
}
else:
fdef = elem_type.find_fdef(elem_type.f_specs(), elem)
return {
fdef[0]: await field_archiver(None, elem, fdef[1])
} | python | async def dump_variant(obj, elem, elem_type=None, params=None, field_archiver=None):
"""
Transform variant to the popo object representation.
:param obj:
:param elem:
:param elem_type:
:param params:
:param field_archiver:
:return:
"""
field_archiver = field_archiver if field_archiver else dump_field
if isinstance(elem, x.VariantType) or elem_type.WRAPS_VALUE:
return {
elem.variant_elem: await field_archiver(None, getattr(elem, elem.variant_elem), elem.variant_elem_type)
}
else:
fdef = elem_type.find_fdef(elem_type.f_specs(), elem)
return {
fdef[0]: await field_archiver(None, elem, fdef[1])
} | [
"async",
"def",
"dump_variant",
"(",
"obj",
",",
"elem",
",",
"elem_type",
"=",
"None",
",",
"params",
"=",
"None",
",",
"field_archiver",
"=",
"None",
")",
":",
"field_archiver",
"=",
"field_archiver",
"if",
"field_archiver",
"else",
"dump_field",
"if",
"isinstance",
"(",
"elem",
",",
"x",
".",
"VariantType",
")",
"or",
"elem_type",
".",
"WRAPS_VALUE",
":",
"return",
"{",
"elem",
".",
"variant_elem",
":",
"await",
"field_archiver",
"(",
"None",
",",
"getattr",
"(",
"elem",
",",
"elem",
".",
"variant_elem",
")",
",",
"elem",
".",
"variant_elem_type",
")",
"}",
"else",
":",
"fdef",
"=",
"elem_type",
".",
"find_fdef",
"(",
"elem_type",
".",
"f_specs",
"(",
")",
",",
"elem",
")",
"return",
"{",
"fdef",
"[",
"0",
"]",
":",
"await",
"field_archiver",
"(",
"None",
",",
"elem",
",",
"fdef",
"[",
"1",
"]",
")",
"}"
] | Transform variant to the popo object representation.
:param obj:
:param elem:
:param elem_type:
:param params:
:param field_archiver:
:return: | [
"Transform",
"variant",
"to",
"the",
"popo",
"object",
"representation",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrobj.py#L229-L250 | train |
ph4r05/monero-serialize | monero_serialize/xmrobj.py | dump_field | async def dump_field(obj, elem, elem_type, params=None):
"""
Dumps generic field to the popo object representation, according to the element specification.
General multiplexer.
:param obj:
:param elem:
:param elem_type:
:param params:
:return:
"""
if isinstance(elem, (int, bool)) or issubclass(elem_type, x.UVarintType) or issubclass(elem_type, x.IntType):
return set_elem(obj, elem)
elif issubclass(elem_type, x.BlobType) or isinstance(obj, bytes) or isinstance(obj, bytearray):
return set_elem(obj, await dump_blob(elem))
elif issubclass(elem_type, x.UnicodeType) or isinstance(elem, str):
return set_elem(obj, elem)
elif issubclass(elem_type, x.VariantType):
return set_elem(obj, await dump_variant(None, elem, elem_type, params))
elif issubclass(elem_type, x.ContainerType): # container ~ simple list
return set_elem(obj, await dump_container(None, elem, elem_type, params))
elif issubclass(elem_type, x.MessageType):
return set_elem(obj, await dump_message(None, elem))
else:
raise TypeError | python | async def dump_field(obj, elem, elem_type, params=None):
"""
Dumps generic field to the popo object representation, according to the element specification.
General multiplexer.
:param obj:
:param elem:
:param elem_type:
:param params:
:return:
"""
if isinstance(elem, (int, bool)) or issubclass(elem_type, x.UVarintType) or issubclass(elem_type, x.IntType):
return set_elem(obj, elem)
elif issubclass(elem_type, x.BlobType) or isinstance(obj, bytes) or isinstance(obj, bytearray):
return set_elem(obj, await dump_blob(elem))
elif issubclass(elem_type, x.UnicodeType) or isinstance(elem, str):
return set_elem(obj, elem)
elif issubclass(elem_type, x.VariantType):
return set_elem(obj, await dump_variant(None, elem, elem_type, params))
elif issubclass(elem_type, x.ContainerType): # container ~ simple list
return set_elem(obj, await dump_container(None, elem, elem_type, params))
elif issubclass(elem_type, x.MessageType):
return set_elem(obj, await dump_message(None, elem))
else:
raise TypeError | [
"async",
"def",
"dump_field",
"(",
"obj",
",",
"elem",
",",
"elem_type",
",",
"params",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"elem",
",",
"(",
"int",
",",
"bool",
")",
")",
"or",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"UVarintType",
")",
"or",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"IntType",
")",
":",
"return",
"set_elem",
"(",
"obj",
",",
"elem",
")",
"elif",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"BlobType",
")",
"or",
"isinstance",
"(",
"obj",
",",
"bytes",
")",
"or",
"isinstance",
"(",
"obj",
",",
"bytearray",
")",
":",
"return",
"set_elem",
"(",
"obj",
",",
"await",
"dump_blob",
"(",
"elem",
")",
")",
"elif",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"UnicodeType",
")",
"or",
"isinstance",
"(",
"elem",
",",
"str",
")",
":",
"return",
"set_elem",
"(",
"obj",
",",
"elem",
")",
"elif",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"VariantType",
")",
":",
"return",
"set_elem",
"(",
"obj",
",",
"await",
"dump_variant",
"(",
"None",
",",
"elem",
",",
"elem_type",
",",
"params",
")",
")",
"elif",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"ContainerType",
")",
":",
"# container ~ simple list",
"return",
"set_elem",
"(",
"obj",
",",
"await",
"dump_container",
"(",
"None",
",",
"elem",
",",
"elem_type",
",",
"params",
")",
")",
"elif",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"MessageType",
")",
":",
"return",
"set_elem",
"(",
"obj",
",",
"await",
"dump_message",
"(",
"None",
",",
"elem",
")",
")",
"else",
":",
"raise",
"TypeError"
] | Dumps generic field to the popo object representation, according to the element specification.
General multiplexer.
:param obj:
:param elem:
:param elem_type:
:param params:
:return: | [
"Dumps",
"generic",
"field",
"to",
"the",
"popo",
"object",
"representation",
"according",
"to",
"the",
"element",
"specification",
".",
"General",
"multiplexer",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrobj.py#L283-L313 | train |
ph4r05/monero-serialize | monero_serialize/xmrobj.py | load_field | async def load_field(obj, elem_type, params=None, elem=None):
"""
Loads a field from the reader, based on the field type specification. Demultiplexer.
:param obj:
:param elem_type:
:param params:
:param elem:
:return:
"""
if issubclass(elem_type, x.UVarintType) or issubclass(elem_type, x.IntType) or isinstance(obj, (int, bool)):
return set_elem(elem, obj)
elif issubclass(elem_type, x.BlobType):
fvalue = await load_blob(obj, elem_type)
return set_elem(elem, fvalue)
elif issubclass(elem_type, x.UnicodeType) or isinstance(elem, str):
return set_elem(elem, obj)
elif issubclass(elem_type, x.VariantType):
fvalue = await load_variant(obj, elem=get_elem(elem), elem_type=elem_type, params=params)
return set_elem(elem, fvalue)
elif issubclass(elem_type, x.ContainerType): # container ~ simple list
fvalue = await load_container(obj, elem_type, params=params, container=get_elem(elem))
return set_elem(elem, fvalue)
elif issubclass(elem_type, x.MessageType):
fvalue = await load_message(obj, msg_type=elem_type, msg=get_elem(elem))
return set_elem(elem, fvalue)
else:
raise TypeError | python | async def load_field(obj, elem_type, params=None, elem=None):
"""
Loads a field from the reader, based on the field type specification. Demultiplexer.
:param obj:
:param elem_type:
:param params:
:param elem:
:return:
"""
if issubclass(elem_type, x.UVarintType) or issubclass(elem_type, x.IntType) or isinstance(obj, (int, bool)):
return set_elem(elem, obj)
elif issubclass(elem_type, x.BlobType):
fvalue = await load_blob(obj, elem_type)
return set_elem(elem, fvalue)
elif issubclass(elem_type, x.UnicodeType) or isinstance(elem, str):
return set_elem(elem, obj)
elif issubclass(elem_type, x.VariantType):
fvalue = await load_variant(obj, elem=get_elem(elem), elem_type=elem_type, params=params)
return set_elem(elem, fvalue)
elif issubclass(elem_type, x.ContainerType): # container ~ simple list
fvalue = await load_container(obj, elem_type, params=params, container=get_elem(elem))
return set_elem(elem, fvalue)
elif issubclass(elem_type, x.MessageType):
fvalue = await load_message(obj, msg_type=elem_type, msg=get_elem(elem))
return set_elem(elem, fvalue)
else:
raise TypeError | [
"async",
"def",
"load_field",
"(",
"obj",
",",
"elem_type",
",",
"params",
"=",
"None",
",",
"elem",
"=",
"None",
")",
":",
"if",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"UVarintType",
")",
"or",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"IntType",
")",
"or",
"isinstance",
"(",
"obj",
",",
"(",
"int",
",",
"bool",
")",
")",
":",
"return",
"set_elem",
"(",
"elem",
",",
"obj",
")",
"elif",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"BlobType",
")",
":",
"fvalue",
"=",
"await",
"load_blob",
"(",
"obj",
",",
"elem_type",
")",
"return",
"set_elem",
"(",
"elem",
",",
"fvalue",
")",
"elif",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"UnicodeType",
")",
"or",
"isinstance",
"(",
"elem",
",",
"str",
")",
":",
"return",
"set_elem",
"(",
"elem",
",",
"obj",
")",
"elif",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"VariantType",
")",
":",
"fvalue",
"=",
"await",
"load_variant",
"(",
"obj",
",",
"elem",
"=",
"get_elem",
"(",
"elem",
")",
",",
"elem_type",
"=",
"elem_type",
",",
"params",
"=",
"params",
")",
"return",
"set_elem",
"(",
"elem",
",",
"fvalue",
")",
"elif",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"ContainerType",
")",
":",
"# container ~ simple list",
"fvalue",
"=",
"await",
"load_container",
"(",
"obj",
",",
"elem_type",
",",
"params",
"=",
"params",
",",
"container",
"=",
"get_elem",
"(",
"elem",
")",
")",
"return",
"set_elem",
"(",
"elem",
",",
"fvalue",
")",
"elif",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"MessageType",
")",
":",
"fvalue",
"=",
"await",
"load_message",
"(",
"obj",
",",
"msg_type",
"=",
"elem_type",
",",
"msg",
"=",
"get_elem",
"(",
"elem",
")",
")",
"return",
"set_elem",
"(",
"elem",
",",
"fvalue",
")",
"else",
":",
"raise",
"TypeError"
] | Loads a field from the reader, based on the field type specification. Demultiplexer.
:param obj:
:param elem_type:
:param params:
:param elem:
:return: | [
"Loads",
"a",
"field",
"from",
"the",
"reader",
"based",
"on",
"the",
"field",
"type",
"specification",
".",
"Demultiplexer",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrobj.py#L316-L349 | train |
Julian/Seep | seep/core.py | instantiate | def instantiate(data, blueprint):
"""
Instantiate the given data using the blueprinter.
Arguments
---------
blueprint (collections.Mapping):
a blueprint (JSON Schema with Seep properties)
"""
Validator = jsonschema.validators.validator_for(blueprint)
blueprinter = extend(Validator)(blueprint)
return blueprinter.instantiate(data) | python | def instantiate(data, blueprint):
"""
Instantiate the given data using the blueprinter.
Arguments
---------
blueprint (collections.Mapping):
a blueprint (JSON Schema with Seep properties)
"""
Validator = jsonschema.validators.validator_for(blueprint)
blueprinter = extend(Validator)(blueprint)
return blueprinter.instantiate(data) | [
"def",
"instantiate",
"(",
"data",
",",
"blueprint",
")",
":",
"Validator",
"=",
"jsonschema",
".",
"validators",
".",
"validator_for",
"(",
"blueprint",
")",
"blueprinter",
"=",
"extend",
"(",
"Validator",
")",
"(",
"blueprint",
")",
"return",
"blueprinter",
".",
"instantiate",
"(",
"data",
")"
] | Instantiate the given data using the blueprinter.
Arguments
---------
blueprint (collections.Mapping):
a blueprint (JSON Schema with Seep properties) | [
"Instantiate",
"the",
"given",
"data",
"using",
"the",
"blueprinter",
"."
] | 57b5f391d0e23afb7777293a9002125967a014ad | https://github.com/Julian/Seep/blob/57b5f391d0e23afb7777293a9002125967a014ad/seep/core.py#L35-L49 | train |
dbarsam/python-vsgen | vsgen/__main__.py | main | def main(argv=None):
"""
The entry point of the script.
"""
from vsgen import VSGSuite
from vsgen import VSGLogger
# Special case to use the sys.argv when main called without a list.
if argv is None:
argv = sys.argv
# Initialize the application logger
pylogger = VSGLogger()
# Construct a command line parser and parse the command line
args = VSGSuite.make_parser(description='Executes the vsgen package as an application.').parse_args(argv[1:])
for s in VSGSuite.from_args(**vars(args)):
s.write(False)
return 0 | python | def main(argv=None):
"""
The entry point of the script.
"""
from vsgen import VSGSuite
from vsgen import VSGLogger
# Special case to use the sys.argv when main called without a list.
if argv is None:
argv = sys.argv
# Initialize the application logger
pylogger = VSGLogger()
# Construct a command line parser and parse the command line
args = VSGSuite.make_parser(description='Executes the vsgen package as an application.').parse_args(argv[1:])
for s in VSGSuite.from_args(**vars(args)):
s.write(False)
return 0 | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"from",
"vsgen",
"import",
"VSGSuite",
"from",
"vsgen",
"import",
"VSGLogger",
"# Special case to use the sys.argv when main called without a list.",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"# Initialize the application logger",
"pylogger",
"=",
"VSGLogger",
"(",
")",
"# Construct a command line parser and parse the command line",
"args",
"=",
"VSGSuite",
".",
"make_parser",
"(",
"description",
"=",
"'Executes the vsgen package as an application.'",
")",
".",
"parse_args",
"(",
"argv",
"[",
"1",
":",
"]",
")",
"for",
"s",
"in",
"VSGSuite",
".",
"from_args",
"(",
"*",
"*",
"vars",
"(",
"args",
")",
")",
":",
"s",
".",
"write",
"(",
"False",
")",
"return",
"0"
] | The entry point of the script. | [
"The",
"entry",
"point",
"of",
"the",
"script",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/__main__.py#L19-L37 | train |
ets-labs/python-domain-models | domain_models/models.py | DomainModelMetaClass.parse_fields | def parse_fields(attributes):
"""Parse model fields."""
return tuple(field.bind_name(name)
for name, field in six.iteritems(attributes)
if isinstance(field, fields.Field)) | python | def parse_fields(attributes):
"""Parse model fields."""
return tuple(field.bind_name(name)
for name, field in six.iteritems(attributes)
if isinstance(field, fields.Field)) | [
"def",
"parse_fields",
"(",
"attributes",
")",
":",
"return",
"tuple",
"(",
"field",
".",
"bind_name",
"(",
"name",
")",
"for",
"name",
",",
"field",
"in",
"six",
".",
"iteritems",
"(",
"attributes",
")",
"if",
"isinstance",
"(",
"field",
",",
"fields",
".",
"Field",
")",
")"
] | Parse model fields. | [
"Parse",
"model",
"fields",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/models.py#L38-L42 | train |
ets-labs/python-domain-models | domain_models/models.py | DomainModelMetaClass.prepare_fields_attribute | def prepare_fields_attribute(attribute_name, attributes, class_name):
"""Prepare model fields attribute."""
attribute = attributes.get(attribute_name)
if not attribute:
attribute = tuple()
elif isinstance(attribute, std_collections.Iterable):
attribute = tuple(attribute)
else:
raise errors.Error('{0}.{1} is supposed to be a list of {2}, '
'instead {3} given', class_name, attribute_name,
fields.Field, attribute)
return attribute | python | def prepare_fields_attribute(attribute_name, attributes, class_name):
"""Prepare model fields attribute."""
attribute = attributes.get(attribute_name)
if not attribute:
attribute = tuple()
elif isinstance(attribute, std_collections.Iterable):
attribute = tuple(attribute)
else:
raise errors.Error('{0}.{1} is supposed to be a list of {2}, '
'instead {3} given', class_name, attribute_name,
fields.Field, attribute)
return attribute | [
"def",
"prepare_fields_attribute",
"(",
"attribute_name",
",",
"attributes",
",",
"class_name",
")",
":",
"attribute",
"=",
"attributes",
".",
"get",
"(",
"attribute_name",
")",
"if",
"not",
"attribute",
":",
"attribute",
"=",
"tuple",
"(",
")",
"elif",
"isinstance",
"(",
"attribute",
",",
"std_collections",
".",
"Iterable",
")",
":",
"attribute",
"=",
"tuple",
"(",
"attribute",
")",
"else",
":",
"raise",
"errors",
".",
"Error",
"(",
"'{0}.{1} is supposed to be a list of {2}, '",
"'instead {3} given'",
",",
"class_name",
",",
"attribute_name",
",",
"fields",
".",
"Field",
",",
"attribute",
")",
"return",
"attribute"
] | Prepare model fields attribute. | [
"Prepare",
"model",
"fields",
"attribute",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/models.py#L50-L61 | train |
ets-labs/python-domain-models | domain_models/models.py | DomainModelMetaClass.bind_fields_to_model_cls | def bind_fields_to_model_cls(cls, model_fields):
"""Bind fields to model class."""
return dict(
(field.name, field.bind_model_cls(cls)) for field in model_fields) | python | def bind_fields_to_model_cls(cls, model_fields):
"""Bind fields to model class."""
return dict(
(field.name, field.bind_model_cls(cls)) for field in model_fields) | [
"def",
"bind_fields_to_model_cls",
"(",
"cls",
",",
"model_fields",
")",
":",
"return",
"dict",
"(",
"(",
"field",
".",
"name",
",",
"field",
".",
"bind_model_cls",
"(",
"cls",
")",
")",
"for",
"field",
"in",
"model_fields",
")"
] | Bind fields to model class. | [
"Bind",
"fields",
"to",
"model",
"class",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/models.py#L64-L67 | train |
ets-labs/python-domain-models | domain_models/models.py | DomainModelMetaClass.bind_collection_to_model_cls | def bind_collection_to_model_cls(cls):
"""Bind collection to model's class.
If collection was not specialized in process of model's declaration,
subclass of collection will be created.
"""
cls.Collection = type('{0}.Collection'.format(cls.__name__),
(cls.Collection,),
{'value_type': cls})
cls.Collection.__module__ = cls.__module__ | python | def bind_collection_to_model_cls(cls):
"""Bind collection to model's class.
If collection was not specialized in process of model's declaration,
subclass of collection will be created.
"""
cls.Collection = type('{0}.Collection'.format(cls.__name__),
(cls.Collection,),
{'value_type': cls})
cls.Collection.__module__ = cls.__module__ | [
"def",
"bind_collection_to_model_cls",
"(",
"cls",
")",
":",
"cls",
".",
"Collection",
"=",
"type",
"(",
"'{0}.Collection'",
".",
"format",
"(",
"cls",
".",
"__name__",
")",
",",
"(",
"cls",
".",
"Collection",
",",
")",
",",
"{",
"'value_type'",
":",
"cls",
"}",
")",
"cls",
".",
"Collection",
".",
"__module__",
"=",
"cls",
".",
"__module__"
] | Bind collection to model's class.
If collection was not specialized in process of model's declaration,
subclass of collection will be created. | [
"Bind",
"collection",
"to",
"model",
"s",
"class",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/models.py#L70-L79 | train |
jenisys/parse_type | tasks/release.py | checklist | def checklist(ctx):
"""Checklist for releasing this project."""
checklist = """PRE-RELEASE CHECKLIST:
[ ] Everything is checked in
[ ] All tests pass w/ tox
RELEASE CHECKLIST:
[{x1}] Bump version to new-version and tag repository (via bump_version)
[{x2}] Build packages (sdist, bdist_wheel via prepare)
[{x3}] Register and upload packages to testpypi repository (first)
[{x4}] Verify release is OK and packages from testpypi are usable
[{x5}] Register and upload packages to pypi repository
[{x6}] Push last changes to Github repository
POST-RELEASE CHECKLIST:
[ ] Bump version to new-develop-version (via bump_version)
[ ] Adapt CHANGES (if necessary)
[ ] Commit latest changes to Github repository
"""
steps = dict(x1=None, x2=None, x3=None, x4=None, x5=None, x6=None)
yesno_map = {True: "x", False: "_", None: " "}
answers = {name: yesno_map[value]
for name, value in steps.items()}
print(checklist.format(**answers)) | python | def checklist(ctx):
"""Checklist for releasing this project."""
checklist = """PRE-RELEASE CHECKLIST:
[ ] Everything is checked in
[ ] All tests pass w/ tox
RELEASE CHECKLIST:
[{x1}] Bump version to new-version and tag repository (via bump_version)
[{x2}] Build packages (sdist, bdist_wheel via prepare)
[{x3}] Register and upload packages to testpypi repository (first)
[{x4}] Verify release is OK and packages from testpypi are usable
[{x5}] Register and upload packages to pypi repository
[{x6}] Push last changes to Github repository
POST-RELEASE CHECKLIST:
[ ] Bump version to new-develop-version (via bump_version)
[ ] Adapt CHANGES (if necessary)
[ ] Commit latest changes to Github repository
"""
steps = dict(x1=None, x2=None, x3=None, x4=None, x5=None, x6=None)
yesno_map = {True: "x", False: "_", None: " "}
answers = {name: yesno_map[value]
for name, value in steps.items()}
print(checklist.format(**answers)) | [
"def",
"checklist",
"(",
"ctx",
")",
":",
"checklist",
"=",
"\"\"\"PRE-RELEASE CHECKLIST:\n[ ] Everything is checked in\n[ ] All tests pass w/ tox\n\nRELEASE CHECKLIST:\n[{x1}] Bump version to new-version and tag repository (via bump_version)\n[{x2}] Build packages (sdist, bdist_wheel via prepare)\n[{x3}] Register and upload packages to testpypi repository (first)\n[{x4}] Verify release is OK and packages from testpypi are usable\n[{x5}] Register and upload packages to pypi repository\n[{x6}] Push last changes to Github repository\n\nPOST-RELEASE CHECKLIST:\n[ ] Bump version to new-develop-version (via bump_version)\n[ ] Adapt CHANGES (if necessary)\n[ ] Commit latest changes to Github repository\n\"\"\"",
"steps",
"=",
"dict",
"(",
"x1",
"=",
"None",
",",
"x2",
"=",
"None",
",",
"x3",
"=",
"None",
",",
"x4",
"=",
"None",
",",
"x5",
"=",
"None",
",",
"x6",
"=",
"None",
")",
"yesno_map",
"=",
"{",
"True",
":",
"\"x\"",
",",
"False",
":",
"\"_\"",
",",
"None",
":",
"\" \"",
"}",
"answers",
"=",
"{",
"name",
":",
"yesno_map",
"[",
"value",
"]",
"for",
"name",
",",
"value",
"in",
"steps",
".",
"items",
"(",
")",
"}",
"print",
"(",
"checklist",
".",
"format",
"(",
"*",
"*",
"answers",
")",
")"
] | Checklist for releasing this project. | [
"Checklist",
"for",
"releasing",
"this",
"project",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/tasks/release.py#L61-L84 | train |
jenisys/parse_type | tasks/release.py | build_packages | def build_packages(ctx, hide=False):
"""Build packages for this release."""
print("build_packages:")
ctx.run("python setup.py sdist bdist_wheel", echo=True, hide=hide) | python | def build_packages(ctx, hide=False):
"""Build packages for this release."""
print("build_packages:")
ctx.run("python setup.py sdist bdist_wheel", echo=True, hide=hide) | [
"def",
"build_packages",
"(",
"ctx",
",",
"hide",
"=",
"False",
")",
":",
"print",
"(",
"\"build_packages:\"",
")",
"ctx",
".",
"run",
"(",
"\"python setup.py sdist bdist_wheel\"",
",",
"echo",
"=",
"True",
",",
"hide",
"=",
"hide",
")"
] | Build packages for this release. | [
"Build",
"packages",
"for",
"this",
"release",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/tasks/release.py#L98-L101 | train |
useblocks/groundwork | groundwork/patterns/gw_threads_pattern.py | ThreadsListPlugin.register | def register(self, name, function, description=None):
"""
Register a new thread.
:param function: Function, which gets called for the new thread
:type function: function
:param name: Unique name of the thread for documentation purposes.
:param description: Short description of the thread
"""
return self.__app.threads.register(name, function, self._plugin, description) | python | def register(self, name, function, description=None):
"""
Register a new thread.
:param function: Function, which gets called for the new thread
:type function: function
:param name: Unique name of the thread for documentation purposes.
:param description: Short description of the thread
"""
return self.__app.threads.register(name, function, self._plugin, description) | [
"def",
"register",
"(",
"self",
",",
"name",
",",
"function",
",",
"description",
"=",
"None",
")",
":",
"return",
"self",
".",
"__app",
".",
"threads",
".",
"register",
"(",
"name",
",",
"function",
",",
"self",
".",
"_plugin",
",",
"description",
")"
] | Register a new thread.
:param function: Function, which gets called for the new thread
:type function: function
:param name: Unique name of the thread for documentation purposes.
:param description: Short description of the thread | [
"Register",
"a",
"new",
"thread",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_threads_pattern.py#L60-L69 | train |
useblocks/groundwork | groundwork/patterns/gw_threads_pattern.py | ThreadsListApplication.unregister | def unregister(self, thread):
"""
Unregisters an existing thread, so that this thread is no longer available.
This function is mainly used during plugin deactivation.
:param thread: Name of the thread
"""
if thread not in self.threads.keys():
self.log.warning("Can not unregister thread %s" % thread)
else:
del (self.threads[thread])
self.__log.debug("Thread %s got unregistered" % thread) | python | def unregister(self, thread):
"""
Unregisters an existing thread, so that this thread is no longer available.
This function is mainly used during plugin deactivation.
:param thread: Name of the thread
"""
if thread not in self.threads.keys():
self.log.warning("Can not unregister thread %s" % thread)
else:
del (self.threads[thread])
self.__log.debug("Thread %s got unregistered" % thread) | [
"def",
"unregister",
"(",
"self",
",",
"thread",
")",
":",
"if",
"thread",
"not",
"in",
"self",
".",
"threads",
".",
"keys",
"(",
")",
":",
"self",
".",
"log",
".",
"warning",
"(",
"\"Can not unregister thread %s\"",
"%",
"thread",
")",
"else",
":",
"del",
"(",
"self",
".",
"threads",
"[",
"thread",
"]",
")",
"self",
".",
"__log",
".",
"debug",
"(",
"\"Thread %s got unregistered\"",
"%",
"thread",
")"
] | Unregisters an existing thread, so that this thread is no longer available.
This function is mainly used during plugin deactivation.
:param thread: Name of the thread | [
"Unregisters",
"an",
"existing",
"thread",
"so",
"that",
"this",
"thread",
"is",
"no",
"longer",
"available",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_threads_pattern.py#L111-L123 | train |
useblocks/groundwork | groundwork/patterns/gw_threads_pattern.py | ThreadsListApplication.get | def get(self, thread=None, plugin=None):
"""
Get one or more threads.
:param thread: Name of the thread
:type thread: str
:param plugin: Plugin object, under which the thread was registered
:type plugin: GwBasePattern
"""
if plugin is not None:
if thread is None:
threads_list = {}
for key in self.threads.keys():
if self.threads[key].plugin == plugin:
threads_list[key] = self.threads[key]
return threads_list
else:
if thread in self.threads.keys():
if self.threads[thread].plugin == plugin:
return self.threads[thread]
else:
return None
else:
return None
else:
if thread is None:
return self.threads
else:
if thread in self.threads.keys():
return self.threads[thread]
else:
return None | python | def get(self, thread=None, plugin=None):
"""
Get one or more threads.
:param thread: Name of the thread
:type thread: str
:param plugin: Plugin object, under which the thread was registered
:type plugin: GwBasePattern
"""
if plugin is not None:
if thread is None:
threads_list = {}
for key in self.threads.keys():
if self.threads[key].plugin == plugin:
threads_list[key] = self.threads[key]
return threads_list
else:
if thread in self.threads.keys():
if self.threads[thread].plugin == plugin:
return self.threads[thread]
else:
return None
else:
return None
else:
if thread is None:
return self.threads
else:
if thread in self.threads.keys():
return self.threads[thread]
else:
return None | [
"def",
"get",
"(",
"self",
",",
"thread",
"=",
"None",
",",
"plugin",
"=",
"None",
")",
":",
"if",
"plugin",
"is",
"not",
"None",
":",
"if",
"thread",
"is",
"None",
":",
"threads_list",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"threads",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"threads",
"[",
"key",
"]",
".",
"plugin",
"==",
"plugin",
":",
"threads_list",
"[",
"key",
"]",
"=",
"self",
".",
"threads",
"[",
"key",
"]",
"return",
"threads_list",
"else",
":",
"if",
"thread",
"in",
"self",
".",
"threads",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"threads",
"[",
"thread",
"]",
".",
"plugin",
"==",
"plugin",
":",
"return",
"self",
".",
"threads",
"[",
"thread",
"]",
"else",
":",
"return",
"None",
"else",
":",
"return",
"None",
"else",
":",
"if",
"thread",
"is",
"None",
":",
"return",
"self",
".",
"threads",
"else",
":",
"if",
"thread",
"in",
"self",
".",
"threads",
".",
"keys",
"(",
")",
":",
"return",
"self",
".",
"threads",
"[",
"thread",
"]",
"else",
":",
"return",
"None"
] | Get one or more threads.
:param thread: Name of the thread
:type thread: str
:param plugin: Plugin object, under which the thread was registered
:type plugin: GwBasePattern | [
"Get",
"one",
"or",
"more",
"threads",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_threads_pattern.py#L125-L156 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/schema.py | create_schema_from_xsd_directory | def create_schema_from_xsd_directory(directory, version):
"""Create and fill the schema from a directory which contains xsd
files. It calls fill_schema_from_xsd_file for each xsd file
found.
"""
schema = Schema(version)
for f in _get_xsd_from_directory(directory):
logger.info("Loading schema %s" % f)
fill_schema_from_xsd_file(f, schema)
return schema | python | def create_schema_from_xsd_directory(directory, version):
"""Create and fill the schema from a directory which contains xsd
files. It calls fill_schema_from_xsd_file for each xsd file
found.
"""
schema = Schema(version)
for f in _get_xsd_from_directory(directory):
logger.info("Loading schema %s" % f)
fill_schema_from_xsd_file(f, schema)
return schema | [
"def",
"create_schema_from_xsd_directory",
"(",
"directory",
",",
"version",
")",
":",
"schema",
"=",
"Schema",
"(",
"version",
")",
"for",
"f",
"in",
"_get_xsd_from_directory",
"(",
"directory",
")",
":",
"logger",
".",
"info",
"(",
"\"Loading schema %s\"",
"%",
"f",
")",
"fill_schema_from_xsd_file",
"(",
"f",
",",
"schema",
")",
"return",
"schema"
] | Create and fill the schema from a directory which contains xsd
files. It calls fill_schema_from_xsd_file for each xsd file
found. | [
"Create",
"and",
"fill",
"the",
"schema",
"from",
"a",
"directory",
"which",
"contains",
"xsd",
"files",
".",
"It",
"calls",
"fill_schema_from_xsd_file",
"for",
"each",
"xsd",
"file",
"found",
"."
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/schema.py#L103-L113 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/schema.py | fill_schema_from_xsd_file | def fill_schema_from_xsd_file(filename, schema):
"""From an xsd file, it fills the schema by creating needed
Resource. The generateds idl_parser is used to parse ifmap
statements in the xsd file.
"""
ifmap_statements = _parse_xsd_file(filename)
properties_all = []
for v in ifmap_statements.values():
if (isinstance(v[0], IDLParser.Link)):
src_name = v[1]
target_name = v[2]
src = schema._get_or_add_resource(src_name)
target = schema._get_or_add_resource(target_name)
if "has" in v[3]:
src.children.append(target_name)
target.parent = src_name
if "ref" in v[3]:
src.refs.append(target_name)
target.back_refs.append(src_name)
elif isinstance(v[0], IDLParser.Property):
target_name = v[1][0]
prop = ResourceProperty(v[0].name, is_list=v[0].is_list, is_map=v[0].is_map)
if target_name != 'all':
target = schema._get_or_add_resource(target_name)
target.properties.append(prop)
else:
properties_all.append(prop)
for r in schema.all_resources():
schema.resource(r).properties += properties_all | python | def fill_schema_from_xsd_file(filename, schema):
"""From an xsd file, it fills the schema by creating needed
Resource. The generateds idl_parser is used to parse ifmap
statements in the xsd file.
"""
ifmap_statements = _parse_xsd_file(filename)
properties_all = []
for v in ifmap_statements.values():
if (isinstance(v[0], IDLParser.Link)):
src_name = v[1]
target_name = v[2]
src = schema._get_or_add_resource(src_name)
target = schema._get_or_add_resource(target_name)
if "has" in v[3]:
src.children.append(target_name)
target.parent = src_name
if "ref" in v[3]:
src.refs.append(target_name)
target.back_refs.append(src_name)
elif isinstance(v[0], IDLParser.Property):
target_name = v[1][0]
prop = ResourceProperty(v[0].name, is_list=v[0].is_list, is_map=v[0].is_map)
if target_name != 'all':
target = schema._get_or_add_resource(target_name)
target.properties.append(prop)
else:
properties_all.append(prop)
for r in schema.all_resources():
schema.resource(r).properties += properties_all | [
"def",
"fill_schema_from_xsd_file",
"(",
"filename",
",",
"schema",
")",
":",
"ifmap_statements",
"=",
"_parse_xsd_file",
"(",
"filename",
")",
"properties_all",
"=",
"[",
"]",
"for",
"v",
"in",
"ifmap_statements",
".",
"values",
"(",
")",
":",
"if",
"(",
"isinstance",
"(",
"v",
"[",
"0",
"]",
",",
"IDLParser",
".",
"Link",
")",
")",
":",
"src_name",
"=",
"v",
"[",
"1",
"]",
"target_name",
"=",
"v",
"[",
"2",
"]",
"src",
"=",
"schema",
".",
"_get_or_add_resource",
"(",
"src_name",
")",
"target",
"=",
"schema",
".",
"_get_or_add_resource",
"(",
"target_name",
")",
"if",
"\"has\"",
"in",
"v",
"[",
"3",
"]",
":",
"src",
".",
"children",
".",
"append",
"(",
"target_name",
")",
"target",
".",
"parent",
"=",
"src_name",
"if",
"\"ref\"",
"in",
"v",
"[",
"3",
"]",
":",
"src",
".",
"refs",
".",
"append",
"(",
"target_name",
")",
"target",
".",
"back_refs",
".",
"append",
"(",
"src_name",
")",
"elif",
"isinstance",
"(",
"v",
"[",
"0",
"]",
",",
"IDLParser",
".",
"Property",
")",
":",
"target_name",
"=",
"v",
"[",
"1",
"]",
"[",
"0",
"]",
"prop",
"=",
"ResourceProperty",
"(",
"v",
"[",
"0",
"]",
".",
"name",
",",
"is_list",
"=",
"v",
"[",
"0",
"]",
".",
"is_list",
",",
"is_map",
"=",
"v",
"[",
"0",
"]",
".",
"is_map",
")",
"if",
"target_name",
"!=",
"'all'",
":",
"target",
"=",
"schema",
".",
"_get_or_add_resource",
"(",
"target_name",
")",
"target",
".",
"properties",
".",
"append",
"(",
"prop",
")",
"else",
":",
"properties_all",
".",
"append",
"(",
"prop",
")",
"for",
"r",
"in",
"schema",
".",
"all_resources",
"(",
")",
":",
"schema",
".",
"resource",
"(",
"r",
")",
".",
"properties",
"+=",
"properties_all"
] | From an xsd file, it fills the schema by creating needed
Resource. The generateds idl_parser is used to parse ifmap
statements in the xsd file. | [
"From",
"an",
"xsd",
"file",
"it",
"fills",
"the",
"schema",
"by",
"creating",
"needed",
"Resource",
".",
"The",
"generateds",
"idl_parser",
"is",
"used",
"to",
"parse",
"ifmap",
"statements",
"in",
"the",
"xsd",
"file",
"."
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/schema.py#L116-L147 | train |
theiviaxx/python-perforce | perforce/models.py | split_ls | def split_ls(func):
"""Decorator to split files into manageable chunks as not to exceed the windows cmd limit
:param func: Function to call for each chunk
:type func: :py:class:Function
"""
@wraps(func)
def wrapper(self, files, silent=True, exclude_deleted=False):
if not isinstance(files, (tuple, list)):
files = [files]
counter = 0
index = 0
results = []
while files:
if index >= len(files):
results += func(self, files, silent, exclude_deleted)
break
length = len(str(files[index]))
if length + counter > CHAR_LIMIT:
# -- at our limit
runfiles = files[:index]
files = files[index:]
counter = 0
index = 0
results += func(self, runfiles, silent, exclude_deleted)
runfiles = None
del runfiles
else:
index += 1
counter += length
return results
return wrapper | python | def split_ls(func):
"""Decorator to split files into manageable chunks as not to exceed the windows cmd limit
:param func: Function to call for each chunk
:type func: :py:class:Function
"""
@wraps(func)
def wrapper(self, files, silent=True, exclude_deleted=False):
if not isinstance(files, (tuple, list)):
files = [files]
counter = 0
index = 0
results = []
while files:
if index >= len(files):
results += func(self, files, silent, exclude_deleted)
break
length = len(str(files[index]))
if length + counter > CHAR_LIMIT:
# -- at our limit
runfiles = files[:index]
files = files[index:]
counter = 0
index = 0
results += func(self, runfiles, silent, exclude_deleted)
runfiles = None
del runfiles
else:
index += 1
counter += length
return results
return wrapper | [
"def",
"split_ls",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"files",
",",
"silent",
"=",
"True",
",",
"exclude_deleted",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"files",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"files",
"=",
"[",
"files",
"]",
"counter",
"=",
"0",
"index",
"=",
"0",
"results",
"=",
"[",
"]",
"while",
"files",
":",
"if",
"index",
">=",
"len",
"(",
"files",
")",
":",
"results",
"+=",
"func",
"(",
"self",
",",
"files",
",",
"silent",
",",
"exclude_deleted",
")",
"break",
"length",
"=",
"len",
"(",
"str",
"(",
"files",
"[",
"index",
"]",
")",
")",
"if",
"length",
"+",
"counter",
">",
"CHAR_LIMIT",
":",
"# -- at our limit",
"runfiles",
"=",
"files",
"[",
":",
"index",
"]",
"files",
"=",
"files",
"[",
"index",
":",
"]",
"counter",
"=",
"0",
"index",
"=",
"0",
"results",
"+=",
"func",
"(",
"self",
",",
"runfiles",
",",
"silent",
",",
"exclude_deleted",
")",
"runfiles",
"=",
"None",
"del",
"runfiles",
"else",
":",
"index",
"+=",
"1",
"counter",
"+=",
"length",
"return",
"results",
"return",
"wrapper"
] | Decorator to split files into manageable chunks as not to exceed the windows cmd limit
:param func: Function to call for each chunk
:type func: :py:class:Function | [
"Decorator",
"to",
"split",
"files",
"into",
"manageable",
"chunks",
"as",
"not",
"to",
"exceed",
"the",
"windows",
"cmd",
"limit"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L69-L105 | train |
theiviaxx/python-perforce | perforce/models.py | Connection.__getVariables | def __getVariables(self):
"""Parses the P4 env vars using 'set p4'"""
try:
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
output = subprocess.check_output(['p4', 'set'], startupinfo=startupinfo)
if six.PY3:
output = str(output, 'utf8')
except subprocess.CalledProcessError as err:
LOGGER.error(err)
return
p4vars = {}
for line in output.splitlines():
if not line:
continue
try:
k, v = line.split('=', 1)
except ValueError:
continue
p4vars[k.strip()] = v.strip().split(' (')[0]
if p4vars[k.strip()].startswith('(config'):
del p4vars[k.strip()]
self._port = self._port or os.getenv('P4PORT', p4vars.get('P4PORT'))
self._user = self._user or os.getenv('P4USER', p4vars.get('P4USER'))
self._client = self._client or os.getenv('P4CLIENT', p4vars.get('P4CLIENT')) | python | def __getVariables(self):
"""Parses the P4 env vars using 'set p4'"""
try:
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
output = subprocess.check_output(['p4', 'set'], startupinfo=startupinfo)
if six.PY3:
output = str(output, 'utf8')
except subprocess.CalledProcessError as err:
LOGGER.error(err)
return
p4vars = {}
for line in output.splitlines():
if not line:
continue
try:
k, v = line.split('=', 1)
except ValueError:
continue
p4vars[k.strip()] = v.strip().split(' (')[0]
if p4vars[k.strip()].startswith('(config'):
del p4vars[k.strip()]
self._port = self._port or os.getenv('P4PORT', p4vars.get('P4PORT'))
self._user = self._user or os.getenv('P4USER', p4vars.get('P4USER'))
self._client = self._client or os.getenv('P4CLIENT', p4vars.get('P4CLIENT')) | [
"def",
"__getVariables",
"(",
"self",
")",
":",
"try",
":",
"startupinfo",
"=",
"None",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"startupinfo",
"=",
"subprocess",
".",
"STARTUPINFO",
"(",
")",
"startupinfo",
".",
"dwFlags",
"|=",
"subprocess",
".",
"STARTF_USESHOWWINDOW",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'p4'",
",",
"'set'",
"]",
",",
"startupinfo",
"=",
"startupinfo",
")",
"if",
"six",
".",
"PY3",
":",
"output",
"=",
"str",
"(",
"output",
",",
"'utf8'",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"err",
":",
"LOGGER",
".",
"error",
"(",
"err",
")",
"return",
"p4vars",
"=",
"{",
"}",
"for",
"line",
"in",
"output",
".",
"splitlines",
"(",
")",
":",
"if",
"not",
"line",
":",
"continue",
"try",
":",
"k",
",",
"v",
"=",
"line",
".",
"split",
"(",
"'='",
",",
"1",
")",
"except",
"ValueError",
":",
"continue",
"p4vars",
"[",
"k",
".",
"strip",
"(",
")",
"]",
"=",
"v",
".",
"strip",
"(",
")",
".",
"split",
"(",
"' ('",
")",
"[",
"0",
"]",
"if",
"p4vars",
"[",
"k",
".",
"strip",
"(",
")",
"]",
".",
"startswith",
"(",
"'(config'",
")",
":",
"del",
"p4vars",
"[",
"k",
".",
"strip",
"(",
")",
"]",
"self",
".",
"_port",
"=",
"self",
".",
"_port",
"or",
"os",
".",
"getenv",
"(",
"'P4PORT'",
",",
"p4vars",
".",
"get",
"(",
"'P4PORT'",
")",
")",
"self",
".",
"_user",
"=",
"self",
".",
"_user",
"or",
"os",
".",
"getenv",
"(",
"'P4USER'",
",",
"p4vars",
".",
"get",
"(",
"'P4USER'",
")",
")",
"self",
".",
"_client",
"=",
"self",
".",
"_client",
"or",
"os",
".",
"getenv",
"(",
"'P4CLIENT'",
",",
"p4vars",
".",
"get",
"(",
"'P4CLIENT'",
")",
")"
] | Parses the P4 env vars using 'set p4 | [
"Parses",
"the",
"P4",
"env",
"vars",
"using",
"set",
"p4"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L138-L166 | train |
theiviaxx/python-perforce | perforce/models.py | Connection.client | def client(self):
"""The client used in perforce queries"""
if isinstance(self._client, six.string_types):
self._client = Client(self._client, self)
return self._client | python | def client(self):
"""The client used in perforce queries"""
if isinstance(self._client, six.string_types):
self._client = Client(self._client, self)
return self._client | [
"def",
"client",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_client",
",",
"six",
".",
"string_types",
")",
":",
"self",
".",
"_client",
"=",
"Client",
"(",
"self",
".",
"_client",
",",
"self",
")",
"return",
"self",
".",
"_client"
] | The client used in perforce queries | [
"The",
"client",
"used",
"in",
"perforce",
"queries"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L169-L174 | train |
theiviaxx/python-perforce | perforce/models.py | Connection.status | def status(self):
"""The status of the connection to perforce"""
try:
# -- Check client
res = self.run(['info'])
if res[0]['clientName'] == '*unknown*':
return ConnectionStatus.INVALID_CLIENT
# -- Trigger an auth error if not logged in
self.run(['user', '-o'])
except errors.CommandError as err:
if 'password (P4PASSWD) invalid or unset' in str(err.args[0]):
return ConnectionStatus.NO_AUTH
if 'Connect to server failed' in str(err.args[0]):
return ConnectionStatus.OFFLINE
return ConnectionStatus.OK | python | def status(self):
"""The status of the connection to perforce"""
try:
# -- Check client
res = self.run(['info'])
if res[0]['clientName'] == '*unknown*':
return ConnectionStatus.INVALID_CLIENT
# -- Trigger an auth error if not logged in
self.run(['user', '-o'])
except errors.CommandError as err:
if 'password (P4PASSWD) invalid or unset' in str(err.args[0]):
return ConnectionStatus.NO_AUTH
if 'Connect to server failed' in str(err.args[0]):
return ConnectionStatus.OFFLINE
return ConnectionStatus.OK | [
"def",
"status",
"(",
"self",
")",
":",
"try",
":",
"# -- Check client",
"res",
"=",
"self",
".",
"run",
"(",
"[",
"'info'",
"]",
")",
"if",
"res",
"[",
"0",
"]",
"[",
"'clientName'",
"]",
"==",
"'*unknown*'",
":",
"return",
"ConnectionStatus",
".",
"INVALID_CLIENT",
"# -- Trigger an auth error if not logged in",
"self",
".",
"run",
"(",
"[",
"'user'",
",",
"'-o'",
"]",
")",
"except",
"errors",
".",
"CommandError",
"as",
"err",
":",
"if",
"'password (P4PASSWD) invalid or unset'",
"in",
"str",
"(",
"err",
".",
"args",
"[",
"0",
"]",
")",
":",
"return",
"ConnectionStatus",
".",
"NO_AUTH",
"if",
"'Connect to server failed'",
"in",
"str",
"(",
"err",
".",
"args",
"[",
"0",
"]",
")",
":",
"return",
"ConnectionStatus",
".",
"OFFLINE",
"return",
"ConnectionStatus",
".",
"OK"
] | The status of the connection to perforce | [
"The",
"status",
"of",
"the",
"connection",
"to",
"perforce"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L201-L216 | train |
theiviaxx/python-perforce | perforce/models.py | Connection.run | def run(self, cmd, stdin=None, marshal_output=True, **kwargs):
"""Runs a p4 command and returns a list of dictionary objects
:param cmd: Command to run
:type cmd: list
:param stdin: Standard Input to send to the process
:type stdin: str
:param marshal_output: Whether or not to marshal the output from the command
:type marshal_output: bool
:param kwargs: Passes any other keyword arguments to subprocess
:raises: :class:`.error.CommandError`
:returns: list, records of results
"""
records = []
args = [self._executable, "-u", self._user, "-p", self._port]
if self._client:
args += ["-c", str(self._client)]
if marshal_output:
args.append('-G')
if isinstance(cmd, six.string_types):
raise ValueError('String commands are not supported, please use a list')
args += cmd
command = ' '.join(args)
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(
args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
startupinfo=startupinfo,
**kwargs
)
if stdin:
proc.stdin.write(six.b(stdin))
if marshal_output:
try:
while True:
record = marshal.load(proc.stdout)
if record.get(b'code', '') == b'error' and record[b'severity'] >= self._level:
proc.stdin.close()
proc.stdout.close()
raise errors.CommandError(record[b'data'], record, command)
if isinstance(record, dict):
if six.PY2:
records.append(record)
else:
records.append({str(k, 'utf8'): str(v) if isinstance(v, int) else str(v, 'utf8', errors='ignore') for k, v in record.items()})
except EOFError:
pass
stdout, stderr = proc.communicate()
else:
records, stderr = proc.communicate()
if stderr:
raise errors.CommandError(stderr, command)
return records | python | def run(self, cmd, stdin=None, marshal_output=True, **kwargs):
"""Runs a p4 command and returns a list of dictionary objects
:param cmd: Command to run
:type cmd: list
:param stdin: Standard Input to send to the process
:type stdin: str
:param marshal_output: Whether or not to marshal the output from the command
:type marshal_output: bool
:param kwargs: Passes any other keyword arguments to subprocess
:raises: :class:`.error.CommandError`
:returns: list, records of results
"""
records = []
args = [self._executable, "-u", self._user, "-p", self._port]
if self._client:
args += ["-c", str(self._client)]
if marshal_output:
args.append('-G')
if isinstance(cmd, six.string_types):
raise ValueError('String commands are not supported, please use a list')
args += cmd
command = ' '.join(args)
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(
args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
startupinfo=startupinfo,
**kwargs
)
if stdin:
proc.stdin.write(six.b(stdin))
if marshal_output:
try:
while True:
record = marshal.load(proc.stdout)
if record.get(b'code', '') == b'error' and record[b'severity'] >= self._level:
proc.stdin.close()
proc.stdout.close()
raise errors.CommandError(record[b'data'], record, command)
if isinstance(record, dict):
if six.PY2:
records.append(record)
else:
records.append({str(k, 'utf8'): str(v) if isinstance(v, int) else str(v, 'utf8', errors='ignore') for k, v in record.items()})
except EOFError:
pass
stdout, stderr = proc.communicate()
else:
records, stderr = proc.communicate()
if stderr:
raise errors.CommandError(stderr, command)
return records | [
"def",
"run",
"(",
"self",
",",
"cmd",
",",
"stdin",
"=",
"None",
",",
"marshal_output",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"records",
"=",
"[",
"]",
"args",
"=",
"[",
"self",
".",
"_executable",
",",
"\"-u\"",
",",
"self",
".",
"_user",
",",
"\"-p\"",
",",
"self",
".",
"_port",
"]",
"if",
"self",
".",
"_client",
":",
"args",
"+=",
"[",
"\"-c\"",
",",
"str",
"(",
"self",
".",
"_client",
")",
"]",
"if",
"marshal_output",
":",
"args",
".",
"append",
"(",
"'-G'",
")",
"if",
"isinstance",
"(",
"cmd",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"'String commands are not supported, please use a list'",
")",
"args",
"+=",
"cmd",
"command",
"=",
"' '",
".",
"join",
"(",
"args",
")",
"startupinfo",
"=",
"None",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"startupinfo",
"=",
"subprocess",
".",
"STARTUPINFO",
"(",
")",
"startupinfo",
".",
"dwFlags",
"|=",
"subprocess",
".",
"STARTF_USESHOWWINDOW",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"startupinfo",
"=",
"startupinfo",
",",
"*",
"*",
"kwargs",
")",
"if",
"stdin",
":",
"proc",
".",
"stdin",
".",
"write",
"(",
"six",
".",
"b",
"(",
"stdin",
")",
")",
"if",
"marshal_output",
":",
"try",
":",
"while",
"True",
":",
"record",
"=",
"marshal",
".",
"load",
"(",
"proc",
".",
"stdout",
")",
"if",
"record",
".",
"get",
"(",
"b'code'",
",",
"''",
")",
"==",
"b'error'",
"and",
"record",
"[",
"b'severity'",
"]",
">=",
"self",
".",
"_level",
":",
"proc",
".",
"stdin",
".",
"close",
"(",
")",
"proc",
".",
"stdout",
".",
"close",
"(",
")",
"raise",
"errors",
".",
"CommandError",
"(",
"record",
"[",
"b'data'",
"]",
",",
"record",
",",
"command",
")",
"if",
"isinstance",
"(",
"record",
",",
"dict",
")",
":",
"if",
"six",
".",
"PY2",
":",
"records",
".",
"append",
"(",
"record",
")",
"else",
":",
"records",
".",
"append",
"(",
"{",
"str",
"(",
"k",
",",
"'utf8'",
")",
":",
"str",
"(",
"v",
")",
"if",
"isinstance",
"(",
"v",
",",
"int",
")",
"else",
"str",
"(",
"v",
",",
"'utf8'",
",",
"errors",
"=",
"'ignore'",
")",
"for",
"k",
",",
"v",
"in",
"record",
".",
"items",
"(",
")",
"}",
")",
"except",
"EOFError",
":",
"pass",
"stdout",
",",
"stderr",
"=",
"proc",
".",
"communicate",
"(",
")",
"else",
":",
"records",
",",
"stderr",
"=",
"proc",
".",
"communicate",
"(",
")",
"if",
"stderr",
":",
"raise",
"errors",
".",
"CommandError",
"(",
"stderr",
",",
"command",
")",
"return",
"records"
] | Runs a p4 command and returns a list of dictionary objects
:param cmd: Command to run
:type cmd: list
:param stdin: Standard Input to send to the process
:type stdin: str
:param marshal_output: Whether or not to marshal the output from the command
:type marshal_output: bool
:param kwargs: Passes any other keyword arguments to subprocess
:raises: :class:`.error.CommandError`
:returns: list, records of results | [
"Runs",
"a",
"p4",
"command",
"and",
"returns",
"a",
"list",
"of",
"dictionary",
"objects"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L218-L287 | train |
theiviaxx/python-perforce | perforce/models.py | Connection.findChangelist | def findChangelist(self, description=None):
"""Gets or creates a Changelist object with a description
:param description: The description to set or lookup
:type description: str
:returns: :class:`.Changelist`
"""
if description is None:
change = Default(self)
else:
if isinstance(description, six.integer_types):
change = Changelist(description, self)
else:
pending = self.run(['changes', '-l', '-s', 'pending', '-c', str(self._client), '-u', self._user])
for cl in pending:
if cl['desc'].strip() == description.strip():
LOGGER.debug('Changelist found: {}'.format(cl['change']))
change = Changelist(int(cl['change']), self)
break
else:
LOGGER.debug('No changelist found, creating one')
change = Changelist.create(description, self)
change.client = self._client
change.save()
return change | python | def findChangelist(self, description=None):
"""Gets or creates a Changelist object with a description
:param description: The description to set or lookup
:type description: str
:returns: :class:`.Changelist`
"""
if description is None:
change = Default(self)
else:
if isinstance(description, six.integer_types):
change = Changelist(description, self)
else:
pending = self.run(['changes', '-l', '-s', 'pending', '-c', str(self._client), '-u', self._user])
for cl in pending:
if cl['desc'].strip() == description.strip():
LOGGER.debug('Changelist found: {}'.format(cl['change']))
change = Changelist(int(cl['change']), self)
break
else:
LOGGER.debug('No changelist found, creating one')
change = Changelist.create(description, self)
change.client = self._client
change.save()
return change | [
"def",
"findChangelist",
"(",
"self",
",",
"description",
"=",
"None",
")",
":",
"if",
"description",
"is",
"None",
":",
"change",
"=",
"Default",
"(",
"self",
")",
"else",
":",
"if",
"isinstance",
"(",
"description",
",",
"six",
".",
"integer_types",
")",
":",
"change",
"=",
"Changelist",
"(",
"description",
",",
"self",
")",
"else",
":",
"pending",
"=",
"self",
".",
"run",
"(",
"[",
"'changes'",
",",
"'-l'",
",",
"'-s'",
",",
"'pending'",
",",
"'-c'",
",",
"str",
"(",
"self",
".",
"_client",
")",
",",
"'-u'",
",",
"self",
".",
"_user",
"]",
")",
"for",
"cl",
"in",
"pending",
":",
"if",
"cl",
"[",
"'desc'",
"]",
".",
"strip",
"(",
")",
"==",
"description",
".",
"strip",
"(",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Changelist found: {}'",
".",
"format",
"(",
"cl",
"[",
"'change'",
"]",
")",
")",
"change",
"=",
"Changelist",
"(",
"int",
"(",
"cl",
"[",
"'change'",
"]",
")",
",",
"self",
")",
"break",
"else",
":",
"LOGGER",
".",
"debug",
"(",
"'No changelist found, creating one'",
")",
"change",
"=",
"Changelist",
".",
"create",
"(",
"description",
",",
"self",
")",
"change",
".",
"client",
"=",
"self",
".",
"_client",
"change",
".",
"save",
"(",
")",
"return",
"change"
] | Gets or creates a Changelist object with a description
:param description: The description to set or lookup
:type description: str
:returns: :class:`.Changelist` | [
"Gets",
"or",
"creates",
"a",
"Changelist",
"object",
"with",
"a",
"description"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L320-L345 | train |
theiviaxx/python-perforce | perforce/models.py | Connection.add | def add(self, filename, change=None):
"""Adds a new file to a changelist
:param filename: File path to add
:type filename: str
:param change: Changelist to add the file to
:type change: int
:returns: :class:`.Revision`
"""
try:
if not self.canAdd(filename):
raise errors.RevisionError('File is not under client path')
if change is None:
self.run(['add', filename])
else:
self.run(['add', '-c', str(change.change), filename])
data = self.run(['fstat', filename])[0]
except errors.CommandError as err:
LOGGER.debug(err)
raise errors.RevisionError('File is not under client path')
rev = Revision(data, self)
if isinstance(change, Changelist):
change.append(rev)
return rev | python | def add(self, filename, change=None):
"""Adds a new file to a changelist
:param filename: File path to add
:type filename: str
:param change: Changelist to add the file to
:type change: int
:returns: :class:`.Revision`
"""
try:
if not self.canAdd(filename):
raise errors.RevisionError('File is not under client path')
if change is None:
self.run(['add', filename])
else:
self.run(['add', '-c', str(change.change), filename])
data = self.run(['fstat', filename])[0]
except errors.CommandError as err:
LOGGER.debug(err)
raise errors.RevisionError('File is not under client path')
rev = Revision(data, self)
if isinstance(change, Changelist):
change.append(rev)
return rev | [
"def",
"add",
"(",
"self",
",",
"filename",
",",
"change",
"=",
"None",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"canAdd",
"(",
"filename",
")",
":",
"raise",
"errors",
".",
"RevisionError",
"(",
"'File is not under client path'",
")",
"if",
"change",
"is",
"None",
":",
"self",
".",
"run",
"(",
"[",
"'add'",
",",
"filename",
"]",
")",
"else",
":",
"self",
".",
"run",
"(",
"[",
"'add'",
",",
"'-c'",
",",
"str",
"(",
"change",
".",
"change",
")",
",",
"filename",
"]",
")",
"data",
"=",
"self",
".",
"run",
"(",
"[",
"'fstat'",
",",
"filename",
"]",
")",
"[",
"0",
"]",
"except",
"errors",
".",
"CommandError",
"as",
"err",
":",
"LOGGER",
".",
"debug",
"(",
"err",
")",
"raise",
"errors",
".",
"RevisionError",
"(",
"'File is not under client path'",
")",
"rev",
"=",
"Revision",
"(",
"data",
",",
"self",
")",
"if",
"isinstance",
"(",
"change",
",",
"Changelist",
")",
":",
"change",
".",
"append",
"(",
"rev",
")",
"return",
"rev"
] | Adds a new file to a changelist
:param filename: File path to add
:type filename: str
:param change: Changelist to add the file to
:type change: int
:returns: :class:`.Revision` | [
"Adds",
"a",
"new",
"file",
"to",
"a",
"changelist"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L347-L375 | train |
theiviaxx/python-perforce | perforce/models.py | Connection.canAdd | def canAdd(self, filename):
"""Determines if a filename can be added to the depot under the current client
:param filename: File path to add
:type filename: str
"""
try:
result = self.run(['add', '-n', '-t', 'text', filename])[0]
except errors.CommandError as err:
LOGGER.debug(err)
return False
if result.get('code') not in ('error', 'info'):
return True
LOGGER.warn('Unable to add {}: {}'.format(filename, result['data']))
return False | python | def canAdd(self, filename):
"""Determines if a filename can be added to the depot under the current client
:param filename: File path to add
:type filename: str
"""
try:
result = self.run(['add', '-n', '-t', 'text', filename])[0]
except errors.CommandError as err:
LOGGER.debug(err)
return False
if result.get('code') not in ('error', 'info'):
return True
LOGGER.warn('Unable to add {}: {}'.format(filename, result['data']))
return False | [
"def",
"canAdd",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"run",
"(",
"[",
"'add'",
",",
"'-n'",
",",
"'-t'",
",",
"'text'",
",",
"filename",
"]",
")",
"[",
"0",
"]",
"except",
"errors",
".",
"CommandError",
"as",
"err",
":",
"LOGGER",
".",
"debug",
"(",
"err",
")",
"return",
"False",
"if",
"result",
".",
"get",
"(",
"'code'",
")",
"not",
"in",
"(",
"'error'",
",",
"'info'",
")",
":",
"return",
"True",
"LOGGER",
".",
"warn",
"(",
"'Unable to add {}: {}'",
".",
"format",
"(",
"filename",
",",
"result",
"[",
"'data'",
"]",
")",
")",
"return",
"False"
] | Determines if a filename can be added to the depot under the current client
:param filename: File path to add
:type filename: str | [
"Determines",
"if",
"a",
"filename",
"can",
"be",
"added",
"to",
"the",
"depot",
"under",
"the",
"current",
"client"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L377-L394 | train |
theiviaxx/python-perforce | perforce/models.py | Changelist.query | def query(self, files=True):
"""Queries the depot to get the current status of the changelist"""
if self._change:
cl = str(self._change)
self._p4dict = {camel_case(k): v for k, v in six.iteritems(self._connection.run(['change', '-o', cl])[0])}
if files:
self._files = []
if self._p4dict.get('status') == 'pending' or self._change == 0:
change = self._change or 'default'
data = self._connection.run(['opened', '-c', str(change)])
self._files = [Revision(r, self._connection) for r in data]
else:
data = self._connection.run(['describe', str(self._change)])[0]
depotfiles = []
for k, v in six.iteritems(data):
if k.startswith('depotFile'):
depotfiles.append(v)
self._files = self._connection.ls(depotfiles) | python | def query(self, files=True):
"""Queries the depot to get the current status of the changelist"""
if self._change:
cl = str(self._change)
self._p4dict = {camel_case(k): v for k, v in six.iteritems(self._connection.run(['change', '-o', cl])[0])}
if files:
self._files = []
if self._p4dict.get('status') == 'pending' or self._change == 0:
change = self._change or 'default'
data = self._connection.run(['opened', '-c', str(change)])
self._files = [Revision(r, self._connection) for r in data]
else:
data = self._connection.run(['describe', str(self._change)])[0]
depotfiles = []
for k, v in six.iteritems(data):
if k.startswith('depotFile'):
depotfiles.append(v)
self._files = self._connection.ls(depotfiles) | [
"def",
"query",
"(",
"self",
",",
"files",
"=",
"True",
")",
":",
"if",
"self",
".",
"_change",
":",
"cl",
"=",
"str",
"(",
"self",
".",
"_change",
")",
"self",
".",
"_p4dict",
"=",
"{",
"camel_case",
"(",
"k",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_connection",
".",
"run",
"(",
"[",
"'change'",
",",
"'-o'",
",",
"cl",
"]",
")",
"[",
"0",
"]",
")",
"}",
"if",
"files",
":",
"self",
".",
"_files",
"=",
"[",
"]",
"if",
"self",
".",
"_p4dict",
".",
"get",
"(",
"'status'",
")",
"==",
"'pending'",
"or",
"self",
".",
"_change",
"==",
"0",
":",
"change",
"=",
"self",
".",
"_change",
"or",
"'default'",
"data",
"=",
"self",
".",
"_connection",
".",
"run",
"(",
"[",
"'opened'",
",",
"'-c'",
",",
"str",
"(",
"change",
")",
"]",
")",
"self",
".",
"_files",
"=",
"[",
"Revision",
"(",
"r",
",",
"self",
".",
"_connection",
")",
"for",
"r",
"in",
"data",
"]",
"else",
":",
"data",
"=",
"self",
".",
"_connection",
".",
"run",
"(",
"[",
"'describe'",
",",
"str",
"(",
"self",
".",
"_change",
")",
"]",
")",
"[",
"0",
"]",
"depotfiles",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"data",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"'depotFile'",
")",
":",
"depotfiles",
".",
"append",
"(",
"v",
")",
"self",
".",
"_files",
"=",
"self",
".",
"_connection",
".",
"ls",
"(",
"depotfiles",
")"
] | Queries the depot to get the current status of the changelist | [
"Queries",
"the",
"depot",
"to",
"get",
"the",
"current",
"status",
"of",
"the",
"changelist"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L542-L560 | train |
theiviaxx/python-perforce | perforce/models.py | Changelist.remove | def remove(self, rev, permanent=False):
"""Removes a revision from this changelist
:param rev: Revision to remove
:type rev: :class:`.Revision`
:param permanent: Whether or not we need to set the changelist to default
:type permanent: bool
"""
if not isinstance(rev, Revision):
raise TypeError('argument needs to be an instance of Revision')
if rev not in self:
raise ValueError('{} not in changelist'.format(rev))
self._files.remove(rev)
if not permanent:
rev.changelist = self._connection.default | python | def remove(self, rev, permanent=False):
"""Removes a revision from this changelist
:param rev: Revision to remove
:type rev: :class:`.Revision`
:param permanent: Whether or not we need to set the changelist to default
:type permanent: bool
"""
if not isinstance(rev, Revision):
raise TypeError('argument needs to be an instance of Revision')
if rev not in self:
raise ValueError('{} not in changelist'.format(rev))
self._files.remove(rev)
if not permanent:
rev.changelist = self._connection.default | [
"def",
"remove",
"(",
"self",
",",
"rev",
",",
"permanent",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"rev",
",",
"Revision",
")",
":",
"raise",
"TypeError",
"(",
"'argument needs to be an instance of Revision'",
")",
"if",
"rev",
"not",
"in",
"self",
":",
"raise",
"ValueError",
"(",
"'{} not in changelist'",
".",
"format",
"(",
"rev",
")",
")",
"self",
".",
"_files",
".",
"remove",
"(",
"rev",
")",
"if",
"not",
"permanent",
":",
"rev",
".",
"changelist",
"=",
"self",
".",
"_connection",
".",
"default"
] | Removes a revision from this changelist
:param rev: Revision to remove
:type rev: :class:`.Revision`
:param permanent: Whether or not we need to set the changelist to default
:type permanent: bool | [
"Removes",
"a",
"revision",
"from",
"this",
"changelist"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L585-L601 | train |
theiviaxx/python-perforce | perforce/models.py | Changelist.revert | def revert(self, unchanged_only=False):
"""Revert all files in this changelist
:param unchanged_only: Only revert unchanged files
:type unchanged_only: bool
:raises: :class:`.ChangelistError`
"""
if self._reverted:
raise errors.ChangelistError('This changelist has been reverted')
change = self._change
if self._change == 0:
change = 'default'
cmd = ['revert', '-c', str(change)]
if unchanged_only:
cmd.append('-a')
files = [f.depotFile for f in self._files]
if files:
cmd += files
self._connection.run(cmd)
self._files = []
self._reverted = True | python | def revert(self, unchanged_only=False):
"""Revert all files in this changelist
:param unchanged_only: Only revert unchanged files
:type unchanged_only: bool
:raises: :class:`.ChangelistError`
"""
if self._reverted:
raise errors.ChangelistError('This changelist has been reverted')
change = self._change
if self._change == 0:
change = 'default'
cmd = ['revert', '-c', str(change)]
if unchanged_only:
cmd.append('-a')
files = [f.depotFile for f in self._files]
if files:
cmd += files
self._connection.run(cmd)
self._files = []
self._reverted = True | [
"def",
"revert",
"(",
"self",
",",
"unchanged_only",
"=",
"False",
")",
":",
"if",
"self",
".",
"_reverted",
":",
"raise",
"errors",
".",
"ChangelistError",
"(",
"'This changelist has been reverted'",
")",
"change",
"=",
"self",
".",
"_change",
"if",
"self",
".",
"_change",
"==",
"0",
":",
"change",
"=",
"'default'",
"cmd",
"=",
"[",
"'revert'",
",",
"'-c'",
",",
"str",
"(",
"change",
")",
"]",
"if",
"unchanged_only",
":",
"cmd",
".",
"append",
"(",
"'-a'",
")",
"files",
"=",
"[",
"f",
".",
"depotFile",
"for",
"f",
"in",
"self",
".",
"_files",
"]",
"if",
"files",
":",
"cmd",
"+=",
"files",
"self",
".",
"_connection",
".",
"run",
"(",
"cmd",
")",
"self",
".",
"_files",
"=",
"[",
"]",
"self",
".",
"_reverted",
"=",
"True"
] | Revert all files in this changelist
:param unchanged_only: Only revert unchanged files
:type unchanged_only: bool
:raises: :class:`.ChangelistError` | [
"Revert",
"all",
"files",
"in",
"this",
"changelist"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L603-L628 | train |
theiviaxx/python-perforce | perforce/models.py | Changelist.submit | def submit(self):
"""Submits a chagelist to the depot"""
if self._dirty:
self.save()
self._connection.run(['submit', '-c', str(self._change)], marshal_output=False) | python | def submit(self):
"""Submits a chagelist to the depot"""
if self._dirty:
self.save()
self._connection.run(['submit', '-c', str(self._change)], marshal_output=False) | [
"def",
"submit",
"(",
"self",
")",
":",
"if",
"self",
".",
"_dirty",
":",
"self",
".",
"save",
"(",
")",
"self",
".",
"_connection",
".",
"run",
"(",
"[",
"'submit'",
",",
"'-c'",
",",
"str",
"(",
"self",
".",
"_change",
")",
"]",
",",
"marshal_output",
"=",
"False",
")"
] | Submits a chagelist to the depot | [
"Submits",
"a",
"chagelist",
"to",
"the",
"depot"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L635-L640 | train |
theiviaxx/python-perforce | perforce/models.py | Changelist.delete | def delete(self):
"""Reverts all files in this changelist then deletes the changelist from perforce"""
try:
self.revert()
except errors.ChangelistError:
pass
self._connection.run(['change', '-d', str(self._change)]) | python | def delete(self):
"""Reverts all files in this changelist then deletes the changelist from perforce"""
try:
self.revert()
except errors.ChangelistError:
pass
self._connection.run(['change', '-d', str(self._change)]) | [
"def",
"delete",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"revert",
"(",
")",
"except",
"errors",
".",
"ChangelistError",
":",
"pass",
"self",
".",
"_connection",
".",
"run",
"(",
"[",
"'change'",
",",
"'-d'",
",",
"str",
"(",
"self",
".",
"_change",
")",
"]",
")"
] | Reverts all files in this changelist then deletes the changelist from perforce | [
"Reverts",
"all",
"files",
"in",
"this",
"changelist",
"then",
"deletes",
"the",
"changelist",
"from",
"perforce"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L642-L649 | train |
theiviaxx/python-perforce | perforce/models.py | Changelist.create | def create(description='<Created by Python>', connection=None):
"""Creates a new changelist
:param connection: Connection to use to create the changelist
:type connection: :class:`.Connection`
:param description: Description for new changelist
:type description: str
:returns: :class:`.Changelist`
"""
connection = connection or Connection()
description = description.replace('\n', '\n\t')
form = NEW_FORMAT.format(client=str(connection.client), description=description)
result = connection.run(['change', '-i'], stdin=form, marshal_output=False)
return Changelist(int(result.split()[1]), connection) | python | def create(description='<Created by Python>', connection=None):
"""Creates a new changelist
:param connection: Connection to use to create the changelist
:type connection: :class:`.Connection`
:param description: Description for new changelist
:type description: str
:returns: :class:`.Changelist`
"""
connection = connection or Connection()
description = description.replace('\n', '\n\t')
form = NEW_FORMAT.format(client=str(connection.client), description=description)
result = connection.run(['change', '-i'], stdin=form, marshal_output=False)
return Changelist(int(result.split()[1]), connection) | [
"def",
"create",
"(",
"description",
"=",
"'<Created by Python>'",
",",
"connection",
"=",
"None",
")",
":",
"connection",
"=",
"connection",
"or",
"Connection",
"(",
")",
"description",
"=",
"description",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\t'",
")",
"form",
"=",
"NEW_FORMAT",
".",
"format",
"(",
"client",
"=",
"str",
"(",
"connection",
".",
"client",
")",
",",
"description",
"=",
"description",
")",
"result",
"=",
"connection",
".",
"run",
"(",
"[",
"'change'",
",",
"'-i'",
"]",
",",
"stdin",
"=",
"form",
",",
"marshal_output",
"=",
"False",
")",
"return",
"Changelist",
"(",
"int",
"(",
"result",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
",",
"connection",
")"
] | Creates a new changelist
:param connection: Connection to use to create the changelist
:type connection: :class:`.Connection`
:param description: Description for new changelist
:type description: str
:returns: :class:`.Changelist` | [
"Creates",
"a",
"new",
"changelist"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L694-L708 | train |
theiviaxx/python-perforce | perforce/models.py | Revision.query | def query(self):
"""Runs an fstat for this file and repopulates the data"""
self._p4dict = self._connection.run(['fstat', '-m', '1', self._p4dict['depotFile']])[0]
self._head = HeadRevision(self._p4dict)
self._filename = self.depotFile | python | def query(self):
"""Runs an fstat for this file and repopulates the data"""
self._p4dict = self._connection.run(['fstat', '-m', '1', self._p4dict['depotFile']])[0]
self._head = HeadRevision(self._p4dict)
self._filename = self.depotFile | [
"def",
"query",
"(",
"self",
")",
":",
"self",
".",
"_p4dict",
"=",
"self",
".",
"_connection",
".",
"run",
"(",
"[",
"'fstat'",
",",
"'-m'",
",",
"'1'",
",",
"self",
".",
"_p4dict",
"[",
"'depotFile'",
"]",
"]",
")",
"[",
"0",
"]",
"self",
".",
"_head",
"=",
"HeadRevision",
"(",
"self",
".",
"_p4dict",
")",
"self",
".",
"_filename",
"=",
"self",
".",
"depotFile"
] | Runs an fstat for this file and repopulates the data | [
"Runs",
"an",
"fstat",
"for",
"this",
"file",
"and",
"repopulates",
"the",
"data"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L770-L776 | train |
theiviaxx/python-perforce | perforce/models.py | Revision.edit | def edit(self, changelist=0):
"""Checks out the file
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist`
"""
command = 'reopen' if self.action in ('add', 'edit') else 'edit'
if int(changelist):
self._connection.run([command, '-c', str(changelist.change), self.depotFile])
else:
self._connection.run([command, self.depotFile])
self.query() | python | def edit(self, changelist=0):
"""Checks out the file
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist`
"""
command = 'reopen' if self.action in ('add', 'edit') else 'edit'
if int(changelist):
self._connection.run([command, '-c', str(changelist.change), self.depotFile])
else:
self._connection.run([command, self.depotFile])
self.query() | [
"def",
"edit",
"(",
"self",
",",
"changelist",
"=",
"0",
")",
":",
"command",
"=",
"'reopen'",
"if",
"self",
".",
"action",
"in",
"(",
"'add'",
",",
"'edit'",
")",
"else",
"'edit'",
"if",
"int",
"(",
"changelist",
")",
":",
"self",
".",
"_connection",
".",
"run",
"(",
"[",
"command",
",",
"'-c'",
",",
"str",
"(",
"changelist",
".",
"change",
")",
",",
"self",
".",
"depotFile",
"]",
")",
"else",
":",
"self",
".",
"_connection",
".",
"run",
"(",
"[",
"command",
",",
"self",
".",
"depotFile",
"]",
")",
"self",
".",
"query",
"(",
")"
] | Checks out the file
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist` | [
"Checks",
"out",
"the",
"file"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L778-L790 | train |
theiviaxx/python-perforce | perforce/models.py | Revision.lock | def lock(self, lock=True, changelist=0):
"""Locks or unlocks the file
:param lock: Lock or unlock the file
:type lock: bool
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist`
"""
cmd = 'lock' if lock else 'unlock'
if changelist:
self._connection.run([cmd, '-c', changelist, self.depotFile])
else:
self._connection.run([cmd, self.depotFile])
self.query() | python | def lock(self, lock=True, changelist=0):
"""Locks or unlocks the file
:param lock: Lock or unlock the file
:type lock: bool
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist`
"""
cmd = 'lock' if lock else 'unlock'
if changelist:
self._connection.run([cmd, '-c', changelist, self.depotFile])
else:
self._connection.run([cmd, self.depotFile])
self.query() | [
"def",
"lock",
"(",
"self",
",",
"lock",
"=",
"True",
",",
"changelist",
"=",
"0",
")",
":",
"cmd",
"=",
"'lock'",
"if",
"lock",
"else",
"'unlock'",
"if",
"changelist",
":",
"self",
".",
"_connection",
".",
"run",
"(",
"[",
"cmd",
",",
"'-c'",
",",
"changelist",
",",
"self",
".",
"depotFile",
"]",
")",
"else",
":",
"self",
".",
"_connection",
".",
"run",
"(",
"[",
"cmd",
",",
"self",
".",
"depotFile",
"]",
")",
"self",
".",
"query",
"(",
")"
] | Locks or unlocks the file
:param lock: Lock or unlock the file
:type lock: bool
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist` | [
"Locks",
"or",
"unlocks",
"the",
"file"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L792-L807 | train |
theiviaxx/python-perforce | perforce/models.py | Revision.sync | def sync(self, force=False, safe=True, revision=0, changelist=0):
"""Syncs the file at the current revision
:param force: Force the file to sync
:type force: bool
:param safe: Don't sync files that were changed outside perforce
:type safe: bool
:param revision: Sync to a specific revision
:type revision: int
:param changelist: Changelist to sync to
:type changelist: int
"""
cmd = ['sync']
if force:
cmd.append('-f')
if safe:
cmd.append('-s')
if revision:
cmd.append('{}#{}'.format(self.depotFile, revision))
elif changelist:
cmd.append('{}@{}'.format(self.depotFile, changelist))
else:
cmd.append(self.depotFile)
self._connection.run(cmd)
self.query() | python | def sync(self, force=False, safe=True, revision=0, changelist=0):
"""Syncs the file at the current revision
:param force: Force the file to sync
:type force: bool
:param safe: Don't sync files that were changed outside perforce
:type safe: bool
:param revision: Sync to a specific revision
:type revision: int
:param changelist: Changelist to sync to
:type changelist: int
"""
cmd = ['sync']
if force:
cmd.append('-f')
if safe:
cmd.append('-s')
if revision:
cmd.append('{}#{}'.format(self.depotFile, revision))
elif changelist:
cmd.append('{}@{}'.format(self.depotFile, changelist))
else:
cmd.append(self.depotFile)
self._connection.run(cmd)
self.query() | [
"def",
"sync",
"(",
"self",
",",
"force",
"=",
"False",
",",
"safe",
"=",
"True",
",",
"revision",
"=",
"0",
",",
"changelist",
"=",
"0",
")",
":",
"cmd",
"=",
"[",
"'sync'",
"]",
"if",
"force",
":",
"cmd",
".",
"append",
"(",
"'-f'",
")",
"if",
"safe",
":",
"cmd",
".",
"append",
"(",
"'-s'",
")",
"if",
"revision",
":",
"cmd",
".",
"append",
"(",
"'{}#{}'",
".",
"format",
"(",
"self",
".",
"depotFile",
",",
"revision",
")",
")",
"elif",
"changelist",
":",
"cmd",
".",
"append",
"(",
"'{}@{}'",
".",
"format",
"(",
"self",
".",
"depotFile",
",",
"changelist",
")",
")",
"else",
":",
"cmd",
".",
"append",
"(",
"self",
".",
"depotFile",
")",
"self",
".",
"_connection",
".",
"run",
"(",
"cmd",
")",
"self",
".",
"query",
"(",
")"
] | Syncs the file at the current revision
:param force: Force the file to sync
:type force: bool
:param safe: Don't sync files that were changed outside perforce
:type safe: bool
:param revision: Sync to a specific revision
:type revision: int
:param changelist: Changelist to sync to
:type changelist: int | [
"Syncs",
"the",
"file",
"at",
"the",
"current",
"revision"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L809-L837 | train |
theiviaxx/python-perforce | perforce/models.py | Revision.revert | def revert(self, unchanged=False):
"""Reverts any file changes
:param unchanged: Only revert if the file is unchanged
:type unchanged: bool
"""
cmd = ['revert']
if unchanged:
cmd.append('-a')
wasadd = self.action == 'add'
cmd.append(self.depotFile)
self._connection.run(cmd)
if 'movedFile' in self._p4dict:
self._p4dict['depotFile'] = self._p4dict['movedFile']
if not wasadd:
self.query()
if self._changelist:
self._changelist.remove(self, permanent=True) | python | def revert(self, unchanged=False):
"""Reverts any file changes
:param unchanged: Only revert if the file is unchanged
:type unchanged: bool
"""
cmd = ['revert']
if unchanged:
cmd.append('-a')
wasadd = self.action == 'add'
cmd.append(self.depotFile)
self._connection.run(cmd)
if 'movedFile' in self._p4dict:
self._p4dict['depotFile'] = self._p4dict['movedFile']
if not wasadd:
self.query()
if self._changelist:
self._changelist.remove(self, permanent=True) | [
"def",
"revert",
"(",
"self",
",",
"unchanged",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"'revert'",
"]",
"if",
"unchanged",
":",
"cmd",
".",
"append",
"(",
"'-a'",
")",
"wasadd",
"=",
"self",
".",
"action",
"==",
"'add'",
"cmd",
".",
"append",
"(",
"self",
".",
"depotFile",
")",
"self",
".",
"_connection",
".",
"run",
"(",
"cmd",
")",
"if",
"'movedFile'",
"in",
"self",
".",
"_p4dict",
":",
"self",
".",
"_p4dict",
"[",
"'depotFile'",
"]",
"=",
"self",
".",
"_p4dict",
"[",
"'movedFile'",
"]",
"if",
"not",
"wasadd",
":",
"self",
".",
"query",
"(",
")",
"if",
"self",
".",
"_changelist",
":",
"self",
".",
"_changelist",
".",
"remove",
"(",
"self",
",",
"permanent",
"=",
"True",
")"
] | Reverts any file changes
:param unchanged: Only revert if the file is unchanged
:type unchanged: bool | [
"Reverts",
"any",
"file",
"changes"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L839-L862 | train |
theiviaxx/python-perforce | perforce/models.py | Revision.shelve | def shelve(self, changelist=None):
"""Shelves the file if it is in a changelist
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist`
"""
if changelist is None and self.changelist.description == 'default':
raise errors.ShelveError('Unabled to shelve files in the default changelist')
cmd = ['shelve']
if changelist:
cmd += ['-c', str(changelist)]
cmd.append(self.depotFile)
self._connection.run(cmd)
self.query() | python | def shelve(self, changelist=None):
"""Shelves the file if it is in a changelist
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist`
"""
if changelist is None and self.changelist.description == 'default':
raise errors.ShelveError('Unabled to shelve files in the default changelist')
cmd = ['shelve']
if changelist:
cmd += ['-c', str(changelist)]
cmd.append(self.depotFile)
self._connection.run(cmd)
self.query() | [
"def",
"shelve",
"(",
"self",
",",
"changelist",
"=",
"None",
")",
":",
"if",
"changelist",
"is",
"None",
"and",
"self",
".",
"changelist",
".",
"description",
"==",
"'default'",
":",
"raise",
"errors",
".",
"ShelveError",
"(",
"'Unabled to shelve files in the default changelist'",
")",
"cmd",
"=",
"[",
"'shelve'",
"]",
"if",
"changelist",
":",
"cmd",
"+=",
"[",
"'-c'",
",",
"str",
"(",
"changelist",
")",
"]",
"cmd",
".",
"append",
"(",
"self",
".",
"depotFile",
")",
"self",
".",
"_connection",
".",
"run",
"(",
"cmd",
")",
"self",
".",
"query",
"(",
")"
] | Shelves the file if it is in a changelist
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist` | [
"Shelves",
"the",
"file",
"if",
"it",
"is",
"in",
"a",
"changelist"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L864-L881 | train |
theiviaxx/python-perforce | perforce/models.py | Revision.delete | def delete(self, changelist=0):
"""Marks the file for delete
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist`
"""
cmd = ['delete']
if changelist:
cmd += ['-c', str(changelist)]
cmd.append(self.depotFile)
self._connection.run(cmd)
self.query() | python | def delete(self, changelist=0):
"""Marks the file for delete
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist`
"""
cmd = ['delete']
if changelist:
cmd += ['-c', str(changelist)]
cmd.append(self.depotFile)
self._connection.run(cmd)
self.query() | [
"def",
"delete",
"(",
"self",
",",
"changelist",
"=",
"0",
")",
":",
"cmd",
"=",
"[",
"'delete'",
"]",
"if",
"changelist",
":",
"cmd",
"+=",
"[",
"'-c'",
",",
"str",
"(",
"changelist",
")",
"]",
"cmd",
".",
"append",
"(",
"self",
".",
"depotFile",
")",
"self",
".",
"_connection",
".",
"run",
"(",
"cmd",
")",
"self",
".",
"query",
"(",
")"
] | Marks the file for delete
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist` | [
"Marks",
"the",
"file",
"for",
"delete"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L909-L923 | train |
theiviaxx/python-perforce | perforce/models.py | Revision.hash | def hash(self):
"""The hash value of the current revision"""
if 'digest' not in self._p4dict:
self._p4dict = self._connection.run(['fstat', '-m', '1', '-Ol', self.depotFile])[0]
return self._p4dict['digest'] | python | def hash(self):
"""The hash value of the current revision"""
if 'digest' not in self._p4dict:
self._p4dict = self._connection.run(['fstat', '-m', '1', '-Ol', self.depotFile])[0]
return self._p4dict['digest'] | [
"def",
"hash",
"(",
"self",
")",
":",
"if",
"'digest'",
"not",
"in",
"self",
".",
"_p4dict",
":",
"self",
".",
"_p4dict",
"=",
"self",
".",
"_connection",
".",
"run",
"(",
"[",
"'fstat'",
",",
"'-m'",
",",
"'1'",
",",
"'-Ol'",
",",
"self",
".",
"depotFile",
"]",
")",
"[",
"0",
"]",
"return",
"self",
".",
"_p4dict",
"[",
"'digest'",
"]"
] | The hash value of the current revision | [
"The",
"hash",
"value",
"of",
"the",
"current",
"revision"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L926-L931 | train |
theiviaxx/python-perforce | perforce/models.py | Client.view | def view(self):
"""A list of view specs"""
spec = []
for k, v in six.iteritems(self._p4dict):
if k.startswith('view'):
match = RE_FILESPEC.search(v)
if match:
spec.append(FileSpec(v[:match.end() - 1], v[match.end():]))
return spec | python | def view(self):
"""A list of view specs"""
spec = []
for k, v in six.iteritems(self._p4dict):
if k.startswith('view'):
match = RE_FILESPEC.search(v)
if match:
spec.append(FileSpec(v[:match.end() - 1], v[match.end():]))
return spec | [
"def",
"view",
"(",
"self",
")",
":",
"spec",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_p4dict",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"'view'",
")",
":",
"match",
"=",
"RE_FILESPEC",
".",
"search",
"(",
"v",
")",
"if",
"match",
":",
"spec",
".",
"append",
"(",
"FileSpec",
"(",
"v",
"[",
":",
"match",
".",
"end",
"(",
")",
"-",
"1",
"]",
",",
"v",
"[",
"match",
".",
"end",
"(",
")",
":",
"]",
")",
")",
"return",
"spec"
] | A list of view specs | [
"A",
"list",
"of",
"view",
"specs"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L1145-L1154 | train |
theiviaxx/python-perforce | perforce/models.py | Client.stream | def stream(self):
"""Which stream, if any, the client is under"""
stream = self._p4dict.get('stream')
if stream:
return Stream(stream, self._connection) | python | def stream(self):
"""Which stream, if any, the client is under"""
stream = self._p4dict.get('stream')
if stream:
return Stream(stream, self._connection) | [
"def",
"stream",
"(",
"self",
")",
":",
"stream",
"=",
"self",
".",
"_p4dict",
".",
"get",
"(",
"'stream'",
")",
"if",
"stream",
":",
"return",
"Stream",
"(",
"stream",
",",
"self",
".",
"_connection",
")"
] | Which stream, if any, the client is under | [
"Which",
"stream",
"if",
"any",
"the",
"client",
"is",
"under"
] | 01a3b01fe5949126fa0097d9a8ad386887823b5a | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L1167-L1171 | train |
ph4r05/monero-serialize | monero_serialize/xmrboost.py | Archive.set_version | async def set_version(self, tp, params, version=None, elem=None):
"""
Stores version to the stream if not stored yet
:param tp:
:param params:
:param version:
:param elem:
:return:
"""
self.registry.set_tr(None)
tw = TypeWrapper(tp, params)
if not tw.is_versioned():
return TypeWrapper.ELEMENTARY_RES
# If not in the DB, store to the archive at the current position
if not self.version_db.is_versioned(tw):
if version is None:
version = self._cur_version(tw, elem)
await dump_uvarint(self.iobj, 0)
await dump_uvarint(self.iobj, version)
self.version_db.set_version(tw, 0, version)
return self.version_db.get_version(tw)[1] | python | async def set_version(self, tp, params, version=None, elem=None):
"""
Stores version to the stream if not stored yet
:param tp:
:param params:
:param version:
:param elem:
:return:
"""
self.registry.set_tr(None)
tw = TypeWrapper(tp, params)
if not tw.is_versioned():
return TypeWrapper.ELEMENTARY_RES
# If not in the DB, store to the archive at the current position
if not self.version_db.is_versioned(tw):
if version is None:
version = self._cur_version(tw, elem)
await dump_uvarint(self.iobj, 0)
await dump_uvarint(self.iobj, version)
self.version_db.set_version(tw, 0, version)
return self.version_db.get_version(tw)[1] | [
"async",
"def",
"set_version",
"(",
"self",
",",
"tp",
",",
"params",
",",
"version",
"=",
"None",
",",
"elem",
"=",
"None",
")",
":",
"self",
".",
"registry",
".",
"set_tr",
"(",
"None",
")",
"tw",
"=",
"TypeWrapper",
"(",
"tp",
",",
"params",
")",
"if",
"not",
"tw",
".",
"is_versioned",
"(",
")",
":",
"return",
"TypeWrapper",
".",
"ELEMENTARY_RES",
"# If not in the DB, store to the archive at the current position",
"if",
"not",
"self",
".",
"version_db",
".",
"is_versioned",
"(",
"tw",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"self",
".",
"_cur_version",
"(",
"tw",
",",
"elem",
")",
"await",
"dump_uvarint",
"(",
"self",
".",
"iobj",
",",
"0",
")",
"await",
"dump_uvarint",
"(",
"self",
".",
"iobj",
",",
"version",
")",
"self",
".",
"version_db",
".",
"set_version",
"(",
"tw",
",",
"0",
",",
"version",
")",
"return",
"self",
".",
"version_db",
".",
"get_version",
"(",
"tw",
")",
"[",
"1",
"]"
] | Stores version to the stream if not stored yet
:param tp:
:param params:
:param version:
:param elem:
:return: | [
"Stores",
"version",
"to",
"the",
"stream",
"if",
"not",
"stored",
"yet"
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrboost.py#L206-L230 | train |
ph4r05/monero-serialize | monero_serialize/xmrboost.py | Archive.version | async def version(self, tp, params, version=None, elem=None):
"""
Symmetric version management
:param tp:
:param params:
:param version:
:return:
"""
if self.writing:
return await self.set_version(tp, params, version, elem)
else:
return await self.get_version(tp, params) | python | async def version(self, tp, params, version=None, elem=None):
"""
Symmetric version management
:param tp:
:param params:
:param version:
:return:
"""
if self.writing:
return await self.set_version(tp, params, version, elem)
else:
return await self.get_version(tp, params) | [
"async",
"def",
"version",
"(",
"self",
",",
"tp",
",",
"params",
",",
"version",
"=",
"None",
",",
"elem",
"=",
"None",
")",
":",
"if",
"self",
".",
"writing",
":",
"return",
"await",
"self",
".",
"set_version",
"(",
"tp",
",",
"params",
",",
"version",
",",
"elem",
")",
"else",
":",
"return",
"await",
"self",
".",
"get_version",
"(",
"tp",
",",
"params",
")"
] | Symmetric version management
:param tp:
:param params:
:param version:
:return: | [
"Symmetric",
"version",
"management"
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrboost.py#L232-L244 | train |
ph4r05/monero-serialize | monero_serialize/xmrboost.py | Archive.root_message | async def root_message(self, msg, msg_type=None):
"""
Root-level message. First entry in the archive.
Archive headers processing
:return:
"""
await self.root()
await self.message(msg, msg_type) | python | async def root_message(self, msg, msg_type=None):
"""
Root-level message. First entry in the archive.
Archive headers processing
:return:
"""
await self.root()
await self.message(msg, msg_type) | [
"async",
"def",
"root_message",
"(",
"self",
",",
"msg",
",",
"msg_type",
"=",
"None",
")",
":",
"await",
"self",
".",
"root",
"(",
")",
"await",
"self",
".",
"message",
"(",
"msg",
",",
"msg_type",
")"
] | Root-level message. First entry in the archive.
Archive headers processing
:return: | [
"Root",
"-",
"level",
"message",
".",
"First",
"entry",
"in",
"the",
"archive",
".",
"Archive",
"headers",
"processing"
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrboost.py#L675-L683 | train |
ph4r05/monero-serialize | monero_serialize/xmrboost.py | Archive.dump_message | async def dump_message(self, msg, msg_type=None):
"""
Dumps message to the writer.
:param msg:
:param msg_type:
:return:
"""
mtype = msg.__class__ if msg_type is None else msg_type
fields = mtype.f_specs()
for field in fields:
await self.message_field(msg=msg, field=field) | python | async def dump_message(self, msg, msg_type=None):
"""
Dumps message to the writer.
:param msg:
:param msg_type:
:return:
"""
mtype = msg.__class__ if msg_type is None else msg_type
fields = mtype.f_specs()
for field in fields:
await self.message_field(msg=msg, field=field) | [
"async",
"def",
"dump_message",
"(",
"self",
",",
"msg",
",",
"msg_type",
"=",
"None",
")",
":",
"mtype",
"=",
"msg",
".",
"__class__",
"if",
"msg_type",
"is",
"None",
"else",
"msg_type",
"fields",
"=",
"mtype",
".",
"f_specs",
"(",
")",
"for",
"field",
"in",
"fields",
":",
"await",
"self",
".",
"message_field",
"(",
"msg",
"=",
"msg",
",",
"field",
"=",
"field",
")"
] | Dumps message to the writer.
:param msg:
:param msg_type:
:return: | [
"Dumps",
"message",
"to",
"the",
"writer",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrboost.py#L753-L764 | train |
ph4r05/monero-serialize | monero_serialize/xmrboost.py | Archive.load_message | async def load_message(self, msg_type, msg=None):
"""
Loads message if the given type from the reader.
Supports reading directly to existing message.
:param msg_type:
:param msg:
:return:
"""
msg = msg_type() if msg is None else msg
fields = msg_type.f_specs() if msg_type else msg.__class__.f_specs()
for field in fields:
await self.message_field(msg, field)
return msg | python | async def load_message(self, msg_type, msg=None):
"""
Loads message if the given type from the reader.
Supports reading directly to existing message.
:param msg_type:
:param msg:
:return:
"""
msg = msg_type() if msg is None else msg
fields = msg_type.f_specs() if msg_type else msg.__class__.f_specs()
for field in fields:
await self.message_field(msg, field)
return msg | [
"async",
"def",
"load_message",
"(",
"self",
",",
"msg_type",
",",
"msg",
"=",
"None",
")",
":",
"msg",
"=",
"msg_type",
"(",
")",
"if",
"msg",
"is",
"None",
"else",
"msg",
"fields",
"=",
"msg_type",
".",
"f_specs",
"(",
")",
"if",
"msg_type",
"else",
"msg",
".",
"__class__",
".",
"f_specs",
"(",
")",
"for",
"field",
"in",
"fields",
":",
"await",
"self",
".",
"message_field",
"(",
"msg",
",",
"field",
")",
"return",
"msg"
] | Loads message if the given type from the reader.
Supports reading directly to existing message.
:param msg_type:
:param msg:
:return: | [
"Loads",
"message",
"if",
"the",
"given",
"type",
"from",
"the",
"reader",
".",
"Supports",
"reading",
"directly",
"to",
"existing",
"message",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrboost.py#L766-L780 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/client.py | contrail_error_handler | def contrail_error_handler(f):
"""Handle HTTP errors returned by the API server
"""
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except HttpError as e:
# Replace message by details to provide a
# meaningful message
if e.details:
e.message, e.details = e.details, e.message
e.args = ("%s (HTTP %s)" % (e.message, e.http_status),)
raise
return wrapper | python | def contrail_error_handler(f):
"""Handle HTTP errors returned by the API server
"""
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except HttpError as e:
# Replace message by details to provide a
# meaningful message
if e.details:
e.message, e.details = e.details, e.message
e.args = ("%s (HTTP %s)" % (e.message, e.http_status),)
raise
return wrapper | [
"def",
"contrail_error_handler",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"HttpError",
"as",
"e",
":",
"# Replace message by details to provide a",
"# meaningful message",
"if",
"e",
".",
"details",
":",
"e",
".",
"message",
",",
"e",
".",
"details",
"=",
"e",
".",
"details",
",",
"e",
".",
"message",
"e",
".",
"args",
"=",
"(",
"\"%s (HTTP %s)\"",
"%",
"(",
"e",
".",
"message",
",",
"e",
".",
"http_status",
")",
",",
")",
"raise",
"return",
"wrapper"
] | Handle HTTP errors returned by the API server | [
"Handle",
"HTTP",
"errors",
"returned",
"by",
"the",
"API",
"server"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/client.py#L15-L29 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/client.py | SessionLoader.make | def make(self, host="localhost", port=8082, protocol="http", base_uri="", os_auth_type="http", **kwargs):
"""Initialize a session to Contrail API server
:param os_auth_type: auth plugin to use:
- http: basic HTTP authentification
- v2password: keystone v2 auth
- v3password: keystone v3 auth
:type os_auth_type: str
"""
loader = loading.base.get_plugin_loader(os_auth_type)
plugin_options = {opt.dest: kwargs.pop("os_%s" % opt.dest)
for opt in loader.get_options()
if 'os_%s' % opt.dest in kwargs}
plugin = loader.load_from_options(**plugin_options)
return self.load_from_argparse_arguments(Namespace(**kwargs),
host=host,
port=port,
protocol=protocol,
base_uri=base_uri,
auth=plugin) | python | def make(self, host="localhost", port=8082, protocol="http", base_uri="", os_auth_type="http", **kwargs):
"""Initialize a session to Contrail API server
:param os_auth_type: auth plugin to use:
- http: basic HTTP authentification
- v2password: keystone v2 auth
- v3password: keystone v3 auth
:type os_auth_type: str
"""
loader = loading.base.get_plugin_loader(os_auth_type)
plugin_options = {opt.dest: kwargs.pop("os_%s" % opt.dest)
for opt in loader.get_options()
if 'os_%s' % opt.dest in kwargs}
plugin = loader.load_from_options(**plugin_options)
return self.load_from_argparse_arguments(Namespace(**kwargs),
host=host,
port=port,
protocol=protocol,
base_uri=base_uri,
auth=plugin) | [
"def",
"make",
"(",
"self",
",",
"host",
"=",
"\"localhost\"",
",",
"port",
"=",
"8082",
",",
"protocol",
"=",
"\"http\"",
",",
"base_uri",
"=",
"\"\"",
",",
"os_auth_type",
"=",
"\"http\"",
",",
"*",
"*",
"kwargs",
")",
":",
"loader",
"=",
"loading",
".",
"base",
".",
"get_plugin_loader",
"(",
"os_auth_type",
")",
"plugin_options",
"=",
"{",
"opt",
".",
"dest",
":",
"kwargs",
".",
"pop",
"(",
"\"os_%s\"",
"%",
"opt",
".",
"dest",
")",
"for",
"opt",
"in",
"loader",
".",
"get_options",
"(",
")",
"if",
"'os_%s'",
"%",
"opt",
".",
"dest",
"in",
"kwargs",
"}",
"plugin",
"=",
"loader",
".",
"load_from_options",
"(",
"*",
"*",
"plugin_options",
")",
"return",
"self",
".",
"load_from_argparse_arguments",
"(",
"Namespace",
"(",
"*",
"*",
"kwargs",
")",
",",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"protocol",
"=",
"protocol",
",",
"base_uri",
"=",
"base_uri",
",",
"auth",
"=",
"plugin",
")"
] | Initialize a session to Contrail API server
:param os_auth_type: auth plugin to use:
- http: basic HTTP authentification
- v2password: keystone v2 auth
- v3password: keystone v3 auth
:type os_auth_type: str | [
"Initialize",
"a",
"session",
"to",
"Contrail",
"API",
"server"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/client.py#L38-L57 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/client.py | ContrailAPISession.post_json | def post_json(self, url, data, cls=None, **kwargs):
"""
POST data to the api-server
:param url: resource location (eg: "/type/uuid")
:type url: str
:param cls: JSONEncoder class
:type cls: JSONEncoder
"""
kwargs['data'] = to_json(data, cls=cls)
kwargs['headers'] = self.default_headers
return self.post(url, **kwargs).json() | python | def post_json(self, url, data, cls=None, **kwargs):
"""
POST data to the api-server
:param url: resource location (eg: "/type/uuid")
:type url: str
:param cls: JSONEncoder class
:type cls: JSONEncoder
"""
kwargs['data'] = to_json(data, cls=cls)
kwargs['headers'] = self.default_headers
return self.post(url, **kwargs).json() | [
"def",
"post_json",
"(",
"self",
",",
"url",
",",
"data",
",",
"cls",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'data'",
"]",
"=",
"to_json",
"(",
"data",
",",
"cls",
"=",
"cls",
")",
"kwargs",
"[",
"'headers'",
"]",
"=",
"self",
".",
"default_headers",
"return",
"self",
".",
"post",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
".",
"json",
"(",
")"
] | POST data to the api-server
:param url: resource location (eg: "/type/uuid")
:type url: str
:param cls: JSONEncoder class
:type cls: JSONEncoder | [
"POST",
"data",
"to",
"the",
"api",
"-",
"server"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/client.py#L136-L147 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/client.py | ContrailAPISession.put_json | def put_json(self, url, data, cls=None, **kwargs):
"""
PUT data to the api-server
:param url: resource location (eg: "/type/uuid")
:type url: str
:param cls: JSONEncoder class
:type cls: JSONEncoder
"""
kwargs['data'] = to_json(data, cls=cls)
kwargs['headers'] = self.default_headers
return self.put(url, **kwargs).json() | python | def put_json(self, url, data, cls=None, **kwargs):
"""
PUT data to the api-server
:param url: resource location (eg: "/type/uuid")
:type url: str
:param cls: JSONEncoder class
:type cls: JSONEncoder
"""
kwargs['data'] = to_json(data, cls=cls)
kwargs['headers'] = self.default_headers
return self.put(url, **kwargs).json() | [
"def",
"put_json",
"(",
"self",
",",
"url",
",",
"data",
",",
"cls",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'data'",
"]",
"=",
"to_json",
"(",
"data",
",",
"cls",
"=",
"cls",
")",
"kwargs",
"[",
"'headers'",
"]",
"=",
"self",
".",
"default_headers",
"return",
"self",
".",
"put",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
".",
"json",
"(",
")"
] | PUT data to the api-server
:param url: resource location (eg: "/type/uuid")
:type url: str
:param cls: JSONEncoder class
:type cls: JSONEncoder | [
"PUT",
"data",
"to",
"the",
"api",
"-",
"server"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/client.py#L150-L161 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/client.py | ContrailAPISession.fqname_to_id | def fqname_to_id(self, fq_name, type):
"""
Return uuid for fq_name
:param fq_name: resource fq name
:type fq_name: FQName
:param type: resource type
:type type: str
:rtype: UUIDv4 str
:raises HttpError: fq_name not found
"""
data = {
"type": type,
"fq_name": list(fq_name)
}
return self.post_json(self.make_url("/fqname-to-id"), data)["uuid"] | python | def fqname_to_id(self, fq_name, type):
"""
Return uuid for fq_name
:param fq_name: resource fq name
:type fq_name: FQName
:param type: resource type
:type type: str
:rtype: UUIDv4 str
:raises HttpError: fq_name not found
"""
data = {
"type": type,
"fq_name": list(fq_name)
}
return self.post_json(self.make_url("/fqname-to-id"), data)["uuid"] | [
"def",
"fqname_to_id",
"(",
"self",
",",
"fq_name",
",",
"type",
")",
":",
"data",
"=",
"{",
"\"type\"",
":",
"type",
",",
"\"fq_name\"",
":",
"list",
"(",
"fq_name",
")",
"}",
"return",
"self",
".",
"post_json",
"(",
"self",
".",
"make_url",
"(",
"\"/fqname-to-id\"",
")",
",",
"data",
")",
"[",
"\"uuid\"",
"]"
] | Return uuid for fq_name
:param fq_name: resource fq name
:type fq_name: FQName
:param type: resource type
:type type: str
:rtype: UUIDv4 str
:raises HttpError: fq_name not found | [
"Return",
"uuid",
"for",
"fq_name"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/client.py#L163-L179 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/client.py | ContrailAPISession.id_to_fqname | def id_to_fqname(self, uuid, type=None):
"""
Return fq_name and type for uuid
If `type` is provided check that uuid is actually
a resource of type `type`. Raise HttpError if it's
not the case.
:param uuid: resource uuid
:type uuid: UUIDv4 str
:param type: resource type
:type type: str
:rtype: dict {'type': str, 'fq_name': FQName}
:raises HttpError: uuid not found
"""
data = {
"uuid": uuid
}
result = self.post_json(self.make_url("/id-to-fqname"), data)
result['fq_name'] = FQName(result['fq_name'])
if type is not None and not result['type'].replace('_', '-') == type:
raise HttpError('uuid %s not found for type %s' % (uuid, type), http_status=404)
return result | python | def id_to_fqname(self, uuid, type=None):
"""
Return fq_name and type for uuid
If `type` is provided check that uuid is actually
a resource of type `type`. Raise HttpError if it's
not the case.
:param uuid: resource uuid
:type uuid: UUIDv4 str
:param type: resource type
:type type: str
:rtype: dict {'type': str, 'fq_name': FQName}
:raises HttpError: uuid not found
"""
data = {
"uuid": uuid
}
result = self.post_json(self.make_url("/id-to-fqname"), data)
result['fq_name'] = FQName(result['fq_name'])
if type is not None and not result['type'].replace('_', '-') == type:
raise HttpError('uuid %s not found for type %s' % (uuid, type), http_status=404)
return result | [
"def",
"id_to_fqname",
"(",
"self",
",",
"uuid",
",",
"type",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"uuid\"",
":",
"uuid",
"}",
"result",
"=",
"self",
".",
"post_json",
"(",
"self",
".",
"make_url",
"(",
"\"/id-to-fqname\"",
")",
",",
"data",
")",
"result",
"[",
"'fq_name'",
"]",
"=",
"FQName",
"(",
"result",
"[",
"'fq_name'",
"]",
")",
"if",
"type",
"is",
"not",
"None",
"and",
"not",
"result",
"[",
"'type'",
"]",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"==",
"type",
":",
"raise",
"HttpError",
"(",
"'uuid %s not found for type %s'",
"%",
"(",
"uuid",
",",
"type",
")",
",",
"http_status",
"=",
"404",
")",
"return",
"result"
] | Return fq_name and type for uuid
If `type` is provided check that uuid is actually
a resource of type `type`. Raise HttpError if it's
not the case.
:param uuid: resource uuid
:type uuid: UUIDv4 str
:param type: resource type
:type type: str
:rtype: dict {'type': str, 'fq_name': FQName}
:raises HttpError: uuid not found | [
"Return",
"fq_name",
"and",
"type",
"for",
"uuid"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/client.py#L181-L204 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/client.py | ContrailAPISession.add_kv_store | def add_kv_store(self, key, value):
"""Add a key-value store entry.
:param key: string
:param value: string
"""
data = {
'operation': 'STORE',
'key': key,
'value': value
}
return self.post(self.make_url("/useragent-kv"), data=to_json(data),
headers=self.default_headers).text | python | def add_kv_store(self, key, value):
"""Add a key-value store entry.
:param key: string
:param value: string
"""
data = {
'operation': 'STORE',
'key': key,
'value': value
}
return self.post(self.make_url("/useragent-kv"), data=to_json(data),
headers=self.default_headers).text | [
"def",
"add_kv_store",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"data",
"=",
"{",
"'operation'",
":",
"'STORE'",
",",
"'key'",
":",
"key",
",",
"'value'",
":",
"value",
"}",
"return",
"self",
".",
"post",
"(",
"self",
".",
"make_url",
"(",
"\"/useragent-kv\"",
")",
",",
"data",
"=",
"to_json",
"(",
"data",
")",
",",
"headers",
"=",
"self",
".",
"default_headers",
")",
".",
"text"
] | Add a key-value store entry.
:param key: string
:param value: string | [
"Add",
"a",
"key",
"-",
"value",
"store",
"entry",
"."
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/client.py#L246-L258 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/client.py | ContrailAPISession.remove_kv_store | def remove_kv_store(self, key):
"""Remove a key-value store entry.
:param key: string
"""
data = {
'operation': 'DELETE',
'key': key
}
return self.post(self.make_url("/useragent-kv"), data=to_json(data),
headers=self.default_headers).text | python | def remove_kv_store(self, key):
"""Remove a key-value store entry.
:param key: string
"""
data = {
'operation': 'DELETE',
'key': key
}
return self.post(self.make_url("/useragent-kv"), data=to_json(data),
headers=self.default_headers).text | [
"def",
"remove_kv_store",
"(",
"self",
",",
"key",
")",
":",
"data",
"=",
"{",
"'operation'",
":",
"'DELETE'",
",",
"'key'",
":",
"key",
"}",
"return",
"self",
".",
"post",
"(",
"self",
".",
"make_url",
"(",
"\"/useragent-kv\"",
")",
",",
"data",
"=",
"to_json",
"(",
"data",
")",
",",
"headers",
"=",
"self",
".",
"default_headers",
")",
".",
"text"
] | Remove a key-value store entry.
:param key: string | [
"Remove",
"a",
"key",
"-",
"value",
"store",
"entry",
"."
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/client.py#L260-L270 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_oven.py | canonical_ops | def canonical_ops(ops):
''' Returns the given operations array sorted with duplicates removed.
@param ops checker.Ops
@return: checker.Ops
'''
new_ops = sorted(set(ops), key=lambda x: (x.entity, x.action))
return new_ops | python | def canonical_ops(ops):
''' Returns the given operations array sorted with duplicates removed.
@param ops checker.Ops
@return: checker.Ops
'''
new_ops = sorted(set(ops), key=lambda x: (x.entity, x.action))
return new_ops | [
"def",
"canonical_ops",
"(",
"ops",
")",
":",
"new_ops",
"=",
"sorted",
"(",
"set",
"(",
"ops",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"(",
"x",
".",
"entity",
",",
"x",
".",
"action",
")",
")",
"return",
"new_ops"
] | Returns the given operations array sorted with duplicates removed.
@param ops checker.Ops
@return: checker.Ops | [
"Returns",
"the",
"given",
"operations",
"array",
"sorted",
"with",
"duplicates",
"removed",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_oven.py#L269-L276 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_oven.py | _macaroon_id_ops | def _macaroon_id_ops(ops):
'''Return operations suitable for serializing as part of a MacaroonId.
It assumes that ops has been canonicalized and that there's at least
one operation.
'''
id_ops = []
for entity, entity_ops in itertools.groupby(ops, lambda x: x.entity):
actions = map(lambda x: x.action, entity_ops)
id_ops.append(id_pb2.Op(entity=entity, actions=actions))
return id_ops | python | def _macaroon_id_ops(ops):
'''Return operations suitable for serializing as part of a MacaroonId.
It assumes that ops has been canonicalized and that there's at least
one operation.
'''
id_ops = []
for entity, entity_ops in itertools.groupby(ops, lambda x: x.entity):
actions = map(lambda x: x.action, entity_ops)
id_ops.append(id_pb2.Op(entity=entity, actions=actions))
return id_ops | [
"def",
"_macaroon_id_ops",
"(",
"ops",
")",
":",
"id_ops",
"=",
"[",
"]",
"for",
"entity",
",",
"entity_ops",
"in",
"itertools",
".",
"groupby",
"(",
"ops",
",",
"lambda",
"x",
":",
"x",
".",
"entity",
")",
":",
"actions",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"action",
",",
"entity_ops",
")",
"id_ops",
".",
"append",
"(",
"id_pb2",
".",
"Op",
"(",
"entity",
"=",
"entity",
",",
"actions",
"=",
"actions",
")",
")",
"return",
"id_ops"
] | Return operations suitable for serializing as part of a MacaroonId.
It assumes that ops has been canonicalized and that there's at least
one operation. | [
"Return",
"operations",
"suitable",
"for",
"serializing",
"as",
"part",
"of",
"a",
"MacaroonId",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_oven.py#L279-L289 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_oven.py | Oven.macaroon | def macaroon(self, version, expiry, caveats, ops):
''' Takes a macaroon with the given version from the oven,
associates it with the given operations and attaches the given caveats.
There must be at least one operation specified.
The macaroon will expire at the given time - a time_before first party
caveat will be added with that time.
@return: a new Macaroon object.
'''
if len(ops) == 0:
raise ValueError('cannot mint a macaroon associated '
'with no operations')
ops = canonical_ops(ops)
root_key, storage_id = self.root_keystore_for_ops(ops).root_key()
id = self._new_macaroon_id(storage_id, expiry, ops)
id_bytes = six.int2byte(LATEST_VERSION) + \
id.SerializeToString()
if macaroon_version(version) < MACAROON_V2:
# The old macaroon format required valid text for the macaroon id,
# so base64-encode it.
id_bytes = raw_urlsafe_b64encode(id_bytes)
m = Macaroon(
root_key,
id_bytes,
self.location,
version,
self.namespace,
)
m.add_caveat(checkers.time_before_caveat(expiry), self.key,
self.locator)
m.add_caveats(caveats, self.key, self.locator)
return m | python | def macaroon(self, version, expiry, caveats, ops):
''' Takes a macaroon with the given version from the oven,
associates it with the given operations and attaches the given caveats.
There must be at least one operation specified.
The macaroon will expire at the given time - a time_before first party
caveat will be added with that time.
@return: a new Macaroon object.
'''
if len(ops) == 0:
raise ValueError('cannot mint a macaroon associated '
'with no operations')
ops = canonical_ops(ops)
root_key, storage_id = self.root_keystore_for_ops(ops).root_key()
id = self._new_macaroon_id(storage_id, expiry, ops)
id_bytes = six.int2byte(LATEST_VERSION) + \
id.SerializeToString()
if macaroon_version(version) < MACAROON_V2:
# The old macaroon format required valid text for the macaroon id,
# so base64-encode it.
id_bytes = raw_urlsafe_b64encode(id_bytes)
m = Macaroon(
root_key,
id_bytes,
self.location,
version,
self.namespace,
)
m.add_caveat(checkers.time_before_caveat(expiry), self.key,
self.locator)
m.add_caveats(caveats, self.key, self.locator)
return m | [
"def",
"macaroon",
"(",
"self",
",",
"version",
",",
"expiry",
",",
"caveats",
",",
"ops",
")",
":",
"if",
"len",
"(",
"ops",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'cannot mint a macaroon associated '",
"'with no operations'",
")",
"ops",
"=",
"canonical_ops",
"(",
"ops",
")",
"root_key",
",",
"storage_id",
"=",
"self",
".",
"root_keystore_for_ops",
"(",
"ops",
")",
".",
"root_key",
"(",
")",
"id",
"=",
"self",
".",
"_new_macaroon_id",
"(",
"storage_id",
",",
"expiry",
",",
"ops",
")",
"id_bytes",
"=",
"six",
".",
"int2byte",
"(",
"LATEST_VERSION",
")",
"+",
"id",
".",
"SerializeToString",
"(",
")",
"if",
"macaroon_version",
"(",
"version",
")",
"<",
"MACAROON_V2",
":",
"# The old macaroon format required valid text for the macaroon id,",
"# so base64-encode it.",
"id_bytes",
"=",
"raw_urlsafe_b64encode",
"(",
"id_bytes",
")",
"m",
"=",
"Macaroon",
"(",
"root_key",
",",
"id_bytes",
",",
"self",
".",
"location",
",",
"version",
",",
"self",
".",
"namespace",
",",
")",
"m",
".",
"add_caveat",
"(",
"checkers",
".",
"time_before_caveat",
"(",
"expiry",
")",
",",
"self",
".",
"key",
",",
"self",
".",
"locator",
")",
"m",
".",
"add_caveats",
"(",
"caveats",
",",
"self",
".",
"key",
",",
"self",
".",
"locator",
")",
"return",
"m"
] | Takes a macaroon with the given version from the oven,
associates it with the given operations and attaches the given caveats.
There must be at least one operation specified.
The macaroon will expire at the given time - a time_before first party
caveat will be added with that time.
@return: a new Macaroon object. | [
"Takes",
"a",
"macaroon",
"with",
"the",
"given",
"version",
"from",
"the",
"oven",
"associates",
"it",
"with",
"the",
"given",
"operations",
"and",
"attaches",
"the",
"given",
"caveats",
".",
"There",
"must",
"be",
"at",
"least",
"one",
"operation",
"specified",
".",
"The",
"macaroon",
"will",
"expire",
"at",
"the",
"given",
"time",
"-",
"a",
"time_before",
"first",
"party",
"caveat",
"will",
"be",
"added",
"with",
"that",
"time",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_oven.py#L81-L117 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_oven.py | Oven.ops_entity | def ops_entity(self, ops):
''' Returns a new multi-op entity name string that represents
all the given operations and caveats. It returns the same value
regardless of the ordering of the operations. It assumes that the
operations have been canonicalized and that there's at least one
operation.
:param ops:
:return: string that represents all the given operations and caveats.
'''
# Hash the operations, removing duplicates as we go.
hash_entity = hashlib.sha256()
for op in ops:
hash_entity.update('{}\n{}\n'.format(
op.action, op.entity).encode())
hash_encoded = base64.urlsafe_b64encode(hash_entity.digest())
return 'multi-' + hash_encoded.decode('utf-8').rstrip('=') | python | def ops_entity(self, ops):
''' Returns a new multi-op entity name string that represents
all the given operations and caveats. It returns the same value
regardless of the ordering of the operations. It assumes that the
operations have been canonicalized and that there's at least one
operation.
:param ops:
:return: string that represents all the given operations and caveats.
'''
# Hash the operations, removing duplicates as we go.
hash_entity = hashlib.sha256()
for op in ops:
hash_entity.update('{}\n{}\n'.format(
op.action, op.entity).encode())
hash_encoded = base64.urlsafe_b64encode(hash_entity.digest())
return 'multi-' + hash_encoded.decode('utf-8').rstrip('=') | [
"def",
"ops_entity",
"(",
"self",
",",
"ops",
")",
":",
"# Hash the operations, removing duplicates as we go.",
"hash_entity",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"for",
"op",
"in",
"ops",
":",
"hash_entity",
".",
"update",
"(",
"'{}\\n{}\\n'",
".",
"format",
"(",
"op",
".",
"action",
",",
"op",
".",
"entity",
")",
".",
"encode",
"(",
")",
")",
"hash_encoded",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"hash_entity",
".",
"digest",
"(",
")",
")",
"return",
"'multi-'",
"+",
"hash_encoded",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"rstrip",
"(",
"'='",
")"
] | Returns a new multi-op entity name string that represents
all the given operations and caveats. It returns the same value
regardless of the ordering of the operations. It assumes that the
operations have been canonicalized and that there's at least one
operation.
:param ops:
:return: string that represents all the given operations and caveats. | [
"Returns",
"a",
"new",
"multi",
"-",
"op",
"entity",
"name",
"string",
"that",
"represents",
"all",
"the",
"given",
"operations",
"and",
"caveats",
".",
"It",
"returns",
"the",
"same",
"value",
"regardless",
"of",
"the",
"ordering",
"of",
"the",
"operations",
".",
"It",
"assumes",
"that",
"the",
"operations",
"have",
"been",
"canonicalized",
"and",
"that",
"there",
"s",
"at",
"least",
"one",
"operation",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_oven.py#L135-L151 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_oven.py | Oven.macaroon_ops | def macaroon_ops(self, macaroons):
''' This method makes the oven satisfy the MacaroonOpStore protocol
required by the Checker class.
For macaroons minted with previous bakery versions, it always
returns a single LoginOp operation.
:param macaroons:
:return:
'''
if len(macaroons) == 0:
raise ValueError('no macaroons provided')
storage_id, ops = _decode_macaroon_id(macaroons[0].identifier_bytes)
root_key = self.root_keystore_for_ops(ops).get(storage_id)
if root_key is None:
raise VerificationError(
'macaroon key not found in storage')
v = Verifier()
conditions = []
def validator(condition):
# Verify the macaroon's signature only. Don't check any of the
# caveats yet but save them so that we can return them.
conditions.append(condition)
return True
v.satisfy_general(validator)
try:
v.verify(macaroons[0], root_key, macaroons[1:])
except Exception as exc:
# Unfortunately pymacaroons doesn't control
# the set of exceptions that can be raised here.
# Possible candidates are:
# pymacaroons.exceptions.MacaroonUnmetCaveatException
# pymacaroons.exceptions.MacaroonInvalidSignatureException
# ValueError
# nacl.exceptions.CryptoError
#
# There may be others too, so just catch everything.
raise six.raise_from(
VerificationError('verification failed: {}'.format(str(exc))),
exc,
)
if (self.ops_store is not None
and len(ops) == 1
and ops[0].entity.startswith('multi-')):
# It's a multi-op entity, so retrieve the actual operations
# it's associated with.
ops = self.ops_store.get_ops(ops[0].entity)
return ops, conditions | python | def macaroon_ops(self, macaroons):
''' This method makes the oven satisfy the MacaroonOpStore protocol
required by the Checker class.
For macaroons minted with previous bakery versions, it always
returns a single LoginOp operation.
:param macaroons:
:return:
'''
if len(macaroons) == 0:
raise ValueError('no macaroons provided')
storage_id, ops = _decode_macaroon_id(macaroons[0].identifier_bytes)
root_key = self.root_keystore_for_ops(ops).get(storage_id)
if root_key is None:
raise VerificationError(
'macaroon key not found in storage')
v = Verifier()
conditions = []
def validator(condition):
# Verify the macaroon's signature only. Don't check any of the
# caveats yet but save them so that we can return them.
conditions.append(condition)
return True
v.satisfy_general(validator)
try:
v.verify(macaroons[0], root_key, macaroons[1:])
except Exception as exc:
# Unfortunately pymacaroons doesn't control
# the set of exceptions that can be raised here.
# Possible candidates are:
# pymacaroons.exceptions.MacaroonUnmetCaveatException
# pymacaroons.exceptions.MacaroonInvalidSignatureException
# ValueError
# nacl.exceptions.CryptoError
#
# There may be others too, so just catch everything.
raise six.raise_from(
VerificationError('verification failed: {}'.format(str(exc))),
exc,
)
if (self.ops_store is not None
and len(ops) == 1
and ops[0].entity.startswith('multi-')):
# It's a multi-op entity, so retrieve the actual operations
# it's associated with.
ops = self.ops_store.get_ops(ops[0].entity)
return ops, conditions | [
"def",
"macaroon_ops",
"(",
"self",
",",
"macaroons",
")",
":",
"if",
"len",
"(",
"macaroons",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'no macaroons provided'",
")",
"storage_id",
",",
"ops",
"=",
"_decode_macaroon_id",
"(",
"macaroons",
"[",
"0",
"]",
".",
"identifier_bytes",
")",
"root_key",
"=",
"self",
".",
"root_keystore_for_ops",
"(",
"ops",
")",
".",
"get",
"(",
"storage_id",
")",
"if",
"root_key",
"is",
"None",
":",
"raise",
"VerificationError",
"(",
"'macaroon key not found in storage'",
")",
"v",
"=",
"Verifier",
"(",
")",
"conditions",
"=",
"[",
"]",
"def",
"validator",
"(",
"condition",
")",
":",
"# Verify the macaroon's signature only. Don't check any of the",
"# caveats yet but save them so that we can return them.",
"conditions",
".",
"append",
"(",
"condition",
")",
"return",
"True",
"v",
".",
"satisfy_general",
"(",
"validator",
")",
"try",
":",
"v",
".",
"verify",
"(",
"macaroons",
"[",
"0",
"]",
",",
"root_key",
",",
"macaroons",
"[",
"1",
":",
"]",
")",
"except",
"Exception",
"as",
"exc",
":",
"# Unfortunately pymacaroons doesn't control",
"# the set of exceptions that can be raised here.",
"# Possible candidates are:",
"# pymacaroons.exceptions.MacaroonUnmetCaveatException",
"# pymacaroons.exceptions.MacaroonInvalidSignatureException",
"# ValueError",
"# nacl.exceptions.CryptoError",
"#",
"# There may be others too, so just catch everything.",
"raise",
"six",
".",
"raise_from",
"(",
"VerificationError",
"(",
"'verification failed: {}'",
".",
"format",
"(",
"str",
"(",
"exc",
")",
")",
")",
",",
"exc",
",",
")",
"if",
"(",
"self",
".",
"ops_store",
"is",
"not",
"None",
"and",
"len",
"(",
"ops",
")",
"==",
"1",
"and",
"ops",
"[",
"0",
"]",
".",
"entity",
".",
"startswith",
"(",
"'multi-'",
")",
")",
":",
"# It's a multi-op entity, so retrieve the actual operations",
"# it's associated with.",
"ops",
"=",
"self",
".",
"ops_store",
".",
"get_ops",
"(",
"ops",
"[",
"0",
"]",
".",
"entity",
")",
"return",
"ops",
",",
"conditions"
] | This method makes the oven satisfy the MacaroonOpStore protocol
required by the Checker class.
For macaroons minted with previous bakery versions, it always
returns a single LoginOp operation.
:param macaroons:
:return: | [
"This",
"method",
"makes",
"the",
"oven",
"satisfy",
"the",
"MacaroonOpStore",
"protocol",
"required",
"by",
"the",
"Checker",
"class",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_oven.py#L153-L204 | train |
ets-labs/python-domain-models | domain_models/collections.py | Collection.extend | def extend(self, iterable):
"""Extend the list by appending all the items in the given list."""
return super(Collection, self).extend(
self._ensure_iterable_is_valid(iterable)) | python | def extend(self, iterable):
"""Extend the list by appending all the items in the given list."""
return super(Collection, self).extend(
self._ensure_iterable_is_valid(iterable)) | [
"def",
"extend",
"(",
"self",
",",
"iterable",
")",
":",
"return",
"super",
"(",
"Collection",
",",
"self",
")",
".",
"extend",
"(",
"self",
".",
"_ensure_iterable_is_valid",
"(",
"iterable",
")",
")"
] | Extend the list by appending all the items in the given list. | [
"Extend",
"the",
"list",
"by",
"appending",
"all",
"the",
"items",
"in",
"the",
"given",
"list",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/collections.py#L27-L30 | train |
ets-labs/python-domain-models | domain_models/collections.py | Collection.insert | def insert(self, index, value):
"""Insert an item at a given position."""
return super(Collection, self).insert(
index, self._ensure_value_is_valid(value)) | python | def insert(self, index, value):
"""Insert an item at a given position."""
return super(Collection, self).insert(
index, self._ensure_value_is_valid(value)) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"value",
")",
":",
"return",
"super",
"(",
"Collection",
",",
"self",
")",
".",
"insert",
"(",
"index",
",",
"self",
".",
"_ensure_value_is_valid",
"(",
"value",
")",
")"
] | Insert an item at a given position. | [
"Insert",
"an",
"item",
"at",
"a",
"given",
"position",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/collections.py#L32-L35 | train |
ets-labs/python-domain-models | domain_models/collections.py | Collection._ensure_value_is_valid | def _ensure_value_is_valid(self, value):
"""Ensure that value is a valid collection's value."""
if not isinstance(value, self.__class__.value_type):
raise TypeError('{0} is not valid collection value, instance '
'of {1} required'.format(
value, self.__class__.value_type))
return value | python | def _ensure_value_is_valid(self, value):
"""Ensure that value is a valid collection's value."""
if not isinstance(value, self.__class__.value_type):
raise TypeError('{0} is not valid collection value, instance '
'of {1} required'.format(
value, self.__class__.value_type))
return value | [
"def",
"_ensure_value_is_valid",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"__class__",
".",
"value_type",
")",
":",
"raise",
"TypeError",
"(",
"'{0} is not valid collection value, instance '",
"'of {1} required'",
".",
"format",
"(",
"value",
",",
"self",
".",
"__class__",
".",
"value_type",
")",
")",
"return",
"value"
] | Ensure that value is a valid collection's value. | [
"Ensure",
"that",
"value",
"is",
"a",
"valid",
"collection",
"s",
"value",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/collections.py#L71-L77 | train |
ph4r05/monero-serialize | monero_serialize/core/message_types.py | container_elem_type | def container_elem_type(container_type, params):
"""
Returns container element type
:param container_type:
:param params:
:return:
"""
elem_type = params[0] if params else None
if elem_type is None:
elem_type = container_type.ELEM_TYPE
return elem_type | python | def container_elem_type(container_type, params):
"""
Returns container element type
:param container_type:
:param params:
:return:
"""
elem_type = params[0] if params else None
if elem_type is None:
elem_type = container_type.ELEM_TYPE
return elem_type | [
"def",
"container_elem_type",
"(",
"container_type",
",",
"params",
")",
":",
"elem_type",
"=",
"params",
"[",
"0",
"]",
"if",
"params",
"else",
"None",
"if",
"elem_type",
"is",
"None",
":",
"elem_type",
"=",
"container_type",
".",
"ELEM_TYPE",
"return",
"elem_type"
] | Returns container element type
:param container_type:
:param params:
:return: | [
"Returns",
"container",
"element",
"type"
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/core/message_types.py#L153-L164 | train |
Phyks/libbmc | libbmc/doi.py | is_valid | def is_valid(doi):
"""
Check that a given DOI is a valid canonical DOI.
:param doi: The DOI to be checked.
:returns: Boolean indicating whether the DOI is valid or not.
>>> is_valid('10.1209/0295-5075/111/40005')
True
>>> is_valid('10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7')
True
>>> is_valid('10.1002/(SICI)1522-2594(199911)42:5<952::AID-MRM16>3.0.CO;2-S')
True
>>> is_valid('10.1007/978-3-642-28108-2_19')
True
>>> is_valid('10.1007.10/978-3-642-28108-2_19')
True
>>> is_valid('10.1016/S0735-1097(98)00347-7')
True
>>> is_valid('10.1579/0044-7447(2006)35\[89:RDUICP\]2.0.CO;2')
True
>>> is_valid('<geo coords="10.4515260,51.1656910"></geo>')
False
"""
match = REGEX.match(doi)
return (match is not None) and (match.group(0) == doi) | python | def is_valid(doi):
"""
Check that a given DOI is a valid canonical DOI.
:param doi: The DOI to be checked.
:returns: Boolean indicating whether the DOI is valid or not.
>>> is_valid('10.1209/0295-5075/111/40005')
True
>>> is_valid('10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7')
True
>>> is_valid('10.1002/(SICI)1522-2594(199911)42:5<952::AID-MRM16>3.0.CO;2-S')
True
>>> is_valid('10.1007/978-3-642-28108-2_19')
True
>>> is_valid('10.1007.10/978-3-642-28108-2_19')
True
>>> is_valid('10.1016/S0735-1097(98)00347-7')
True
>>> is_valid('10.1579/0044-7447(2006)35\[89:RDUICP\]2.0.CO;2')
True
>>> is_valid('<geo coords="10.4515260,51.1656910"></geo>')
False
"""
match = REGEX.match(doi)
return (match is not None) and (match.group(0) == doi) | [
"def",
"is_valid",
"(",
"doi",
")",
":",
"match",
"=",
"REGEX",
".",
"match",
"(",
"doi",
")",
"return",
"(",
"match",
"is",
"not",
"None",
")",
"and",
"(",
"match",
".",
"group",
"(",
"0",
")",
"==",
"doi",
")"
] | Check that a given DOI is a valid canonical DOI.
:param doi: The DOI to be checked.
:returns: Boolean indicating whether the DOI is valid or not.
>>> is_valid('10.1209/0295-5075/111/40005')
True
>>> is_valid('10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7')
True
>>> is_valid('10.1002/(SICI)1522-2594(199911)42:5<952::AID-MRM16>3.0.CO;2-S')
True
>>> is_valid('10.1007/978-3-642-28108-2_19')
True
>>> is_valid('10.1007.10/978-3-642-28108-2_19')
True
>>> is_valid('10.1016/S0735-1097(98)00347-7')
True
>>> is_valid('10.1579/0044-7447(2006)35\[89:RDUICP\]2.0.CO;2')
True
>>> is_valid('<geo coords="10.4515260,51.1656910"></geo>')
False | [
"Check",
"that",
"a",
"given",
"DOI",
"is",
"a",
"valid",
"canonical",
"DOI",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/doi.py#L26-L58 | train |
Phyks/libbmc | libbmc/doi.py | get_oa_version | def get_oa_version(doi):
"""
Get an OA version for a given DOI.
.. note::
Uses beta.dissem.in API.
:param doi: A canonical DOI.
:returns: The URL of the OA version of the given DOI, or ``None``.
>>> get_oa_version('10.1209/0295-5075/111/40005')
'http://arxiv.org/abs/1506.06690'
"""
try:
request = requests.get("%s%s" % (DISSEMIN_API, doi))
request.raise_for_status()
result = request.json()
assert result["status"] == "ok"
return result["paper"]["pdf_url"]
except (AssertionError, ValueError, KeyError, RequestException):
return None | python | def get_oa_version(doi):
"""
Get an OA version for a given DOI.
.. note::
Uses beta.dissem.in API.
:param doi: A canonical DOI.
:returns: The URL of the OA version of the given DOI, or ``None``.
>>> get_oa_version('10.1209/0295-5075/111/40005')
'http://arxiv.org/abs/1506.06690'
"""
try:
request = requests.get("%s%s" % (DISSEMIN_API, doi))
request.raise_for_status()
result = request.json()
assert result["status"] == "ok"
return result["paper"]["pdf_url"]
except (AssertionError, ValueError, KeyError, RequestException):
return None | [
"def",
"get_oa_version",
"(",
"doi",
")",
":",
"try",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"\"%s%s\"",
"%",
"(",
"DISSEMIN_API",
",",
"doi",
")",
")",
"request",
".",
"raise_for_status",
"(",
")",
"result",
"=",
"request",
".",
"json",
"(",
")",
"assert",
"result",
"[",
"\"status\"",
"]",
"==",
"\"ok\"",
"return",
"result",
"[",
"\"paper\"",
"]",
"[",
"\"pdf_url\"",
"]",
"except",
"(",
"AssertionError",
",",
"ValueError",
",",
"KeyError",
",",
"RequestException",
")",
":",
"return",
"None"
] | Get an OA version for a given DOI.
.. note::
Uses beta.dissem.in API.
:param doi: A canonical DOI.
:returns: The URL of the OA version of the given DOI, or ``None``.
>>> get_oa_version('10.1209/0295-5075/111/40005')
'http://arxiv.org/abs/1506.06690' | [
"Get",
"an",
"OA",
"version",
"for",
"a",
"given",
"DOI",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/doi.py#L116-L137 | train |
Phyks/libbmc | libbmc/doi.py | get_oa_policy | def get_oa_policy(doi):
"""
Get OA policy for a given DOI.
.. note::
Uses beta.dissem.in API.
:param doi: A canonical DOI.
:returns: The OpenAccess policy for the associated publications, or \
``None`` if unknown.
>>> tmp = get_oa_policy('10.1209/0295-5075/111/40005'); (tmp["published"], tmp["preprint"], tmp["postprint"], tmp["romeo_id"])
('can', 'can', 'can', '1896')
>>> get_oa_policy('10.1215/9780822387268') is None
True
"""
try:
request = requests.get("%s%s" % (DISSEMIN_API, doi))
request.raise_for_status()
result = request.json()
assert result["status"] == "ok"
return ([i
for i in result["paper"]["publications"]
if i["doi"] == doi][0])["policy"]
except (AssertionError, ValueError,
KeyError, RequestException, IndexError):
return None | python | def get_oa_policy(doi):
"""
Get OA policy for a given DOI.
.. note::
Uses beta.dissem.in API.
:param doi: A canonical DOI.
:returns: The OpenAccess policy for the associated publications, or \
``None`` if unknown.
>>> tmp = get_oa_policy('10.1209/0295-5075/111/40005'); (tmp["published"], tmp["preprint"], tmp["postprint"], tmp["romeo_id"])
('can', 'can', 'can', '1896')
>>> get_oa_policy('10.1215/9780822387268') is None
True
"""
try:
request = requests.get("%s%s" % (DISSEMIN_API, doi))
request.raise_for_status()
result = request.json()
assert result["status"] == "ok"
return ([i
for i in result["paper"]["publications"]
if i["doi"] == doi][0])["policy"]
except (AssertionError, ValueError,
KeyError, RequestException, IndexError):
return None | [
"def",
"get_oa_policy",
"(",
"doi",
")",
":",
"try",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"\"%s%s\"",
"%",
"(",
"DISSEMIN_API",
",",
"doi",
")",
")",
"request",
".",
"raise_for_status",
"(",
")",
"result",
"=",
"request",
".",
"json",
"(",
")",
"assert",
"result",
"[",
"\"status\"",
"]",
"==",
"\"ok\"",
"return",
"(",
"[",
"i",
"for",
"i",
"in",
"result",
"[",
"\"paper\"",
"]",
"[",
"\"publications\"",
"]",
"if",
"i",
"[",
"\"doi\"",
"]",
"==",
"doi",
"]",
"[",
"0",
"]",
")",
"[",
"\"policy\"",
"]",
"except",
"(",
"AssertionError",
",",
"ValueError",
",",
"KeyError",
",",
"RequestException",
",",
"IndexError",
")",
":",
"return",
"None"
] | Get OA policy for a given DOI.
.. note::
Uses beta.dissem.in API.
:param doi: A canonical DOI.
:returns: The OpenAccess policy for the associated publications, or \
``None`` if unknown.
>>> tmp = get_oa_policy('10.1209/0295-5075/111/40005'); (tmp["published"], tmp["preprint"], tmp["postprint"], tmp["romeo_id"])
('can', 'can', 'can', '1896')
>>> get_oa_policy('10.1215/9780822387268') is None
True | [
"Get",
"OA",
"policy",
"for",
"a",
"given",
"DOI",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/doi.py#L140-L168 | train |
Phyks/libbmc | libbmc/doi.py | get_linked_version | def get_linked_version(doi):
"""
Get the original link behind the DOI.
:param doi: A canonical DOI.
:returns: The canonical URL behind the DOI, or ``None``.
>>> get_linked_version('10.1209/0295-5075/111/40005')
'http://stacks.iop.org/0295-5075/111/i=4/a=40005?key=crossref.9ad851948a976ecdf216d4929b0b6f01'
"""
try:
request = requests.head(to_url(doi))
return request.headers.get("location")
except RequestException:
return None | python | def get_linked_version(doi):
"""
Get the original link behind the DOI.
:param doi: A canonical DOI.
:returns: The canonical URL behind the DOI, or ``None``.
>>> get_linked_version('10.1209/0295-5075/111/40005')
'http://stacks.iop.org/0295-5075/111/i=4/a=40005?key=crossref.9ad851948a976ecdf216d4929b0b6f01'
"""
try:
request = requests.head(to_url(doi))
return request.headers.get("location")
except RequestException:
return None | [
"def",
"get_linked_version",
"(",
"doi",
")",
":",
"try",
":",
"request",
"=",
"requests",
".",
"head",
"(",
"to_url",
"(",
"doi",
")",
")",
"return",
"request",
".",
"headers",
".",
"get",
"(",
"\"location\"",
")",
"except",
"RequestException",
":",
"return",
"None"
] | Get the original link behind the DOI.
:param doi: A canonical DOI.
:returns: The canonical URL behind the DOI, or ``None``.
>>> get_linked_version('10.1209/0295-5075/111/40005')
'http://stacks.iop.org/0295-5075/111/i=4/a=40005?key=crossref.9ad851948a976ecdf216d4929b0b6f01' | [
"Get",
"the",
"original",
"link",
"behind",
"the",
"DOI",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/doi.py#L171-L185 | train |
Phyks/libbmc | libbmc/doi.py | get_bibtex | def get_bibtex(doi):
"""
Get a BibTeX entry for a given DOI.
.. note::
Adapted from https://gist.github.com/jrsmith3/5513926.
:param doi: The canonical DOI to get BibTeX from.
:returns: A BibTeX string or ``None``.
>>> get_bibtex('10.1209/0295-5075/111/40005')
'@article{Verney_2015,\\n\\tdoi = {10.1209/0295-5075/111/40005},\\n\\turl = {http://dx.doi.org/10.1209/0295-5075/111/40005},\\n\\tyear = 2015,\\n\\tmonth = {aug},\\n\\tpublisher = {{IOP} Publishing},\\n\\tvolume = {111},\\n\\tnumber = {4},\\n\\tpages = {40005},\\n\\tauthor = {Lucas Verney and Lev Pitaevskii and Sandro Stringari},\\n\\ttitle = {Hybridization of first and second sound in a weakly interacting Bose gas},\\n\\tjournal = {{EPL}}\\n}'
"""
try:
request = requests.get(to_url(doi),
headers={"accept": "application/x-bibtex"})
request.raise_for_status()
assert request.headers.get("content-type") == "application/x-bibtex"
return request.text
except (RequestException, AssertionError):
return None | python | def get_bibtex(doi):
"""
Get a BibTeX entry for a given DOI.
.. note::
Adapted from https://gist.github.com/jrsmith3/5513926.
:param doi: The canonical DOI to get BibTeX from.
:returns: A BibTeX string or ``None``.
>>> get_bibtex('10.1209/0295-5075/111/40005')
'@article{Verney_2015,\\n\\tdoi = {10.1209/0295-5075/111/40005},\\n\\turl = {http://dx.doi.org/10.1209/0295-5075/111/40005},\\n\\tyear = 2015,\\n\\tmonth = {aug},\\n\\tpublisher = {{IOP} Publishing},\\n\\tvolume = {111},\\n\\tnumber = {4},\\n\\tpages = {40005},\\n\\tauthor = {Lucas Verney and Lev Pitaevskii and Sandro Stringari},\\n\\ttitle = {Hybridization of first and second sound in a weakly interacting Bose gas},\\n\\tjournal = {{EPL}}\\n}'
"""
try:
request = requests.get(to_url(doi),
headers={"accept": "application/x-bibtex"})
request.raise_for_status()
assert request.headers.get("content-type") == "application/x-bibtex"
return request.text
except (RequestException, AssertionError):
return None | [
"def",
"get_bibtex",
"(",
"doi",
")",
":",
"try",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"to_url",
"(",
"doi",
")",
",",
"headers",
"=",
"{",
"\"accept\"",
":",
"\"application/x-bibtex\"",
"}",
")",
"request",
".",
"raise_for_status",
"(",
")",
"assert",
"request",
".",
"headers",
".",
"get",
"(",
"\"content-type\"",
")",
"==",
"\"application/x-bibtex\"",
"return",
"request",
".",
"text",
"except",
"(",
"RequestException",
",",
"AssertionError",
")",
":",
"return",
"None"
] | Get a BibTeX entry for a given DOI.
.. note::
Adapted from https://gist.github.com/jrsmith3/5513926.
:param doi: The canonical DOI to get BibTeX from.
:returns: A BibTeX string or ``None``.
>>> get_bibtex('10.1209/0295-5075/111/40005')
'@article{Verney_2015,\\n\\tdoi = {10.1209/0295-5075/111/40005},\\n\\turl = {http://dx.doi.org/10.1209/0295-5075/111/40005},\\n\\tyear = 2015,\\n\\tmonth = {aug},\\n\\tpublisher = {{IOP} Publishing},\\n\\tvolume = {111},\\n\\tnumber = {4},\\n\\tpages = {40005},\\n\\tauthor = {Lucas Verney and Lev Pitaevskii and Sandro Stringari},\\n\\ttitle = {Hybridization of first and second sound in a weakly interacting Bose gas},\\n\\tjournal = {{EPL}}\\n}' | [
"Get",
"a",
"BibTeX",
"entry",
"for",
"a",
"given",
"DOI",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/doi.py#L188-L209 | train |
useblocks/groundwork | groundwork/groundwork.py | App._configure_logging | def _configure_logging(self, logger_dict=None):
"""
Configures the logging module with a given dictionary, which in most cases was loaded from a configuration
file.
If no dictionary is provided, it falls back to a default configuration.
See `Python docs
<https://docs.python.org/3.5/library/logging.config.html#logging.config.dictConfig>`_ for more information.
:param logger_dict: dictionary for logger.
"""
self.log.debug("Configure logging")
# Let's be sure, that for our log no handlers are registered anymore
for handler in self.log.handlers:
self.log.removeHandler(handler)
if logger_dict is None:
self.log.debug("No logger dictionary defined. Doing default logger configuration")
formatter = logging.Formatter("%(name)s - %(asctime)s - [%(levelname)s] - %(module)s - %(message)s")
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.WARNING)
stream_handler.setFormatter(formatter)
self.log.addHandler(stream_handler)
self.log.setLevel(logging.WARNING)
else:
self.log.debug("Logger dictionary defined. Loading dictConfig for logging")
logging.config.dictConfig(logger_dict)
self.log.debug("dictConfig loaded") | python | def _configure_logging(self, logger_dict=None):
"""
Configures the logging module with a given dictionary, which in most cases was loaded from a configuration
file.
If no dictionary is provided, it falls back to a default configuration.
See `Python docs
<https://docs.python.org/3.5/library/logging.config.html#logging.config.dictConfig>`_ for more information.
:param logger_dict: dictionary for logger.
"""
self.log.debug("Configure logging")
# Let's be sure, that for our log no handlers are registered anymore
for handler in self.log.handlers:
self.log.removeHandler(handler)
if logger_dict is None:
self.log.debug("No logger dictionary defined. Doing default logger configuration")
formatter = logging.Formatter("%(name)s - %(asctime)s - [%(levelname)s] - %(module)s - %(message)s")
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.WARNING)
stream_handler.setFormatter(formatter)
self.log.addHandler(stream_handler)
self.log.setLevel(logging.WARNING)
else:
self.log.debug("Logger dictionary defined. Loading dictConfig for logging")
logging.config.dictConfig(logger_dict)
self.log.debug("dictConfig loaded") | [
"def",
"_configure_logging",
"(",
"self",
",",
"logger_dict",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Configure logging\"",
")",
"# Let's be sure, that for our log no handlers are registered anymore",
"for",
"handler",
"in",
"self",
".",
"log",
".",
"handlers",
":",
"self",
".",
"log",
".",
"removeHandler",
"(",
"handler",
")",
"if",
"logger_dict",
"is",
"None",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"No logger dictionary defined. Doing default logger configuration\"",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"\"%(name)s - %(asctime)s - [%(levelname)s] - %(module)s - %(message)s\"",
")",
"stream_handler",
"=",
"logging",
".",
"StreamHandler",
"(",
"sys",
".",
"stdout",
")",
"stream_handler",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"stream_handler",
".",
"setFormatter",
"(",
"formatter",
")",
"self",
".",
"log",
".",
"addHandler",
"(",
"stream_handler",
")",
"self",
".",
"log",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"else",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Logger dictionary defined. Loading dictConfig for logging\"",
")",
"logging",
".",
"config",
".",
"dictConfig",
"(",
"logger_dict",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"dictConfig loaded\"",
")"
] | Configures the logging module with a given dictionary, which in most cases was loaded from a configuration
file.
If no dictionary is provided, it falls back to a default configuration.
See `Python docs
<https://docs.python.org/3.5/library/logging.config.html#logging.config.dictConfig>`_ for more information.
:param logger_dict: dictionary for logger. | [
"Configures",
"the",
"logging",
"module",
"with",
"a",
"given",
"dictionary",
"which",
"in",
"most",
"cases",
"was",
"loaded",
"from",
"a",
"configuration",
"file",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/groundwork.py#L92-L120 | train |
ph4r05/monero-serialize | monero_serialize/xmrserialize.py | Archive._dump_message_field | async def _dump_message_field(self, writer, msg, field, fvalue=None):
"""
Dumps a message field to the writer. Field is defined by the message field specification.
:param writer:
:param msg:
:param field:
:param fvalue:
:return:
"""
fname, ftype, params = field[0], field[1], field[2:]
fvalue = getattr(msg, fname, None) if fvalue is None else fvalue
await self.dump_field(writer, fvalue, ftype, params) | python | async def _dump_message_field(self, writer, msg, field, fvalue=None):
"""
Dumps a message field to the writer. Field is defined by the message field specification.
:param writer:
:param msg:
:param field:
:param fvalue:
:return:
"""
fname, ftype, params = field[0], field[1], field[2:]
fvalue = getattr(msg, fname, None) if fvalue is None else fvalue
await self.dump_field(writer, fvalue, ftype, params) | [
"async",
"def",
"_dump_message_field",
"(",
"self",
",",
"writer",
",",
"msg",
",",
"field",
",",
"fvalue",
"=",
"None",
")",
":",
"fname",
",",
"ftype",
",",
"params",
"=",
"field",
"[",
"0",
"]",
",",
"field",
"[",
"1",
"]",
",",
"field",
"[",
"2",
":",
"]",
"fvalue",
"=",
"getattr",
"(",
"msg",
",",
"fname",
",",
"None",
")",
"if",
"fvalue",
"is",
"None",
"else",
"fvalue",
"await",
"self",
".",
"dump_field",
"(",
"writer",
",",
"fvalue",
",",
"ftype",
",",
"params",
")"
] | Dumps a message field to the writer. Field is defined by the message field specification.
:param writer:
:param msg:
:param field:
:param fvalue:
:return: | [
"Dumps",
"a",
"message",
"field",
"to",
"the",
"writer",
".",
"Field",
"is",
"defined",
"by",
"the",
"message",
"field",
"specification",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrserialize.py#L659-L671 | train |
ph4r05/monero-serialize | monero_serialize/xmrserialize.py | Archive._load_message_field | async def _load_message_field(self, reader, msg, field):
"""
Loads message field from the reader. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:return:
"""
fname, ftype, params = field[0], field[1], field[2:]
await self.load_field(reader, ftype, params, eref(msg, fname)) | python | async def _load_message_field(self, reader, msg, field):
"""
Loads message field from the reader. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:return:
"""
fname, ftype, params = field[0], field[1], field[2:]
await self.load_field(reader, ftype, params, eref(msg, fname)) | [
"async",
"def",
"_load_message_field",
"(",
"self",
",",
"reader",
",",
"msg",
",",
"field",
")",
":",
"fname",
",",
"ftype",
",",
"params",
"=",
"field",
"[",
"0",
"]",
",",
"field",
"[",
"1",
"]",
",",
"field",
"[",
"2",
":",
"]",
"await",
"self",
".",
"load_field",
"(",
"reader",
",",
"ftype",
",",
"params",
",",
"eref",
"(",
"msg",
",",
"fname",
")",
")"
] | Loads message field from the reader. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:return: | [
"Loads",
"message",
"field",
"from",
"the",
"reader",
".",
"Field",
"is",
"defined",
"by",
"the",
"message",
"field",
"specification",
".",
"Returns",
"loaded",
"value",
"supports",
"field",
"reference",
"."
] | cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42 | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrserialize.py#L673-L684 | train |
dbarsam/python-vsgen | vsgen/util/timer.py | VSGTimer.start | def start(self, message):
"""
Manually starts timer with the message.
:param message: The display message.
"""
self._start = time.clock()
VSGLogger.info("{0:<20} - Started".format(message)) | python | def start(self, message):
"""
Manually starts timer with the message.
:param message: The display message.
"""
self._start = time.clock()
VSGLogger.info("{0:<20} - Started".format(message)) | [
"def",
"start",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"_start",
"=",
"time",
".",
"clock",
"(",
")",
"VSGLogger",
".",
"info",
"(",
"\"{0:<20} - Started\"",
".",
"format",
"(",
"message",
")",
")"
] | Manually starts timer with the message.
:param message: The display message. | [
"Manually",
"starts",
"timer",
"with",
"the",
"message",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/timer.py#L47-L54 | train |
dbarsam/python-vsgen | vsgen/util/timer.py | VSGTimer.stop | def stop(self, message):
"""
Manually stops timer with the message.
:param message: The display message.
"""
self._stop = time.clock()
VSGLogger.info("{0:<20} - Finished [{1}s]".format(message, self.pprint(self._stop - self._start))) | python | def stop(self, message):
"""
Manually stops timer with the message.
:param message: The display message.
"""
self._stop = time.clock()
VSGLogger.info("{0:<20} - Finished [{1}s]".format(message, self.pprint(self._stop - self._start))) | [
"def",
"stop",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"_stop",
"=",
"time",
".",
"clock",
"(",
")",
"VSGLogger",
".",
"info",
"(",
"\"{0:<20} - Finished [{1}s]\"",
".",
"format",
"(",
"message",
",",
"self",
".",
"pprint",
"(",
"self",
".",
"_stop",
"-",
"self",
".",
"_start",
")",
")",
")"
] | Manually stops timer with the message.
:param message: The display message. | [
"Manually",
"stops",
"timer",
"with",
"the",
"message",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/timer.py#L56-L63 | train |
Phyks/libbmc | libbmc/papers/identifiers.py | get_bibtex | def get_bibtex(identifier):
"""
Try to fetch BibTeX from a found identifier.
.. note::
Calls the functions in the respective identifiers module.
:param identifier: a tuple (type, identifier) with a valid type.
:returns: A BibTeX string or ``None`` if an error occurred.
# TODO: Should return a BiBTeX object?
"""
identifier_type, identifier_id = identifier
if identifier_type not in __valid_identifiers__:
return None
# Dynamically call the ``get_bibtex`` method from the associated module.
module = sys.modules.get("libbmc.%s" % (identifier_type,), None)
if module is None:
return None
return getattr(module, "get_bibtex")(identifier_id) | python | def get_bibtex(identifier):
"""
Try to fetch BibTeX from a found identifier.
.. note::
Calls the functions in the respective identifiers module.
:param identifier: a tuple (type, identifier) with a valid type.
:returns: A BibTeX string or ``None`` if an error occurred.
# TODO: Should return a BiBTeX object?
"""
identifier_type, identifier_id = identifier
if identifier_type not in __valid_identifiers__:
return None
# Dynamically call the ``get_bibtex`` method from the associated module.
module = sys.modules.get("libbmc.%s" % (identifier_type,), None)
if module is None:
return None
return getattr(module, "get_bibtex")(identifier_id) | [
"def",
"get_bibtex",
"(",
"identifier",
")",
":",
"identifier_type",
",",
"identifier_id",
"=",
"identifier",
"if",
"identifier_type",
"not",
"in",
"__valid_identifiers__",
":",
"return",
"None",
"# Dynamically call the ``get_bibtex`` method from the associated module.",
"module",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"\"libbmc.%s\"",
"%",
"(",
"identifier_type",
",",
")",
",",
"None",
")",
"if",
"module",
"is",
"None",
":",
"return",
"None",
"return",
"getattr",
"(",
"module",
",",
"\"get_bibtex\"",
")",
"(",
"identifier_id",
")"
] | Try to fetch BibTeX from a found identifier.
.. note::
Calls the functions in the respective identifiers module.
:param identifier: a tuple (type, identifier) with a valid type.
:returns: A BibTeX string or ``None`` if an error occurred.
# TODO: Should return a BiBTeX object? | [
"Try",
"to",
"fetch",
"BibTeX",
"from",
"a",
"found",
"identifier",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/papers/identifiers.py#L72-L92 | train |
SandstoneHPC/sandstone-ide | sandstone/lib/handlers/rest.py | JSONHandler.initialize | def initialize(self,*args,**kwargs):
"""
Only try to parse as JSON if the JSON content type
header is set.
"""
super(JSONHandler,self).initialize(*args,**kwargs)
content_type = self.request.headers.get('Content-Type', '')
if 'application/json' in content_type.lower():
self._parse_json_body_arguments() | python | def initialize(self,*args,**kwargs):
"""
Only try to parse as JSON if the JSON content type
header is set.
"""
super(JSONHandler,self).initialize(*args,**kwargs)
content_type = self.request.headers.get('Content-Type', '')
if 'application/json' in content_type.lower():
self._parse_json_body_arguments() | [
"def",
"initialize",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"JSONHandler",
",",
"self",
")",
".",
"initialize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"content_type",
"=",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
",",
"''",
")",
"if",
"'application/json'",
"in",
"content_type",
".",
"lower",
"(",
")",
":",
"self",
".",
"_parse_json_body_arguments",
"(",
")"
] | Only try to parse as JSON if the JSON content type
header is set. | [
"Only",
"try",
"to",
"parse",
"as",
"JSON",
"if",
"the",
"JSON",
"content",
"type",
"header",
"is",
"set",
"."
] | 7a47947fb07281c3e3018042863dc67e7e56dc04 | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/handlers/rest.py#L17-L25 | train |
Phyks/libbmc | libbmc/citations/bibtex.py | get_plaintext_citations | def get_plaintext_citations(bibtex):
"""
Parse a BibTeX file to get a clean list of plaintext citations.
:param bibtex: Either the path to the BibTeX file or the content of a \
BibTeX file.
:returns: A list of cleaned plaintext citations.
"""
parser = BibTexParser()
parser.customization = convert_to_unicode
# Load the BibTeX
if os.path.isfile(bibtex):
with open(bibtex) as fh:
bib_database = bibtexparser.load(fh, parser=parser)
else:
bib_database = bibtexparser.loads(bibtex, parser=parser)
# Convert bibentries to plaintext
bibentries = [bibentry_as_plaintext(bibentry)
for bibentry in bib_database.entries]
# Return them
return bibentries | python | def get_plaintext_citations(bibtex):
"""
Parse a BibTeX file to get a clean list of plaintext citations.
:param bibtex: Either the path to the BibTeX file or the content of a \
BibTeX file.
:returns: A list of cleaned plaintext citations.
"""
parser = BibTexParser()
parser.customization = convert_to_unicode
# Load the BibTeX
if os.path.isfile(bibtex):
with open(bibtex) as fh:
bib_database = bibtexparser.load(fh, parser=parser)
else:
bib_database = bibtexparser.loads(bibtex, parser=parser)
# Convert bibentries to plaintext
bibentries = [bibentry_as_plaintext(bibentry)
for bibentry in bib_database.entries]
# Return them
return bibentries | [
"def",
"get_plaintext_citations",
"(",
"bibtex",
")",
":",
"parser",
"=",
"BibTexParser",
"(",
")",
"parser",
".",
"customization",
"=",
"convert_to_unicode",
"# Load the BibTeX",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"bibtex",
")",
":",
"with",
"open",
"(",
"bibtex",
")",
"as",
"fh",
":",
"bib_database",
"=",
"bibtexparser",
".",
"load",
"(",
"fh",
",",
"parser",
"=",
"parser",
")",
"else",
":",
"bib_database",
"=",
"bibtexparser",
".",
"loads",
"(",
"bibtex",
",",
"parser",
"=",
"parser",
")",
"# Convert bibentries to plaintext",
"bibentries",
"=",
"[",
"bibentry_as_plaintext",
"(",
"bibentry",
")",
"for",
"bibentry",
"in",
"bib_database",
".",
"entries",
"]",
"# Return them",
"return",
"bibentries"
] | Parse a BibTeX file to get a clean list of plaintext citations.
:param bibtex: Either the path to the BibTeX file or the content of a \
BibTeX file.
:returns: A list of cleaned plaintext citations. | [
"Parse",
"a",
"BibTeX",
"file",
"to",
"get",
"a",
"clean",
"list",
"of",
"plaintext",
"citations",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/citations/bibtex.py#L36-L56 | train |
suurjaak/InputScope | inputscope/conf.py | init | def init(filename=ConfigPath):
"""Loads INI configuration into this module's attributes."""
section, parts = "DEFAULT", filename.rsplit(":", 1)
if len(parts) > 1 and os.path.isfile(parts[0]): filename, section = parts
if not os.path.isfile(filename): return
vardict, parser = globals(), configparser.RawConfigParser()
parser.optionxform = str # Force case-sensitivity on names
try:
def parse_value(raw):
try: return json.loads(raw) # Try to interpret as JSON
except ValueError: return raw # JSON failed, fall back to raw
txt = open(filename).read() # Add DEFAULT section if none present
if not re.search("\\[\\w+\\]", txt): txt = "[DEFAULT]\n" + txt
parser.readfp(StringIO.StringIO(txt), filename)
for k, v in parser.items(section): vardict[k] = parse_value(v)
except Exception:
logging.warn("Error reading config from %s.", filename, exc_info=True) | python | def init(filename=ConfigPath):
"""Loads INI configuration into this module's attributes."""
section, parts = "DEFAULT", filename.rsplit(":", 1)
if len(parts) > 1 and os.path.isfile(parts[0]): filename, section = parts
if not os.path.isfile(filename): return
vardict, parser = globals(), configparser.RawConfigParser()
parser.optionxform = str # Force case-sensitivity on names
try:
def parse_value(raw):
try: return json.loads(raw) # Try to interpret as JSON
except ValueError: return raw # JSON failed, fall back to raw
txt = open(filename).read() # Add DEFAULT section if none present
if not re.search("\\[\\w+\\]", txt): txt = "[DEFAULT]\n" + txt
parser.readfp(StringIO.StringIO(txt), filename)
for k, v in parser.items(section): vardict[k] = parse_value(v)
except Exception:
logging.warn("Error reading config from %s.", filename, exc_info=True) | [
"def",
"init",
"(",
"filename",
"=",
"ConfigPath",
")",
":",
"section",
",",
"parts",
"=",
"\"DEFAULT\"",
",",
"filename",
".",
"rsplit",
"(",
"\":\"",
",",
"1",
")",
"if",
"len",
"(",
"parts",
")",
">",
"1",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"parts",
"[",
"0",
"]",
")",
":",
"filename",
",",
"section",
"=",
"parts",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"return",
"vardict",
",",
"parser",
"=",
"globals",
"(",
")",
",",
"configparser",
".",
"RawConfigParser",
"(",
")",
"parser",
".",
"optionxform",
"=",
"str",
"# Force case-sensitivity on names\r",
"try",
":",
"def",
"parse_value",
"(",
"raw",
")",
":",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"raw",
")",
"# Try to interpret as JSON\r",
"except",
"ValueError",
":",
"return",
"raw",
"# JSON failed, fall back to raw\r",
"txt",
"=",
"open",
"(",
"filename",
")",
".",
"read",
"(",
")",
"# Add DEFAULT section if none present\r",
"if",
"not",
"re",
".",
"search",
"(",
"\"\\\\[\\\\w+\\\\]\"",
",",
"txt",
")",
":",
"txt",
"=",
"\"[DEFAULT]\\n\"",
"+",
"txt",
"parser",
".",
"readfp",
"(",
"StringIO",
".",
"StringIO",
"(",
"txt",
")",
",",
"filename",
")",
"for",
"k",
",",
"v",
"in",
"parser",
".",
"items",
"(",
"section",
")",
":",
"vardict",
"[",
"k",
"]",
"=",
"parse_value",
"(",
"v",
")",
"except",
"Exception",
":",
"logging",
".",
"warn",
"(",
"\"Error reading config from %s.\"",
",",
"filename",
",",
"exc_info",
"=",
"True",
")"
] | Loads INI configuration into this module's attributes. | [
"Loads",
"INI",
"configuration",
"into",
"this",
"module",
"s",
"attributes",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/conf.py#L253-L270 | train |
suurjaak/InputScope | inputscope/conf.py | save | def save(filename=ConfigPath):
"""Saves this module's changed attributes to INI configuration."""
default_values = defaults()
parser = configparser.RawConfigParser()
parser.optionxform = str # Force case-sensitivity on names
try:
save_types = basestring, int, float, tuple, list, dict, type(None)
for k, v in sorted(globals().items()):
if not isinstance(v, save_types) or k.startswith("_") \
or default_values.get(k, parser) == v: continue # for k, v
try: parser.set("DEFAULT", k, json.dumps(v))
except Exception: pass
if parser.defaults():
with open(filename, "wb") as f:
f.write("# %s %s configuration written on %s.\n" % (Title, Version,
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
parser.write(f)
else: # Nothing to write: delete configuration file
try: os.unlink(filename)
except Exception: pass
except Exception:
logging.warn("Error writing config to %s.", filename, exc_info=True) | python | def save(filename=ConfigPath):
"""Saves this module's changed attributes to INI configuration."""
default_values = defaults()
parser = configparser.RawConfigParser()
parser.optionxform = str # Force case-sensitivity on names
try:
save_types = basestring, int, float, tuple, list, dict, type(None)
for k, v in sorted(globals().items()):
if not isinstance(v, save_types) or k.startswith("_") \
or default_values.get(k, parser) == v: continue # for k, v
try: parser.set("DEFAULT", k, json.dumps(v))
except Exception: pass
if parser.defaults():
with open(filename, "wb") as f:
f.write("# %s %s configuration written on %s.\n" % (Title, Version,
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
parser.write(f)
else: # Nothing to write: delete configuration file
try: os.unlink(filename)
except Exception: pass
except Exception:
logging.warn("Error writing config to %s.", filename, exc_info=True) | [
"def",
"save",
"(",
"filename",
"=",
"ConfigPath",
")",
":",
"default_values",
"=",
"defaults",
"(",
")",
"parser",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"parser",
".",
"optionxform",
"=",
"str",
"# Force case-sensitivity on names\r",
"try",
":",
"save_types",
"=",
"basestring",
",",
"int",
",",
"float",
",",
"tuple",
",",
"list",
",",
"dict",
",",
"type",
"(",
"None",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"globals",
"(",
")",
".",
"items",
"(",
")",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"save_types",
")",
"or",
"k",
".",
"startswith",
"(",
"\"_\"",
")",
"or",
"default_values",
".",
"get",
"(",
"k",
",",
"parser",
")",
"==",
"v",
":",
"continue",
"# for k, v\r",
"try",
":",
"parser",
".",
"set",
"(",
"\"DEFAULT\"",
",",
"k",
",",
"json",
".",
"dumps",
"(",
"v",
")",
")",
"except",
"Exception",
":",
"pass",
"if",
"parser",
".",
"defaults",
"(",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"\"# %s %s configuration written on %s.\\n\"",
"%",
"(",
"Title",
",",
"Version",
",",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y-%m-%d %H:%M:%S\"",
")",
")",
")",
"parser",
".",
"write",
"(",
"f",
")",
"else",
":",
"# Nothing to write: delete configuration file\r",
"try",
":",
"os",
".",
"unlink",
"(",
"filename",
")",
"except",
"Exception",
":",
"pass",
"except",
"Exception",
":",
"logging",
".",
"warn",
"(",
"\"Error writing config to %s.\"",
",",
"filename",
",",
"exc_info",
"=",
"True",
")"
] | Saves this module's changed attributes to INI configuration. | [
"Saves",
"this",
"module",
"s",
"changed",
"attributes",
"to",
"INI",
"configuration",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/conf.py#L273-L294 | train |
Subsets and Splits