uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8264d36a097a662cc905cf16 | train | function | def na_logical_op(x: np.ndarray, y, op):
try:
# For exposition, write:
# yarr = isinstance(y, np.ndarray)
# yint = is_integer(y) or (yarr and y.dtype.kind == "i")
# ybool = is_bool(y) or (yarr and y.dtype.kind == "b")
# xint = x.dtype.kind == "i"
# xbool = x.dtyp... | def na_logical_op(x: np.ndarray, y, op):
| try:
# For exposition, write:
# yarr = isinstance(y, np.ndarray)
# yint = is_integer(y) or (yarr and y.dtype.kind == "i")
# ybool = is_bool(y) or (yarr and y.dtype.kind == "b")
# xint = x.dtype.kind == "i"
# xbool = x.dtype.kind == "b"
# Then Cases where ... | __)
method = getattr(lvalues, op_name)
with np.errstate(all="ignore"):
res_values = method(rvalues)
if res_values is NotImplemented:
res_values = invalid_comparison(lvalues, rvalues, op)
if is_scalar(res_values):
raise TypeError(
"Coul... | 104 | 104 | 349 | 14 | 89 | raghavgai/mypandas | pandas/core/ops/array_ops.py | Python | na_logical_op | na_logical_op | 263 | 302 | 263 | 263 | ab502cf0f36e59cead4b0e4c2863028eb18ee2a2 | bigcode/the-stack | train |
10930048ba4bf88342dc2c1d | train | function | def define_na_arithmetic_op(op, str_rep: str):
def na_op(x, y):
return na_arithmetic_op(x, y, op, str_rep)
return na_op
| def define_na_arithmetic_op(op, str_rep: str):
| def na_op(x, y):
return na_arithmetic_op(x, y, op, str_rep)
return na_op
| result[mask] = op(xrav[mask], y)
result, changed = maybe_upcast_putmask(result, ~mask, np.nan)
result = result.reshape(x.shape) # 2D compat
return result
def define_na_arithmetic_op(op, str_rep: str):
| 64 | 64 | 41 | 13 | 50 | raghavgai/mypandas | pandas/core/ops/array_ops.py | Python | define_na_arithmetic_op | define_na_arithmetic_op | 118 | 122 | 118 | 118 | 775e1361c824668fd006c45bab2632a6362abde2 | bigcode/the-stack | train |
d7fdc69679428790e188162b | train | function | def logical_op(
left: Union[np.ndarray, ABCExtensionArray], right: Any, op
) -> Union[np.ndarray, ABCExtensionArray]:
"""
Evaluate a logical operation `|`, `&`, or `^`.
Parameters
----------
left : np.ndarray or ExtensionArray
right : object
Cannot be a DataFrame, Series, or Index.
... | def logical_op(
left: Union[np.ndarray, ABCExtensionArray], right: Any, op
) -> Union[np.ndarray, ABCExtensionArray]:
| """
Evaluate a logical operation `|`, `&`, or `^`.
Parameters
----------
left : np.ndarray or ExtensionArray
right : object
Cannot be a DataFrame, Series, or Index.
op : {operator.and_, operator.or_, operator.xor}
Or one of the reversed variants from roperator.
Returns
... | (y)
if not isna(y):
y = bool(y)
try:
result = libops.scalar_binop(x, y, op)
except (
TypeError,
ValueError,
AttributeError,
OverflowError,
NotImplementedError,
... | 152 | 152 | 509 | 35 | 116 | raghavgai/mypandas | pandas/core/ops/array_ops.py | Python | logical_op | logical_op | 305 | 369 | 305 | 307 | 5617e03af99ca6b137e1e87d7ead3829f2d58ffd | bigcode/the-stack | train |
2a0b9774d8adb6361696f9ad | train | class | class Tracker:
"""
This is the multi-target tracker.
Parameters
----------
metric : nn_matching.NearestNeighborDistanceMetric
A distance metric for measurement-to-track association.
max_age : int
Maximum number of missed misses before a track is deleted.
n_init : int
... | class Tracker:
| """
This is the multi-target tracker.
Parameters
----------
metric : nn_matching.NearestNeighborDistanceMetric
A distance metric for measurement-to-track association.
max_age : int
Maximum number of missed misses before a track is deleted.
n_init : int
Number of cons... | # vim: expandtab:ts=4:sw=4
from __future__ import absolute_import
import numpy as np
from . import kalman_filter
from . import linear_assignment
from . import iou_matching
from .track import Track
class Tracker:
| 56 | 256 | 1,074 | 3 | 52 | makan898/DETR_DeepSORT | deep_sort/sort/tracker.py | Python | Tracker | Tracker | 10 | 138 | 10 | 10 | 0333a346ba2ef51ab34e2c5789fbf11fad72feeb | bigcode/the-stack | train |
e6067628cae8f9603351b3dd | train | class | class WordExtractingDoFn(beam.DoFn):
"""Parse each line of input text into words."""
def process(self, element):
"""Returns an iterator over the words of this element.
The element is a line of text. If the line is blank, note that, too.
Args:
element: the element being processed
Returns:
... | class WordExtractingDoFn(beam.DoFn):
| """Parse each line of input text into words."""
def process(self, element):
"""Returns an iterator over the words of this element.
The element is a line of text. If the line is blank, note that, too.
Args:
element: the element being processed
Returns:
The processed element.
"""
... |
import re
import apache_beam as beam
from apache_beam.io import ReadFromText
from apache_beam.io import WriteToText
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions
class WordExtractingDoFn(beam.DoFn):
| 64 | 64 | 100 | 11 | 52 | harrydrippin/beam | sdks/python/apache_beam/examples/wordcount.py | Python | WordExtractingDoFn | WordExtractingDoFn | 44 | 57 | 44 | 44 | 7edcce79b3a96a808e1b8a4ae3d404d0c4d1b008 | bigcode/the-stack | train |
f1873e20a4a9332aca1e7184 | train | function | def run(argv=None, save_main_session=True):
"""Main entry point; defines and runs the wordcount pipeline."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--input',
dest='input',
default='gs://dataflow-samples/shakespeare/kinglear.txt',
help='Input file to process.')
parser.ad... | def run(argv=None, save_main_session=True):
| """Main entry point; defines and runs the wordcount pipeline."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--input',
dest='input',
default='gs://dataflow-samples/shakespeare/kinglear.txt',
help='Input file to process.')
parser.add_argument(
'--output',
dest='ou... | _options import SetupOptions
class WordExtractingDoFn(beam.DoFn):
"""Parse each line of input text into words."""
def process(self, element):
"""Returns an iterator over the words of this element.
The element is a line of text. If the line is blank, note that, too.
Args:
element: the element ... | 115 | 115 | 385 | 10 | 105 | harrydrippin/beam | sdks/python/apache_beam/examples/wordcount.py | Python | run | run | 60 | 100 | 60 | 60 | d7eec5cf89e92325c2a6a9dd90459693292305ba | bigcode/the-stack | train |
ac4432cd82e41905630db77f | train | function | def solve_linear_system(system, *symbols, **flags):
r"""
Solve system of $N$ linear equations with $M$ variables, which means
both under- and overdetermined systems are supported.
Explanation
===========
The possible number of solutions is zero, one, or infinite. Respectively,
this procedu... | def solve_linear_system(system, *symbols, **flags):
| r"""
Solve system of $N$ linear equations with $M$ variables, which means
both under- and overdetermined systems are supported.
Explanation
===========
The possible number of solutions is zero, one, or infinite. Respectively,
this procedure will return None or a dictionary with solutions. ... | =True)
n0 = len([x for x in bestsol.values() if x != 0])
for n in range(n0 - 1, 1, -1):
debug('minsolve: %s' % n)
thissol = None
for nonzeros in combinations(list(range(N)), n):
subm = Matrix([system.col(i).T for i in nonzeros] + [system.col(-1).T]).T
... | 256 | 256 | 1,660 | 12 | 243 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | solve_linear_system | solve_linear_system | 2,279 | 2,481 | 2,279 | 2,279 | d0109a765c48f5fae596f2ba4f37e848aecf1601 | bigcode/the-stack | train |
3ad0917eabf9453d5df97203 | train | function | def check_assumptions(expr, against=None, **assumptions):
"""
Checks whether expression *expr* satisfies all assumptions.
Explanation
===========
*assumptions* is a dict of assumptions: {'assumption': True|False, ...}.
Examples
========
>>> from sympy import Symbol, pi, I, exp, ch... | def check_assumptions(expr, against=None, **assumptions):
| """
Checks whether expression *expr* satisfies all assumptions.
Explanation
===========
*assumptions* is a dict of assumptions: {'assumption': True|False, ...}.
Examples
========
>>> from sympy import Symbol, pi, I, exp, check_assumptions
>>> check_assumptions(-5, integer=... | , positive=True)
{'positive': None}
If *expr* satisfies all of the assumptions, an empty dictionary is returned.
>>> failing_assumptions(x**2, positive=True)
{}
"""
expr = sympify(expr)
failed = {}
for key in list(assumptions.keys()):
test = getattr(expr, 'is_%s' % key, None)
... | 128 | 128 | 428 | 15 | 113 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | check_assumptions | check_assumptions | 409 | 467 | 409 | 409 | 92f4d5cd95e8e30484905796e241ac10acc57046 | bigcode/the-stack | train |
df1b38a3fed0dec3be60181a | train | function | def solve_linear(lhs, rhs=0, symbols=[], exclude=[]):
r"""
Return a tuple derived from ``f = lhs - rhs`` that is one of
the following: ``(0, 1)``, ``(0, 0)``, ``(symbol, solution)``, ``(n, d)``.
Explanation
===========
``(0, 1)`` meaning that ``f`` is independent of the symbols in *symbols*
... | def solve_linear(lhs, rhs=0, symbols=[], exclude=[]):
| r"""
Return a tuple derived from ``f = lhs - rhs`` that is one of
the following: ``(0, 1)``, ``(0, 0)``, ``(symbol, solution)``, ``(n, d)``.
Explanation
===========
``(0, 1)`` meaning that ``f`` is independent of the symbols in *symbols*
that are not in *exclude*.
``(0, 0)`` meaning t... |
newresult.append(rnew)
hit = True
got_s.add(s)
if not hit:
raise NotImplementedError('could not solve %s' % eq2)
else:
result = newresult
for b in bad_results:
... | 256 | 256 | 1,732 | 14 | 241 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | solve_linear | solve_linear | 2,011 | 2,192 | 2,011 | 2,011 | 0f21335136eb9fc370e2a79bfc367490e3c7d616 | bigcode/the-stack | train |
11ef8149ec90bd2edec6b47c | train | function | def denoms(eq, *symbols):
"""
Return (recursively) set of all denominators that appear in *eq*
that contain any symbol in *symbols*; if *symbols* are not
provided then all denominators will be returned.
Examples
========
>>> from sympy.solvers.solvers import denoms
>>> from sympy.abc i... | def denoms(eq, *symbols):
| """
Return (recursively) set of all denominators that appear in *eq*
that contain any symbol in *symbols*; if *symbols* are not
provided then all denominators will be returned.
Examples
========
>>> from sympy.solvers.solvers import denoms
>>> from sympy.abc import x, y, z
>>> from... | the power will be zero, too. To keep it simple and fast, we
# limit simplification to exponents that are Numbers
dens = set()
for d in denoms(f, symbols):
if d.is_Pow and d.exp.is_Number:
if d.exp.is_zero:
continue # foo**0 is never 0
d = d.base
dens... | 98 | 98 | 327 | 8 | 89 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | denoms | denoms | 128 | 179 | 128 | 128 | a6bb7430390d81ea32bf8f9d2e48c8268ba3c240 | bigcode/the-stack | train |
a8668d218bacae9fc37de903 | train | function | def _solve(f, *symbols, **flags):
"""
Return a checked solution for *f* in terms of one or more of the
symbols. A list should be returned except for the case when a linear
undetermined-coefficients equation is encountered (in which case
a dictionary is returned).
If no method is implemented to ... | def _solve(f, *symbols, **flags):
| """
Return a checked solution for *f* in terms of one or more of the
symbols. A list should be returned except for the case when a linear
undetermined-coefficients equation is encountered (in which case
a dictionary is returned).
If no method is implemented to solve the equation, a NotImplement... | done
###########################################################################
as_dict = flags.get('dict', False)
as_set = flags.get('set', False)
if not as_set and isinstance(solution, list):
# Make sure that a list of solutions is ordered in a canonical way.
solution.sort(key=defa... | 256 | 256 | 3,773 | 11 | 245 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | _solve | _solve | 1,398 | 1,807 | 1,398 | 1,398 | 48ff18f70d176365ad9b27d0e5ccea56871c5642 | bigcode/the-stack | train |
1abac56e978ea5bc5dfd0133 | train | function | def failing_assumptions(expr, **assumptions):
"""
Return a dictionary containing assumptions with values not
matching those of the passed assumptions.
Examples
========
>>> from sympy import failing_assumptions, Symbol
>>> x = Symbol('x', real=True, positive=True)
>>> y = Symbol('y')
... | def failing_assumptions(expr, **assumptions):
| """
Return a dictionary containing assumptions with values not
matching those of the passed assumptions.
Examples
========
>>> from sympy import failing_assumptions, Symbol
>>> x = Symbol('x', real=True, positive=True)
>>> y = Symbol('y')
>>> failing_assumptions(6*x + y, real=True... | -9) is S.true
was = val
if flags.get('warn', False):
warnings.warn("\n\tWarning: could not verify solution %s." % sol)
# returns None if it can't conclude
# TODO: improve solution testing
def failing_assumptions(expr, **assumptions):
| 68 | 68 | 228 | 12 | 55 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | failing_assumptions | failing_assumptions | 376 | 406 | 376 | 376 | 359a339973aa13b3099f1d24c25951539216a1e6 | bigcode/the-stack | train |
44591a4c6892dfd276d6c54f | train | function | def minsolve_linear_system(system, *symbols, **flags):
r"""
Find a particular solution to a linear system.
Explanation
===========
In particular, try to find a solution with the minimal possible number
of non-zero variables using a naive algorithm with exponential complexity.
If ``quick=Tr... | def minsolve_linear_system(system, *symbols, **flags):
| r"""
Find a particular solution to a linear system.
Explanation
===========
In particular, try to find a solution with the minimal possible number
of non-zero variables using a naive algorithm with exponential complexity.
If ``quick=True``, a heuristic is used.
"""
quick = flags.g... | or any(dnewn_dxi.diff(s) for s in free)):
all_zero = False
if dnewn_dxi is S.NaN:
break
if xi not in dnewn_dxi.free_symbols:
vi = -1/dnewn_dxi*(newn.subs(xi, 0))
if dens is None:
dens = _simple_dens(eq, symbols)
... | 232 | 232 | 775 | 13 | 218 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | minsolve_linear_system | minsolve_linear_system | 2,195 | 2,276 | 2,195 | 2,195 | 155883a049329f486871f8381e737efcbbff28a9 | bigcode/the-stack | train |
0227a4a73967e95271b9e198 | train | function | def unrad(eq, *syms, **flags):
"""
Remove radicals with symbolic arguments and return (eq, cov),
None, or raise an error.
Explanation
===========
None is returned if there are no radicals to remove.
NotImplementedError is raised if there are radicals and they cannot be
removed or if t... | def unrad(eq, *syms, **flags):
| """
Remove radicals with symbolic arguments and return (eq, cov),
None, or raise an error.
Explanation
===========
None is returned if there are no radicals to remove.
NotImplementedError is raised if there are radicals and they cannot be
removed or if the relationship between the ori... | rhs and lhs.is_Pow and lhs.exp.is_Integer and lhs.exp < 0:
lhs = 1/lhs
rhs = 1/rhs
# base**a = b -> base = b**(1/a) if
# a is an Integer and dointpow=True (this gives real branch of root)
# a is not an Integer and the equation is multivariate and the
# ... | 256 | 256 | 3,966 | 12 | 243 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | unrad | unrad | 3,323 | 3,700 | 3,323 | 3,323 | dba7848e8e539ea040e466bdfa01e99aefac0ecf | bigcode/the-stack | train |
c4daba9acc449cbd64e77512 | train | function | @conserve_mpmath_dps
def nsolve(*args, **kwargs):
r"""
Solve a nonlinear equation system numerically: ``nsolve(f, [args,] x0,
modules=['mpmath'], **kwargs)``.
Explanation
===========
``f`` is a vector function of symbolic expressions representing the system.
*args* are the variables. If th... | @conserve_mpmath_dps
def nsolve(*args, **kwargs):
| r"""
Solve a nonlinear equation system numerically: ``nsolve(f, [args,] x0,
modules=['mpmath'], **kwargs)``.
Explanation
===========
``f`` is a vector function of symbolic expressions representing the system.
*args* are the variables. If there is only one variable, this argument can
be... | - rhs, *g)
if gpu is None:
raise NotImplementedError
g, p, u = gpu
flags['bivariate'] = False
inversion = _tsolve(g - u, sym, **flags)
if inversion:
... | 256 | 256 | 1,983 | 18 | 237 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | nsolve | nsolve | 2,929 | 3,130 | 2,929 | 2,930 | 6947278274cfafef9801cdd95f96e4404d627778 | bigcode/the-stack | train |
91487c6cfbeeadbd2347cb42 | train | function | def det_quick(M, method=None):
"""
Return ``det(M)`` assuming that either
there are lots of zeros or the size of the matrix
is small. If this assumption is not met, then the normal
Matrix.det function will be used with method = ``method``.
See Also
========
det_minor
det_perm
... | def det_quick(M, method=None):
| """
Return ``det(M)`` assuming that either
there are lots of zeros or the size of the matrix
is small. If this assumption is not met, then the normal
Matrix.det function will be used with method = ``method``.
See Also
========
det_minor
det_perm
"""
if any(i.has(Symbol) fo... | )[i % 2]*Add(*[M[0, i]*d for d in
Add.make_args(det_minor(M.minor_submatrix(0, i)))])
if M[0, i] else S.Zero for i in range(n)])
def det_quick(M, method=None):
| 63 | 64 | 140 | 9 | 54 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | det_quick | det_quick | 2,628 | 2,647 | 2,628 | 2,628 | be5b489bc4b0a78e5d092624746d7cf0e5a56444 | bigcode/the-stack | train |
ddf43c41073834e470d4e4e7 | train | function | def solve_undetermined_coeffs(equ, coeffs, sym, **flags):
r"""
Solve equation of a type $p(x; a_1, \ldots, a_k) = q(x)$ where both
$p$ and $q$ are univariate polynomials that depend on $k$ parameters.
Explanation
===========
The result of this function is a dictionary with symbolic values of t... | def solve_undetermined_coeffs(equ, coeffs, sym, **flags):
| r"""
Solve equation of a type $p(x; a_1, \ldots, a_k) = q(x)$ where both
$p$ and $q$ are univariate polynomials that depend on $k$ parameters.
Explanation
===========
The result of this function is a dictionary with symbolic values of those
parameters with respect to coefficients in $q$.
... | + 1, i):
content -= matrix[k, j]*solutions[syms[j]]
# run back-substitution for parameters
for j in range(i, m):
content -= matrix[k, j]*syms[j]
if do_simplify:
solutions[syms[k]] = simplify(content)
else:
... | 120 | 120 | 400 | 18 | 101 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | solve_undetermined_coeffs | solve_undetermined_coeffs | 2,484 | 2,528 | 2,484 | 2,484 | 751b1caafc65d28b292f6a3cf41f8fececcdc4eb | bigcode/the-stack | train |
32fdac244ff7cc6554a05dd5 | train | function | def _tsolve(eq, sym, **flags):
"""
Helper for ``_solve`` that solves a transcendental equation with respect
to the given symbol. Various equations containing powers and logarithms,
can be solved.
There is currently no guarantee that all solutions will be returned or
that a real solution will be... | def _tsolve(eq, sym, **flags):
| """
Helper for ``_solve`` that solves a transcendental equation with respect
to the given symbol. Various equations containing powers and logarithms,
can be solved.
There is currently no guarantee that all solutions will be returned or
that a real solution will be favored over a complex one.
... | that either
there are lots of zeros or the size of the matrix
is small.
"""
from sympy.matrices import zeros
if not all(i.is_Number for i in M):
if not any(i.is_Number for i in M):
det = lambda _: det_perm(_)
else:
det = lambda _: det_minor(_)
else:
... | 256 | 256 | 2,305 | 11 | 245 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | _tsolve | _tsolve | 2,685 | 2,924 | 2,685 | 2,685 | c9fc08b09fb295599fddf540f40293fa42eae251 | bigcode/the-stack | train |
4a63a929d893d8f1bff6b5de | train | function | def det_minor(M):
"""
Return the ``det(M)`` computed from minors without
introducing new nesting in products.
See Also
========
det_perm
det_quick
"""
n = M.rows
if n == 2:
return M[0, 0]*M[1, 1] - M[1, 0]*M[0, 1]
else:
return sum([(1, -1)[i % 2]*Add(*[M[0,... | def det_minor(M):
| """
Return the ``det(M)`` computed from minors without
introducing new nesting in products.
See Also
========
det_perm
det_quick
"""
n = M.rows
if n == 2:
return M[0, 0]*M[1, 1] - M[1, 0]*M[0, 1]
else:
return sum([(1, -1)[i % 2]*Add(*[M[0, i]*d for d in
... | :
fac.append(list_[idx + j])
idx += n
term = Mul(*fac) # disaster with unevaluated Mul -- takes forever for n=7
args.append(term if s else -term)
s = not s
return Add(*args)
def det_minor(M):
| 64 | 64 | 155 | 5 | 59 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | det_minor | det_minor | 2,607 | 2,625 | 2,607 | 2,607 | 36f7cb644701558b628112bd3730198428a83301 | bigcode/the-stack | train |
20291a79c54cd2587578297d | train | function | def _simple_dens(f, symbols):
# when checking if a denominator is zero, we can just check the
# base of powers with nonzero exponents since if the base is zero
# the power will be zero, too. To keep it simple and fast, we
# limit simplification to exponents that are Numbers
dens = set()
for d in... | def _simple_dens(f, symbols):
# when checking if a denominator is zero, we can just check the
# base of powers with nonzero exponents since if the base is zero
# the power will be zero, too. To keep it simple and fast, we
# limit simplification to exponents that are Numbers
| dens = set()
for d in denoms(f, symbols):
if d.is_Pow and d.exp.is_Number:
if d.exp.is_zero:
continue # foo**0 is never 0
d = d.base
dens.add(d)
return dens
| def _simple_dens(f, symbols):
# when checking if a denominator is zero, we can just check the
# base of powers with nonzero exponents since if the base is zero
# the power will be zero, too. To keep it simple and fast, we
# limit simplification to exponents that are Numbers
| 73 | 64 | 134 | 73 | 0 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | _simple_dens | _simple_dens | 113 | 125 | 113 | 117 | 4c0f86b3c70d05e0f0333b0c49d9d0294fd8ecd0 | bigcode/the-stack | train |
31860c71db37da0400b9e4af | train | function | def _ispow(e):
"""Return True if e is a Pow or is exp."""
return isinstance(e, Expr) and (e.is_Pow or isinstance(e, exp))
| def _ispow(e):
| """Return True if e is a Pow or is exp."""
return isinstance(e, Expr) and (e.is_Pow or isinstance(e, exp))
| ', None)
if isubs is not None:
new_f.append(isubs(swap_sym))
else:
new_f.append(i)
swap_sym = {v: k for k, v in swap_sym.items()}
return new_f, new_symbols, swap_sym
def _ispow(e):
| 64 | 64 | 38 | 6 | 57 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | _ispow | _ispow | 108 | 110 | 108 | 108 | efb3132a336f12860c7463e9adeddc07a2e197e9 | bigcode/the-stack | train |
07f7362b671224c9a3cce836 | train | function | def solve(f, *symbols, **flags):
r"""
Algebraically solves equations and systems of equations.
Explanation
===========
Currently supported:
- polynomial
- transcendental
- piecewise combinations of the above
- systems of linear and polynomial equations
- sys... | def solve(f, *symbols, **flags):
| r"""
Algebraically solves equations and systems of equations.
Explanation
===========
Currently supported:
- polynomial
- transcendental
- piecewise combinations of the above
- systems of linear and polynomial equations
- systems containing relational expres... | =True)
True
>>> check_assumptions(-2*x - 5, real=True, positive=True)
False
To check assumptions of *expr* against another variable or expression,
pass the expression or variable as ``against``.
>>> check_assumptions(2*x + 1, x)
True
``None`` is returned if ``c... | 256 | 256 | 8,452 | 10 | 246 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | solve | solve | 470 | 1,395 | 470 | 470 | 9c889cf716f21060f505255d41264ed49ca21698 | bigcode/the-stack | train |
f58666f78faa7d00fb18a180 | train | function | def checksol(f, symbol, sol=None, **flags):
"""
Checks whether sol is a solution of equation f == 0.
Explanation
===========
Input can be either a single symbol and corresponding value
or a dictionary of symbols and values. When given as a dictionary
and flag ``simplify=True``, the values ... | def checksol(f, symbol, sol=None, **flags):
| """
Checks whether sol is a solution of equation f == 0.
Explanation
===========
Input can be either a single symbol and corresponding value
or a dictionary of symbols and values. When given as a dictionary
and flag ``simplify=True``, the values in the dictionary will be
simplified. *f... | y, z
>>> from sympy import sqrt
>>> denoms(x/y)
{y}
>>> denoms(x/(y*z))
{y, z}
>>> denoms(3/x + y/z)
{x, z}
>>> denoms(x/2 + y/z)
{2, z}
If *symbols* are provided then only denominators containing
those symbols will be returned:
>>> denoms(1/x + 1/y + 1/z, y, z)
... | 256 | 256 | 1,521 | 13 | 243 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | checksol | checksol | 182 | 371 | 182 | 182 | 7dffe35f2d72f2cc40abced5ce6e126d5438cd62 | bigcode/the-stack | train |
f297f8a4d71dc357be87b5fe | train | function | def _invert(eq, *symbols, **kwargs):
"""
Return tuple (i, d) where ``i`` is independent of *symbols* and ``d``
contains symbols.
Explanation
===========
``i`` and ``d`` are obtained after recursively using algebraic inversion
until an uninvertible ``d`` remains. If there are no free symbol... | def _invert(eq, *symbols, **kwargs):
| """
Return tuple (i, d) where ``i`` is independent of *symbols* and ``d``
contains symbols.
Explanation
===========
``i`` and ``d`` are obtained after recursively using algebraic inversion
until an uninvertible ``d`` remains. If there are no free symbols then
``d`` will be zero. Some (... |
# the function is better behaved when the denominator is present
# e.g., issue 11768
f = lambdify(fargs, f, modules)
x = sympify(findroot(f, x0, **kwargs))
if as_dict:
return [{fargs: x}]
return x
if len(fargs) > f.cols:
raise NotImplementedErro... | 256 | 256 | 1,646 | 11 | 245 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | _invert | _invert | 3,133 | 3,320 | 3,133 | 3,133 | b95fe4987eccb2bc3691ef87f00d1af5a671bd4a | bigcode/the-stack | train |
ed3348a5a723d3c58378223c | train | function | def det_perm(M):
"""
Return the determinant of *M* by using permutations to select factors.
Explanation
===========
For sizes larger than 8 the number of permutations becomes prohibitively
large, or if there are no symbols in the matrix, it is better to use the
standard determinant routine... | def det_perm(M):
| """
Return the determinant of *M* by using permutations to select factors.
Explanation
===========
For sizes larger than 8 the number of permutations becomes prohibitively
large, or if there are no symbols in the matrix, it is better to use the
standard determinant routines (e.g., ``M.det(... | [:matrix.rows, :matrix.rows]
b = matrix[:, matrix.cols - 1:]
soln = A.LUsolve(b)
solutions = {}
for i in range(soln.rows):
solutions[syms[i]] = soln[i, 0]
return solutions
def det_perm(M):
| 66 | 66 | 222 | 5 | 60 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | det_perm | det_perm | 2,571 | 2,604 | 2,571 | 2,571 | 75224b26f50c1a6739eb1f2f16b94213bc3ea619 | bigcode/the-stack | train |
0c4c315fe2c94cd420ee025d | train | function | def inv_quick(M):
"""Return the inverse of ``M``, assuming that either
there are lots of zeros or the size of the matrix
is small.
"""
from sympy.matrices import zeros
if not all(i.is_Number for i in M):
if not any(i.is_Number for i in M):
det = lambda _: det_perm(_)
... | def inv_quick(M):
| """Return the inverse of ``M``, assuming that either
there are lots of zeros or the size of the matrix
is small.
"""
from sympy.matrices import zeros
if not all(i.is_Number for i in M):
if not any(i.is_Number for i in M):
det = lambda _: det_perm(_)
else:
... | if any(i.has(Symbol) for i in M):
if M.rows < 8 and all(i.has(Symbol) for i in M):
return det_perm(M)
return det_minor(M)
else:
return M.det(method=method) if method else M.det()
def inv_quick(M):
| 64 | 64 | 207 | 6 | 58 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | inv_quick | inv_quick | 2,650 | 2,675 | 2,650 | 2,650 | 482644302b1728151c4a701232d05eab757f838c | bigcode/the-stack | train |
eeea9301da7bcf90c2dd8b44 | train | function | def solve_linear_system_LU(matrix, syms):
"""
Solves the augmented matrix system using ``LUsolve`` and returns a
dictionary in which solutions are keyed to the symbols of *syms* as ordered.
Explanation
===========
The matrix must be invertible.
Examples
========
>>> from sympy im... | def solve_linear_system_LU(matrix, syms):
| """
Solves the augmented matrix system using ``LUsolve`` and returns a
dictionary in which solutions are keyed to the symbols of *syms* as ordered.
Explanation
===========
The matrix must be invertible.
Examples
========
>>> from sympy import Matrix
>>> from sympy.abc import ... | collect(equ.expand(), sym, evaluate=False).values())
if not any(equ.has(sym) for equ in system):
# consecutive powers in the input expressions have
# been successfully collected, so solve remaining
# system using Gaussian elimination algorithm
return solve(system, *coeffs, **flags)
... | 88 | 88 | 294 | 11 | 76 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | solve_linear_system_LU | solve_linear_system_LU | 2,531 | 2,568 | 2,531 | 2,531 | 8b908d3f612aa48f22e927b7011f390f1a2ab5e8 | bigcode/the-stack | train |
f1e66a0075c486336000726c | train | function | def recast_to_symbols(eqs, symbols):
"""
Return (e, s, d) where e and s are versions of *eqs* and
*symbols* in which any non-Symbol objects in *symbols* have
been replaced with generic Dummy symbols and d is a dictionary
that can be used to restore the original expressions.
Examples
=======... | def recast_to_symbols(eqs, symbols):
| """
Return (e, s, d) where e and s are versions of *eqs* and
*symbols* in which any non-Symbol objects in *symbols* have
been replaced with generic Dummy symbols and d is a dictionary
that can be used to restore the original expressions.
Examples
========
>>> from sympy.solvers.solvers... | ary.piecewise import piecewise_fold, Piecewise
from sympy.utilities.lambdify import lambdify
from sympy.utilities.misc import filldedent
from sympy.utilities.iterables import uniq, generate_bell, flatten
from sympy.utilities.decorator import conserve_mpmath_dps
from mpmath import findroot
from sympy.solvers.polysys ... | 126 | 126 | 422 | 10 | 115 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | recast_to_symbols | recast_to_symbols | 65 | 105 | 65 | 65 | 7b45ae9c0a1de4afa81103578d6a335e3580ed0c | bigcode/the-stack | train |
0a20d316724de0d4f7622de3 | train | function | def _solve_system(exprs, symbols, **flags):
if not exprs:
return []
polys = []
dens = set()
failed = []
result = False
linear = False
manual = flags.get('manual', False)
checkdens = check = flags.get('check', True)
for j, g in enumerate(exprs):
dens.update(_simple_d... | def _solve_system(exprs, symbols, **flags):
| if not exprs:
return []
polys = []
dens = set()
failed = []
result = False
linear = False
manual = flags.get('manual', False)
checkdens = check = flags.get('check', True)
for j, g in enumerate(exprs):
dens.update(_simple_dens(g, symbols))
i, d = _invert(g, *... | (f_num, symbol, **flags)
if soln is not None:
result = soln
except PolynomialError:
pass
# ----------- end of fallback ----------------------------
if result is False:
raise NotImplementedError('\n'.join([msg, not_impl_msg % f]))
if flags.get('simpli... | 256 | 256 | 1,547 | 12 | 243 | iamabhishek0/sympy | sympy/solvers/solvers.py | Python | _solve_system | _solve_system | 1,810 | 2,008 | 1,810 | 1,810 | 9736281115ce527a5898c1c3a065bb7990afa6ad | bigcode/the-stack | train |
266989c18fc9ac03f624d5e6 | train | function | def create_test_data():
train_data_path = os.path.join(data_path, 'test')
images = os.listdir(train_data_path)
total = len(images)
imgs = np.ndarray((total, image_rows, image_cols), dtype=np.uint8)
imgs_id = np.ndarray((total, ), dtype=np.int32)
i = 0
print('-'*30)
print('Creating test... | def create_test_data():
| train_data_path = os.path.join(data_path, 'test')
images = os.listdir(train_data_path)
total = len(images)
imgs = np.ndarray((total, image_rows, image_cols), dtype=np.uint8)
imgs_id = np.ndarray((total, ), dtype=np.int32)
i = 0
print('-'*30)
print('Creating test images...')
print('... | )
np.save('imgs_mask_train.npy', imgs_mask)
print('Saving to .npy files done.')
def load_train_data():
imgs_train = np.load('imgs_train.npy')
imgs_mask_train = np.load('imgs_mask_train.npy')
return imgs_train, imgs_mask_train
def create_test_data():
| 68 | 68 | 227 | 5 | 62 | zhangdidemi/multi-gpu | data.py | Python | create_test_data | create_test_data | 55 | 83 | 55 | 55 | ab6c0734ae4b7ade9b2b5d2d5899c5aa4f0f755a | bigcode/the-stack | train |
3e8c19020384a37733ff6410 | train | function | def create_train_data():
train_data_path = os.path.join(data_path, 'train')
images = os.listdir(train_data_path)
total = len(images) // 2
imgs = np.ndarray((total, image_rows, image_cols), dtype=np.uint8)
imgs_mask = np.ndarray((total, image_rows, image_cols), dtype=np.uint8)
i = 0
print('... | def create_train_data():
| train_data_path = os.path.join(data_path, 'train')
images = os.listdir(train_data_path)
total = len(images) // 2
imgs = np.ndarray((total, image_rows, image_cols), dtype=np.uint8)
imgs_mask = np.ndarray((total, image_rows, image_cols), dtype=np.uint8)
i = 0
print('-'*30)
print('Creatin... | from __future__ import print_function
import os
import numpy as np
from skimage.io import imsave, imread
data_path = 'raw/'
image_rows = 420
image_cols = 580
def create_train_data():
| 51 | 85 | 286 | 5 | 45 | zhangdidemi/multi-gpu | data.py | Python | create_train_data | create_train_data | 14 | 46 | 14 | 14 | 52cb86618db1f060c0ff11ed9dd97f58233ddb30 | bigcode/the-stack | train |
7ab4981516c46262d54ffb54 | train | function | def load_test_data():
imgs_test = np.load('imgs_test.npy')
imgs_id = np.load('imgs_id_test.npy')
return imgs_test, imgs_id
| def load_test_data():
| imgs_test = np.load('imgs_test.npy')
imgs_id = np.load('imgs_id_test.npy')
return imgs_test, imgs_id
| : {0}/{1} images'.format(i, total))
i += 1
print('Loading done.')
np.save('imgs_test.npy', imgs)
np.save('imgs_id_test.npy', imgs_id)
print('Saving to .npy files done.')
def load_test_data():
| 63 | 64 | 36 | 5 | 58 | zhangdidemi/multi-gpu | data.py | Python | load_test_data | load_test_data | 86 | 89 | 86 | 86 | fb17c39e3a6138552eddc1dad7e04f615af20b1e | bigcode/the-stack | train |
30dc4b092236a69eee88b13e | train | function | def load_train_data():
imgs_train = np.load('imgs_train.npy')
imgs_mask_train = np.load('imgs_mask_train.npy')
return imgs_train, imgs_mask_train
| def load_train_data():
| imgs_train = np.load('imgs_train.npy')
imgs_mask_train = np.load('imgs_mask_train.npy')
return imgs_train, imgs_mask_train
| : {0}/{1} images'.format(i, total))
i += 1
print('Loading done.')
np.save('imgs_train.npy', imgs)
np.save('imgs_mask_train.npy', imgs_mask)
print('Saving to .npy files done.')
def load_train_data():
| 63 | 64 | 38 | 5 | 58 | zhangdidemi/multi-gpu | data.py | Python | load_train_data | load_train_data | 49 | 52 | 49 | 49 | 39c5eaa17f18261d968bb6df02640fd12636ae92 | bigcode/the-stack | train |
df5c7b242d75ce851e8b80c9 | train | class | class AboutMethods(Koan):
def test_calling_a_global_function(self):
self.assertEqual(5, my_global_function(2,3))
# NOTE: Wrong number of arguments is not a SYNTAX error, but a
# runtime error.
def test_calling_functions_with_wrong_number_of_arguments(self):
try:
my_global_fu... | class AboutMethods(Koan):
| def test_calling_a_global_function(self):
self.assertEqual(5, my_global_function(2,3))
# NOTE: Wrong number of arguments is not a SYNTAX error, but a
# runtime error.
def test_calling_functions_with_wrong_number_of_arguments(self):
try:
my_global_function()
except Ty... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Partially based on AboutMethods in the Ruby Koans
#
from runner.koan import *
def my_global_function(a,b):
return a + b
class AboutMethods(Koan):
| 55 | 256 | 1,047 | 6 | 48 | mwawrzyniuk/python_koans | python3/koans/about_methods.py | Python | AboutMethods | AboutMethods | 13 | 160 | 13 | 13 | f1f47013bcdce230a7a79b124ed1dae94e1fa3f6 | bigcode/the-stack | train |
8cad71a8b66065810945e02a | train | function | def my_global_function(a,b):
return a + b
| def my_global_function(a,b):
| return a + b
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Partially based on AboutMethods in the Ruby Koans
#
from runner.koan import *
def my_global_function(a,b):
| 43 | 64 | 13 | 7 | 36 | mwawrzyniuk/python_koans | python3/koans/about_methods.py | Python | my_global_function | my_global_function | 10 | 11 | 10 | 10 | 5e23eaaf4d1fa3f4002ab8189412a3626fd70aa2 | bigcode/the-stack | train |
b0f5ac10c51b272a75f4c6d3 | train | function | def test(
model: LightningModule, data_module: LightningDataModule, seed: Optional[int] = None, gpu: Optional[int] = None
):
seed_everything(seed)
dgl.seed(seed)
trainer = Trainer(gpus=gpu)
trainer.test(model, datamodule=data_module)
| def test(
model: LightningModule, data_module: LightningDataModule, seed: Optional[int] = None, gpu: Optional[int] = None
):
| seed_everything(seed)
dgl.seed(seed)
trainer = Trainer(gpus=gpu)
trainer.test(model, datamodule=data_module)
| from typing import Optional
import dgl
from pytorch_lightning import LightningModule, LightningDataModule, seed_everything, Trainer
def test(
model: LightningModule, data_module: LightningDataModule, seed: Optional[int] = None, gpu: Optional[int] = None
):
| 61 | 64 | 65 | 33 | 27 | SpirinEgor/embeddings-for-trees | embeddings_for_trees/utils/test.py | Python | test | test | 7 | 13 | 7 | 9 | 2243ffcb045829f1e072e5472f0c1ba4dbf4b52a | bigcode/the-stack | train |
728c9b57b1d9bd96f86092b7 | train | class | class TestDeprecatedFilePage(DeprecationTestCase):
"""Test deprecated parts of FilePage."""
family = 'commons'
code = 'commons'
cached = True
def test_getFirstUploader(self):
"""Test getFirstUploader."""
page = pywikibot.FilePage(self.site, 'File:Albert Einstein.jpg')
fir... | class TestDeprecatedFilePage(DeprecationTestCase):
| """Test deprecated parts of FilePage."""
family = 'commons'
code = 'commons'
cached = True
def test_getFirstUploader(self):
"""Test getFirstUploader."""
page = pywikibot.FilePage(self.site, 'File:Albert Einstein.jpg')
first = page.getFirstUploader()
self.assertOneD... | = self.get_site()
image = pywikibot.FilePage(site, u'File:Test with no image')
self.assertTrue(image.exists())
with self.assertRaises(pywikibot.PageRelatedError):
image = image.latest_file_info
class TestDeprecatedFilePage(DeprecationTestCase):
| 66 | 66 | 221 | 12 | 53 | jkjkjkjkjk/pywikibot-core | tests/file_tests.py | Python | TestDeprecatedFilePage | TestDeprecatedFilePage | 155 | 180 | 155 | 156 | e83501b08e56ce0476f57eee0ea01d801cf5bfe3 | bigcode/the-stack | train |
c3d526a6417f55ce311bccc1 | train | class | class TestShareFiles(TestCase):
"""Test methods fileIsShared, exists and fileUrl with shared files."""
sites = {
'enwiki': {
'family': 'wikipedia',
'code': 'en',
},
'itwiki': {
'family': 'wikipedia',
'code': 'it',
},
'test... | class TestShareFiles(TestCase):
| """Test methods fileIsShared, exists and fileUrl with shared files."""
sites = {
'enwiki': {
'family': 'wikipedia',
'code': 'en',
},
'itwiki': {
'family': 'wikipedia',
'code': 'it',
},
'testwiki': {
'family': 'w... | # -*- coding: utf-8 -*-
"""FilePage tests."""
#
# (C) Pywikibot team, 2014
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id: de459bc624b43db12bb224f6a3b0932debfd27f6 $'
import pywikibot
from pywikibot.tools import UnicodeType as unicod... | 124 | 245 | 819 | 7 | 116 | jkjkjkjkjk/pywikibot-core | tests/file_tests.py | Python | TestShareFiles | TestShareFiles | 19 | 121 | 19 | 20 | c335e869b6b192f35254b9c6d5538fdce5350f49 | bigcode/the-stack | train |
c75ba5e7caf2634f5d17022c | train | class | class TestFilePage(TestCase):
"""Test FilePage.latest_revision_info.
These tests cover exceptions for all properties and methods
in FilePage that rely on site.loadimageinfo.
"""
family = 'wikipedia'
code = 'test'
cached = True
def test_file_info_with_no_page(self):
"""FileP... | class TestFilePage(TestCase):
| """Test FilePage.latest_revision_info.
These tests cover exceptions for all properties and methods
in FilePage that rely on site.loadimageinfo.
"""
family = 'wikipedia'
code = 'test'
cached = True
def test_file_info_with_no_page(self):
"""FilePage:latest_file_info raises NoP... | .assertTrue(testwp_file.fileUrl())
self.assertTrue(testwp_file.exists())
self.assertTrue(testwp_file.fileIsShared())
commons_file = pywikibot.FilePage(commons, title)
self.assertEqual(testwp_file.fileUrl(),
commons_file.fileUrl())
class TestFilePage(TestCase):
| 66 | 66 | 223 | 7 | 59 | jkjkjkjkjk/pywikibot-core | tests/file_tests.py | Python | TestFilePage | TestFilePage | 124 | 152 | 124 | 125 | 473171d5fa668bcaa19b3cd8d4f35847154d24d2 | bigcode/the-stack | train |
f39b8f8b98290ff3030aa1a2 | train | class | class SideEffectGuardsTest(converter_testing.TestCase):
def test_side_effect_on_return_only_variable(self):
def test_fn(a):
tf.assign(a, a + 1)
return a
node, ctx = self.prepare(test_fn, {})
node = side_effect_guards.transform(node, ctx)
self.assertEqual(len(node.body[0].body), 1)
... | class SideEffectGuardsTest(converter_testing.TestCase):
| def test_side_effect_on_return_only_variable(self):
def test_fn(a):
tf.assign(a, a + 1)
return a
node, ctx = self.prepare(test_fn, {})
node = side_effect_guards.transform(node, ctx)
self.assertEqual(len(node.body[0].body), 1)
with self.compiled(node, {}, state_ops.assign) as result... | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | 256 | 256 | 1,013 | 12 | 244 | elielhojman/tensorflow | tensorflow/contrib/autograph/converters/side_effect_guards_test.py | Python | SideEffectGuardsTest | SideEffectGuardsTest | 35 | 159 | 35 | 36 | 53be792f12f389022ac75463c233f4dfe36de7e9 | bigcode/the-stack | train |
ce1fcafd778314fc87feca11 | train | function | def time_it(dataset, username):
start = time.perf_counter_ns()
reader = Reader(
inner_reader=DiskReader,
dataset=dataset,
raw_path=True,
filters=("user_name", "==", username),
)
res = [r for r in reader]
# print(res)
return (time.perf_counter_ns() - start) / 1e9
| def time_it(dataset, username):
| start = time.perf_counter_ns()
reader = Reader(
inner_reader=DiskReader,
dataset=dataset,
raw_path=True,
filters=("user_name", "==", username),
)
res = [r for r in reader]
# print(res)
return (time.perf_counter_ns() - start) / 1e9
|
yes | no | 0.006 <- over 50x faster when no match
no | yes | 0.357
no | no | 0.332
-------------------------------
"""
import time
def time_it(dataset, username):
| 64 | 64 | 84 | 7 | 56 | mabel-dev/mabel | tests/performance/index_performance.py | Python | time_it | time_it | 16 | 26 | 16 | 16 | bcf1eecf5bb93c87d9ef576c4944b2d061711e59 | bigcode/the-stack | train |
1b4c33c8365ed41db757a12e | train | function | def wlan_interface_state():
root = lxml.html.parse(url).getroot()
form_list = root.cssselect("form[name='wlan_intf']")
form1 = form_list[0]
return form1.fields['56']=='1'
| def wlan_interface_state():
| root = lxml.html.parse(url).getroot()
form_list = root.cssselect("form[name='wlan_intf']")
form1 = form_list[0]
return form1.fields['56']=='1'
| if(enableWLAN):
form1.fields[b'56']=b'1' #enable WLAN
else:
form1.fields[b'56']=b'0' #disable WLAN
#form1.form_values()
lxml.html.submit_form(form1)
def wlan_interface_state():
| 64 | 64 | 52 | 5 | 59 | prisme60/horaire | enable_wlan.py | Python | wlan_interface_state | wlan_interface_state | 23 | 27 | 23 | 23 | 8e906999d70ecb8a02fda7077e2f1e42cf2a3bf1 | bigcode/the-stack | train |
bd1268ab7620a4d2a4e27ed5 | train | function | def wlan_interface(enableWLAN):
root = lxml.html.parse(url).getroot()
#print lxml.etree.tostring(root)
form_list = root.cssselect("form[name='wlan_intf']")
form1 = form_list[0]
#form1.form_values()
form1.fields[b'0']=b'10'
if(enableWLAN):
form1.fields[b'56']=b'1' #enable WLAN
else:
form1.fields... | def wlan_interface(enableWLAN):
| root = lxml.html.parse(url).getroot()
#print lxml.etree.tostring(root)
form_list = root.cssselect("form[name='wlan_intf']")
form1 = form_list[0]
#form1.form_values()
form1.fields[b'0']=b'10'
if(enableWLAN):
form1.fields[b'56']=b'1' #enable WLAN
else:
form1.fields[b'56']=b'0' #disable WLAN
#f... | import sys
import lxml.etree
import lxml.html
url = "http://192.168.1.254/cgi/b/_wli_/cfg/?be=0&l0=4&l1=2&name=WLAN:%20montjoie"
def wlan_interface(enableWLAN):
| 64 | 64 | 133 | 7 | 57 | prisme60/horaire | enable_wlan.py | Python | wlan_interface | wlan_interface | 9 | 21 | 9 | 9 | 140d2990748d9fb15515a61ffc4880370e86392a | bigcode/the-stack | train |
fe78a3f2c7a6fbe6e9ff64d4 | train | function | def hex_to_int(hex_string):
return int(hex_string, 16)
| def hex_to_int(hex_string):
| return int(hex_string, 16)
| : new valid competitors set
}
},
rwd: dict of reward transactions, rewarding self and rewarding previous reference block creators
no_txs: number of transactions (sum of number of asgn_stmts, ttx, trr, trx]
"""
def hex_to_int(hex_string):
| 63 | 64 | 16 | 7 | 56 | snwokenk/Orses_Core | Orses_Competitor_Core/Block_Data_Aggregator.py | Python | hex_to_int | hex_to_int | 68 | 69 | 68 | 68 | bdc4c7f08230a5a408a662e8a1eb79f4e7ac95d3 | bigcode/the-stack | train |
dae765f035347fc3217db6a4 | train | class | class RegularBlockHeader(BaseBlockHeader):
def __init__(self):
super().__init__()
self.p_h = None # previous hashes of past 2 blocks
self.no_txs = 0 # number of transactions misc messages and txs is given
self.no_asgn = 0 # the sum of assignment statements represented by wallet h... | class RegularBlockHeader(BaseBlockHeader):
| def __init__(self):
super().__init__()
self.p_h = None # previous hashes of past 2 blocks
self.no_txs = 0 # number of transactions misc messages and txs is given
self.no_asgn = 0 # the sum of assignment statements represented by wallet hash states saved
def set_previous_2_has... | _char = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
random.shuffle(hex_char) # shuffles hex_char in place
hex_char = {x+1: y for x, y in enumerate(hex_char)} # assign value to shuffled hex character
self.shv = hex_char
class RegularBlockHeader(B... | 108 | 108 | 363 | 8 | 99 | snwokenk/Orses_Core | Orses_Competitor_Core/Block_Data_Aggregator.py | Python | RegularBlockHeader | RegularBlockHeader | 259 | 295 | 259 | 260 | 138e75a80d615a4501ea3a1d3e78f91abf791334 | bigcode/the-stack | train |
560257c8a193f2e38898c083 | train | class | class GenesisBlock(BaseBlock):
def __init__(self):
super().__init__()
self.tats = None # token association transaction
self.sig = None # b85 string
self.vph = None # validity protocol
self.pubkey = None # pubkey dict with x and y
self.bcws = None # genesis blockc... | class GenesisBlock(BaseBlock):
| def __init__(self):
super().__init__()
self.tats = None # token association transaction
self.sig = None # b85 string
self.vph = None # validity protocol
self.pubkey = None # pubkey dict with x and y
self.bcws = None # genesis blockchain connected wallets
def... | _wallet_id):
self.p_s = primary_sig_wallet_id
def set_maximum_probability_target(self, prob_of_5_runnerups='P6+0'):
self.mpt = prob_of_5_runnerups # for Genesis Block
# **** Class Representing Blocks **** #
class BaseBlock:
def __init__(self):
self.bh = None # block header
... | 112 | 113 | 377 | 6 | 106 | snwokenk/Orses_Core | Orses_Competitor_Core/Block_Data_Aggregator.py | Python | GenesisBlock | GenesisBlock | 364 | 422 | 364 | 364 | 9d55222c1fb0cebade55533eb459794b4c737e3b | bigcode/the-stack | train |
4b209d7e736f4af845d1ccd3 | train | class | class BlockOneHeader(BaseBlockHeader):
def __init__(self):
super().__init__()
self.no_txs = 0 # number of transactions misc messages and txs is given
self.no_asgns = 0 # the sum of assignment statements represented by wallet hash states saved
def set_header_before_compete(
... | class BlockOneHeader(BaseBlockHeader):
| def __init__(self):
super().__init__()
self.no_txs = 0 # number of transactions misc messages and txs is given
self.no_asgns = 0 # the sum of assignment statements represented by wallet hash states saved
def set_header_before_compete(
self,
primary_sig_wallet_i... | .set_previous_2_hashes(list_of_prev_2_hashes=list_of_prev_2_hashes)
self.set_prev_hash(prev_block_hash=prev_hash)
def set_no_txs(self, no_txs: int):
self.no_txs = no_txs
def set_no_asgns(self, no_asgns: int):
self.no_asgns = no_asgns
class BlockOneHeader(BaseBlockHeader):
| 93 | 93 | 310 | 8 | 84 | snwokenk/Orses_Core | Orses_Competitor_Core/Block_Data_Aggregator.py | Python | BlockOneHeader | BlockOneHeader | 298 | 329 | 298 | 298 | ed7b32c8d43db74cd4af93f4a2b0407d5803ec36 | bigcode/the-stack | train |
77db9c9b984dd7bbbb84eac1 | train | class | class BlockOne(NonGenesisBlock):
pass
| class BlockOne(NonGenesisBlock):
| pass
| ty(combined_list=combined_list)
self.set_secondary_signatories(list_of_secondary_signatories=secondary_signatories)
self.set_wsh(wsh=wsh)
def set_after_competing(self, block_header):
self.set_block_header(block_header=block_header)
class BlockOne(NonGenesisBlock):
| 64 | 64 | 11 | 8 | 56 | snwokenk/Orses_Core | Orses_Competitor_Core/Block_Data_Aggregator.py | Python | BlockOne | BlockOne | 454 | 455 | 454 | 454 | 1c9718fb23ff76dc83cfb3255fa82c6008413275 | bigcode/the-stack | train |
e8660e218c7f3f35ae5e4bb9 | train | class | class GenesisBlockHeader(BaseBlockHeader):
def set_header_before_compete(self, primary_sig_wallet_id, merkle_root):
self.set_block_no()
self.set_primary_signatory(primary_sig_wallet_id=primary_sig_wallet_id)
self.set_shuffled_hex_values()
self.set_maximum_probability_target()
... | class GenesisBlockHeader(BaseBlockHeader):
| def set_header_before_compete(self, primary_sig_wallet_id, merkle_root):
self.set_block_no()
self.set_primary_signatory(primary_sig_wallet_id=primary_sig_wallet_id)
self.set_shuffled_hex_values()
self.set_maximum_probability_target()
self.set_merkle_root(merkle_root=merkle_ro... | s: int):
self.no_asgns = no_asgns
def set_maximum_probability_target(self, probability_of_5_runnerups): # just a string "p7+0"
self.mpt = probability_of_5_runnerups
class GenesisBlockHeader(BaseBlockHeader):
| 64 | 64 | 165 | 9 | 54 | snwokenk/Orses_Core | Orses_Competitor_Core/Block_Data_Aggregator.py | Python | GenesisBlockHeader | GenesisBlockHeader | 332 | 349 | 332 | 334 | e560c614c74058adb6f21e488889d7c8807c7beb | bigcode/the-stack | train |
ede856e29ecb3c4c5d649fa0 | train | class | class BaseBlock:
def __init__(self):
self.bh = None # block header
self.s_s = None # secondary signatories
def get_block(self):
return self.__dict__
| class BaseBlock:
| def __init__(self):
self.bh = None # block header
self.s_s = None # secondary signatories
def get_block(self):
return self.__dict__
| _wallet_id):
self.p_s = primary_sig_wallet_id
def set_maximum_probability_target(self, prob_of_5_runnerups='P6+0'):
self.mpt = prob_of_5_runnerups # for Genesis Block
# **** Class Representing Blocks **** #
class BaseBlock:
| 63 | 64 | 46 | 4 | 59 | snwokenk/Orses_Core | Orses_Competitor_Core/Block_Data_Aggregator.py | Python | BaseBlock | BaseBlock | 355 | 361 | 355 | 355 | f548a791307899dcb931c6d039e61bee4ed1dacb | bigcode/the-stack | train |
ab7d49531f897ba9e248b11c | train | class | class BaseBlockHeader:
def __init__(self):
self.block_no = None # hex number without the 0x
self.block_hash = None # valid hash of block
self.prev_hash = None # hash of previous block
self.mrh = None # Merkle root
self.n = None # nonce
self.x_n = None # extra non... | class BaseBlockHeader:
| def __init__(self):
self.block_no = None # hex number without the 0x
self.block_hash = None # valid hash of block
self.prev_hash = None # hash of previous block
self.mrh = None # Merkle root
self.n = None # nonce
self.x_n = None # extra nonce
self.p_s = N... | 1 standard deviation of the average of probabilities of
primary and secondary signatories of the last 3 blocks or 3 competitions. The maximum
probability is used to determining number of leading prime characters and additional characters
hex_shuf: ... | 255 | 256 | 1,776 | 5 | 250 | snwokenk/Orses_Core | Orses_Competitor_Core/Block_Data_Aggregator.py | Python | BaseBlockHeader | BaseBlockHeader | 74 | 256 | 74 | 74 | 1c803c0b78ef10767718fc5e304b9363b6d79edf | bigcode/the-stack | train |
eede0672decdf25324c5e36d | train | class | class RegularBlock(NonGenesisBlock):
pass
| class RegularBlock(NonGenesisBlock):
| pass
| _secondary_signatories(list_of_secondary_signatories=secondary_signatories)
self.set_wsh(wsh=wsh)
def set_after_competing(self, block_header):
self.set_block_header(block_header=block_header)
class BlockOne(NonGenesisBlock):
pass
class RegularBlock(NonGenesisBlock):
| 64 | 64 | 11 | 8 | 55 | snwokenk/Orses_Core | Orses_Competitor_Core/Block_Data_Aggregator.py | Python | RegularBlock | RegularBlock | 458 | 459 | 458 | 458 | 8dacfad8bc324834bcaa26e913c7364c7ebeff20 | bigcode/the-stack | train |
41b2b4aeaf622898ea7381ae | train | class | class NonGenesisBlock(BaseBlock):
def __init__(self):
super().__init__()
self.block_activity = None
self.wsh = None
def set_block_header(self, block_header):
self.bh = block_header
def set_block_activty(self, combined_list):
self.block_activity = combined_list
... | class NonGenesisBlock(BaseBlock):
| def __init__(self):
super().__init__()
self.block_activity = None
self.wsh = None
def set_block_header(self, block_header):
self.bh = block_header
def set_block_activty(self, combined_list):
self.block_activity = combined_list
def set_secondary_signatories(sel... | _secondary_signatories(self, list_of_secondary_signatories):
self.s_s = list_of_secondary_signatories
def set_gen_pub_key(self, pubkey_dict):
self.pubkey = pubkey_dict
def set_signature(self, signature):
self.sig = signature
class NonGenesisBlock(BaseBlock):
| 64 | 64 | 195 | 7 | 56 | snwokenk/Orses_Core | Orses_Competitor_Core/Block_Data_Aggregator.py | Python | NonGenesisBlock | NonGenesisBlock | 425 | 451 | 425 | 426 | 46e7638b60ef7df050c3cf57a6510a8457ba57ad | bigcode/the-stack | train |
d4fdc1156f9f6364f26397e6 | train | function | def get_features(users, devices):
# Get user info
uid = users[(users["_id"] == "5b5b2b94ed261d61ede3d085")].iloc[0]["_id"]
# Get devices info for the user
devIds = devices[(devices["user_id"] == uid)].iloc[:]["device_id"]
# Get gestures
gests = pd.DataFrame()
for devId in devIds.index:
... | def get_features(users, devices):
# Get user info
| uid = users[(users["_id"] == "5b5b2b94ed261d61ede3d085")].iloc[0]["_id"]
# Get devices info for the user
devIds = devices[(devices["user_id"] == uid)].iloc[:]["device_id"]
# Get gestures
gests = pd.DataFrame()
for devId in devIds.index:
gests = gests.append(gestures[(gestures["device_id... | devId])])
gests = gests.reset_index(drop=True)
gestureVisualizer = GV.GesturesVisualizer(gests.loc[0:25], deviceWidth=411, deviceHeight=798)
gestureVisualizer.plot_gestures()
def get_features(users, devices):
# Get user info
| 64 | 64 | 186 | 13 | 51 | AuthEceSoftEng/emb-ntua-workshop | 1_BrainRun/code.py | Python | get_features | get_features | 101 | 117 | 101 | 103 | bc5424eb26ce715a9ab4117bc5cb1db25b918899 | bigcode/the-stack | train |
aec5561812cd19f2fc1c2b99 | train | function | def create_pie_charts(users, devices, games, gestures):
# Percentage of playing time per game type
types = games["game_type"].tolist()
plt.subplot(221).pie(Counter(types).values(), labels=Counter(types).keys(), autopct='%1.1f%%', shadow=True)
# Percentage of swipes and taps
types = gestures["type"... | def create_pie_charts(users, devices, games, gestures):
# Percentage of playing time per game type
| types = games["game_type"].tolist()
plt.subplot(221).pie(Counter(types).values(), labels=Counter(types).keys(), autopct='%1.1f%%', shadow=True)
# Percentage of swipes and taps
types = gestures["type"].tolist()
plt.subplot(222).pie(Counter(types).values(), labels=Counter(types).keys(), autopct='%1.1... | # Print statistics about game types
print("\n", games[["game_type"]].describe())
# Print statistics about gesture types
print("\n", gestures[["type"]].describe())
def create_pie_charts(users, devices, games, gestures):
# Percentage of playing time per game type
| 66 | 66 | 221 | 24 | 42 | AuthEceSoftEng/emb-ntua-workshop | 1_BrainRun/code.py | Python | create_pie_charts | create_pie_charts | 41 | 59 | 41 | 43 | 853c9f91d2b0d8963498ec8453352ba99b1a861f | bigcode/the-stack | train |
5165009ba74997b652f5b529 | train | function | def read_data():
# Read data
users = pd.read_csv("1_BrainRun/data/users.csv", sep=";")
devices = pd.read_csv("1_BrainRun/data/devices.csv", sep=";")
games = pd.read_csv("1_BrainRun/data/games.csv", sep=";")
gestures = pd.read_csv("1_BrainRun/data/gestures.csv", sep=";")
# Transform string repre... | def read_data():
# Read data
| users = pd.read_csv("1_BrainRun/data/users.csv", sep=";")
devices = pd.read_csv("1_BrainRun/data/devices.csv", sep=";")
games = pd.read_csv("1_BrainRun/data/games.csv", sep=";")
gestures = pd.read_csv("1_BrainRun/data/gestures.csv", sep=";")
# Transform string representation of list into a python l... | import json
import numpy as np
import pandas as pd
from collections import Counter
from matplotlib import pyplot as plt
from utilities import GesturesVisualizer as GV
from utilities import FeaturesExtractor as FE
def read_data():
# Read data
| 51 | 64 | 134 | 9 | 41 | AuthEceSoftEng/emb-ntua-workshop | 1_BrainRun/code.py | Python | read_data | read_data | 9 | 19 | 9 | 10 | 3459803155fc4cc625fcb82d7d7782b3df0ba51c | bigcode/the-stack | train |
ba11f3af68d67a26d4d198b4 | train | function | def get_statistics(users, devices, games, gestures):
# Get data statistics
print("\n")
print("Number of users: ", len(users.index))
print("Number of devices: ", len(devices.index))
print("Number of games: ", len(games.index))
print("Number of gestures: ", len(gestures.index))
# Print statis... | def get_statistics(users, devices, games, gestures):
# Get data statistics
| print("\n")
print("Number of users: ", len(users.index))
print("Number of devices: ", len(devices.index))
print("Number of games: ", len(games.index))
print("Number of gestures: ", len(gestures.index))
# Print statistics about age, num_of_devices, num_of_games and num_of_gestures for each user
... | ;")
# Transform string representation of list into a python list
gestures["data"] = gestures["data"].apply(lambda x: json.loads(x.replace("'", "\"")))
return users, devices, games, gestures
def get_statistics(users, devices, games, gestures):
# Get data statistics
| 64 | 64 | 192 | 17 | 46 | AuthEceSoftEng/emb-ntua-workshop | 1_BrainRun/code.py | Python | get_statistics | get_statistics | 21 | 39 | 21 | 22 | d1c5bc15430d89cd5d9fb8a5d3c02267597e5893 | bigcode/the-stack | train |
29cacd622442d60b4a3c7e1b | train | function | def create_boxplot(devices):
devices["os"] = devices.set_index("os").index
devices.boxplot(column=["width", "height"], by="os", rot=45)
plt.show()
| def create_boxplot(devices):
| devices["os"] = devices.set_index("os").index
devices.boxplot(column=["width", "height"], by="os", rot=45)
plt.show()
| set_ylabel("Number of data points")
plt.subplot(212).set_title("Number of data points sampled from each swipe")
plt.subplots_adjust(left = 0.15, top = 0.95, hspace = 0.55)
plt.show()
def create_boxplot(devices):
| 64 | 64 | 44 | 7 | 57 | AuthEceSoftEng/emb-ntua-workshop | 1_BrainRun/code.py | Python | create_boxplot | create_boxplot | 82 | 86 | 82 | 83 | bb7dcfabfbf20f0bf72282d10ebb4caaff9a62e4 | bigcode/the-stack | train |
ad85c034218a64ef01786356 | train | function | def visualize_gestures(users, devices):
uid = users[(users["_id"] == "5b5b2b94ed261d61ede3d085")].iloc[0]["_id"]
devIds = devices[(devices["user_id"] == uid)].iloc[:]["device_id"]
gests = pd.DataFrame()
for devId in devIds.index:
gests = gests.append(gestures[(gestures["device_id"] == devIds.l... | def visualize_gestures(users, devices):
| uid = users[(users["_id"] == "5b5b2b94ed261d61ede3d085")].iloc[0]["_id"]
devIds = devices[(devices["user_id"] == uid)].iloc[:]["device_id"]
gests = pd.DataFrame()
for devId in devIds.index:
gests = gests.append(gestures[(gestures["device_id"] == devIds.loc[devId])])
gests = gests.reset_inde... | space = 0.55)
plt.show()
def create_boxplot(devices):
devices["os"] = devices.set_index("os").index
devices.boxplot(column=["width", "height"], by="os", rot=45)
plt.show()
def visualize_gestures(users, devices):
| 64 | 64 | 154 | 9 | 55 | AuthEceSoftEng/emb-ntua-workshop | 1_BrainRun/code.py | Python | visualize_gestures | visualize_gestures | 88 | 99 | 88 | 89 | fc83d947ca73dda35836b142ca7cbcd666a63594 | bigcode/the-stack | train |
422f985957bc428cb1421036 | train | function | def create_line_charts(users, gestures):
# Plot users experience points
# plt.subplot(211).plot(x=list(np.arange(1, len(users) + 1)), y=list(users["xp"]))
plt.subplot(211).plot(list(np.arange(1, len(users) + 1)), list(users["xp"]), "-")
plt.subplot(211).set_xlabel("Users")
plt.subplot(211).set_ylab... | def create_line_charts(users, gestures):
# Plot users experience points
# plt.subplot(211).plot(x=list(np.arange(1, len(users) + 1)), y=list(users["xp"]))
| plt.subplot(211).plot(list(np.arange(1, len(users) + 1)), list(users["xp"]), "-")
plt.subplot(211).set_xlabel("Users")
plt.subplot(211).set_ylabel("Experience points")
plt.subplot(211).set_title("Experience points per user")
# Plot number of data points sampled from each swipe
swipes = gestures... | pie(Counter(types).values(), labels=Counter(types).keys(), autopct='%1.1f%%', shadow=True)
plt.show()
def create_line_charts(users, gestures):
# Plot users experience points
# plt.subplot(211).plot(x=list(np.arange(1, len(users) + 1)), y=list(users["xp"]))
| 75 | 75 | 252 | 44 | 31 | AuthEceSoftEng/emb-ntua-workshop | 1_BrainRun/code.py | Python | create_line_charts | create_line_charts | 61 | 80 | 61 | 64 | 82d77fe213f80358a335223c930b30a9260976b7 | bigcode/the-stack | train |
168d34341138ab2f911f8a25 | train | class | class Instance(object):
"""Representation of a Cloud Spanner Instance.
We can use a :class:`Instance` to:
* :meth:`reload` itself
* :meth:`create` itself
* :meth:`update` itself
* :meth:`delete` itself
:type instance_id: str
:param instance_id: The ID of the instance.
:type clien... | class Instance(object):
| """Representation of a Cloud Spanner Instance.
We can use a :class:`Instance` to:
* :meth:`reload` itself
* :meth:`create` itself
* :meth:`update` itself
* :meth:`delete` itself
:type instance_id: str
:param instance_id: The ID of the instance.
:type client: :class:`~google.cloud... | ed-imports
_INSTANCE_NAME_RE = re.compile(
r"^projects/(?P<project>[^/]+)/" r"instances/(?P<instance_id>[a-z][-a-z0-9]*)$"
)
DEFAULT_NODE_COUNT = 1
_OPERATION_METADATA_MESSAGES = (
backup.Backup,
backup.CreateBackupMetadata,
spanner_database_admin.CreateDatabaseMetadata,
spanner_database_admin.D... | 256 | 256 | 3,529 | 4 | 252 | thiagotnunes/python-spanner | google/cloud/spanner_v1/instance.py | Python | Instance | Instance | 73 | 545 | 73 | 73 | c8836fed455cd9485a410d4ecb329d60bd5fb5a1 | bigcode/the-stack | train |
38cd3f1e5dbf8270343caff2 | train | function | def _type_string_to_type_pb(type_string):
return _OPERATION_METADATA_TYPES.get(type_string, Empty)
| def _type_string_to_type_pb(type_string):
| return _OPERATION_METADATA_TYPES.get(type_string, Empty)
| spanner_database_admin.Database,
spanner_database_admin.OptimizeRestoredDatabaseMetadata: spanner_database_admin.Database,
spanner_database_admin.RestoreDatabaseMetadata: spanner_database_admin.Database,
spanner_database_admin.UpdateDatabaseDdlMetadata: Empty,
}
def _type_string_to_type_pb(type_string):
| 64 | 64 | 23 | 10 | 54 | thiagotnunes/python-spanner | google/cloud/spanner_v1/instance.py | Python | _type_string_to_type_pb | _type_string_to_type_pb | 69 | 70 | 69 | 69 | 757d44db758b9abe6676685cbab81d189ecea283 | bigcode/the-stack | train |
1764cc32e97be78166f6968d | train | function | def idxmaxmin_chunk(x, fn=None, skipna=True):
minmax = "max" if fn == "idxmax" else "min"
if len(x) > 0:
idx = getattr(x, fn)(skipna=skipna)
value = getattr(x, minmax)(skipna=skipna)
else:
idx = value = pd.Series([], dtype="i8")
if is_series_like(idx):
return pd.DataFrame... | def idxmaxmin_chunk(x, fn=None, skipna=True):
| minmax = "max" if fn == "idxmax" else "min"
if len(x) > 0:
idx = getattr(x, fn)(skipna=skipna)
value = getattr(x, minmax)(skipna=skipna)
else:
idx = value = pd.Series([], dtype="i8")
if is_series_like(idx):
return pd.DataFrame({"idx": idx, "value": value})
return pd.D... | T if is_series_like(o) else o
def _reduction_aggregate(x, aca_aggregate=None, **kwargs):
if isinstance(x, list):
x = pd.Series(x)
return aca_aggregate(x, **kwargs)
def idxmaxmin_chunk(x, fn=None, skipna=True):
| 64 | 64 | 126 | 14 | 50 | galipremsagar/dask | dask/dataframe/core.py | Python | idxmaxmin_chunk | idxmaxmin_chunk | 6,493 | 6,502 | 6,493 | 6,493 | 7f72498b52c36f4b30ca9baec1eab9e8e707acbc | bigcode/the-stack | train |
79e6396021720cb9c08ae4a1 | train | function | def idxmaxmin_row(x, fn=None, skipna=True):
minmax = "max" if fn == "idxmax" else "min"
if len(x) > 0:
x = x.set_index("idx")
idx = [getattr(x.value, fn)(skipna=skipna)]
value = [getattr(x.value, minmax)(skipna=skipna)]
else:
idx = value = pd.Series([], dtype="i8")
return... | def idxmaxmin_row(x, fn=None, skipna=True):
| minmax = "max" if fn == "idxmax" else "min"
if len(x) > 0:
x = x.set_index("idx")
idx = [getattr(x.value, fn)(skipna=skipna)]
value = [getattr(x.value, minmax)(skipna=skipna)]
else:
idx = value = pd.Series([], dtype="i8")
return pd.DataFrame({"idx": idx, "value": value})
| value = pd.Series([], dtype="i8")
if is_series_like(idx):
return pd.DataFrame({"idx": idx, "value": value})
return pd.DataFrame({"idx": [idx], "value": [value]})
def idxmaxmin_row(x, fn=None, skipna=True):
| 64 | 64 | 116 | 14 | 50 | galipremsagar/dask | dask/dataframe/core.py | Python | idxmaxmin_row | idxmaxmin_row | 6,505 | 6,513 | 6,505 | 6,505 | b701152a3e9bf1cb8e66f6ca1f6d1bca4c1f2a55 | bigcode/the-stack | train |
d8be17232a095b517d689896 | train | function | def _reduction_aggregate(x, aca_aggregate=None, **kwargs):
if isinstance(x, list):
x = pd.Series(x)
return aca_aggregate(x, **kwargs)
| def _reduction_aggregate(x, aca_aggregate=None, **kwargs):
| if isinstance(x, list):
x = pd.Series(x)
return aca_aggregate(x, **kwargs)
| = pd.Series(x)
o = aca_combine(x, **kwargs)
# Return a dataframe so that the concatenated version is also a dataframe
return o.to_frame().T if is_series_like(o) else o
def _reduction_aggregate(x, aca_aggregate=None, **kwargs):
| 64 | 64 | 40 | 16 | 47 | galipremsagar/dask | dask/dataframe/core.py | Python | _reduction_aggregate | _reduction_aggregate | 6,487 | 6,490 | 6,487 | 6,487 | 10ae7c82bab7f9c33348c00b3ed76fb07e573db6 | bigcode/the-stack | train |
6e3846bc208f88e59335c1b0 | train | function | def repartition_size(df, size):
"""
Repartition dataframe so that new partitions have approximately `size` memory usage each
"""
if isinstance(size, str):
size = parse_bytes(size)
size = int(size)
mem_usages = df.map_partitions(total_mem_usage, deep=True).compute()
# 1. split each ... | def repartition_size(df, size):
| """
Repartition dataframe so that new partitions have approximately `size` memory usage each
"""
if isinstance(size, str):
size = parse_bytes(size)
size = int(size)
mem_usages = df.map_partitions(total_mem_usage, deep=True).compute()
# 1. split each partition that is larger than pa... | [-1], freq=freq)
)
if not len(divisions):
divisions = [df.divisions[0], df.divisions[-1]]
else:
divisions.append(df.divisions[-1])
if divisions[0] != df.divisions[0]:
divisions = [df.divisions[0]] + divisions
return df.repartition(divisions=divisions)
def repartition... | 89 | 89 | 298 | 8 | 81 | galipremsagar/dask | dask/dataframe/core.py | Python | repartition_size | repartition_size | 6,282 | 6,308 | 6,282 | 6,282 | ab472907983f70cc65c20e1202b462d4e53f7158 | bigcode/the-stack | train |
a7431620f2b3dfe780339bf5 | train | function | def maybe_shift_divisions(df, periods, freq):
"""Maybe shift divisions by periods of size freq
Used to shift the divisions for the `shift` method. If freq isn't a fixed
size (not anchored or relative), then the divisions are shifted
appropriately. Otherwise the divisions are cleared.
Parameters
... | def maybe_shift_divisions(df, periods, freq):
| """Maybe shift divisions by periods of size freq
Used to shift the divisions for the `shift` method. If freq isn't a fixed
size (not anchored or relative), then the divisions are shifted
appropriately. Otherwise the divisions are cleared.
Parameters
----------
df : dd.DataFrame, dd.Series,... | ")
def safe_head(df, n):
r = M.head(df, n)
if len(r) != n:
msg = (
"Insufficient elements for `head`. {0} elements "
"requested, only {1} elements available. Try passing larger "
"`npartitions` to `head`."
)
warnings.warn(msg.format(n, len(r)))
r... | 96 | 96 | 323 | 11 | 84 | galipremsagar/dask | dask/dataframe/core.py | Python | maybe_shift_divisions | maybe_shift_divisions | 6,564 | 6,597 | 6,564 | 6,564 | dbcb4d7761c3977864c2df6df0786e1a9af2d192 | bigcode/the-stack | train |
65db8da1b228d9ea492889bc | train | function | def partitionwise_graph(func, name, *args, **kwargs):
"""
Apply a function partition-wise across arguments to create layer of a graph
This applies a function, ``func``, in an embarrassingly parallel fashion
across partitions/chunks in the provided arguments. It handles Dataframes,
Arrays, and scal... | def partitionwise_graph(func, name, *args, **kwargs):
| """
Apply a function partition-wise across arguments to create layer of a graph
This applies a function, ``func``, in an embarrassingly parallel fashion
across partitions/chunks in the provided arguments. It handles Dataframes,
Arrays, and scalars smoothly, and relies on the ``blockwise`` machiner... | > 1:
layer = dsk.layers[name]
if isinstance(layer, Blockwise):
layer.new_axes["j"] = chunks[1][0]
layer.output_indices = layer.output_indices + ("j",)
else:
suffix = (0,) * (len(chunks) - 1)
for i in range(len(chunks[0]... | 147 | 147 | 493 | 14 | 133 | galipremsagar/dask | dask/dataframe/core.py | Python | partitionwise_graph | partitionwise_graph | 6,699 | 6,757 | 6,699 | 6,699 | 69c1e769bc44be006d322fba2116a1f88c811447 | bigcode/the-stack | train |
c3296a80d597f6d648a7ae9b | train | function | def idxmaxmin_combine(x, fn=None, skipna=True):
if len(x) == 0:
return x
return (
x.groupby(level=0)
.apply(idxmaxmin_row, fn=fn, skipna=skipna)
.reset_index(level=1, drop=True)
)
| def idxmaxmin_combine(x, fn=None, skipna=True):
| if len(x) == 0:
return x
return (
x.groupby(level=0)
.apply(idxmaxmin_row, fn=fn, skipna=skipna)
.reset_index(level=1, drop=True)
)
| value = [getattr(x.value, minmax)(skipna=skipna)]
else:
idx = value = pd.Series([], dtype="i8")
return pd.DataFrame({"idx": idx, "value": value})
def idxmaxmin_combine(x, fn=None, skipna=True):
| 64 | 64 | 69 | 15 | 49 | galipremsagar/dask | dask/dataframe/core.py | Python | idxmaxmin_combine | idxmaxmin_combine | 6,516 | 6,523 | 6,516 | 6,516 | 56c95b750931a77e2f7dc06a408729f21c53f674 | bigcode/the-stack | train |
90f012ce8731baebb40ef292 | train | function | def _concat(args, ignore_index=False):
if not args:
return args
if isinstance(first(core.flatten(args)), np.ndarray):
return da.core.concatenate3(args)
if not has_parallel_type(args[0]):
try:
return pd.Series(args)
except Exception:
return args
# W... | def _concat(args, ignore_index=False):
| if not args:
return args
if isinstance(first(core.flatten(args)), np.ndarray):
return da.core.concatenate3(args)
if not has_parallel_type(args[0]):
try:
return pd.Series(args)
except Exception:
return args
# We filter out empty partitions here beca... | is_dataframe_like,
is_index_like,
is_series_like,
make_meta,
meta_nonempty,
raise_on_meta_error,
valid_divisions,
)
no_default = "__no_default__"
pd.set_option("compute.use_numexpr", False)
def _concat(args, ignore_index=False):
| 64 | 64 | 165 | 9 | 55 | galipremsagar/dask | dask/dataframe/core.py | Python | _concat | _concat | 85 | 104 | 85 | 85 | 336cdcb1e8d44f9d71004c3eec4de96c437e38c1 | bigcode/the-stack | train |
7c1470f4b5bf94bdbb7be3f3 | train | function | def repartition(df, divisions=None, force=False):
"""Repartition dataframe along new divisions
Dask.DataFrame objects are partitioned along their index. Often when
multiple dataframes interact we need to align these partitionings. The
``repartition`` function constructs a new DataFrame object holding... | def repartition(df, divisions=None, force=False):
| """Repartition dataframe along new divisions
Dask.DataFrame objects are partitioned along their index. Often when
multiple dataframes interact we need to align these partitionings. The
``repartition`` function constructs a new DataFrame object holding the same
data but partitioned on different va... | df._name, i)
j += 1
else:
dsk[split_name, i] = (split_evenly, (df._name, i), k)
for jj in range(k):
dsk[new_name, j] = (getitem, (split_name, i), jj)
j += 1
divisions = [None] * (1 + sum(nsplits))
graph = HighLevelGraph.from_collection... | 132 | 132 | 443 | 11 | 121 | galipremsagar/dask | dask/dataframe/core.py | Python | repartition | repartition | 6,424 | 6,470 | 6,424 | 6,424 | ef15f6110c3dc370b7f7e1e885ceef7af9e328b3 | bigcode/the-stack | train |
094cf155235786670f107605 | train | function | @get_parallel_type.register(object)
def get_parallel_type_object(_):
return Scalar
| @get_parallel_type.register(object)
def get_parallel_type_object(_):
| return Scalar
| _parallel_type_dataframe(_):
return DataFrame
@get_parallel_type.register(pd.Index)
def get_parallel_type_index(_):
return Index
@get_parallel_type.register(_Frame)
def get_parallel_type_frame(o):
return get_parallel_type(o._meta)
@get_parallel_type.register(object)
def get_parallel_type_object(_):
| 64 | 64 | 17 | 13 | 51 | galipremsagar/dask | dask/dataframe/core.py | Python | get_parallel_type_object | get_parallel_type_object | 6,662 | 6,664 | 6,662 | 6,663 | b91897e5f7782dab1d70a49ddfc08683a984372b | bigcode/the-stack | train |
207e06f5719e3eb52d4fec77 | train | function | def elemwise(op, *args, **kwargs):
"""Elementwise operation for Dask dataframes
Parameters
----------
op: callable
Function to apply across input dataframes
*args: DataFrames, Series, Scalars, Arrays,
The arguments of the operation
**kwrags: scalars
meta: pd.DataFrame, pd.Se... | def elemwise(op, *args, **kwargs):
| """Elementwise operation for Dask dataframes
Parameters
----------
op: callable
Function to apply across input dataframes
*args: DataFrames, Series, Scalars, Arrays,
The arguments of the operation
**kwrags: scalars
meta: pd.DataFrame, pd.Series (optional)
Valid metad... | "mod",
"pow",
"radd",
"rsub",
"rmul",
"rdiv",
"rtruediv",
"rfloordiv",
"rmod",
"rpow",
]:
meth = getattr(pd.DataFrame, name)
DataFrame._bind_operator_method(name, meth)
meth = getattr(pd.Series, name)
Series._bind_operator_method(name, meth)
for name in ["lt", "gt"... | 256 | 256 | 908 | 11 | 245 | galipremsagar/dask | dask/dataframe/core.py | Python | elemwise | elemwise | 5,071 | 5,172 | 5,071 | 5,071 | 6d8749593f3fe0ff8b1502bc36b294b7a2a93124 | bigcode/the-stack | train |
7d7513c6a06bc38bd3aed6b3 | train | function | def _repartition_from_boundaries(df, new_partitions_boundaries, new_name):
if not isinstance(new_partitions_boundaries, list):
new_partitions_boundaries = list(new_partitions_boundaries)
if new_partitions_boundaries[0] > 0:
new_partitions_boundaries.insert(0, 0)
if new_partitions_boundaries[... | def _repartition_from_boundaries(df, new_partitions_boundaries, new_name):
| if not isinstance(new_partitions_boundaries, list):
new_partitions_boundaries = list(new_partitions_boundaries)
if new_partitions_boundaries[0] > 0:
new_partitions_boundaries.insert(0, 0)
if new_partitions_boundaries[-1] < df.npartitions:
new_partitions_boundaries.append(df.npartitio... | mod(npartitions, df.npartitions)
nsplits = [div] * df.npartitions
nsplits[-1] += mod
return _split_partitions(df, nsplits, new_name)
def _repartition_from_boundaries(df, new_partitions_boundaries, new_name):
| 64 | 64 | 215 | 18 | 46 | galipremsagar/dask | dask/dataframe/core.py | Python | _repartition_from_boundaries | _repartition_from_boundaries | 6,370 | 6,384 | 6,370 | 6,370 | 8be96149a063f281af6dd316e6c586076f7070f9 | bigcode/the-stack | train |
174247fc3e963f5d092e20c6 | train | function | def suffix_reduction(f, ddf, identity, **kwargs):
"""Computes the suffix sums of f on df
If df has partitions [P1, P2, ..., Pn], then returns the DataFrame with
partitions [f(P1, f(P2, ...f(Pn, identity)...)),
f(P2, ...f(Pn, identity)...),
...f(Pn, identity)...,
... | def suffix_reduction(f, ddf, identity, **kwargs):
| """Computes the suffix sums of f on df
If df has partitions [P1, P2, ..., Pn], then returns the DataFrame with
partitions [f(P1, f(P2, ...f(Pn, identity)...)),
f(P2, ...f(Pn, identity)...),
...f(Pn, identity)...,
...]
Parameters
----------
f : ca... | dsk[(name, i + d - 1, d, 1)] = (name, i + 2 * d - 1, 2 * d, 1)
dsk[(name, i + 2 * d - 1, d, 1)] = (
apply,
f,
[(name, i + 2 * d - 1, 2 * d, 1), (name, i + d - 1, d, 0)],
kwargs,
)
for i in range(n):
dsk[(name, i)] = (a... | 192 | 192 | 642 | 14 | 178 | galipremsagar/dask | dask/dataframe/core.py | Python | suffix_reduction | suffix_reduction | 6,849 | 6,910 | 6,849 | 6,849 | 89027d74c8992e5f350ee74e99ef95e335e8debb | bigcode/the-stack | train |
506701d26cc38ddd819fbf03 | train | class | class _Frame(DaskMethodsMixin, OperatorMethodMixin):
"""Superclass for DataFrame and Series
Parameters
----------
dsk: dict
The dask graph to compute this DataFrame
name: str
The key prefix that specifies which keys in the dask comprise this
particular DataFrame / Series
... | class _Frame(DaskMethodsMixin, OperatorMethodMixin):
| """Superclass for DataFrame and Series
Parameters
----------
dsk: dict
The dask graph to compute this DataFrame
name: str
The key prefix that specifies which keys in the dask comprise this
particular DataFrame / Series
meta: pandas.DataFrame, pandas.Series, or pandas.Ind... | ):
name = "{0}-{1}".format(funcname(op), tokenize(self, other))
dependencies = [self]
dsk = {}
return_type = get_parallel_type(other)
if isinstance(other, Scalar):
dependencies.append(other)
other_key = (other._name, 0)
elif is_dask_collection(other):
return NotImplemen... | 256 | 256 | 21,642 | 12 | 244 | galipremsagar/dask | dask/dataframe/core.py | Python | _Frame | _Frame | 279 | 2,929 | 279 | 279 | 3f08c1b6348dee31ea837a8fb6401394b2d8eeaf | bigcode/the-stack | train |
a723e08bf29e1f3e3445b5fc | train | function | def _rename(columns, df):
"""
Rename columns of pd.DataFrame or name of pd.Series.
Not for dd.DataFrame or dd.Series.
Parameters
----------
columns : tuple, string, pd.DataFrame or pd.Series
Column names, Series name or pandas instance which has the
target column names / name.
... | def _rename(columns, df):
| """
Rename columns of pd.DataFrame or name of pd.Series.
Not for dd.DataFrame or dd.Series.
Parameters
----------
columns : tuple, string, pd.DataFrame or pd.Series
Column names, Series name or pandas instance which has the
target column names / name.
df : pd.DataFrame or pd... | .pop("_meta")
df = func(*args, **kwargs)
if is_dataframe_like(df) or is_series_like(df) or is_index_like(df):
if not len(df):
return meta
if is_dataframe_like(df):
check_matching_columns(meta, df)
c = meta.columns
else:
c = meta.name
... | 92 | 92 | 307 | 7 | 84 | galipremsagar/dask | dask/dataframe/core.py | Python | _rename | _rename | 5,678 | 5,722 | 5,678 | 5,678 | a612dff1da37a99ac640260cca607a81841b0577 | bigcode/the-stack | train |
aaee6f60e1c4c09e81264acc | train | function | def split_out_on_index(df):
h = df.index
if isinstance(h, pd.MultiIndex):
h = pd.DataFrame([], index=h).reset_index()
return h
| def split_out_on_index(df):
| h = df.index
if isinstance(h, pd.MultiIndex):
h = pd.DataFrame([], index=h).reset_index()
return h
| k):
""" Split dataframe into k roughly equal parts """
divisions = np.linspace(0, len(df), k + 1).astype(int)
return {i: df.iloc[divisions[i] : divisions[i + 1]] for i in range(k)}
def split_out_on_index(df):
| 63 | 64 | 39 | 7 | 56 | galipremsagar/dask | dask/dataframe/core.py | Python | split_out_on_index | split_out_on_index | 5,255 | 5,259 | 5,255 | 5,255 | 43afa28073a438d28399c04bc53d8a8532632720 | bigcode/the-stack | train |
e554195bb1a0c9c9eca9da01 | train | class | class Series(_Frame):
"""Parallel Pandas Series
Do not use this class directly. Instead use functions like
``dd.read_csv``, ``dd.read_parquet``, or ``dd.from_pandas``.
Parameters
----------
dsk: dict
The dask graph to compute this Series
_name: str
The key prefix that spe... | class Series(_Frame):
| """Parallel Pandas Series
Do not use this class directly. Instead use functions like
``dd.read_csv``, ``dd.read_parquet``, or ``dd.from_pandas``.
Parameters
----------
dsk: dict
The dask graph to compute this Series
_name: str
The key prefix that specifies which keys in t... | is an index level reference
To be considered an index level reference, `key` must match the index name
and must NOT match the name of any column (if a dataframe).
"""
return (
self.index.name is not None
and not is_dask_collection(key)
and (np.isscal... | 256 | 256 | 4,733 | 5 | 251 | galipremsagar/dask | dask/dataframe/core.py | Python | Series | Series | 2,941 | 3,568 | 2,941 | 2,941 | fe8c1dc70a57c285f351d21784ed8303b48708e3 | bigcode/the-stack | train |
e188ecea4463b8a94c22f4cf | train | function | def safe_head(df, n):
r = M.head(df, n)
if len(r) != n:
msg = (
"Insufficient elements for `head`. {0} elements "
"requested, only {1} elements available. Try passing larger "
"`npartitions` to `head`."
)
warnings.warn(msg.format(n, len(r)))
return... | def safe_head(df, n):
| r = M.head(df, n)
if len(r) != n:
msg = (
"Insufficient elements for `head`. {0} elements "
"requested, only {1} elements available. Try passing larger "
"`npartitions` to `head`."
)
warnings.warn(msg.format(n, len(r)))
return r
| mode_series = (
value_count_series[value_count_series == max_val]
.index.to_series()
.sort_values()
.reset_index(drop=True)
)
return mode_series
def _count_aggregate(x):
return x.sum().astype("int64")
def safe_head(df, n):
| 64 | 64 | 84 | 7 | 57 | galipremsagar/dask | dask/dataframe/core.py | Python | safe_head | safe_head | 6,552 | 6,561 | 6,552 | 6,552 | 4a7e5835d1ef17343fbe74d0426131039a64eb91 | bigcode/the-stack | train |
f7c496d118e6dc0ec9b073a1 | train | function | @get_parallel_type.register(pd.Index)
def get_parallel_type_index(_):
return Index
| @get_parallel_type.register(pd.Index)
def get_parallel_type_index(_):
| return Index
| .name)
get_parallel_type = Dispatch("get_parallel_type")
@get_parallel_type.register(pd.Series)
def get_parallel_type_series(_):
return Series
@get_parallel_type.register(pd.DataFrame)
def get_parallel_type_dataframe(_):
return DataFrame
@get_parallel_type.register(pd.Index)
def get_parallel_type_index(_)... | 64 | 64 | 18 | 14 | 49 | galipremsagar/dask | dask/dataframe/core.py | Python | get_parallel_type_index | get_parallel_type_index | 6,652 | 6,654 | 6,652 | 6,653 | abc21b2dbbadc78a0b52d11f36b57b4f5e7ff724 | bigcode/the-stack | train |
b1b3b6fc9f3cd5cade740216 | train | function | def prefix_reduction(f, ddf, identity, **kwargs):
"""Computes the prefix sums of f on df
If df has partitions [P1, P2, ..., Pn], then returns the DataFrame with
partitions [f(identity, P1),
f(f(identity, P1), P2),
f(f(f(identity, P1), P2), P3),
...]
Para... | def prefix_reduction(f, ddf, identity, **kwargs):
| """Computes the prefix sums of f on df
If df has partitions [P1, P2, ..., Pn], then returns the DataFrame with
partitions [f(identity, P1),
f(f(identity, P1), P2),
f(f(f(identity, P1), P2), P3),
...]
Parameters
----------
f : callable
an ... | ()}
elif is_series_like(df):
meta_str = (df.name, str(df.dtype))
else:
meta_str = None
msg = (
"\nYou did not provide metadata, so Dask is running your "
"function on a small dataset to guess output types. "
"It is possible that Dask will guess incorrectly.\n"
... | 184 | 184 | 616 | 14 | 169 | galipremsagar/dask | dask/dataframe/core.py | Python | prefix_reduction | prefix_reduction | 6,787 | 6,846 | 6,787 | 6,787 | 5fe91af339d0081b28e06d15b1d2fd8737c7bc69 | bigcode/the-stack | train |
09d14ec6811517d83cd09cc3 | train | function | @get_parallel_type.register(pd.Series)
def get_parallel_type_series(_):
return Series
| @get_parallel_type.register(pd.Series)
def get_parallel_type_series(_):
| return Series
| dtype = "category[unknown]"
else:
dtype = str(s.dtype)
return pd.Series([dtype] + ["..."] * npartitions, index=index, name=s.name)
get_parallel_type = Dispatch("get_parallel_type")
@get_parallel_type.register(pd.Series)
def get_parallel_type_series(_):
| 64 | 64 | 18 | 14 | 50 | galipremsagar/dask | dask/dataframe/core.py | Python | get_parallel_type_series | get_parallel_type_series | 6,642 | 6,644 | 6,642 | 6,643 | ca931b183378dc7c38a0b7a7a7e060c36bcf420f | bigcode/the-stack | train |
072952ad9214b33c838bc7de | train | function | def new_dd_object(dsk, name, meta, divisions):
"""Generic constructor for dask.dataframe objects.
Decides the appropriate output class based on the type of `meta` provided.
"""
if has_parallel_type(meta):
return get_parallel_type(meta)(dsk, name, meta, divisions)
elif is_arraylike(meta) and... | def new_dd_object(dsk, name, meta, divisions):
| """Generic constructor for dask.dataframe objects.
Decides the appropriate output class based on the type of `meta` provided.
"""
if has_parallel_type(meta):
return get_parallel_type(meta)(dsk, name, meta, divisions)
elif is_arraylike(meta) and meta.shape:
import dask.array as da
... | )
def get_parallel_type_frame(o):
return get_parallel_type(o._meta)
@get_parallel_type.register(object)
def get_parallel_type_object(_):
return Scalar
def has_parallel_type(x):
""" Does this object have a dask dataframe equivalent? """
return get_parallel_type(x) is not Scalar
def new_dd_object(dsk,... | 77 | 77 | 259 | 13 | 63 | galipremsagar/dask | dask/dataframe/core.py | Python | new_dd_object | new_dd_object | 6,672 | 6,696 | 6,672 | 6,672 | 46f483c7460d5bc5dd590b25a4213c07207638e3 | bigcode/the-stack | train |
d35beba563f9abf9cedf71ff | train | function | def cov_corr(df, min_periods=None, corr=False, scalar=False, split_every=False):
"""DataFrame covariance and pearson correlation.
Computes pairwise covariance or correlation of columns, excluding NA/null
values.
Parameters
----------
df : DataFrame
min_periods : int, optional
Minim... | def cov_corr(df, min_periods=None, corr=False, scalar=False, split_every=False):
| """DataFrame covariance and pearson correlation.
Computes pairwise covariance or correlation of columns, excluding NA/null
values.
Parameters
----------
df : DataFrame
min_periods : int, optional
Minimum number of observations required per pair of columns
to have a valid re... | , mode="constant")
calc_qs[-1] = 100
name = "quantiles-1-" + token
val_dsk = {
(name, i): (_percentile, (getattr, key, "values"), calc_qs)
for i, key in enumerate(df.__dask_keys__())
}
name2 = "quantiles-2-" + token
merge_dsk = {
(name... | 199 | 199 | 664 | 20 | 179 | galipremsagar/dask | dask/dataframe/core.py | Python | cov_corr | cov_corr | 5,867 | 5,939 | 5,867 | 5,867 | 9bb7bb99af611d33fcd3cc41ea44f402178b16d8 | bigcode/the-stack | train |
0c679d6f364bcad347602734 | train | function | def _raise_if_object_series(x, funcname):
"""
Utility function to raise an error if an object column does not support
a certain operation like `mean`.
"""
if isinstance(x, Series) and hasattr(x, "dtype") and x.dtype == object:
raise ValueError("`%s` not supported with object series" % funcna... | def _raise_if_object_series(x, funcname):
| """
Utility function to raise an error if an object column does not support
a certain operation like `mean`.
"""
if isinstance(x, Series) and hasattr(x, "dtype") and x.dtype == object:
raise ValueError("`%s` not supported with object series" % funcname)
| the index of the DataFrame/Series
"""
if isinstance(columns_or_index, list):
return any(self._is_index_level_reference(n) for n in columns_or_index)
else:
return self._is_index_level_reference(columns_or_index)
def _raise_if_object_series(x, funcname):
| 64 | 64 | 77 | 11 | 53 | galipremsagar/dask | dask/dataframe/core.py | Python | _raise_if_object_series | _raise_if_object_series | 2,932 | 2,938 | 2,932 | 2,932 | 0f70c0539b283bb1678ca5515c0d2cf622397f7b | bigcode/the-stack | train |
852f3064181db1fdcaeef880 | train | function | def finalize(results):
return _concat(results)
| def finalize(results):
| return _concat(results)
| practice
# this seems easier. TODO: don't do this.
args2 = [i for i in args if len(i)]
return (
args[0]
if not args2
else methods.concat(args2, uniform=True, ignore_index=ignore_index)
)
def finalize(results):
| 64 | 64 | 10 | 4 | 60 | galipremsagar/dask | dask/dataframe/core.py | Python | finalize | finalize | 107 | 108 | 107 | 107 | 1a866e4ef1fa9d93bf7d80d6ad2e5dbcde476471 | bigcode/the-stack | train |
e77256cc741759a62a544161 | train | function | def split_out_on_cols(df, cols=None):
return df[cols]
| def split_out_on_cols(df, cols=None):
| return df[cols]
| ] : divisions[i + 1]] for i in range(k)}
def split_out_on_index(df):
h = df.index
if isinstance(h, pd.MultiIndex):
h = pd.DataFrame([], index=h).reset_index()
return h
def split_out_on_cols(df, cols=None):
| 64 | 64 | 16 | 10 | 53 | galipremsagar/dask | dask/dataframe/core.py | Python | split_out_on_cols | split_out_on_cols | 5,262 | 5,263 | 5,262 | 5,262 | 2e3931a7916c03ef502d2e1ea99ff712a3755be6 | bigcode/the-stack | train |
2d985dcb46075ca26a2da313 | train | function | def handle_out(out, result):
"""Handle out parameters
If out is a dask.DataFrame, dask.Series or dask.Scalar then
this overwrites the contents of it with the result
"""
if isinstance(out, tuple):
if len(out) == 1:
out = out[0]
elif len(out) > 1:
raise NotImpl... | def handle_out(out, result):
| """Handle out parameters
If out is a dask.DataFrame, dask.Series or dask.Scalar then
this overwrites the contents of it with the result
"""
if isinstance(out, tuple):
if len(out) == 1:
out = out[0]
elif len(out) > 1:
raise NotImplementedError("The out paramet... | no rows.
parts = [
d._meta
if _is_broadcastable(d)
else np.empty((), dtype=d.dtype)
if isinstance(d, Array)
else d._meta_nonempty
for d in dasks
]
with raise_on_meta_error(funcname(op)):
meta = partial_by_order(... | 112 | 112 | 376 | 7 | 105 | galipremsagar/dask | dask/dataframe/core.py | Python | handle_out | handle_out | 5,175 | 5,219 | 5,175 | 5,175 | 53f4b6eabdb79cf574ce0e1860b15bbf4bc01534 | bigcode/the-stack | train |
cd480610d86b23a47acc36d4 | train | function | def apply_and_enforce(*args, **kwargs):
"""Apply a function, and enforce the output to match meta
Ensures the output has the same columns, even if empty."""
func = kwargs.pop("_func")
meta = kwargs.pop("_meta")
df = func(*args, **kwargs)
if is_dataframe_like(df) or is_series_like(df) or is_inde... | def apply_and_enforce(*args, **kwargs):
| """Apply a function, and enforce the output to match meta
Ensures the output has the same columns, even if empty."""
func = kwargs.pop("_func")
meta = kwargs.pop("_meta")
df = func(*args, **kwargs)
if is_dataframe_like(df) or is_series_like(df) or is_index_like(df):
if not len(df):
... | v.dsk[key] = task
dsk[k] = (v,) + vv[1:]
graph = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies)
return new_dd_object(graph, name, meta, divisions)
def apply_and_enforce(*args, **kwargs):
| 64 | 64 | 136 | 11 | 53 | galipremsagar/dask | dask/dataframe/core.py | Python | apply_and_enforce | apply_and_enforce | 5,659 | 5,675 | 5,659 | 5,659 | 7ba8505daabcaea844f886d95af88fa94017a579 | bigcode/the-stack | train |
2f4ae844389ae99aeaad5835 | train | function | def meta_warning(df):
"""
Provide an informative message when the user is asked to provide metadata
"""
if is_dataframe_like(df):
meta_str = {k: str(v) for k, v in df.dtypes.to_dict().items()}
elif is_series_like(df):
meta_str = (df.name, str(df.dtype))
else:
meta_str = N... | def meta_warning(df):
| """
Provide an informative message when the user is asked to provide metadata
"""
if is_dataframe_like(df):
meta_str = {k: str(v) for k, v in df.dtypes.to_dict().items()}
elif is_series_like(df):
meta_str = (df.name, str(df.dtype))
else:
meta_str = None
msg = (
... | Can't add multi-dimensional array to dataframes")
numblocks[arg._name] = arg.numblocks
else:
pairs.extend([arg, None])
return blockwise(
func, name, "i", *pairs, numblocks=numblocks, concatenate=True, **kwargs
)
def meta_warning(df):
| 66 | 66 | 222 | 5 | 61 | galipremsagar/dask | dask/dataframe/core.py | Python | meta_warning | meta_warning | 6,760 | 6,784 | 6,760 | 6,760 | 22b237f03f719bab982a0a0e191df98fb9515529 | bigcode/the-stack | train |
e406d7183cafb2043d65611d | train | function | def cov_corr_chunk(df, corr=False):
"""Chunk part of a covariance or correlation computation"""
shape = (df.shape[1], df.shape[1])
df = df.astype("float64", copy=False)
sums = zeros_like_safe(df.values, shape=shape)
counts = zeros_like_safe(df.values, shape=shape)
for idx, col in enumerate(df):
... | def cov_corr_chunk(df, corr=False):
| """Chunk part of a covariance or correlation computation"""
shape = (df.shape[1], df.shape[1])
df = df.astype("float64", copy=False)
sums = zeros_like_safe(df.values, shape=shape)
counts = zeros_like_safe(df.values, shape=shape)
for idx, col in enumerate(df):
mask = df.iloc[:, idx].notnu... | df.columns,
min_periods,
corr,
scalar,
)
graph = HighLevelGraph.from_collections(name, dsk, dependencies=[df])
if scalar:
return Scalar(graph, name, "f8")
meta = make_meta([(c, "f8") for c in df.columns], index=df.columns)
return DataFrame(graph, name, meta, (... | 102 | 103 | 345 | 9 | 93 | galipremsagar/dask | dask/dataframe/core.py | Python | cov_corr_chunk | cov_corr_chunk | 5,942 | 5,973 | 5,942 | 5,942 | fd1c725fbb23496281a7eded15a83e282a7fc44b | bigcode/the-stack | train |
022687460452cb85b0f25274 | train | function | def pd_split(df, p, random_state=None, shuffle=False):
"""Split DataFrame into multiple pieces pseudorandomly
>>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6],
... 'b': [2, 3, 4, 5, 6, 7]})
>>> a, b = pd_split(
... df, [0.5, 0.5], random_state=123, shuffle=True
... ) # ro... | def pd_split(df, p, random_state=None, shuffle=False):
| """Split DataFrame into multiple pieces pseudorandomly
>>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6],
... 'b': [2, 3, 4, 5, 6, 7]})
>>> a, b = pd_split(
... df, [0.5, 0.5], random_state=123, shuffle=True
... ) # roughly 50/50 split
>>> a
a b
3 4 5
... | )
else:
den = np.where(counts, counts, np.nan) - 1
with np.errstate(invalid="ignore", divide="ignore"):
mat = C / den
if scalar:
return float(mat[0, 1])
return pd.DataFrame(mat, columns=cols, index=cols)
def pd_split(df, p, random_state=None, shuffle=False):
| 85 | 85 | 284 | 14 | 71 | galipremsagar/dask | dask/dataframe/core.py | Python | pd_split | pd_split | 6,030 | 6,056 | 6,030 | 6,030 | de2b2a58adedafbeab67475ad1b51478658941ac | bigcode/the-stack | train |
fa6770fecc9ac25261c5621c | train | function | @insert_meta_param_description
def apply_concat_apply(
args,
chunk=None,
aggregate=None,
combine=None,
meta=no_default,
token=None,
chunk_kwargs=None,
aggregate_kwargs=None,
combine_kwargs=None,
split_every=None,
split_out=None,
split_out_setup=None,
split_out_setup_k... | @insert_meta_param_description
def apply_concat_apply(
args,
chunk=None,
aggregate=None,
combine=None,
meta=no_default,
token=None,
chunk_kwargs=None,
aggregate_kwargs=None,
combine_kwargs=None,
split_every=None,
split_out=None,
split_out_setup=None,
split_out_setup_k... | """Apply a function to blocks, then concat, then apply again
Parameters
----------
args :
Positional arguments for the `chunk` function. All `dask.dataframe`
objects should be partitioned and indexed equivalently.
chunk : function [block-per-arg] -> block
Function to operate... | = hash_object_dispatch(h, index=False)
if is_series_like(h):
h = h.values
np.mod(h, nparts, out=h)
return group_split_dispatch(df, h, nparts, ignore_index=ignore_index)
def split_evenly(df, k):
""" Split dataframe into k roughly equal parts """
divisions = np.linspace(0, len(df), k + 1).a... | 256 | 256 | 1,661 | 87 | 169 | galipremsagar/dask | dask/dataframe/core.py | Python | apply_concat_apply | apply_concat_apply | 5,266 | 5,475 | 5,266 | 5,284 | e0db4399e7403c718490328ce8a0df5bc0527ecc | bigcode/the-stack | train |
c2b5ada41e5179e86824a338 | train | function | def check_divisions(divisions):
if not isinstance(divisions, (list, tuple)):
raise ValueError("New division must be list or tuple")
divisions = list(divisions)
if divisions != sorted(divisions):
raise ValueError("New division must be sorted")
if len(divisions[:-1]) != len(list(unique(div... | def check_divisions(divisions):
| if not isinstance(divisions, (list, tuple)):
raise ValueError("New division must be list or tuple")
divisions = list(divisions)
if divisions != sorted(divisions):
raise ValueError("New division must be sorted")
if len(divisions[:-1]) != len(list(unique(divisions[:-1]))):
msg = "N... | :1, 0])
if a.empty:
return series_typ([], dtype="float")
return series_typ(
{col: _last_valid(a[col]) for col in a.columns}, index=a.columns
)
else:
return _last_valid(a)
def check_divisions(divisions):
| 64 | 64 | 98 | 7 | 57 | galipremsagar/dask | dask/dataframe/core.py | Python | check_divisions | check_divisions | 6,100 | 6,108 | 6,100 | 6,100 | d8492a6687eeb14340422c4bc0530c136452ff81 | bigcode/the-stack | train |
ebf477896964879168199695 | train | function | @insert_meta_param_description
def map_partitions(
func,
*args,
meta=no_default,
enforce_metadata=True,
transform_divisions=True,
**kwargs,
):
"""Apply Python function on each DataFrame partition.
Parameters
----------
func : function
Function applied to each partition.
... | @insert_meta_param_description
def map_partitions(
func,
*args,
meta=no_default,
enforce_metadata=True,
transform_divisions=True,
**kwargs,
):
| """Apply Python function on each DataFrame partition.
Parameters
----------
func : function
Function applied to each partition.
args, kwargs :
Arguments and keywords to pass to the function. At least one of the
args should be a Dask.dataframe. Arguments and keywords may con... | nonempty else x._meta
elif isinstance(x, list):
return [_extract_meta(_x, nonempty) for _x in x]
elif isinstance(x, tuple):
return tuple([_extract_meta(_x, nonempty) for _x in x])
elif isinstance(x, dict):
res = {}
for k in x:
res[k] = _extract_meta(x[k], nonempt... | 256 | 256 | 1,133 | 39 | 217 | galipremsagar/dask | dask/dataframe/core.py | Python | map_partitions | map_partitions | 5,513 | 5,656 | 5,513 | 5,521 | 37defa5de0444af3f9b40b3ef029d159bdcdd9ec | bigcode/the-stack | train |
132abfc9274829a8ddc85045 | train | function | def repartition_divisions(a, b, name, out1, out2, force=False):
"""dask graph to repartition dataframe by new divisions
Parameters
----------
a : tuple
old divisions
b : tuple, list
new divisions
name : str
name of old dataframe
out1 : str
name of temporary s... | def repartition_divisions(a, b, name, out1, out2, force=False):
| """dask graph to repartition dataframe by new divisions
Parameters
----------
a : tuple
old divisions
b : tuple, list
new divisions
name : str
name of old dataframe
out1 : str
name of temporary splits
out2 : str
name of new dataframe
force : b... | null.empty:
return nonnull.iloc[-1]
return None
if skipna is False:
return a.iloc[-1]
else:
# take last valid value excluding NaN, NaN location may be different
# in each column
if is_dataframe_like(a):
# create Series from appropriate backend... | 256 | 256 | 1,448 | 20 | 236 | galipremsagar/dask | dask/dataframe/core.py | Python | repartition_divisions | repartition_divisions | 6,111 | 6,258 | 6,111 | 6,111 | f4c532cce5b2db9012b8af4319a24e2a25ed2f9b | bigcode/the-stack | train |
e3992c2e3a0224c5ec09ae14 | train | function | def _maybe_from_pandas(dfs):
from .io import from_pandas
dfs = [
from_pandas(df, 1)
if (is_series_like(df) or is_dataframe_like(df)) and not is_dask_collection(df)
else df
for df in dfs
]
return dfs
| def _maybe_from_pandas(dfs):
| from .io import from_pandas
dfs = [
from_pandas(df, 1)
if (is_series_like(df) or is_dataframe_like(df)) and not is_dask_collection(df)
else df
for df in dfs
]
return dfs
| not None:
msg = (
"The out parameter is not fully supported."
" Received type %s, expected %s "
% (typename(type(out)), typename(type(result)))
)
raise NotImplementedError(msg)
else:
return result
def _maybe_from_pandas(dfs):
| 64 | 64 | 69 | 9 | 54 | galipremsagar/dask | dask/dataframe/core.py | Python | _maybe_from_pandas | _maybe_from_pandas | 5,222 | 5,231 | 5,222 | 5,222 | 9d6f64949d391c923f3389214cdfed5ecd01e543 | bigcode/the-stack | train |
2293ea380dc81eb3d1413455 | train | function | def _mode_aggregate(df, dropna):
value_count_series = df.sum()
max_val = value_count_series.max(skipna=dropna)
mode_series = (
value_count_series[value_count_series == max_val]
.index.to_series()
.sort_values()
.reset_index(drop=True)
)
return mode_series
| def _mode_aggregate(df, dropna):
| value_count_series = df.sum()
max_val = value_count_series.max(skipna=dropna)
mode_series = (
value_count_series[value_count_series == max_val]
.index.to_series()
.sort_values()
.reset_index(drop=True)
)
return mode_series
| fn, skipna=skipna)["idx"]
if len(res) == 0:
raise ValueError("attempt to get argmax of an empty sequence")
if scalar:
return res[0]
res.name = None
return res
def _mode_aggregate(df, dropna):
| 64 | 64 | 73 | 10 | 53 | galipremsagar/dask | dask/dataframe/core.py | Python | _mode_aggregate | _mode_aggregate | 6,536 | 6,545 | 6,536 | 6,536 | 3f7398c2de2bd0ff30092a7d53edb04e721f3811 | bigcode/the-stack | train |
9702fb62cdb290686b62d742 | train | function | def cov_corr_combine(data_in, corr=False):
data = {"sum": None, "count": None, "cov": None}
if corr:
data["m"] = None
for k in data.keys():
data[k] = [d[k] for d in data_in]
data[k] = np.concatenate(data[k]).reshape((len(data[k]),) + data[k][0].shape)
sums = np.nan_to_num(data... | def cov_corr_combine(data_in, corr=False):
| data = {"sum": None, "count": None, "cov": None}
if corr:
data["m"] = None
for k in data.keys():
data[k] = [d[k] for d in data_in]
data[k] = np.concatenate(data[k]).reshape((len(data[k]),) + data[k][0].shape)
sums = np.nan_to_num(data["sum"])
counts = data["count"]
cum... | mu[idx][None, :]) ** 2
)
mu_discrepancy[mask] = np.nan
m[idx] = np.nansum(mu_discrepancy, axis=0)
m = m.T
dtype.append(("m", m.dtype))
out = {"sum": sums, "count": counts, "cov": cov * (counts - 1)}
if corr:
out["m"] = m
return out
def cov_corr_c... | 111 | 111 | 371 | 11 | 99 | galipremsagar/dask | dask/dataframe/core.py | Python | cov_corr_combine | cov_corr_combine | 5,976 | 6,010 | 5,976 | 5,977 | bab995a2a012c11520a3f8a41db8fa7068690b1f | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.