id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27,500 | cjdrake/pyeda | pyeda/boolalg/expr.py | Expression.encode_inputs | def encode_inputs(self):
"""Return a compact encoding for input variables."""
litmap = dict()
nvars = 0
for i, v in enumerate(self.inputs, start=1):
litmap[v] = i
litmap[~v] = -i
litmap[i] = v
litmap[-i] = ~v
nvars += 1
return litmap, nvars | python | def encode_inputs(self):
litmap = dict()
nvars = 0
for i, v in enumerate(self.inputs, start=1):
litmap[v] = i
litmap[~v] = -i
litmap[i] = v
litmap[-i] = ~v
nvars += 1
return litmap, nvars | [
"def",
"encode_inputs",
"(",
"self",
")",
":",
"litmap",
"=",
"dict",
"(",
")",
"nvars",
"=",
"0",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"self",
".",
"inputs",
",",
"start",
"=",
"1",
")",
":",
"litmap",
"[",
"v",
"]",
"=",
"i",
"litmap... | Return a compact encoding for input variables. | [
"Return",
"a",
"compact",
"encoding",
"for",
"input",
"variables",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L915-L925 |
27,501 | cjdrake/pyeda | pyeda/boolalg/expr.py | Expression.tseitin | def tseitin(self, auxvarname='aux'):
"""Convert the expression to Tseitin's encoding."""
if self.is_cnf():
return self
_, constraints = _tseitin(self.to_nnf(), auxvarname)
fst = constraints[-1][1]
rst = [Equal(v, ex).to_cnf() for v, ex in constraints[:-1]]
return And(fst, *rst) | python | def tseitin(self, auxvarname='aux'):
if self.is_cnf():
return self
_, constraints = _tseitin(self.to_nnf(), auxvarname)
fst = constraints[-1][1]
rst = [Equal(v, ex).to_cnf() for v, ex in constraints[:-1]]
return And(fst, *rst) | [
"def",
"tseitin",
"(",
"self",
",",
"auxvarname",
"=",
"'aux'",
")",
":",
"if",
"self",
".",
"is_cnf",
"(",
")",
":",
"return",
"self",
"_",
",",
"constraints",
"=",
"_tseitin",
"(",
"self",
".",
"to_nnf",
"(",
")",
",",
"auxvarname",
")",
"fst",
"... | Convert the expression to Tseitin's encoding. | [
"Convert",
"the",
"expression",
"to",
"Tseitin",
"s",
"encoding",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L941-L949 |
27,502 | cjdrake/pyeda | pyeda/boolalg/expr.py | Expression.equivalent | def equivalent(self, other):
"""Return True if this expression is equivalent to other."""
f = Xor(self, self.box(other))
return f.satisfy_one() is None | python | def equivalent(self, other):
f = Xor(self, self.box(other))
return f.satisfy_one() is None | [
"def",
"equivalent",
"(",
"self",
",",
"other",
")",
":",
"f",
"=",
"Xor",
"(",
"self",
",",
"self",
".",
"box",
"(",
"other",
")",
")",
"return",
"f",
".",
"satisfy_one",
"(",
")",
"is",
"None"
] | Return True if this expression is equivalent to other. | [
"Return",
"True",
"if",
"this",
"expression",
"is",
"equivalent",
"to",
"other",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L951-L954 |
27,503 | cjdrake/pyeda | pyeda/boolalg/expr.py | NormalForm.reduce | def reduce(self):
"""Reduce to a canonical form."""
support = frozenset(range(1, self.nvars+1))
new_clauses = set()
for clause in self.clauses:
vs = list(support - {abs(uniqid) for uniqid in clause})
if vs:
for num in range(1 << len(vs)):
new_part = {v if bit_on(num, i) else ~v
for i, v in enumerate(vs)}
new_clauses.add(clause | new_part)
else:
new_clauses.add(clause)
return self.__class__(self.nvars, new_clauses) | python | def reduce(self):
support = frozenset(range(1, self.nvars+1))
new_clauses = set()
for clause in self.clauses:
vs = list(support - {abs(uniqid) for uniqid in clause})
if vs:
for num in range(1 << len(vs)):
new_part = {v if bit_on(num, i) else ~v
for i, v in enumerate(vs)}
new_clauses.add(clause | new_part)
else:
new_clauses.add(clause)
return self.__class__(self.nvars, new_clauses) | [
"def",
"reduce",
"(",
"self",
")",
":",
"support",
"=",
"frozenset",
"(",
"range",
"(",
"1",
",",
"self",
".",
"nvars",
"+",
"1",
")",
")",
"new_clauses",
"=",
"set",
"(",
")",
"for",
"clause",
"in",
"self",
".",
"clauses",
":",
"vs",
"=",
"list"... | Reduce to a canonical form. | [
"Reduce",
"to",
"a",
"canonical",
"form",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1331-L1344 |
27,504 | cjdrake/pyeda | pyeda/boolalg/expr.py | DisjNormalForm.decode | def decode(self, litmap):
"""Convert the DNF to an expression."""
return Or(*[And(*[litmap[idx] for idx in clause])
for clause in self.clauses]) | python | def decode(self, litmap):
return Or(*[And(*[litmap[idx] for idx in clause])
for clause in self.clauses]) | [
"def",
"decode",
"(",
"self",
",",
"litmap",
")",
":",
"return",
"Or",
"(",
"*",
"[",
"And",
"(",
"*",
"[",
"litmap",
"[",
"idx",
"]",
"for",
"idx",
"in",
"clause",
"]",
")",
"for",
"clause",
"in",
"self",
".",
"clauses",
"]",
")"
] | Convert the DNF to an expression. | [
"Convert",
"the",
"DNF",
"to",
"an",
"expression",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1350-L1353 |
27,505 | cjdrake/pyeda | pyeda/boolalg/expr.py | ConjNormalForm.satisfy_one | def satisfy_one(self, assumptions=None, **params):
"""
If the input CNF is satisfiable, return a satisfying input point.
A contradiction will return None.
"""
verbosity = params.get('verbosity', 0)
default_phase = params.get('default_phase', 2)
propagation_limit = params.get('propagation_limit', -1)
decision_limit = params.get('decision_limit', -1)
seed = params.get('seed', 1)
return picosat.satisfy_one(self.nvars, self.clauses, assumptions,
verbosity, default_phase, propagation_limit,
decision_limit, seed) | python | def satisfy_one(self, assumptions=None, **params):
verbosity = params.get('verbosity', 0)
default_phase = params.get('default_phase', 2)
propagation_limit = params.get('propagation_limit', -1)
decision_limit = params.get('decision_limit', -1)
seed = params.get('seed', 1)
return picosat.satisfy_one(self.nvars, self.clauses, assumptions,
verbosity, default_phase, propagation_limit,
decision_limit, seed) | [
"def",
"satisfy_one",
"(",
"self",
",",
"assumptions",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"verbosity",
"=",
"params",
".",
"get",
"(",
"'verbosity'",
",",
"0",
")",
"default_phase",
"=",
"params",
".",
"get",
"(",
"'default_phase'",
",",
"... | If the input CNF is satisfiable, return a satisfying input point.
A contradiction will return None. | [
"If",
"the",
"input",
"CNF",
"is",
"satisfiable",
"return",
"a",
"satisfying",
"input",
"point",
".",
"A",
"contradiction",
"will",
"return",
"None",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1372-L1384 |
27,506 | cjdrake/pyeda | pyeda/boolalg/expr.py | ConjNormalForm.satisfy_all | def satisfy_all(self, **params):
"""Iterate through all satisfying input points."""
verbosity = params.get('verbosity', 0)
default_phase = params.get('default_phase', 2)
propagation_limit = params.get('propagation_limit', -1)
decision_limit = params.get('decision_limit', -1)
seed = params.get('seed', 1)
yield from picosat.satisfy_all(self.nvars, self.clauses, verbosity,
default_phase, propagation_limit,
decision_limit, seed) | python | def satisfy_all(self, **params):
verbosity = params.get('verbosity', 0)
default_phase = params.get('default_phase', 2)
propagation_limit = params.get('propagation_limit', -1)
decision_limit = params.get('decision_limit', -1)
seed = params.get('seed', 1)
yield from picosat.satisfy_all(self.nvars, self.clauses, verbosity,
default_phase, propagation_limit,
decision_limit, seed) | [
"def",
"satisfy_all",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"verbosity",
"=",
"params",
".",
"get",
"(",
"'verbosity'",
",",
"0",
")",
"default_phase",
"=",
"params",
".",
"get",
"(",
"'default_phase'",
",",
"2",
")",
"propagation_limit",
"=",
... | Iterate through all satisfying input points. | [
"Iterate",
"through",
"all",
"satisfying",
"input",
"points",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1386-L1395 |
27,507 | cjdrake/pyeda | pyeda/boolalg/expr.py | ConjNormalForm.soln2point | def soln2point(soln, litmap):
"""Convert a solution vector to a point."""
return {litmap[i]: int(val > 0)
for i, val in enumerate(soln, start=1)} | python | def soln2point(soln, litmap):
return {litmap[i]: int(val > 0)
for i, val in enumerate(soln, start=1)} | [
"def",
"soln2point",
"(",
"soln",
",",
"litmap",
")",
":",
"return",
"{",
"litmap",
"[",
"i",
"]",
":",
"int",
"(",
"val",
">",
"0",
")",
"for",
"i",
",",
"val",
"in",
"enumerate",
"(",
"soln",
",",
"start",
"=",
"1",
")",
"}"
] | Convert a solution vector to a point. | [
"Convert",
"a",
"solution",
"vector",
"to",
"a",
"point",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L1398-L1401 |
27,508 | cjdrake/pyeda | pyeda/boolalg/minimization.py | _cover2exprs | def _cover2exprs(inputs, noutputs, cover):
"""Convert a cover to a tuple of Expression instances."""
fs = list()
for i in range(noutputs):
terms = list()
for invec, outvec in cover:
if outvec[i]:
term = list()
for j, v in enumerate(inputs):
if invec[j] == 1:
term.append(~v)
elif invec[j] == 2:
term.append(v)
terms.append(term)
fs.append(Or(*[And(*term) for term in terms]))
return tuple(fs) | python | def _cover2exprs(inputs, noutputs, cover):
fs = list()
for i in range(noutputs):
terms = list()
for invec, outvec in cover:
if outvec[i]:
term = list()
for j, v in enumerate(inputs):
if invec[j] == 1:
term.append(~v)
elif invec[j] == 2:
term.append(v)
terms.append(term)
fs.append(Or(*[And(*term) for term in terms]))
return tuple(fs) | [
"def",
"_cover2exprs",
"(",
"inputs",
",",
"noutputs",
",",
"cover",
")",
":",
"fs",
"=",
"list",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"noutputs",
")",
":",
"terms",
"=",
"list",
"(",
")",
"for",
"invec",
",",
"outvec",
"in",
"cover",
":",
"... | Convert a cover to a tuple of Expression instances. | [
"Convert",
"a",
"cover",
"to",
"a",
"tuple",
"of",
"Expression",
"instances",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/minimization.py#L156-L172 |
27,509 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | fcat | def fcat(*fs):
"""Concatenate a sequence of farrays.
The variadic *fs* input is a homogeneous sequence of functions or arrays.
"""
items = list()
for f in fs:
if isinstance(f, boolfunc.Function):
items.append(f)
elif isinstance(f, farray):
items.extend(f.flat)
else:
raise TypeError("expected Function or farray")
return farray(items) | python | def fcat(*fs):
items = list()
for f in fs:
if isinstance(f, boolfunc.Function):
items.append(f)
elif isinstance(f, farray):
items.extend(f.flat)
else:
raise TypeError("expected Function or farray")
return farray(items) | [
"def",
"fcat",
"(",
"*",
"fs",
")",
":",
"items",
"=",
"list",
"(",
")",
"for",
"f",
"in",
"fs",
":",
"if",
"isinstance",
"(",
"f",
",",
"boolfunc",
".",
"Function",
")",
":",
"items",
".",
"append",
"(",
"f",
")",
"elif",
"isinstance",
"(",
"f... | Concatenate a sequence of farrays.
The variadic *fs* input is a homogeneous sequence of functions or arrays. | [
"Concatenate",
"a",
"sequence",
"of",
"farrays",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L395-L408 |
27,510 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _dims2shape | def _dims2shape(*dims):
"""Convert input dimensions to a shape."""
if not dims:
raise ValueError("expected at least one dimension spec")
shape = list()
for dim in dims:
if isinstance(dim, int):
dim = (0, dim)
if isinstance(dim, tuple) and len(dim) == 2:
if dim[0] < 0:
raise ValueError("expected low dimension to be >= 0")
if dim[1] < 0:
raise ValueError("expected high dimension to be >= 0")
if dim[0] > dim[1]:
raise ValueError("expected low <= high dimensions")
start, stop = dim
else:
raise TypeError("expected dimension to be int or (int, int)")
shape.append((start, stop))
return tuple(shape) | python | def _dims2shape(*dims):
if not dims:
raise ValueError("expected at least one dimension spec")
shape = list()
for dim in dims:
if isinstance(dim, int):
dim = (0, dim)
if isinstance(dim, tuple) and len(dim) == 2:
if dim[0] < 0:
raise ValueError("expected low dimension to be >= 0")
if dim[1] < 0:
raise ValueError("expected high dimension to be >= 0")
if dim[0] > dim[1]:
raise ValueError("expected low <= high dimensions")
start, stop = dim
else:
raise TypeError("expected dimension to be int or (int, int)")
shape.append((start, stop))
return tuple(shape) | [
"def",
"_dims2shape",
"(",
"*",
"dims",
")",
":",
"if",
"not",
"dims",
":",
"raise",
"ValueError",
"(",
"\"expected at least one dimension spec\"",
")",
"shape",
"=",
"list",
"(",
")",
"for",
"dim",
"in",
"dims",
":",
"if",
"isinstance",
"(",
"dim",
",",
... | Convert input dimensions to a shape. | [
"Convert",
"input",
"dimensions",
"to",
"a",
"shape",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L926-L945 |
27,511 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _volume | def _volume(shape):
"""Return the volume of a shape."""
prod = 1
for start, stop in shape:
prod *= stop - start
return prod | python | def _volume(shape):
prod = 1
for start, stop in shape:
prod *= stop - start
return prod | [
"def",
"_volume",
"(",
"shape",
")",
":",
"prod",
"=",
"1",
"for",
"start",
",",
"stop",
"in",
"shape",
":",
"prod",
"*=",
"stop",
"-",
"start",
"return",
"prod"
] | Return the volume of a shape. | [
"Return",
"the",
"volume",
"of",
"a",
"shape",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L948-L953 |
27,512 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _zeros | def _zeros(ftype, *dims):
"""Return a new farray filled with zeros."""
shape = _dims2shape(*dims)
objs = [ftype.box(0) for _ in range(_volume(shape))]
return farray(objs, shape, ftype) | python | def _zeros(ftype, *dims):
shape = _dims2shape(*dims)
objs = [ftype.box(0) for _ in range(_volume(shape))]
return farray(objs, shape, ftype) | [
"def",
"_zeros",
"(",
"ftype",
",",
"*",
"dims",
")",
":",
"shape",
"=",
"_dims2shape",
"(",
"*",
"dims",
")",
"objs",
"=",
"[",
"ftype",
".",
"box",
"(",
"0",
")",
"for",
"_",
"in",
"range",
"(",
"_volume",
"(",
"shape",
")",
")",
"]",
"return... | Return a new farray filled with zeros. | [
"Return",
"a",
"new",
"farray",
"filled",
"with",
"zeros",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L956-L960 |
27,513 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _vars | def _vars(ftype, name, *dims):
"""Return a new farray filled with Boolean variables."""
shape = _dims2shape(*dims)
objs = list()
for indices in itertools.product(*[range(i, j) for i, j in shape]):
objs.append(_VAR[ftype](name, indices))
return farray(objs, shape, ftype) | python | def _vars(ftype, name, *dims):
shape = _dims2shape(*dims)
objs = list()
for indices in itertools.product(*[range(i, j) for i, j in shape]):
objs.append(_VAR[ftype](name, indices))
return farray(objs, shape, ftype) | [
"def",
"_vars",
"(",
"ftype",
",",
"name",
",",
"*",
"dims",
")",
":",
"shape",
"=",
"_dims2shape",
"(",
"*",
"dims",
")",
"objs",
"=",
"list",
"(",
")",
"for",
"indices",
"in",
"itertools",
".",
"product",
"(",
"*",
"[",
"range",
"(",
"i",
",",
... | Return a new farray filled with Boolean variables. | [
"Return",
"a",
"new",
"farray",
"filled",
"with",
"Boolean",
"variables",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L970-L976 |
27,514 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _uint2objs | def _uint2objs(ftype, num, length=None):
"""Convert an unsigned integer to a list of constant expressions."""
if num == 0:
objs = [ftype.box(0)]
else:
_num = num
objs = list()
while _num != 0:
objs.append(ftype.box(_num & 1))
_num >>= 1
if length:
if length < len(objs):
fstr = "overflow: num = {} requires length >= {}, got length = {}"
raise ValueError(fstr.format(num, len(objs), length))
else:
while len(objs) < length:
objs.append(ftype.box(0))
return objs | python | def _uint2objs(ftype, num, length=None):
if num == 0:
objs = [ftype.box(0)]
else:
_num = num
objs = list()
while _num != 0:
objs.append(ftype.box(_num & 1))
_num >>= 1
if length:
if length < len(objs):
fstr = "overflow: num = {} requires length >= {}, got length = {}"
raise ValueError(fstr.format(num, len(objs), length))
else:
while len(objs) < length:
objs.append(ftype.box(0))
return objs | [
"def",
"_uint2objs",
"(",
"ftype",
",",
"num",
",",
"length",
"=",
"None",
")",
":",
"if",
"num",
"==",
"0",
":",
"objs",
"=",
"[",
"ftype",
".",
"box",
"(",
"0",
")",
"]",
"else",
":",
"_num",
"=",
"num",
"objs",
"=",
"list",
"(",
")",
"whil... | Convert an unsigned integer to a list of constant expressions. | [
"Convert",
"an",
"unsigned",
"integer",
"to",
"a",
"list",
"of",
"constant",
"expressions",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L979-L998 |
27,515 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _uint2farray | def _uint2farray(ftype, num, length=None):
"""Convert an unsigned integer to an farray."""
if num < 0:
raise ValueError("expected num >= 0")
else:
objs = _uint2objs(ftype, num, length)
return farray(objs) | python | def _uint2farray(ftype, num, length=None):
if num < 0:
raise ValueError("expected num >= 0")
else:
objs = _uint2objs(ftype, num, length)
return farray(objs) | [
"def",
"_uint2farray",
"(",
"ftype",
",",
"num",
",",
"length",
"=",
"None",
")",
":",
"if",
"num",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"expected num >= 0\"",
")",
"else",
":",
"objs",
"=",
"_uint2objs",
"(",
"ftype",
",",
"num",
",",
"length"... | Convert an unsigned integer to an farray. | [
"Convert",
"an",
"unsigned",
"integer",
"to",
"an",
"farray",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1001-L1007 |
27,516 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _int2farray | def _int2farray(ftype, num, length=None):
"""Convert a signed integer to an farray."""
if num < 0:
req_length = clog2(abs(num)) + 1
objs = _uint2objs(ftype, 2**req_length + num)
else:
req_length = clog2(num + 1) + 1
objs = _uint2objs(ftype, num, req_length)
if length:
if length < req_length:
fstr = "overflow: num = {} requires length >= {}, got length = {}"
raise ValueError(fstr.format(num, req_length, length))
else:
sign = objs[-1]
objs += [sign] * (length - req_length)
return farray(objs) | python | def _int2farray(ftype, num, length=None):
if num < 0:
req_length = clog2(abs(num)) + 1
objs = _uint2objs(ftype, 2**req_length + num)
else:
req_length = clog2(num + 1) + 1
objs = _uint2objs(ftype, num, req_length)
if length:
if length < req_length:
fstr = "overflow: num = {} requires length >= {}, got length = {}"
raise ValueError(fstr.format(num, req_length, length))
else:
sign = objs[-1]
objs += [sign] * (length - req_length)
return farray(objs) | [
"def",
"_int2farray",
"(",
"ftype",
",",
"num",
",",
"length",
"=",
"None",
")",
":",
"if",
"num",
"<",
"0",
":",
"req_length",
"=",
"clog2",
"(",
"abs",
"(",
"num",
")",
")",
"+",
"1",
"objs",
"=",
"_uint2objs",
"(",
"ftype",
",",
"2",
"**",
"... | Convert a signed integer to an farray. | [
"Convert",
"a",
"signed",
"integer",
"to",
"an",
"farray",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1010-L1027 |
27,517 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _itemize | def _itemize(objs):
"""Recursive helper function for farray."""
if not isinstance(objs, collections.Sequence):
raise TypeError("expected a sequence of Function")
isseq = [isinstance(obj, collections.Sequence) for obj in objs]
if not any(isseq):
ftype = None
for obj in objs:
if ftype is None:
if isinstance(obj, BinaryDecisionDiagram):
ftype = BinaryDecisionDiagram
elif isinstance(obj, Expression):
ftype = Expression
elif isinstance(obj, TruthTable):
ftype = TruthTable
else:
raise TypeError("expected valid Function inputs")
elif not isinstance(obj, ftype):
raise ValueError("expected uniform Function types")
return list(objs), ((0, len(objs)), ), ftype
elif all(isseq):
items = list()
shape = None
ftype = None
for obj in objs:
_items, _shape, _ftype = _itemize(obj)
if shape is None:
shape = _shape
elif shape != _shape:
raise ValueError("expected uniform farray dimensions")
if ftype is None:
ftype = _ftype
elif ftype != _ftype:
raise ValueError("expected uniform Function types")
items += _items
shape = ((0, len(objs)), ) + shape
return items, shape, ftype
else:
raise ValueError("expected uniform farray dimensions") | python | def _itemize(objs):
if not isinstance(objs, collections.Sequence):
raise TypeError("expected a sequence of Function")
isseq = [isinstance(obj, collections.Sequence) for obj in objs]
if not any(isseq):
ftype = None
for obj in objs:
if ftype is None:
if isinstance(obj, BinaryDecisionDiagram):
ftype = BinaryDecisionDiagram
elif isinstance(obj, Expression):
ftype = Expression
elif isinstance(obj, TruthTable):
ftype = TruthTable
else:
raise TypeError("expected valid Function inputs")
elif not isinstance(obj, ftype):
raise ValueError("expected uniform Function types")
return list(objs), ((0, len(objs)), ), ftype
elif all(isseq):
items = list()
shape = None
ftype = None
for obj in objs:
_items, _shape, _ftype = _itemize(obj)
if shape is None:
shape = _shape
elif shape != _shape:
raise ValueError("expected uniform farray dimensions")
if ftype is None:
ftype = _ftype
elif ftype != _ftype:
raise ValueError("expected uniform Function types")
items += _items
shape = ((0, len(objs)), ) + shape
return items, shape, ftype
else:
raise ValueError("expected uniform farray dimensions") | [
"def",
"_itemize",
"(",
"objs",
")",
":",
"if",
"not",
"isinstance",
"(",
"objs",
",",
"collections",
".",
"Sequence",
")",
":",
"raise",
"TypeError",
"(",
"\"expected a sequence of Function\"",
")",
"isseq",
"=",
"[",
"isinstance",
"(",
"obj",
",",
"collect... | Recursive helper function for farray. | [
"Recursive",
"helper",
"function",
"for",
"farray",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1030-L1069 |
27,518 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _check_shape | def _check_shape(shape):
"""Verify that a shape has the right format."""
if isinstance(shape, tuple):
for dim in shape:
if (isinstance(dim, tuple) and len(dim) == 2 and
isinstance(dim[0], int) and isinstance(dim[1], int)):
if dim[0] < 0:
raise ValueError("expected low dimension to be >= 0")
if dim[1] < 0:
raise ValueError("expected high dimension to be >= 0")
if dim[0] > dim[1]:
raise ValueError("expected low <= high dimensions")
else:
raise TypeError("expected shape dimension to be (int, int)")
else:
raise TypeError("expected shape to be tuple of (int, int)") | python | def _check_shape(shape):
if isinstance(shape, tuple):
for dim in shape:
if (isinstance(dim, tuple) and len(dim) == 2 and
isinstance(dim[0], int) and isinstance(dim[1], int)):
if dim[0] < 0:
raise ValueError("expected low dimension to be >= 0")
if dim[1] < 0:
raise ValueError("expected high dimension to be >= 0")
if dim[0] > dim[1]:
raise ValueError("expected low <= high dimensions")
else:
raise TypeError("expected shape dimension to be (int, int)")
else:
raise TypeError("expected shape to be tuple of (int, int)") | [
"def",
"_check_shape",
"(",
"shape",
")",
":",
"if",
"isinstance",
"(",
"shape",
",",
"tuple",
")",
":",
"for",
"dim",
"in",
"shape",
":",
"if",
"(",
"isinstance",
"(",
"dim",
",",
"tuple",
")",
"and",
"len",
"(",
"dim",
")",
"==",
"2",
"and",
"i... | Verify that a shape has the right format. | [
"Verify",
"that",
"a",
"shape",
"has",
"the",
"right",
"format",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1072-L1087 |
27,519 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _norm_index | def _norm_index(dim, index, start, stop):
"""Return an index normalized to an farray start index."""
length = stop - start
if -length <= index < 0:
normindex = index + length
elif start <= index < stop:
normindex = index - start
else:
fstr = "expected dim {} index in range [{}, {})"
raise IndexError(fstr.format(dim, start, stop))
return normindex | python | def _norm_index(dim, index, start, stop):
length = stop - start
if -length <= index < 0:
normindex = index + length
elif start <= index < stop:
normindex = index - start
else:
fstr = "expected dim {} index in range [{}, {})"
raise IndexError(fstr.format(dim, start, stop))
return normindex | [
"def",
"_norm_index",
"(",
"dim",
",",
"index",
",",
"start",
",",
"stop",
")",
":",
"length",
"=",
"stop",
"-",
"start",
"if",
"-",
"length",
"<=",
"index",
"<",
"0",
":",
"normindex",
"=",
"index",
"+",
"length",
"elif",
"start",
"<=",
"index",
"... | Return an index normalized to an farray start index. | [
"Return",
"an",
"index",
"normalized",
"to",
"an",
"farray",
"start",
"index",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1118-L1128 |
27,520 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _norm_slice | def _norm_slice(sl, start, stop):
"""Return a slice normalized to an farray start index."""
length = stop - start
if sl.start is None:
normstart = 0
else:
if sl.start < 0:
if sl.start < -length:
normstart = 0
else:
normstart = sl.start + length
else:
if sl.start > stop:
normstart = length
else:
normstart = sl.start - start
if sl.stop is None:
normstop = length
else:
if sl.stop < 0:
if sl.stop < -length:
normstop = 0
else:
normstop = sl.stop + length
else:
if sl.stop > stop:
normstop = length
else:
normstop = sl.stop - start
if normstop < normstart:
normstop = normstart
return slice(normstart, normstop) | python | def _norm_slice(sl, start, stop):
length = stop - start
if sl.start is None:
normstart = 0
else:
if sl.start < 0:
if sl.start < -length:
normstart = 0
else:
normstart = sl.start + length
else:
if sl.start > stop:
normstart = length
else:
normstart = sl.start - start
if sl.stop is None:
normstop = length
else:
if sl.stop < 0:
if sl.stop < -length:
normstop = 0
else:
normstop = sl.stop + length
else:
if sl.stop > stop:
normstop = length
else:
normstop = sl.stop - start
if normstop < normstart:
normstop = normstart
return slice(normstart, normstop) | [
"def",
"_norm_slice",
"(",
"sl",
",",
"start",
",",
"stop",
")",
":",
"length",
"=",
"stop",
"-",
"start",
"if",
"sl",
".",
"start",
"is",
"None",
":",
"normstart",
"=",
"0",
"else",
":",
"if",
"sl",
".",
"start",
"<",
"0",
":",
"if",
"sl",
"."... | Return a slice normalized to an farray start index. | [
"Return",
"a",
"slice",
"normalized",
"to",
"an",
"farray",
"start",
"index",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1131-L1162 |
27,521 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _filtdim | def _filtdim(items, shape, dim, nsl):
"""Return items, shape filtered by a dimension slice."""
normshape = tuple(stop - start for start, stop in shape)
nsl_type = type(nsl)
newitems = list()
# Number of groups
num = reduce(operator.mul, normshape[:dim+1])
# Size of each group
size = len(items) // num
# Size of the dimension
n = normshape[dim]
if nsl_type is int:
for i in range(num):
if i % n == nsl:
newitems += items[size*i:size*(i+1)]
# Collapse dimension
newshape = shape[:dim] + shape[dim+1:]
elif nsl_type is slice:
for i in range(num):
if nsl.start <= (i % n) < nsl.stop:
newitems += items[size*i:size*(i+1)]
# Reshape dimension
offset = shape[dim][0]
redim = (offset + nsl.start, offset + nsl.stop)
newshape = shape[:dim] + (redim, ) + shape[dim+1:]
# farray
else:
if nsl.size < clog2(n):
fstr = "expected dim {} select to have >= {} bits, got {}"
raise ValueError(fstr.format(dim, clog2(n), nsl.size))
groups = [list() for _ in range(n)]
for i in range(num):
groups[i % n] += items[size*i:size*(i+1)]
for muxins in zip(*groups):
it = boolfunc.iter_terms(nsl._items)
xs = [reduce(operator.and_, (muxin, ) + next(it))
for muxin in muxins]
newitems.append(reduce(operator.or_, xs))
# Collapse dimension
newshape = shape[:dim] + shape[dim+1:]
return newitems, newshape | python | def _filtdim(items, shape, dim, nsl):
normshape = tuple(stop - start for start, stop in shape)
nsl_type = type(nsl)
newitems = list()
# Number of groups
num = reduce(operator.mul, normshape[:dim+1])
# Size of each group
size = len(items) // num
# Size of the dimension
n = normshape[dim]
if nsl_type is int:
for i in range(num):
if i % n == nsl:
newitems += items[size*i:size*(i+1)]
# Collapse dimension
newshape = shape[:dim] + shape[dim+1:]
elif nsl_type is slice:
for i in range(num):
if nsl.start <= (i % n) < nsl.stop:
newitems += items[size*i:size*(i+1)]
# Reshape dimension
offset = shape[dim][0]
redim = (offset + nsl.start, offset + nsl.stop)
newshape = shape[:dim] + (redim, ) + shape[dim+1:]
# farray
else:
if nsl.size < clog2(n):
fstr = "expected dim {} select to have >= {} bits, got {}"
raise ValueError(fstr.format(dim, clog2(n), nsl.size))
groups = [list() for _ in range(n)]
for i in range(num):
groups[i % n] += items[size*i:size*(i+1)]
for muxins in zip(*groups):
it = boolfunc.iter_terms(nsl._items)
xs = [reduce(operator.and_, (muxin, ) + next(it))
for muxin in muxins]
newitems.append(reduce(operator.or_, xs))
# Collapse dimension
newshape = shape[:dim] + shape[dim+1:]
return newitems, newshape | [
"def",
"_filtdim",
"(",
"items",
",",
"shape",
",",
"dim",
",",
"nsl",
")",
":",
"normshape",
"=",
"tuple",
"(",
"stop",
"-",
"start",
"for",
"start",
",",
"stop",
"in",
"shape",
")",
"nsl_type",
"=",
"type",
"(",
"nsl",
")",
"newitems",
"=",
"list... | Return items, shape filtered by a dimension slice. | [
"Return",
"items",
"shape",
"filtered",
"by",
"a",
"dimension",
"slice",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1165-L1205 |
27,522 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | _iter_coords | def _iter_coords(nsls):
"""Iterate through all matching coordinates in a sequence of slices."""
# First convert all slices to ranges
ranges = list()
for nsl in nsls:
if isinstance(nsl, int):
ranges.append(range(nsl, nsl+1))
else:
ranges.append(range(nsl.start, nsl.stop))
# Iterate through all matching coordinates
yield from itertools.product(*ranges) | python | def _iter_coords(nsls):
# First convert all slices to ranges
ranges = list()
for nsl in nsls:
if isinstance(nsl, int):
ranges.append(range(nsl, nsl+1))
else:
ranges.append(range(nsl.start, nsl.stop))
# Iterate through all matching coordinates
yield from itertools.product(*ranges) | [
"def",
"_iter_coords",
"(",
"nsls",
")",
":",
"# First convert all slices to ranges",
"ranges",
"=",
"list",
"(",
")",
"for",
"nsl",
"in",
"nsls",
":",
"if",
"isinstance",
"(",
"nsl",
",",
"int",
")",
":",
"ranges",
".",
"append",
"(",
"range",
"(",
"nsl... | Iterate through all matching coordinates in a sequence of slices. | [
"Iterate",
"through",
"all",
"matching",
"coordinates",
"in",
"a",
"sequence",
"of",
"slices",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1208-L1218 |
27,523 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | farray.restrict | def restrict(self, point):
"""Apply the ``restrict`` method to all functions.
Returns a new farray.
"""
items = [f.restrict(point) for f in self._items]
return self.__class__(items, self.shape, self.ftype) | python | def restrict(self, point):
items = [f.restrict(point) for f in self._items]
return self.__class__(items, self.shape, self.ftype) | [
"def",
"restrict",
"(",
"self",
",",
"point",
")",
":",
"items",
"=",
"[",
"f",
".",
"restrict",
"(",
"point",
")",
"for",
"f",
"in",
"self",
".",
"_items",
"]",
"return",
"self",
".",
"__class__",
"(",
"items",
",",
"self",
".",
"shape",
",",
"s... | Apply the ``restrict`` method to all functions.
Returns a new farray. | [
"Apply",
"the",
"restrict",
"method",
"to",
"all",
"functions",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L628-L634 |
27,524 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | farray.compose | def compose(self, mapping):
"""Apply the ``compose`` method to all functions.
Returns a new farray.
"""
items = [f.compose(mapping) for f in self._items]
return self.__class__(items, self.shape, self.ftype) | python | def compose(self, mapping):
items = [f.compose(mapping) for f in self._items]
return self.__class__(items, self.shape, self.ftype) | [
"def",
"compose",
"(",
"self",
",",
"mapping",
")",
":",
"items",
"=",
"[",
"f",
".",
"compose",
"(",
"mapping",
")",
"for",
"f",
"in",
"self",
".",
"_items",
"]",
"return",
"self",
".",
"__class__",
"(",
"items",
",",
"self",
".",
"shape",
",",
... | Apply the ``compose`` method to all functions.
Returns a new farray. | [
"Apply",
"the",
"compose",
"method",
"to",
"all",
"functions",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L640-L646 |
27,525 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | farray.reshape | def reshape(self, *dims):
"""Return an equivalent farray with a modified shape."""
shape = _dims2shape(*dims)
if _volume(shape) != self.size:
raise ValueError("expected shape with equal volume")
return self.__class__(self._items, shape, self.ftype) | python | def reshape(self, *dims):
shape = _dims2shape(*dims)
if _volume(shape) != self.size:
raise ValueError("expected shape with equal volume")
return self.__class__(self._items, shape, self.ftype) | [
"def",
"reshape",
"(",
"self",
",",
"*",
"dims",
")",
":",
"shape",
"=",
"_dims2shape",
"(",
"*",
"dims",
")",
"if",
"_volume",
"(",
"shape",
")",
"!=",
"self",
".",
"size",
":",
"raise",
"ValueError",
"(",
"\"expected shape with equal volume\"",
")",
"r... | Return an equivalent farray with a modified shape. | [
"Return",
"an",
"equivalent",
"farray",
"with",
"a",
"modified",
"shape",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L668-L673 |
27,526 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | farray.to_uint | def to_uint(self):
"""Convert vector to an unsigned integer, if possible.
This is only useful for arrays filled with zero/one entries.
"""
num = 0
for i, f in enumerate(self._items):
if f.is_zero():
pass
elif f.is_one():
num += 1 << i
else:
fstr = "expected all functions to be a constant (0 or 1) form"
raise ValueError(fstr)
return num | python | def to_uint(self):
num = 0
for i, f in enumerate(self._items):
if f.is_zero():
pass
elif f.is_one():
num += 1 << i
else:
fstr = "expected all functions to be a constant (0 or 1) form"
raise ValueError(fstr)
return num | [
"def",
"to_uint",
"(",
"self",
")",
":",
"num",
"=",
"0",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"self",
".",
"_items",
")",
":",
"if",
"f",
".",
"is_zero",
"(",
")",
":",
"pass",
"elif",
"f",
".",
"is_one",
"(",
")",
":",
"num",
"+=",... | Convert vector to an unsigned integer, if possible.
This is only useful for arrays filled with zero/one entries. | [
"Convert",
"vector",
"to",
"an",
"unsigned",
"integer",
"if",
"possible",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L680-L694 |
27,527 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | farray.to_int | def to_int(self):
"""Convert vector to an integer, if possible.
This is only useful for arrays filled with zero/one entries.
"""
num = self.to_uint()
if num and self._items[-1].unbox():
return num - (1 << self.size)
else:
return num | python | def to_int(self):
num = self.to_uint()
if num and self._items[-1].unbox():
return num - (1 << self.size)
else:
return num | [
"def",
"to_int",
"(",
"self",
")",
":",
"num",
"=",
"self",
".",
"to_uint",
"(",
")",
"if",
"num",
"and",
"self",
".",
"_items",
"[",
"-",
"1",
"]",
".",
"unbox",
"(",
")",
":",
"return",
"num",
"-",
"(",
"1",
"<<",
"self",
".",
"size",
")",
... | Convert vector to an integer, if possible.
This is only useful for arrays filled with zero/one entries. | [
"Convert",
"vector",
"to",
"an",
"integer",
"if",
"possible",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L696-L705 |
27,528 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | farray.uor | def uor(self):
"""Unary OR reduction operator"""
return reduce(operator.or_, self._items, self.ftype.box(0)) | python | def uor(self):
return reduce(operator.or_, self._items, self.ftype.box(0)) | [
"def",
"uor",
"(",
"self",
")",
":",
"return",
"reduce",
"(",
"operator",
".",
"or_",
",",
"self",
".",
"_items",
",",
"self",
".",
"ftype",
".",
"box",
"(",
"0",
")",
")"
] | Unary OR reduction operator | [
"Unary",
"OR",
"reduction",
"operator"
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L724-L726 |
27,529 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | farray.uand | def uand(self):
"""Unary AND reduction operator"""
return reduce(operator.and_, self._items, self.ftype.box(1)) | python | def uand(self):
return reduce(operator.and_, self._items, self.ftype.box(1)) | [
"def",
"uand",
"(",
"self",
")",
":",
"return",
"reduce",
"(",
"operator",
".",
"and_",
",",
"self",
".",
"_items",
",",
"self",
".",
"ftype",
".",
"box",
"(",
"1",
")",
")"
] | Unary AND reduction operator | [
"Unary",
"AND",
"reduction",
"operator"
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L732-L734 |
27,530 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | farray.uxor | def uxor(self):
"""Unary XOR reduction operator"""
return reduce(operator.xor, self._items, self.ftype.box(0)) | python | def uxor(self):
return reduce(operator.xor, self._items, self.ftype.box(0)) | [
"def",
"uxor",
"(",
"self",
")",
":",
"return",
"reduce",
"(",
"operator",
".",
"xor",
",",
"self",
".",
"_items",
",",
"self",
".",
"ftype",
".",
"box",
"(",
"0",
")",
")"
] | Unary XOR reduction operator | [
"Unary",
"XOR",
"reduction",
"operator"
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L740-L742 |
27,531 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | farray._keys2sls | def _keys2sls(self, keys, key2sl):
"""Convert an input key to a list of slices."""
sls = list()
if isinstance(keys, tuple):
for key in keys:
sls.append(key2sl(key))
else:
sls.append(key2sl(keys))
if len(sls) > self.ndim:
fstr = "expected <= {0.ndim} slice dimensions, got {1}"
raise ValueError(fstr.format(self, len(sls)))
return sls | python | def _keys2sls(self, keys, key2sl):
sls = list()
if isinstance(keys, tuple):
for key in keys:
sls.append(key2sl(key))
else:
sls.append(key2sl(keys))
if len(sls) > self.ndim:
fstr = "expected <= {0.ndim} slice dimensions, got {1}"
raise ValueError(fstr.format(self, len(sls)))
return sls | [
"def",
"_keys2sls",
"(",
"self",
",",
"keys",
",",
"key2sl",
")",
":",
"sls",
"=",
"list",
"(",
")",
"if",
"isinstance",
"(",
"keys",
",",
"tuple",
")",
":",
"for",
"key",
"in",
"keys",
":",
"sls",
".",
"append",
"(",
"key2sl",
"(",
"key",
")",
... | Convert an input key to a list of slices. | [
"Convert",
"an",
"input",
"key",
"to",
"a",
"list",
"of",
"slices",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L850-L861 |
27,532 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | farray._coord2offset | def _coord2offset(self, coord):
"""Convert a normalized coordinate to an item offset."""
size = self.size
offset = 0
for dim, index in enumerate(coord):
size //= self._normshape[dim]
offset += size * index
return offset | python | def _coord2offset(self, coord):
size = self.size
offset = 0
for dim, index in enumerate(coord):
size //= self._normshape[dim]
offset += size * index
return offset | [
"def",
"_coord2offset",
"(",
"self",
",",
"coord",
")",
":",
"size",
"=",
"self",
".",
"size",
"offset",
"=",
"0",
"for",
"dim",
",",
"index",
"in",
"enumerate",
"(",
"coord",
")",
":",
"size",
"//=",
"self",
".",
"_normshape",
"[",
"dim",
"]",
"of... | Convert a normalized coordinate to an item offset. | [
"Convert",
"a",
"normalized",
"coordinate",
"to",
"an",
"item",
"offset",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L899-L906 |
27,533 | cjdrake/pyeda | pyeda/boolalg/bfarray.py | farray._op_shape | def _op_shape(self, other):
"""Return shape that will be used by farray constructor."""
if isinstance(other, farray):
if self.shape == other.shape:
return self.shape
elif self.size == other.size:
return None
else:
raise ValueError("expected operand sizes to match")
else:
raise TypeError("expected farray input") | python | def _op_shape(self, other):
if isinstance(other, farray):
if self.shape == other.shape:
return self.shape
elif self.size == other.size:
return None
else:
raise ValueError("expected operand sizes to match")
else:
raise TypeError("expected farray input") | [
"def",
"_op_shape",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"farray",
")",
":",
"if",
"self",
".",
"shape",
"==",
"other",
".",
"shape",
":",
"return",
"self",
".",
"shape",
"elif",
"self",
".",
"size",
"==",
"ot... | Return shape that will be used by farray constructor. | [
"Return",
"shape",
"that",
"will",
"be",
"used",
"by",
"farray",
"constructor",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L913-L923 |
27,534 | tobyqin/xmind2testlink | web/application.py | delete_records | def delete_records(keep=20):
"""Clean up files on server and mark the record as deleted"""
sql = "SELECT * from records where is_deleted<>1 ORDER BY id desc LIMIT -1 offset {}".format(keep)
assert isinstance(g.db, sqlite3.Connection)
c = g.db.cursor()
c.execute(sql)
rows = c.fetchall()
for row in rows:
name = row[1]
xmind = join(app.config['UPLOAD_FOLDER'], name)
xml = join(app.config['UPLOAD_FOLDER'], name[:-5] + 'xml')
for f in [xmind, xml]:
if exists(f):
os.remove(f)
sql = 'UPDATE records SET is_deleted=1 WHERE id = ?'
c.execute(sql, (row[0],))
g.db.commit() | python | def delete_records(keep=20):
sql = "SELECT * from records where is_deleted<>1 ORDER BY id desc LIMIT -1 offset {}".format(keep)
assert isinstance(g.db, sqlite3.Connection)
c = g.db.cursor()
c.execute(sql)
rows = c.fetchall()
for row in rows:
name = row[1]
xmind = join(app.config['UPLOAD_FOLDER'], name)
xml = join(app.config['UPLOAD_FOLDER'], name[:-5] + 'xml')
for f in [xmind, xml]:
if exists(f):
os.remove(f)
sql = 'UPDATE records SET is_deleted=1 WHERE id = ?'
c.execute(sql, (row[0],))
g.db.commit() | [
"def",
"delete_records",
"(",
"keep",
"=",
"20",
")",
":",
"sql",
"=",
"\"SELECT * from records where is_deleted<>1 ORDER BY id desc LIMIT -1 offset {}\"",
".",
"format",
"(",
"keep",
")",
"assert",
"isinstance",
"(",
"g",
".",
"db",
",",
"sqlite3",
".",
"Connection... | Clean up files on server and mark the record as deleted | [
"Clean",
"up",
"files",
"on",
"server",
"and",
"mark",
"the",
"record",
"as",
"deleted"
] | 7ce2a5798d09cdfc0294481214c9ef9674264f61 | https://github.com/tobyqin/xmind2testlink/blob/7ce2a5798d09cdfc0294481214c9ef9674264f61/web/application.py#L65-L83 |
27,535 | horejsek/python-webdriverwrapper | webdriverwrapper/errors.py | WebdriverWrapperErrorMixin.check_expected_errors | def check_expected_errors(self, test_method):
"""
This method is called after each test. It will read decorated
informations and check if there are expected errors.
You can set expected errors by decorators :py:func:`.expected_error_page`,
:py:func:`.allowed_error_pages`, :py:func:`.expected_error_messages`,
:py:func:`.allowed_error_messages` and :py:func:`.allowed_any_error_message`.
"""
f = lambda key, default=[]: getattr(test_method, key, default)
expected_error_page = f(EXPECTED_ERROR_PAGE, default=None)
allowed_error_pages = f(ALLOWED_ERROR_PAGES)
expected_error_messages = f(EXPECTED_ERROR_MESSAGES)
allowed_error_messages = f(ALLOWED_ERROR_MESSAGES)
self.check_errors(
expected_error_page,
allowed_error_pages,
expected_error_messages,
allowed_error_messages,
) | python | def check_expected_errors(self, test_method):
f = lambda key, default=[]: getattr(test_method, key, default)
expected_error_page = f(EXPECTED_ERROR_PAGE, default=None)
allowed_error_pages = f(ALLOWED_ERROR_PAGES)
expected_error_messages = f(EXPECTED_ERROR_MESSAGES)
allowed_error_messages = f(ALLOWED_ERROR_MESSAGES)
self.check_errors(
expected_error_page,
allowed_error_pages,
expected_error_messages,
allowed_error_messages,
) | [
"def",
"check_expected_errors",
"(",
"self",
",",
"test_method",
")",
":",
"f",
"=",
"lambda",
"key",
",",
"default",
"=",
"[",
"]",
":",
"getattr",
"(",
"test_method",
",",
"key",
",",
"default",
")",
"expected_error_page",
"=",
"f",
"(",
"EXPECTED_ERROR_... | This method is called after each test. It will read decorated
informations and check if there are expected errors.
You can set expected errors by decorators :py:func:`.expected_error_page`,
:py:func:`.allowed_error_pages`, :py:func:`.expected_error_messages`,
:py:func:`.allowed_error_messages` and :py:func:`.allowed_any_error_message`. | [
"This",
"method",
"is",
"called",
"after",
"each",
"test",
".",
"It",
"will",
"read",
"decorated",
"informations",
"and",
"check",
"if",
"there",
"are",
"expected",
"errors",
"."
] | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/errors.py#L107-L126 |
27,536 | horejsek/python-webdriverwrapper | webdriverwrapper/errors.py | WebdriverWrapperErrorMixin.get_error_page | def get_error_page(self):
"""
Method returning error page. Should return string.
By default it find element with class ``error-page`` and returns text
of ``h1`` header. You can change this method accordingly to your app.
Error page returned from this method is used in decorators
:py:func:`.expected_error_page` and :py:func:`.allowed_error_pages`.
"""
try:
error_page = self.get_elm(class_name='error-page')
except NoSuchElementException:
pass
else:
header = error_page.get_elm(tag_name='h1')
return header.text | python | def get_error_page(self):
try:
error_page = self.get_elm(class_name='error-page')
except NoSuchElementException:
pass
else:
header = error_page.get_elm(tag_name='h1')
return header.text | [
"def",
"get_error_page",
"(",
"self",
")",
":",
"try",
":",
"error_page",
"=",
"self",
".",
"get_elm",
"(",
"class_name",
"=",
"'error-page'",
")",
"except",
"NoSuchElementException",
":",
"pass",
"else",
":",
"header",
"=",
"error_page",
".",
"get_elm",
"("... | Method returning error page. Should return string.
By default it find element with class ``error-page`` and returns text
of ``h1`` header. You can change this method accordingly to your app.
Error page returned from this method is used in decorators
:py:func:`.expected_error_page` and :py:func:`.allowed_error_pages`. | [
"Method",
"returning",
"error",
"page",
".",
"Should",
"return",
"string",
"."
] | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/errors.py#L169-L185 |
27,537 | horejsek/python-webdriverwrapper | webdriverwrapper/errors.py | WebdriverWrapperErrorMixin.get_error_traceback | def get_error_traceback(self):
"""
Method returning traceback of error page.
By default it find element with class ``error-page`` and returns text
of element with class ``traceback``. You can change this method
accordingly to your app.
"""
try:
error_page = self.get_elm(class_name='error-page')
traceback = error_page.get_elm(class_name='traceback')
except NoSuchElementException:
pass
else:
return traceback.text | python | def get_error_traceback(self):
try:
error_page = self.get_elm(class_name='error-page')
traceback = error_page.get_elm(class_name='traceback')
except NoSuchElementException:
pass
else:
return traceback.text | [
"def",
"get_error_traceback",
"(",
"self",
")",
":",
"try",
":",
"error_page",
"=",
"self",
".",
"get_elm",
"(",
"class_name",
"=",
"'error-page'",
")",
"traceback",
"=",
"error_page",
".",
"get_elm",
"(",
"class_name",
"=",
"'traceback'",
")",
"except",
"No... | Method returning traceback of error page.
By default it find element with class ``error-page`` and returns text
of element with class ``traceback``. You can change this method
accordingly to your app. | [
"Method",
"returning",
"traceback",
"of",
"error",
"page",
"."
] | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/errors.py#L187-L201 |
27,538 | horejsek/python-webdriverwrapper | webdriverwrapper/errors.py | WebdriverWrapperErrorMixin.get_error_messages | def get_error_messages(self):
"""
Method returning error messages. Should return list of messages.
By default it find element with class ``error`` and theirs value in
attribute ``error`` or text if that attribute is missing. You can change
this method accordingly to your app.
Error messages returned from this method are used in decorators
:py:func:`.expected_error_messages` and :py:func:`.allowed_error_messages`.
"""
try:
error_elms = self.get_elms(class_name='error')
except NoSuchElementException:
return []
else:
try:
error_values = [error_elm.get_attribute('error') for error_elm in error_elms]
except Exception:
error_values = [error_elm.text for error_elm in error_elms]
finally:
return error_values | python | def get_error_messages(self):
try:
error_elms = self.get_elms(class_name='error')
except NoSuchElementException:
return []
else:
try:
error_values = [error_elm.get_attribute('error') for error_elm in error_elms]
except Exception:
error_values = [error_elm.text for error_elm in error_elms]
finally:
return error_values | [
"def",
"get_error_messages",
"(",
"self",
")",
":",
"try",
":",
"error_elms",
"=",
"self",
".",
"get_elms",
"(",
"class_name",
"=",
"'error'",
")",
"except",
"NoSuchElementException",
":",
"return",
"[",
"]",
"else",
":",
"try",
":",
"error_values",
"=",
"... | Method returning error messages. Should return list of messages.
By default it find element with class ``error`` and theirs value in
attribute ``error`` or text if that attribute is missing. You can change
this method accordingly to your app.
Error messages returned from this method are used in decorators
:py:func:`.expected_error_messages` and :py:func:`.allowed_error_messages`. | [
"Method",
"returning",
"error",
"messages",
".",
"Should",
"return",
"list",
"of",
"messages",
"."
] | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/errors.py#L203-L224 |
27,539 | horejsek/python-webdriverwrapper | webdriverwrapper/info.py | WebdriverWrapperInfoMixin.check_expected_infos | def check_expected_infos(self, test_method):
"""
This method is called after each test. It will read decorated
informations and check if there are expected infos.
You can set expected infos by decorators :py:func:`.expected_info_messages`
and :py:func:`.allowed_info_messages`.
"""
f = lambda key, default=[]: getattr(test_method, key, default)
expected_info_messages = f(EXPECTED_INFO_MESSAGES)
allowed_info_messages = f(ALLOWED_INFO_MESSAGES)
self.check_infos(expected_info_messages, allowed_info_messages) | python | def check_expected_infos(self, test_method):
f = lambda key, default=[]: getattr(test_method, key, default)
expected_info_messages = f(EXPECTED_INFO_MESSAGES)
allowed_info_messages = f(ALLOWED_INFO_MESSAGES)
self.check_infos(expected_info_messages, allowed_info_messages) | [
"def",
"check_expected_infos",
"(",
"self",
",",
"test_method",
")",
":",
"f",
"=",
"lambda",
"key",
",",
"default",
"=",
"[",
"]",
":",
"getattr",
"(",
"test_method",
",",
"key",
",",
"default",
")",
"expected_info_messages",
"=",
"f",
"(",
"EXPECTED_INFO... | This method is called after each test. It will read decorated
informations and check if there are expected infos.
You can set expected infos by decorators :py:func:`.expected_info_messages`
and :py:func:`.allowed_info_messages`. | [
"This",
"method",
"is",
"called",
"after",
"each",
"test",
".",
"It",
"will",
"read",
"decorated",
"informations",
"and",
"check",
"if",
"there",
"are",
"expected",
"infos",
"."
] | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/info.py#L52-L63 |
27,540 | horejsek/python-webdriverwrapper | webdriverwrapper/info.py | WebdriverWrapperInfoMixin.get_info_messages | def get_info_messages(self):
"""
Method returning info messages. Should return list of messages.
By default it find element with class ``info`` and theirs value in
attribute ``info`` or text if that attribute is missing. You can change
this method accordingly to your app.
Info messages returned from this method are used in decorators
:py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`.
"""
try:
info_elms = self.get_elms(class_name='info')
except NoSuchElementException:
return []
else:
try:
info_values = [info_elm.get_attribute('info') for info_elm in info_elms]
except Exception: # pylint: disable=broad-except
info_values = [info_elm.text for info_elm in info_elms]
finally:
return info_values | python | def get_info_messages(self):
try:
info_elms = self.get_elms(class_name='info')
except NoSuchElementException:
return []
else:
try:
info_values = [info_elm.get_attribute('info') for info_elm in info_elms]
except Exception: # pylint: disable=broad-except
info_values = [info_elm.text for info_elm in info_elms]
finally:
return info_values | [
"def",
"get_info_messages",
"(",
"self",
")",
":",
"try",
":",
"info_elms",
"=",
"self",
".",
"get_elms",
"(",
"class_name",
"=",
"'info'",
")",
"except",
"NoSuchElementException",
":",
"return",
"[",
"]",
"else",
":",
"try",
":",
"info_values",
"=",
"[",
... | Method returning info messages. Should return list of messages.
By default it find element with class ``info`` and theirs value in
attribute ``info`` or text if that attribute is missing. You can change
this method accordingly to your app.
Info messages returned from this method are used in decorators
:py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`. | [
"Method",
"returning",
"info",
"messages",
".",
"Should",
"return",
"list",
"of",
"messages",
"."
] | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/info.py#L89-L110 |
27,541 | horejsek/python-webdriverwrapper | webdriverwrapper/wrapper.py | _ConvertToWebelementWrapper._make_instance | def _make_instance(cls, element_class, webelement):
"""
Firefox uses another implementation of element. This method
switch base of wrapped element to firefox one.
"""
if isinstance(webelement, FirefoxWebElement):
element_class = copy.deepcopy(element_class)
element_class.__bases__ = tuple(
FirefoxWebElement if base is WebElement else base
for base in element_class.__bases__
)
return element_class(webelement) | python | def _make_instance(cls, element_class, webelement):
if isinstance(webelement, FirefoxWebElement):
element_class = copy.deepcopy(element_class)
element_class.__bases__ = tuple(
FirefoxWebElement if base is WebElement else base
for base in element_class.__bases__
)
return element_class(webelement) | [
"def",
"_make_instance",
"(",
"cls",
",",
"element_class",
",",
"webelement",
")",
":",
"if",
"isinstance",
"(",
"webelement",
",",
"FirefoxWebElement",
")",
":",
"element_class",
"=",
"copy",
".",
"deepcopy",
"(",
"element_class",
")",
"element_class",
".",
"... | Firefox uses another implementation of element. This method
switch base of wrapped element to firefox one. | [
"Firefox",
"uses",
"another",
"implementation",
"of",
"element",
".",
"This",
"method",
"switch",
"base",
"of",
"wrapped",
"element",
"to",
"firefox",
"one",
"."
] | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L74-L85 |
27,542 | horejsek/python-webdriverwrapper | webdriverwrapper/wrapper.py | _WebdriverWrapper.html | def html(self):
"""
Returns ``innerHTML`` of whole page. On page have to be tag ``body``.
.. versionadded:: 2.2
"""
try:
body = self.get_elm(tag_name='body')
except selenium_exc.NoSuchElementException:
return None
else:
return body.get_attribute('innerHTML') | python | def html(self):
try:
body = self.get_elm(tag_name='body')
except selenium_exc.NoSuchElementException:
return None
else:
return body.get_attribute('innerHTML') | [
"def",
"html",
"(",
"self",
")",
":",
"try",
":",
"body",
"=",
"self",
".",
"get_elm",
"(",
"tag_name",
"=",
"'body'",
")",
"except",
"selenium_exc",
".",
"NoSuchElementException",
":",
"return",
"None",
"else",
":",
"return",
"body",
".",
"get_attribute",... | Returns ``innerHTML`` of whole page. On page have to be tag ``body``.
.. versionadded:: 2.2 | [
"Returns",
"innerHTML",
"of",
"whole",
"page",
".",
"On",
"page",
"have",
"to",
"be",
"tag",
"body",
"."
] | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L408-L419 |
27,543 | horejsek/python-webdriverwrapper | webdriverwrapper/wrapper.py | _WebdriverWrapper.switch_to_window | def switch_to_window(self, window_name=None, title=None, url=None):
"""
WebDriver implements switching to other window only by it's name. With
wrapper there is also option to switch by title of window or URL. URL
can be also relative path.
"""
if window_name:
self.switch_to.window(window_name)
return
if url:
url = self.get_url(path=url)
for window_handle in self.window_handles:
self.switch_to.window(window_handle)
if title and self.title == title:
return
if url and self.current_url == url:
return
raise selenium_exc.NoSuchWindowException('Window (title=%s, url=%s) not found.' % (title, url)) | python | def switch_to_window(self, window_name=None, title=None, url=None):
if window_name:
self.switch_to.window(window_name)
return
if url:
url = self.get_url(path=url)
for window_handle in self.window_handles:
self.switch_to.window(window_handle)
if title and self.title == title:
return
if url and self.current_url == url:
return
raise selenium_exc.NoSuchWindowException('Window (title=%s, url=%s) not found.' % (title, url)) | [
"def",
"switch_to_window",
"(",
"self",
",",
"window_name",
"=",
"None",
",",
"title",
"=",
"None",
",",
"url",
"=",
"None",
")",
":",
"if",
"window_name",
":",
"self",
".",
"switch_to",
".",
"window",
"(",
"window_name",
")",
"return",
"if",
"url",
":... | WebDriver implements switching to other window only by it's name. With
wrapper there is also option to switch by title of window or URL. URL
can be also relative path. | [
"WebDriver",
"implements",
"switching",
"to",
"other",
"window",
"only",
"by",
"it",
"s",
"name",
".",
"With",
"wrapper",
"there",
"is",
"also",
"option",
"to",
"switch",
"by",
"title",
"of",
"window",
"or",
"URL",
".",
"URL",
"can",
"be",
"also",
"relat... | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L495-L514 |
27,544 | horejsek/python-webdriverwrapper | webdriverwrapper/wrapper.py | _WebdriverWrapper.close_window | def close_window(self, window_name=None, title=None, url=None):
"""
WebDriver implements only closing current window. If you want to close
some window without having to switch to it, use this method.
"""
main_window_handle = self.current_window_handle
self.switch_to_window(window_name, title, url)
self.close()
self.switch_to_window(main_window_handle) | python | def close_window(self, window_name=None, title=None, url=None):
main_window_handle = self.current_window_handle
self.switch_to_window(window_name, title, url)
self.close()
self.switch_to_window(main_window_handle) | [
"def",
"close_window",
"(",
"self",
",",
"window_name",
"=",
"None",
",",
"title",
"=",
"None",
",",
"url",
"=",
"None",
")",
":",
"main_window_handle",
"=",
"self",
".",
"current_window_handle",
"self",
".",
"switch_to_window",
"(",
"window_name",
",",
"tit... | WebDriver implements only closing current window. If you want to close
some window without having to switch to it, use this method. | [
"WebDriver",
"implements",
"only",
"closing",
"current",
"window",
".",
"If",
"you",
"want",
"to",
"close",
"some",
"window",
"without",
"having",
"to",
"switch",
"to",
"it",
"use",
"this",
"method",
"."
] | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L516-L524 |
27,545 | horejsek/python-webdriverwrapper | webdriverwrapper/wrapper.py | _WebdriverWrapper.close_other_windows | def close_other_windows(self):
"""
Closes all not current windows. Useful for tests - after each test you
can automatically close all windows.
"""
main_window_handle = self.current_window_handle
for window_handle in self.window_handles:
if window_handle == main_window_handle:
continue
self.switch_to_window(window_handle)
self.close()
self.switch_to_window(main_window_handle) | python | def close_other_windows(self):
main_window_handle = self.current_window_handle
for window_handle in self.window_handles:
if window_handle == main_window_handle:
continue
self.switch_to_window(window_handle)
self.close()
self.switch_to_window(main_window_handle) | [
"def",
"close_other_windows",
"(",
"self",
")",
":",
"main_window_handle",
"=",
"self",
".",
"current_window_handle",
"for",
"window_handle",
"in",
"self",
".",
"window_handles",
":",
"if",
"window_handle",
"==",
"main_window_handle",
":",
"continue",
"self",
".",
... | Closes all not current windows. Useful for tests - after each test you
can automatically close all windows. | [
"Closes",
"all",
"not",
"current",
"windows",
".",
"Useful",
"for",
"tests",
"-",
"after",
"each",
"test",
"you",
"can",
"automatically",
"close",
"all",
"windows",
"."
] | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L526-L537 |
27,546 | horejsek/python-webdriverwrapper | webdriverwrapper/wrapper.py | _WebdriverWrapper.close_alert | def close_alert(self, ignore_exception=False):
"""
JS alerts all blocking. This method closes it. If there is no alert,
method raises exception. In tests is good to call this method with
``ignore_exception`` setted to ``True`` which will ignore any exception.
"""
try:
alert = self.get_alert()
alert.accept()
except:
if not ignore_exception:
raise | python | def close_alert(self, ignore_exception=False):
try:
alert = self.get_alert()
alert.accept()
except:
if not ignore_exception:
raise | [
"def",
"close_alert",
"(",
"self",
",",
"ignore_exception",
"=",
"False",
")",
":",
"try",
":",
"alert",
"=",
"self",
".",
"get_alert",
"(",
")",
"alert",
".",
"accept",
"(",
")",
"except",
":",
"if",
"not",
"ignore_exception",
":",
"raise"
] | JS alerts all blocking. This method closes it. If there is no alert,
method raises exception. In tests is good to call this method with
``ignore_exception`` setted to ``True`` which will ignore any exception. | [
"JS",
"alerts",
"all",
"blocking",
".",
"This",
"method",
"closes",
"it",
".",
"If",
"there",
"is",
"no",
"alert",
"method",
"raises",
"exception",
".",
"In",
"tests",
"is",
"good",
"to",
"call",
"this",
"method",
"with",
"ignore_exception",
"setted",
"to"... | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L539-L550 |
27,547 | horejsek/python-webdriverwrapper | webdriverwrapper/wrapper.py | _WebdriverWrapper.wait_for_alert | def wait_for_alert(self, timeout=None):
"""
Shortcut for waiting for alert. If it not ends with exception, it
returns that alert. Detault timeout is `~.default_wait_timeout`.
"""
if not timeout:
timeout = self.default_wait_timeout
alert = Alert(self)
# There is no better way how to check alert appearance
def alert_shown(driver):
try:
alert.text
return True
except selenium_exc.NoAlertPresentException:
return False
self.wait(timeout).until(alert_shown)
return alert | python | def wait_for_alert(self, timeout=None):
if not timeout:
timeout = self.default_wait_timeout
alert = Alert(self)
# There is no better way how to check alert appearance
def alert_shown(driver):
try:
alert.text
return True
except selenium_exc.NoAlertPresentException:
return False
self.wait(timeout).until(alert_shown)
return alert | [
"def",
"wait_for_alert",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"timeout",
":",
"timeout",
"=",
"self",
".",
"default_wait_timeout",
"alert",
"=",
"Alert",
"(",
"self",
")",
"# There is no better way how to check alert appearance",
"def",... | Shortcut for waiting for alert. If it not ends with exception, it
returns that alert. Detault timeout is `~.default_wait_timeout`. | [
"Shortcut",
"for",
"waiting",
"for",
"alert",
".",
"If",
"it",
"not",
"ends",
"with",
"exception",
"it",
"returns",
"that",
"alert",
".",
"Detault",
"timeout",
"is",
"~",
".",
"default_wait_timeout",
"."
] | a492f79ab60ed83d860dd817b6a0961500d7e3f5 | https://github.com/horejsek/python-webdriverwrapper/blob/a492f79ab60ed83d860dd817b6a0961500d7e3f5/webdriverwrapper/wrapper.py#L558-L578 |
27,548 | rr-/docstring_parser | docstring_parser/parser/common.py | DocstringTypeMeta.type_name | def type_name(self) -> T.Optional[str]:
"""Return type name associated with given docstring metadata."""
return self.args[1] if len(self.args) > 1 else None | python | def type_name(self) -> T.Optional[str]:
return self.args[1] if len(self.args) > 1 else None | [
"def",
"type_name",
"(",
"self",
")",
"->",
"T",
".",
"Optional",
"[",
"str",
"]",
":",
"return",
"self",
".",
"args",
"[",
"1",
"]",
"if",
"len",
"(",
"self",
".",
"args",
")",
">",
"1",
"else",
"None"
] | Return type name associated with given docstring metadata. | [
"Return",
"type",
"name",
"associated",
"with",
"given",
"docstring",
"metadata",
"."
] | 389773f6790a84d33b10160589ce8591122e12bb | https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/common.py#L42-L44 |
27,549 | rr-/docstring_parser | docstring_parser/parser/common.py | Docstring.params | def params(self) -> T.List[DocstringParam]:
"""Return parameters indicated in docstring."""
return [
DocstringParam.from_meta(meta)
for meta in self.meta
if meta.args[0]
in {"param", "parameter", "arg", "argument", "key", "keyword"}
] | python | def params(self) -> T.List[DocstringParam]:
return [
DocstringParam.from_meta(meta)
for meta in self.meta
if meta.args[0]
in {"param", "parameter", "arg", "argument", "key", "keyword"}
] | [
"def",
"params",
"(",
"self",
")",
"->",
"T",
".",
"List",
"[",
"DocstringParam",
"]",
":",
"return",
"[",
"DocstringParam",
".",
"from_meta",
"(",
"meta",
")",
"for",
"meta",
"in",
"self",
".",
"meta",
"if",
"meta",
".",
"args",
"[",
"0",
"]",
"in... | Return parameters indicated in docstring. | [
"Return",
"parameters",
"indicated",
"in",
"docstring",
"."
] | 389773f6790a84d33b10160589ce8591122e12bb | https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/common.py#L89-L96 |
27,550 | rr-/docstring_parser | docstring_parser/parser/common.py | Docstring.raises | def raises(self) -> T.List[DocstringRaises]:
"""Return exceptions indicated in docstring."""
return [
DocstringRaises.from_meta(meta)
for meta in self.meta
if meta.args[0] in {"raises", "raise", "except", "exception"}
] | python | def raises(self) -> T.List[DocstringRaises]:
return [
DocstringRaises.from_meta(meta)
for meta in self.meta
if meta.args[0] in {"raises", "raise", "except", "exception"}
] | [
"def",
"raises",
"(",
"self",
")",
"->",
"T",
".",
"List",
"[",
"DocstringRaises",
"]",
":",
"return",
"[",
"DocstringRaises",
".",
"from_meta",
"(",
"meta",
")",
"for",
"meta",
"in",
"self",
".",
"meta",
"if",
"meta",
".",
"args",
"[",
"0",
"]",
"... | Return exceptions indicated in docstring. | [
"Return",
"exceptions",
"indicated",
"in",
"docstring",
"."
] | 389773f6790a84d33b10160589ce8591122e12bb | https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/common.py#L99-L105 |
27,551 | rr-/docstring_parser | docstring_parser/parser/common.py | Docstring.returns | def returns(self) -> T.Optional[DocstringReturns]:
"""Return return information indicated in docstring."""
try:
return next(
DocstringReturns.from_meta(meta)
for meta in self.meta
if meta.args[0] in {"return", "returns", "yield", "yields"}
)
except StopIteration:
return None | python | def returns(self) -> T.Optional[DocstringReturns]:
try:
return next(
DocstringReturns.from_meta(meta)
for meta in self.meta
if meta.args[0] in {"return", "returns", "yield", "yields"}
)
except StopIteration:
return None | [
"def",
"returns",
"(",
"self",
")",
"->",
"T",
".",
"Optional",
"[",
"DocstringReturns",
"]",
":",
"try",
":",
"return",
"next",
"(",
"DocstringReturns",
".",
"from_meta",
"(",
"meta",
")",
"for",
"meta",
"in",
"self",
".",
"meta",
"if",
"meta",
".",
... | Return return information indicated in docstring. | [
"Return",
"return",
"information",
"indicated",
"in",
"docstring",
"."
] | 389773f6790a84d33b10160589ce8591122e12bb | https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/common.py#L108-L117 |
27,552 | rr-/docstring_parser | docstring_parser/parser/google.py | _build_meta | def _build_meta(text: str, title: str) -> DocstringMeta:
"""Build docstring element.
:param text: docstring element text
:param title: title of section containing element
:return:
"""
meta = _sections[title]
if meta == "returns" and ":" not in text.split()[0]:
return DocstringMeta([meta], description=text)
# Split spec and description
before, desc = text.split(":", 1)
if desc:
desc = desc[1:] if desc[0] == " " else desc
if "\n" in desc:
first_line, rest = desc.split("\n", 1)
desc = first_line + "\n" + inspect.cleandoc(rest)
desc = desc.strip("\n")
# Build Meta args
m = re.match(r"(\S+) \((\S+)\)$", before)
if meta == "param" and m:
arg_name, type_name = m.group(1, 2)
args = [meta, type_name, arg_name]
else:
args = [meta, before]
return DocstringMeta(args, description=desc) | python | def _build_meta(text: str, title: str) -> DocstringMeta:
meta = _sections[title]
if meta == "returns" and ":" not in text.split()[0]:
return DocstringMeta([meta], description=text)
# Split spec and description
before, desc = text.split(":", 1)
if desc:
desc = desc[1:] if desc[0] == " " else desc
if "\n" in desc:
first_line, rest = desc.split("\n", 1)
desc = first_line + "\n" + inspect.cleandoc(rest)
desc = desc.strip("\n")
# Build Meta args
m = re.match(r"(\S+) \((\S+)\)$", before)
if meta == "param" and m:
arg_name, type_name = m.group(1, 2)
args = [meta, type_name, arg_name]
else:
args = [meta, before]
return DocstringMeta(args, description=desc) | [
"def",
"_build_meta",
"(",
"text",
":",
"str",
",",
"title",
":",
"str",
")",
"->",
"DocstringMeta",
":",
"meta",
"=",
"_sections",
"[",
"title",
"]",
"if",
"meta",
"==",
"\"returns\"",
"and",
"\":\"",
"not",
"in",
"text",
".",
"split",
"(",
")",
"["... | Build docstring element.
:param text: docstring element text
:param title: title of section containing element
:return: | [
"Build",
"docstring",
"element",
"."
] | 389773f6790a84d33b10160589ce8591122e12bb | https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/google.py#L28-L57 |
27,553 | rr-/docstring_parser | docstring_parser/parser/google.py | parse | def parse(text: str) -> Docstring:
"""
Parse the Google-style docstring into its components.
:returns: parsed docstring
"""
ret = Docstring()
if not text:
return ret
# Clean according to PEP-0257
text = inspect.cleandoc(text)
# Find first title and split on its position
match = _titles_re.search(text)
if match:
desc_chunk = text[: match.start()]
meta_chunk = text[match.start() :]
else:
desc_chunk = text
meta_chunk = ""
# Break description into short and long parts
parts = desc_chunk.split("\n", 1)
ret.short_description = parts[0] or None
if len(parts) > 1:
long_desc_chunk = parts[1] or ""
ret.blank_after_short_description = long_desc_chunk.startswith("\n")
ret.blank_after_long_description = long_desc_chunk.endswith("\n\n")
ret.long_description = long_desc_chunk.strip() or None
# Split by sections determined by titles
matches = list(_titles_re.finditer(meta_chunk))
if not matches:
return ret
splits = []
for j in range(len(matches) - 1):
splits.append((matches[j].end(), matches[j + 1].start()))
splits.append((matches[-1].end(), len(meta_chunk)))
chunks = {}
for j, (start, end) in enumerate(splits):
title = matches[j].group(1)
if title not in _valid:
continue
chunks[title] = meta_chunk[start:end].strip("\n")
if not chunks:
return ret
# Add elements from each chunk
for title, chunk in chunks.items():
# Determine indent
indent_match = re.search(r"^\s+", chunk)
if not indent_match:
raise ParseError(f'Can\'t infer indent from "{chunk}"')
indent = indent_match.group()
# Check for returns/yeilds (only one element)
if _sections[title] in ("returns", "yields"):
part = inspect.cleandoc(chunk)
ret.meta.append(_build_meta(part, title))
continue
# Split based on lines which have exactly that indent
_re = "^" + indent + r"(?=\S)"
c_matches = list(re.finditer(_re, chunk, flags=re.M))
if not c_matches:
raise ParseError(f'No specification for "{title}": "{chunk}"')
c_splits = []
for j in range(len(c_matches) - 1):
c_splits.append((c_matches[j].end(), c_matches[j + 1].start()))
c_splits.append((c_matches[-1].end(), len(chunk)))
for j, (start, end) in enumerate(c_splits):
part = chunk[start:end].strip("\n")
ret.meta.append(_build_meta(part, title))
return ret | python | def parse(text: str) -> Docstring:
ret = Docstring()
if not text:
return ret
# Clean according to PEP-0257
text = inspect.cleandoc(text)
# Find first title and split on its position
match = _titles_re.search(text)
if match:
desc_chunk = text[: match.start()]
meta_chunk = text[match.start() :]
else:
desc_chunk = text
meta_chunk = ""
# Break description into short and long parts
parts = desc_chunk.split("\n", 1)
ret.short_description = parts[0] or None
if len(parts) > 1:
long_desc_chunk = parts[1] or ""
ret.blank_after_short_description = long_desc_chunk.startswith("\n")
ret.blank_after_long_description = long_desc_chunk.endswith("\n\n")
ret.long_description = long_desc_chunk.strip() or None
# Split by sections determined by titles
matches = list(_titles_re.finditer(meta_chunk))
if not matches:
return ret
splits = []
for j in range(len(matches) - 1):
splits.append((matches[j].end(), matches[j + 1].start()))
splits.append((matches[-1].end(), len(meta_chunk)))
chunks = {}
for j, (start, end) in enumerate(splits):
title = matches[j].group(1)
if title not in _valid:
continue
chunks[title] = meta_chunk[start:end].strip("\n")
if not chunks:
return ret
# Add elements from each chunk
for title, chunk in chunks.items():
# Determine indent
indent_match = re.search(r"^\s+", chunk)
if not indent_match:
raise ParseError(f'Can\'t infer indent from "{chunk}"')
indent = indent_match.group()
# Check for returns/yeilds (only one element)
if _sections[title] in ("returns", "yields"):
part = inspect.cleandoc(chunk)
ret.meta.append(_build_meta(part, title))
continue
# Split based on lines which have exactly that indent
_re = "^" + indent + r"(?=\S)"
c_matches = list(re.finditer(_re, chunk, flags=re.M))
if not c_matches:
raise ParseError(f'No specification for "{title}": "{chunk}"')
c_splits = []
for j in range(len(c_matches) - 1):
c_splits.append((c_matches[j].end(), c_matches[j + 1].start()))
c_splits.append((c_matches[-1].end(), len(chunk)))
for j, (start, end) in enumerate(c_splits):
part = chunk[start:end].strip("\n")
ret.meta.append(_build_meta(part, title))
return ret | [
"def",
"parse",
"(",
"text",
":",
"str",
")",
"->",
"Docstring",
":",
"ret",
"=",
"Docstring",
"(",
")",
"if",
"not",
"text",
":",
"return",
"ret",
"# Clean according to PEP-0257",
"text",
"=",
"inspect",
".",
"cleandoc",
"(",
"text",
")",
"# Find first ti... | Parse the Google-style docstring into its components.
:returns: parsed docstring | [
"Parse",
"the",
"Google",
"-",
"style",
"docstring",
"into",
"its",
"components",
"."
] | 389773f6790a84d33b10160589ce8591122e12bb | https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/google.py#L60-L136 |
27,554 | project-generator/project_generator | project_generator/init_yaml.py | _determine_tool | def _determine_tool(files):
"""Yields tuples in the form of (linker file, tool the file links for"""
for file in files:
linker_ext = file.split('.')[-1]
if "sct" in linker_ext or "lin" in linker_ext:
yield (str(file),"uvision")
elif "ld" in linker_ext:
yield (str(file),"make_gcc_arm")
elif "icf" in linker_ext:
yield (str(file),"iar_arm") | python | def _determine_tool(files):
for file in files:
linker_ext = file.split('.')[-1]
if "sct" in linker_ext or "lin" in linker_ext:
yield (str(file),"uvision")
elif "ld" in linker_ext:
yield (str(file),"make_gcc_arm")
elif "icf" in linker_ext:
yield (str(file),"iar_arm") | [
"def",
"_determine_tool",
"(",
"files",
")",
":",
"for",
"file",
"in",
"files",
":",
"linker_ext",
"=",
"file",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"if",
"\"sct\"",
"in",
"linker_ext",
"or",
"\"lin\"",
"in",
"linker_ext",
":",
"yield",
... | Yields tuples in the form of (linker file, tool the file links for | [
"Yields",
"tuples",
"in",
"the",
"form",
"of",
"(",
"linker",
"file",
"tool",
"the",
"file",
"links",
"for"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/init_yaml.py#L25-L34 |
27,555 | project-generator/project_generator | project_generator/tools/iar.py | IAREmbeddedWorkbenchProject._get_option | def _get_option(self, settings, find_key):
""" Return index for provided key """
# This is used as in IAR template, everything
# is as an array with random positions. We look for key with an index
for option in settings:
if option['name'] == find_key:
return settings.index(option) | python | def _get_option(self, settings, find_key):
# This is used as in IAR template, everything
# is as an array with random positions. We look for key with an index
for option in settings:
if option['name'] == find_key:
return settings.index(option) | [
"def",
"_get_option",
"(",
"self",
",",
"settings",
",",
"find_key",
")",
":",
"# This is used as in IAR template, everything ",
"# is as an array with random positions. We look for key with an index",
"for",
"option",
"in",
"settings",
":",
"if",
"option",
"[",
"'name'",
"... | Return index for provided key | [
"Return",
"index",
"for",
"provided",
"key"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L101-L107 |
27,556 | project-generator/project_generator | project_generator/tools/iar.py | IAREmbeddedWorkbenchProject._ewp_flags_set | def _ewp_flags_set(self, ewp_dic_subset, project_dic, flag_type, flag_dic):
""" Flags from misc to set to ewp project """
try:
if flag_type in project_dic['misc'].keys():
# enable commands
index_option = self._get_option(ewp_dic_subset, flag_dic['enable'])
self._set_option(ewp_dic_subset[index_option], '1')
index_option = self._get_option(ewp_dic_subset, flag_dic['set'])
if type(ewp_dic_subset[index_option]['state']) != list:
# if it's string, only one state
previous_state = ewp_dic_subset[index_option]['state']
ewp_dic_subset[index_option]['state'] = []
ewp_dic_subset[index_option]['state'].append(previous_state)
for item in project_dic['misc'][flag_type]:
ewp_dic_subset[index_option]['state'].append(item)
except KeyError:
return | python | def _ewp_flags_set(self, ewp_dic_subset, project_dic, flag_type, flag_dic):
try:
if flag_type in project_dic['misc'].keys():
# enable commands
index_option = self._get_option(ewp_dic_subset, flag_dic['enable'])
self._set_option(ewp_dic_subset[index_option], '1')
index_option = self._get_option(ewp_dic_subset, flag_dic['set'])
if type(ewp_dic_subset[index_option]['state']) != list:
# if it's string, only one state
previous_state = ewp_dic_subset[index_option]['state']
ewp_dic_subset[index_option]['state'] = []
ewp_dic_subset[index_option]['state'].append(previous_state)
for item in project_dic['misc'][flag_type]:
ewp_dic_subset[index_option]['state'].append(item)
except KeyError:
return | [
"def",
"_ewp_flags_set",
"(",
"self",
",",
"ewp_dic_subset",
",",
"project_dic",
",",
"flag_type",
",",
"flag_dic",
")",
":",
"try",
":",
"if",
"flag_type",
"in",
"project_dic",
"[",
"'misc'",
"]",
".",
"keys",
"(",
")",
":",
"# enable commands",
"index_opti... | Flags from misc to set to ewp project | [
"Flags",
"from",
"misc",
"to",
"set",
"to",
"ewp",
"project"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L153-L171 |
27,557 | project-generator/project_generator | project_generator/tools/iar.py | IAREmbeddedWorkbenchProject._ewp_files_set | def _ewp_files_set(self, ewp_dic, project_dic):
""" Fills files in the ewp dictionary """
# empty any files in the template which are not grouped
try:
ewp_dic['project']['file'] = []
except KeyError:
pass
# empty groups
ewp_dic['project']['group'] = []
i = 0
for group_name, files in project_dic['groups'].items():
ewp_dic['project']['group'].append({'name': group_name, 'file': []})
for file in files:
ewp_dic['project']['group'][i]['file'].append({'name': file})
ewp_dic['project']['group'][i]['file'] = sorted(ewp_dic['project']['group'][i]['file'], key=lambda x: os.path.basename(x['name'].lower()))
i += 1 | python | def _ewp_files_set(self, ewp_dic, project_dic):
# empty any files in the template which are not grouped
try:
ewp_dic['project']['file'] = []
except KeyError:
pass
# empty groups
ewp_dic['project']['group'] = []
i = 0
for group_name, files in project_dic['groups'].items():
ewp_dic['project']['group'].append({'name': group_name, 'file': []})
for file in files:
ewp_dic['project']['group'][i]['file'].append({'name': file})
ewp_dic['project']['group'][i]['file'] = sorted(ewp_dic['project']['group'][i]['file'], key=lambda x: os.path.basename(x['name'].lower()))
i += 1 | [
"def",
"_ewp_files_set",
"(",
"self",
",",
"ewp_dic",
",",
"project_dic",
")",
":",
"# empty any files in the template which are not grouped",
"try",
":",
"ewp_dic",
"[",
"'project'",
"]",
"[",
"'file'",
"]",
"=",
"[",
"]",
"except",
"KeyError",
":",
"pass",
"# ... | Fills files in the ewp dictionary | [
"Fills",
"files",
"in",
"the",
"ewp",
"dictionary"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L173-L188 |
27,558 | project-generator/project_generator | project_generator/tools/iar.py | IAREmbeddedWorkbenchProject._clean_xmldict_single_dic | def _clean_xmldict_single_dic(self, dictionary):
""" Every None replace by '' in the dic, as xml parsers puts None in those fiels, which is not valid for IAR """
for k, v in dictionary.items():
if v is None:
dictionary[k] = '' | python | def _clean_xmldict_single_dic(self, dictionary):
for k, v in dictionary.items():
if v is None:
dictionary[k] = '' | [
"def",
"_clean_xmldict_single_dic",
"(",
"self",
",",
"dictionary",
")",
":",
"for",
"k",
",",
"v",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"None",
":",
"dictionary",
"[",
"k",
"]",
"=",
"''"
] | Every None replace by '' in the dic, as xml parsers puts None in those fiels, which is not valid for IAR | [
"Every",
"None",
"replace",
"by",
"in",
"the",
"dic",
"as",
"xml",
"parsers",
"puts",
"None",
"in",
"those",
"fiels",
"which",
"is",
"not",
"valid",
"for",
"IAR"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L196-L200 |
27,559 | project-generator/project_generator | project_generator/tools/iar.py | IAREmbeddedWorkbench._fix_paths | def _fix_paths(self, data):
""" All paths needs to be fixed - add PROJ_DIR prefix + normalize """
data['include_paths'] = [join('$PROJ_DIR$', path) for path in data['include_paths']]
if data['linker_file']:
data['linker_file'] = join('$PROJ_DIR$', data['linker_file'])
data['groups'] = {}
for attribute in SOURCE_KEYS:
for k, v in data[attribute].items():
if k not in data['groups']:
data['groups'][k] = []
data['groups'][k].extend([join('$PROJ_DIR$', file) for file in v])
for k,v in data['include_files'].items():
if k not in data['groups']:
data['groups'][k] = []
data['groups'][k].extend([join('$PROJ_DIR$', file) for file in v])
# sort groups
data['groups'] = OrderedDict(sorted(data['groups'].items(), key=lambda t: t[0])) | python | def _fix_paths(self, data):
data['include_paths'] = [join('$PROJ_DIR$', path) for path in data['include_paths']]
if data['linker_file']:
data['linker_file'] = join('$PROJ_DIR$', data['linker_file'])
data['groups'] = {}
for attribute in SOURCE_KEYS:
for k, v in data[attribute].items():
if k not in data['groups']:
data['groups'][k] = []
data['groups'][k].extend([join('$PROJ_DIR$', file) for file in v])
for k,v in data['include_files'].items():
if k not in data['groups']:
data['groups'][k] = []
data['groups'][k].extend([join('$PROJ_DIR$', file) for file in v])
# sort groups
data['groups'] = OrderedDict(sorted(data['groups'].items(), key=lambda t: t[0])) | [
"def",
"_fix_paths",
"(",
"self",
",",
"data",
")",
":",
"data",
"[",
"'include_paths'",
"]",
"=",
"[",
"join",
"(",
"'$PROJ_DIR$'",
",",
"path",
")",
"for",
"path",
"in",
"data",
"[",
"'include_paths'",
"]",
"]",
"if",
"data",
"[",
"'linker_file'",
"]... | All paths needs to be fixed - add PROJ_DIR prefix + normalize | [
"All",
"paths",
"needs",
"to",
"be",
"fixed",
"-",
"add",
"PROJ_DIR",
"prefix",
"+",
"normalize"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L335-L354 |
27,560 | project-generator/project_generator | project_generator/tools/iar.py | IAREmbeddedWorkbench.build_project | def build_project(self):
""" Build IAR project """
# > IarBuild [project_path] -build [project_name]
proj_path = join(getcwd(), self.workspace['files']['ewp'])
if proj_path.split('.')[-1] != 'ewp':
proj_path += '.ewp'
if not os.path.exists(proj_path):
logger.debug("The file: %s does not exists, exported prior building?" % proj_path)
return -1
logger.debug("Building IAR project: %s" % proj_path)
args = [join(self.env_settings.get_env_settings('iar'), 'IarBuild.exe'), proj_path, '-build', os.path.splitext(os.path.basename(self.workspace['files']['ewp']))[0]]
logger.debug(args)
try:
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
except:
logger.error("Project: %s build failed. Please check IARBUILD path in the user_settings.py file." % self.workspace['files']['ewp'])
return -1
else:
build_log_path = os.path.join(os.path.dirname(proj_path),'build_log.txt')
with open(build_log_path, 'w') as f:
f.write(output)
num_errors = self._parse_subprocess_output(output)
if num_errors == 0:
logger.info("Project: %s build completed." % self.workspace['files']['ewp'])
return 0
else:
logger.error("Project: %s build failed with %d errors" %
(self.workspace['files']['ewp'], num_errors))
return -1 | python | def build_project(self):
# > IarBuild [project_path] -build [project_name]
proj_path = join(getcwd(), self.workspace['files']['ewp'])
if proj_path.split('.')[-1] != 'ewp':
proj_path += '.ewp'
if not os.path.exists(proj_path):
logger.debug("The file: %s does not exists, exported prior building?" % proj_path)
return -1
logger.debug("Building IAR project: %s" % proj_path)
args = [join(self.env_settings.get_env_settings('iar'), 'IarBuild.exe'), proj_path, '-build', os.path.splitext(os.path.basename(self.workspace['files']['ewp']))[0]]
logger.debug(args)
try:
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
except:
logger.error("Project: %s build failed. Please check IARBUILD path in the user_settings.py file." % self.workspace['files']['ewp'])
return -1
else:
build_log_path = os.path.join(os.path.dirname(proj_path),'build_log.txt')
with open(build_log_path, 'w') as f:
f.write(output)
num_errors = self._parse_subprocess_output(output)
if num_errors == 0:
logger.info("Project: %s build completed." % self.workspace['files']['ewp'])
return 0
else:
logger.error("Project: %s build failed with %d errors" %
(self.workspace['files']['ewp'], num_errors))
return -1 | [
"def",
"build_project",
"(",
"self",
")",
":",
"# > IarBuild [project_path] -build [project_name]",
"proj_path",
"=",
"join",
"(",
"getcwd",
"(",
")",
",",
"self",
".",
"workspace",
"[",
"'files'",
"]",
"[",
"'ewp'",
"]",
")",
"if",
"proj_path",
".",
"split",
... | Build IAR project | [
"Build",
"IAR",
"project"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L544-L575 |
27,561 | project-generator/project_generator | project_generator/tools/tool.py | Exporter.gen_file_jinja | def gen_file_jinja(self, template_file, data, output, dest_path):
if not os.path.exists(dest_path):
os.makedirs(dest_path)
output = join(dest_path, output)
logger.debug("Generating: %s" % output)
""" Fills data to the project template, using jinja2. """
env = Environment()
env.loader = FileSystemLoader(self.TEMPLATE_DIR)
# TODO: undefined=StrictUndefined - this needs fixes in templates
template = env.get_template(template_file)
target_text = template.render(data)
open(output, "w").write(target_text)
return dirname(output), output | python | def gen_file_jinja(self, template_file, data, output, dest_path):
if not os.path.exists(dest_path):
os.makedirs(dest_path)
output = join(dest_path, output)
logger.debug("Generating: %s" % output)
env = Environment()
env.loader = FileSystemLoader(self.TEMPLATE_DIR)
# TODO: undefined=StrictUndefined - this needs fixes in templates
template = env.get_template(template_file)
target_text = template.render(data)
open(output, "w").write(target_text)
return dirname(output), output | [
"def",
"gen_file_jinja",
"(",
"self",
",",
"template_file",
",",
"data",
",",
"output",
",",
"dest_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dest_path",
")",
":",
"os",
".",
"makedirs",
"(",
"dest_path",
")",
"output",
"=",
... | Fills data to the project template, using jinja2. | [
"Fills",
"data",
"to",
"the",
"project",
"template",
"using",
"jinja2",
"."
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/tool.py#L140-L154 |
27,562 | project-generator/project_generator | project_generator/tools/tool.py | Exporter._expand_data | def _expand_data(self, old_data, new_data, group):
""" data expansion - uvision needs filename and path separately. """
for file in old_data:
if file:
extension = file.split(".")[-1].lower()
if extension in self.file_types.keys():
new_data['groups'][group].append(self._expand_one_file(normpath(file),
new_data, extension))
else:
logger.debug("Filetype for file %s not recognized" % file)
if hasattr(self, '_expand_sort_key'):
new_data['groups'][group] = sorted(new_data['groups'][group],
key=self._expand_sort_key) | python | def _expand_data(self, old_data, new_data, group):
for file in old_data:
if file:
extension = file.split(".")[-1].lower()
if extension in self.file_types.keys():
new_data['groups'][group].append(self._expand_one_file(normpath(file),
new_data, extension))
else:
logger.debug("Filetype for file %s not recognized" % file)
if hasattr(self, '_expand_sort_key'):
new_data['groups'][group] = sorted(new_data['groups'][group],
key=self._expand_sort_key) | [
"def",
"_expand_data",
"(",
"self",
",",
"old_data",
",",
"new_data",
",",
"group",
")",
":",
"for",
"file",
"in",
"old_data",
":",
"if",
"file",
":",
"extension",
"=",
"file",
".",
"split",
"(",
"\".\"",
")",
"[",
"-",
"1",
"]",
".",
"lower",
"(",... | data expansion - uvision needs filename and path separately. | [
"data",
"expansion",
"-",
"uvision",
"needs",
"filename",
"and",
"path",
"separately",
"."
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/tool.py#L163-L175 |
27,563 | project-generator/project_generator | project_generator/tools/tool.py | Exporter._get_groups | def _get_groups(self, data):
""" Get all groups defined """
groups = []
for attribute in SOURCE_KEYS:
for k, v in data[attribute].items():
if k == None:
k = 'Sources'
if k not in groups:
groups.append(k)
for k, v in data['include_files'].items():
if k == None:
k = 'Includes'
if k not in groups:
groups.append(k)
return groups | python | def _get_groups(self, data):
groups = []
for attribute in SOURCE_KEYS:
for k, v in data[attribute].items():
if k == None:
k = 'Sources'
if k not in groups:
groups.append(k)
for k, v in data['include_files'].items():
if k == None:
k = 'Includes'
if k not in groups:
groups.append(k)
return groups | [
"def",
"_get_groups",
"(",
"self",
",",
"data",
")",
":",
"groups",
"=",
"[",
"]",
"for",
"attribute",
"in",
"SOURCE_KEYS",
":",
"for",
"k",
",",
"v",
"in",
"data",
"[",
"attribute",
"]",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"None",
":",... | Get all groups defined | [
"Get",
"all",
"groups",
"defined"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/tool.py#L177-L191 |
27,564 | project-generator/project_generator | project_generator/tools/tool.py | Exporter._iterate | def _iterate(self, data, expanded_data):
""" _Iterate through all data, store the result expansion in extended dictionary """
for attribute in SOURCE_KEYS:
for k, v in data[attribute].items():
if k == None:
group = 'Sources'
else:
group = k
if group in data[attribute].keys():
self._expand_data(data[attribute][group], expanded_data, group)
for k, v in data['include_files'].items():
if k == None:
group = 'Includes'
else:
group = k
self._expand_data(data['include_files'][group], expanded_data, group)
# sort groups
expanded_data['groups'] = OrderedDict(sorted(expanded_data['groups'].items(), key=lambda t: t[0])) | python | def _iterate(self, data, expanded_data):
for attribute in SOURCE_KEYS:
for k, v in data[attribute].items():
if k == None:
group = 'Sources'
else:
group = k
if group in data[attribute].keys():
self._expand_data(data[attribute][group], expanded_data, group)
for k, v in data['include_files'].items():
if k == None:
group = 'Includes'
else:
group = k
self._expand_data(data['include_files'][group], expanded_data, group)
# sort groups
expanded_data['groups'] = OrderedDict(sorted(expanded_data['groups'].items(), key=lambda t: t[0])) | [
"def",
"_iterate",
"(",
"self",
",",
"data",
",",
"expanded_data",
")",
":",
"for",
"attribute",
"in",
"SOURCE_KEYS",
":",
"for",
"k",
",",
"v",
"in",
"data",
"[",
"attribute",
"]",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"None",
":",
"group"... | _Iterate through all data, store the result expansion in extended dictionary | [
"_Iterate",
"through",
"all",
"data",
"store",
"the",
"result",
"expansion",
"in",
"extended",
"dictionary"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/tool.py#L193-L211 |
27,565 | project-generator/project_generator | project_generator/tools/eclipse.py | EclipseGnuARM.export_project | def export_project(self):
""" Processes groups and misc options specific for eclipse, and run generator """
output = copy.deepcopy(self.generated_project)
data_for_make = self.workspace.copy()
self.exporter.process_data_for_makefile(data_for_make)
output['path'], output['files']['makefile'] = self.gen_file_jinja('makefile_gcc.tmpl', data_for_make, 'Makefile', data_for_make['output_dir']['path'])
expanded_dic = self.workspace.copy()
expanded_dic['rel_path'] = data_for_make['output_dir']['rel_path']
groups = self._get_groups(expanded_dic)
expanded_dic['groups'] = {}
for group in groups:
expanded_dic['groups'][group] = []
self._iterate(self.workspace, expanded_dic)
# Project file
project_path, output['files']['cproj'] = self.gen_file_jinja(
'eclipse_makefile.cproject.tmpl', expanded_dic, '.cproject', data_for_make['output_dir']['path'])
project_path, output['files']['proj_file'] = self.gen_file_jinja(
'eclipse.project.tmpl', expanded_dic, '.project', data_for_make['output_dir']['path'])
return output | python | def export_project(self):
output = copy.deepcopy(self.generated_project)
data_for_make = self.workspace.copy()
self.exporter.process_data_for_makefile(data_for_make)
output['path'], output['files']['makefile'] = self.gen_file_jinja('makefile_gcc.tmpl', data_for_make, 'Makefile', data_for_make['output_dir']['path'])
expanded_dic = self.workspace.copy()
expanded_dic['rel_path'] = data_for_make['output_dir']['rel_path']
groups = self._get_groups(expanded_dic)
expanded_dic['groups'] = {}
for group in groups:
expanded_dic['groups'][group] = []
self._iterate(self.workspace, expanded_dic)
# Project file
project_path, output['files']['cproj'] = self.gen_file_jinja(
'eclipse_makefile.cproject.tmpl', expanded_dic, '.cproject', data_for_make['output_dir']['path'])
project_path, output['files']['proj_file'] = self.gen_file_jinja(
'eclipse.project.tmpl', expanded_dic, '.project', data_for_make['output_dir']['path'])
return output | [
"def",
"export_project",
"(",
"self",
")",
":",
"output",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"generated_project",
")",
"data_for_make",
"=",
"self",
".",
"workspace",
".",
"copy",
"(",
")",
"self",
".",
"exporter",
".",
"process_data_for_makefil... | Processes groups and misc options specific for eclipse, and run generator | [
"Processes",
"groups",
"and",
"misc",
"options",
"specific",
"for",
"eclipse",
"and",
"run",
"generator"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/eclipse.py#L65-L87 |
27,566 | project-generator/project_generator | project_generator/project.py | ProjectWorkspace.generate | def generate(self, tool, copied=False, copy=False):
""" Generates a workspace """
# copied - already done by external script, copy - do actual copy
tools = []
if not tool:
logger.info("Workspace supports one tool for all projects within.")
return -1
else:
tools = [tool]
result = 0
for export_tool in tools:
tool_export = ToolsSupported().get_tool(export_tool)
if tool_export is None:
result = -1
continue
project_export_dir_overwrite = False
if self.settings.export_location_format != self.settings.DEFAULT_EXPORT_LOCATION_FORMAT:
location_format = self.settings.export_location_format
else:
if 'export_dir' in self.workspace_settings:
location_format = self.workspace_settings['export_dir'][0]
project_export_dir_overwrite = True
else:
location_format = self.settings.export_location_format
# substitute all of the different dynamic values
location = PartialFormatter().format(location_format, **{
'project_name': self.name,
'tool': tool,
'workspace_name': self.name
})
workspace_dic = {
'projects': [],
'settings': {
'name': self.name,
'path': os.path.normpath(location),
},
}
for project in self.projects:
generated_files = {
'projects' : [],
'workspaces': [],
}
if project_export_dir_overwrite:
project.project['common']['export_dir'] = location
# Merge all dics, copy sources if required, correct output dir. This happens here
# because we need tool to set proper path (tool might be used as string template)
project._fill_export_dict(export_tool, copied)
if copy:
project._copy_sources_to_generated_destination()
project.project['export']['singular'] = False
files = tool_export(project.project['export'], self.settings).export_project()
# we gather all generated files, needed for workspace files
workspace_dic['projects'].append(files)
generated_files['projects'].append(files)
# all projects are genereated, now generate workspace files
generated_files['workspaces'] = tool_export(workspace_dic, self.settings).export_workspace()
self.generated_files[export_tool] = generated_files
return result | python | def generate(self, tool, copied=False, copy=False):
# copied - already done by external script, copy - do actual copy
tools = []
if not tool:
logger.info("Workspace supports one tool for all projects within.")
return -1
else:
tools = [tool]
result = 0
for export_tool in tools:
tool_export = ToolsSupported().get_tool(export_tool)
if tool_export is None:
result = -1
continue
project_export_dir_overwrite = False
if self.settings.export_location_format != self.settings.DEFAULT_EXPORT_LOCATION_FORMAT:
location_format = self.settings.export_location_format
else:
if 'export_dir' in self.workspace_settings:
location_format = self.workspace_settings['export_dir'][0]
project_export_dir_overwrite = True
else:
location_format = self.settings.export_location_format
# substitute all of the different dynamic values
location = PartialFormatter().format(location_format, **{
'project_name': self.name,
'tool': tool,
'workspace_name': self.name
})
workspace_dic = {
'projects': [],
'settings': {
'name': self.name,
'path': os.path.normpath(location),
},
}
for project in self.projects:
generated_files = {
'projects' : [],
'workspaces': [],
}
if project_export_dir_overwrite:
project.project['common']['export_dir'] = location
# Merge all dics, copy sources if required, correct output dir. This happens here
# because we need tool to set proper path (tool might be used as string template)
project._fill_export_dict(export_tool, copied)
if copy:
project._copy_sources_to_generated_destination()
project.project['export']['singular'] = False
files = tool_export(project.project['export'], self.settings).export_project()
# we gather all generated files, needed for workspace files
workspace_dic['projects'].append(files)
generated_files['projects'].append(files)
# all projects are genereated, now generate workspace files
generated_files['workspaces'] = tool_export(workspace_dic, self.settings).export_workspace()
self.generated_files[export_tool] = generated_files
return result | [
"def",
"generate",
"(",
"self",
",",
"tool",
",",
"copied",
"=",
"False",
",",
"copy",
"=",
"False",
")",
":",
"# copied - already done by external script, copy - do actual copy",
"tools",
"=",
"[",
"]",
"if",
"not",
"tool",
":",
"logger",
".",
"info",
"(",
... | Generates a workspace | [
"Generates",
"a",
"workspace"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L38-L106 |
27,567 | project-generator/project_generator | project_generator/project.py | Project._validate_tools | def _validate_tools(self, tool):
""" Use tool_supported or tool """
tools = []
if not tool:
if len(self.project['common']['tools_supported']) == 0:
logger.info("No tool defined.")
return -1
tools = self.project['common']['tools_supported']
else:
tools = [tool]
return tools | python | def _validate_tools(self, tool):
tools = []
if not tool:
if len(self.project['common']['tools_supported']) == 0:
logger.info("No tool defined.")
return -1
tools = self.project['common']['tools_supported']
else:
tools = [tool]
return tools | [
"def",
"_validate_tools",
"(",
"self",
",",
"tool",
")",
":",
"tools",
"=",
"[",
"]",
"if",
"not",
"tool",
":",
"if",
"len",
"(",
"self",
".",
"project",
"[",
"'common'",
"]",
"[",
"'tools_supported'",
"]",
")",
"==",
"0",
":",
"logger",
".",
"info... | Use tool_supported or tool | [
"Use",
"tool_supported",
"or",
"tool"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L339-L350 |
27,568 | project-generator/project_generator | project_generator/project.py | Project._generate_output_dir | def _generate_output_dir(settings, path):
""" This is a separate function, so that it can be more easily tested """
relpath = os.path.relpath(settings.root,path)
count = relpath.count(os.sep) + 1
return relpath+os.path.sep, count | python | def _generate_output_dir(settings, path):
relpath = os.path.relpath(settings.root,path)
count = relpath.count(os.sep) + 1
return relpath+os.path.sep, count | [
"def",
"_generate_output_dir",
"(",
"settings",
",",
"path",
")",
":",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"settings",
".",
"root",
",",
"path",
")",
"count",
"=",
"relpath",
".",
"count",
"(",
"os",
".",
"sep",
")",
"+",
"1",
"... | This is a separate function, so that it can be more easily tested | [
"This",
"is",
"a",
"separate",
"function",
"so",
"that",
"it",
"can",
"be",
"more",
"easily",
"tested"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L353-L359 |
27,569 | project-generator/project_generator | project_generator/project.py | Project._copy_sources_to_generated_destination | def _copy_sources_to_generated_destination(self):
""" Copies all project files to specified directory - generated dir """
files = []
for key in FILES_EXTENSIONS.keys():
if type(self.project['export'][key]) is dict:
for k,v in self.project['export'][key].items():
files.extend(v)
elif type(self.project['export'][key]) is list:
files.extend(self.project['export'][key])
else:
files.append(self.project['export'][key])
destination = os.path.join(self.settings.root, self.project['export']['output_dir']['path'])
if os.path.exists(destination):
shutil.rmtree(destination)
for item in files:
s = os.path.join(self.settings.root, item)
d = os.path.join(destination, item)
if os.path.isdir(s):
shutil.copytree(s,d)
else:
if not os.path.exists(os.path.dirname(d)):
os.makedirs(os.path.join(self.settings.root, os.path.dirname(d)))
shutil.copy2(s,d) | python | def _copy_sources_to_generated_destination(self):
files = []
for key in FILES_EXTENSIONS.keys():
if type(self.project['export'][key]) is dict:
for k,v in self.project['export'][key].items():
files.extend(v)
elif type(self.project['export'][key]) is list:
files.extend(self.project['export'][key])
else:
files.append(self.project['export'][key])
destination = os.path.join(self.settings.root, self.project['export']['output_dir']['path'])
if os.path.exists(destination):
shutil.rmtree(destination)
for item in files:
s = os.path.join(self.settings.root, item)
d = os.path.join(destination, item)
if os.path.isdir(s):
shutil.copytree(s,d)
else:
if not os.path.exists(os.path.dirname(d)):
os.makedirs(os.path.join(self.settings.root, os.path.dirname(d)))
shutil.copy2(s,d) | [
"def",
"_copy_sources_to_generated_destination",
"(",
"self",
")",
":",
"files",
"=",
"[",
"]",
"for",
"key",
"in",
"FILES_EXTENSIONS",
".",
"keys",
"(",
")",
":",
"if",
"type",
"(",
"self",
".",
"project",
"[",
"'export'",
"]",
"[",
"key",
"]",
")",
"... | Copies all project files to specified directory - generated dir | [
"Copies",
"all",
"project",
"files",
"to",
"specified",
"directory",
"-",
"generated",
"dir"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L475-L499 |
27,570 | project-generator/project_generator | project_generator/project.py | Project.clean | def clean(self, tool):
""" Clean a project """
tools = self._validate_tools(tool)
if tools == -1:
return -1
for current_tool in tools:
# We get the export dict formed, then use it for cleaning
self._fill_export_dict(current_tool)
path = self.project['export']['output_dir']['path']
if os.path.isdir(path):
logger.info("Cleaning directory %s" % path)
shutil.rmtree(path)
return 0 | python | def clean(self, tool):
tools = self._validate_tools(tool)
if tools == -1:
return -1
for current_tool in tools:
# We get the export dict formed, then use it for cleaning
self._fill_export_dict(current_tool)
path = self.project['export']['output_dir']['path']
if os.path.isdir(path):
logger.info("Cleaning directory %s" % path)
shutil.rmtree(path)
return 0 | [
"def",
"clean",
"(",
"self",
",",
"tool",
")",
":",
"tools",
"=",
"self",
".",
"_validate_tools",
"(",
"tool",
")",
"if",
"tools",
"==",
"-",
"1",
":",
"return",
"-",
"1",
"for",
"current_tool",
"in",
"tools",
":",
"# We get the export dict formed, then us... | Clean a project | [
"Clean",
"a",
"project"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L501-L517 |
27,571 | project-generator/project_generator | project_generator/project.py | Project.generate | def generate(self, tool, copied=False, copy=False):
""" Generates a project """
tools = self._validate_tools(tool)
if tools == -1:
return -1
generated_files = {}
result = 0
for export_tool in tools:
exporter = ToolsSupported().get_tool(export_tool)
# None is an error
if exporter is None:
result = -1
logger.debug("Tool: %s was not found" % export_tool)
continue
self._fill_export_dict(export_tool, copied)
if copy:
logger.debug("Copying sources to the output directory")
self._copy_sources_to_generated_destination()
# dump a log file if debug is enabled
if logger.isEnabledFor(logging.DEBUG):
dump_data = {}
dump_data['common'] = self.project['common']
dump_data['tool_specific'] = self.project['tool_specific']
dump_data['merged'] = self.project['export']
handler = logging.FileHandler(os.path.join(os.getcwd(), "%s.log" % self.name),"w", encoding=None, delay="true")
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.debug("\n" + yaml.dump(dump_data))
files = exporter(self.project['export'], self.settings).export_project()
generated_files[export_tool] = files
self.generated_files = generated_files
return result | python | def generate(self, tool, copied=False, copy=False):
tools = self._validate_tools(tool)
if tools == -1:
return -1
generated_files = {}
result = 0
for export_tool in tools:
exporter = ToolsSupported().get_tool(export_tool)
# None is an error
if exporter is None:
result = -1
logger.debug("Tool: %s was not found" % export_tool)
continue
self._fill_export_dict(export_tool, copied)
if copy:
logger.debug("Copying sources to the output directory")
self._copy_sources_to_generated_destination()
# dump a log file if debug is enabled
if logger.isEnabledFor(logging.DEBUG):
dump_data = {}
dump_data['common'] = self.project['common']
dump_data['tool_specific'] = self.project['tool_specific']
dump_data['merged'] = self.project['export']
handler = logging.FileHandler(os.path.join(os.getcwd(), "%s.log" % self.name),"w", encoding=None, delay="true")
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.debug("\n" + yaml.dump(dump_data))
files = exporter(self.project['export'], self.settings).export_project()
generated_files[export_tool] = files
self.generated_files = generated_files
return result | [
"def",
"generate",
"(",
"self",
",",
"tool",
",",
"copied",
"=",
"False",
",",
"copy",
"=",
"False",
")",
":",
"tools",
"=",
"self",
".",
"_validate_tools",
"(",
"tool",
")",
"if",
"tools",
"==",
"-",
"1",
":",
"return",
"-",
"1",
"generated_files",
... | Generates a project | [
"Generates",
"a",
"project"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L519-L555 |
27,572 | project-generator/project_generator | project_generator/project.py | Project.build | def build(self, tool):
"""build the project"""
tools = self._validate_tools(tool)
if tools == -1:
return -1
result = 0
for build_tool in tools:
builder = ToolsSupported().get_tool(build_tool)
# None is an error
if builder is None:
logger.debug("Tool: %s was not found" % builder)
result = -1
continue
logger.debug("Building for tool: %s", build_tool)
logger.debug(self.generated_files)
if builder(self.generated_files[build_tool], self.settings).build_project() == -1:
# if one fails, set to -1 to report
result = -1
return result | python | def build(self, tool):
tools = self._validate_tools(tool)
if tools == -1:
return -1
result = 0
for build_tool in tools:
builder = ToolsSupported().get_tool(build_tool)
# None is an error
if builder is None:
logger.debug("Tool: %s was not found" % builder)
result = -1
continue
logger.debug("Building for tool: %s", build_tool)
logger.debug(self.generated_files)
if builder(self.generated_files[build_tool], self.settings).build_project() == -1:
# if one fails, set to -1 to report
result = -1
return result | [
"def",
"build",
"(",
"self",
",",
"tool",
")",
":",
"tools",
"=",
"self",
".",
"_validate_tools",
"(",
"tool",
")",
"if",
"tools",
"==",
"-",
"1",
":",
"return",
"-",
"1",
"result",
"=",
"0",
"for",
"build_tool",
"in",
"tools",
":",
"builder",
"=",... | build the project | [
"build",
"the",
"project"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L557-L579 |
27,573 | project-generator/project_generator | project_generator/project.py | Project.get_generated_project_files | def get_generated_project_files(self, tool):
""" Get generated project files, the content depends on a tool. Look at tool implementation """
exporter = ToolsSupported().get_tool(tool)
return exporter(self.generated_files[tool], self.settings).get_generated_project_files() | python | def get_generated_project_files(self, tool):
exporter = ToolsSupported().get_tool(tool)
return exporter(self.generated_files[tool], self.settings).get_generated_project_files() | [
"def",
"get_generated_project_files",
"(",
"self",
",",
"tool",
")",
":",
"exporter",
"=",
"ToolsSupported",
"(",
")",
".",
"get_tool",
"(",
"tool",
")",
"return",
"exporter",
"(",
"self",
".",
"generated_files",
"[",
"tool",
"]",
",",
"self",
".",
"settin... | Get generated project files, the content depends on a tool. Look at tool implementation | [
"Get",
"generated",
"project",
"files",
"the",
"content",
"depends",
"on",
"a",
"tool",
".",
"Look",
"at",
"tool",
"implementation"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L581-L585 |
27,574 | project-generator/project_generator | project_generator/tools/makearmcc.py | MakefileArmcc.export_project | def export_project(self):
""" Processes misc options specific for GCC ARM, and run generator """
generated_projects = deepcopy(self.generated_projects)
self.process_data_for_makefile(self.workspace)
generated_projects['path'], generated_projects['files']['makefile'] = self.gen_file_jinja('makefile_armcc.tmpl', self.workspace, 'Makefile', self.workspace['output_dir']['path'])
return generated_projects | python | def export_project(self):
generated_projects = deepcopy(self.generated_projects)
self.process_data_for_makefile(self.workspace)
generated_projects['path'], generated_projects['files']['makefile'] = self.gen_file_jinja('makefile_armcc.tmpl', self.workspace, 'Makefile', self.workspace['output_dir']['path'])
return generated_projects | [
"def",
"export_project",
"(",
"self",
")",
":",
"generated_projects",
"=",
"deepcopy",
"(",
"self",
".",
"generated_projects",
")",
"self",
".",
"process_data_for_makefile",
"(",
"self",
".",
"workspace",
")",
"generated_projects",
"[",
"'path'",
"]",
",",
"gene... | Processes misc options specific for GCC ARM, and run generator | [
"Processes",
"misc",
"options",
"specific",
"for",
"GCC",
"ARM",
"and",
"run",
"generator"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/makearmcc.py#L35-L40 |
27,575 | project-generator/project_generator | project_generator/tools/makefile.py | MakefileTool._parse_specific_options | def _parse_specific_options(self, data):
""" Parse all specific setttings. """
data['common_flags'] = []
data['ld_flags'] = []
data['c_flags'] = []
data['cxx_flags'] = []
data['asm_flags'] = []
for k, v in data['misc'].items():
if type(v) is list:
if k not in data:
data[k] = []
data[k].extend(v)
else:
if k not in data:
data[k] = ''
data[k] = v | python | def _parse_specific_options(self, data):
data['common_flags'] = []
data['ld_flags'] = []
data['c_flags'] = []
data['cxx_flags'] = []
data['asm_flags'] = []
for k, v in data['misc'].items():
if type(v) is list:
if k not in data:
data[k] = []
data[k].extend(v)
else:
if k not in data:
data[k] = ''
data[k] = v | [
"def",
"_parse_specific_options",
"(",
"self",
",",
"data",
")",
":",
"data",
"[",
"'common_flags'",
"]",
"=",
"[",
"]",
"data",
"[",
"'ld_flags'",
"]",
"=",
"[",
"]",
"data",
"[",
"'c_flags'",
"]",
"=",
"[",
"]",
"data",
"[",
"'cxx_flags'",
"]",
"="... | Parse all specific setttings. | [
"Parse",
"all",
"specific",
"setttings",
"."
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/makefile.py#L54-L69 |
27,576 | project-generator/project_generator | project_generator/tools/sublimetext.py | SublimeTextMakeGccARM.export_project | def export_project(self):
""" Processes misc options specific for GCC ARM, and run generator. """
output = copy.deepcopy(self.generated_project)
self.process_data_for_makefile(self.workspace)
self._fix_sublime_paths(self.workspace)
self.workspace['linker_options'] =[]
output['path'], output['files']['makefile'] = self.gen_file_jinja('makefile_gcc.tmpl', self.workspace, 'Makefile', self.workspace['output_dir']['path'])
self.workspace['buildsys_name'] = 'Make'
self.workspace['buildsys_cmd'] = 'make all'
path, output['files']['sublimetext'] = self.gen_file_jinja(
'sublimetext.sublime-project.tmpl', self.workspace, '%s.sublime-project' % self.workspace['name'], self.workspace['output_dir']['path'])
generated_projects = output
return generated_projects | python | def export_project(self):
output = copy.deepcopy(self.generated_project)
self.process_data_for_makefile(self.workspace)
self._fix_sublime_paths(self.workspace)
self.workspace['linker_options'] =[]
output['path'], output['files']['makefile'] = self.gen_file_jinja('makefile_gcc.tmpl', self.workspace, 'Makefile', self.workspace['output_dir']['path'])
self.workspace['buildsys_name'] = 'Make'
self.workspace['buildsys_cmd'] = 'make all'
path, output['files']['sublimetext'] = self.gen_file_jinja(
'sublimetext.sublime-project.tmpl', self.workspace, '%s.sublime-project' % self.workspace['name'], self.workspace['output_dir']['path'])
generated_projects = output
return generated_projects | [
"def",
"export_project",
"(",
"self",
")",
":",
"output",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"generated_project",
")",
"self",
".",
"process_data_for_makefile",
"(",
"self",
".",
"workspace",
")",
"self",
".",
"_fix_sublime_paths",
"(",
"self",
... | Processes misc options specific for GCC ARM, and run generator. | [
"Processes",
"misc",
"options",
"specific",
"for",
"GCC",
"ARM",
"and",
"run",
"generator",
"."
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/sublimetext.py#L46-L61 |
27,577 | project-generator/project_generator | project_generator/util.py | fix_paths | def fix_paths(project_data, rel_path, extensions):
""" Fix paths for extension list """
norm_func = lambda path : os.path.normpath(os.path.join(rel_path, path))
for key in extensions:
if type(project_data[key]) is dict:
for k,v in project_data[key].items():
project_data[key][k] = [norm_func(i) for i in v]
elif type(project_data[key]) is list:
project_data[key] = [norm_func(i) for i in project_data[key]]
else:
project_data[key] = norm_func(project_data[key]) | python | def fix_paths(project_data, rel_path, extensions):
norm_func = lambda path : os.path.normpath(os.path.join(rel_path, path))
for key in extensions:
if type(project_data[key]) is dict:
for k,v in project_data[key].items():
project_data[key][k] = [norm_func(i) for i in v]
elif type(project_data[key]) is list:
project_data[key] = [norm_func(i) for i in project_data[key]]
else:
project_data[key] = norm_func(project_data[key]) | [
"def",
"fix_paths",
"(",
"project_data",
",",
"rel_path",
",",
"extensions",
")",
":",
"norm_func",
"=",
"lambda",
"path",
":",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"rel_path",
",",
"path",
")",
")",
"for",
"k... | Fix paths for extension list | [
"Fix",
"paths",
"for",
"extension",
"list"
] | a361be16eeb5a8829ff5cd26850ddd4b264296fe | https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/util.py#L91-L101 |
27,578 | RusticiSoftware/TinCanPython | tincan/typed_list.py | TypedList._make_cls | def _make_cls(self, value):
"""If value is not instance of self._cls, converts and returns
it. Otherwise, returns value.
:param value: the thing to make a self._cls from
:rtype self._cls
"""
if isinstance(value, self._cls):
return value
return self._cls(value) | python | def _make_cls(self, value):
if isinstance(value, self._cls):
return value
return self._cls(value) | [
"def",
"_make_cls",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"self",
".",
"_cls",
")",
":",
"return",
"value",
"return",
"self",
".",
"_cls",
"(",
"value",
")"
] | If value is not instance of self._cls, converts and returns
it. Otherwise, returns value.
:param value: the thing to make a self._cls from
:rtype self._cls | [
"If",
"value",
"is",
"not",
"instance",
"of",
"self",
".",
"_cls",
"converts",
"and",
"returns",
"it",
".",
"Otherwise",
"returns",
"value",
"."
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/typed_list.py#L45-L54 |
27,579 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS._send_request | def _send_request(self, request):
"""Establishes connection and returns http response based off of request.
:param request: HTTPRequest object
:type request: :class:`tincan.http_request.HTTPRequest`
:returns: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
headers = {"X-Experience-API-Version": self.version}
if self.auth is not None:
headers["Authorization"] = self.auth
headers.update(request.headers)
params = request.query_params
params = {k: unicode(params[k]).encode('utf-8') for k in params.keys()}
params = urllib.urlencode(params)
if request.resource.startswith('http'):
url = request.resource
else:
url = self.endpoint
url += request.resource
parsed = urlparse(url)
if parsed.scheme == "https":
web_req = httplib.HTTPSConnection(parsed.hostname, parsed.port)
else:
web_req = httplib.HTTPConnection(parsed.hostname, parsed.port)
path = parsed.path
if parsed.query or parsed.path:
path += "?"
if parsed.query:
path += parsed.query
if params:
path += params
if hasattr(request, "content") and request.content is not None:
web_req.request(
method=request.method,
url=path,
body=request.content,
headers=headers,
)
else:
web_req.request(
method=request.method,
url=path,
headers=headers,
)
response = web_req.getresponse()
data = response.read()
web_req.close()
if (200 <= response.status < 300
or (response.status == 404
and hasattr(request, "ignore404")
and request.ignore404)):
success = True
else:
success = False
return LRSResponse(
success=success,
request=request,
response=response,
data=data,
) | python | def _send_request(self, request):
headers = {"X-Experience-API-Version": self.version}
if self.auth is not None:
headers["Authorization"] = self.auth
headers.update(request.headers)
params = request.query_params
params = {k: unicode(params[k]).encode('utf-8') for k in params.keys()}
params = urllib.urlencode(params)
if request.resource.startswith('http'):
url = request.resource
else:
url = self.endpoint
url += request.resource
parsed = urlparse(url)
if parsed.scheme == "https":
web_req = httplib.HTTPSConnection(parsed.hostname, parsed.port)
else:
web_req = httplib.HTTPConnection(parsed.hostname, parsed.port)
path = parsed.path
if parsed.query or parsed.path:
path += "?"
if parsed.query:
path += parsed.query
if params:
path += params
if hasattr(request, "content") and request.content is not None:
web_req.request(
method=request.method,
url=path,
body=request.content,
headers=headers,
)
else:
web_req.request(
method=request.method,
url=path,
headers=headers,
)
response = web_req.getresponse()
data = response.read()
web_req.close()
if (200 <= response.status < 300
or (response.status == 404
and hasattr(request, "ignore404")
and request.ignore404)):
success = True
else:
success = False
return LRSResponse(
success=success,
request=request,
response=response,
data=data,
) | [
"def",
"_send_request",
"(",
"self",
",",
"request",
")",
":",
"headers",
"=",
"{",
"\"X-Experience-API-Version\"",
":",
"self",
".",
"version",
"}",
"if",
"self",
".",
"auth",
"is",
"not",
"None",
":",
"headers",
"[",
"\"Authorization\"",
"]",
"=",
"self"... | Establishes connection and returns http response based off of request.
:param request: HTTPRequest object
:type request: :class:`tincan.http_request.HTTPRequest`
:returns: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Establishes",
"connection",
"and",
"returns",
"http",
"response",
"based",
"off",
"of",
"request",
"."
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L89-L160 |
27,580 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.about | def about(self):
"""Gets about response from LRS
:return: LRS Response object with the returned LRS about object as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="GET",
resource="about"
)
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = About.from_json(lrs_response.data)
return lrs_response | python | def about(self):
request = HTTPRequest(
method="GET",
resource="about"
)
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = About.from_json(lrs_response.data)
return lrs_response | [
"def",
"about",
"(",
"self",
")",
":",
"request",
"=",
"HTTPRequest",
"(",
"method",
"=",
"\"GET\"",
",",
"resource",
"=",
"\"about\"",
")",
"lrs_response",
"=",
"self",
".",
"_send_request",
"(",
"request",
")",
"if",
"lrs_response",
".",
"success",
":",
... | Gets about response from LRS
:return: LRS Response object with the returned LRS about object as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Gets",
"about",
"response",
"from",
"LRS"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L162-L177 |
27,581 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.save_statement | def save_statement(self, statement):
"""Save statement to LRS and update statement id if necessary
:param statement: Statement object to be saved
:type statement: :class:`tincan.statement.Statement`
:return: LRS Response object with the saved statement as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(statement, Statement):
statement = Statement(statement)
request = HTTPRequest(
method="POST",
resource="statements"
)
if statement.id is not None:
request.method = "PUT"
request.query_params["statementId"] = statement.id
request.headers["Content-Type"] = "application/json"
request.content = statement.to_json(self.version)
lrs_response = self._send_request(request)
if lrs_response.success:
if statement.id is None:
statement.id = json.loads(lrs_response.data)[0]
lrs_response.content = statement
return lrs_response | python | def save_statement(self, statement):
if not isinstance(statement, Statement):
statement = Statement(statement)
request = HTTPRequest(
method="POST",
resource="statements"
)
if statement.id is not None:
request.method = "PUT"
request.query_params["statementId"] = statement.id
request.headers["Content-Type"] = "application/json"
request.content = statement.to_json(self.version)
lrs_response = self._send_request(request)
if lrs_response.success:
if statement.id is None:
statement.id = json.loads(lrs_response.data)[0]
lrs_response.content = statement
return lrs_response | [
"def",
"save_statement",
"(",
"self",
",",
"statement",
")",
":",
"if",
"not",
"isinstance",
"(",
"statement",
",",
"Statement",
")",
":",
"statement",
"=",
"Statement",
"(",
"statement",
")",
"request",
"=",
"HTTPRequest",
"(",
"method",
"=",
"\"POST\"",
... | Save statement to LRS and update statement id if necessary
:param statement: Statement object to be saved
:type statement: :class:`tincan.statement.Statement`
:return: LRS Response object with the saved statement as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Save",
"statement",
"to",
"LRS",
"and",
"update",
"statement",
"id",
"if",
"necessary"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L179-L208 |
27,582 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.save_statements | def save_statements(self, statements):
"""Save statements to LRS and update their statement id's
:param statements: A list of statement objects to be saved
:type statements: :class:`StatementList`
:return: LRS Response object with the saved list of statements as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(statements, StatementList):
statements = StatementList(statements)
request = HTTPRequest(
method="POST",
resource="statements"
)
request.headers["Content-Type"] = "application/json"
request.content = statements.to_json()
lrs_response = self._send_request(request)
if lrs_response.success:
id_list = json.loads(lrs_response.data)
for s, statement_id in zip(statements, id_list):
s.id = statement_id
lrs_response.content = statements
return lrs_response | python | def save_statements(self, statements):
if not isinstance(statements, StatementList):
statements = StatementList(statements)
request = HTTPRequest(
method="POST",
resource="statements"
)
request.headers["Content-Type"] = "application/json"
request.content = statements.to_json()
lrs_response = self._send_request(request)
if lrs_response.success:
id_list = json.loads(lrs_response.data)
for s, statement_id in zip(statements, id_list):
s.id = statement_id
lrs_response.content = statements
return lrs_response | [
"def",
"save_statements",
"(",
"self",
",",
"statements",
")",
":",
"if",
"not",
"isinstance",
"(",
"statements",
",",
"StatementList",
")",
":",
"statements",
"=",
"StatementList",
"(",
"statements",
")",
"request",
"=",
"HTTPRequest",
"(",
"method",
"=",
"... | Save statements to LRS and update their statement id's
:param statements: A list of statement objects to be saved
:type statements: :class:`StatementList`
:return: LRS Response object with the saved list of statements as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Save",
"statements",
"to",
"LRS",
"and",
"update",
"their",
"statement",
"id",
"s"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L210-L238 |
27,583 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.retrieve_statement | def retrieve_statement(self, statement_id):
"""Retrieve a statement from the server from its id
:param statement_id: The UUID of the desired statement
:type statement_id: str | unicode
:return: LRS Response object with the retrieved statement as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="GET",
resource="statements"
)
request.query_params["statementId"] = statement_id
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = Statement.from_json(lrs_response.data)
return lrs_response | python | def retrieve_statement(self, statement_id):
request = HTTPRequest(
method="GET",
resource="statements"
)
request.query_params["statementId"] = statement_id
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = Statement.from_json(lrs_response.data)
return lrs_response | [
"def",
"retrieve_statement",
"(",
"self",
",",
"statement_id",
")",
":",
"request",
"=",
"HTTPRequest",
"(",
"method",
"=",
"\"GET\"",
",",
"resource",
"=",
"\"statements\"",
")",
"request",
".",
"query_params",
"[",
"\"statementId\"",
"]",
"=",
"statement_id",
... | Retrieve a statement from the server from its id
:param statement_id: The UUID of the desired statement
:type statement_id: str | unicode
:return: LRS Response object with the retrieved statement as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Retrieve",
"a",
"statement",
"from",
"the",
"server",
"from",
"its",
"id"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L240-L259 |
27,584 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.query_statements | def query_statements(self, query):
"""Query the LRS for statements with specified parameters
:param query: Dictionary of query parameters and their values
:type query: dict
:return: LRS Response object with the returned StatementsResult object as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
.. note::
Optional query parameters are\n
**statementId:** (*str*) ID of the Statement to fetch
**voidedStatementId:** (*str*) ID of the voided Statement to fetch
**agent:** (*Agent* |*Group*) Filter to return Statements for which the
specified Agent or Group is the Actor
**verb:** (*Verb id IRI*) Filter to return Statements matching the verb id
**activity:** (*Activity id IRI*) Filter to return Statements for which the
specified Activity is the Object
**registration:** (*UUID*) Filter to return Statements matching the specified registration ID
**related_activities:** (*bool*) Include Statements for which the Object,
Context Activities or any Sub-Statement
properties match the specified Activity
**related_agents:** (*bool*) Include Statements for which the Actor, Object,
Authority, Instructor, Team, or any Sub-Statement properties match the specified Agent
**since:** (*datetime*) Filter to return Statements stored since the specified datetime
**until:** (*datetime*) Filter to return Statements stored at or before the specified datetime
**limit:** (*positive int*) Allow <limit> Statements to be returned. 0 indicates the
maximum supported by the LRS
**format:** (*str* {"ids"|"exact"|"canonical"}) Manipulates how the LRS handles
importing and returning the statements
**attachments:** (*bool*) If true, the LRS will use multipart responses and include
all attachment data per Statement returned.
Otherwise, application/json is used and no attachment information will be returned
**ascending:** (*bool*) If true, the LRS will return results in ascending order of
stored time (oldest first)
"""
params = {}
param_keys = [
"registration",
"since",
"until",
"limit",
"ascending",
"related_activities",
"related_agents",
"format",
"attachments",
]
for k, v in query.iteritems():
if v is not None:
if k == "agent":
params[k] = v.to_json(self.version)
elif k == "verb" or k == "activity":
params[k] = v.id
elif k in param_keys:
params[k] = v
request = HTTPRequest(
method="GET",
resource="statements"
)
request.query_params = params
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = StatementsResult.from_json(lrs_response.data)
return lrs_response | python | def query_statements(self, query):
params = {}
param_keys = [
"registration",
"since",
"until",
"limit",
"ascending",
"related_activities",
"related_agents",
"format",
"attachments",
]
for k, v in query.iteritems():
if v is not None:
if k == "agent":
params[k] = v.to_json(self.version)
elif k == "verb" or k == "activity":
params[k] = v.id
elif k in param_keys:
params[k] = v
request = HTTPRequest(
method="GET",
resource="statements"
)
request.query_params = params
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = StatementsResult.from_json(lrs_response.data)
return lrs_response | [
"def",
"query_statements",
"(",
"self",
",",
"query",
")",
":",
"params",
"=",
"{",
"}",
"param_keys",
"=",
"[",
"\"registration\"",
",",
"\"since\"",
",",
"\"until\"",
",",
"\"limit\"",
",",
"\"ascending\"",
",",
"\"related_activities\"",
",",
"\"related_agents... | Query the LRS for statements with specified parameters
:param query: Dictionary of query parameters and their values
:type query: dict
:return: LRS Response object with the returned StatementsResult object as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
.. note::
Optional query parameters are\n
**statementId:** (*str*) ID of the Statement to fetch
**voidedStatementId:** (*str*) ID of the voided Statement to fetch
**agent:** (*Agent* |*Group*) Filter to return Statements for which the
specified Agent or Group is the Actor
**verb:** (*Verb id IRI*) Filter to return Statements matching the verb id
**activity:** (*Activity id IRI*) Filter to return Statements for which the
specified Activity is the Object
**registration:** (*UUID*) Filter to return Statements matching the specified registration ID
**related_activities:** (*bool*) Include Statements for which the Object,
Context Activities or any Sub-Statement
properties match the specified Activity
**related_agents:** (*bool*) Include Statements for which the Actor, Object,
Authority, Instructor, Team, or any Sub-Statement properties match the specified Agent
**since:** (*datetime*) Filter to return Statements stored since the specified datetime
**until:** (*datetime*) Filter to return Statements stored at or before the specified datetime
**limit:** (*positive int*) Allow <limit> Statements to be returned. 0 indicates the
maximum supported by the LRS
**format:** (*str* {"ids"|"exact"|"canonical"}) Manipulates how the LRS handles
importing and returning the statements
**attachments:** (*bool*) If true, the LRS will use multipart responses and include
all attachment data per Statement returned.
Otherwise, application/json is used and no attachment information will be returned
**ascending:** (*bool*) If true, the LRS will return results in ascending order of
stored time (oldest first) | [
"Query",
"the",
"LRS",
"for",
"statements",
"with",
"specified",
"parameters"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L282-L351 |
27,585 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.more_statements | def more_statements(self, more_url):
"""Query the LRS for more statements
:param more_url: URL from a StatementsResult object used to retrieve more statements
:type more_url: str | unicode
:return: LRS Response object with the returned StatementsResult object as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if isinstance(more_url, StatementsResult):
more_url = more_url.more
more_url = self.get_endpoint_server_root() + more_url
request = HTTPRequest(
method="GET",
resource=more_url
)
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = StatementsResult.from_json(lrs_response.data)
return lrs_response | python | def more_statements(self, more_url):
if isinstance(more_url, StatementsResult):
more_url = more_url.more
more_url = self.get_endpoint_server_root() + more_url
request = HTTPRequest(
method="GET",
resource=more_url
)
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = StatementsResult.from_json(lrs_response.data)
return lrs_response | [
"def",
"more_statements",
"(",
"self",
",",
"more_url",
")",
":",
"if",
"isinstance",
"(",
"more_url",
",",
"StatementsResult",
")",
":",
"more_url",
"=",
"more_url",
".",
"more",
"more_url",
"=",
"self",
".",
"get_endpoint_server_root",
"(",
")",
"+",
"more... | Query the LRS for more statements
:param more_url: URL from a StatementsResult object used to retrieve more statements
:type more_url: str | unicode
:return: LRS Response object with the returned StatementsResult object as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Query",
"the",
"LRS",
"for",
"more",
"statements"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L353-L376 |
27,586 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.retrieve_state_ids | def retrieve_state_ids(self, activity, agent, registration=None, since=None):
"""Retrieve state id's from the LRS with the provided parameters
:param activity: Activity object of desired states
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of desired states
:type agent: :class:`tincan.agent.Agent`
:param registration: Registration UUID of desired states
:type registration: str | unicode
:param since: Retrieve state id's since this time
:type since: str | unicode
:return: LRS Response object with the retrieved state id's as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(activity, Activity):
activity = Activity(activity)
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="GET",
resource="activities/state"
)
request.query_params = {
"activityId": activity.id,
"agent": agent.to_json(self.version)
}
if registration is not None:
request.query_params["registration"] = registration
if since is not None:
request.query_params["since"] = since
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = json.loads(lrs_response.data)
return lrs_response | python | def retrieve_state_ids(self, activity, agent, registration=None, since=None):
if not isinstance(activity, Activity):
activity = Activity(activity)
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="GET",
resource="activities/state"
)
request.query_params = {
"activityId": activity.id,
"agent": agent.to_json(self.version)
}
if registration is not None:
request.query_params["registration"] = registration
if since is not None:
request.query_params["since"] = since
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = json.loads(lrs_response.data)
return lrs_response | [
"def",
"retrieve_state_ids",
"(",
"self",
",",
"activity",
",",
"agent",
",",
"registration",
"=",
"None",
",",
"since",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"activity",
",",
"Activity",
")",
":",
"activity",
"=",
"Activity",
"(",
"acti... | Retrieve state id's from the LRS with the provided parameters
:param activity: Activity object of desired states
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of desired states
:type agent: :class:`tincan.agent.Agent`
:param registration: Registration UUID of desired states
:type registration: str | unicode
:param since: Retrieve state id's since this time
:type since: str | unicode
:return: LRS Response object with the retrieved state id's as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Retrieve",
"state",
"id",
"s",
"from",
"the",
"LRS",
"with",
"the",
"provided",
"parameters"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L378-L417 |
27,587 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.retrieve_state | def retrieve_state(self, activity, agent, state_id, registration=None):
"""Retrieve state from LRS with the provided parameters
:param activity: Activity object of desired state
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of desired state
:type agent: :class:`tincan.agent.Agent`
:param state_id: UUID of desired state
:type state_id: str | unicode
:param registration: registration UUID of desired state
:type registration: str | unicode
:return: LRS Response object with retrieved state document as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(activity, Activity):
activity = Activity(activity)
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="GET",
resource="activities/state",
ignore404=True
)
request.query_params = {
"activityId": activity.id,
"agent": agent.to_json(self.version),
"stateId": state_id
}
if registration is not None:
request.query_params["registration"] = registration
lrs_response = self._send_request(request)
if lrs_response.success:
doc = StateDocument(
id=state_id,
content=lrs_response.data,
activity=activity,
agent=agent
)
if registration is not None:
doc.registration = registration
headers = lrs_response.response.getheaders()
if "lastModified" in headers and headers["lastModified"] is not None:
doc.timestamp = headers["lastModified"]
if "contentType" in headers and headers["contentType"] is not None:
doc.content_type = headers["contentType"]
if "etag" in headers and headers["etag"] is not None:
doc.etag = headers["etag"]
lrs_response.content = doc
return lrs_response | python | def retrieve_state(self, activity, agent, state_id, registration=None):
if not isinstance(activity, Activity):
activity = Activity(activity)
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="GET",
resource="activities/state",
ignore404=True
)
request.query_params = {
"activityId": activity.id,
"agent": agent.to_json(self.version),
"stateId": state_id
}
if registration is not None:
request.query_params["registration"] = registration
lrs_response = self._send_request(request)
if lrs_response.success:
doc = StateDocument(
id=state_id,
content=lrs_response.data,
activity=activity,
agent=agent
)
if registration is not None:
doc.registration = registration
headers = lrs_response.response.getheaders()
if "lastModified" in headers and headers["lastModified"] is not None:
doc.timestamp = headers["lastModified"]
if "contentType" in headers and headers["contentType"] is not None:
doc.content_type = headers["contentType"]
if "etag" in headers and headers["etag"] is not None:
doc.etag = headers["etag"]
lrs_response.content = doc
return lrs_response | [
"def",
"retrieve_state",
"(",
"self",
",",
"activity",
",",
"agent",
",",
"state_id",
",",
"registration",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"activity",
",",
"Activity",
")",
":",
"activity",
"=",
"Activity",
"(",
"activity",
")",
"i... | Retrieve state from LRS with the provided parameters
:param activity: Activity object of desired state
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of desired state
:type agent: :class:`tincan.agent.Agent`
:param state_id: UUID of desired state
:type state_id: str | unicode
:param registration: registration UUID of desired state
:type registration: str | unicode
:return: LRS Response object with retrieved state document as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Retrieve",
"state",
"from",
"LRS",
"with",
"the",
"provided",
"parameters"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L419-L476 |
27,588 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.save_state | def save_state(self, state):
"""Save a state doc to the LRS
:param state: State document to be saved
:type state: :class:`tincan.documents.state_document.StateDocument`
:return: LRS Response object with saved state as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="PUT",
resource="activities/state",
content=state.content,
)
if state.content_type is not None:
request.headers["Content-Type"] = state.content_type
else:
request.headers["Content-Type"] = "application/octet-stream"
if state.etag is not None:
request.headers["If-Match"] = state.etag
request.query_params = {
"stateId": state.id,
"activityId": state.activity.id,
"agent": state.agent.to_json(self.version)
}
lrs_response = self._send_request(request)
lrs_response.content = state
return self._send_request(request) | python | def save_state(self, state):
request = HTTPRequest(
method="PUT",
resource="activities/state",
content=state.content,
)
if state.content_type is not None:
request.headers["Content-Type"] = state.content_type
else:
request.headers["Content-Type"] = "application/octet-stream"
if state.etag is not None:
request.headers["If-Match"] = state.etag
request.query_params = {
"stateId": state.id,
"activityId": state.activity.id,
"agent": state.agent.to_json(self.version)
}
lrs_response = self._send_request(request)
lrs_response.content = state
return self._send_request(request) | [
"def",
"save_state",
"(",
"self",
",",
"state",
")",
":",
"request",
"=",
"HTTPRequest",
"(",
"method",
"=",
"\"PUT\"",
",",
"resource",
"=",
"\"activities/state\"",
",",
"content",
"=",
"state",
".",
"content",
",",
")",
"if",
"state",
".",
"content_type"... | Save a state doc to the LRS
:param state: State document to be saved
:type state: :class:`tincan.documents.state_document.StateDocument`
:return: LRS Response object with saved state as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Save",
"a",
"state",
"doc",
"to",
"the",
"LRS"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L478-L507 |
27,589 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS._delete_state | def _delete_state(self, activity, agent, state_id=None, registration=None, etag=None):
"""Private method to delete a specified state from the LRS
:param activity: Activity object of state to be deleted
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of state to be deleted
:type agent: :class:`tincan.agent.Agent`
:param state_id: UUID of state to be deleted
:type state_id: str | unicode
:param registration: registration UUID of state to be deleted
:type registration: str | unicode
:param etag: etag of state to be deleted
:type etag: str | unicode
:return: LRS Response object with deleted state as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(activity, Activity):
activity = Activity(activity)
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="DELETE",
resource="activities/state"
)
if etag is not None:
request.headers["If-Match"] = etag
request.query_params = {
"activityId": activity.id,
"agent": agent.to_json(self.version)
}
if state_id is not None:
request.query_params["stateId"] = state_id
if registration is not None:
request.query_params["registration"] = registration
lrs_response = self._send_request(request)
return lrs_response | python | def _delete_state(self, activity, agent, state_id=None, registration=None, etag=None):
if not isinstance(activity, Activity):
activity = Activity(activity)
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="DELETE",
resource="activities/state"
)
if etag is not None:
request.headers["If-Match"] = etag
request.query_params = {
"activityId": activity.id,
"agent": agent.to_json(self.version)
}
if state_id is not None:
request.query_params["stateId"] = state_id
if registration is not None:
request.query_params["registration"] = registration
lrs_response = self._send_request(request)
return lrs_response | [
"def",
"_delete_state",
"(",
"self",
",",
"activity",
",",
"agent",
",",
"state_id",
"=",
"None",
",",
"registration",
"=",
"None",
",",
"etag",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"activity",
",",
"Activity",
")",
":",
"activity",
"... | Private method to delete a specified state from the LRS
:param activity: Activity object of state to be deleted
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of state to be deleted
:type agent: :class:`tincan.agent.Agent`
:param state_id: UUID of state to be deleted
:type state_id: str | unicode
:param registration: registration UUID of state to be deleted
:type registration: str | unicode
:param etag: etag of state to be deleted
:type etag: str | unicode
:return: LRS Response object with deleted state as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Private",
"method",
"to",
"delete",
"a",
"specified",
"state",
"from",
"the",
"LRS"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L509-L551 |
27,590 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.delete_state | def delete_state(self, state):
"""Delete a specified state from the LRS
:param state: State document to be deleted
:type state: :class:`tincan.documents.state_document.StateDocument`
:return: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
return self._delete_state(
activity=state.activity,
agent=state.agent,
state_id=state.id,
etag=state.etag
) | python | def delete_state(self, state):
return self._delete_state(
activity=state.activity,
agent=state.agent,
state_id=state.id,
etag=state.etag
) | [
"def",
"delete_state",
"(",
"self",
",",
"state",
")",
":",
"return",
"self",
".",
"_delete_state",
"(",
"activity",
"=",
"state",
".",
"activity",
",",
"agent",
"=",
"state",
".",
"agent",
",",
"state_id",
"=",
"state",
".",
"id",
",",
"etag",
"=",
... | Delete a specified state from the LRS
:param state: State document to be deleted
:type state: :class:`tincan.documents.state_document.StateDocument`
:return: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Delete",
"a",
"specified",
"state",
"from",
"the",
"LRS"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L553-L566 |
27,591 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.retrieve_activity_profile | def retrieve_activity_profile(self, activity, profile_id):
"""Retrieve activity profile with the specified parameters
:param activity: Activity object of the desired activity profile
:type activity: :class:`tincan.activity.Activity`
:param profile_id: UUID of the desired profile
:type profile_id: str | unicode
:return: LRS Response object with an activity profile doc as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(activity, Activity):
activity = Activity(activity)
request = HTTPRequest(
method="GET",
resource="activities/profile",
ignore404=True
)
request.query_params = {
"profileId": profile_id,
"activityId": activity.id
}
lrs_response = self._send_request(request)
if lrs_response.success:
doc = ActivityProfileDocument(
id=profile_id,
content=lrs_response.data,
activity=activity
)
headers = lrs_response.response.getheaders()
if "lastModified" in headers and headers["lastModified"] is not None:
doc.timestamp = headers["lastModified"]
if "contentType" in headers and headers["contentType"] is not None:
doc.content_type = headers["contentType"]
if "etag" in headers and headers["etag"] is not None:
doc.etag = headers["etag"]
lrs_response.content = doc
return lrs_response | python | def retrieve_activity_profile(self, activity, profile_id):
if not isinstance(activity, Activity):
activity = Activity(activity)
request = HTTPRequest(
method="GET",
resource="activities/profile",
ignore404=True
)
request.query_params = {
"profileId": profile_id,
"activityId": activity.id
}
lrs_response = self._send_request(request)
if lrs_response.success:
doc = ActivityProfileDocument(
id=profile_id,
content=lrs_response.data,
activity=activity
)
headers = lrs_response.response.getheaders()
if "lastModified" in headers and headers["lastModified"] is not None:
doc.timestamp = headers["lastModified"]
if "contentType" in headers and headers["contentType"] is not None:
doc.content_type = headers["contentType"]
if "etag" in headers and headers["etag"] is not None:
doc.etag = headers["etag"]
lrs_response.content = doc
return lrs_response | [
"def",
"retrieve_activity_profile",
"(",
"self",
",",
"activity",
",",
"profile_id",
")",
":",
"if",
"not",
"isinstance",
"(",
"activity",
",",
"Activity",
")",
":",
"activity",
"=",
"Activity",
"(",
"activity",
")",
"request",
"=",
"HTTPRequest",
"(",
"meth... | Retrieve activity profile with the specified parameters
:param activity: Activity object of the desired activity profile
:type activity: :class:`tincan.activity.Activity`
:param profile_id: UUID of the desired profile
:type profile_id: str | unicode
:return: LRS Response object with an activity profile doc as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Retrieve",
"activity",
"profile",
"with",
"the",
"specified",
"parameters"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L615-L655 |
27,592 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.save_activity_profile | def save_activity_profile(self, profile):
"""Save an activity profile doc to the LRS
:param profile: Activity profile doc to be saved
:type profile: :class:`tincan.documents.activity_profile_document.ActivityProfileDocument`
:return: LRS Response object with the saved activity profile doc as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="PUT",
resource="activities/profile",
content=profile.content
)
if profile.content_type is not None:
request.headers["Content-Type"] = profile.content_type
else:
request.headers["Content-Type"] = "application/octet-stream"
if profile.etag is not None:
request.headers["If-Match"] = profile.etag
request.query_params = {
"profileId": profile.id,
"activityId": profile.activity.id
}
lrs_response = self._send_request(request)
lrs_response.content = profile
return lrs_response | python | def save_activity_profile(self, profile):
request = HTTPRequest(
method="PUT",
resource="activities/profile",
content=profile.content
)
if profile.content_type is not None:
request.headers["Content-Type"] = profile.content_type
else:
request.headers["Content-Type"] = "application/octet-stream"
if profile.etag is not None:
request.headers["If-Match"] = profile.etag
request.query_params = {
"profileId": profile.id,
"activityId": profile.activity.id
}
lrs_response = self._send_request(request)
lrs_response.content = profile
return lrs_response | [
"def",
"save_activity_profile",
"(",
"self",
",",
"profile",
")",
":",
"request",
"=",
"HTTPRequest",
"(",
"method",
"=",
"\"PUT\"",
",",
"resource",
"=",
"\"activities/profile\"",
",",
"content",
"=",
"profile",
".",
"content",
")",
"if",
"profile",
".",
"c... | Save an activity profile doc to the LRS
:param profile: Activity profile doc to be saved
:type profile: :class:`tincan.documents.activity_profile_document.ActivityProfileDocument`
:return: LRS Response object with the saved activity profile doc as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Save",
"an",
"activity",
"profile",
"doc",
"to",
"the",
"LRS"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L657-L685 |
27,593 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.delete_activity_profile | def delete_activity_profile(self, profile):
"""Delete activity profile doc from LRS
:param profile: Activity profile document to be deleted
:type profile: :class:`tincan.documents.activity_profile_document.ActivityProfileDocument`
:return: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="DELETE",
resource="activities/profile"
)
request.query_params = {
"profileId": profile.id,
"activityId": profile.activity.id
}
if profile.etag is not None:
request.headers["If-Match"] = profile.etag
return self._send_request(request) | python | def delete_activity_profile(self, profile):
request = HTTPRequest(
method="DELETE",
resource="activities/profile"
)
request.query_params = {
"profileId": profile.id,
"activityId": profile.activity.id
}
if profile.etag is not None:
request.headers["If-Match"] = profile.etag
return self._send_request(request) | [
"def",
"delete_activity_profile",
"(",
"self",
",",
"profile",
")",
":",
"request",
"=",
"HTTPRequest",
"(",
"method",
"=",
"\"DELETE\"",
",",
"resource",
"=",
"\"activities/profile\"",
")",
"request",
".",
"query_params",
"=",
"{",
"\"profileId\"",
":",
"profil... | Delete activity profile doc from LRS
:param profile: Activity profile document to be deleted
:type profile: :class:`tincan.documents.activity_profile_document.ActivityProfileDocument`
:return: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Delete",
"activity",
"profile",
"doc",
"from",
"LRS"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L687-L707 |
27,594 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.retrieve_agent_profile | def retrieve_agent_profile(self, agent, profile_id):
"""Retrieve agent profile with the specified parameters
:param agent: Agent object of the desired agent profile
:type agent: :class:`tincan.agent.Agent`
:param profile_id: UUID of the desired agent profile
:type profile_id: str | unicode
:return: LRS Response object with an agent profile doc as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="GET",
resource="agents/profile",
ignore404=True
)
request.query_params = {
"profileId": profile_id,
"agent": agent.to_json(self.version)
}
lrs_response = self._send_request(request)
if lrs_response.success:
doc = AgentProfileDocument(
id=profile_id,
content=lrs_response.data,
agent=agent
)
headers = lrs_response.response.getheaders()
if "lastModified" in headers and headers["lastModified"] is not None:
doc.timestamp = headers["lastModified"]
if "contentType" in headers and headers["contentType"] is not None:
doc.content_type = headers["contentType"]
if "etag" in headers and headers["etag"] is not None:
doc.etag = headers["etag"]
lrs_response.content = doc
return lrs_response | python | def retrieve_agent_profile(self, agent, profile_id):
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="GET",
resource="agents/profile",
ignore404=True
)
request.query_params = {
"profileId": profile_id,
"agent": agent.to_json(self.version)
}
lrs_response = self._send_request(request)
if lrs_response.success:
doc = AgentProfileDocument(
id=profile_id,
content=lrs_response.data,
agent=agent
)
headers = lrs_response.response.getheaders()
if "lastModified" in headers and headers["lastModified"] is not None:
doc.timestamp = headers["lastModified"]
if "contentType" in headers and headers["contentType"] is not None:
doc.content_type = headers["contentType"]
if "etag" in headers and headers["etag"] is not None:
doc.etag = headers["etag"]
lrs_response.content = doc
return lrs_response | [
"def",
"retrieve_agent_profile",
"(",
"self",
",",
"agent",
",",
"profile_id",
")",
":",
"if",
"not",
"isinstance",
"(",
"agent",
",",
"Agent",
")",
":",
"agent",
"=",
"Agent",
"(",
"agent",
")",
"request",
"=",
"HTTPRequest",
"(",
"method",
"=",
"\"GET\... | Retrieve agent profile with the specified parameters
:param agent: Agent object of the desired agent profile
:type agent: :class:`tincan.agent.Agent`
:param profile_id: UUID of the desired agent profile
:type profile_id: str | unicode
:return: LRS Response object with an agent profile doc as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Retrieve",
"agent",
"profile",
"with",
"the",
"specified",
"parameters"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L738-L779 |
27,595 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.save_agent_profile | def save_agent_profile(self, profile):
"""Save an agent profile doc to the LRS
:param profile: Agent profile doc to be saved
:type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument`
:return: LRS Response object with the saved agent profile doc as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="PUT",
resource="agents/profile",
content=profile.content,
)
if profile.content_type is not None:
request.headers["Content-Type"] = profile.content_type
else:
request.headers["Content-Type"] = "application/octet-stream"
if profile.etag is not None:
request.headers["If-Match"] = profile.etag
request.query_params = {
"profileId": profile.id,
"agent": profile.agent.to_json(self.version)
}
lrs_response = self._send_request(request)
lrs_response.content = profile
return lrs_response | python | def save_agent_profile(self, profile):
request = HTTPRequest(
method="PUT",
resource="agents/profile",
content=profile.content,
)
if profile.content_type is not None:
request.headers["Content-Type"] = profile.content_type
else:
request.headers["Content-Type"] = "application/octet-stream"
if profile.etag is not None:
request.headers["If-Match"] = profile.etag
request.query_params = {
"profileId": profile.id,
"agent": profile.agent.to_json(self.version)
}
lrs_response = self._send_request(request)
lrs_response.content = profile
return lrs_response | [
"def",
"save_agent_profile",
"(",
"self",
",",
"profile",
")",
":",
"request",
"=",
"HTTPRequest",
"(",
"method",
"=",
"\"PUT\"",
",",
"resource",
"=",
"\"agents/profile\"",
",",
"content",
"=",
"profile",
".",
"content",
",",
")",
"if",
"profile",
".",
"c... | Save an agent profile doc to the LRS
:param profile: Agent profile doc to be saved
:type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument`
:return: LRS Response object with the saved agent profile doc as content
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Save",
"an",
"agent",
"profile",
"doc",
"to",
"the",
"LRS"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L781-L809 |
27,596 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.delete_agent_profile | def delete_agent_profile(self, profile):
"""Delete agent profile doc from LRS
:param profile: Agent profile document to be deleted
:type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument`
:return: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="DELETE",
resource="agents/profile"
)
request.query_params = {
"profileId": profile.id,
"agent": profile.agent.to_json(self.version)
}
if profile.etag is not None:
request.headers["If-Match"] = profile.etag
return self._send_request(request) | python | def delete_agent_profile(self, profile):
request = HTTPRequest(
method="DELETE",
resource="agents/profile"
)
request.query_params = {
"profileId": profile.id,
"agent": profile.agent.to_json(self.version)
}
if profile.etag is not None:
request.headers["If-Match"] = profile.etag
return self._send_request(request) | [
"def",
"delete_agent_profile",
"(",
"self",
",",
"profile",
")",
":",
"request",
"=",
"HTTPRequest",
"(",
"method",
"=",
"\"DELETE\"",
",",
"resource",
"=",
"\"agents/profile\"",
")",
"request",
".",
"query_params",
"=",
"{",
"\"profileId\"",
":",
"profile",
"... | Delete agent profile doc from LRS
:param profile: Agent profile document to be deleted
:type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument`
:return: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse` | [
"Delete",
"agent",
"profile",
"doc",
"from",
"LRS"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L811-L831 |
27,597 | RusticiSoftware/TinCanPython | tincan/remote_lrs.py | RemoteLRS.get_endpoint_server_root | def get_endpoint_server_root(self):
"""Parses RemoteLRS object's endpoint and returns its root
:return: Root of the RemoteLRS object endpoint
:rtype: unicode
"""
parsed = urlparse(self._endpoint)
root = parsed.scheme + "://" + parsed.hostname
if parsed.port is not None:
root += ":" + unicode(parsed.port)
return root | python | def get_endpoint_server_root(self):
parsed = urlparse(self._endpoint)
root = parsed.scheme + "://" + parsed.hostname
if parsed.port is not None:
root += ":" + unicode(parsed.port)
return root | [
"def",
"get_endpoint_server_root",
"(",
"self",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"self",
".",
"_endpoint",
")",
"root",
"=",
"parsed",
".",
"scheme",
"+",
"\"://\"",
"+",
"parsed",
".",
"hostname",
"if",
"parsed",
".",
"port",
"is",
"not",
"None... | Parses RemoteLRS object's endpoint and returns its root
:return: Root of the RemoteLRS object endpoint
:rtype: unicode | [
"Parses",
"RemoteLRS",
"object",
"s",
"endpoint",
"and",
"returns",
"its",
"root"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L894-L906 |
27,598 | RusticiSoftware/TinCanPython | tincan/serializable_base.py | SerializableBase.from_json | def from_json(cls, json_data):
"""Tries to convert a JSON representation to an object of the same
type as self
A class can provide a _fromJSON implementation in order to do specific
type checking or other custom implementation details. This method
will throw a ValueError for invalid JSON, a TypeError for
improperly constructed, but valid JSON, and any custom errors
that can be be propagated from class constructors.
:param json_data: The JSON string to convert
:type json_data: str | unicode
:raises: TypeError, ValueError, LanguageMapInitError
"""
data = json.loads(json_data)
result = cls(data)
if hasattr(result, "_from_json"):
result._from_json()
return result | python | def from_json(cls, json_data):
data = json.loads(json_data)
result = cls(data)
if hasattr(result, "_from_json"):
result._from_json()
return result | [
"def",
"from_json",
"(",
"cls",
",",
"json_data",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"json_data",
")",
"result",
"=",
"cls",
"(",
"data",
")",
"if",
"hasattr",
"(",
"result",
",",
"\"_from_json\"",
")",
":",
"result",
".",
"_from_json",
... | Tries to convert a JSON representation to an object of the same
type as self
A class can provide a _fromJSON implementation in order to do specific
type checking or other custom implementation details. This method
will throw a ValueError for invalid JSON, a TypeError for
improperly constructed, but valid JSON, and any custom errors
that can be be propagated from class constructors.
:param json_data: The JSON string to convert
:type json_data: str | unicode
:raises: TypeError, ValueError, LanguageMapInitError | [
"Tries",
"to",
"convert",
"a",
"JSON",
"representation",
"to",
"an",
"object",
"of",
"the",
"same",
"type",
"as",
"self"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/serializable_base.py#L70-L89 |
27,599 | RusticiSoftware/TinCanPython | tincan/serializable_base.py | SerializableBase.to_json | def to_json(self, version=Version.latest):
"""Tries to convert an object into a JSON representation and return
the resulting string
An Object can define how it is serialized by overriding the as_version()
implementation. A caller may further define how the object is serialized
by passing in a custom encoder. The default encoder will ignore
properties of an object that are None at the time of serialization.
:param version: The version to which the object must be serialized to.
This will default to the latest version supported by the library.
:type version: str | unicode
"""
return json.dumps(self.as_version(version)) | python | def to_json(self, version=Version.latest):
return json.dumps(self.as_version(version)) | [
"def",
"to_json",
"(",
"self",
",",
"version",
"=",
"Version",
".",
"latest",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"as_version",
"(",
"version",
")",
")"
] | Tries to convert an object into a JSON representation and return
the resulting string
An Object can define how it is serialized by overriding the as_version()
implementation. A caller may further define how the object is serialized
by passing in a custom encoder. The default encoder will ignore
properties of an object that are None at the time of serialization.
:param version: The version to which the object must be serialized to.
This will default to the latest version supported by the library.
:type version: str | unicode | [
"Tries",
"to",
"convert",
"an",
"object",
"into",
"a",
"JSON",
"representation",
"and",
"return",
"the",
"resulting",
"string"
] | 424eedaa6d19221efb1108edb915fc332abbb317 | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/serializable_base.py#L91-L105 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.