body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
f6f52416cabbee3fd71f878254392fa7037a4a1f5ffb07d758b505013f087789
def update(self, **values): 'Updates values.' for (k, v) in values.items(): self[k] = v
Updates values.
aftercovid/models/_base_sir.py
update
sdpython/covidsim
0
python
def update(self, **values): for (k, v) in values.items(): self[k] = v
def update(self, **values): for (k, v) in values.items(): self[k] = v<|docstring|>Updates values.<|endoftext|>
b6f15f61079476ac2c9e9a90e3c812f106a5c94db2fadda99b29080af3191e81
def get(self): 'Retrieves all values.' return {n: self[n] for n in self.names}
Retrieves all values.
aftercovid/models/_base_sir.py
get
sdpython/covidsim
0
python
def get(self): return {n: self[n] for n in self.names}
def get(self): return {n: self[n] for n in self.names}<|docstring|>Retrieves all values.<|endoftext|>
2a722940f71b5cf02761febc02d3d84e20ad182374071648ba4ff9f9bbf24b77
def to_rst(self): '\n Returns a string formatted in RST.\n ' rows = ['*{}*'.format(self.__class__.__name__), '', '*Quantities*', ''] for (name, _, doc) in self._q: rows.append('* *{}*: {}'.format(name, doc)) rows.extend(['', '*Constants*', '']) for (name, _, doc) in self._c: rows.append('* *{}*: {}'.format(name, doc)) rows.extend(['', '*Parameters*', '']) for (name, _, doc) in self._p: rows.append('* *{}*: {}'.format(name, doc)) if (self._eq is not None): rows.extend(['', '*Equations*', '', '.. math::', '', ' \\begin{array}{l}']) for (i, (k, v)) in enumerate(sorted(self._eq.items())): line = ''.join([' ', ('\\frac{d%s}{dt} = ' % k), printing.latex(v)]) if (i < (len(self._eq) - 1)): line += ' \\\\' rows.append(line) rows.append(' \\end{array}') return '\n'.join(rows)
Returns a string formatted in RST.
aftercovid/models/_base_sir.py
to_rst
sdpython/covidsim
0
python
def to_rst(self): '\n \n ' rows = ['*{}*'.format(self.__class__.__name__), , '*Quantities*', ] for (name, _, doc) in self._q: rows.append('* *{}*: {}'.format(name, doc)) rows.extend([, '*Constants*', ]) for (name, _, doc) in self._c: rows.append('* *{}*: {}'.format(name, doc)) rows.extend([, '*Parameters*', ]) for (name, _, doc) in self._p: rows.append('* *{}*: {}'.format(name, doc)) if (self._eq is not None): rows.extend([, '*Equations*', , '.. math::', , ' \\begin{array}{l}']) for (i, (k, v)) in enumerate(sorted(self._eq.items())): line = .join([' ', ('\\frac{d%s}{dt} = ' % k), printing.latex(v)]) if (i < (len(self._eq) - 1)): line += ' \\\\' rows.append(line) rows.append(' \\end{array}') return '\n'.join(rows)
def to_rst(self): '\n \n ' rows = ['*{}*'.format(self.__class__.__name__), , '*Quantities*', ] for (name, _, doc) in self._q: rows.append('* *{}*: {}'.format(name, doc)) rows.extend([, '*Constants*', ]) for (name, _, doc) in self._c: rows.append('* *{}*: {}'.format(name, doc)) rows.extend([, '*Parameters*', ]) for (name, _, doc) in self._p: rows.append('* *{}*: {}'.format(name, doc)) if (self._eq is not None): rows.extend([, '*Equations*', , '.. math::', , ' \\begin{array}{l}']) for (i, (k, v)) in enumerate(sorted(self._eq.items())): line = .join([' ', ('\\frac{d%s}{dt} = ' % k), printing.latex(v)]) if (i < (len(self._eq) - 1)): line += ' \\\\' rows.append(line) rows.append(' \\end{array}') return '\n'.join(rows)<|docstring|>Returns a string formatted in RST.<|endoftext|>
6f85dc475fdfae074835ef350cf56a5c1b79e209f5ddc301035f22c0dc6ceb76
def _repr_html_(self): '\n Returns a string formatted in RST.\n ' rows = ['<p><b>{}</b></p>'.format(self.__class__.__name__), '', '<p><i>Quantities</i></p>', '', '<ul>'] for (name, _, doc) in self._q: rows.append('<li><i>{}</i>: {}</li>'.format(name, doc)) rows.extend(['</ul>', '', '<p><i>Constants</i></p>', '', '<ul>']) for (name, _, doc) in self._c: rows.append('<li><i>{}</i>: {}</li>'.format(name, doc)) rows.extend(['</ul>', '', '<p><i>Parameters</i></p>', '', '<ul>']) for (name, _, doc) in self._p: rows.append('<li><i>{}</i>: {}</li>'.format(name, doc)) if (self._eq is not None): rows.extend(['</ul>', '', '<p><i>Equations</i></p>', '', '<ul>']) for (i, (k, v)) in enumerate(sorted(self._eq.items())): lats = ('\\frac{d%s}{dt} = %s' % (k, printing.latex(v))) lat = latex(lats, mode='equation') line = ''.join(['<li>', str(lat), '</li>']) rows.append(line) rows.append('</ul>') return '\n'.join(rows)
Returns a string formatted in RST.
aftercovid/models/_base_sir.py
_repr_html_
sdpython/covidsim
0
python
def _repr_html_(self): '\n \n ' rows = ['<p><b>{}</b></p>'.format(self.__class__.__name__), , '<p><i>Quantities</i></p>', , '<ul>'] for (name, _, doc) in self._q: rows.append('<li><i>{}</i>: {}</li>'.format(name, doc)) rows.extend(['</ul>', , '<p><i>Constants</i></p>', , '<ul>']) for (name, _, doc) in self._c: rows.append('<li><i>{}</i>: {}</li>'.format(name, doc)) rows.extend(['</ul>', , '<p><i>Parameters</i></p>', , '<ul>']) for (name, _, doc) in self._p: rows.append('<li><i>{}</i>: {}</li>'.format(name, doc)) if (self._eq is not None): rows.extend(['</ul>', , '<p><i>Equations</i></p>', , '<ul>']) for (i, (k, v)) in enumerate(sorted(self._eq.items())): lats = ('\\frac{d%s}{dt} = %s' % (k, printing.latex(v))) lat = latex(lats, mode='equation') line = .join(['<li>', str(lat), '</li>']) rows.append(line) rows.append('</ul>') return '\n'.join(rows)
def _repr_html_(self): '\n \n ' rows = ['<p><b>{}</b></p>'.format(self.__class__.__name__), , '<p><i>Quantities</i></p>', , '<ul>'] for (name, _, doc) in self._q: rows.append('<li><i>{}</i>: {}</li>'.format(name, doc)) rows.extend(['</ul>', , '<p><i>Constants</i></p>', , '<ul>']) for (name, _, doc) in self._c: rows.append('<li><i>{}</i>: {}</li>'.format(name, doc)) rows.extend(['</ul>', , '<p><i>Parameters</i></p>', , '<ul>']) for (name, _, doc) in self._p: rows.append('<li><i>{}</i>: {}</li>'.format(name, doc)) if (self._eq is not None): rows.extend(['</ul>', , '<p><i>Equations</i></p>', , '<ul>']) for (i, (k, v)) in enumerate(sorted(self._eq.items())): lats = ('\\frac{d%s}{dt} = %s' % (k, printing.latex(v))) lat = latex(lats, mode='equation') line = .join(['<li>', str(lat), '</li>']) rows.append(line) rows.append('</ul>') return '\n'.join(rows)<|docstring|>Returns a string formatted in RST.<|endoftext|>
f8e00ef7a24982312940a249f39f168c4af40c8462ce17cddfa0aaa2b2f65309
def enumerate_edges(self): '\n Enumerates the list of quantities contributing\n to others. It ignores constants.\n ' if (self._eq is not None): params = set((_[0] for _ in self.P)) quants = set((_[0] for _ in self.Q)) for (k, v) in sorted(self._eq.items()): n2 = k n = [] for dobj in enumerate_traverse(v): term = dobj['e'] if (not hasattr(term, 'name')): continue if (term.name not in params): continue parent = dobj['p'] others = list((_['e'] for _ in enumerate_traverse(parent))) for o in others: if (hasattr(o, 'name') and (o.name in quants)): sign = self.eqsign(n2, o.name) (yield (sign, o.name, n2, term.name)) if (o.name != n2): n.append((sign, o.name, n2, term.name)) if (len(n) == 0): (yield (0, '?', n2, '?'))
Enumerates the list of quantities contributing to others. It ignores constants.
aftercovid/models/_base_sir.py
enumerate_edges
sdpython/covidsim
0
python
def enumerate_edges(self): '\n Enumerates the list of quantities contributing\n to others. It ignores constants.\n ' if (self._eq is not None): params = set((_[0] for _ in self.P)) quants = set((_[0] for _ in self.Q)) for (k, v) in sorted(self._eq.items()): n2 = k n = [] for dobj in enumerate_traverse(v): term = dobj['e'] if (not hasattr(term, 'name')): continue if (term.name not in params): continue parent = dobj['p'] others = list((_['e'] for _ in enumerate_traverse(parent))) for o in others: if (hasattr(o, 'name') and (o.name in quants)): sign = self.eqsign(n2, o.name) (yield (sign, o.name, n2, term.name)) if (o.name != n2): n.append((sign, o.name, n2, term.name)) if (len(n) == 0): (yield (0, '?', n2, '?'))
def enumerate_edges(self): '\n Enumerates the list of quantities contributing\n to others. It ignores constants.\n ' if (self._eq is not None): params = set((_[0] for _ in self.P)) quants = set((_[0] for _ in self.Q)) for (k, v) in sorted(self._eq.items()): n2 = k n = [] for dobj in enumerate_traverse(v): term = dobj['e'] if (not hasattr(term, 'name')): continue if (term.name not in params): continue parent = dobj['p'] others = list((_['e'] for _ in enumerate_traverse(parent))) for o in others: if (hasattr(o, 'name') and (o.name in quants)): sign = self.eqsign(n2, o.name) (yield (sign, o.name, n2, term.name)) if (o.name != n2): n.append((sign, o.name, n2, term.name)) if (len(n) == 0): (yield (0, '?', n2, '?'))<|docstring|>Enumerates the list of quantities contributing to others. It ignores constants.<|endoftext|>
bfe3fca9dd43fed86b10f69691ec74f366c76214248457288cc6a6b48a524edb
def to_dot(self, verbose=False, full=False): '\n Produces a graph in :epkg:`DOT` format.\n ' rows = ['digraph{'] pattern = (' {name} [label="{name}\\n{doc}" shape=record];' if verbose else ' {name} [label="{name}"];') for (name, _, doc) in self._q: rows.append(pattern.format(name=name, doc=doc)) for (name, _, doc) in self._c: rows.append(pattern.format(name=name, doc=doc)) if (self._eq is not None): pattern = (' {n1} -> {n2} [label="{sg}{name}\\nvalue={v:1.2g}"];' if verbose else ' {n1} -> {n2} [label="{sg}{name}"];') for (sg, a, b, name) in set(self.enumerate_edges()): if ((not full) and ((a == b) or (sg < 0))): continue if (name == '?'): rows.append(pattern.format(n1=a, n2=b, name=name, v=numpy.nan, sg='0')) continue value = self[name] stsg = ('' if (sg > 0) else '-') rows.append(pattern.format(n1=a, n2=b, name=name, v=value, sg=stsg)) rows.append('}') return '\n'.join(rows)
Produces a graph in :epkg:`DOT` format.
aftercovid/models/_base_sir.py
to_dot
sdpython/covidsim
0
python
def to_dot(self, verbose=False, full=False): '\n \n ' rows = ['digraph{'] pattern = (' {name} [label="{name}\\n{doc}" shape=record];' if verbose else ' {name} [label="{name}"];') for (name, _, doc) in self._q: rows.append(pattern.format(name=name, doc=doc)) for (name, _, doc) in self._c: rows.append(pattern.format(name=name, doc=doc)) if (self._eq is not None): pattern = (' {n1} -> {n2} [label="{sg}{name}\\nvalue={v:1.2g}"];' if verbose else ' {n1} -> {n2} [label="{sg}{name}"];') for (sg, a, b, name) in set(self.enumerate_edges()): if ((not full) and ((a == b) or (sg < 0))): continue if (name == '?'): rows.append(pattern.format(n1=a, n2=b, name=name, v=numpy.nan, sg='0')) continue value = self[name] stsg = ( if (sg > 0) else '-') rows.append(pattern.format(n1=a, n2=b, name=name, v=value, sg=stsg)) rows.append('}') return '\n'.join(rows)
def to_dot(self, verbose=False, full=False): '\n \n ' rows = ['digraph{'] pattern = (' {name} [label="{name}\\n{doc}" shape=record];' if verbose else ' {name} [label="{name}"];') for (name, _, doc) in self._q: rows.append(pattern.format(name=name, doc=doc)) for (name, _, doc) in self._c: rows.append(pattern.format(name=name, doc=doc)) if (self._eq is not None): pattern = (' {n1} -> {n2} [label="{sg}{name}\\nvalue={v:1.2g}"];' if verbose else ' {n1} -> {n2} [label="{sg}{name}"];') for (sg, a, b, name) in set(self.enumerate_edges()): if ((not full) and ((a == b) or (sg < 0))): continue if (name == '?'): rows.append(pattern.format(n1=a, n2=b, name=name, v=numpy.nan, sg='0')) continue value = self[name] stsg = ( if (sg > 0) else '-') rows.append(pattern.format(n1=a, n2=b, name=name, v=value, sg=stsg)) rows.append('}') return '\n'.join(rows)<|docstring|>Produces a graph in :epkg:`DOT` format.<|endoftext|>
2c6c2a0986d80a740bac56111b58a6167408768ca71513e274a78c023ddb3c18
@property def cst_param(self): '\n Returns a dictionary with the constant and the parameters.\n ' res = {} for (k, v) in zip(self._c, self._val_c): res[k[0]] = v for (k, v) in zip(self._p, self._val_p): res[k[0]] = v return res
Returns a dictionary with the constant and the parameters.
aftercovid/models/_base_sir.py
cst_param
sdpython/covidsim
0
python
@property def cst_param(self): '\n \n ' res = {} for (k, v) in zip(self._c, self._val_c): res[k[0]] = v for (k, v) in zip(self._p, self._val_p): res[k[0]] = v return res
@property def cst_param(self): '\n \n ' res = {} for (k, v) in zip(self._c, self._val_c): res[k[0]] = v for (k, v) in zip(self._p, self._val_p): res[k[0]] = v return res<|docstring|>Returns a dictionary with the constant and the parameters.<|endoftext|>
80fe47131549df4c11a418ad2aecf313a057a479375e8883045821da96f71110
def evalf_eq(self, eq, t=0): '\n Evaluates an :epkg:`sympy` expression.\n ' svalues = self._eval_cache() svalues[self._syms['t']] = t for (k, v) in zip(self._q, self._val_q): svalues[self._syms[k[0]]] = v return eq.evalf(subs=svalues)
Evaluates an :epkg:`sympy` expression.
aftercovid/models/_base_sir.py
evalf_eq
sdpython/covidsim
0
python
def evalf_eq(self, eq, t=0): '\n \n ' svalues = self._eval_cache() svalues[self._syms['t']] = t for (k, v) in zip(self._q, self._val_q): svalues[self._syms[k[0]]] = v return eq.evalf(subs=svalues)
def evalf_eq(self, eq, t=0): '\n \n ' svalues = self._eval_cache() svalues[self._syms['t']] = t for (k, v) in zip(self._q, self._val_q): svalues[self._syms[k[0]]] = v return eq.evalf(subs=svalues)<|docstring|>Evaluates an :epkg:`sympy` expression.<|endoftext|>
f800624cdd8e31bb9319c708ed574fe84c55c56226e835c93141861781d9ee57
def evalf_leq(self, name, t=0): '\n Evaluates a lambdified expression.\n\n :param name: name of the lambdified expresion\n :param t: t values\n :return: evaluation\n ' leq = self._lambdified_(name) if (leq is None): raise RuntimeError("Equation '{}' was not lambdified.".format(name)) return leq(*self.vect(t))
Evaluates a lambdified expression. :param name: name of the lambdified expresion :param t: t values :return: evaluation
aftercovid/models/_base_sir.py
evalf_leq
sdpython/covidsim
0
python
def evalf_leq(self, name, t=0): '\n Evaluates a lambdified expression.\n\n :param name: name of the lambdified expresion\n :param t: t values\n :return: evaluation\n ' leq = self._lambdified_(name) if (leq is None): raise RuntimeError("Equation '{}' was not lambdified.".format(name)) return leq(*self.vect(t))
def evalf_leq(self, name, t=0): '\n Evaluates a lambdified expression.\n\n :param name: name of the lambdified expresion\n :param t: t values\n :return: evaluation\n ' leq = self._lambdified_(name) if (leq is None): raise RuntimeError("Equation '{}' was not lambdified.".format(name)) return leq(*self.vect(t))<|docstring|>Evaluates a lambdified expression. :param name: name of the lambdified expresion :param t: t values :return: evaluation<|endoftext|>
1d299c979f74f69b24183a2410ba4c6a5cb63410981fbc7c961829f795f83424
def _lambdify_(self, name, eq, derivative=False): 'Lambdifies an expression and caches in member `_lambda_`.' if (not hasattr(self, '_lambda_')): self._lambda_ = {} if (name not in self._lambda_): names = (((self.quantity_names + self.param_names) + self.cst_names) + ['t']) sym = [Symbol(n) for n in names] if derivative: sym += [Symbol(('d' + n)) for n in self.quantity_names] self._lambda_[name] = {'names': names, 'symbols': sym, 'eq': eq, 'pos': {n: i for (i, n) in enumerate(names)}} ll = lambdify(sym, eq, 'numpy') self._lambda_[name]['la'] = ll return self._lambda_[name]['la']
Lambdifies an expression and caches in member `_lambda_`.
aftercovid/models/_base_sir.py
_lambdify_
sdpython/covidsim
0
python
def _lambdify_(self, name, eq, derivative=False): if (not hasattr(self, '_lambda_')): self._lambda_ = {} if (name not in self._lambda_): names = (((self.quantity_names + self.param_names) + self.cst_names) + ['t']) sym = [Symbol(n) for n in names] if derivative: sym += [Symbol(('d' + n)) for n in self.quantity_names] self._lambda_[name] = {'names': names, 'symbols': sym, 'eq': eq, 'pos': {n: i for (i, n) in enumerate(names)}} ll = lambdify(sym, eq, 'numpy') self._lambda_[name]['la'] = ll return self._lambda_[name]['la']
def _lambdify_(self, name, eq, derivative=False): if (not hasattr(self, '_lambda_')): self._lambda_ = {} if (name not in self._lambda_): names = (((self.quantity_names + self.param_names) + self.cst_names) + ['t']) sym = [Symbol(n) for n in names] if derivative: sym += [Symbol(('d' + n)) for n in self.quantity_names] self._lambda_[name] = {'names': names, 'symbols': sym, 'eq': eq, 'pos': {n: i for (i, n) in enumerate(names)}} ll = lambdify(sym, eq, 'numpy') self._lambda_[name]['la'] = ll return self._lambda_[name]['la']<|docstring|>Lambdifies an expression and caches in member `_lambda_`.<|endoftext|>
01fe77f9ea011ec9c0b0ba0c0f3620ae66d7360745b7855a16885216930fb4d6
def _lambdified_(self, name): '\n Returns the lambdified expression of name *name*.\n ' if hasattr(self, '_lambda_'): r = self._lambda_.get(name, None) if (r is not None): return r['la'] return None
Returns the lambdified expression of name *name*.
aftercovid/models/_base_sir.py
_lambdified_
sdpython/covidsim
0
python
def _lambdified_(self, name): '\n \n ' if hasattr(self, '_lambda_'): r = self._lambda_.get(name, None) if (r is not None): return r['la'] return None
def _lambdified_(self, name): '\n \n ' if hasattr(self, '_lambda_'): r = self._lambda_.get(name, None) if (r is not None): return r['la'] return None<|docstring|>Returns the lambdified expression of name *name*.<|endoftext|>
0a3ba6580d9a511806fe444cc4ca4b74af5039ad0e8f4636f509990108d0d922
def _eval_diff_sympy(self, t=0): '\n Evaluates derivatives.\n Returns a dictionary.\n ' svalues = self._eval_cache() svalues[self._syms['t']] = t for (k, v) in zip(self._q, self._val_q): svalues[self._syms[k[0]]] = v x = self.vect(t=t) res = {} for (k, v) in self._eq.items(): res[k] = v.evalf(subs=svalues) for (k, v) in self._leq.items(): res[k] = v(*x) return res
Evaluates derivatives. Returns a dictionary.
aftercovid/models/_base_sir.py
_eval_diff_sympy
sdpython/covidsim
0
python
def _eval_diff_sympy(self, t=0): '\n Evaluates derivatives.\n Returns a dictionary.\n ' svalues = self._eval_cache() svalues[self._syms['t']] = t for (k, v) in zip(self._q, self._val_q): svalues[self._syms[k[0]]] = v x = self.vect(t=t) res = {} for (k, v) in self._eq.items(): res[k] = v.evalf(subs=svalues) for (k, v) in self._leq.items(): res[k] = v(*x) return res
def _eval_diff_sympy(self, t=0): '\n Evaluates derivatives.\n Returns a dictionary.\n ' svalues = self._eval_cache() svalues[self._syms['t']] = t for (k, v) in zip(self._q, self._val_q): svalues[self._syms[k[0]]] = v x = self.vect(t=t) res = {} for (k, v) in self._eq.items(): res[k] = v.evalf(subs=svalues) for (k, v) in self._leq.items(): res[k] = v(*x) return res<|docstring|>Evaluates derivatives. Returns a dictionary.<|endoftext|>
b80f773cd7d3039eeffd88c6826f379fedbfcca6f820b5ee5fc80a93c273946f
def eval_diff(self, t=0): '\n Evaluates derivatives.\n Returns a dictionary.\n ' x = self.vect(t=t) res = {} for (k, v) in self._leq.items(): res[k] = v(*x) return res
Evaluates derivatives. Returns a dictionary.
aftercovid/models/_base_sir.py
eval_diff
sdpython/covidsim
0
python
def eval_diff(self, t=0): '\n Evaluates derivatives.\n Returns a dictionary.\n ' x = self.vect(t=t) res = {} for (k, v) in self._leq.items(): res[k] = v(*x) return res
def eval_diff(self, t=0): '\n Evaluates derivatives.\n Returns a dictionary.\n ' x = self.vect(t=t) res = {} for (k, v) in self._leq.items(): res[k] = v(*x) return res<|docstring|>Evaluates derivatives. Returns a dictionary.<|endoftext|>
98a30426a23b30d3641d6e75efb36ecf45c35f0511deb6d03b4cb23ff5489cdb
def test_union(self, benchmark): 'Merge sets using set.union' def run(sets): return set().union(*sets) benchmark(run, self.BASE_SETS)
Merge sets using set.union
tests/test_set_union.py
test_union
tmr232/python-benchmark
0
python
def test_union(self, benchmark): def run(sets): return set().union(*sets) benchmark(run, self.BASE_SETS)
def test_union(self, benchmark): def run(sets): return set().union(*sets) benchmark(run, self.BASE_SETS)<|docstring|>Merge sets using set.union<|endoftext|>
1f5eeb809f04d3779d142af7eb06500f6a26bbcd10353f963f1df257ead05b72
def test_itertools_chain(self, benchmark): 'Merge sets using set(itertools.chain)' def run(sets): return set(itertools.chain(*sets)) benchmark(run, self.BASE_SETS)
Merge sets using set(itertools.chain)
tests/test_set_union.py
test_itertools_chain
tmr232/python-benchmark
0
python
def test_itertools_chain(self, benchmark): def run(sets): return set(itertools.chain(*sets)) benchmark(run, self.BASE_SETS)
def test_itertools_chain(self, benchmark): def run(sets): return set(itertools.chain(*sets)) benchmark(run, self.BASE_SETS)<|docstring|>Merge sets using set(itertools.chain)<|endoftext|>
4ded4a7908de5d5cb0a1e35c62a734d345ad5556312cdf92dc9fc63785f3b09b
@click.command('start') def start(): 'Start apostello production environment' if (not os.path.isfile('.env')): click.echo('You have not configured apostello yet') click.echo('Please run the config command:') click.echo('\t apostello config') return click.echo('Starting apostello ...') try: subprocess.check_call('docker-compose up -d'.split()) except subprocess.CalledProcessError: click.echo('apostello was unable to fully start') click.echo('Run apostello logs for more info') return except Exception: return click.echo('\tApostello is now running') click.echo('\t View logs with apostello logs')
Start apostello production environment
ap_cli/apostello.py
start
monty5811/apostello-docker-cli
0
python
@click.command('start') def start(): if (not os.path.isfile('.env')): click.echo('You have not configured apostello yet') click.echo('Please run the config command:') click.echo('\t apostello config') return click.echo('Starting apostello ...') try: subprocess.check_call('docker-compose up -d'.split()) except subprocess.CalledProcessError: click.echo('apostello was unable to fully start') click.echo('Run apostello logs for more info') return except Exception: return click.echo('\tApostello is now running') click.echo('\t View logs with apostello logs')
@click.command('start') def start(): if (not os.path.isfile('.env')): click.echo('You have not configured apostello yet') click.echo('Please run the config command:') click.echo('\t apostello config') return click.echo('Starting apostello ...') try: subprocess.check_call('docker-compose up -d'.split()) except subprocess.CalledProcessError: click.echo('apostello was unable to fully start') click.echo('Run apostello logs for more info') return except Exception: return click.echo('\tApostello is now running') click.echo('\t View logs with apostello logs')<|docstring|>Start apostello production environment<|endoftext|>
e44f8563ad350c290f07a9c7aff26f8c143790af800139509eeafe0adce6176b
@click.command('stop') def stop(): 'Stop apostello production environment' click.echo('Stopping apostello ...') subprocess.call('docker-compose stop'.split())
Stop apostello production environment
ap_cli/apostello.py
stop
monty5811/apostello-docker-cli
0
python
@click.command('stop') def stop(): click.echo('Stopping apostello ...') subprocess.call('docker-compose stop'.split())
@click.command('stop') def stop(): click.echo('Stopping apostello ...') subprocess.call('docker-compose stop'.split())<|docstring|>Stop apostello production environment<|endoftext|>
77a3edeb1fcccbfa25b13771b0c5f576ae12d29de29eaedd90fb0eed62740018
@click.command('logs') def logs(): 'Show apostello logs' subprocess.call('docker-compose logs'.split())
Show apostello logs
ap_cli/apostello.py
logs
monty5811/apostello-docker-cli
0
python
@click.command('logs') def logs(): subprocess.call('docker-compose logs'.split())
@click.command('logs') def logs(): subprocess.call('docker-compose logs'.split())<|docstring|>Show apostello logs<|endoftext|>
4d6ac17ef3a4fe3f867d8b8f83a72b8598f272c807a84c8e911440a2e0529060
def build_filename(outpath, date, duration, site, client_provider, client_country, metric, suffix): "Builds an output filename that reflects the data being written to file.\n\n Args:\n outpath (str): Indicates the path (excluding filename) where the file\n will be written.\n date (str): A string indicating the start time of the data window the\n file represents.\n duration (str): A string indicating the duration of the data window the\n file represents.\n site (str): The name of the M-Lab site from which the data was collected\n (e.g. lga01)\n client_provider (str): The name of the client provider associated with\n the test results.\n client_country (str): The name of the client country associated with\n the test results.\n metric (str): The name of the metric this data represents (e.g.\n download_throughput).\n suffix (str): The appended string such as a note on the file information\n or the file extension (e.g. '-bigquery.sql').\n\n Returns:\n (str): The generated full pathname of the output file.\n " filename_format = '{date}+{duration}_{additional_properties}_{metric}{suffix}' additional_properties = '_'.join(filter(None, [site, client_country, client_provider])) filename = filename_format.format(date=date, duration=duration, additional_properties=additional_properties, metric=metric, suffix=suffix) filename = strip_special_chars(filename) filepath = os.path.join(outpath, filename) return filepath
Builds an output filename that reflects the data being written to file. Args: outpath (str): Indicates the path (excluding filename) where the file will be written. date (str): A string indicating the start time of the data window the file represents. duration (str): A string indicating the duration of the data window the file represents. site (str): The name of the M-Lab site from which the data was collected (e.g. lga01) client_provider (str): The name of the client provider associated with the test results. client_country (str): The name of the client country associated with the test results. metric (str): The name of the metric this data represents (e.g. download_throughput). suffix (str): The appended string such as a note on the file information or the file extension (e.g. '-bigquery.sql'). Returns: (str): The generated full pathname of the output file.
telescope/utils.py
build_filename
mtlynch/telescope
9
python
def build_filename(outpath, date, duration, site, client_provider, client_country, metric, suffix): "Builds an output filename that reflects the data being written to file.\n\n Args:\n outpath (str): Indicates the path (excluding filename) where the file\n will be written.\n date (str): A string indicating the start time of the data window the\n file represents.\n duration (str): A string indicating the duration of the data window the\n file represents.\n site (str): The name of the M-Lab site from which the data was collected\n (e.g. lga01)\n client_provider (str): The name of the client provider associated with\n the test results.\n client_country (str): The name of the client country associated with\n the test results.\n metric (str): The name of the metric this data represents (e.g.\n download_throughput).\n suffix (str): The appended string such as a note on the file information\n or the file extension (e.g. '-bigquery.sql').\n\n Returns:\n (str): The generated full pathname of the output file.\n " filename_format = '{date}+{duration}_{additional_properties}_{metric}{suffix}' additional_properties = '_'.join(filter(None, [site, client_country, client_provider])) filename = filename_format.format(date=date, duration=duration, additional_properties=additional_properties, metric=metric, suffix=suffix) filename = strip_special_chars(filename) filepath = os.path.join(outpath, filename) return filepath
def build_filename(outpath, date, duration, site, client_provider, client_country, metric, suffix): "Builds an output filename that reflects the data being written to file.\n\n Args:\n outpath (str): Indicates the path (excluding filename) where the file\n will be written.\n date (str): A string indicating the start time of the data window the\n file represents.\n duration (str): A string indicating the duration of the data window the\n file represents.\n site (str): The name of the M-Lab site from which the data was collected\n (e.g. lga01)\n client_provider (str): The name of the client provider associated with\n the test results.\n client_country (str): The name of the client country associated with\n the test results.\n metric (str): The name of the metric this data represents (e.g.\n download_throughput).\n suffix (str): The appended string such as a note on the file information\n or the file extension (e.g. '-bigquery.sql').\n\n Returns:\n (str): The generated full pathname of the output file.\n " filename_format = '{date}+{duration}_{additional_properties}_{metric}{suffix}' additional_properties = '_'.join(filter(None, [site, client_country, client_provider])) filename = filename_format.format(date=date, duration=duration, additional_properties=additional_properties, metric=metric, suffix=suffix) filename = strip_special_chars(filename) filepath = os.path.join(outpath, filename) return filepath<|docstring|>Builds an output filename that reflects the data being written to file. Args: outpath (str): Indicates the path (excluding filename) where the file will be written. date (str): A string indicating the start time of the data window the file represents. duration (str): A string indicating the duration of the data window the file represents. site (str): The name of the M-Lab site from which the data was collected (e.g. lga01) client_provider (str): The name of the client provider associated with the test results. client_country (str): The name of the client country associated with the test results. metric (str): The name of the metric this data represents (e.g. download_throughput). suffix (str): The appended string such as a note on the file information or the file extension (e.g. '-bigquery.sql'). Returns: (str): The generated full pathname of the output file.<|endoftext|>
44bec997f297209cbde4cd29e9c2293f45c9d8c97cd4b9f4a289197b54e51fa3
def check_for_valid_cache(cache_path, manifest_path=None): 'Checks for results file previously generated by this tool.\n\n Args:\n cache_path (str): Built path to cache file that we are interested in.\n manifest_path (str, optional): Built path to cache file that we are\n interested in. Defaults to None.\n\n Returns:\n bool: True if valid file, False otherwise.\n ' does_file_exist_at_cache_path = os.path.exists(cache_path) return does_file_exist_at_cache_path
Checks for results file previously generated by this tool. Args: cache_path (str): Built path to cache file that we are interested in. manifest_path (str, optional): Built path to cache file that we are interested in. Defaults to None. Returns: bool: True if valid file, False otherwise.
telescope/utils.py
check_for_valid_cache
mtlynch/telescope
9
python
def check_for_valid_cache(cache_path, manifest_path=None): 'Checks for results file previously generated by this tool.\n\n Args:\n cache_path (str): Built path to cache file that we are interested in.\n manifest_path (str, optional): Built path to cache file that we are\n interested in. Defaults to None.\n\n Returns:\n bool: True if valid file, False otherwise.\n ' does_file_exist_at_cache_path = os.path.exists(cache_path) return does_file_exist_at_cache_path
def check_for_valid_cache(cache_path, manifest_path=None): 'Checks for results file previously generated by this tool.\n\n Args:\n cache_path (str): Built path to cache file that we are interested in.\n manifest_path (str, optional): Built path to cache file that we are\n interested in. Defaults to None.\n\n Returns:\n bool: True if valid file, False otherwise.\n ' does_file_exist_at_cache_path = os.path.exists(cache_path) return does_file_exist_at_cache_path<|docstring|>Checks for results file previously generated by this tool. Args: cache_path (str): Built path to cache file that we are interested in. manifest_path (str, optional): Built path to cache file that we are interested in. Defaults to None. Returns: bool: True if valid file, False otherwise.<|endoftext|>
b3df8ea24384c94f6629ffe1053e0c9661d72999b4d0265fa3ddd104fcde8e62
def strip_special_chars(filename): 'Removes shell special characters from a filename.\n\n Args:\n filename (str): Filename to be sanitized. Note that this should be a\n single filename and not a full path, as this will strip path\n separators.\n\n Returns:\n (str) Sanitized version of filename.\n ' sanitized = filename special_chars = '\\/"\'`<>|:;\t\n?#$^&*=' for special_char in special_chars: sanitized = sanitized.replace(special_char, '') return sanitized
Removes shell special characters from a filename. Args: filename (str): Filename to be sanitized. Note that this should be a single filename and not a full path, as this will strip path separators. Returns: (str) Sanitized version of filename.
telescope/utils.py
strip_special_chars
mtlynch/telescope
9
python
def strip_special_chars(filename): 'Removes shell special characters from a filename.\n\n Args:\n filename (str): Filename to be sanitized. Note that this should be a\n single filename and not a full path, as this will strip path\n separators.\n\n Returns:\n (str) Sanitized version of filename.\n ' sanitized = filename special_chars = '\\/"\'`<>|:;\t\n?#$^&*=' for special_char in special_chars: sanitized = sanitized.replace(special_char, ) return sanitized
def strip_special_chars(filename): 'Removes shell special characters from a filename.\n\n Args:\n filename (str): Filename to be sanitized. Note that this should be a\n single filename and not a full path, as this will strip path\n separators.\n\n Returns:\n (str) Sanitized version of filename.\n ' sanitized = filename special_chars = '\\/"\'`<>|:;\t\n?#$^&*=' for special_char in special_chars: sanitized = sanitized.replace(special_char, ) return sanitized<|docstring|>Removes shell special characters from a filename. Args: filename (str): Filename to be sanitized. Note that this should be a single filename and not a full path, as this will strip path separators. Returns: (str) Sanitized version of filename.<|endoftext|>
c17913c402721989b0202d4a13f5ab243516feee190a25fb7f188cf7e4ba9c54
def ready(self): 'Run when Django starts.' logger.debug('App {} ready.'.format(self.name))
Run when Django starts.
newsletter/apps.py
ready
hbuyse/dj-newsletter
0
python
def ready(self): logger.debug('App {} ready.'.format(self.name))
def ready(self): logger.debug('App {} ready.'.format(self.name))<|docstring|>Run when Django starts.<|endoftext|>
10caad9f034ef2174bbb2bf373c61f604b1aa25f17016e7cce2f0b99051dc604
def test_get_service_providers(self): 'Test that get_service_providers filters correctly.' self._set_override([(constants.LOADBALANCER + ':lbaas:driver_path1'), (constants.FIREWALL + ':fwaas:driver_path2')]) ctx = context.get_admin_context() res = self.manager.get_service_providers(ctx, filters=dict(service_type=[constants.LOADBALANCER])) self.assertEqual(1, len(res)) res = self.manager.get_service_providers(ctx, filters=dict(service_type=[constants.FIREWALL])) self.assertEqual(1, len(res))
Test that get_service_providers filters correctly.
neutron/tests/unit/extensions/test_servicetype.py
test_get_service_providers
cloudbase/neutron
1
python
def test_get_service_providers(self): self._set_override([(constants.LOADBALANCER + ':lbaas:driver_path1'), (constants.FIREWALL + ':fwaas:driver_path2')]) ctx = context.get_admin_context() res = self.manager.get_service_providers(ctx, filters=dict(service_type=[constants.LOADBALANCER])) self.assertEqual(1, len(res)) res = self.manager.get_service_providers(ctx, filters=dict(service_type=[constants.FIREWALL])) self.assertEqual(1, len(res))
def test_get_service_providers(self): self._set_override([(constants.LOADBALANCER + ':lbaas:driver_path1'), (constants.FIREWALL + ':fwaas:driver_path2')]) ctx = context.get_admin_context() res = self.manager.get_service_providers(ctx, filters=dict(service_type=[constants.LOADBALANCER])) self.assertEqual(1, len(res)) res = self.manager.get_service_providers(ctx, filters=dict(service_type=[constants.FIREWALL])) self.assertEqual(1, len(res))<|docstring|>Test that get_service_providers filters correctly.<|endoftext|>
4fc237f308565787132b6d7277fda873383bca0ae83622dd9d0b48f535597c5b
def __init__(self, filename, building_ids=None): '\n :param filename: str, path to the GeoJSON file to parse\n :param building_ids: list[str | int] | None, optional, list of GeoJSON building\n IDs to parse from the file. If None or an empty list, parse all buildings.\n ' if (not Path(filename).exists()): raise GeoJsonValidationError(f'URBANopt GeoJSON file does not exist: {filename}') with open(filename, 'r') as f: self.data = geojson.load(f) self.schemas = Schemas() building_errors = {} self.buildings = [] for feature in self.data.features: if (feature['properties']['type'] == 'Building'): building = UrbanOptLoad(feature) if ((not building_ids) or (building.id in building_ids)): errors = self.schemas.validate('building', building.feature.properties) if errors: building_errors[building.id] = errors else: self.buildings.append(building) if building_errors: formatted_errors = '' for (building_id, errors) in building_errors.items(): building_errors_bullets = ''.join([f''' * {error}''' for error in errors]) formatted_errors += f''' ID {building_id}:{building_errors_bullets}''' message = f'GeoJSON file is not valid:{formatted_errors}' raise GeoJsonValidationError(message) if (not self.buildings): raise GeoJsonValidationError(f'No valid buildings found in GeoJSON file: {filename}')
:param filename: str, path to the GeoJSON file to parse :param building_ids: list[str | int] | None, optional, list of GeoJSON building IDs to parse from the file. If None or an empty list, parse all buildings.
geojson_modelica_translator/geojson/urbanopt_geojson.py
__init__
mingzhe37/geojson-modelica-translator
11
python
def __init__(self, filename, building_ids=None): '\n :param filename: str, path to the GeoJSON file to parse\n :param building_ids: list[str | int] | None, optional, list of GeoJSON building\n IDs to parse from the file. If None or an empty list, parse all buildings.\n ' if (not Path(filename).exists()): raise GeoJsonValidationError(f'URBANopt GeoJSON file does not exist: {filename}') with open(filename, 'r') as f: self.data = geojson.load(f) self.schemas = Schemas() building_errors = {} self.buildings = [] for feature in self.data.features: if (feature['properties']['type'] == 'Building'): building = UrbanOptLoad(feature) if ((not building_ids) or (building.id in building_ids)): errors = self.schemas.validate('building', building.feature.properties) if errors: building_errors[building.id] = errors else: self.buildings.append(building) if building_errors: formatted_errors = for (building_id, errors) in building_errors.items(): building_errors_bullets = .join([f' * {error}' for error in errors]) formatted_errors += f' ID {building_id}:{building_errors_bullets}' message = f'GeoJSON file is not valid:{formatted_errors}' raise GeoJsonValidationError(message) if (not self.buildings): raise GeoJsonValidationError(f'No valid buildings found in GeoJSON file: {filename}')
def __init__(self, filename, building_ids=None): '\n :param filename: str, path to the GeoJSON file to parse\n :param building_ids: list[str | int] | None, optional, list of GeoJSON building\n IDs to parse from the file. If None or an empty list, parse all buildings.\n ' if (not Path(filename).exists()): raise GeoJsonValidationError(f'URBANopt GeoJSON file does not exist: {filename}') with open(filename, 'r') as f: self.data = geojson.load(f) self.schemas = Schemas() building_errors = {} self.buildings = [] for feature in self.data.features: if (feature['properties']['type'] == 'Building'): building = UrbanOptLoad(feature) if ((not building_ids) or (building.id in building_ids)): errors = self.schemas.validate('building', building.feature.properties) if errors: building_errors[building.id] = errors else: self.buildings.append(building) if building_errors: formatted_errors = for (building_id, errors) in building_errors.items(): building_errors_bullets = .join([f' * {error}' for error in errors]) formatted_errors += f' ID {building_id}:{building_errors_bullets}' message = f'GeoJSON file is not valid:{formatted_errors}' raise GeoJsonValidationError(message) if (not self.buildings): raise GeoJsonValidationError(f'No valid buildings found in GeoJSON file: {filename}')<|docstring|>:param filename: str, path to the GeoJSON file to parse :param building_ids: list[str | int] | None, optional, list of GeoJSON building IDs to parse from the file. If None or an empty list, parse all buildings.<|endoftext|>
d102815082aa46cb7bc8d10847eda8edd501dbef1709f47367bca3404cb2248a
def execute(self, for_shotgun, **kwargs): '\n Gets encoding settings for Quicktimes generated by the export process.\n\n :param bool for_shotgun: Whether the settings are being gathered for\n Quicktime output intended for use within the Shotgun web app.\n\n :returns: A tuple, where the first item is the file_type of a Nuke\n write node, and the second item is a dictionary of knob names and\n values.\n :rtype: tuple\n ' pass
Gets encoding settings for Quicktimes generated by the export process. :param bool for_shotgun: Whether the settings are being gathered for Quicktime output intended for use within the Shotgun web app. :returns: A tuple, where the first item is the file_type of a Nuke write node, and the second item is a dictionary of knob names and values. :rtype: tuple
bundle_cache/app_store/tk-hiero-export/v0.5.1/python/base_hooks/hiero_get_quicktime_settings.py
execute
ColinKennedy/tk-config-default2-respawn
4
python
def execute(self, for_shotgun, **kwargs): '\n Gets encoding settings for Quicktimes generated by the export process.\n\n :param bool for_shotgun: Whether the settings are being gathered for\n Quicktime output intended for use within the Shotgun web app.\n\n :returns: A tuple, where the first item is the file_type of a Nuke\n write node, and the second item is a dictionary of knob names and\n values.\n :rtype: tuple\n ' pass
def execute(self, for_shotgun, **kwargs): '\n Gets encoding settings for Quicktimes generated by the export process.\n\n :param bool for_shotgun: Whether the settings are being gathered for\n Quicktime output intended for use within the Shotgun web app.\n\n :returns: A tuple, where the first item is the file_type of a Nuke\n write node, and the second item is a dictionary of knob names and\n values.\n :rtype: tuple\n ' pass<|docstring|>Gets encoding settings for Quicktimes generated by the export process. :param bool for_shotgun: Whether the settings are being gathered for Quicktime output intended for use within the Shotgun web app. :returns: A tuple, where the first item is the file_type of a Nuke write node, and the second item is a dictionary of knob names and values. :rtype: tuple<|endoftext|>
45da2665c6ba337d43af55965d0e763ded17832b47f81bee823cf3231d347a68
def image_cb(self, msg): "Identifies red lights in the incoming camera image and publishes the index\n of the waypoint closest to the red light's stop line to /traffic_waypoint\n\n Args:\n msg (Image): image from car-mounted camera\n\n " self.has_image = True self.camera_image = msg (light_wp, state) = self.process_traffic_lights() '\n Publish upcoming red lights at camera frequency.\n Each predicted state has to occur `STATE_COUNT_THRESHOLD` number\n of times till we start using it. Otherwise the previous stable state is\n used.\n ' if (self.state != state): self.state_count = 0 self.state = state elif (self.state_count >= STATE_COUNT_THRESHOLD): self.last_state = self.state light_wp = (light_wp if (state == TrafficLight.RED) else (- 1)) self.last_wp = light_wp self.upcoming_red_light_pub.publish(Int32(light_wp)) else: self.upcoming_red_light_pub.publish(Int32(self.last_wp)) self.state_count += 1
Identifies red lights in the incoming camera image and publishes the index of the waypoint closest to the red light's stop line to /traffic_waypoint Args: msg (Image): image from car-mounted camera
ros/src/tl_detector/tl_detector.py
image_cb
Clara-YR/Udacity-SDC-Term-Three-Capstone
1
python
def image_cb(self, msg): "Identifies red lights in the incoming camera image and publishes the index\n of the waypoint closest to the red light's stop line to /traffic_waypoint\n\n Args:\n msg (Image): image from car-mounted camera\n\n " self.has_image = True self.camera_image = msg (light_wp, state) = self.process_traffic_lights() '\n Publish upcoming red lights at camera frequency.\n Each predicted state has to occur `STATE_COUNT_THRESHOLD` number\n of times till we start using it. Otherwise the previous stable state is\n used.\n ' if (self.state != state): self.state_count = 0 self.state = state elif (self.state_count >= STATE_COUNT_THRESHOLD): self.last_state = self.state light_wp = (light_wp if (state == TrafficLight.RED) else (- 1)) self.last_wp = light_wp self.upcoming_red_light_pub.publish(Int32(light_wp)) else: self.upcoming_red_light_pub.publish(Int32(self.last_wp)) self.state_count += 1
def image_cb(self, msg): "Identifies red lights in the incoming camera image and publishes the index\n of the waypoint closest to the red light's stop line to /traffic_waypoint\n\n Args:\n msg (Image): image from car-mounted camera\n\n " self.has_image = True self.camera_image = msg (light_wp, state) = self.process_traffic_lights() '\n Publish upcoming red lights at camera frequency.\n Each predicted state has to occur `STATE_COUNT_THRESHOLD` number\n of times till we start using it. Otherwise the previous stable state is\n used.\n ' if (self.state != state): self.state_count = 0 self.state = state elif (self.state_count >= STATE_COUNT_THRESHOLD): self.last_state = self.state light_wp = (light_wp if (state == TrafficLight.RED) else (- 1)) self.last_wp = light_wp self.upcoming_red_light_pub.publish(Int32(light_wp)) else: self.upcoming_red_light_pub.publish(Int32(self.last_wp)) self.state_count += 1<|docstring|>Identifies red lights in the incoming camera image and publishes the index of the waypoint closest to the red light's stop line to /traffic_waypoint Args: msg (Image): image from car-mounted camera<|endoftext|>
885474519f077d308ff78967f4114dbda3703279b6def1926bf4190368f35480
def get_closest_waypoint(self, x, y): 'Identifies the closest path waypoint to the given position\n https://en.wikipedia.org/wiki/Closest_pair_of_points_problem\n Args:\n x, y(Pose): position to match a waypoint to\n\n Returns:\n int: index of the closest waypoint in self.waypoints\n\n ' closest_idx = self.waypoint_tree.query([x, y], 1)[1] closest_coord = self.waypoints_2d[closest_idx] prev_coord = self.waypoints_2d[(closest_idx - 1)] cl_vect = np.array(closest_coord) prev_vect = np.array(prev_coord) pos_vect = np.array([x, y]) val = np.dot((cl_vect - prev_vect), (pos_vect - cl_vect)) if (val > 0): closest_idx = ((closest_idx + 1) % len(self.waypoints_2d)) return closest_idx
Identifies the closest path waypoint to the given position https://en.wikipedia.org/wiki/Closest_pair_of_points_problem Args: x, y(Pose): position to match a waypoint to Returns: int: index of the closest waypoint in self.waypoints
ros/src/tl_detector/tl_detector.py
get_closest_waypoint
Clara-YR/Udacity-SDC-Term-Three-Capstone
1
python
def get_closest_waypoint(self, x, y): 'Identifies the closest path waypoint to the given position\n https://en.wikipedia.org/wiki/Closest_pair_of_points_problem\n Args:\n x, y(Pose): position to match a waypoint to\n\n Returns:\n int: index of the closest waypoint in self.waypoints\n\n ' closest_idx = self.waypoint_tree.query([x, y], 1)[1] closest_coord = self.waypoints_2d[closest_idx] prev_coord = self.waypoints_2d[(closest_idx - 1)] cl_vect = np.array(closest_coord) prev_vect = np.array(prev_coord) pos_vect = np.array([x, y]) val = np.dot((cl_vect - prev_vect), (pos_vect - cl_vect)) if (val > 0): closest_idx = ((closest_idx + 1) % len(self.waypoints_2d)) return closest_idx
def get_closest_waypoint(self, x, y): 'Identifies the closest path waypoint to the given position\n https://en.wikipedia.org/wiki/Closest_pair_of_points_problem\n Args:\n x, y(Pose): position to match a waypoint to\n\n Returns:\n int: index of the closest waypoint in self.waypoints\n\n ' closest_idx = self.waypoint_tree.query([x, y], 1)[1] closest_coord = self.waypoints_2d[closest_idx] prev_coord = self.waypoints_2d[(closest_idx - 1)] cl_vect = np.array(closest_coord) prev_vect = np.array(prev_coord) pos_vect = np.array([x, y]) val = np.dot((cl_vect - prev_vect), (pos_vect - cl_vect)) if (val > 0): closest_idx = ((closest_idx + 1) % len(self.waypoints_2d)) return closest_idx<|docstring|>Identifies the closest path waypoint to the given position https://en.wikipedia.org/wiki/Closest_pair_of_points_problem Args: x, y(Pose): position to match a waypoint to Returns: int: index of the closest waypoint in self.waypoints<|endoftext|>
6575355d15b77f4a6180497504f83144e6077854a958f7fd732c2b5585335fcb
def get_light_state(self, light): 'Determines the current color of the traffic light\n\n Args:\n light (TrafficLight): light to classify\n\n Returns:\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n\n ' if (not self.has_image): self.prev_light_loc = None return False return self.light_classifier.get_classification(self.detectedlights)
Determines the current color of the traffic light Args: light (TrafficLight): light to classify Returns: int: ID of traffic light color (specified in styx_msgs/TrafficLight)
ros/src/tl_detector/tl_detector.py
get_light_state
Clara-YR/Udacity-SDC-Term-Three-Capstone
1
python
def get_light_state(self, light): 'Determines the current color of the traffic light\n\n Args:\n light (TrafficLight): light to classify\n\n Returns:\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n\n ' if (not self.has_image): self.prev_light_loc = None return False return self.light_classifier.get_classification(self.detectedlights)
def get_light_state(self, light): 'Determines the current color of the traffic light\n\n Args:\n light (TrafficLight): light to classify\n\n Returns:\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n\n ' if (not self.has_image): self.prev_light_loc = None return False return self.light_classifier.get_classification(self.detectedlights)<|docstring|>Determines the current color of the traffic light Args: light (TrafficLight): light to classify Returns: int: ID of traffic light color (specified in styx_msgs/TrafficLight)<|endoftext|>
2d193eb8a0bcb886ec8a9b2759556d81a5303c092a08f4791bb60be7165c5b1b
def process_traffic_lights(self): 'Finds closest visible traffic light, if one exists, and determines its\n location and color\n\n Returns:\n int: index of waypoint closes to the upcoming stop line for a traffic light (-1 if none exists)\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n\n ' closest_light = None line_wp_idx = None stop_line_positions = self.config['stop_line_positions'] if self.pose: car_wp_idx = self.get_closest_waypoint(self.pose.pose.position.x, self.pose.pose.position.y) diff = len(self.waypoints.waypoints) for (i, light) in enumerate(self.lights): line = stop_line_positions[i] temp_wp_idx = self.get_closest_waypoint(line[0], line[1]) d = (temp_wp_idx - car_wp_idx) if ((d >= 0) and (d < diff)): diff = d closest_light = light line_wp_idx = temp_wp_idx if closest_light: state = self.get_light_state(closest_light) return (line_wp_idx, state) return ((- 1), TrafficLight.UNKNOWN)
Finds closest visible traffic light, if one exists, and determines its location and color Returns: int: index of waypoint closes to the upcoming stop line for a traffic light (-1 if none exists) int: ID of traffic light color (specified in styx_msgs/TrafficLight)
ros/src/tl_detector/tl_detector.py
process_traffic_lights
Clara-YR/Udacity-SDC-Term-Three-Capstone
1
python
def process_traffic_lights(self): 'Finds closest visible traffic light, if one exists, and determines its\n location and color\n\n Returns:\n int: index of waypoint closes to the upcoming stop line for a traffic light (-1 if none exists)\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n\n ' closest_light = None line_wp_idx = None stop_line_positions = self.config['stop_line_positions'] if self.pose: car_wp_idx = self.get_closest_waypoint(self.pose.pose.position.x, self.pose.pose.position.y) diff = len(self.waypoints.waypoints) for (i, light) in enumerate(self.lights): line = stop_line_positions[i] temp_wp_idx = self.get_closest_waypoint(line[0], line[1]) d = (temp_wp_idx - car_wp_idx) if ((d >= 0) and (d < diff)): diff = d closest_light = light line_wp_idx = temp_wp_idx if closest_light: state = self.get_light_state(closest_light) return (line_wp_idx, state) return ((- 1), TrafficLight.UNKNOWN)
def process_traffic_lights(self): 'Finds closest visible traffic light, if one exists, and determines its\n location and color\n\n Returns:\n int: index of waypoint closes to the upcoming stop line for a traffic light (-1 if none exists)\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n\n ' closest_light = None line_wp_idx = None stop_line_positions = self.config['stop_line_positions'] if self.pose: car_wp_idx = self.get_closest_waypoint(self.pose.pose.position.x, self.pose.pose.position.y) diff = len(self.waypoints.waypoints) for (i, light) in enumerate(self.lights): line = stop_line_positions[i] temp_wp_idx = self.get_closest_waypoint(line[0], line[1]) d = (temp_wp_idx - car_wp_idx) if ((d >= 0) and (d < diff)): diff = d closest_light = light line_wp_idx = temp_wp_idx if closest_light: state = self.get_light_state(closest_light) return (line_wp_idx, state) return ((- 1), TrafficLight.UNKNOWN)<|docstring|>Finds closest visible traffic light, if one exists, and determines its location and color Returns: int: index of waypoint closes to the upcoming stop line for a traffic light (-1 if none exists) int: ID of traffic light color (specified in styx_msgs/TrafficLight)<|endoftext|>
bd6023a12e51d8b6cf4ee54beb9099251cf0c5062c1b83dc5b3d24a5b9161544
def post(self, request): '保持订单信息' data = json.loads(request.body.decode()) address_id = data.get('address_id') pay_method = data.get('pay_method') if (not all([address_id, pay_method])): return JsonResponse({'code': 400, 'errmsg': '缺少必要参数'}) try: address = Address.objects.get(pk=address_id) except Exception as e: return {'code': 400, 'errmsg': '地址错误'} if (pay_method not in [1, 2]): return JsonResponse({'code': 400, 'errmsg': '不支持的付款方式'}) user = request.user order_id = (timezone.localtime().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)) with transaction.atomic(): save_id = transaction.savepoint() order = OrderInfo.objects.create(order_id=order_id, user=user, address=address, total_count=0, total_amount=Decimal('0'), freight=Decimal('10.00'), pay_method=pay_method, status=(OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if (pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY']) else OrderInfo.ORDER_STATUS_ENUM['UNSEND'])) redis_conn = get_redis_connection('carts') cart_dict = redis_conn.hgetall(('carts_%s' % user.id)) selected_redis = redis_conn.smembers(('selected_%s' % user.id)) carts = {} for (k, v) in cart_dict.items(): if (k in selected_redis): carts[int(k)] = int(v) sku_ids = carts.keys() for sku_id in sku_ids: while True: sku = SKU.objects.get(id=sku_id) old_stock = sku.stock old_sales = sku.sales sku_count = carts[sku.id] if (sku_count > sku.stock): transaction.savepoint_rollback(save_id) return JsonResponse({'code': 400, 'errmsg': '库存不足'}) new_stock = (old_stock - sku_count) new_sales = (old_sales + sku_count) result = SKU.objects.filter(id=sku.id, stock=old_stock, sales=old_sales).update(stock=new_stock, sales=old_sales) if (result == 0): continue break OrderGoods.objects.create(order=order, sku=sku, count=carts[sku_id], price=sku.price) order.total_count += sku_count order.total_amount += (sku_count * sku.price) order.total_amount += order.freight order.save() transaction.savepoint_commit(save_id) redis_conn.hdel(('carts_%s' % user.id), *selected_redis) redis_conn.srem(('selected_%s' % user.id), *selected_redis) return JsonResponse({'code': 0, 'errmsg': '下单成功', 'order_id': order.order_id})
保持订单信息
shopping_mall/shopping_mall/apps/orders/views.py
post
zhangwei-python/Super_shopping_mall
0
python
def post(self, request): data = json.loads(request.body.decode()) address_id = data.get('address_id') pay_method = data.get('pay_method') if (not all([address_id, pay_method])): return JsonResponse({'code': 400, 'errmsg': '缺少必要参数'}) try: address = Address.objects.get(pk=address_id) except Exception as e: return {'code': 400, 'errmsg': '地址错误'} if (pay_method not in [1, 2]): return JsonResponse({'code': 400, 'errmsg': '不支持的付款方式'}) user = request.user order_id = (timezone.localtime().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)) with transaction.atomic(): save_id = transaction.savepoint() order = OrderInfo.objects.create(order_id=order_id, user=user, address=address, total_count=0, total_amount=Decimal('0'), freight=Decimal('10.00'), pay_method=pay_method, status=(OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if (pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY']) else OrderInfo.ORDER_STATUS_ENUM['UNSEND'])) redis_conn = get_redis_connection('carts') cart_dict = redis_conn.hgetall(('carts_%s' % user.id)) selected_redis = redis_conn.smembers(('selected_%s' % user.id)) carts = {} for (k, v) in cart_dict.items(): if (k in selected_redis): carts[int(k)] = int(v) sku_ids = carts.keys() for sku_id in sku_ids: while True: sku = SKU.objects.get(id=sku_id) old_stock = sku.stock old_sales = sku.sales sku_count = carts[sku.id] if (sku_count > sku.stock): transaction.savepoint_rollback(save_id) return JsonResponse({'code': 400, 'errmsg': '库存不足'}) new_stock = (old_stock - sku_count) new_sales = (old_sales + sku_count) result = SKU.objects.filter(id=sku.id, stock=old_stock, sales=old_sales).update(stock=new_stock, sales=old_sales) if (result == 0): continue break OrderGoods.objects.create(order=order, sku=sku, count=carts[sku_id], price=sku.price) order.total_count += sku_count order.total_amount += (sku_count * sku.price) order.total_amount += order.freight order.save() transaction.savepoint_commit(save_id) redis_conn.hdel(('carts_%s' % user.id), *selected_redis) redis_conn.srem(('selected_%s' % user.id), *selected_redis) return JsonResponse({'code': 0, 'errmsg': '下单成功', 'order_id': order.order_id})
def post(self, request): data = json.loads(request.body.decode()) address_id = data.get('address_id') pay_method = data.get('pay_method') if (not all([address_id, pay_method])): return JsonResponse({'code': 400, 'errmsg': '缺少必要参数'}) try: address = Address.objects.get(pk=address_id) except Exception as e: return {'code': 400, 'errmsg': '地址错误'} if (pay_method not in [1, 2]): return JsonResponse({'code': 400, 'errmsg': '不支持的付款方式'}) user = request.user order_id = (timezone.localtime().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)) with transaction.atomic(): save_id = transaction.savepoint() order = OrderInfo.objects.create(order_id=order_id, user=user, address=address, total_count=0, total_amount=Decimal('0'), freight=Decimal('10.00'), pay_method=pay_method, status=(OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if (pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY']) else OrderInfo.ORDER_STATUS_ENUM['UNSEND'])) redis_conn = get_redis_connection('carts') cart_dict = redis_conn.hgetall(('carts_%s' % user.id)) selected_redis = redis_conn.smembers(('selected_%s' % user.id)) carts = {} for (k, v) in cart_dict.items(): if (k in selected_redis): carts[int(k)] = int(v) sku_ids = carts.keys() for sku_id in sku_ids: while True: sku = SKU.objects.get(id=sku_id) old_stock = sku.stock old_sales = sku.sales sku_count = carts[sku.id] if (sku_count > sku.stock): transaction.savepoint_rollback(save_id) return JsonResponse({'code': 400, 'errmsg': '库存不足'}) new_stock = (old_stock - sku_count) new_sales = (old_sales + sku_count) result = SKU.objects.filter(id=sku.id, stock=old_stock, sales=old_sales).update(stock=new_stock, sales=old_sales) if (result == 0): continue break OrderGoods.objects.create(order=order, sku=sku, count=carts[sku_id], price=sku.price) order.total_count += sku_count order.total_amount += (sku_count * sku.price) order.total_amount += order.freight order.save() transaction.savepoint_commit(save_id) redis_conn.hdel(('carts_%s' % user.id), *selected_redis) redis_conn.srem(('selected_%s' % user.id), *selected_redis) return JsonResponse({'code': 0, 'errmsg': '下单成功', 'order_id': order.order_id})<|docstring|>保持订单信息<|endoftext|>
fc0d65fcb1fbec0da875d86254355d03f048c9c43b031f5b18b17dc34b512d76
def __init__(self, database=None): 'open the camera hardware' self.db = database self.camera = (picamera.PiCamera() if has_picamera else cv2.VideoCapture(0)) self.qr_codes = []
open the camera hardware
zhima/camera.py
__init__
ericgibert/zhima
0
python
def __init__(self, database=None): self.db = database self.camera = (picamera.PiCamera() if has_picamera else cv2.VideoCapture(0)) self.qr_codes = []
def __init__(self, database=None): self.db = database self.camera = (picamera.PiCamera() if has_picamera else cv2.VideoCapture(0)) self.qr_codes = []<|docstring|>open the camera hardware<|endoftext|>
fc7de306d5f34668ce8bbc3b803703c3057218467372f2e9bfa556beb38fcb29
def close(self): 'release the hardware' if has_picamera: try: self.camera.close() except: pass else: self.camera.release() del self.camera
release the hardware
zhima/camera.py
close
ericgibert/zhima
0
python
def close(self): if has_picamera: try: self.camera.close() except: pass else: self.camera.release() del self.camera
def close(self): if has_picamera: try: self.camera.close() except: pass else: self.camera.release() del self.camera<|docstring|>release the hardware<|endoftext|>
ffc9c9f57cf92a1e8e1f575b815a94e8018446509c6b11dadb8417728d634957
def save_photo(self, file_path=None): 'save the current image' (_, self.file_path) = (mkstemp(prefix='QR-', suffix='.png', text=False) if (file_path is None) else (None, file_path)) cv2.imwrite(self.file_path, self.cv2_img) return self.file_path
save the current image
zhima/camera.py
save_photo
ericgibert/zhima
0
python
def save_photo(self, file_path=None): (_, self.file_path) = (mkstemp(prefix='QR-', suffix='.png', text=False) if (file_path is None) else (None, file_path)) cv2.imwrite(self.file_path, self.cv2_img) return self.file_path
def save_photo(self, file_path=None): (_, self.file_path) = (mkstemp(prefix='QR-', suffix='.png', text=False) if (file_path is None) else (None, file_path)) cv2.imwrite(self.file_path, self.cv2_img) return self.file_path<|docstring|>save the current image<|endoftext|>
566d1f0cdd5477a04a8f325663339bd9e5003e075d3c2446b0edebf99866a0be
def get_QRcode(self, max_photos=10, debug=False): 'take max_photos until a QR code is found else returns []' self.qr_codes = [] (self.image, self.cv2_img) = (None, None) for i in range(max_photos): if debug: print('Taking photo', i, end='\r') sleep(0.1) if has_picamera: with picamera.array.PiRGBArray(self.camera) as stream: self.camera.capture(stream, format='bgr') self.cv2_img = stream.array else: try: (cv2_return_code, self.cv2_img) = self.camera.read() except cv2.error as cv2_err: msg = 'Error with the camera: {}'.format(cv2_err) if self.db: self.db.log('ERROR', (- 3000), msg, debug=debug) else: print(msg) return None try: self.image = Image.fromarray(self.cv2_img) self.qr_codes = zbarlight.scan_codes('qrcode', self.image) except AttributeError as err: msg = 'Photo not taken properly: {}'.format(err) if self.db: self.db.log('WARNING', (- 3001), msg, debug=debug) else: print(msg) return None if self.qr_codes: if debug: print('QR code found on', self.save_photo()) print('\n') return self.qr_codes else: if debug: print('NO QR code found on', self.save_photo(), '[', i, ']') print('\n') print('\n') return []
take max_photos until a QR code is found else returns []
zhima/camera.py
get_QRcode
ericgibert/zhima
0
python
def get_QRcode(self, max_photos=10, debug=False): self.qr_codes = [] (self.image, self.cv2_img) = (None, None) for i in range(max_photos): if debug: print('Taking photo', i, end='\r') sleep(0.1) if has_picamera: with picamera.array.PiRGBArray(self.camera) as stream: self.camera.capture(stream, format='bgr') self.cv2_img = stream.array else: try: (cv2_return_code, self.cv2_img) = self.camera.read() except cv2.error as cv2_err: msg = 'Error with the camera: {}'.format(cv2_err) if self.db: self.db.log('ERROR', (- 3000), msg, debug=debug) else: print(msg) return None try: self.image = Image.fromarray(self.cv2_img) self.qr_codes = zbarlight.scan_codes('qrcode', self.image) except AttributeError as err: msg = 'Photo not taken properly: {}'.format(err) if self.db: self.db.log('WARNING', (- 3001), msg, debug=debug) else: print(msg) return None if self.qr_codes: if debug: print('QR code found on', self.save_photo()) print('\n') return self.qr_codes else: if debug: print('NO QR code found on', self.save_photo(), '[', i, ']') print('\n') print('\n') return []
def get_QRcode(self, max_photos=10, debug=False): self.qr_codes = [] (self.image, self.cv2_img) = (None, None) for i in range(max_photos): if debug: print('Taking photo', i, end='\r') sleep(0.1) if has_picamera: with picamera.array.PiRGBArray(self.camera) as stream: self.camera.capture(stream, format='bgr') self.cv2_img = stream.array else: try: (cv2_return_code, self.cv2_img) = self.camera.read() except cv2.error as cv2_err: msg = 'Error with the camera: {}'.format(cv2_err) if self.db: self.db.log('ERROR', (- 3000), msg, debug=debug) else: print(msg) return None try: self.image = Image.fromarray(self.cv2_img) self.qr_codes = zbarlight.scan_codes('qrcode', self.image) except AttributeError as err: msg = 'Photo not taken properly: {}'.format(err) if self.db: self.db.log('WARNING', (- 3001), msg, debug=debug) else: print(msg) return None if self.qr_codes: if debug: print('QR code found on', self.save_photo()) print('\n') return self.qr_codes else: if debug: print('NO QR code found on', self.save_photo(), '[', i, ']') print('\n') print('\n') return []<|docstring|>take max_photos until a QR code is found else returns []<|endoftext|>
e2734ef012fba04d5e5c92dfcb59e2fa8199d660de6cf55a63a8f63bd80eee67
def uniform_distance_prior(d, rlim=30.0): '\n Uniform distance prior\n \n Input:\n d: distance (typically an array)\n Optional:\n rlim: Maximum allowed distance (default: 30 kpc)\n Output:\n Uniform distance prior\n ' return np.piecewise(d, [(d < 0), ((d >= 0) * (d <= rlim)), (d > rlim)], [0, (1 / rlim), 0])
Uniform distance prior Input: d: distance (typically an array) Optional: rlim: Maximum allowed distance (default: 30 kpc) Output: Uniform distance prior
abj2016.py
uniform_distance_prior
fjaellet/abj2016
6
python
def uniform_distance_prior(d, rlim=30.0): '\n Uniform distance prior\n \n Input:\n d: distance (typically an array)\n Optional:\n rlim: Maximum allowed distance (default: 30 kpc)\n Output:\n Uniform distance prior\n ' return np.piecewise(d, [(d < 0), ((d >= 0) * (d <= rlim)), (d > rlim)], [0, (1 / rlim), 0])
def uniform_distance_prior(d, rlim=30.0): '\n Uniform distance prior\n \n Input:\n d: distance (typically an array)\n Optional:\n rlim: Maximum allowed distance (default: 30 kpc)\n Output:\n Uniform distance prior\n ' return np.piecewise(d, [(d < 0), ((d >= 0) * (d <= rlim)), (d > rlim)], [0, (1 / rlim), 0])<|docstring|>Uniform distance prior Input: d: distance (typically an array) Optional: rlim: Maximum allowed distance (default: 30 kpc) Output: Uniform distance prior<|endoftext|>
fdae3a54ae0e4cd689a02cfab1a4247b16822e377f570dc5b5c66e0471039d13
def uniform_density_prior(d, rlim=30.0): '\n Uniform space density prior\n \n Input:\n d: distance (typically an array)\n Optional:\n rlim: Maximum allowed distance (default: 30 kpc)\n Output:\n Uniform density prior\n ' return np.piecewise(d, [(d < 0), ((d >= 0) * (d <= rlim)), (d > rlim)], [0, ((1 / (rlim ** 3.0)) * (d ** 2.0)), 0])
Uniform space density prior Input: d: distance (typically an array) Optional: rlim: Maximum allowed distance (default: 30 kpc) Output: Uniform density prior
abj2016.py
uniform_density_prior
fjaellet/abj2016
6
python
def uniform_density_prior(d, rlim=30.0): '\n Uniform space density prior\n \n Input:\n d: distance (typically an array)\n Optional:\n rlim: Maximum allowed distance (default: 30 kpc)\n Output:\n Uniform density prior\n ' return np.piecewise(d, [(d < 0), ((d >= 0) * (d <= rlim)), (d > rlim)], [0, ((1 / (rlim ** 3.0)) * (d ** 2.0)), 0])
def uniform_density_prior(d, rlim=30.0): '\n Uniform space density prior\n \n Input:\n d: distance (typically an array)\n Optional:\n rlim: Maximum allowed distance (default: 30 kpc)\n Output:\n Uniform density prior\n ' return np.piecewise(d, [(d < 0), ((d >= 0) * (d <= rlim)), (d > rlim)], [0, ((1 / (rlim ** 3.0)) * (d ** 2.0)), 0])<|docstring|>Uniform space density prior Input: d: distance (typically an array) Optional: rlim: Maximum allowed distance (default: 30 kpc) Output: Uniform density prior<|endoftext|>
5e4bbcf7b48f39d1f6b043001806eccf46ffa9363cdc76f04c6ab1b7682999e8
def exp_prior(d, L=1.35): '\n Exponentially decreasing space density prior\n \n Input:\n d: distance (typically an array)\n Optional:\n L: Scale of the exponentially decreasing density (default: 1.35 kpc)\n Output:\n Exponentially decreasing space density prior\n ' return np.piecewise(d, [(d < 0), (d >= 0)], [0, (((1 / (2 * (L ** 3.0))) * (d ** 2.0)) * np.exp(((- d) / L)))])
Exponentially decreasing space density prior Input: d: distance (typically an array) Optional: L: Scale of the exponentially decreasing density (default: 1.35 kpc) Output: Exponentially decreasing space density prior
abj2016.py
exp_prior
fjaellet/abj2016
6
python
def exp_prior(d, L=1.35): '\n Exponentially decreasing space density prior\n \n Input:\n d: distance (typically an array)\n Optional:\n L: Scale of the exponentially decreasing density (default: 1.35 kpc)\n Output:\n Exponentially decreasing space density prior\n ' return np.piecewise(d, [(d < 0), (d >= 0)], [0, (((1 / (2 * (L ** 3.0))) * (d ** 2.0)) * np.exp(((- d) / L)))])
def exp_prior(d, L=1.35): '\n Exponentially decreasing space density prior\n \n Input:\n d: distance (typically an array)\n Optional:\n L: Scale of the exponentially decreasing density (default: 1.35 kpc)\n Output:\n Exponentially decreasing space density prior\n ' return np.piecewise(d, [(d < 0), (d >= 0)], [0, (((1 / (2 * (L ** 3.0))) * (d ** 2.0)) * np.exp(((- d) / L)))])<|docstring|>Exponentially decreasing space density prior Input: d: distance (typically an array) Optional: L: Scale of the exponentially decreasing density (default: 1.35 kpc) Output: Exponentially decreasing space density prior<|endoftext|>
15b54abc52b3557108f5b93a3a3374dbd7f8bd537d1e1929176a5d8abfceb3e0
def likelihood(pi, d, sigma_pi): '\n Gaussian likelihood of parallax given distance and parallax uncertainty\n \n Input:\n pi: parallax (array or scalar)\n d: distance (typically an array)\n sigma_pi: parallax_uncertainty (array or scalar)\n Output:\n Likelihood of parallax given distance and parallax uncertainty (formula 1 of Astraatmadja&Bailer-Jones 2016)\n ' if np.isscalar(pi): return ((1 / np.sqrt(((2 * np.pi) * (sigma_pi ** 2.0)))) * np.exp((((- 1) / (2 * (sigma_pi ** 2.0))) * ((pi - (1.0 / d)) ** 2.0)))) else: return ((1 / np.sqrt(((2 * np.pi) * (sigma_pi ** 2.0)))) * np.exp((((- 1) / (2 * (sigma_pi ** 2.0))) * ((pi[(np.newaxis, :)] - (1.0 / d[(:, np.newaxis)])) ** 2.0))))
Gaussian likelihood of parallax given distance and parallax uncertainty Input: pi: parallax (array or scalar) d: distance (typically an array) sigma_pi: parallax_uncertainty (array or scalar) Output: Likelihood of parallax given distance and parallax uncertainty (formula 1 of Astraatmadja&Bailer-Jones 2016)
abj2016.py
likelihood
fjaellet/abj2016
6
python
def likelihood(pi, d, sigma_pi): '\n Gaussian likelihood of parallax given distance and parallax uncertainty\n \n Input:\n pi: parallax (array or scalar)\n d: distance (typically an array)\n sigma_pi: parallax_uncertainty (array or scalar)\n Output:\n Likelihood of parallax given distance and parallax uncertainty (formula 1 of Astraatmadja&Bailer-Jones 2016)\n ' if np.isscalar(pi): return ((1 / np.sqrt(((2 * np.pi) * (sigma_pi ** 2.0)))) * np.exp((((- 1) / (2 * (sigma_pi ** 2.0))) * ((pi - (1.0 / d)) ** 2.0)))) else: return ((1 / np.sqrt(((2 * np.pi) * (sigma_pi ** 2.0)))) * np.exp((((- 1) / (2 * (sigma_pi ** 2.0))) * ((pi[(np.newaxis, :)] - (1.0 / d[(:, np.newaxis)])) ** 2.0))))
def likelihood(pi, d, sigma_pi): '\n Gaussian likelihood of parallax given distance and parallax uncertainty\n \n Input:\n pi: parallax (array or scalar)\n d: distance (typically an array)\n sigma_pi: parallax_uncertainty (array or scalar)\n Output:\n Likelihood of parallax given distance and parallax uncertainty (formula 1 of Astraatmadja&Bailer-Jones 2016)\n ' if np.isscalar(pi): return ((1 / np.sqrt(((2 * np.pi) * (sigma_pi ** 2.0)))) * np.exp((((- 1) / (2 * (sigma_pi ** 2.0))) * ((pi - (1.0 / d)) ** 2.0)))) else: return ((1 / np.sqrt(((2 * np.pi) * (sigma_pi ** 2.0)))) * np.exp((((- 1) / (2 * (sigma_pi ** 2.0))) * ((pi[(np.newaxis, :)] - (1.0 / d[(:, np.newaxis)])) ** 2.0))))<|docstring|>Gaussian likelihood of parallax given distance and parallax uncertainty Input: pi: parallax (array or scalar) d: distance (typically an array) sigma_pi: parallax_uncertainty (array or scalar) Output: Likelihood of parallax given distance and parallax uncertainty (formula 1 of Astraatmadja&Bailer-Jones 2016)<|endoftext|>
b7630debb3e71286b3c235435d8d7bc0bf0b5c284d8db18cd42a88d007179528
def posterior(distarray, pi, sigma_pi, prior='exponential'): '\n Posterior distance distribution.\n \n Input:\n distarray:distance array on which to calculate the posterior PDF\n pi: parallax (array or scalar)\n sigma_pi: parallax_uncertainty (array or scalar)\n Optional:\n prior: String. Decides which prior to use (at present either "exponential", "uniform_density", "uniform_distance")\n Output:\n Posterior distance PDF (up to a factor), given parallax and parallax uncertainty (formula 2 of Astraatmadja&Bailer-Jones 2016)\n ' if (prior == 'exponential'): prior = exp_prior elif (prior == 'uniform_density'): prior = uniform_density_prior elif (prior == 'uniform_distance'): prior = uniform_distance_prior else: raise ValueError('Prior keyword does not exist') if np.isscalar(pi): return (prior(distarray) * likelihood(pi, distarray, sigma_pi)) else: return (prior(distarray)[(:, np.newaxis)] * likelihood(pi, distarray, sigma_pi))
Posterior distance distribution. Input: distarray:distance array on which to calculate the posterior PDF pi: parallax (array or scalar) sigma_pi: parallax_uncertainty (array or scalar) Optional: prior: String. Decides which prior to use (at present either "exponential", "uniform_density", "uniform_distance") Output: Posterior distance PDF (up to a factor), given parallax and parallax uncertainty (formula 2 of Astraatmadja&Bailer-Jones 2016)
abj2016.py
posterior
fjaellet/abj2016
6
python
def posterior(distarray, pi, sigma_pi, prior='exponential'): '\n Posterior distance distribution.\n \n Input:\n distarray:distance array on which to calculate the posterior PDF\n pi: parallax (array or scalar)\n sigma_pi: parallax_uncertainty (array or scalar)\n Optional:\n prior: String. Decides which prior to use (at present either "exponential", "uniform_density", "uniform_distance")\n Output:\n Posterior distance PDF (up to a factor), given parallax and parallax uncertainty (formula 2 of Astraatmadja&Bailer-Jones 2016)\n ' if (prior == 'exponential'): prior = exp_prior elif (prior == 'uniform_density'): prior = uniform_density_prior elif (prior == 'uniform_distance'): prior = uniform_distance_prior else: raise ValueError('Prior keyword does not exist') if np.isscalar(pi): return (prior(distarray) * likelihood(pi, distarray, sigma_pi)) else: return (prior(distarray)[(:, np.newaxis)] * likelihood(pi, distarray, sigma_pi))
def posterior(distarray, pi, sigma_pi, prior='exponential'): '\n Posterior distance distribution.\n \n Input:\n distarray:distance array on which to calculate the posterior PDF\n pi: parallax (array or scalar)\n sigma_pi: parallax_uncertainty (array or scalar)\n Optional:\n prior: String. Decides which prior to use (at present either "exponential", "uniform_density", "uniform_distance")\n Output:\n Posterior distance PDF (up to a factor), given parallax and parallax uncertainty (formula 2 of Astraatmadja&Bailer-Jones 2016)\n ' if (prior == 'exponential'): prior = exp_prior elif (prior == 'uniform_density'): prior = uniform_density_prior elif (prior == 'uniform_distance'): prior = uniform_distance_prior else: raise ValueError('Prior keyword does not exist') if np.isscalar(pi): return (prior(distarray) * likelihood(pi, distarray, sigma_pi)) else: return (prior(distarray)[(:, np.newaxis)] * likelihood(pi, distarray, sigma_pi))<|docstring|>Posterior distance distribution. Input: distarray:distance array on which to calculate the posterior PDF pi: parallax (array or scalar) sigma_pi: parallax_uncertainty (array or scalar) Optional: prior: String. Decides which prior to use (at present either "exponential", "uniform_density", "uniform_distance") Output: Posterior distance PDF (up to a factor), given parallax and parallax uncertainty (formula 2 of Astraatmadja&Bailer-Jones 2016)<|endoftext|>
c89f0f48b17618101eed9af71114618fc7872a32c73e8077b12321251839604c
def __init__(self, pi, sigma_pi, min_dist=0.0, max_dist=30.0, resolution=10000, **kwargs): '\n Returns a distance array and the corresponding distance PDF\n \n Input:\n pi: parallax (array or scalar)\n sigma_pi: parallax_uncertainty (array or scalar)\n Optional:\n min_dist: minimum allowed distance\n max_dist: maximum allowed distance\n resolution:resolution of the distance PDF\n Output:\n (none)\n Object properties:\n distarray, distpdf - distance array & corresponding posterior \n distance PDF (1D if pi&sigma_pi are scalar, \n 2D if not)\n meandist, diststd, modedist - statistics of the distance PDF\n ' self.distarray = np.linspace(min_dist, max_dist, resolution) distpdf = posterior(self.distarray, pi, sigma_pi, **kwargs) self.distpdf = (distpdf / np.sum(distpdf, axis=0)) if np.isscalar(pi): self.meandist = np.average(self.distarray, axis=0, weights=self.distpdf) self.diststd = np.sqrt(np.average(((self.distarray - self.meandist) ** 2), axis=0, weights=self.distpdf)) self.modedist = self.distarray[np.argmax(self.distpdf)] else: self.meandist = np.sum(((self.distpdf * self.distarray[(:, np.newaxis)]) / np.sum(self.distpdf, axis=0)), axis=0) self.diststd = np.sqrt(np.sum((self.distpdf * ((self.distarray[(:, np.newaxis)] - (self.meandist[(np.newaxis, :)] / np.sum(self.distpdf, axis=0))) ** 2.0)), axis=0)) self.modedist = self.distarray[np.argmax(self.distpdf, axis=0)]
Returns a distance array and the corresponding distance PDF Input: pi: parallax (array or scalar) sigma_pi: parallax_uncertainty (array or scalar) Optional: min_dist: minimum allowed distance max_dist: maximum allowed distance resolution:resolution of the distance PDF Output: (none) Object properties: distarray, distpdf - distance array & corresponding posterior distance PDF (1D if pi&sigma_pi are scalar, 2D if not) meandist, diststd, modedist - statistics of the distance PDF
abj2016.py
__init__
fjaellet/abj2016
6
python
def __init__(self, pi, sigma_pi, min_dist=0.0, max_dist=30.0, resolution=10000, **kwargs): '\n Returns a distance array and the corresponding distance PDF\n \n Input:\n pi: parallax (array or scalar)\n sigma_pi: parallax_uncertainty (array or scalar)\n Optional:\n min_dist: minimum allowed distance\n max_dist: maximum allowed distance\n resolution:resolution of the distance PDF\n Output:\n (none)\n Object properties:\n distarray, distpdf - distance array & corresponding posterior \n distance PDF (1D if pi&sigma_pi are scalar, \n 2D if not)\n meandist, diststd, modedist - statistics of the distance PDF\n ' self.distarray = np.linspace(min_dist, max_dist, resolution) distpdf = posterior(self.distarray, pi, sigma_pi, **kwargs) self.distpdf = (distpdf / np.sum(distpdf, axis=0)) if np.isscalar(pi): self.meandist = np.average(self.distarray, axis=0, weights=self.distpdf) self.diststd = np.sqrt(np.average(((self.distarray - self.meandist) ** 2), axis=0, weights=self.distpdf)) self.modedist = self.distarray[np.argmax(self.distpdf)] else: self.meandist = np.sum(((self.distpdf * self.distarray[(:, np.newaxis)]) / np.sum(self.distpdf, axis=0)), axis=0) self.diststd = np.sqrt(np.sum((self.distpdf * ((self.distarray[(:, np.newaxis)] - (self.meandist[(np.newaxis, :)] / np.sum(self.distpdf, axis=0))) ** 2.0)), axis=0)) self.modedist = self.distarray[np.argmax(self.distpdf, axis=0)]
def __init__(self, pi, sigma_pi, min_dist=0.0, max_dist=30.0, resolution=10000, **kwargs): '\n Returns a distance array and the corresponding distance PDF\n \n Input:\n pi: parallax (array or scalar)\n sigma_pi: parallax_uncertainty (array or scalar)\n Optional:\n min_dist: minimum allowed distance\n max_dist: maximum allowed distance\n resolution:resolution of the distance PDF\n Output:\n (none)\n Object properties:\n distarray, distpdf - distance array & corresponding posterior \n distance PDF (1D if pi&sigma_pi are scalar, \n 2D if not)\n meandist, diststd, modedist - statistics of the distance PDF\n ' self.distarray = np.linspace(min_dist, max_dist, resolution) distpdf = posterior(self.distarray, pi, sigma_pi, **kwargs) self.distpdf = (distpdf / np.sum(distpdf, axis=0)) if np.isscalar(pi): self.meandist = np.average(self.distarray, axis=0, weights=self.distpdf) self.diststd = np.sqrt(np.average(((self.distarray - self.meandist) ** 2), axis=0, weights=self.distpdf)) self.modedist = self.distarray[np.argmax(self.distpdf)] else: self.meandist = np.sum(((self.distpdf * self.distarray[(:, np.newaxis)]) / np.sum(self.distpdf, axis=0)), axis=0) self.diststd = np.sqrt(np.sum((self.distpdf * ((self.distarray[(:, np.newaxis)] - (self.meandist[(np.newaxis, :)] / np.sum(self.distpdf, axis=0))) ** 2.0)), axis=0)) self.modedist = self.distarray[np.argmax(self.distpdf, axis=0)]<|docstring|>Returns a distance array and the corresponding distance PDF Input: pi: parallax (array or scalar) sigma_pi: parallax_uncertainty (array or scalar) Optional: min_dist: minimum allowed distance max_dist: maximum allowed distance resolution:resolution of the distance PDF Output: (none) Object properties: distarray, distpdf - distance array & corresponding posterior distance PDF (1D if pi&sigma_pi are scalar, 2D if not) meandist, diststd, modedist - statistics of the distance PDF<|endoftext|>
fc0ac03b35f3b4d2225e49a4dc1fcd5a8290ba458ee7608ab7cd9700f35c3585
@pytest.fixture def runner(app): "A test runner for the app's Click commands." return app.test_cli_runner()
A test runner for the app's Click commands.
tests/conftest.py
runner
MVEMCJSUNPE/microblog-ci
0
python
@pytest.fixture def runner(app): return app.test_cli_runner()
@pytest.fixture def runner(app): return app.test_cli_runner()<|docstring|>A test runner for the app's Click commands.<|endoftext|>
a2919ef759132739711e388208f52de5ea3eef5147f16ace945ebc5991671f62
def Generate_Layout_1(): '\n Generates a layout dictionary for a single 28x14 display, according to the layout specifications.\n :return:\n ' output = {} for i in range(28): for j in range(7): output[(j, i)] = (1, i, j) for i in range(28): for j in range(7): output[((j + 7), i)] = (2, i, j) return output
Generates a layout dictionary for a single 28x14 display, according to the layout specifications. :return:
Generate_Layout.py
Generate_Layout_1
chapman-mcd/Flip-Sign
1
python
def Generate_Layout_1(): '\n Generates a layout dictionary for a single 28x14 display, according to the layout specifications.\n :return:\n ' output = {} for i in range(28): for j in range(7): output[(j, i)] = (1, i, j) for i in range(28): for j in range(7): output[((j + 7), i)] = (2, i, j) return output
def Generate_Layout_1(): '\n Generates a layout dictionary for a single 28x14 display, according to the layout specifications.\n :return:\n ' output = {} for i in range(28): for j in range(7): output[(j, i)] = (1, i, j) for i in range(28): for j in range(7): output[((j + 7), i)] = (2, i, j) return output<|docstring|>Generates a layout dictionary for a single 28x14 display, according to the layout specifications. :return:<|endoftext|>
3f3323ea348991cfb97086402a547eb7232ce0276cb35e20dcdcd580a2f7b7b2
def Generate_Layout_2(): '\n Generates a layout dictionary for the main sign project, according to the layout spec.\n :return: Dictionary, indicating the pixel layout of the sign\n ' output = {} for x in range(6): for z in range(3): for i in range(28): for j in range(7): output[((j + (7 * z)), (i + (28 * x)))] = ((z + (3 * x)), (27 - i), (6 - j)) return output
Generates a layout dictionary for the main sign project, according to the layout spec. :return: Dictionary, indicating the pixel layout of the sign
Generate_Layout.py
Generate_Layout_2
chapman-mcd/Flip-Sign
1
python
def Generate_Layout_2(): '\n Generates a layout dictionary for the main sign project, according to the layout spec.\n :return: Dictionary, indicating the pixel layout of the sign\n ' output = {} for x in range(6): for z in range(3): for i in range(28): for j in range(7): output[((j + (7 * z)), (i + (28 * x)))] = ((z + (3 * x)), (27 - i), (6 - j)) return output
def Generate_Layout_2(): '\n Generates a layout dictionary for the main sign project, according to the layout spec.\n :return: Dictionary, indicating the pixel layout of the sign\n ' output = {} for x in range(6): for z in range(3): for i in range(28): for j in range(7): output[((j + (7 * z)), (i + (28 * x)))] = ((z + (3 * x)), (27 - i), (6 - j)) return output<|docstring|>Generates a layout dictionary for the main sign project, according to the layout spec. :return: Dictionary, indicating the pixel layout of the sign<|endoftext|>
cc39cf89547b4a15c12f699c2208138245bedac4db095041b126c73496d7f71e
def generate_addresses(): '\n Generates a list of all display addresses\n :return: a list of display addresses in the flip dot display\n ' addr = ([b''] * 18) addr[0] = b'\x00' addr[1] = b'\x01' addr[2] = b'\x02' addr[3] = b'\x03' addr[4] = b'\x04' addr[5] = b'\x05' addr[6] = b'\x06' addr[7] = b'\x07' addr[8] = b'\x08' addr[9] = b'\t' addr[10] = b'\n' addr[11] = b'\x0b' addr[12] = b'\x0c' addr[13] = b'\r' addr[14] = b'\x0e' addr[15] = b'\x0f' addr[16] = b'\x10' addr[17] = b'\x11' return addr
Generates a list of all display addresses :return: a list of display addresses in the flip dot display
Generate_Layout.py
generate_addresses
chapman-mcd/Flip-Sign
1
python
def generate_addresses(): '\n Generates a list of all display addresses\n :return: a list of display addresses in the flip dot display\n ' addr = ([b] * 18) addr[0] = b'\x00' addr[1] = b'\x01' addr[2] = b'\x02' addr[3] = b'\x03' addr[4] = b'\x04' addr[5] = b'\x05' addr[6] = b'\x06' addr[7] = b'\x07' addr[8] = b'\x08' addr[9] = b'\t' addr[10] = b'\n' addr[11] = b'\x0b' addr[12] = b'\x0c' addr[13] = b'\r' addr[14] = b'\x0e' addr[15] = b'\x0f' addr[16] = b'\x10' addr[17] = b'\x11' return addr
def generate_addresses(): '\n Generates a list of all display addresses\n :return: a list of display addresses in the flip dot display\n ' addr = ([b] * 18) addr[0] = b'\x00' addr[1] = b'\x01' addr[2] = b'\x02' addr[3] = b'\x03' addr[4] = b'\x04' addr[5] = b'\x05' addr[6] = b'\x06' addr[7] = b'\x07' addr[8] = b'\x08' addr[9] = b'\t' addr[10] = b'\n' addr[11] = b'\x0b' addr[12] = b'\x0c' addr[13] = b'\r' addr[14] = b'\x0e' addr[15] = b'\x0f' addr[16] = b'\x10' addr[17] = b'\x11' return addr<|docstring|>Generates a list of all display addresses :return: a list of display addresses in the flip dot display<|endoftext|>
1eb0ae585a4d6e96161f2f73561c3a9da4acec16c5530f300d21c0056f2c9c01
def reset_command(): '\n Returns a command that can be sent to the display to turn all dots white\n :return: a binary string command that sets all dots white\n ' head = b'\x80' cmd = b'\x84' tail = b'\x8f' refreshcmd = b'\x82' result = b'' for address in generate_addresses(): result += ((((head + cmd) + address) + (b'\x7f' * 28)) + tail) result += ((head + refreshcmd) + tail) return result
Returns a command that can be sent to the display to turn all dots white :return: a binary string command that sets all dots white
Generate_Layout.py
reset_command
chapman-mcd/Flip-Sign
1
python
def reset_command(): '\n Returns a command that can be sent to the display to turn all dots white\n :return: a binary string command that sets all dots white\n ' head = b'\x80' cmd = b'\x84' tail = b'\x8f' refreshcmd = b'\x82' result = b for address in generate_addresses(): result += ((((head + cmd) + address) + (b'\x7f' * 28)) + tail) result += ((head + refreshcmd) + tail) return result
def reset_command(): '\n Returns a command that can be sent to the display to turn all dots white\n :return: a binary string command that sets all dots white\n ' head = b'\x80' cmd = b'\x84' tail = b'\x8f' refreshcmd = b'\x82' result = b for address in generate_addresses(): result += ((((head + cmd) + address) + (b'\x7f' * 28)) + tail) result += ((head + refreshcmd) + tail) return result<|docstring|>Returns a command that can be sent to the display to turn all dots white :return: a binary string command that sets all dots white<|endoftext|>
b93495c73039cb014e6029fe776f73220ffc5a0bf2e7f95d2d1a5345f0b6507f
def all_black_command(): '\n Returns a command that can be sent to the display to turn all dots black\n :return: a binary string command that sets all dots black\n ' head = b'\x80' cmd = b'\x84' tail = b'\x8f' refreshcmd = b'\x82' result = b'' for address in generate_addresses(): result += ((((head + cmd) + address) + (b'\x00' * 28)) + tail) result += ((head + refreshcmd) + tail) return result
Returns a command that can be sent to the display to turn all dots black :return: a binary string command that sets all dots black
Generate_Layout.py
all_black_command
chapman-mcd/Flip-Sign
1
python
def all_black_command(): '\n Returns a command that can be sent to the display to turn all dots black\n :return: a binary string command that sets all dots black\n ' head = b'\x80' cmd = b'\x84' tail = b'\x8f' refreshcmd = b'\x82' result = b for address in generate_addresses(): result += ((((head + cmd) + address) + (b'\x00' * 28)) + tail) result += ((head + refreshcmd) + tail) return result
def all_black_command(): '\n Returns a command that can be sent to the display to turn all dots black\n :return: a binary string command that sets all dots black\n ' head = b'\x80' cmd = b'\x84' tail = b'\x8f' refreshcmd = b'\x82' result = b for address in generate_addresses(): result += ((((head + cmd) + address) + (b'\x00' * 28)) + tail) result += ((head + refreshcmd) + tail) return result<|docstring|>Returns a command that can be sent to the display to turn all dots black :return: a binary string command that sets all dots black<|endoftext|>
b0c94fe053d9306e405d43f5b1a17efbb07088a38ad3433e06b9f1d435b3eaa8
def load(args): 'Load roles defaults and generate CHANGE_ME secrets' args.defaults = {} for role in args.glue['roles']: role_vars = yaml_load(('%s/ansible/roles/sf-%s/defaults/main.yml' % (args.share, role))) args.defaults.update(role_vars) for (key, value) in role_vars.items(): if (str(value).strip().replace('"', '') == 'CHANGE_ME'): if (key not in args.secrets): args.secrets[key] = str(uuid.uuid4()) args.glue['gateway_url'] = ('https://%s' % args.sfconfig['fqdn']) if args.sfconfig['debug']: for service in ('managesf', 'zuul', 'nodepool'): args.glue[('%s_loglevel' % service)] = 'DEBUG' args.glue[('%s_root_loglevel' % service)] = 'INFO' if (not args.skip_setup): yaml_dump(args.secrets, open(('%s/secrets.yaml' % args.lib), 'w')) args.glue.update(args.secrets)
Load roles defaults and generate CHANGE_ME secrets
sfconfig/groupvars.py
load
softwarefactory-project/sf-conf
1
python
def load(args): args.defaults = {} for role in args.glue['roles']: role_vars = yaml_load(('%s/ansible/roles/sf-%s/defaults/main.yml' % (args.share, role))) args.defaults.update(role_vars) for (key, value) in role_vars.items(): if (str(value).strip().replace('"', ) == 'CHANGE_ME'): if (key not in args.secrets): args.secrets[key] = str(uuid.uuid4()) args.glue['gateway_url'] = ('https://%s' % args.sfconfig['fqdn']) if args.sfconfig['debug']: for service in ('managesf', 'zuul', 'nodepool'): args.glue[('%s_loglevel' % service)] = 'DEBUG' args.glue[('%s_root_loglevel' % service)] = 'INFO' if (not args.skip_setup): yaml_dump(args.secrets, open(('%s/secrets.yaml' % args.lib), 'w')) args.glue.update(args.secrets)
def load(args): args.defaults = {} for role in args.glue['roles']: role_vars = yaml_load(('%s/ansible/roles/sf-%s/defaults/main.yml' % (args.share, role))) args.defaults.update(role_vars) for (key, value) in role_vars.items(): if (str(value).strip().replace('"', ) == 'CHANGE_ME'): if (key not in args.secrets): args.secrets[key] = str(uuid.uuid4()) args.glue['gateway_url'] = ('https://%s' % args.sfconfig['fqdn']) if args.sfconfig['debug']: for service in ('managesf', 'zuul', 'nodepool'): args.glue[('%s_loglevel' % service)] = 'DEBUG' args.glue[('%s_root_loglevel' % service)] = 'INFO' if (not args.skip_setup): yaml_dump(args.secrets, open(('%s/secrets.yaml' % args.lib), 'w')) args.glue.update(args.secrets)<|docstring|>Load roles defaults and generate CHANGE_ME secrets<|endoftext|>
5923aed78300221450b8542791276b07d6a68105df5dfc363f4887ae31de9f60
def db_for_read(self, model, **hints): '\n\t\tAttempts to read kbbi models go to kbbi.\n\t\t' if (model._meta.app_label == 'kbbi'): return 'kbbi_db' return None
Attempts to read kbbi models go to kbbi.
kbbi/router.py
db_for_read
efenfauzi/django_kbb
10
python
def db_for_read(self, model, **hints): '\n\t\t\n\t\t' if (model._meta.app_label == 'kbbi'): return 'kbbi_db' return None
def db_for_read(self, model, **hints): '\n\t\t\n\t\t' if (model._meta.app_label == 'kbbi'): return 'kbbi_db' return None<|docstring|>Attempts to read kbbi models go to kbbi.<|endoftext|>
af1fda962e593a855746c192ec29065f10b32dd7145c8cffb76ffae3b6367426
def db_for_write(self, model, **hints): '\n\t\tAttempts to write kbbi models go to kbbi.\n\t\t' if (model._meta.app_label == 'kbbi'): return 'kbbi_db' return None
Attempts to write kbbi models go to kbbi.
kbbi/router.py
db_for_write
efenfauzi/django_kbb
10
python
def db_for_write(self, model, **hints): '\n\t\t\n\t\t' if (model._meta.app_label == 'kbbi'): return 'kbbi_db' return None
def db_for_write(self, model, **hints): '\n\t\t\n\t\t' if (model._meta.app_label == 'kbbi'): return 'kbbi_db' return None<|docstring|>Attempts to write kbbi models go to kbbi.<|endoftext|>
a8084dcb16187a0d17a8ac0b694be091f545ab982c562f7ef5c107589bd31f07
def allow_relation(self, obj1, obj2, **hints): '\n\t\tAllow relations if a model in the kbbi app is involved.\n\t\t' if ((obj1._meta.app_label == 'kbbi') or (obj2._meta.app_label == 'kbbi')): return True return None
Allow relations if a model in the kbbi app is involved.
kbbi/router.py
allow_relation
efenfauzi/django_kbb
10
python
def allow_relation(self, obj1, obj2, **hints): '\n\t\t\n\t\t' if ((obj1._meta.app_label == 'kbbi') or (obj2._meta.app_label == 'kbbi')): return True return None
def allow_relation(self, obj1, obj2, **hints): '\n\t\t\n\t\t' if ((obj1._meta.app_label == 'kbbi') or (obj2._meta.app_label == 'kbbi')): return True return None<|docstring|>Allow relations if a model in the kbbi app is involved.<|endoftext|>
409be337880bfaaf1271e07d0723caf7843d47202dd8d059c880f3b6c4415d7e
def allow_migrate(self, db, app_label, model_name=None, **hints): "\n\t\tMake sure the kbbi app only appears in the 'kbbi'\n\t\tdatabase.\n\t\t" if (app_label == 'kbbi'): return (db == 'kbbi_db') return None
Make sure the kbbi app only appears in the 'kbbi' database.
kbbi/router.py
allow_migrate
efenfauzi/django_kbb
10
python
def allow_migrate(self, db, app_label, model_name=None, **hints): "\n\t\tMake sure the kbbi app only appears in the 'kbbi'\n\t\tdatabase.\n\t\t" if (app_label == 'kbbi'): return (db == 'kbbi_db') return None
def allow_migrate(self, db, app_label, model_name=None, **hints): "\n\t\tMake sure the kbbi app only appears in the 'kbbi'\n\t\tdatabase.\n\t\t" if (app_label == 'kbbi'): return (db == 'kbbi_db') return None<|docstring|>Make sure the kbbi app only appears in the 'kbbi' database.<|endoftext|>
e56c8f7b7b638051642971cfae5f82b52caa34a04df07803e5d1b7251acc49da
def trim_batch(input_ids, pad_token_id, attention_mask=None): 'Remove columns that are populated exclusively by pad_token_id' keep_column_mask = input_ids.ne(pad_token_id).any(dim=0) if (attention_mask is None): return input_ids[(:, keep_column_mask)] else: return (input_ids[(:, keep_column_mask)], attention_mask[(:, keep_column_mask)])
Remove columns that are populated exclusively by pad_token_id
utils/angle_utils.py
trim_batch
allenai/entailment_bank
11
python
def trim_batch(input_ids, pad_token_id, attention_mask=None): keep_column_mask = input_ids.ne(pad_token_id).any(dim=0) if (attention_mask is None): return input_ids[(:, keep_column_mask)] else: return (input_ids[(:, keep_column_mask)], attention_mask[(:, keep_column_mask)])
def trim_batch(input_ids, pad_token_id, attention_mask=None): keep_column_mask = input_ids.ne(pad_token_id).any(dim=0) if (attention_mask is None): return input_ids[(:, keep_column_mask)] else: return (input_ids[(:, keep_column_mask)], attention_mask[(:, keep_column_mask)])<|docstring|>Remove columns that are populated exclusively by pad_token_id<|endoftext|>
6ea50c891c104804c06c6a2831b10fa874d31cb96a9d6726b7b353aba756463b
def pickle_save(obj, path): 'pickle.dump(obj, path)' with open(path, 'wb') as f: return pickle.dump(obj, f)
pickle.dump(obj, path)
utils/angle_utils.py
pickle_save
allenai/entailment_bank
11
python
def pickle_save(obj, path): with open(path, 'wb') as f: return pickle.dump(obj, f)
def pickle_save(obj, path): with open(path, 'wb') as f: return pickle.dump(obj, f)<|docstring|>pickle.dump(obj, path)<|endoftext|>
03a447ebd567d6e24b86f5cef198237f79996dd2328aafbff65e2ea9a31a632b
def product_ansatz_parameters(num_qubits, depth, value): 'Returns Parameters for a product ansatz on the given\n number of qubits for the input depth.\n\n Args:\n num_qubits : int\n Number of qubits in the ansatz.\n\n depth : int\n Number of parameterized gates appearing on each qubit.\n\n value : Union[float, int]\n Initial parameter value that appears in all gates.\n ' if (type(num_qubits) != int): raise ValueError('num_qubits must be an integer.') if (type(depth) != int): raise ValueError('depth must be an integer.') try: value = float(value) except TypeError: print('Invalid type for value.') raise TypeError params = {} for qubit in range(num_qubits): params[qubit] = ([value] * depth) return Parameters(params)
Returns Parameters for a product ansatz on the given number of qubits for the input depth. Args: num_qubits : int Number of qubits in the ansatz. depth : int Number of parameterized gates appearing on each qubit. value : Union[float, int] Initial parameter value that appears in all gates.
src/nisqai/layer/_params.py
product_ansatz_parameters
obliviateandsurrender/nisqai-dev
14
python
def product_ansatz_parameters(num_qubits, depth, value): 'Returns Parameters for a product ansatz on the given\n number of qubits for the input depth.\n\n Args:\n num_qubits : int\n Number of qubits in the ansatz.\n\n depth : int\n Number of parameterized gates appearing on each qubit.\n\n value : Union[float, int]\n Initial parameter value that appears in all gates.\n ' if (type(num_qubits) != int): raise ValueError('num_qubits must be an integer.') if (type(depth) != int): raise ValueError('depth must be an integer.') try: value = float(value) except TypeError: print('Invalid type for value.') raise TypeError params = {} for qubit in range(num_qubits): params[qubit] = ([value] * depth) return Parameters(params)
def product_ansatz_parameters(num_qubits, depth, value): 'Returns Parameters for a product ansatz on the given\n number of qubits for the input depth.\n\n Args:\n num_qubits : int\n Number of qubits in the ansatz.\n\n depth : int\n Number of parameterized gates appearing on each qubit.\n\n value : Union[float, int]\n Initial parameter value that appears in all gates.\n ' if (type(num_qubits) != int): raise ValueError('num_qubits must be an integer.') if (type(depth) != int): raise ValueError('depth must be an integer.') try: value = float(value) except TypeError: print('Invalid type for value.') raise TypeError params = {} for qubit in range(num_qubits): params[qubit] = ([value] * depth) return Parameters(params)<|docstring|>Returns Parameters for a product ansatz on the given number of qubits for the input depth. Args: num_qubits : int Number of qubits in the ansatz. depth : int Number of parameterized gates appearing on each qubit. value : Union[float, int] Initial parameter value that appears in all gates.<|endoftext|>
a8292b80de9583bb420c43a4bba22b8ce6ef19d8bba58933e411003e0892c7b6
def mera_ansatz_parameters(num_qubits, depth, value): 'Returns a Parameters object for the MERA Tensor network ansatz.\n\n Args:\n num_qubits : int\n Number of qubits in the parameterized circuit.\n\n depth : int [must equal log2(num_qubits)]\n Number of "hyperlayers" in MERA network, i.e., the number of different "scales" of alternating layers.\n\n Example. Here is a depth 3 MERA network:\n\n |0>-----||--\n ||\n |0>--||-||-------||--\n || ||\n |0>--||-||-- ||\n || ||\n |0>--||-||----||-||----||--\n || || ||\n |0>--||-||-- || ||\n || || ||\n |0>--||-||----||-||-- ||\n || || ||\n |0>--||-||-- || ||\n || || ||\n |0>-----||-------||----||------MEASURE\n 1 2 3\n \n The ||\'s represent 2-body gates and which qubits they operate on.\n Qubit wires that are discontinued are being traced out / discarded.\n \n Layer 1 with num_qubits/(2^1) alternating gates; \n Layer 2 with num_qubits/(2^2) alternating gates;\n ...\n Layer i with num_qubits/(2^i) alternating gates.\n\n Thus we see why the constraint depth = log2(num_qubits) is necessary,\n and that depth is NOT the actual circuit depth (it is actually\n 2*depth - 1 gates deep).\n\n For the inspiration of our implementation, see "Hierarchical Quantum Classifiers" by\n Grant et al. at https://arxiv.org/abs/1804.03680\n\n value : float\n Initial parameter value that appears in all gates.\n ' if (type(num_qubits) != int): raise ValueError('num_qubits must be an integer.') if (((num_qubits & (num_qubits - 1)) == 1) or (num_qubits == 0)): raise ValueError('num_qubits must be a power of 2 for TTN / MERA circuit topology.') if (type(depth) != int): raise ValueError('depth must be an integer.') if (log2(num_qubits) != depth): raise ValueError('log2(num_qubits) must equal depth for TTN / MERA circuit topology.') try: value = float(value) except TypeError: print('Invalid type for value.') raise TypeError params = {} for i in range(num_qubits): params[i] = ([None] * ((2 * depth) - 1)) for i in range(depth, 0, (- 1)): for j in range(2): for g in range((((2 ** (i - 1)) - 1) + j)): q = (((2 ** ((depth - i) + 1)) * ((g - (j / 2)) + 1)) - 1) layer = ((2 * (depth - i)) + j) if (i == 1): layer -= 1 params[q][layer] = value params[(q + (2 ** (depth - i)))][layer] = value return Parameters(params)
Returns a Parameters object for the MERA Tensor network ansatz. Args: num_qubits : int Number of qubits in the parameterized circuit. depth : int [must equal log2(num_qubits)] Number of "hyperlayers" in MERA network, i.e., the number of different "scales" of alternating layers. Example. Here is a depth 3 MERA network: |0>-----||-- || |0>--||-||-------||-- || || |0>--||-||-- || || || |0>--||-||----||-||----||-- || || || |0>--||-||-- || || || || || |0>--||-||----||-||-- || || || || |0>--||-||-- || || || || || |0>-----||-------||----||------MEASURE 1 2 3 The ||'s represent 2-body gates and which qubits they operate on. Qubit wires that are discontinued are being traced out / discarded. Layer 1 with num_qubits/(2^1) alternating gates; Layer 2 with num_qubits/(2^2) alternating gates; ... Layer i with num_qubits/(2^i) alternating gates. Thus we see why the constraint depth = log2(num_qubits) is necessary, and that depth is NOT the actual circuit depth (it is actually 2*depth - 1 gates deep). For the inspiration of our implementation, see "Hierarchical Quantum Classifiers" by Grant et al. at https://arxiv.org/abs/1804.03680 value : float Initial parameter value that appears in all gates.
src/nisqai/layer/_params.py
mera_ansatz_parameters
obliviateandsurrender/nisqai-dev
14
python
def mera_ansatz_parameters(num_qubits, depth, value): 'Returns a Parameters object for the MERA Tensor network ansatz.\n\n Args:\n num_qubits : int\n Number of qubits in the parameterized circuit.\n\n depth : int [must equal log2(num_qubits)]\n Number of "hyperlayers" in MERA network, i.e., the number of different "scales" of alternating layers.\n\n Example. Here is a depth 3 MERA network:\n\n |0>-----||--\n ||\n |0>--||-||-------||--\n || ||\n |0>--||-||-- ||\n || ||\n |0>--||-||----||-||----||--\n || || ||\n |0>--||-||-- || ||\n || || ||\n |0>--||-||----||-||-- ||\n || || ||\n |0>--||-||-- || ||\n || || ||\n |0>-----||-------||----||------MEASURE\n 1 2 3\n \n The ||\'s represent 2-body gates and which qubits they operate on.\n Qubit wires that are discontinued are being traced out / discarded.\n \n Layer 1 with num_qubits/(2^1) alternating gates; \n Layer 2 with num_qubits/(2^2) alternating gates;\n ...\n Layer i with num_qubits/(2^i) alternating gates.\n\n Thus we see why the constraint depth = log2(num_qubits) is necessary,\n and that depth is NOT the actual circuit depth (it is actually\n 2*depth - 1 gates deep).\n\n For the inspiration of our implementation, see "Hierarchical Quantum Classifiers" by\n Grant et al. at https://arxiv.org/abs/1804.03680\n\n value : float\n Initial parameter value that appears in all gates.\n ' if (type(num_qubits) != int): raise ValueError('num_qubits must be an integer.') if (((num_qubits & (num_qubits - 1)) == 1) or (num_qubits == 0)): raise ValueError('num_qubits must be a power of 2 for TTN / MERA circuit topology.') if (type(depth) != int): raise ValueError('depth must be an integer.') if (log2(num_qubits) != depth): raise ValueError('log2(num_qubits) must equal depth for TTN / MERA circuit topology.') try: value = float(value) except TypeError: print('Invalid type for value.') raise TypeError params = {} for i in range(num_qubits): params[i] = ([None] * ((2 * depth) - 1)) for i in range(depth, 0, (- 1)): for j in range(2): for g in range((((2 ** (i - 1)) - 1) + j)): q = (((2 ** ((depth - i) + 1)) * ((g - (j / 2)) + 1)) - 1) layer = ((2 * (depth - i)) + j) if (i == 1): layer -= 1 params[q][layer] = value params[(q + (2 ** (depth - i)))][layer] = value return Parameters(params)
def mera_ansatz_parameters(num_qubits, depth, value): 'Returns a Parameters object for the MERA Tensor network ansatz.\n\n Args:\n num_qubits : int\n Number of qubits in the parameterized circuit.\n\n depth : int [must equal log2(num_qubits)]\n Number of "hyperlayers" in MERA network, i.e., the number of different "scales" of alternating layers.\n\n Example. Here is a depth 3 MERA network:\n\n |0>-----||--\n ||\n |0>--||-||-------||--\n || ||\n |0>--||-||-- ||\n || ||\n |0>--||-||----||-||----||--\n || || ||\n |0>--||-||-- || ||\n || || ||\n |0>--||-||----||-||-- ||\n || || ||\n |0>--||-||-- || ||\n || || ||\n |0>-----||-------||----||------MEASURE\n 1 2 3\n \n The ||\'s represent 2-body gates and which qubits they operate on.\n Qubit wires that are discontinued are being traced out / discarded.\n \n Layer 1 with num_qubits/(2^1) alternating gates; \n Layer 2 with num_qubits/(2^2) alternating gates;\n ...\n Layer i with num_qubits/(2^i) alternating gates.\n\n Thus we see why the constraint depth = log2(num_qubits) is necessary,\n and that depth is NOT the actual circuit depth (it is actually\n 2*depth - 1 gates deep).\n\n For the inspiration of our implementation, see "Hierarchical Quantum Classifiers" by\n Grant et al. at https://arxiv.org/abs/1804.03680\n\n value : float\n Initial parameter value that appears in all gates.\n ' if (type(num_qubits) != int): raise ValueError('num_qubits must be an integer.') if (((num_qubits & (num_qubits - 1)) == 1) or (num_qubits == 0)): raise ValueError('num_qubits must be a power of 2 for TTN / MERA circuit topology.') if (type(depth) != int): raise ValueError('depth must be an integer.') if (log2(num_qubits) != depth): raise ValueError('log2(num_qubits) must equal depth for TTN / MERA circuit topology.') try: value = float(value) except TypeError: print('Invalid type for value.') raise TypeError params = {} for i in range(num_qubits): params[i] = ([None] * ((2 * depth) - 1)) for i in range(depth, 0, (- 1)): for j in range(2): for g in range((((2 ** (i - 1)) - 1) + j)): q = (((2 ** ((depth - i) + 1)) * ((g - (j / 2)) + 1)) - 1) layer = ((2 * (depth - i)) + j) if (i == 1): layer -= 1 params[q][layer] = value params[(q + (2 ** (depth - i)))][layer] = value return Parameters(params)<|docstring|>Returns a Parameters object for the MERA Tensor network ansatz. Args: num_qubits : int Number of qubits in the parameterized circuit. depth : int [must equal log2(num_qubits)] Number of "hyperlayers" in MERA network, i.e., the number of different "scales" of alternating layers. Example. Here is a depth 3 MERA network: |0>-----||-- || |0>--||-||-------||-- || || |0>--||-||-- || || || |0>--||-||----||-||----||-- || || || |0>--||-||-- || || || || || |0>--||-||----||-||-- || || || || |0>--||-||-- || || || || || |0>-----||-------||----||------MEASURE 1 2 3 The ||'s represent 2-body gates and which qubits they operate on. Qubit wires that are discontinued are being traced out / discarded. Layer 1 with num_qubits/(2^1) alternating gates; Layer 2 with num_qubits/(2^2) alternating gates; ... Layer i with num_qubits/(2^i) alternating gates. Thus we see why the constraint depth = log2(num_qubits) is necessary, and that depth is NOT the actual circuit depth (it is actually 2*depth - 1 gates deep). For the inspiration of our implementation, see "Hierarchical Quantum Classifiers" by Grant et al. at https://arxiv.org/abs/1804.03680 value : float Initial parameter value that appears in all gates.<|endoftext|>
9e5f226d05cbb715e25965f2e317d53ed625c4bed09a7247e5650492d3473147
def __init__(self, parameters): 'Initializes a Parameters class.\n\n Args:\n parameters : dict[int, list[float]]\n Dictionary of\n\n {qubit : list of parameter values for qubit}\n\n pairs.\n\n IMPORTANT: All qubit indices must explicitly be included as keys, even if\n some qubits do not have parameterized gates.\n\n Qubits with no parameterized gate at a certain depth will have None in the list\n for that qubit index.\n\n Examples:\n\n parameters = {0 : [pi/4, pi/3],\n 1 : [pi/8, pi/6]}\n\n Corresponds to a circuit which looks like:\n\n Qubit 0 ----[pi/4]----[pi/3]----\n Qubit 1 ----[pi/8]----[pi/6]----\n\n That is: A circuit with two qubits, 0 and 1, where qubit 0 has\n parameters 1 and 2 for its first and second parameterized gates,\n respectively, and qubit 1 has parameters 3 and 4 for its first\n and second parameterized gates, respectively.\n\n Note that other unparameterized gates can appear in the circuit,\n at any point before, in between, or after parameterized gates.\n\n\n\n parameters = {0 : [1, 2],\n 1 : [None, None]\n 2 : [3, None]}\n\n Corresponds to a circuit which looks like:\n\n Qubit 0 ----[1]----[2]----\n Qubit 1 ------------------\n Qubit 2 ----[3]-----------\n\n That is: A circuit with three qubits. Qubit 0 has parameters 1 and 2\n for its first and second parameterized gates, respectively. Qubit 1\n has no parameterized gates. Qubit 2 has parameter 3 for its first\n parameterized gate.\n ' self._values = parameters self._num_qubits = len(self._values.keys()) self.names = self._make_parameter_names()
Initializes a Parameters class. Args: parameters : dict[int, list[float]] Dictionary of {qubit : list of parameter values for qubit} pairs. IMPORTANT: All qubit indices must explicitly be included as keys, even if some qubits do not have parameterized gates. Qubits with no parameterized gate at a certain depth will have None in the list for that qubit index. Examples: parameters = {0 : [pi/4, pi/3], 1 : [pi/8, pi/6]} Corresponds to a circuit which looks like: Qubit 0 ----[pi/4]----[pi/3]---- Qubit 1 ----[pi/8]----[pi/6]---- That is: A circuit with two qubits, 0 and 1, where qubit 0 has parameters 1 and 2 for its first and second parameterized gates, respectively, and qubit 1 has parameters 3 and 4 for its first and second parameterized gates, respectively. Note that other unparameterized gates can appear in the circuit, at any point before, in between, or after parameterized gates. parameters = {0 : [1, 2], 1 : [None, None] 2 : [3, None]} Corresponds to a circuit which looks like: Qubit 0 ----[1]----[2]---- Qubit 1 ------------------ Qubit 2 ----[3]----------- That is: A circuit with three qubits. Qubit 0 has parameters 1 and 2 for its first and second parameterized gates, respectively. Qubit 1 has no parameterized gates. Qubit 2 has parameter 3 for its first parameterized gate.
src/nisqai/layer/_params.py
__init__
obliviateandsurrender/nisqai-dev
14
python
def __init__(self, parameters): 'Initializes a Parameters class.\n\n Args:\n parameters : dict[int, list[float]]\n Dictionary of\n\n {qubit : list of parameter values for qubit}\n\n pairs.\n\n IMPORTANT: All qubit indices must explicitly be included as keys, even if\n some qubits do not have parameterized gates.\n\n Qubits with no parameterized gate at a certain depth will have None in the list\n for that qubit index.\n\n Examples:\n\n parameters = {0 : [pi/4, pi/3],\n 1 : [pi/8, pi/6]}\n\n Corresponds to a circuit which looks like:\n\n Qubit 0 ----[pi/4]----[pi/3]----\n Qubit 1 ----[pi/8]----[pi/6]----\n\n That is: A circuit with two qubits, 0 and 1, where qubit 0 has\n parameters 1 and 2 for its first and second parameterized gates,\n respectively, and qubit 1 has parameters 3 and 4 for its first\n and second parameterized gates, respectively.\n\n Note that other unparameterized gates can appear in the circuit,\n at any point before, in between, or after parameterized gates.\n\n\n\n parameters = {0 : [1, 2],\n 1 : [None, None]\n 2 : [3, None]}\n\n Corresponds to a circuit which looks like:\n\n Qubit 0 ----[1]----[2]----\n Qubit 1 ------------------\n Qubit 2 ----[3]-----------\n\n That is: A circuit with three qubits. Qubit 0 has parameters 1 and 2\n for its first and second parameterized gates, respectively. Qubit 1\n has no parameterized gates. Qubit 2 has parameter 3 for its first\n parameterized gate.\n ' self._values = parameters self._num_qubits = len(self._values.keys()) self.names = self._make_parameter_names()
def __init__(self, parameters): 'Initializes a Parameters class.\n\n Args:\n parameters : dict[int, list[float]]\n Dictionary of\n\n {qubit : list of parameter values for qubit}\n\n pairs.\n\n IMPORTANT: All qubit indices must explicitly be included as keys, even if\n some qubits do not have parameterized gates.\n\n Qubits with no parameterized gate at a certain depth will have None in the list\n for that qubit index.\n\n Examples:\n\n parameters = {0 : [pi/4, pi/3],\n 1 : [pi/8, pi/6]}\n\n Corresponds to a circuit which looks like:\n\n Qubit 0 ----[pi/4]----[pi/3]----\n Qubit 1 ----[pi/8]----[pi/6]----\n\n That is: A circuit with two qubits, 0 and 1, where qubit 0 has\n parameters 1 and 2 for its first and second parameterized gates,\n respectively, and qubit 1 has parameters 3 and 4 for its first\n and second parameterized gates, respectively.\n\n Note that other unparameterized gates can appear in the circuit,\n at any point before, in between, or after parameterized gates.\n\n\n\n parameters = {0 : [1, 2],\n 1 : [None, None]\n 2 : [3, None]}\n\n Corresponds to a circuit which looks like:\n\n Qubit 0 ----[1]----[2]----\n Qubit 1 ------------------\n Qubit 2 ----[3]-----------\n\n That is: A circuit with three qubits. Qubit 0 has parameters 1 and 2\n for its first and second parameterized gates, respectively. Qubit 1\n has no parameterized gates. Qubit 2 has parameter 3 for its first\n parameterized gate.\n ' self._values = parameters self._num_qubits = len(self._values.keys()) self.names = self._make_parameter_names()<|docstring|>Initializes a Parameters class. Args: parameters : dict[int, list[float]] Dictionary of {qubit : list of parameter values for qubit} pairs. IMPORTANT: All qubit indices must explicitly be included as keys, even if some qubits do not have parameterized gates. Qubits with no parameterized gate at a certain depth will have None in the list for that qubit index. Examples: parameters = {0 : [pi/4, pi/3], 1 : [pi/8, pi/6]} Corresponds to a circuit which looks like: Qubit 0 ----[pi/4]----[pi/3]---- Qubit 1 ----[pi/8]----[pi/6]---- That is: A circuit with two qubits, 0 and 1, where qubit 0 has parameters 1 and 2 for its first and second parameterized gates, respectively, and qubit 1 has parameters 3 and 4 for its first and second parameterized gates, respectively. Note that other unparameterized gates can appear in the circuit, at any point before, in between, or after parameterized gates. parameters = {0 : [1, 2], 1 : [None, None] 2 : [3, None]} Corresponds to a circuit which looks like: Qubit 0 ----[1]----[2]---- Qubit 1 ------------------ Qubit 2 ----[3]----------- That is: A circuit with three qubits. Qubit 0 has parameters 1 and 2 for its first and second parameterized gates, respectively. Qubit 1 has no parameterized gates. Qubit 2 has parameter 3 for its first parameterized gate.<|endoftext|>
d7e58ae9e5206201fac68a3960c59f8f1799c87ed51009e49881898fd14a0565
def _make_parameter_names(self): 'Returns a dictionary of names according to the standard naming convention.\n\n The standard naming convention is given by\n\n q_ABC_g_XYZ\n\n where\n\n ABC = three digit integer label of qubit\n\n and\n\n XYZ = three digit integer label of gate.\n\n Examples:\n q_000_g_005 = Fifth parameterized gate on qubit zero.\n q_999_g_024 = Twenty fourth (!) parameterized gate on qubit 999. (!!!)\n ' names = {} for qubit in self._values.keys(): names[qubit] = [] qubit_key = format(qubit, FORMAT_SPEC) for gate in range(len(self._values[qubit])): gate_key = format(gate, FORMAT_SPEC) names[qubit].append('q_{}_g_{}'.format(qubit_key, gate_key)) return names
Returns a dictionary of names according to the standard naming convention. The standard naming convention is given by q_ABC_g_XYZ where ABC = three digit integer label of qubit and XYZ = three digit integer label of gate. Examples: q_000_g_005 = Fifth parameterized gate on qubit zero. q_999_g_024 = Twenty fourth (!) parameterized gate on qubit 999. (!!!)
src/nisqai/layer/_params.py
_make_parameter_names
obliviateandsurrender/nisqai-dev
14
python
def _make_parameter_names(self): 'Returns a dictionary of names according to the standard naming convention.\n\n The standard naming convention is given by\n\n q_ABC_g_XYZ\n\n where\n\n ABC = three digit integer label of qubit\n\n and\n\n XYZ = three digit integer label of gate.\n\n Examples:\n q_000_g_005 = Fifth parameterized gate on qubit zero.\n q_999_g_024 = Twenty fourth (!) parameterized gate on qubit 999. (!!!)\n ' names = {} for qubit in self._values.keys(): names[qubit] = [] qubit_key = format(qubit, FORMAT_SPEC) for gate in range(len(self._values[qubit])): gate_key = format(gate, FORMAT_SPEC) names[qubit].append('q_{}_g_{}'.format(qubit_key, gate_key)) return names
def _make_parameter_names(self): 'Returns a dictionary of names according to the standard naming convention.\n\n The standard naming convention is given by\n\n q_ABC_g_XYZ\n\n where\n\n ABC = three digit integer label of qubit\n\n and\n\n XYZ = three digit integer label of gate.\n\n Examples:\n q_000_g_005 = Fifth parameterized gate on qubit zero.\n q_999_g_024 = Twenty fourth (!) parameterized gate on qubit 999. (!!!)\n ' names = {} for qubit in self._values.keys(): names[qubit] = [] qubit_key = format(qubit, FORMAT_SPEC) for gate in range(len(self._values[qubit])): gate_key = format(gate, FORMAT_SPEC) names[qubit].append('q_{}_g_{}'.format(qubit_key, gate_key)) return names<|docstring|>Returns a dictionary of names according to the standard naming convention. The standard naming convention is given by q_ABC_g_XYZ where ABC = three digit integer label of qubit and XYZ = three digit integer label of gate. Examples: q_000_g_005 = Fifth parameterized gate on qubit zero. q_999_g_024 = Twenty fourth (!) parameterized gate on qubit 999. (!!!)<|endoftext|>
78c19e99358c17e82ff0e2d3fc45ca7d8230fd19c96a09f648a8bce1ed0e41df
@property def values(self): 'Returns the current values of the Parameters as a dict.' return self._values
Returns the current values of the Parameters as a dict.
src/nisqai/layer/_params.py
values
obliviateandsurrender/nisqai-dev
14
python
@property def values(self): return self._values
@property def values(self): return self._values<|docstring|>Returns the current values of the Parameters as a dict.<|endoftext|>
53b02b8cc7003054d1cc58c3be706aaee0b401b40a9e46e4b4533ff50d8337e9
def list_values(self): 'Returns a one dimensional list of all parameter values.' return list(chain.from_iterable(self._values.values()))
Returns a one dimensional list of all parameter values.
src/nisqai/layer/_params.py
list_values
obliviateandsurrender/nisqai-dev
14
python
def list_values(self): return list(chain.from_iterable(self._values.values()))
def list_values(self): return list(chain.from_iterable(self._values.values()))<|docstring|>Returns a one dimensional list of all parameter values.<|endoftext|>
e4f88b58306cc808e25dcd800f7d89192a4151821fef6c93c94aca991aafe733
def list_names(self): 'Returns a one dimensional list of all parameter names.' return list(chain.from_iterable(self.names.values()))
Returns a one dimensional list of all parameter names.
src/nisqai/layer/_params.py
list_names
obliviateandsurrender/nisqai-dev
14
python
def list_names(self): return list(chain.from_iterable(self.names.values()))
def list_names(self): return list(chain.from_iterable(self.names.values()))<|docstring|>Returns a one dimensional list of all parameter names.<|endoftext|>
a5f7a3f46ac321efe55b078da2b55c66be9d517223d3f6d2c6dcda8bc9c31d9c
def grid_values(self): 'Returns a two dimensional array of all parameter values.' return list(self._values.values())
Returns a two dimensional array of all parameter values.
src/nisqai/layer/_params.py
grid_values
obliviateandsurrender/nisqai-dev
14
python
def grid_values(self): return list(self._values.values())
def grid_values(self): return list(self._values.values())<|docstring|>Returns a two dimensional array of all parameter values.<|endoftext|>
60d862d05c907a559332cbf424aa8177364d730b2462696fbf78cd07b4905853
def grid_names(self): 'Returns a two dimensional array of all parameter names.' return list(self.names.values())
Returns a two dimensional array of all parameter names.
src/nisqai/layer/_params.py
grid_names
obliviateandsurrender/nisqai-dev
14
python
def grid_names(self): return list(self.names.values())
def grid_names(self): return list(self.names.values())<|docstring|>Returns a two dimensional array of all parameter names.<|endoftext|>
7750e2708cb59efbda3ab1ed7f4ce80fc90c875ae68bce7b4fff96ba4103fda7
def memory_map(self): 'Returns a memory map for use in pyQuil.\n\n A memory map is defined by a dictionary of\n\n {parameter name: parameter value}\n\n pairs.\n ' mem_map = {} for qubit in range(len(self._values)): for gate in range(len(self._values[qubit])): mem_map[self.names[qubit][gate]] = [float(self._values[qubit][gate])] return mem_map
Returns a memory map for use in pyQuil. A memory map is defined by a dictionary of {parameter name: parameter value} pairs.
src/nisqai/layer/_params.py
memory_map
obliviateandsurrender/nisqai-dev
14
python
def memory_map(self): 'Returns a memory map for use in pyQuil.\n\n A memory map is defined by a dictionary of\n\n {parameter name: parameter value}\n\n pairs.\n ' mem_map = {} for qubit in range(len(self._values)): for gate in range(len(self._values[qubit])): mem_map[self.names[qubit][gate]] = [float(self._values[qubit][gate])] return mem_map
def memory_map(self): 'Returns a memory map for use in pyQuil.\n\n A memory map is defined by a dictionary of\n\n {parameter name: parameter value}\n\n pairs.\n ' mem_map = {} for qubit in range(len(self._values)): for gate in range(len(self._values[qubit])): mem_map[self.names[qubit][gate]] = [float(self._values[qubit][gate])] return mem_map<|docstring|>Returns a memory map for use in pyQuil. A memory map is defined by a dictionary of {parameter name: parameter value} pairs.<|endoftext|>
0ed0784af3cb2eefdc2ec2a5454ebd20e58fa71023cf3e5dc06e26a9b791d0aa
def update_values(self, values): 'Updates the values of the Parameters in place.\n\n Args:\n values : Union[dict, list, tuple, numpy.ndarray]\n New parameter values.\n ' if (type(values) != dict): try: values = list(values) values = self._list_to_dict(values) except TypeError: raise InvalidParameterList('Invalid type for values. Must be a dict, list, tuple, or numpy array.') self._values = values
Updates the values of the Parameters in place. Args: values : Union[dict, list, tuple, numpy.ndarray] New parameter values.
src/nisqai/layer/_params.py
update_values
obliviateandsurrender/nisqai-dev
14
python
def update_values(self, values): 'Updates the values of the Parameters in place.\n\n Args:\n values : Union[dict, list, tuple, numpy.ndarray]\n New parameter values.\n ' if (type(values) != dict): try: values = list(values) values = self._list_to_dict(values) except TypeError: raise InvalidParameterList('Invalid type for values. Must be a dict, list, tuple, or numpy array.') self._values = values
def update_values(self, values): 'Updates the values of the Parameters in place.\n\n Args:\n values : Union[dict, list, tuple, numpy.ndarray]\n New parameter values.\n ' if (type(values) != dict): try: values = list(values) values = self._list_to_dict(values) except TypeError: raise InvalidParameterList('Invalid type for values. Must be a dict, list, tuple, or numpy array.') self._values = values<|docstring|>Updates the values of the Parameters in place. Args: values : Union[dict, list, tuple, numpy.ndarray] New parameter values.<|endoftext|>
419865ff746c698dc8654ad511741b90fb54db416bd29f7903fa294352ec98f7
def update_values_memory_map(self, values): 'Updates the values of the parameters in place and returns a memory map.\n\n Args:\n values : Union[dict, list, tuple, numpy.ndarray]\n New parameter values\n ' self.update_values(values) return self.memory_map()
Updates the values of the parameters in place and returns a memory map. Args: values : Union[dict, list, tuple, numpy.ndarray] New parameter values
src/nisqai/layer/_params.py
update_values_memory_map
obliviateandsurrender/nisqai-dev
14
python
def update_values_memory_map(self, values): 'Updates the values of the parameters in place and returns a memory map.\n\n Args:\n values : Union[dict, list, tuple, numpy.ndarray]\n New parameter values\n ' self.update_values(values) return self.memory_map()
def update_values_memory_map(self, values): 'Updates the values of the parameters in place and returns a memory map.\n\n Args:\n values : Union[dict, list, tuple, numpy.ndarray]\n New parameter values\n ' self.update_values(values) return self.memory_map()<|docstring|>Updates the values of the parameters in place and returns a memory map. Args: values : Union[dict, list, tuple, numpy.ndarray] New parameter values<|endoftext|>
c5fc1e99f5b10361359edd795a199197e29383a3be282a79acd77d26272faeb7
def _list_to_dict(self, lst): 'Converts a valid list to a dictionary and returns the dictionary.\n\n Valid lists have the correct number of parameters (including None elements).\n\n Args:\n lst : list\n List of parameter values, including None elements.\n\n Examples:\n lst = [1, 2, 3, None, 5, 6]\n\n is valid for a one qubit circuit with depth six\n\n ---[1]---[2]---[3]---[]----[5]---[6]---\n\n or a two qubit circuit with depth three\n\n ---[1]---[2]---[3]---\n ---[]----[5]---[6]---\n\n or a three qubit circuit with depth two\n\n ---[1]---[2]---\n ---[3]---[]----\n ---[5]---[6]---\n\n Any other parameterized circuit is NOT valid!\n ' (nqubits, depth) = self.shape() if ((nqubits * depth) != len(lst)): raise InvalidParameterList((('Number of parameters is not valid. It must be equal to' + '(nqubits * depth) = {}.\n'.format((nqubits * depth))) + 'Are you explicitly declaring None for non-parameterized gates?')) params = {} for ii in range(nqubits): params[ii] = lst[(ii * depth):((ii + 1) * depth)] return params
Converts a valid list to a dictionary and returns the dictionary. Valid lists have the correct number of parameters (including None elements). Args: lst : list List of parameter values, including None elements. Examples: lst = [1, 2, 3, None, 5, 6] is valid for a one qubit circuit with depth six ---[1]---[2]---[3]---[]----[5]---[6]--- or a two qubit circuit with depth three ---[1]---[2]---[3]--- ---[]----[5]---[6]--- or a three qubit circuit with depth two ---[1]---[2]--- ---[3]---[]---- ---[5]---[6]--- Any other parameterized circuit is NOT valid!
src/nisqai/layer/_params.py
_list_to_dict
obliviateandsurrender/nisqai-dev
14
python
def _list_to_dict(self, lst): 'Converts a valid list to a dictionary and returns the dictionary.\n\n Valid lists have the correct number of parameters (including None elements).\n\n Args:\n lst : list\n List of parameter values, including None elements.\n\n Examples:\n lst = [1, 2, 3, None, 5, 6]\n\n is valid for a one qubit circuit with depth six\n\n ---[1]---[2]---[3]---[]----[5]---[6]---\n\n or a two qubit circuit with depth three\n\n ---[1]---[2]---[3]---\n ---[]----[5]---[6]---\n\n or a three qubit circuit with depth two\n\n ---[1]---[2]---\n ---[3]---[]----\n ---[5]---[6]---\n\n Any other parameterized circuit is NOT valid!\n ' (nqubits, depth) = self.shape() if ((nqubits * depth) != len(lst)): raise InvalidParameterList((('Number of parameters is not valid. It must be equal to' + '(nqubits * depth) = {}.\n'.format((nqubits * depth))) + 'Are you explicitly declaring None for non-parameterized gates?')) params = {} for ii in range(nqubits): params[ii] = lst[(ii * depth):((ii + 1) * depth)] return params
def _list_to_dict(self, lst): 'Converts a valid list to a dictionary and returns the dictionary.\n\n Valid lists have the correct number of parameters (including None elements).\n\n Args:\n lst : list\n List of parameter values, including None elements.\n\n Examples:\n lst = [1, 2, 3, None, 5, 6]\n\n is valid for a one qubit circuit with depth six\n\n ---[1]---[2]---[3]---[]----[5]---[6]---\n\n or a two qubit circuit with depth three\n\n ---[1]---[2]---[3]---\n ---[]----[5]---[6]---\n\n or a three qubit circuit with depth two\n\n ---[1]---[2]---\n ---[3]---[]----\n ---[5]---[6]---\n\n Any other parameterized circuit is NOT valid!\n ' (nqubits, depth) = self.shape() if ((nqubits * depth) != len(lst)): raise InvalidParameterList((('Number of parameters is not valid. It must be equal to' + '(nqubits * depth) = {}.\n'.format((nqubits * depth))) + 'Are you explicitly declaring None for non-parameterized gates?')) params = {} for ii in range(nqubits): params[ii] = lst[(ii * depth):((ii + 1) * depth)] return params<|docstring|>Converts a valid list to a dictionary and returns the dictionary. Valid lists have the correct number of parameters (including None elements). Args: lst : list List of parameter values, including None elements. Examples: lst = [1, 2, 3, None, 5, 6] is valid for a one qubit circuit with depth six ---[1]---[2]---[3]---[]----[5]---[6]--- or a two qubit circuit with depth three ---[1]---[2]---[3]--- ---[]----[5]---[6]--- or a three qubit circuit with depth two ---[1]---[2]--- ---[3]---[]---- ---[5]---[6]--- Any other parameterized circuit is NOT valid!<|endoftext|>
11314daef3b335dd5ccdc0b3c125f9bedd369cf4309f4eecc2f6e6c70b5254d8
def depth(self): 'Returns the depth of the Parameters, defined as the maximum length\n of all parameter lists over all qubits.\n ' return len(max(self._values.values(), key=len))
Returns the depth of the Parameters, defined as the maximum length of all parameter lists over all qubits.
src/nisqai/layer/_params.py
depth
obliviateandsurrender/nisqai-dev
14
python
def depth(self): 'Returns the depth of the Parameters, defined as the maximum length\n of all parameter lists over all qubits.\n ' return len(max(self._values.values(), key=len))
def depth(self): 'Returns the depth of the Parameters, defined as the maximum length\n of all parameter lists over all qubits.\n ' return len(max(self._values.values(), key=len))<|docstring|>Returns the depth of the Parameters, defined as the maximum length of all parameter lists over all qubits.<|endoftext|>
ba378a92d2acece5002b9e1b0c03fdc53cfa856576738b179bb5df6175c48d21
def shape(self): 'Returns the (height, width) of a quantum circuit, where:\n\n height = number of qubits\n width = depth of the Parameters\n\n Note that some qubits may have fewer parameters than the width.\n\n Return type: Tuple\n ' return (self._num_qubits, self.depth())
Returns the (height, width) of a quantum circuit, where: height = number of qubits width = depth of the Parameters Note that some qubits may have fewer parameters than the width. Return type: Tuple
src/nisqai/layer/_params.py
shape
obliviateandsurrender/nisqai-dev
14
python
def shape(self): 'Returns the (height, width) of a quantum circuit, where:\n\n height = number of qubits\n width = depth of the Parameters\n\n Note that some qubits may have fewer parameters than the width.\n\n Return type: Tuple\n ' return (self._num_qubits, self.depth())
def shape(self): 'Returns the (height, width) of a quantum circuit, where:\n\n height = number of qubits\n width = depth of the Parameters\n\n Note that some qubits may have fewer parameters than the width.\n\n Return type: Tuple\n ' return (self._num_qubits, self.depth())<|docstring|>Returns the (height, width) of a quantum circuit, where: height = number of qubits width = depth of the Parameters Note that some qubits may have fewer parameters than the width. Return type: Tuple<|endoftext|>
afc7631d2c12bd572e60a8414a99a9448a3e367ed6d9566742482295d0e3366b
def declare_memory_references(self, program): 'Declares all Parameters in a pyQuil Program.\n\n Args:\n program : pyquil.Program\n The program to declare parameters for.\n ' if (type(program) != Program): raise ValueError('Argument program must be a pyquil.Program.') mem_refs = {} for qubit in range(len(self.names)): mem_refs[qubit] = [] for name in self.names[qubit]: mem_ref = program.declare(name, memory_type='REAL', memory_size=1) mem_refs[qubit].append(mem_ref) self.memory_references = mem_refs
Declares all Parameters in a pyQuil Program. Args: program : pyquil.Program The program to declare parameters for.
src/nisqai/layer/_params.py
declare_memory_references
obliviateandsurrender/nisqai-dev
14
python
def declare_memory_references(self, program): 'Declares all Parameters in a pyQuil Program.\n\n Args:\n program : pyquil.Program\n The program to declare parameters for.\n ' if (type(program) != Program): raise ValueError('Argument program must be a pyquil.Program.') mem_refs = {} for qubit in range(len(self.names)): mem_refs[qubit] = [] for name in self.names[qubit]: mem_ref = program.declare(name, memory_type='REAL', memory_size=1) mem_refs[qubit].append(mem_ref) self.memory_references = mem_refs
def declare_memory_references(self, program): 'Declares all Parameters in a pyQuil Program.\n\n Args:\n program : pyquil.Program\n The program to declare parameters for.\n ' if (type(program) != Program): raise ValueError('Argument program must be a pyquil.Program.') mem_refs = {} for qubit in range(len(self.names)): mem_refs[qubit] = [] for name in self.names[qubit]: mem_ref = program.declare(name, memory_type='REAL', memory_size=1) mem_refs[qubit].append(mem_ref) self.memory_references = mem_refs<|docstring|>Declares all Parameters in a pyQuil Program. Args: program : pyquil.Program The program to declare parameters for.<|endoftext|>
b62810949ae3dd2c90ec5f3b8702103af5ecebd31b3c33f43aad231ca93fa477
def __init__(self, x=None, y=None, canvas=None, system=None, layer=None, direction=0, diff=0, name=None, vars=None, **kwargs): '初期化処理\n\n 全てのマテリアルインスタンスは重要な属性として\n - マテリアルの名前\n - マテリアルの変数辞書(vars)\n - マテリアルの向き\n - マテリアルの差分\n - レイヤ内の位置にあたるx, y座標\n - 所属するゲームキャンバスクラス\n - 所属するゲームシステムクラス\n - 所属するレイヤクラス(背景ならtile_layer等)\n - マテリアルを識別するためのid\n を持っています。\n\n 更に、マテリアルの種類や具象クラスによっては固有の属性を持ちます。\n\n 基本的に、レイヤクラスのcreate_materialを使ってマテリアルを生成することになります。\n\n ' cls = type(self) self.x = x self.y = y self.canvas = canvas self.system = system self.layer = layer self.id = None if (name is None): self.name = cls.name else: self.name = name if (vars is None): self.vars = cls.vars else: self.vars = vars self.direction = direction self.diff = diff for attr_name in cls.attrs: if (attr_name in kwargs): value = kwargs[attr_name] else: value = getattr(cls, attr_name) if (attr_name in self.func_attrs): value = self.create_method(value) if isinstance(value, (list, dict)): value = value.copy() setattr(self, attr_name, value)
初期化処理 全てのマテリアルインスタンスは重要な属性として - マテリアルの名前 - マテリアルの変数辞書(vars) - マテリアルの向き - マテリアルの差分 - レイヤ内の位置にあたるx, y座標 - 所属するゲームキャンバスクラス - 所属するゲームシステムクラス - 所属するレイヤクラス(背景ならtile_layer等) - マテリアルを識別するためのid を持っています。 更に、マテリアルの種類や具象クラスによっては固有の属性を持ちます。 基本的に、レイヤクラスのcreate_materialを使ってマテリアルを生成することになります。
broccoli/material/base.py
__init__
naritotakizawa/broccoli
5
python
def __init__(self, x=None, y=None, canvas=None, system=None, layer=None, direction=0, diff=0, name=None, vars=None, **kwargs): '初期化処理\n\n 全てのマテリアルインスタンスは重要な属性として\n - マテリアルの名前\n - マテリアルの変数辞書(vars)\n - マテリアルの向き\n - マテリアルの差分\n - レイヤ内の位置にあたるx, y座標\n - 所属するゲームキャンバスクラス\n - 所属するゲームシステムクラス\n - 所属するレイヤクラス(背景ならtile_layer等)\n - マテリアルを識別するためのid\n を持っています。\n\n 更に、マテリアルの種類や具象クラスによっては固有の属性を持ちます。\n\n 基本的に、レイヤクラスのcreate_materialを使ってマテリアルを生成することになります。\n\n ' cls = type(self) self.x = x self.y = y self.canvas = canvas self.system = system self.layer = layer self.id = None if (name is None): self.name = cls.name else: self.name = name if (vars is None): self.vars = cls.vars else: self.vars = vars self.direction = direction self.diff = diff for attr_name in cls.attrs: if (attr_name in kwargs): value = kwargs[attr_name] else: value = getattr(cls, attr_name) if (attr_name in self.func_attrs): value = self.create_method(value) if isinstance(value, (list, dict)): value = value.copy() setattr(self, attr_name, value)
def __init__(self, x=None, y=None, canvas=None, system=None, layer=None, direction=0, diff=0, name=None, vars=None, **kwargs): '初期化処理\n\n 全てのマテリアルインスタンスは重要な属性として\n - マテリアルの名前\n - マテリアルの変数辞書(vars)\n - マテリアルの向き\n - マテリアルの差分\n - レイヤ内の位置にあたるx, y座標\n - 所属するゲームキャンバスクラス\n - 所属するゲームシステムクラス\n - 所属するレイヤクラス(背景ならtile_layer等)\n - マテリアルを識別するためのid\n を持っています。\n\n 更に、マテリアルの種類や具象クラスによっては固有の属性を持ちます。\n\n 基本的に、レイヤクラスのcreate_materialを使ってマテリアルを生成することになります。\n\n ' cls = type(self) self.x = x self.y = y self.canvas = canvas self.system = system self.layer = layer self.id = None if (name is None): self.name = cls.name else: self.name = name if (vars is None): self.vars = cls.vars else: self.vars = vars self.direction = direction self.diff = diff for attr_name in cls.attrs: if (attr_name in kwargs): value = kwargs[attr_name] else: value = getattr(cls, attr_name) if (attr_name in self.func_attrs): value = self.create_method(value) if isinstance(value, (list, dict)): value = value.copy() setattr(self, attr_name, value)<|docstring|>初期化処理 全てのマテリアルインスタンスは重要な属性として - マテリアルの名前 - マテリアルの変数辞書(vars) - マテリアルの向き - マテリアルの差分 - レイヤ内の位置にあたるx, y座標 - 所属するゲームキャンバスクラス - 所属するゲームシステムクラス - 所属するレイヤクラス(背景ならtile_layer等) - マテリアルを識別するためのid を持っています。 更に、マテリアルの種類や具象クラスによっては固有の属性を持ちます。 基本的に、レイヤクラスのcreate_materialを使ってマテリアルを生成することになります。<|endoftext|>
e90b150cff8adfafc8e1b22b8bfec5a4214d5d99f062bc318d8dc67f2e4e7821
def change_direction(self, value): '向きを変え、その画像を反映させる。\n\n 同じ向きを向いた場合は差分を増やし、そして画像を反映させます。\n キャラクターを歩行させたい、歩行させる際のグラフィック更新に便利です。\n\n ' if (self.direction != value): self.diff = 0 self.direction = value else: self.diff += 1 self.canvas.itemconfig(self.id, image=self.image)
向きを変え、その画像を反映させる。 同じ向きを向いた場合は差分を増やし、そして画像を反映させます。 キャラクターを歩行させたい、歩行させる際のグラフィック更新に便利です。
broccoli/material/base.py
change_direction
naritotakizawa/broccoli
5
python
def change_direction(self, value): '向きを変え、その画像を反映させる。\n\n 同じ向きを向いた場合は差分を増やし、そして画像を反映させます。\n キャラクターを歩行させたい、歩行させる際のグラフィック更新に便利です。\n\n ' if (self.direction != value): self.diff = 0 self.direction = value else: self.diff += 1 self.canvas.itemconfig(self.id, image=self.image)
def change_direction(self, value): '向きを変え、その画像を反映させる。\n\n 同じ向きを向いた場合は差分を増やし、そして画像を反映させます。\n キャラクターを歩行させたい、歩行させる際のグラフィック更新に便利です。\n\n ' if (self.direction != value): self.diff = 0 self.direction = value else: self.diff += 1 self.canvas.itemconfig(self.id, image=self.image)<|docstring|>向きを変え、その画像を反映させる。 同じ向きを向いた場合は差分を増やし、そして画像を反映させます。 キャラクターを歩行させたい、歩行させる際のグラフィック更新に便利です。<|endoftext|>
67b49fec18d19a33c11031a4e636d8eec44aeab0f803c744eb7afa5a2474b5c4
def get_4_positions(self): '4方向の座標を取得するショートカットメソッドです。\n\n [\n (DOWN, self.x, self.y+1),にも\n (LEFT, self.x-1, self.y),\n (RIGHT, self.x+1, self.y),\n (UP, self.x, self.y - 1),\n ]\n といったリストを返します。\n DOWNなどは向きに直接代入(direction=DOWN)できる定数で、change_directionメソッドにもそのまま渡せます。\n また、その方向がマップの範囲外になる場合は無視されます。\n 空のリストが返ったら、4方向が全てマップの範囲外ということです。\n\n デフォルトではシャッフルして返しますので、必ずしも下座標から取得できる訳ではありません。\n\n ' positions = [(const.DOWN, self.x, (self.y + 1)), (const.LEFT, (self.x - 1), self.y), (const.RIGHT, (self.x + 1), self.y), (const.UP, self.x, (self.y - 1))] result_positions = [] for (direction, x, y) in positions: if self.canvas.check_position(x, y): result_positions.append((direction, x, y)) random.shuffle(result_positions) return result_positions
4方向の座標を取得するショートカットメソッドです。 [ (DOWN, self.x, self.y+1),にも (LEFT, self.x-1, self.y), (RIGHT, self.x+1, self.y), (UP, self.x, self.y - 1), ] といったリストを返します。 DOWNなどは向きに直接代入(direction=DOWN)できる定数で、change_directionメソッドにもそのまま渡せます。 また、その方向がマップの範囲外になる場合は無視されます。 空のリストが返ったら、4方向が全てマップの範囲外ということです。 デフォルトではシャッフルして返しますので、必ずしも下座標から取得できる訳ではありません。
broccoli/material/base.py
get_4_positions
naritotakizawa/broccoli
5
python
def get_4_positions(self): '4方向の座標を取得するショートカットメソッドです。\n\n [\n (DOWN, self.x, self.y+1),にも\n (LEFT, self.x-1, self.y),\n (RIGHT, self.x+1, self.y),\n (UP, self.x, self.y - 1),\n ]\n といったリストを返します。\n DOWNなどは向きに直接代入(direction=DOWN)できる定数で、change_directionメソッドにもそのまま渡せます。\n また、その方向がマップの範囲外になる場合は無視されます。\n 空のリストが返ったら、4方向が全てマップの範囲外ということです。\n\n デフォルトではシャッフルして返しますので、必ずしも下座標から取得できる訳ではありません。\n\n ' positions = [(const.DOWN, self.x, (self.y + 1)), (const.LEFT, (self.x - 1), self.y), (const.RIGHT, (self.x + 1), self.y), (const.UP, self.x, (self.y - 1))] result_positions = [] for (direction, x, y) in positions: if self.canvas.check_position(x, y): result_positions.append((direction, x, y)) random.shuffle(result_positions) return result_positions
def get_4_positions(self): '4方向の座標を取得するショートカットメソッドです。\n\n [\n (DOWN, self.x, self.y+1),にも\n (LEFT, self.x-1, self.y),\n (RIGHT, self.x+1, self.y),\n (UP, self.x, self.y - 1),\n ]\n といったリストを返します。\n DOWNなどは向きに直接代入(direction=DOWN)できる定数で、change_directionメソッドにもそのまま渡せます。\n また、その方向がマップの範囲外になる場合は無視されます。\n 空のリストが返ったら、4方向が全てマップの範囲外ということです。\n\n デフォルトではシャッフルして返しますので、必ずしも下座標から取得できる訳ではありません。\n\n ' positions = [(const.DOWN, self.x, (self.y + 1)), (const.LEFT, (self.x - 1), self.y), (const.RIGHT, (self.x + 1), self.y), (const.UP, self.x, (self.y - 1))] result_positions = [] for (direction, x, y) in positions: if self.canvas.check_position(x, y): result_positions.append((direction, x, y)) random.shuffle(result_positions) return result_positions<|docstring|>4方向の座標を取得するショートカットメソッドです。 [ (DOWN, self.x, self.y+1),にも (LEFT, self.x-1, self.y), (RIGHT, self.x+1, self.y), (UP, self.x, self.y - 1), ] といったリストを返します。 DOWNなどは向きに直接代入(direction=DOWN)できる定数で、change_directionメソッドにもそのまま渡せます。 また、その方向がマップの範囲外になる場合は無視されます。 空のリストが返ったら、4方向が全てマップの範囲外ということです。 デフォルトではシャッフルして返しますので、必ずしも下座標から取得できる訳ではありません。<|endoftext|>
5a52c149a57b9a38faf36320ec2af15a29b864623ad683ab88ff4663a44c1a20
def get_nearest(self, materials): 'materialsの中から、自分に最も近いものを返す。' def _nearest(material): return (abs((self.x - material.x)) + abs((self.y - material.y))) sorted_materials = sorted(materials, key=_nearest) return sorted_materials[0]
materialsの中から、自分に最も近いものを返す。
broccoli/material/base.py
get_nearest
naritotakizawa/broccoli
5
python
def get_nearest(self, materials): def _nearest(material): return (abs((self.x - material.x)) + abs((self.y - material.y))) sorted_materials = sorted(materials, key=_nearest) return sorted_materials[0]
def get_nearest(self, materials): def _nearest(material): return (abs((self.x - material.x)) + abs((self.y - material.y))) sorted_materials = sorted(materials, key=_nearest) return sorted_materials[0]<|docstring|>materialsの中から、自分に最も近いものを返す。<|endoftext|>
2ce1c1fe192cef8d2fe832309f71f3615564ef1efe843aa363718b248aa8888a
@classmethod def get_class_attrs(cls): 'クラスの属性を辞書として返します。\n\n マテリアルの主要なクラス属性を辞書として返します。\n まだインスタンス化していない状態で、そのマテリアルクラスの属性を確認したい場合に有効です。\n エディタでのマテリアル説明欄に使っています。\n\n ' result = {'name': cls.name, 'vars': cls.vars} for attr_name in cls.attrs: value = getattr(cls, attr_name) result[attr_name] = value return result
クラスの属性を辞書として返します。 マテリアルの主要なクラス属性を辞書として返します。 まだインスタンス化していない状態で、そのマテリアルクラスの属性を確認したい場合に有効です。 エディタでのマテリアル説明欄に使っています。
broccoli/material/base.py
get_class_attrs
naritotakizawa/broccoli
5
python
@classmethod def get_class_attrs(cls): 'クラスの属性を辞書として返します。\n\n マテリアルの主要なクラス属性を辞書として返します。\n まだインスタンス化していない状態で、そのマテリアルクラスの属性を確認したい場合に有効です。\n エディタでのマテリアル説明欄に使っています。\n\n ' result = {'name': cls.name, 'vars': cls.vars} for attr_name in cls.attrs: value = getattr(cls, attr_name) result[attr_name] = value return result
@classmethod def get_class_attrs(cls): 'クラスの属性を辞書として返します。\n\n マテリアルの主要なクラス属性を辞書として返します。\n まだインスタンス化していない状態で、そのマテリアルクラスの属性を確認したい場合に有効です。\n エディタでのマテリアル説明欄に使っています。\n\n ' result = {'name': cls.name, 'vars': cls.vars} for attr_name in cls.attrs: value = getattr(cls, attr_name) result[attr_name] = value return result<|docstring|>クラスの属性を辞書として返します。 マテリアルの主要なクラス属性を辞書として返します。 まだインスタンス化していない状態で、そのマテリアルクラスの属性を確認したい場合に有効です。 エディタでのマテリアル説明欄に使っています。<|endoftext|>
f70515f0515eebd0594d260bc1710fc5bca6b996a21a1bdb0c458a2e38dc9838
def get_instance_attrs(self): 'マテリアルインスタンスの属性を返します。\n\n マテリアルのコピーを作りたい場合は、dumpを利用してください。\n\n ' result = {'name': self.name, 'direction': self.direction, 'diff': self.diff, 'vars': self.vars} for attr_name in self.attrs: value = getattr(self, attr_name) result[attr_name] = value return result
マテリアルインスタンスの属性を返します。 マテリアルのコピーを作りたい場合は、dumpを利用してください。
broccoli/material/base.py
get_instance_attrs
naritotakizawa/broccoli
5
python
def get_instance_attrs(self): 'マテリアルインスタンスの属性を返します。\n\n マテリアルのコピーを作りたい場合は、dumpを利用してください。\n\n ' result = {'name': self.name, 'direction': self.direction, 'diff': self.diff, 'vars': self.vars} for attr_name in self.attrs: value = getattr(self, attr_name) result[attr_name] = value return result
def get_instance_attrs(self): 'マテリアルインスタンスの属性を返します。\n\n マテリアルのコピーを作りたい場合は、dumpを利用してください。\n\n ' result = {'name': self.name, 'direction': self.direction, 'diff': self.diff, 'vars': self.vars} for attr_name in self.attrs: value = getattr(self, attr_name) result[attr_name] = value return result<|docstring|>マテリアルインスタンスの属性を返します。 マテリアルのコピーを作りたい場合は、dumpを利用してください。<|endoftext|>
d5999d92b4d44a28d872a452cc82150eccbbb6552b01c7d414d5999889e67a00
def dump(self): 'cls, kwargsの形式でマテリアルを返す。\n\n cls, kwargs = material.dump()\n layer.create_material(material_cls=cls, **kwargs)\n\n のようにするとマテリアルのコピーが作れます。\n\n マテリアルのある属性がリストや辞書だった場合で、\n 内部にマテリアルを格納していた場合は(cls, kwargs)形式に変換されていきます。\n\n ' cls = type(self) kwargs = self.get_instance_attrs() for (name, value) in kwargs.items(): if isinstance(value, (list, tuple)): for (i, data) in enumerate(value): if isinstance(data, BaseMaterial): value[i] = data.dump() elif isinstance(value, dict): for (attr_name, attr_value) in value.items(): if isinstance(attr_value, BaseMaterial): value[name] = attr_name.dump() return (cls, kwargs)
cls, kwargsの形式でマテリアルを返す。 cls, kwargs = material.dump() layer.create_material(material_cls=cls, **kwargs) のようにするとマテリアルのコピーが作れます。 マテリアルのある属性がリストや辞書だった場合で、 内部にマテリアルを格納していた場合は(cls, kwargs)形式に変換されていきます。
broccoli/material/base.py
dump
naritotakizawa/broccoli
5
python
def dump(self): 'cls, kwargsの形式でマテリアルを返す。\n\n cls, kwargs = material.dump()\n layer.create_material(material_cls=cls, **kwargs)\n\n のようにするとマテリアルのコピーが作れます。\n\n マテリアルのある属性がリストや辞書だった場合で、\n 内部にマテリアルを格納していた場合は(cls, kwargs)形式に変換されていきます。\n\n ' cls = type(self) kwargs = self.get_instance_attrs() for (name, value) in kwargs.items(): if isinstance(value, (list, tuple)): for (i, data) in enumerate(value): if isinstance(data, BaseMaterial): value[i] = data.dump() elif isinstance(value, dict): for (attr_name, attr_value) in value.items(): if isinstance(attr_value, BaseMaterial): value[name] = attr_name.dump() return (cls, kwargs)
def dump(self): 'cls, kwargsの形式でマテリアルを返す。\n\n cls, kwargs = material.dump()\n layer.create_material(material_cls=cls, **kwargs)\n\n のようにするとマテリアルのコピーが作れます。\n\n マテリアルのある属性がリストや辞書だった場合で、\n 内部にマテリアルを格納していた場合は(cls, kwargs)形式に変換されていきます。\n\n ' cls = type(self) kwargs = self.get_instance_attrs() for (name, value) in kwargs.items(): if isinstance(value, (list, tuple)): for (i, data) in enumerate(value): if isinstance(data, BaseMaterial): value[i] = data.dump() elif isinstance(value, dict): for (attr_name, attr_value) in value.items(): if isinstance(attr_value, BaseMaterial): value[name] = attr_name.dump() return (cls, kwargs)<|docstring|>cls, kwargsの形式でマテリアルを返す。 cls, kwargs = material.dump() layer.create_material(material_cls=cls, **kwargs) のようにするとマテリアルのコピーが作れます。 マテリアルのある属性がリストや辞書だった場合で、 内部にマテリアルを格納していた場合は(cls, kwargs)形式に変換されていきます。<|endoftext|>
e65ffe85a9c609fc89f654849aa05b3d5e228e2d6d06062e6ef3fcb0f2834aa7
def create_method(self, func): 'マテリアルのメソッドとして関数を登録します。' if (not inspect.ismethod(func)): func = types.MethodType(func, self) return func
マテリアルのメソッドとして関数を登録します。
broccoli/material/base.py
create_method
naritotakizawa/broccoli
5
python
def create_method(self, func): if (not inspect.ismethod(func)): func = types.MethodType(func, self) return func
def create_method(self, func): if (not inspect.ismethod(func)): func = types.MethodType(func, self) return func<|docstring|>マテリアルのメソッドとして関数を登録します。<|endoftext|>
fe3a63e4707921146b4bb1bcf7ea0bd43ad7a4522babdabef32a842e5b29b5e3
def delete(self): 'マテリアルを削除する。\n\n material.layer.delete_material(material)\n を、簡単に書くためのショートカットです。\n\n ' self.layer.delete_material(self)
マテリアルを削除する。 material.layer.delete_material(material) を、簡単に書くためのショートカットです。
broccoli/material/base.py
delete
naritotakizawa/broccoli
5
python
def delete(self): 'マテリアルを削除する。\n\n material.layer.delete_material(material)\n を、簡単に書くためのショートカットです。\n\n ' self.layer.delete_material(self)
def delete(self): 'マテリアルを削除する。\n\n material.layer.delete_material(material)\n を、簡単に書くためのショートカットです。\n\n ' self.layer.delete_material(self)<|docstring|>マテリアルを削除する。 material.layer.delete_material(material) を、簡単に書くためのショートカットです。<|endoftext|>
7b1ee6e410ca56ec8fd36ce34d94291be44051851d024eb1d5212758ce20b524
def paged(oper, *args, per_page=30, max_pages=9999, **kwargs): 'Convert operation `oper(*args,**kwargs)` into an iterator' (yield from itertools.takewhile(noop, (oper(*args, per_page=per_page, page=i, **kwargs) for i in range(1, (max_pages + 1)))))
Convert operation `oper(*args,**kwargs)` into an iterator
ghapi/page.py
paged
Sou-786/ghapi
321
python
def paged(oper, *args, per_page=30, max_pages=9999, **kwargs): (yield from itertools.takewhile(noop, (oper(*args, per_page=per_page, page=i, **kwargs) for i in range(1, (max_pages + 1)))))
def paged(oper, *args, per_page=30, max_pages=9999, **kwargs): (yield from itertools.takewhile(noop, (oper(*args, per_page=per_page, page=i, **kwargs) for i in range(1, (max_pages + 1)))))<|docstring|>Convert operation `oper(*args,**kwargs)` into an iterator<|endoftext|>
66e4adf42cb37a650f1b4c744094a69eacbfca8a4d8d19ffe93a5c69261a5e74
def _parse_link_hdr(header): 'Parse an RFC 5988 link header, returning a `list` of `tuple`s of URL and attr `dict`' (scanner, links) = (_Scanner(header), []) while scanner.scan(_RE_COMMA_HREF): (href, attrs) = (scanner[1], []) while scanner.scan('; *'): if scanner.scan(_RE_ATTR): (attr_name, token, quoted) = (scanner[1], scanner[3], scanner[4]) if (quoted is not None): attrs.append([attr_name, quoted.replace('\\"', '"')]) elif (token is not None): attrs.append([attr_name, token]) else: attrs.append([attr_name, None]) links.append((href, dict(attrs))) if scanner.buf: raise Exception(f'parse() failed at {scanner.buf!r}') return links
Parse an RFC 5988 link header, returning a `list` of `tuple`s of URL and attr `dict`
ghapi/page.py
_parse_link_hdr
Sou-786/ghapi
321
python
def _parse_link_hdr(header): (scanner, links) = (_Scanner(header), []) while scanner.scan(_RE_COMMA_HREF): (href, attrs) = (scanner[1], []) while scanner.scan('; *'): if scanner.scan(_RE_ATTR): (attr_name, token, quoted) = (scanner[1], scanner[3], scanner[4]) if (quoted is not None): attrs.append([attr_name, quoted.replace('\\"', '"')]) elif (token is not None): attrs.append([attr_name, token]) else: attrs.append([attr_name, None]) links.append((href, dict(attrs))) if scanner.buf: raise Exception(f'parse() failed at {scanner.buf!r}') return links
def _parse_link_hdr(header): (scanner, links) = (_Scanner(header), []) while scanner.scan(_RE_COMMA_HREF): (href, attrs) = (scanner[1], []) while scanner.scan('; *'): if scanner.scan(_RE_ATTR): (attr_name, token, quoted) = (scanner[1], scanner[3], scanner[4]) if (quoted is not None): attrs.append([attr_name, quoted.replace('\\"', '"')]) elif (token is not None): attrs.append([attr_name, token]) else: attrs.append([attr_name, None]) links.append((href, dict(attrs))) if scanner.buf: raise Exception(f'parse() failed at {scanner.buf!r}') return links<|docstring|>Parse an RFC 5988 link header, returning a `list` of `tuple`s of URL and attr `dict`<|endoftext|>
e1af75a56c9110f6afbad34888ba6c3fff13bbb009d50a260cd4ec29b8fffb3a
def parse_link_hdr(header): 'Parse an RFC 5988 link header, returning a `dict` from rels to a `tuple` of URL and attrs `dict`' return {a.pop('rel'): (u, a) for (u, a) in _parse_link_hdr(header)}
Parse an RFC 5988 link header, returning a `dict` from rels to a `tuple` of URL and attrs `dict`
ghapi/page.py
parse_link_hdr
Sou-786/ghapi
321
python
def parse_link_hdr(header): return {a.pop('rel'): (u, a) for (u, a) in _parse_link_hdr(header)}
def parse_link_hdr(header): return {a.pop('rel'): (u, a) for (u, a) in _parse_link_hdr(header)}<|docstring|>Parse an RFC 5988 link header, returning a `dict` from rels to a `tuple` of URL and attrs `dict`<|endoftext|>
1cc5cf2cd8f65cfaa72989056c6574f87e7432c7e5fa1ac6bc07c31377c901a0
@patch def last_page(self: GhApi): 'Parse RFC 5988 link header from most recent operation, and extract the last page' header = self.recv_hdrs.get('Link', '') last = (nested_idx(parse_link_hdr(header), 'last', 0) or '') qs = parse_qs(urlsplit(last).query) return int((nested_idx(qs, 'page', 0) or 0))
Parse RFC 5988 link header from most recent operation, and extract the last page
ghapi/page.py
last_page
Sou-786/ghapi
321
python
@patch def last_page(self: GhApi): header = self.recv_hdrs.get('Link', ) last = (nested_idx(parse_link_hdr(header), 'last', 0) or ) qs = parse_qs(urlsplit(last).query) return int((nested_idx(qs, 'page', 0) or 0))
@patch def last_page(self: GhApi): header = self.recv_hdrs.get('Link', ) last = (nested_idx(parse_link_hdr(header), 'last', 0) or ) qs = parse_qs(urlsplit(last).query) return int((nested_idx(qs, 'page', 0) or 0))<|docstring|>Parse RFC 5988 link header from most recent operation, and extract the last page<|endoftext|>
773821db43b93b7451a2fa35c7e1f26deb21c7408c5206c15821b4333ea04780
def pages(oper, n_pages, *args, n_workers=None, per_page=100, **kwargs): 'Get `n_pages` pages from `oper(*args,**kwargs)`' return parallel(_call_page, range(1, (n_pages + 1)), oper=oper, per_page=per_page, args=args, kwargs=kwargs, progress=False, n_workers=ifnone(n_workers, n_pages), threadpool=True)
Get `n_pages` pages from `oper(*args,**kwargs)`
ghapi/page.py
pages
Sou-786/ghapi
321
python
def pages(oper, n_pages, *args, n_workers=None, per_page=100, **kwargs): return parallel(_call_page, range(1, (n_pages + 1)), oper=oper, per_page=per_page, args=args, kwargs=kwargs, progress=False, n_workers=ifnone(n_workers, n_pages), threadpool=True)
def pages(oper, n_pages, *args, n_workers=None, per_page=100, **kwargs): return parallel(_call_page, range(1, (n_pages + 1)), oper=oper, per_page=per_page, args=args, kwargs=kwargs, progress=False, n_workers=ifnone(n_workers, n_pages), threadpool=True)<|docstring|>Get `n_pages` pages from `oper(*args,**kwargs)`<|endoftext|>
0707d5d4f222a3b26f461d614142003b1941f170be88def3c3ed26e8cd760185
def is_docker(): ' Checks if the current script is executed in a docker container ' path = '/proc/self/cgroup' return (os.path.exists('/.dockerenv') or (os.path.isfile(path) and any((('docker' in line) for line in open(path)))))
Checks if the current script is executed in a docker container
orc8r/gateway/python/scripts/health_cli.py
is_docker
electrocucaracha/magma
849
python
def is_docker(): ' ' path = '/proc/self/cgroup' return (os.path.exists('/.dockerenv') or (os.path.isfile(path) and any((('docker' in line) for line in open(path)))))
def is_docker(): ' ' path = '/proc/self/cgroup' return (os.path.exists('/.dockerenv') or (os.path.isfile(path) and any((('docker' in line) for line in open(path)))))<|docstring|>Checks if the current script is executed in a docker container<|endoftext|>
efb42347f171bbfcf589b9346a58466b69cc17290dbd4722260a2c24b1e0fbe9
def status(self): '\n Global health status \n\n Example:\n `health_cli.py status`\n `health_cli.py`\n `venvsudo health_cli.py` (if running without sufficient permissions)\n ' print('Health Summary') print('\nGateway <-> Controller connectivity') (checkin, error) = subprocess.Popen(['checkin_cli.py'], stdout=subprocess.PIPE).communicate() print(str(checkin, 'utf-8')) print(str(self._health_checker.get_health_summary()))
Global health status Example: `health_cli.py status` `health_cli.py` `venvsudo health_cli.py` (if running without sufficient permissions)
orc8r/gateway/python/scripts/health_cli.py
status
electrocucaracha/magma
849
python
def status(self): '\n Global health status \n\n Example:\n `health_cli.py status`\n `health_cli.py`\n `venvsudo health_cli.py` (if running without sufficient permissions)\n ' print('Health Summary') print('\nGateway <-> Controller connectivity') (checkin, error) = subprocess.Popen(['checkin_cli.py'], stdout=subprocess.PIPE).communicate() print(str(checkin, 'utf-8')) print(str(self._health_checker.get_health_summary()))
def status(self): '\n Global health status \n\n Example:\n `health_cli.py status`\n `health_cli.py`\n `venvsudo health_cli.py` (if running without sufficient permissions)\n ' print('Health Summary') print('\nGateway <-> Controller connectivity') (checkin, error) = subprocess.Popen(['checkin_cli.py'], stdout=subprocess.PIPE).communicate() print(str(checkin, 'utf-8')) print(str(self._health_checker.get_health_summary()))<|docstring|>Global health status Example: `health_cli.py status` `health_cli.py` `venvsudo health_cli.py` (if running without sufficient permissions)<|endoftext|>
adf7638d07f3dd3ee36f75cdfaf1f24d00de39fdf134019a0ce2546111dcf03a
def magma_version(self): '\n Get the installed magma version\n ' print(str(self._health_checker.get_magma_version()))
Get the installed magma version
orc8r/gateway/python/scripts/health_cli.py
magma_version
electrocucaracha/magma
849
python
def magma_version(self): '\n \n ' print(str(self._health_checker.get_magma_version()))
def magma_version(self): '\n \n ' print(str(self._health_checker.get_magma_version()))<|docstring|>Get the installed magma version<|endoftext|>
eb287ab57b91e84c9e83e41f7660f88c41826e53f1f984dff597bede09a93ecc
def kernel_version(self): '\n Get kernel version of the VM\n ' print(str(self._health_checker.get_kernel_version()))
Get kernel version of the VM
orc8r/gateway/python/scripts/health_cli.py
kernel_version
electrocucaracha/magma
849
python
def kernel_version(self): '\n \n ' print(str(self._health_checker.get_kernel_version()))
def kernel_version(self): '\n \n ' print(str(self._health_checker.get_kernel_version()))<|docstring|>Get kernel version of the VM<|endoftext|>
6116c5773b2a73e14acd6233baefd0db97ca55c8d7f7e8a03f47669fe14ca994
def internet_status(self, host): "\n Checks if it's possible to connect to the specified host \n\n Examples:\n `health_cli.py internet_status --host 8.8.8.8`\n `health_cli.py internet_status --host google.com`\n " print(str(self._health_checker.ping_status(host)))
Checks if it's possible to connect to the specified host Examples: `health_cli.py internet_status --host 8.8.8.8` `health_cli.py internet_status --host google.com`
orc8r/gateway/python/scripts/health_cli.py
internet_status
electrocucaracha/magma
849
python
def internet_status(self, host): "\n Checks if it's possible to connect to the specified host \n\n Examples:\n `health_cli.py internet_status --host 8.8.8.8`\n `health_cli.py internet_status --host google.com`\n " print(str(self._health_checker.ping_status(host)))
def internet_status(self, host): "\n Checks if it's possible to connect to the specified host \n\n Examples:\n `health_cli.py internet_status --host 8.8.8.8`\n `health_cli.py internet_status --host google.com`\n " print(str(self._health_checker.ping_status(host)))<|docstring|>Checks if it's possible to connect to the specified host Examples: `health_cli.py internet_status --host 8.8.8.8` `health_cli.py internet_status --host google.com`<|endoftext|>
ff264fad55271c561af81d51c5a17999300fcf27977874ff174c165f57c31162
def services_status(self): '\n Get status summary for all the magma services\n ' print(str(self._health_checker.get_magma_services_summary()))
Get status summary for all the magma services
orc8r/gateway/python/scripts/health_cli.py
services_status
electrocucaracha/magma
849
python
def services_status(self): '\n \n ' print(str(self._health_checker.get_magma_services_summary()))
def services_status(self): '\n \n ' print(str(self._health_checker.get_magma_services_summary()))<|docstring|>Get status summary for all the magma services<|endoftext|>
26f460eb2462f6a937904c2fe33427328df390990e74e44a2d89debe940f3c9d
def restarts_status(self): '\n How many times each services was restarting since the whole system start\n ' return str(self._health_checker.get_unexpected_restart_summary())
How many times each services was restarting since the whole system start
orc8r/gateway/python/scripts/health_cli.py
restarts_status
electrocucaracha/magma
849
python
def restarts_status(self): '\n \n ' return str(self._health_checker.get_unexpected_restart_summary())
def restarts_status(self): '\n \n ' return str(self._health_checker.get_unexpected_restart_summary())<|docstring|>How many times each services was restarting since the whole system start<|endoftext|>
bdcaffbea44cadadefe6c1509aacb754add4981e9b929dc606cf36f8bf9cd66c
def error_status(self, service_names): "\n How many errors have each service had since the last restart \n\n Examples:\n `health_cli.py error_status --service_names mme,dnsd`\n `health_cli.py error_status --service_names '[pipelined,mme]'`\n :param service_names: list or tuple of service names\n " print('\n'.join(['{}:\t{}'.format(name, errors) for (name, errors) in self._health_checker.get_error_summary(service_names).items()]))
How many errors have each service had since the last restart Examples: `health_cli.py error_status --service_names mme,dnsd` `health_cli.py error_status --service_names '[pipelined,mme]'` :param service_names: list or tuple of service names
orc8r/gateway/python/scripts/health_cli.py
error_status
electrocucaracha/magma
849
python
def error_status(self, service_names): "\n How many errors have each service had since the last restart \n\n Examples:\n `health_cli.py error_status --service_names mme,dnsd`\n `health_cli.py error_status --service_names '[pipelined,mme]'`\n :param service_names: list or tuple of service names\n " print('\n'.join(['{}:\t{}'.format(name, errors) for (name, errors) in self._health_checker.get_error_summary(service_names).items()]))
def error_status(self, service_names): "\n How many errors have each service had since the last restart \n\n Examples:\n `health_cli.py error_status --service_names mme,dnsd`\n `health_cli.py error_status --service_names '[pipelined,mme]'`\n :param service_names: list or tuple of service names\n " print('\n'.join(['{}:\t{}'.format(name, errors) for (name, errors) in self._health_checker.get_error_summary(service_names).items()]))<|docstring|>How many errors have each service had since the last restart Examples: `health_cli.py error_status --service_names mme,dnsd` `health_cli.py error_status --service_names '[pipelined,mme]'` :param service_names: list or tuple of service names<|endoftext|>
3d5d65273912bebe8fa35b18435167f07381b088eab781df798d0a1e24937344
def example_parse_o8c(dict_name: str, word: str, html: str) -> Tuple[(str, str, str)]: '牛津8词典' ...
牛津8词典
es/indexing.py
example_parse_o8c
zhimoe/mdict-py
6
python
def example_parse_o8c(dict_name: str, word: str, html: str) -> Tuple[(str, str, str)]: ...
def example_parse_o8c(dict_name: str, word: str, html: str) -> Tuple[(str, str, str)]: ...<|docstring|>牛津8词典<|endoftext|>
31dcbaf48d6d0ab587136526d80227296928aeeca3782b1281eac50fe214d59b
def example_parse_lsc4(word: str, html: str) -> List[Tuple[(str, str, str, str)]]: '朗文4词典\n :return:(word,en,han,templates)\n ' result = [] if (not html): return result bs = BeautifulSoup(html, 'templates.parser') examples = bs.find_all('span', attrs={'class': 'example'}) for html in examples: try: en = html.next.text han = html.next.nextSibling.text result.append((word, en, han, html.encode_contents().decode())) except AttributeError: 'some example has no next element' print(f'this example is not on rule') return result
朗文4词典 :return:(word,en,han,templates)
es/indexing.py
example_parse_lsc4
zhimoe/mdict-py
6
python
def example_parse_lsc4(word: str, html: str) -> List[Tuple[(str, str, str, str)]]: '朗文4词典\n :return:(word,en,han,templates)\n ' result = [] if (not html): return result bs = BeautifulSoup(html, 'templates.parser') examples = bs.find_all('span', attrs={'class': 'example'}) for html in examples: try: en = html.next.text han = html.next.nextSibling.text result.append((word, en, han, html.encode_contents().decode())) except AttributeError: 'some example has no next element' print(f'this example is not on rule') return result
def example_parse_lsc4(word: str, html: str) -> List[Tuple[(str, str, str, str)]]: '朗文4词典\n :return:(word,en,han,templates)\n ' result = [] if (not html): return result bs = BeautifulSoup(html, 'templates.parser') examples = bs.find_all('span', attrs={'class': 'example'}) for html in examples: try: en = html.next.text han = html.next.nextSibling.text result.append((word, en, han, html.encode_contents().decode())) except AttributeError: 'some example has no next element' print(f'this example is not on rule') return result<|docstring|>朗文4词典 :return:(word,en,han,templates)<|endoftext|>
12de64f93f4c6fbbae9b34e11c8b136865e399753b93cd6b095489f7912fb607
def ingest(dict_name: str, examples: List[Tuple[(str, str, str, str)]]) -> int: '\n 将例句写入到ES中,字段(id,word,en,han,templates).\n 搜索的是en,han字段,id=word+en.strip保证例句不重复\n html是例句的原始html,方便展示\n :param dict_name: LSC4 or O8C,方便在返回html中添加css\n :param examples:(word,en,han,templates)\n :return: success count\n ' docs = [] for tpl in examples: (word, en, han, html) = tpl source = {'dict': dict_name, 'en': en, 'han': han, 'templates': html} body = {'_index': INDEX, '_type': 'doc', '_source': source, '_id': ((((dict_name + '-') + word) + '-') + re.sub('\\W+', '', en))} docs.append(body) helpers.bulk(esClt, docs) return len(examples)
将例句写入到ES中,字段(id,word,en,han,templates). 搜索的是en,han字段,id=word+en.strip保证例句不重复 html是例句的原始html,方便展示 :param dict_name: LSC4 or O8C,方便在返回html中添加css :param examples:(word,en,han,templates) :return: success count
es/indexing.py
ingest
zhimoe/mdict-py
6
python
def ingest(dict_name: str, examples: List[Tuple[(str, str, str, str)]]) -> int: '\n 将例句写入到ES中,字段(id,word,en,han,templates).\n 搜索的是en,han字段,id=word+en.strip保证例句不重复\n html是例句的原始html,方便展示\n :param dict_name: LSC4 or O8C,方便在返回html中添加css\n :param examples:(word,en,han,templates)\n :return: success count\n ' docs = [] for tpl in examples: (word, en, han, html) = tpl source = {'dict': dict_name, 'en': en, 'han': han, 'templates': html} body = {'_index': INDEX, '_type': 'doc', '_source': source, '_id': ((((dict_name + '-') + word) + '-') + re.sub('\\W+', , en))} docs.append(body) helpers.bulk(esClt, docs) return len(examples)
def ingest(dict_name: str, examples: List[Tuple[(str, str, str, str)]]) -> int: '\n 将例句写入到ES中,字段(id,word,en,han,templates).\n 搜索的是en,han字段,id=word+en.strip保证例句不重复\n html是例句的原始html,方便展示\n :param dict_name: LSC4 or O8C,方便在返回html中添加css\n :param examples:(word,en,han,templates)\n :return: success count\n ' docs = [] for tpl in examples: (word, en, han, html) = tpl source = {'dict': dict_name, 'en': en, 'han': han, 'templates': html} body = {'_index': INDEX, '_type': 'doc', '_source': source, '_id': ((((dict_name + '-') + word) + '-') + re.sub('\\W+', , en))} docs.append(body) helpers.bulk(esClt, docs) return len(examples)<|docstring|>将例句写入到ES中,字段(id,word,en,han,templates). 搜索的是en,han字段,id=word+en.strip保证例句不重复 html是例句的原始html,方便展示 :param dict_name: LSC4 or O8C,方便在返回html中添加css :param examples:(word,en,han,templates) :return: success count<|endoftext|>
b718e16576f3869c17b1102cb50b920aeeff3d8b880863ae49591350c0f95fd1
def es_indexing(builder) -> int: 'indexing all examples in lsc4 dict\n TODO: 性能很差,indexing动作应该放在解析mdx文件的时候\n :param builder dict builder\n ' if (not create_index()): return 0 print('es is connected and index created succeed, starting indexing the examples...') conn = sqlite3.connect(builder.get_mdx_db()) cursor = conn.execute('SELECT key_text FROM MDX_INDEX') keys = [item[0] for item in cursor] conn.close() examples = [] for key in keys: content = builder.mdx_lookup(key) str_content = '' if (len(content) > 0): for c in content: str_content += c.replace('\r\n', '').replace('entry:/', '') exs = example_parse_lsc4(key, str_content) if exs: examples.extend(exs) if (len(examples) > 2000): ingest('lsc4', examples) examples = [] ingest('lsc4', examples) print('indexing done', len(keys))
indexing all examples in lsc4 dict TODO: 性能很差,indexing动作应该放在解析mdx文件的时候 :param builder dict builder
es/indexing.py
es_indexing
zhimoe/mdict-py
6
python
def es_indexing(builder) -> int: 'indexing all examples in lsc4 dict\n TODO: 性能很差,indexing动作应该放在解析mdx文件的时候\n :param builder dict builder\n ' if (not create_index()): return 0 print('es is connected and index created succeed, starting indexing the examples...') conn = sqlite3.connect(builder.get_mdx_db()) cursor = conn.execute('SELECT key_text FROM MDX_INDEX') keys = [item[0] for item in cursor] conn.close() examples = [] for key in keys: content = builder.mdx_lookup(key) str_content = if (len(content) > 0): for c in content: str_content += c.replace('\r\n', ).replace('entry:/', ) exs = example_parse_lsc4(key, str_content) if exs: examples.extend(exs) if (len(examples) > 2000): ingest('lsc4', examples) examples = [] ingest('lsc4', examples) print('indexing done', len(keys))
def es_indexing(builder) -> int: 'indexing all examples in lsc4 dict\n TODO: 性能很差,indexing动作应该放在解析mdx文件的时候\n :param builder dict builder\n ' if (not create_index()): return 0 print('es is connected and index created succeed, starting indexing the examples...') conn = sqlite3.connect(builder.get_mdx_db()) cursor = conn.execute('SELECT key_text FROM MDX_INDEX') keys = [item[0] for item in cursor] conn.close() examples = [] for key in keys: content = builder.mdx_lookup(key) str_content = if (len(content) > 0): for c in content: str_content += c.replace('\r\n', ).replace('entry:/', ) exs = example_parse_lsc4(key, str_content) if exs: examples.extend(exs) if (len(examples) > 2000): ingest('lsc4', examples) examples = [] ingest('lsc4', examples) print('indexing done', len(keys))<|docstring|>indexing all examples in lsc4 dict TODO: 性能很差,indexing动作应该放在解析mdx文件的时候 :param builder dict builder<|endoftext|>
adefe057b1c181a881aebcec412c0693f2dee32e7aed1d67bbbb6999a01bb868
def create_index() -> bool: '创建index' if esClt.indices.exists(INDEX): print(f'the index {INDEX} already exists,indexing skipped') return False mappings = {'settings': {'index': {'number_of_shards': 2, 'number_of_replicas': 1}, 'analysis': {'analyzer': {'default': {'type': 'ik_smart'}, 'default_search': {'type': 'ik_smart'}}}}, 'mappings': {'doc': {'properties': {'dict': {'type': 'keyword'}, 'en': {'type': 'text'}, 'han': {'type': 'text'}, 'templates': {'type': 'text'}}}}} return esClt.indices.create(index=INDEX, body=mappings)
创建index
es/indexing.py
create_index
zhimoe/mdict-py
6
python
def create_index() -> bool: if esClt.indices.exists(INDEX): print(f'the index {INDEX} already exists,indexing skipped') return False mappings = {'settings': {'index': {'number_of_shards': 2, 'number_of_replicas': 1}, 'analysis': {'analyzer': {'default': {'type': 'ik_smart'}, 'default_search': {'type': 'ik_smart'}}}}, 'mappings': {'doc': {'properties': {'dict': {'type': 'keyword'}, 'en': {'type': 'text'}, 'han': {'type': 'text'}, 'templates': {'type': 'text'}}}}} return esClt.indices.create(index=INDEX, body=mappings)
def create_index() -> bool: if esClt.indices.exists(INDEX): print(f'the index {INDEX} already exists,indexing skipped') return False mappings = {'settings': {'index': {'number_of_shards': 2, 'number_of_replicas': 1}, 'analysis': {'analyzer': {'default': {'type': 'ik_smart'}, 'default_search': {'type': 'ik_smart'}}}}, 'mappings': {'doc': {'properties': {'dict': {'type': 'keyword'}, 'en': {'type': 'text'}, 'han': {'type': 'text'}, 'templates': {'type': 'text'}}}}} return esClt.indices.create(index=INDEX, body=mappings)<|docstring|>创建index<|endoftext|>
c25554c3e89f5cbc2d6fd2f62882e22e3141a3c66496e82b425ca2d5f8af3118
def _get_cfg_defaults(): '\n Get the config template\n NOT USE IN OTHER FILES!!\n ' return config.clone()
Get the config template NOT USE IN OTHER FILES!!
lib/config/config.py
_get_cfg_defaults
JokerWDL/PyAnomaly
1
python
def _get_cfg_defaults(): '\n Get the config template\n NOT USE IN OTHER FILES!!\n ' return config.clone()
def _get_cfg_defaults(): '\n Get the config template\n NOT USE IN OTHER FILES!!\n ' return config.clone()<|docstring|>Get the config template NOT USE IN OTHER FILES!!<|endoftext|>
703658c31129b272fade341e05746e6b91acc57043aacda82909f18349eb68aa
def update_config(yaml_path, opts): '\n Make the template update based on the yaml file\n ' print('=>Merge the config with {}\t'.format(yaml_path)) cfg = _get_cfg_defaults() cfg.merge_from_file(yaml_path) cfg.merge_from_list(opts) cfg.freeze() return cfg
Make the template update based on the yaml file
lib/config/config.py
update_config
JokerWDL/PyAnomaly
1
python
def update_config(yaml_path, opts): '\n \n ' print('=>Merge the config with {}\t'.format(yaml_path)) cfg = _get_cfg_defaults() cfg.merge_from_file(yaml_path) cfg.merge_from_list(opts) cfg.freeze() return cfg
def update_config(yaml_path, opts): '\n \n ' print('=>Merge the config with {}\t'.format(yaml_path)) cfg = _get_cfg_defaults() cfg.merge_from_file(yaml_path) cfg.merge_from_list(opts) cfg.freeze() return cfg<|docstring|>Make the template update based on the yaml file<|endoftext|>
493f1d3762b6b01829dfa7b7ab1e9f620bc72f599a08d8c893cf3e4672015ccf
def initUI(self): 'Override.' layout = QGridLayout() AR = Qt.AlignRight row = 0 layout.addWidget(self.update_image_btn, row, 0) layout.addWidget(self.auto_update_cb, row, 1, AR) row += 1 layout.addWidget(self.auto_level_btn, row, 0) row += 1 layout.addWidget(QLabel('Moving average: '), row, 0, AR) layout.addWidget(self.moving_avg_le, row, 1) row += 1 layout.addWidget(self.save_image_btn, row, 0) layout.setVerticalSpacing(20) self.setLayout(layout)
Override.
extra_foam/gui/ctrl_widgets/image_ctrl_widget.py
initUI
zhujun98/EXtra-foam
0
python
def initUI(self): layout = QGridLayout() AR = Qt.AlignRight row = 0 layout.addWidget(self.update_image_btn, row, 0) layout.addWidget(self.auto_update_cb, row, 1, AR) row += 1 layout.addWidget(self.auto_level_btn, row, 0) row += 1 layout.addWidget(QLabel('Moving average: '), row, 0, AR) layout.addWidget(self.moving_avg_le, row, 1) row += 1 layout.addWidget(self.save_image_btn, row, 0) layout.setVerticalSpacing(20) self.setLayout(layout)
def initUI(self): layout = QGridLayout() AR = Qt.AlignRight row = 0 layout.addWidget(self.update_image_btn, row, 0) layout.addWidget(self.auto_update_cb, row, 1, AR) row += 1 layout.addWidget(self.auto_level_btn, row, 0) row += 1 layout.addWidget(QLabel('Moving average: '), row, 0, AR) layout.addWidget(self.moving_avg_le, row, 1) row += 1 layout.addWidget(self.save_image_btn, row, 0) layout.setVerticalSpacing(20) self.setLayout(layout)<|docstring|>Override.<|endoftext|>
2690b551495d5dec4abed9c8bf338edd8bb1f1b1157f9300afd2921c807b11af
def initConnections(self): 'Override.' mediator = self._mediator self.auto_update_cb.toggled.connect((lambda : self.update_image_btn.setEnabled((not self.sender().isChecked()))))
Override.
extra_foam/gui/ctrl_widgets/image_ctrl_widget.py
initConnections
zhujun98/EXtra-foam
0
python
def initConnections(self): mediator = self._mediator self.auto_update_cb.toggled.connect((lambda : self.update_image_btn.setEnabled((not self.sender().isChecked()))))
def initConnections(self): mediator = self._mediator self.auto_update_cb.toggled.connect((lambda : self.update_image_btn.setEnabled((not self.sender().isChecked()))))<|docstring|>Override.<|endoftext|>