input
stringlengths 11
7.65k
| target
stringlengths 22
8.26k
|
---|---|
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, m1, m2):
super(differencematcher, self).__init__(m1._root, m1._cwd)
self._m1 = m1
self._m2 = m2
self.bad = m1.bad
self.traversedir = m1.traversedir |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def matchfn(self, f):
return self._m1(f) and (not self._m2(f) or self._m1.exact(f)) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _files(self):
if self.isexact():
return [f for f in self._m1.files() if self(f)]
# If m1 is not an exact matcher, we can't easily figure out the set of
# files, because its files() are not always files. For example, if
# m1 is "path:dir" and m2 is "rootfileins:.", we don't
# want to remove "dir" from the set even though it would match m2,
# because the "dir" in m1 may not be a file.
return self._m1.files() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def visitdir(self, dir):
dir = normalizerootdir(dir, "visitdir")
if not self._m2.visitdir(dir):
return self._m1.visitdir(dir)
if self._m2.visitdir(dir) == "all":
# There's a bug here: If m1 matches file 'dir/file' and m2 excludes
# 'dir' (recursively), we should still visit 'dir' due to the
# exception we have for exact matches.
return False
return bool(self._m1.visitdir(dir)) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def isexact(self):
return self._m1.isexact() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __repr__(self):
return "<differencematcher m1=%r, m2=%r>" % (self._m1, self._m2) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def intersectmatchers(m1, m2):
"""Composes two matchers by matching if both of them match.
The second matcher's non-matching-attributes (root, cwd, bad, traversedir)
are ignored.
"""
if m1 is None or m2 is None:
return m1 or m2
if m1.always():
m = copy.copy(m2)
# TODO: Consider encapsulating these things in a class so there's only
# one thing to copy from m1.
m.bad = m1.bad
m.traversedir = m1.traversedir
m.abs = m1.abs
m.rel = m1.rel
m._relativeuipath |= m1._relativeuipath
return m
if m2.always():
m = copy.copy(m1)
m._relativeuipath |= m2._relativeuipath
return m
return intersectionmatcher(m1, m2) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, m1, m2):
super(intersectionmatcher, self).__init__(m1._root, m1._cwd)
self._m1 = m1
self._m2 = m2
self.bad = m1.bad
self.traversedir = m1.traversedir |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _files(self):
if self.isexact():
m1, m2 = self._m1, self._m2
if not m1.isexact():
m1, m2 = m2, m1
return [f for f in m1.files() if m2(f)]
# It neither m1 nor m2 is an exact matcher, we can't easily intersect
# the set of files, because their files() are not always files. For
# example, if intersecting a matcher "-I glob:foo.txt" with matcher of
# "path:dir2", we don't want to remove "dir2" from the set.
return self._m1.files() + self._m2.files() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def matchfn(self, f):
return self._m1(f) and self._m2(f) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def visitdir(self, dir):
dir = normalizerootdir(dir, "visitdir")
visit1 = self._m1.visitdir(dir)
if visit1 == "all":
return self._m2.visitdir(dir)
# bool() because visit1=True + visit2='all' should not be 'all'
return bool(visit1 and self._m2.visitdir(dir)) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def always(self):
return self._m1.always() and self._m2.always() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def isexact(self):
return self._m1.isexact() or self._m2.isexact() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __repr__(self):
return "<intersectionmatcher m1=%r, m2=%r>" % (self._m1, self._m2) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, path, matcher):
super(subdirmatcher, self).__init__(matcher._root, matcher._cwd)
self._path = path
self._matcher = matcher
self._always = matcher.always()
self._files = [
f[len(path) + 1 :] for f in matcher._files if f.startswith(path + "/")
]
# If the parent repo had a path to this subrepo and the matcher is
# a prefix matcher, this submatcher always matches.
if matcher.prefix():
self._always = any(f == path for f in matcher._files) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def bad(self, f, msg):
self._matcher.bad(self._path + "/" + f, msg) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def abs(self, f):
return self._matcher.abs(self._path + "/" + f) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def rel(self, f):
return self._matcher.rel(self._path + "/" + f) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def uipath(self, f):
return self._matcher.uipath(self._path + "/" + f) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def matchfn(self, f):
# Some information is lost in the superclass's constructor, so we
# can not accurately create the matching function for the subdirectory
# from the inputs. Instead, we override matchfn() and visitdir() to
# call the original matcher with the subdirectory path prepended.
return self._matcher.matchfn(self._path + "/" + f) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def visitdir(self, dir):
dir = normalizerootdir(dir, "visitdir")
if dir == "":
dir = self._path
else:
dir = self._path + "/" + dir
return self._matcher.visitdir(dir) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def always(self):
return self._always |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def prefix(self):
return self._matcher.prefix() and not self._always |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __repr__(self):
return "<subdirmatcher path=%r, matcher=%r>" % (self._path, self._matcher) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, matchers):
m1 = matchers[0]
super(unionmatcher, self).__init__(m1._root, m1._cwd)
self.traversedir = m1.traversedir
self._matchers = matchers |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def matchfn(self, f):
for match in self._matchers:
if match(f):
return True
return False |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def visitdir(self, dir):
r = False
for m in self._matchers:
v = m.visitdir(dir)
if v == "all":
return v
r |= v
return r |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __repr__(self):
return "<unionmatcher matchers=%r>" % self._matchers |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, m1, m2):
super(xormatcher, self).__init__(m1._root, m1._cwd)
self.traversedir = m1.traversedir
self.m1 = m1
self.m2 = m2 |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def matchfn(self, f):
return bool(self.m1(f)) ^ bool(self.m2(f)) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def visitdir(self, dir):
m1dir = self.m1.visitdir(dir)
m2dir = self.m2.visitdir(dir)
# if both matchers return "all" then we know for sure we don't need
# to visit this directory. Same if all matchers return False. In all
# other case we have to visit a directory.
if m1dir == "all" and m2dir == "all":
return False
if not m1dir and not m2dir:
return False
return True |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __repr__(self):
return "<xormatcher matchers=%r>" % self._matchers |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, matcher):
self._matcher = matcher |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def matchfn(self, f):
match = self._matcher
return match(f) or any(map(match, util.dirs((f,)))) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def visitdir(self, dir):
if self(dir):
return "all"
return self._matcher.visitdir(dir) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __repr__(self):
return "<recursivematcher %r>" % self._matcher |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def patkind(pattern, default=None):
"""If pattern is 'kind:pat' with a known kind, return kind."""
return _patsplit(pattern, default)[0] |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _patsplit(pattern, default):
"""Split a string into the optional pattern kind prefix and the actual
pattern."""
if ":" in pattern:
kind, pat = pattern.split(":", 1)
if kind in allpatternkinds:
return kind, pat
return default, pattern |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def peek():
return i < n and pat[i : i + 1] |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _regex(kind, pat, globsuffix):
"""Convert a (normalized) pattern of any kind into a regular expression.
globsuffix is appended to the regexp of globs."""
if not pat and kind in ("glob", "relpath"):
return ""
if kind == "re":
return pat
if kind in ("path", "relpath"):
if pat == ".":
return ""
return util.re.escape(pat) + "(?:/|$)"
if kind == "rootfilesin":
if pat == ".":
escaped = ""
else:
# Pattern is a directory name.
escaped = util.re.escape(pat) + "/"
# Anything after the pattern must be a non-directory.
return escaped + "[^/]+$"
if kind == "relglob":
return "(?:|.*/)" + _globre(pat) + globsuffix
if kind == "relre":
if pat.startswith("^"):
return pat
return ".*" + pat
return _globre(pat) + globsuffix |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def matchsubinclude(f):
for prefix, matcherargs in subincludes:
if f.startswith(prefix):
mf = submatchers.get(prefix)
if mf is None:
mf = match(*matcherargs)
submatchers[prefix] = mf
if mf(f[len(prefix) :]):
return True
return False |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _buildregexmatch(kindpats, globsuffix):
"""Build a match function from a list of kinds and kindpats,
return regexp string and a matcher function."""
try:
regex = "(?:%s)" % "|".join(
[_regex(k, p, globsuffix) for (k, p, s) in kindpats]
)
if len(regex) > 20000:
raise OverflowError
return regex, _rematcher(regex)
except OverflowError:
# We're using a Python with a tiny regex engine and we
# made it explode, so we'll divide the pattern list in two
# until it works
l = len(kindpats)
if l < 2:
raise
regexa, a = _buildregexmatch(kindpats[: l // 2], globsuffix)
regexb, b = _buildregexmatch(kindpats[l // 2 :], globsuffix)
return regex, lambda s: a(s) or b(s)
except re.error:
for k, p, s in kindpats:
try:
_rematcher("(?:%s)" % _regex(k, p, globsuffix))
except re.error:
if s:
raise error.Abort(_("%s: invalid pattern (%s): %s") % (s, k, p))
else:
raise error.Abort(_("invalid pattern (%s): %s") % (k, p))
raise error.Abort(_("invalid pattern")) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _patternrootsanddirs(kindpats):
"""Returns roots and directories corresponding to each pattern.
This calculates the roots and directories exactly matching the patterns and
returns a tuple of (roots, dirs) for each. It does not return other
directories which may also need to be considered, like the parent
directories.
"""
r = []
d = []
for kind, pat, source in kindpats:
if kind == "glob": # find the non-glob prefix
root = []
for p in pat.split("/"):
if "[" in p or "{" in p or "*" in p or "?" in p:
break
root.append(p)
r.append("/".join(root))
elif kind in ("relpath", "path"):
if pat == ".":
pat = ""
r.append(pat)
elif kind in ("rootfilesin",):
if pat == ".":
pat = ""
d.append(pat)
else: # relglob, re, relre
r.append("")
return r, d |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _roots(kindpats):
"""Returns root directories to match recursively from the given patterns."""
roots, dirs = _patternrootsanddirs(kindpats)
return roots |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _rootsanddirs(kindpats):
"""Returns roots and exact directories from patterns.
roots are directories to match recursively, whereas exact directories should
be matched non-recursively. The returned (roots, dirs) tuple will also
include directories that need to be implicitly considered as either, such as
parent directories.
>>> _rootsanddirs(
... [(b'glob', b'g/h/*', b''), (b'glob', b'g/h', b''),
... (b'glob', b'g*', b'')])
(['g/h', 'g/h', ''], ['', 'g'])
>>> _rootsanddirs(
... [(b'rootfilesin', b'g/h', b''), (b'rootfilesin', b'', b'')])
([], ['g/h', '', '', 'g'])
>>> _rootsanddirs(
... [(b'relpath', b'r', b''), (b'path', b'p/p', b''),
... (b'path', b'', b'')])
(['r', 'p/p', ''], ['', 'p'])
>>> _rootsanddirs(
... [(b'relglob', b'rg*', b''), (b're', b're/', b''),
... (b'relre', b'rr', b'')])
(['', '', ''], [''])
"""
r, d = _patternrootsanddirs(kindpats)
# Append the parents as non-recursive/exact directories, since they must be
# scanned to get to either the roots or the other exact directories.
d.extend(sorted(util.dirs(d)))
d.extend(sorted(util.dirs(r)))
return r, d |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _explicitfiles(kindpats):
"""Returns the potential explicit filenames from the patterns.
>>> _explicitfiles([(b'path', b'foo/bar', b'')])
['foo/bar']
>>> _explicitfiles([(b'rootfilesin', b'foo/bar', b'')])
[]
"""
# Keep only the pattern kinds where one can specify filenames (vs only
# directory names).
filable = [kp for kp in kindpats if kp[0] not in ("rootfilesin",)]
return _roots(filable) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _prefix(kindpats):
"""Whether all the patterns match a prefix (i.e. recursively)"""
for kind, pat, source in kindpats:
if kind not in ("path", "relpath"):
return False
return True |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def readpatternfile(filepath, warn, sourceinfo=False):
"""parse a pattern file, returning a list of
patterns. These patterns should be given to compile()
to be validated and converted into a match function.
trailing white space is dropped.
the escape character is backslash.
comments start with #.
empty lines are skipped.
lines can be of the following formats:
syntax: regexp # defaults following lines to non-rooted regexps
syntax: glob # defaults following lines to non-rooted globs
re:pattern # non-rooted regular expression
glob:pattern # non-rooted glob
pattern # pattern of the current default type
if sourceinfo is set, returns a list of tuples:
(pattern, lineno, originalline). This is useful to debug ignore patterns.
"""
syntaxes = {
"re": "relre:",
"regexp": "relre:",
"glob": "relglob:",
"include": "include",
"subinclude": "subinclude",
}
syntax = "relre:"
patterns = []
fp = open(filepath, "rb")
for lineno, line in enumerate(util.iterfile(fp), start=1):
if "#" in line:
global _commentre
if not _commentre:
_commentre = util.re.compile(br"((?:^|[^\\])(?:\\\\)*)#.*")
# remove comments prefixed by an even number of escapes
m = _commentre.search(line)
if m:
line = line[: m.end(1)]
# fixup properly escaped comments that survived the above
line = line.replace("\\#", "#")
line = line.rstrip()
if not line:
continue
if line.startswith("syntax:"):
s = line[7:].strip()
try:
syntax = syntaxes[s]
except KeyError:
if warn:
warn(_("%s: ignoring invalid syntax '%s'\n") % (filepath, s))
continue
linesyntax = syntax
for s, rels in pycompat.iteritems(syntaxes):
if line.startswith(rels):
linesyntax = rels
line = line[len(rels) :]
break
elif line.startswith(s + ":"):
linesyntax = rels
line = line[len(s) + 1 :]
break
if sourceinfo:
patterns.append((linesyntax + line, lineno, line))
else:
patterns.append(linesyntax + line)
fp.close()
return patterns |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def sm_section(name: str) -> str:
""":return: section title used in .gitmodules configuration file"""
return f'submodule "{name}"' |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _ccode(self, printer):
return "fabs(%s)" % printer._print(self.args[0]) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def sm_name(section: str) -> str:
""":return: name of the submodule as parsed from the section name"""
section = section.strip()
return section[11:-1] |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_sqrt():
assert ccode(sqrt(x)) == "sqrt(x)"
assert ccode(x**0.5) == "sqrt(x)"
assert ccode(sqrt(x)) == "sqrt(x)" |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def mkhead(repo: 'Repo', path: PathLike) -> 'Head':
""":return: New branch/head instance"""
return git.Head(repo, git.Head.to_full_path(path)) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_Pow():
assert ccode(x**3) == "pow(x, 3)"
assert ccode(x**(y**3)) == "pow(x, pow(y, 3))"
assert ccode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
"pow(3.5*g(x), -x + pow(y, x))/(pow(x, 2) + y)"
assert ccode(x**-1.0) == '1.0/x'
assert ccode(x**Rational(2, 3)) == 'pow(x, 2.0L/3.0L)'
_cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"),
(lambda base, exp: not exp.is_integer, "pow")]
assert ccode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)'
assert ccode(x**3.2, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 3.2)' |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def find_first_remote_branch(remotes: Sequence['Remote'], branch_name: str) -> 'RemoteReference':
"""Find the remote branch matching the name of the given branch or raise InvalidGitRepositoryError"""
for remote in remotes:
try:
return remote.refs[branch_name]
except IndexError:
continue
# END exception handling
# END for remote
raise InvalidGitRepositoryError("Didn't find remote branch '%r' in any of the given remotes" % branch_name) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_constants_mathh():
assert ccode(exp(1)) == "M_E"
assert ccode(pi) == "M_PI"
assert ccode(oo) == "HUGE_VAL"
assert ccode(-oo) == "-HUGE_VAL" |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, *args: Any, **kwargs: Any) -> None:
self._smref: Union['ReferenceType[Submodule]', None] = None
self._index = None
self._auto_write = True
super(SubmoduleConfigParser, self).__init__(*args, **kwargs) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_constants_other():
assert ccode(2*GoldenRatio) == "double const GoldenRatio = 1.61803398874989;\n2*GoldenRatio"
assert ccode(
2*Catalan) == "double const Catalan = 0.915965594177219;\n2*Catalan"
assert ccode(2*EulerGamma) == "double const EulerGamma = 0.577215664901533;\n2*EulerGamma" |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def set_submodule(self, submodule: 'Submodule') -> None:
"""Set this instance's submodule. It must be called before
the first write operation begins"""
self._smref = weakref.ref(submodule) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_Rational():
assert ccode(Rational(3, 7)) == "3.0L/7.0L"
assert ccode(Rational(18, 9)) == "2"
assert ccode(Rational(3, -7)) == "-3.0L/7.0L"
assert ccode(Rational(-3, -7)) == "3.0L/7.0L"
assert ccode(x + Rational(3, 7)) == "x + 3.0L/7.0L"
assert ccode(Rational(3, 7)*x) == "(3.0L/7.0L)*x" |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def flush_to_index(self) -> None:
"""Flush changes in our configuration file to the index"""
assert self._smref is not None
# should always have a file here
assert not isinstance(self._file_or_files, BytesIO)
sm = self._smref()
if sm is not None:
index = self._index
if index is None:
index = sm.repo.index
# END handle index
index.add([sm.k_modules_file], write=self._auto_write)
sm._clear_cache()
# END handle weakref |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_Integer():
assert ccode(Integer(67)) == "67"
assert ccode(Integer(-1)) == "-1" |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def write(self) -> None: # type: ignore[override]
rval: None = super(SubmoduleConfigParser, self).write()
self.flush_to_index()
return rval |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_functions():
assert ccode(sin(x) ** cos(x)) == "pow(sin(x), cos(x))" |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_inline_function():
x = symbols('x')
g = implemented_function('g', Lambda(x, 2*x))
assert ccode(g(x)) == "2*x"
g = implemented_function('g', Lambda(x, 2*x/Catalan))
assert ccode(
g(x)) == "double const Catalan = %s;\n2*x/Catalan" % Catalan.n()
A = IndexedBase('A')
i = Idx('i', symbols('n', integer=True))
g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
assert ccode(g(A[i]), assign_to=A[i]) == (
"for (int i=0; i<n; i++){\n"
" A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
"}"
) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_exceptions():
assert ccode(ceiling(x)) == "ceil(x)"
assert ccode(Abs(x)) == "fabs(x)"
assert ccode(gamma(x)) == "tgamma(x)" |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_user_functions():
x = symbols('x', integer=False)
n = symbols('n', integer=True)
custom_functions = {
"ceiling": "ceil",
"Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")],
}
assert ccode(ceiling(x), user_functions=custom_functions) == "ceil(x)"
assert ccode(Abs(x), user_functions=custom_functions) == "fabs(x)"
assert ccode(Abs(n), user_functions=custom_functions) == "abs(n)" |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_boolean():
assert ccode(x & y) == "x && y"
assert ccode(x | y) == "x || y"
assert ccode(~x) == "!x"
assert ccode(x & y & z) == "x && y && z"
assert ccode(x | y | z) == "x || y || z"
assert ccode((x & y) | z) == "z || x && y"
assert ccode((x | y) & z) == "z && (x || y)" |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_Piecewise():
p = ccode(Piecewise((x, x < 1), (x**2, True)))
s = \ |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_Piecewise_deep():
p = ccode(2*Piecewise((x, x < 1), (x**2, True)))
s = \ |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_settings():
raises(TypeError, lambda: ccode(sin(x), method="garbage")) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_Indexed():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m, o = symbols('n m o', integer=True)
i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
p = CCodePrinter()
p._not_c = set()
x = IndexedBase('x')[j]
assert p._print_Indexed(x) == 'x[j]'
A = IndexedBase('A')[i, j]
assert p._print_Indexed(A) == 'A[%s]' % (m*i+j)
B = IndexedBase('B')[i, j, k]
assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k)
assert p._not_c == set() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_Indexed_without_looking_for_contraction():
len_y = 5
y = IndexedBase('y', shape=(len_y,))
x = IndexedBase('x', shape=(len_y,))
Dy = IndexedBase('Dy', shape=(len_y-1,))
i = Idx('i', len_y-1)
e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
code0 = ccode(e.rhs, assign_to=e.lhs, contract=False)
assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_loops_matrix_vector():
n, m = symbols('n m', integer=True)
A = IndexedBase('A')
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
s = (
'for (int i=0; i<m; i++){\n'
' y[i] = 0;\n'
'}\n'
'for (int i=0; i<m; i++){\n'
' for (int j=0; j<n; j++){\n'
' y[i] = x[j]*A[%s] + y[i];\n' % (i*n + j) +\
' }\n'
'}'
)
c = ccode(A[i, j]*x[j], assign_to=y[i])
assert c == s |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_dummy_loops():
# the following line could also be
# [Dummy(s, integer=True) for s in 'im']
# or [Dummy(integer=True) for s in 'im']
i, m = symbols('i m', integer=True, cls=Dummy)
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx(i, m)
expected = (
'for (int i_%(icount)i=0; i_%(icount)i<m_%(mcount)i; i_%(icount)i++){\n'
' y[i_%(icount)i] = x[i_%(icount)i];\n'
'}'
) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
code = ccode(x[i], assign_to=y[i])
assert code == expected |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_loops_add():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m = symbols('n m', integer=True)
A = IndexedBase('A')
x = IndexedBase('x')
y = IndexedBase('y')
z = IndexedBase('z')
i = Idx('i', m)
j = Idx('j', n)
s = (
'for (int i=0; i<m; i++){\n'
' y[i] = x[i] + z[i];\n'
'}\n'
'for (int i=0; i<m; i++){\n'
' for (int j=0; j<n; j++){\n'
' y[i] = x[j]*A[%s] + y[i];\n' % (i*n + j) +\
' }\n'
'}'
)
c = ccode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i])
assert c == s |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_loops_multiple_contractions():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m, o, p = symbols('n m o p', integer=True)
a = IndexedBase('a')
b = IndexedBase('b')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
k = Idx('k', o)
l = Idx('l', p)
s = (
'for (int i=0; i<m; i++){\n'
' y[i] = 0;\n'
'}\n'
'for (int i=0; i<m; i++){\n'
' for (int j=0; j<n; j++){\n'
' for (int k=0; k<o; k++){\n'
' for (int l=0; l<p; l++){\n'
' y[i] = y[i] + b[%s]*a[%s];\n' % (j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l) +\
' }\n'
' }\n'
' }\n'
'}'
)
c = ccode(b[j, k, l]*a[i, j, k, l], assign_to=y[i])
assert c == s |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_ccode_loops_addfactor():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m, o, p = symbols('n m o p', integer=True)
a = IndexedBase('a')
b = IndexedBase('b')
c = IndexedBase('c')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
k = Idx('k', o)
l = Idx('l', p)
s = (
'for (int i=0; i<m; i++){\n'
' y[i] = 0;\n'
'}\n'
'for (int i=0; i<m; i++){\n'
' for (int j=0; j<n; j++){\n'
' for (int k=0; k<o; k++){\n'
' for (int l=0; l<p; l++){\n'
' y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
' }\n'
' }\n'
' }\n'
'}'
)
c = ccode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i])
assert c == s |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | async def close(self) -> None:
await self._client.close() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def build_get_request(
resource_group_name: str,
managed_instance_name: str,
database_name: str,
query_id: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2020-11-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'),
"managedInstanceName": _SERIALIZER.url("managed_instance_name", managed_instance_name, 'str'),
"databaseName": _SERIALIZER.url("database_name", database_name, 'str'),
"queryId": _SERIALIZER.url("query_id", query_id, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def index():
return render_template('index.html'), 200 |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def build_list_by_query_request(
resource_group_name: str,
managed_instance_name: str,
database_name: str,
query_id: str,
subscription_id: str,
*,
start_time: Optional[str] = None,
end_time: Optional[str] = None,
interval: Optional[Union[str, "_models.QueryTimeGrainType"]] = None,
**kwargs: Any
) -> HttpRequest:
api_version = "2020-11-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}/statistics')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'),
"managedInstanceName": _SERIALIZER.url("managed_instance_name", managed_instance_name, 'str'),
"databaseName": _SERIALIZER.url("database_name", database_name, 'str'),
"queryId": _SERIALIZER.url("query_id", query_id, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
if start_time is not None:
query_parameters['startTime'] = _SERIALIZER.query("start_time", start_time, 'str')
if end_time is not None:
query_parameters['endTime'] = _SERIALIZER.query("end_time", end_time, 'str')
if interval is not None:
query_parameters['interval'] = _SERIALIZER.query("interval", interval, 'str')
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200 |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500 |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def get(
self,
resource_group_name: str,
managed_instance_name: str,
database_name: str,
query_id: str,
**kwargs: Any
) -> "_models.ManagedInstanceQuery":
"""Get query by query id.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal.
:type resource_group_name: str
:param managed_instance_name: The name of the managed instance.
:type managed_instance_name: str
:param database_name: The name of the database.
:type database_name: str
:param query_id:
:type query_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ManagedInstanceQuery, or the result of cls(response)
:rtype: ~azure.mgmt.sql.models.ManagedInstanceQuery
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceQuery"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {})) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5 |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def prepare_request(next_link=None):
if not next_link: |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def extract_data(pipeline_response):
deserialized = self._deserialize("ManagedInstanceQueryStatistics", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def idfun(x): return x |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_supertype(self):
self.assert_(isinstance(None, NullType))
self.assert_(isinstance(Optional('a'), NullType))
self.assert_(isinstance(NotPassed, NotPassedType))
self.assert_(isinstance(NotPassed, NullType)) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | async def _post_initial(
self,
body: "_models.CalculateExchangeRequest",
**kwargs: Any
) -> Optional["_models.CalculateExchangeOperationResultResponse"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.CalculateExchangeOperationResultResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-10-01-preview"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._post_initial.metadata['url'] # type: ignore
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(body, 'CalculateExchangeRequest')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CalculateExchangeOperationResultResponse', pipeline_response)
if response.status_code == 202:
response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation'))
response_headers['Location']=self._deserialize('str', response.headers.get('Location'))
response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After'))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def myfunc(first, second=None, third=Optional(5), fourth=Optional(execute=list)):
#Equivalent: second = deoption(second, 5)
if isinstance(second, type(None)):
second = 5 |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def get_long_running_output(pipeline_response):
deserialized = self._deserialize('CalculateExchangeOperationResultResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.