code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
text = conversions.to_string(text, ctx)
by_spaces = conversions.to_boolean(by_spaces, ctx)
return len(__get_words(text, by_spaces)) | def word_count(ctx, text, by_spaces=False) | Returns the number of words in the given text string | 4.556956 | 3.632715 | 1.254422 |
text = conversions.to_string(text, ctx)
start = conversions.to_integer(start, ctx)
stop = conversions.to_integer(stop, ctx)
by_spaces = conversions.to_boolean(by_spaces, ctx)
if start == 0:
raise ValueError("Start word cannot be zero")
elif start > 0:
start -= 1 # convert ... | def word_slice(ctx, text, start, stop=0, by_spaces=False) | Extracts a substring spanning from start up to but not-including stop | 3.06291 | 3.04495 | 1.005898 |
dt = conversions.to_datetime(text, ctx)
return dt.astimezone(ctx.timezone).strftime(ctx.get_date_format(True)) | def format_date(ctx, text) | Takes a single parameter (date as string) and returns it in the format defined by the org | 6.241953 | 6.425833 | 0.971384 |
text = conversions.to_string(text, ctx)
return text.split(">")[-1].strip() | def format_location(ctx, text) | Takes a single parameter (administrative boundary as a string) and returns the name of the leaf boundary | 10.595923 | 10.766316 | 0.984174 |
text = conversions.to_string(text, ctx)
pattern = conversions.to_string(pattern, ctx)
group_num = conversions.to_integer(group_num, ctx)
expression = regex.compile(pattern, regex.UNICODE | regex.IGNORECASE | regex.MULTILINE | regex.V0)
match = expression.search(text)
if not match:
... | def regex_group(ctx, text, pattern, group_num) | Tries to match the text with the given pattern and returns the value of matching group | 2.428835 | 2.375309 | 1.022535 |
if by_spaces:
splits = regex.split(r'\s+', text, flags=regex.MULTILINE | regex.UNICODE | regex.V0)
return [split for split in splits if split] # return only non-empty
else:
return tokenize(text) | def __get_words(text, by_spaces) | Helper function which splits the given text string into words. If by_spaces is false, then text like
'01-02-2014' will be split into 3 separate words. For backwards compatibility, this is the default for all
expression functions.
:param text: the text to split
:param by_spaces: whether words should be s... | 4.445846 | 5.199599 | 0.855036 |
exp = Decimal(10) ** -num_digits
if num_digits >= 0:
return number.quantize(exp, rounding)
else:
return exp * (number / exp).to_integral_value(rounding) | def decimal_round(number, num_digits, rounding=ROUND_HALF_UP) | Rounding for decimals with support for negative digits | 3.557911 | 3.548922 | 1.002533 |
if not value:
return None
return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC) | def parse_json_date(value) | Parses an ISO8601 formatted datetime from a string value | 3.412996 | 3.148802 | 1.083903 |
if not value:
return None
# %f will include 6 microsecond digits
micro_precision = value.astimezone(pytz.UTC).strftime(JSON_DATETIME_FORMAT)
# only keep the milliseconds portion of the second fraction
return micro_precision[:-4] + 'Z' | def format_json_date(value) | Formats a datetime as ISO8601 in UTC with millisecond precision, e.g. "2014-10-03T09:41:12.790Z" | 8.926404 | 6.969511 | 1.280779 |
text = conversions.to_string(text, ctx)
return ''.join([c for c in text if ord(c) >= 32]) | def clean(ctx, text) | Removes all non-printable characters from a text string | 5.826585 | 4.685685 | 1.243486 |
result = ''
for arg in text:
result += conversions.to_string(arg, ctx)
return result | def concatenate(ctx, *text) | Joins text strings into one text string | 6.530208 | 6.542261 | 0.998158 |
value = _round(ctx, number, decimals)
format_str = '{:f}' if no_commas else '{:,f}'
return format_str.format(value) | def fixed(ctx, number, decimals=2, no_commas=False) | Formats the given number in decimal format using a period and commas | 3.891743 | 4.085715 | 0.952524 |
num_chars = conversions.to_integer(num_chars, ctx)
if num_chars < 0:
raise ValueError("Number of chars can't be negative")
return conversions.to_string(text, ctx)[0:num_chars] | def left(ctx, text, num_chars) | Returns the first characters in a text string | 3.553025 | 3.285765 | 1.081339 |
if number_times < 0:
raise ValueError("Number of times can't be negative")
return conversions.to_string(text, ctx) * conversions.to_integer(number_times, ctx) | def rept(ctx, text, number_times) | Repeats text a given number of times | 4.549854 | 4.508564 | 1.009158 |
num_chars = conversions.to_integer(num_chars, ctx)
if num_chars < 0:
raise ValueError("Number of chars can't be negative")
elif num_chars == 0:
return ''
else:
return conversions.to_string(text, ctx)[-num_chars:] | def right(ctx, text, num_chars) | Returns the last characters in a text string | 3.09129 | 2.969391 | 1.041052 |
text = conversions.to_string(text, ctx)
old_text = conversions.to_string(old_text, ctx)
new_text = conversions.to_string(new_text, ctx)
if instance_num < 0:
return text.replace(old_text, new_text)
else:
splits = text.split(old_text)
output = splits[0]
instance =... | def substitute(ctx, text, old_text, new_text, instance_num=-1) | Substitutes new_text for old_text in a text string | 2.088161 | 2.068131 | 1.009685 |
text = conversions.to_string(text, ctx)
if len(text) == 0:
raise ValueError("Text can't be empty")
return ord(text[0]) | def _unicode(ctx, text) | Returns a numeric code for the first character in a text string | 4.842551 | 3.64742 | 1.327665 |
return _date(conversions.to_integer(year, ctx), conversions.to_integer(month, ctx), conversions.to_integer(day, ctx)) | def date(ctx, year, month, day) | Defines a date value | 4.124239 | 4.238231 | 0.973104 |
start_date = conversions.to_date(start_date, ctx)
end_date = conversions.to_date(end_date, ctx)
unit = conversions.to_string(unit, ctx).lower()
if start_date > end_date:
raise ValueError("Start date cannot be after end date")
if unit == 'y':
return relativedelta(end_date, star... | def datedif(ctx, start_date, end_date, unit) | Calculates the number of days, months, or years between two dates. | 1.952123 | 1.871339 | 1.043169 |
return conversions.to_date_or_datetime(date, ctx) + relativedelta(months=conversions.to_integer(months, ctx)) | def edate(ctx, date, months) | Moves a date by the given number of months | 9.917287 | 9.257489 | 1.071272 |
return _time(conversions.to_integer(hours, ctx), conversions.to_integer(minutes, ctx), conversions.to_integer(seconds, ctx)) | def time(ctx, hours, minutes, seconds) | Defines a time value | 4.405473 | 4.347572 | 1.013318 |
return conversions.to_decimal(abs(conversions.to_decimal(number, ctx)), ctx) | def _abs(ctx, number) | Returns the absolute value of a number | 10.6931 | 10.244176 | 1.043822 |
return conversions.to_integer(conversions.to_decimal(number, ctx).to_integral_value(ROUND_FLOOR), ctx) | def _int(ctx, number) | Rounds a number down to the nearest integer | 8.689286 | 7.118916 | 1.220591 |
if len(number) == 0:
raise ValueError("Wrong number of arguments")
result = conversions.to_decimal(number[0], ctx)
for arg in number[1:]:
arg = conversions.to_decimal(arg, ctx)
if arg > result:
result = arg
return result | def _max(ctx, *number) | Returns the maximum value of all arguments | 2.9322 | 2.763165 | 1.061174 |
number = conversions.to_decimal(number, ctx)
divisor = conversions.to_decimal(divisor, ctx)
return number - divisor * _int(ctx, number / divisor) | def mod(ctx, number, divisor) | Returns the remainder after number is divided by divisor | 5.074474 | 4.23758 | 1.197494 |
return decimal_pow(conversions.to_decimal(number, ctx), conversions.to_decimal(power, ctx)) | def _power(ctx, number, power) | Returns the result of a number raised to a power | 6.778768 | 6.36409 | 1.065159 |
bottom = conversions.to_integer(bottom, ctx)
top = conversions.to_integer(top, ctx)
return random.randint(bottom, top) | def randbetween(ctx, bottom, top) | Returns a random integer number between the numbers you specify | 3.471315 | 3.273704 | 1.060363 |
number = conversions.to_decimal(number, ctx)
num_digits = conversions.to_integer(num_digits, ctx)
return decimal_round(number, num_digits, ROUND_HALF_UP) | def _round(ctx, number, num_digits) | Rounds a number to a specified number of digits | 3.63587 | 3.433627 | 1.058901 |
number = conversions.to_decimal(number, ctx)
num_digits = conversions.to_integer(num_digits, ctx)
return decimal_round(number, num_digits, ROUND_DOWN) | def rounddown(ctx, number, num_digits) | Rounds a number down, toward zero | 3.697883 | 3.54511 | 1.043094 |
number = conversions.to_decimal(number, ctx)
num_digits = conversions.to_integer(num_digits, ctx)
return decimal_round(number, num_digits, ROUND_UP) | def roundup(ctx, number, num_digits) | Rounds a number up, away from zero | 3.667931 | 3.581466 | 1.024142 |
if len(number) == 0:
raise ValueError("Wrong number of arguments")
result = Decimal(0)
for arg in number:
result += conversions.to_decimal(arg, ctx)
return result | def _sum(ctx, *number) | Returns the sum of all arguments | 4.115091 | 3.771564 | 1.091083 |
return conversions.to_integer(conversions.to_decimal(number, ctx).to_integral_value(ROUND_DOWN), ctx) | def trunc(ctx, number) | Truncates a number to an integer by removing the fractional part of the number | 8.068932 | 7.596632 | 1.062172 |
for arg in logical:
if not conversions.to_boolean(arg, ctx):
return False
return True | def _and(ctx, *logical) | Returns TRUE if and only if all its arguments evaluate to TRUE | 7.336243 | 4.997662 | 1.467935 |
return value_if_true if conversions.to_boolean(logical_test, ctx) else value_if_false | def _if(ctx, logical_test, value_if_true=0, value_if_false=False) | Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE | 5.093346 | 4.972795 | 1.024242 |
for arg in logical:
if conversions.to_boolean(arg, ctx):
return True
return False | def _or(ctx, *logical) | Returns TRUE if any argument is TRUE | 8.262537 | 5.562662 | 1.485357 |
sum1_ij = 1.
for idx, d in zip([i,j], [data1, data2]):
if isinstance(d, field): sum1_ij *= d.wvalue[idx]
elif isinstance(d, points): sum1_ij *= d.weights[idx]
else:
raise NotImplementedError("data type not recognized")
sum2_ij = data1.weights[i] * data2.weights[j]
... | def compute_sum_values(i, j, data1, data2) | Return the sum1_ij and sum2_ij values given
the input indices and data instances.
Notes
-----
This is called in `Binning.update_sums` to compute
the `sum1` and `sum2` contributions for indices `(i,j)`
Parameters
----------
i,j : array_like
the bin indices for these pairs
da... | 3.931746 | 3.376502 | 1.164443 |
dtype = [('inv', 'f8'), ('min', 'f8'), ('max', 'f8'),('N', 'i4'), ('spacing','object')]
dtype = numpy.dtype(dtype)
self._info = numpy.empty(self.Ndim, dtype=dtype)
self.min = self._info['min']
self.max = self._info['max']
self.N = self._inf... | def _setup(self) | Set the binning info we need from the `edges` | 2.397598 | 2.304839 | 1.040245 |
N = len(paircoords[list(paircoords.keys())[0]])
integer = numpy.empty(N, ('i8', (self.Ndim,))).T
# do each dimension
for i, dim in enumerate(self.dims):
if self.spacing[i] == 'linspace':
x = paircoords[dim] - self.min[i]
integer[i] =... | def linear(self, **paircoords) | Linearize bin indices.
This function is called by subclasses. Refer to the source
code of :py:class:`RBinning` for an example.
Parameters
----------
args : list
a list of bin index, (xi, yi, zi, ..)
Returns
-------
linearlized bin index | 2.942282 | 3.204922 | 0.918051 |
# the summation values for this (r,i,j)
sum1_ij, sum2_ij = compute_sum_values(i, j, data1, data2)
# digitize
digr = self.digitize(r, i, j, data1, data2)
if len(digr) == 3 and isinstance(digr[1], dict):
dig, paircoords, weights = digr
elif len(digr) ... | def update_sums(self, r, i, j, data1, data2, sum1, sum2, N=None, centers_sum=None) | The main function that digitizes the pair counts,
calls bincount for the appropriate `sum1` and `sum2`
values, and adds them to the input arrays,
will modify sum1, sum2, N, and centers_sum inplace. | 3.475998 | 3.481953 | 0.99829 |
# the linear shape (put extra dimensions first)
linearshape = [-1] + list(self.shape)
# determine the full shape
subshapes = [list(d.subshape) for d in [data1, data2] if isinstance(d, field)]
subshape = []
if len(subshapes) == 2:
assert subshapes[0] ... | def sum_shapes(self, data1, data2) | Return the shapes of the summation arrays,
given the input data and shape of the bins | 4.17556 | 4.273991 | 0.97697 |
if N is None or centers_sum is None: return
N.flat[:] += utils.bincount(dig, 1., minlength=N.size)
for i, dim in enumerate(self.dims):
size = centers_sum[i].size
centers_sum[i].flat[:] += utils.bincount(dig, paircoords[dim], minlength=size) | def _update_mean_coords(self, dig, N, centers_sum, **paircoords) | Update the mean coordinate sums | 4.311283 | 4.149541 | 1.038978 |
n1, n2 = self.p[i]
# initialize the total arrays for this process
sum1 = numpy.zeros_like(self.sum1g)
sum2 = 1.
if not self.pts_only: sum2 = numpy.zeros_like(self.sum2g)
if self.compute_mean_coords:
N = numpy.zeros_like(self.N)
centers_s... | def work(self, i) | Internal function that performs the pair-counting | 6.213195 | 6.130993 | 1.013408 |
self.sum1g[...] += sum1
if not self.pts_only: self.sum2g[...] += sum2
if self.compute_mean_coords:
N, centers_sum = args
self.N[...] += N
for i in range(self.bins.Ndim):
self.centers[i][...] += centers_sum[i] | def reduce(self, sum1, sum2, *args) | The internal reduce function that sums the results from various
processors | 7.098425 | 7.343287 | 0.966655 |
r
# ensure overwrite flag in passed arguments
kwargs['overwrite_lw'] = True
# log raw weights from log_lik
lw = -log_lik
# compute Pareto smoothed log weights given raw log weights
lw, ks = psislw(lw, **kwargs)
# compute
lw += log_lik
loos = sumlogs(lw, axis=0)
loo = loos.sum... | def psisloo(log_lik, **kwargs) | r"""PSIS leave-one-out log predictive densities.
Computes the log predictive densities given posterior samples of the log
likelihood terms :math:`p(y_i|\theta^s)` in input parameter `log_lik`.
Returns a sum of the leave-one-out log predictive densities `loo`,
individual leave-one-out log predictive den... | 11.746377 | 7.843936 | 1.497511 |
if lw.ndim == 2:
n, m = lw.shape
elif lw.ndim == 1:
n = len(lw)
m = 1
else:
raise ValueError("Argument `lw` must be 1 or 2 dimensional.")
if n <= 1:
raise ValueError("More than one log-weight needed.")
if overwrite_lw and lw.flags.f_contiguous:
#... | def psislw(lw, Reff=1.0, overwrite_lw=False) | Pareto smoothed importance sampling (PSIS).
Parameters
----------
lw : ndarray
Array of size n x m containing m sets of n log weights. It is also
possible to provide one dimensional array of length n.
Reff : scalar, optional
relative MCMC efficiency ``N_eff / N``
overwrite... | 4.922069 | 4.465402 | 1.102268 |
if x.ndim != 1 or len(x) <= 1:
raise ValueError("Invalid input array.")
# check if x should be sorted
if sort is True:
if sort_in_place:
x.sort()
xsorted = True
else:
sort = np.argsort(x)
xsorted = False
elif sort is False:
... | def gpdfitnew(x, sort=True, sort_in_place=False, return_quadrature=False) | Estimate the paramaters for the Generalized Pareto Distribution (GPD)
Returns empirical Bayes estimate for the parameters of the two-parameter
generalized Parato distribution given the data.
Parameters
----------
x : ndarray
One dimensional data array
sort : bool or ndarray, optional
... | 3.48665 | 3.035129 | 1.148765 |
x = np.empty(p.shape)
x.fill(np.nan)
if sigma <= 0:
return x
ok = (p > 0) & (p < 1)
if np.all(ok):
if np.abs(k) < np.finfo(float).eps:
np.negative(p, out=x)
np.log1p(x, out=x)
np.negative(x, out=x)
else:
np.negative(p, out=... | def gpinv(p, k, sigma) | Inverse Generalised Pareto distribution function. | 1.893831 | 1.898788 | 0.997389 |
maxx = x.max(axis=axis, keepdims=True)
xnorm = x - maxx
np.exp(xnorm, out=xnorm)
out = np.sum(xnorm, axis=axis, out=out)
if isinstance(out, np.ndarray):
np.log(out, out=out)
else:
out = np.log(out)
out += np.squeeze(maxx)
return out | def sumlogs(x, axis=None, out=None) | Sum of vector where numbers are represented by their logarithms.
Calculates ``np.log(np.sum(np.exp(x), axis=axis))`` in such a fashion that
it works even when elements have large magnitude. | 2.3371 | 2.36859 | 0.986705 |
for fn in library.__dict__.copy().values():
# ignore imported methods and anything beginning __
if inspect.isfunction(fn) and inspect.getmodule(fn) == library and not fn.__name__.startswith('__'):
name = fn.__name__.lower()
# strip preceding _ ch... | def add_library(self, library) | Adds functions from a library module
:param library: the library module
:return: | 6.116642 | 5.600296 | 1.0922 |
from temba_expressions import EvaluationError, conversions
# find function with given name
func = self.get_function(name)
if func is None:
raise EvaluationError("Undefined function: %s" % name)
args, varargs, defaults = self._get_arg_spec(func)
cal... | def invoke_function(self, ctx, name, arguments) | Invokes the given function
:param ctx: the evaluation context
:param name: the function name (case insensitive)
:param arguments: the arguments to be passed to the function
:return: the function return value | 2.449185 | 2.512742 | 0.974706 |
def func_entry(name, func):
args, varargs, defaults = self._get_arg_spec(func)
# add regular arguments
params = [{'name': str(a), 'optional': a in defaults, 'vararg': False} for a in args if a != 'ctx']
# add possible variable argument
if va... | def build_listing(self) | Builds a listing of all functions sorted A-Z, with their names and descriptions | 3.706615 | 3.406282 | 1.08817 |
args, varargs, keywords, defaults = inspect.getargspec(func)
# build a mapping from argument names to their default values, if any:
if defaults is None:
defaults = {}
else:
defaulted_args = args[-len(defaults):]
defaults = {name: val for name... | def _get_arg_spec(func) | Gets the argument spec of the given function, returning defaults as a dict of param names to values | 3.123401 | 2.963205 | 1.054062 |
"Run ocrmypdf and confirmed that a valid file was created"
p, out, err = run_ocrmypdf(input_file, output_file, *args, env=env)
if p.returncode != 0:
print('stdout\n======')
print(out)
print('stderr\n======')
print(err)
#assert p.returncode == 0
#assert os.path.exists... | def check_ocrmypdf(input_file, output_file, *args, env=None) | Run ocrmypdf and confirmed that a valid file was created | 3.256144 | 2.779027 | 1.171685 |
"Run ocrmypdf and let caller deal with results"
if env is None:
env = os.environ
p_args = OCRMYPDF + list(args) + [input_file, output_file]
p = Popen(
p_args, close_fds=True, stdout=PIPE, stderr=PIPE,
universal_newlines=True, env=env)
out, err = p.communicate()
return p... | def run_ocrmypdf(input_file, output_file, *args, env=None) | Run ocrmypdf and let caller deal with results | 3.362092 | 2.876021 | 1.169008 |
#print("foreignName: %s (%s)"%(mapName, mapName in c.mapNameTranslations))
#if mapName in c.mapNameTranslations:
# return c.mapNameTranslations[mapName]
newName = os.path.basename(mapName)
newName = newName.split(".")[0]
newName = newName.split("(")[0]
newName = re.sub("[LT]E+$", ""... | def standardizeMapName(mapName) | pretty-fy the name for pysc2 map lookup | 3.199758 | 3.2542 | 0.98327 |
'''
Returns a string that contains the Python version and runtime path.
'''
v = sys.version_info
pyver = f'Python {v.major}.{v.minor}.{v.micro}'
if v.releaselevel == 'alpha':
pyver += 'a'
if v.releaselevel == 'beta':
pyver += 'b'
if v.releaselevel == 'candidate':
... | def env_info() | Returns a string that contains the Python version and runtime path. | 2.594377 | 2.078918 | 1.247946 |
'''
Serializes a dict-like object into a generator of the flatten list of
repeating key-value pairs. It is useful when using HMSET method in Redis.
Example:
>>> list(dict2kvlist({'a': 1, 'b': 2}))
['a', 1, 'b', 2]
'''
return chain.from_iterable((k, v) for k, v in o.items()) | def dict2kvlist(o) | Serializes a dict-like object into a generator of the flatten list of
repeating key-value pairs. It is useful when using HMSET method in Redis.
Example:
>>> list(dict2kvlist({'a': 1, 'b': 2}))
['a', 1, 'b', 2] | 5.425482 | 1.564978 | 3.46681 |
'''
A short-hand for retrieving a value from nested mappings
("nested-mapping-get"). At each level it checks if the given "path"
component in the given key exists and return the default value whenever
fails.
Example:
>>> o = {'a':{'b':1}, 'x': None}
>>> nmget(o, 'a', 0)
{'b': 1}
... | def nmget(o, key_path, def_val=None, path_delimiter='.', null_as_default=True) | A short-hand for retrieving a value from nested mappings
("nested-mapping-get"). At each level it checks if the given "path"
component in the given key exists and return the default value whenever
fails.
Example:
>>> o = {'a':{'b':1}, 'x': None}
>>> nmget(o, 'a', 0)
{'b': 1}
>>> nmget(... | 3.105341 | 1.375309 | 2.257922 |
# Ensure main package dir is there (may be absent in script-only packages)
package_dir = os.path.join(base_dir, name)
if not os.path.isdir(package_dir):
os.makedirs(package_dir)
# Open top-level __init__.py and read whole file
init_py = os.path.join(package_dir, '__init__.py')
log.i... | def patch_init_py(base_dir, name, version) | Patch __init__.py to remove version check and append hard-coded version. | 3.897198 | 3.828462 | 1.017954 |
# If 'use_katversion' is False, ignore the rest
if not value:
return
# Enforce the version obtained by katversion, overriding user setting
version = get_version()
if dist.metadata.version is not None:
s = "Ignoring explicit version='{0}' in setup.py, using '{1}' instead"
... | def setuptools_entry(dist, keyword, value) | Setuptools entry point for setting version and baking it into package. | 4.177149 | 4.092522 | 1.020678 |
translator = self._meta['translator']
state = translator.translate(state)
return self.actual_state == state | def is_(self, state) | Check if machine is in given state. | 13.66458 | 8.725937 | 1.565973 |
translator = self._meta['translator']
state = translator.translate(state)
if self._meta['complete']:
return True
if self.actual_state is None:
return True
transitions = self._meta['transitions'][self.actual_state]
return state in transitions | def can_be_(self, state) | Check if machine can transit to given state. | 6.040133 | 4.883963 | 1.236728 |
translator = self._meta['translator']
state = translator.translate(state)
attr = self._meta['state_attribute_name']
setattr(self, attr, state) | def force_set(self, state) | Set new state without checking if transition is allowed. | 6.693218 | 5.23727 | 1.277997 |
if not self.can_be_(state):
state = self._meta['translator'].translate(state)
raise TransitionError(
"Cannot transit from '{actual_value}' to '{value}'."
.format(actual_value=self.actual_state.value, value=state.value)
)
self.force_set(state) | def set_(self, state) | Set new state for machine. | 7.346764 | 6.942482 | 1.058233 |
@property
@wraps(is_)
def getter(self):
return self.is_(value)
return getter | def generate_getter(value) | Generate getter for given value. | 7.355735 | 7.271559 | 1.011576 |
@property
@wraps(can_be_)
def checker(self):
return self.can_be_(value)
return checker | def generate_checker(value) | Generate state checker for given value. | 8.481785 | 8.369766 | 1.013384 |
@wraps(set_)
def setter(self):
self.set_(value)
return setter | def generate_setter(value) | Generate setter for given value. | 10.299316 | 8.825173 | 1.167038 |
if self._check_if_already_proper(value):
return value
try:
return self.search_table[value]
except KeyError:
raise ValueError("Value {value} doesn't match any state.".format(
value=value
)) | def translate(self, value) | Translate value to enum instance.
If value is already enum instance, check if this value belongs to base
enum. | 6.530749 | 5.991018 | 1.09009 |
params = (
('v', self.api_version),
('query', text),
('lang', self.language),
('sessionId', self.session_id),
('timezone', self.timezone),
)
# store query_response if required
if self.query_response:
self.pr... | def _query(self, text) | Takes natural language text and information as query parameters and returns information as JSON. | 3.585064 | 3.18338 | 1.126182 |
dir_path = os.path.dirname(SRC)
is_venv_flag = True
if SYS_NAME == "Windows":
executable_list = ["activate", "pip.exe", "python.exe"]
elif SYS_NAME in ["Darwin", "Linux"]:
executable_list = ["activate", "pip", "python"]
for executable in executable_list:
path = os.path... | def is_venv() | Check whether if this workspace is a virtualenv. | 2.801231 | 2.681708 | 1.04457 |
available_python_version = [
"python2.6",
"python2.7",
"python3.3",
"python3.4",
"python3.5",
"python3.6",
]
dir_path = os.path.dirname(SRC)
for basename in os.listdir(os.path.join(dir_path, BIN_SCRIPTS)):
for python_version in available_pytho... | def find_linux_venv_py_version() | Find python version name used in this virtualenv.
For example: ``python2.7``, ``python3.4`` | 2.791801 | 2.816982 | 0.991061 |
dir_path = os.path.dirname(SRC)
if SYS_NAME == "Windows":
DST = os.path.join(dir_path, "Lib", "site-packages", PKG_NAME)
elif SYS_NAME in ["Darwin", "Linux"]:
python_version = find_linux_venv_py_version()
DST = os.path.join(dir_path, "lib", python_version, "site-packages", PKG_... | def find_venv_DST() | Find where this package should be installed to in this virtualenv.
For example: ``/path-to-venv/lib/python2.7/site-packages/package-name`` | 2.913064 | 3.031759 | 0.960849 |
if SYS_NAME == "Windows":
return os.path.join(site.getsitepackages()[1], PKG_NAME)
elif SYS_NAME in ["Darwin", "Linux"]:
return os.path.join(site.getsitepackages()[0], PKG_NAME) | def find_DST() | Find where this package should be installed to. | 2.987608 | 2.708094 | 1.103214 |
chunk_size = 1024 * 1024
m = hashlib.md5()
with open(abspath, "rb") as f:
while True:
data = f.read(chunk_size)
if not data:
break
m.update(data)
return m.hexdigest() | def md5_of_file(abspath) | Md5 value of a file. | 1.503994 | 1.584783 | 0.949022 |
need_install_flag = False
for root, _, basename_list in os.walk(SRC):
if os.path.basename(root) != "__pycache__":
for basename in basename_list:
src = os.path.join(root, basename)
dst = os.path.join(root.replace(SRC, DST), basename)
if os.... | def check_need_install() | Check if installed package are exactly the same to this one.
By checking md5 value of all files. | 2.519995 | 2.306815 | 1.092413 |
# check installed package
print("Compare to '%s' ..." % DST)
need_install_flag = check_need_install()
if not need_install_flag:
print(" package is up-to-date, no need to install.")
return
print("Difference been found, start installing ...")
# remove __pycache__ folder an... | def install() | Manual install main script. | 3.43151 | 3.42837 | 1.000916 |
'''
Authorize to the docker registry using the given credentials and token scope, and returns a set
of required aiohttp.ClientSession.request() keyword arguments for further API requests.
Some registry servers only rely on HTTP Basic Authentication without token-based access controls
(usually via n... | async def login(
sess: aiohttp.ClientSession,
registry_url: yarl.URL,
credentials: dict,
scope: str) -> dict | Authorize to the docker registry using the given credentials and token scope, and returns a set
of required aiohttp.ClientSession.request() keyword arguments for further API requests.
Some registry servers only rely on HTTP Basic Authentication without token-based access controls
(usually via nginx proxy).... | 3.555661 | 2.396242 | 1.483849 |
try:
repo_dir = run_cmd(path, 'git', 'rev-parse', '--git-dir')
return True if repo_dir else False
except (OSError, RuntimeError):
return False | def is_git(path) | Return True if this is a git repo. | 3.693109 | 3.58538 | 1.030047 |
dt = str(time.strftime('%Y%m%d%H%M'))
if scm:
version = "0.0+unknown.{0}.{1}".format(scm, dt)
else:
version = "0.0+unknown." + dt
return version | def date_version(scm=None) | Generate a version string based on the SCM type and the date. | 3.502882 | 3.204741 | 1.093031 |
# Get name of current branch (or 'HEAD' for a detached HEAD)
branch_name = run_cmd(path, 'git', 'rev-parse', '--abbrev-ref', 'HEAD')
branch_name = re.sub(r"[^A-Za-z0-9]+", ".", branch_name.strip())
return branch_name | def get_git_cleaned_branch_name(path) | Get the git branch name of the current HEAD in path. The branch name is
scrubbed to conform to PEP-440.
PEP-440 Local version identifiers shall only consist out of:
- ASCII letters ( [a-zA-Z] )
- ASCII digits ( [0-9] )
- periods ( . )
https://www.python.org/dev/peps/pep-0440/#local-version-iden... | 3.190162 | 3.359751 | 0.949523 |
branch_name = get_git_cleaned_branch_name(path)
# Determine whether working copy is dirty (i.e. contains modified files)
mods = run_cmd(path, 'git', 'status', '--porcelain', '--untracked-files=no')
dirty = '.dirty' if mods else ''
# Get a list of all commits on branch, with corresponding branch... | def get_git_version(path) | Get the GIT version. | 4.607437 | 4.613364 | 0.998715 |
if is_git(path):
return 'git', get_git_version(path)
elif is_svn(path):
return 'svn', get_svn_version(path)
return None, None | def get_version_from_scm(path=None) | Get the current version string of this package using SCM tool.
Parameters
----------
path : None or string, optional
The SCM checkout path (default is current directory)
Returns
-------
version : string
The version string for this package | 2.591162 | 3.399535 | 0.762211 |
if module is not None:
# Setup.py will not pass in a module, but creating __version__ from
# __init__ will.
module = str(module).split('.', 1)[0]
try:
package = pkg_resources.get_distribution(module)
return package.version
except pkg_resources.Dis... | def get_version_from_module(module) | Use pkg_resources to get version of installed module by name. | 6.852838 | 6.045775 | 1.133492 |
if type(value) is bytes:
try:
return value.decode('utf-8')
except UnicodeDecodeError:
return value.decode('latin1')
return value | def _must_decode(value) | Copied from pkginfo 1.4.1, _compat module. | 2.423903 | 2.06741 | 1.172434 |
# This is a condensed version of the relevant code in pkginfo 1.4.1
try:
with open(os.path.join(path, 'PKG-INFO')) as f:
data = f.read()
except IOError:
# Could not load path as an unpacked sdist as it had no PKG-INFO file
return
fp = StringIO(_must_decode(data))... | def get_version_from_unpacked_sdist(path) | Assume path points to unpacked source distribution and get version. | 5.727969 | 5.394531 | 1.06181 |
filename = os.path.join(path, VERSION_FILE)
if not os.path.isfile(filename):
# Look in the parent directory of path instead.
filename = os.path.join(os.path.dirname(path), VERSION_FILE)
if not os.path.isfile(filename):
filename = ''
if filename:
with open(fi... | def get_version_from_file(path) | Find the VERSION_FILE and return its contents.
Returns
-------
version : string or None | 2.350437 | 2.313907 | 1.015787 |
norm_version = pkg_resources.parse_version(version)
if not isinstance(norm_version, tuple):
# Let setuptools (>= 8) do the normalisation
return str(norm_version)
else:
# Homegrown normalisation for older setuptools (< 8)
public, sep, local = version.lower().partition('+'... | def normalised(version) | Normalise a version string according to PEP 440, if possible. | 4.53843 | 4.300723 | 1.055272 |
# Check the module option first.
version = get_version_from_module(module)
if version:
return normalised(version)
# Turn path into a valid directory (default is current directory)
if path is None:
path = os.getcwd()
path = os.path.abspath(path)
if os.path.exists(path) a... | def get_version(path=None, module=None) | Return the version string.
This function ensures that the version string complies with PEP 440.
The format of our version string is:
- for RELEASE builds:
<major>.<minor>
e.g.
0.1
2.4
- for DEVELOPMENT builds:
<major>.<minor>.dev<num_b... | 3.471887 | 3.32723 | 1.043477 |
v0 = str(version[0])
if v0:
# Test if the major is a number.
try:
v0 = v0.lstrip("v").lstrip("V")
# Handle the common case where tags have v before major.
v0 = int(v0)
except ValueError:
v0 = None
if v0 is None:
version = ... | def _sane_version_list(version) | Ensure the major and minor are int.
Parameters
----------
version: list
Version components
Returns
-------
version: list
List of components where first two components has been sanitised | 3.693448 | 3.74432 | 0.986414 |
major = 0
minor = 0
patch = '' # PEP440 calls this prerelease, postrelease or devrelease
ver = get_version(path, module)
if ver is not None:
ver_segments = _sane_version_list(ver.split(".", 2))
major = ver_segments[0]
minor = ver_segments[1]
patch = ".".join(ver... | def get_version_list(path=None, module=None) | Return the version information as a tuple.
This uses get_version and breaks the string up. Would make more sense if
the version was a tuple throughout katversion. | 6.433624 | 6.3798 | 1.008437 |
verlist = get_version_list(path, module)
verlist[0] = name
return tuple(verlist) | def build_info(name, path=None, module=None) | Return the build info tuple. | 6.582435 | 5.530287 | 1.190252 |
return self.indices[self.offset[groupid]
:self.offset[groupid]+ self.length[groupid]] | def find(self, groupid) | return all of the indices of particles of groupid | 7.150869 | 5.861787 | 1.219913 |
if weights is None:
weights = self.data.weights
return utils.bincount(self.labels, weights, self.N) | def sum(self, weights=None) | return the sum of weights of each object | 7.396164 | 6.747606 | 1.096117 |
if weights is None:
weights = self.data.weights
mass = utils.bincount(self.labels, weights, self.N)
cp = numpy.empty((len(mass), self.data.pos.shape[-1]), 'f8')
for d in range(self.data.pos.shape[-1]):
cp[..., d] = utils.bincount(self.labels, weights *
... | def center(self, weights=None) | return the center of each object | 3.872705 | 3.650011 | 1.061012 |
if not paramName is None:
if not paramId is None:
if getParameterTypeNameFromID(paramId) != paramName:
raise ValueError("Parameters paramId and paramName "
+ "passed to ParamSample.getParamValues() are incompat... | def getParamValues(self, paramName=None, paramId=None, useOnlyValids=True) | Return the rows of sampleDF that are associated to the parameter
specified in paramName. | 4.614964 | 4.127605 | 1.118073 |
self.__operations.append(["interpolate", interpValues])
df = self.sampleDF
self.interpValues = interpValues
for interParamName, value in interpValues.items():
self.__report += "Interpolation of the parameters for independent variables '" \... | def interpolate(self, interpValues) | interpValues should be a dictionnary where the keys are the parameter names
for the independant variable for which interpolation should be run and
the values are the value to which the parameter should be interpolated. | 7.493709 | 7.074851 | 1.059204 |
## TODO: confirm that dimensions for psisloo1 & psisloo2 are the same
loores = psisloo1.pointwise.join(
psisloo2.pointwise,
lsuffix = '_m1',
rsuffix = '_m2')
loores['pw_diff'] = loores.pointwise_elpd_m2 - loores.pointwise_elpd_m1
sum_elpd_diff = loores.apply(numpy.sum).pw_... | def loo_compare(psisloo1, psisloo2) | Compares two models using pointwise approximate leave-one-out cross validation.
For the method to be valid, the two models should have been fit on the same input data.
Parameters
-------------------
psisloo1 : Psisloo object for model1
psisloo2 : Psisloo object for model2
Returns
---... | 4.171728 | 3.681679 | 1.133105 |
seaborn.pointplot(
y = self.pointwise.pareto_k,
x = self.pointwise.index,
join = False) | def plot(self) | Graphical summary of pointwise pareto-k importance-sampling indices
Pareto-k tail indices are plotted (on the y axis) for each observation unit (on the x axis) | 14.654449 | 7.081581 | 2.069375 |
if formula == '':
return
_new_stack = _utilities.formula_to_dictionary(formula=formula,
thickness=thickness,
density=density,
... | def add_layer(self, formula='', thickness=np.NaN, density=np.NaN) | provide another way to define the layers (stack)
Parameters:
===========
formula: string
ex: 'CoAg2'
ex: 'Al'
thickness: float (in mm)
density: float (g/cm3) | 7.573208 | 7.893315 | 0.959446 |
_stack = self.stack
compound = str(compound)
if compound == '':
_list_compounds = _stack.keys()
list_all_dict = {}
for _compound in _list_compounds:
_compound = str(_compound)
_list_element = _stack[_compound]['element... | def get_isotopic_ratio(self, compound='', element='') | returns the list of isotopes for the element of the compound defined with their stoichiometric values
Parameters:
===========
compound: string (default is empty). If empty, all the stoichiometric will be displayed
element: string (default is same as compound).
Raises:
=... | 2.575352 | 2.572533 | 1.001096 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.