code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
r = np.empty(self.size, np.int)
r[self.sorter] = np.arange(self.size)
return r | def rank(self) | how high in sorted list each key is. inverse permutation of sorter, such that sorted[rank]==keys | 4.994692 | 3.291615 | 1.517399 |
return tuple(
(array_as_typed(s, k.dtype, k.shape) if k.ndim>1 else s)[self.start]
for s, k in zip(self.sorted, self._keys)) | def unique(self) | returns a tuple of unique key columns | 13.383467 | 12.357882 | 1.08299 |
columns = [np.asarray(c) for c in columns]
rows = len(columns[0])
names = ['f'+str(i) for i in range(len(columns))]
dtype = [(names[i], c.dtype, c.shape[1:]) for i, c in enumerate(columns)]
data = np.empty(rows, dtype)
for i, c in enumerate(columns):
data[names[i]] = c
return d... | def as_struct_array(*columns) | pack a sequence of columns into a recarray
Parameters
----------
columns : sequence of key objects
Returns
-------
data : recarray
recarray containing the input columns as struct fields | 2.328661 | 2.787115 | 0.83551 |
shape = arr.shape
# make axis to be viewed as a void object as contiguous items
arr = np.ascontiguousarray(np.rollaxis(arr, axis, arr.ndim))
# number of bytes in each void object
nbytes = arr.dtype.itemsize * shape[axis]
# void type with the correct number of bytes
voidtype = np.dtype((... | def axis_as_object(arr, axis=-1) | cast the given axis of an array to a void object
if the axis to be cast is contiguous, a view is returned, otherwise a copy is made
this is useful for efficiently sorting by the content of an axis, for instance
Parameters
----------
arr : ndarray
array to view as void object type
axis :... | 5.201216 | 5.103923 | 1.019062 |
# view the void objects as typed elements
arr = arr.view(dtype).reshape(arr.shape + (-1,))
# put the axis in the specified location
return np.rollaxis(arr, -1, axis) | def object_as_axis(arr, dtype, axis=-1) | cast an array of void objects to a typed axis
Parameters
----------
arr : ndarray, [ndim], void
array of type np.void
dtype : numpy dtype object
the output dtype to cast the input array to
axis : int
position to insert the newly formed axis into
Returns
-------
... | 7.001359 | 7.52247 | 0.930726 |
index = as_index(keys, axis, base=True)
return index.unique, index.count | def count(keys, axis=semantics.axis_default) | count the number of times each key occurs in the input set
Arguments
---------
keys : indexable object
Returns
-------
unique : ndarray, [groups, ...]
unique keys
count : ndarray, [groups], int
the number of times each key occurs in the input set
Notes
-----
Ca... | 11.176077 | 11.154824 | 1.001905 |
indices = [as_index(k, axis=0) for k in keys]
uniques = [i.unique for i in indices]
inverses = [i.inverse for i in indices]
shape = [i.groups for i in indices]
table = np.zeros(shape, np.int)
np.add.at(table, inverses, 1)
return tuple(uniques), table | def count_table(*keys) | count the number of times each key occurs in the input set
Arguments
---------
keys : tuple of indexable objects, each having the same number of items
Returns
-------
unique : tuple of ndarray, [groups, ...]
unique keys for each input item
they form the axes labels of the table... | 4.174549 | 3.656877 | 1.141561 |
if isinstance(keys, tuple):
n_keys = len(keys)
else:
n_keys = 1
bins = np.linspace(start, end, count+1, endpoint=True)
idx = np.searchsorted(bins, keys)
if axes is None:
axes = [-1] | def binning(keys, start, end, count, axes=None) | Perform binning over the given axes of the keys
Parameters
----------
keys : indexable or tuple of indexable
Examples
--------
binning(np.random.rand(100), 0, 1, 10) | 2.577459 | 3.173859 | 0.81209 |
index = as_index(keys, axis)
return index.count[index.inverse] | def multiplicity(keys, axis=semantics.axis_default) | return the multiplicity of each key, or how often it occurs in the set
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
the number of times each input item occurs in the set | 13.430074 | 24.751822 | 0.542589 |
index = as_index(keys, axis)
return index.rank | def rank(keys, axis=semantics.axis_default) | where each item is in the pecking order.
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
unique integers, ranking the sorting order
Notes
-----
we should have that index.sorted[index.rank] == keys | 8.084949 | 11.534764 | 0.70092 |
index = as_index(keys, axis)
if weights is None:
unique, weights = count(index)
else:
unique, weights = group_by(index).sum(weights)
bin = np.argmax(weights)
_mode = unique[bin] # FIXME: replace with index.take for lexindex compatibility?
if return_indices:
indic... | def mode(keys, axis=semantics.axis_default, weights=None, return_indices=False) | compute the mode, or most frequent occuring key in a set
Parameters
----------
keys : ndarray, [n_keys, ...]
input array. elements of 'keys' can have arbitrary shape or dtype
weights : ndarray, [n_keys], optional
if given, the contribution of each key to the mode is weighted by the give... | 6.089935 | 8.211064 | 0.741674 |
return GroupBy(boundary).split(np.arange(boundary.size) // boundary.shape[1]) | def incidence(boundary) | given an Nxm matrix containing boundary info between simplices,
compute indidence info matrix
not very reusable; should probably not be in this lib | 19.625303 | 21.40118 | 0.91702 |
index = as_index(keys, axis)
return index.groups == index.size | def all_unique(keys, axis=semantics.axis_default) | Returns true if all keys are unique | 10.91151 | 13.241647 | 0.82403 |
index = as_index(keys, axis)
return np.any(index.count == 1) | def any_unique(keys, axis=semantics.axis_default) | returns true if any of the keys is unique | 6.904295 | 8.316444 | 0.830198 |
index = as_index(keys, axis)
return index.groups == 1 | def all_equal(keys, axis=semantics.axis_default) | returns true of all keys are equal | 10.247488 | 11.565083 | 0.886071 |
index = as_index(keys, axis)
return index.uniform | def is_uniform(keys, axis=semantics.axis_default) | returns true if all keys have equal multiplicity | 10.838114 | 14.410506 | 0.752098 |
return tuple([as_index(k, axis=0).inverse for k in keys]) | def get_inverses(self, keys) | Returns
-------
Tuple of inverse indices | 18.691313 | 14.532937 | 1.286135 |
_, count = self.count()
if not np.array_equiv(count, 1):
raise ValueError("Not every entry in the table is assigned a unique value")
return self.sum(values) | def unique(self, values) | Place each entry in a table, while asserting that each entry occurs once | 9.51018 | 7.631426 | 1.246186 |
stable = return_index or return_inverse
index = as_index(keys, axis, base = not stable, stable = stable)
ret = index.unique,
if return_index:
ret = ret + (index.index,)
if return_inverse:
ret = ret + (index.inverse,)
if return_count:
ret = ret + (index.count,)
r... | def unique(keys, axis=semantics.axis_default, return_index=False, return_inverse=False, return_count=False) | compute the set of unique keys
Parameters
----------
keys : indexable key object
keys object to find unique keys within
axis : int
if keys is a multi-dimensional array, the axis to regard as the sequence of key objects
return_index : bool
if True, return indexes such that ke... | 3.598121 | 4.161921 | 0.864534 |
this = as_index(this, axis=axis, lex_as_struct=True, base=True)
that = as_index(that, axis=axis, lex_as_struct=True)
left = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side='left')
right = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side='right')
flags = np.zer... | def contains(this, that, axis=semantics.axis_default) | Returns bool for each element of `that`, indicating if it is contained in `this`
Parameters
----------
this : indexable key sequence
sequence of items to test against
that : indexable key sequence
sequence of items to test for
Returns
-------
ndarray, [that.size], bool
... | 2.864373 | 3.248382 | 0.881784 |
this = as_index(this, axis=axis, lex_as_struct=True, base=True)
that = as_index(that, axis=axis, lex_as_struct=True)
left = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side='left')
right = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side='right')
return left !=... | def in_(this, that, axis=semantics.axis_default) | Returns bool for each element of `this`, indicating if it is present in `that`
Parameters
----------
this : indexable key sequence
sequence of items to test for
that : indexable key sequence
sequence of items to test against
Returns
-------
ndarray, [that.size], bool
... | 3.348789 | 4.003438 | 0.836478 |
this = as_index(this, axis=axis, lex_as_struct=True)
# use this for getting this.keys and that.keys organized the same way;
# sorting is superfluous though. make sorting a cached property?
# should we be working with cached properties generally?
# or we should use sorted values, if searchsorted... | def indices(this, that, axis=semantics.axis_default, missing='raise') | Find indices such that this[indices] == that
If multiple indices satisfy this condition, the first index found is returned
Parameters
----------
this : indexable object
items to search in
that : indexable object
items to search for
axis : int, optional
axis to operate on... | 7.196401 | 7.341853 | 0.980189 |
input = np.asarray(input) # FIXME: currently instances of Index are not allowed
values = np.asarray(values)
if missing == 'ignore':
idx = indices(keys, input, missing='mask')
mask = np.logical_not(idx.mask)
idx = idx.data
elif missing == 'raise':
idx = indices(keys... | def remap(input, keys, values, missing='ignore', inplace=False) | Given an input array, remap its entries corresponding to 'keys' to 'values'
equivalent of output = [map.get(i, default=i) for i in input],
if map were a dictionary of corresponding keys and values
Parameters
----------
input : ndarray, [...]
values to perform replacements in
keys : ndar... | 3.4274 | 4.217052 | 0.812748 |
axis = kwargs.get('axis', semantics.axis_default)
assume_unique = kwargs.get('assume_unique', False)
if assume_unique:
sets = [as_index(s, axis=axis).unique for s in sets]
else:
sets = [as_index(s, axis=axis).unique for s in sets]
return sets | def _set_preprocess(sets, **kwargs) | upcasts a sequence of indexable objects to Index objets according to the given kwargs
Parameters
----------
sets : iterable of indexable objects
axis : int, optional
axis to view as item sequence
assume_unique : bool, optional
if we should assume the items sequence does not contain ... | 4.059305 | 3.59619 | 1.128779 |
def con(set):
# if not all():
# raise ValueError('concatenated keys must have the same dtype')
try:
return np.concatenate([s for s in sets if len(s)])
except ValueError:
return set[0]
if any(not isinstance(s, tuple) for s in sets):
#assum... | def _set_concatenate(sets) | concatenate indexable objects.
Parameters
----------
sets : iterable of indexable objects
Returns
-------
indexable object
handles both arrays and tuples of arrays | 5.274902 | 4.819769 | 1.09443 |
sets = _set_preprocess(sets, **kwargs)
i = as_index(_set_concatenate(sets), axis=0, base=True)
# FIXME : this does not work for lex-keys
return i.unique[i.count == n] | def _set_count(sets, n, **kwargs) | return the elements which occur n times over the sequence of sets
Parameters
----------
sets : iterable of indexable objects
n : int
number of sets the element should occur in
Returns
-------
indexable
indexable with all elements that occured in n of the sets
Notes
... | 14.783723 | 15.64732 | 0.944809 |
sets = _set_preprocess(sets, **kwargs)
return as_index( _set_concatenate(sets), axis=0, base=True).unique | def union(*sets, **kwargs) | all unique items which occur in any one of the sets
Parameters
----------
sets : tuple of indexable objects
Returns
-------
union of all items in all sets | 17.677912 | 24.105276 | 0.733363 |
head, tail = sets[0], sets[1:]
idx = as_index(head, **kwargs)
lhs = idx.unique
rhs = [intersection(idx, s, **kwargs) for s in tail]
return exclusive(lhs, *rhs, axis=0, assume_unique=True) | def difference(*sets, **kwargs) | subtracts all tail sets from the head set
Parameters
----------
sets : tuple of indexable objects
first set is the head, from which we subtract
other items form the tail, which are subtracted from head
Returns
-------
items which are in the head but not in any of the tail sets
... | 5.73668 | 5.528996 | 1.037563 |
choices = (random.randrange(0, 52) for _ in range(digits))
return prefix + "".join((string.ascii_letters[x] for x in choices)) | def _generate_div_id_chart(prefix="chart_id", digits=8) | Generate a random id for div chart. | 5.660733 | 4.505752 | 1.256335 |
if chart_type not in ("default", "stock"):
raise ValueError("Wrong chart_type: accept 'default' or 'stock'.")
chart_id = render_to if render_to is not None else _generate_div_id_chart()
json_data = serialize(df, render_to=chart_id, chart_type=chart_type,
**kwargs)
... | def display_charts(df, chart_type="default", render_to=None, **kwargs) | Display you DataFrame with Highcharts.
df: DataFrame
chart_type: str
'default' or 'stock'
render_to: str
div id for plotting your data | 4.148396 | 4.085623 | 1.015364 |
data = copy.deepcopy(data)
if "series" in data:
for series in data["series"]:
series["data"] = "[...]"
return data | def _series_data_filter(data) | Replace each 'data' key in the list stored under 'series' by "[...]".
Use to not store and display the series data when you just want display and
modify the Highcharts parameters.
data: dict
Serialized DataFrame in a dict for Highcharts
Returns: a dict with filtered values
See also `core... | 4.706027 | 3.724329 | 1.263591 |
data_to_print = _series_data_filter(data)
print(json.dumps(data_to_print, indent=indent)) | def pretty_params(data, indent=2) | Pretty print your Highcharts params (into a JSON).
data: dict
Serialized DataFrame in a dict for Highcharts | 5.75215 | 6.406877 | 0.897809 |
# TODO: Move these params to their own vertical if needed.
polling_params = [
'locationschema',
'carrierschema',
'sorttype',
'sortorder',
'originairports',
'destinationairports',
'stops',
'outboundd... | def get_additional_params(self, **params) | Filter to get the additional params needed for polling | 4.558613 | 4.190409 | 1.087868 |
additional_params = self.get_additional_params(**params)
return self.poll_session(
self.create_session(**params),
errors=errors,
**additional_params
) | def get_result(self, errors=GRACEFUL, **params) | Get all results, no filtering, etc. by creating and polling the
session. | 4.764905 | 3.798654 | 1.254367 |
error_modes = (STRICT, GRACEFUL, IGNORE)
error_mode = errors or GRACEFUL
if error_mode.lower() not in error_modes:
raise ValueError(
'Possible values for errors argument are: %s' %
', '.join(error_modes)
)
if callback is N... | def make_request(self, service_url, method='get', headers=None, data=None,
callback=None, errors=GRACEFUL, **params) | Reusable method for performing requests.
:param service_url - URL to request
:param method - request method, default is 'get'
:param headers - request headers
:param data - post data
:param callback - callback to be applied to response,
default callback... | 2.716964 | 2.815888 | 0.964869 |
url = "{url}/{market}".format(url=self.MARKET_SERVICE_URL,
market=market)
return self.make_request(url, headers=self._headers()) | def get_markets(self, market) | Get the list of markets
http://business.skyscanner.net/portal/en-GB/Documentation/Markets | 4.874295 | 4.072505 | 1.196879 |
service_url = "{url}/{params_path}".format(
url=self.LOCATION_AUTOSUGGEST_URL,
params_path=self._construct_params(
params, self.LOCATION_AUTOSUGGEST_PARAMS)
)
return self.make_request(
service_url,
headers=self._headers(),
... | def location_autosuggest(self, **params) | Location Autosuggest Services
Doc URLs:
http://business.skyscanner.net/portal/en-GB/
Documentation/Autosuggest
http://business.skyscanner.net/portal/en-GB/
Documentation/CarHireAutoSuggest
http://business.skyscanner.net/portal/en-GB/
Doc... | 3.853732 | 3.77323 | 1.021335 |
time.sleep(initial_delay)
poll_response = None
for n in range(tries):
poll_response = self.make_request(
poll_url,
headers=self._headers(),
errors=errors, **params
)
if self.is_poll_complete(poll_respon... | def poll_session(self, poll_url, initial_delay=2, delay=1, tries=20,
errors=GRACEFUL, **params) | Poll the URL
:param poll_url - URL to poll,
should be returned by 'create_session' call
:param initial_delay - specifies how many seconds to wait before
the first poll
:param delay - specifies how many seconds to wait between the polls
... | 3.249698 | 3.429098 | 0.947683 |
try:
params_list = [params.pop(key) for key in required_keys]
except KeyError as e:
raise MissingParameter(
'Missing expected request parameter: %s' % e)
if opt_keys:
params_list.extend([params.pop(key)
... | def _construct_params(params, required_keys, opt_keys=None) | Construct params list in order of given keys. | 2.620909 | 2.520293 | 1.039922 |
return self.make_request(self.PRICING_SESSION_URL,
method='post',
headers=self._session_headers(),
callback=lambda resp: resp.headers[
'location'],
... | def create_session(self, **params) | Create the session
date format: YYYY-mm-dd
location: ISO code | 7.047638 | 7.058264 | 0.998495 |
return self.make_request("%s/booking" % poll_url,
method='put',
headers=self._headers(),
callback=lambda resp: resp.headers[
'location'],
... | def request_booking_details(self, poll_url, **params) | Request for booking details
URL Format:
{API_HOST}/apiservices/pricing/v1.0/{session key}/booking
?apiKey={apiKey} | 6.859715 | 7.616297 | 0.900663 |
service_url = "{url}/{params_path}".format(
url=self.BROWSE_DATES_SERVICE_URL,
params_path=self._construct_params(
params, self._REQ_PARAMS, self._OPT_PARAMS)
)
return self.make_request(
service_url,
headers=self._headers(... | def get_cheapest_price_by_date(self, **params) | {API_HOST}/apiservices/browsedates/v1.0/{market}/{currency}/{locale}/
{originPlace}/{destinationPlace}/
{outboundPartialDate}/{inboundPartialDate}
?apiKey={apiKey} | 5.311927 | 4.92776 | 1.07796 |
service_url = "{url}/{params_path}".format(
url=self.BROWSE_ROUTES_SERVICE_URL,
params_path=self._construct_params(
params, self._REQ_PARAMS, self._OPT_PARAMS)
)
return self.make_request(
service_url,
headers=self._headers... | def get_cheapest_price_by_route(self, **params) | {API_HOST}/apiservices/browseroutes/v1.0/{market}/{currency}/{locale}/
{originPlace}/{destinationPlace}/
{outboundPartialDate}/{inboundPartialDate}
?apiKey={apiKey} | 5.551254 | 5.351139 | 1.037397 |
service_url = "{url}/{params_path}".format(
url=self.BROWSE_QUOTES_SERVICE_URL,
params_path=self._construct_params(
params, self._REQ_PARAMS, self._OPT_PARAMS)
)
return self.make_request(
service_url,
headers=self._headers(... | def get_cheapest_quotes(self, **params) | {API_HOST}/apiservices/browsequotes/v1.0/{market}/{currency}/{locale}/
{originPlace}/{destinationPlace}/
{outboundPartialDate}/{inboundPartialDate}
?apiKey={apiKey} | 4.82769 | 4.7776 | 1.010484 |
service_url = "{url}/{params_path}".format(
url=self.BROWSE_GRID_SERVICE_URL,
params_path=self._construct_params(
params, self._REQ_PARAMS, self._OPT_PARAMS)
)
return self.make_request(
service_url,
headers=self._headers(),... | def get_grid_prices_by_date(self, **params) | {API_HOST}/apiservices/browsegrid/v1.0/{market}/{currency}/{locale}/
{originPlace}/{destinationPlace}/
{outboundPartialDate}/{inboundPartialDate}
?apiKey={apiKey} | 4.946433 | 4.639755 | 1.066098 |
required_keys = ('market', 'currency', 'locale', 'pickupplace',
'dropoffplace', 'pickupdatetime', 'dropoffdatetime',
'driverage')
service_url = "{url}/{params_path}".format(
url=self.PRICING_SESSION_URL,
params_path=sel... | def create_session(self, **params) | Create the session
date format: YYYY-MM-DDThh:mm
location: ISO code | 6.31413 | 6.047819 | 1.044034 |
qs = QueryDict(args)
per_line = qs.get('per_line', 1)
field = qs.get("field", "slug")
command = qs.get("command")
convert = lambda element: "/" + command + " " + str(getattr(element, field))
group = lambda flat, size: [flat[i:i+size] for i in range(0, len(flat), size)]
grouped = group(v... | def keyboard_field(value, args=None) | Format keyboard /command field. | 4.241617 | 3.997132 | 1.061165 |
if self.queryset is None:
if self.model:
return self.model._default_manager.all()
else:
raise ImproperlyConfigured(
"%(cls)s is missing a QuerySet. Define "
"%(cls)s.model, %(cls)s.queryset, or override "
... | def get_queryset(self) | Return the `QuerySet` that will be used to look up the object.
Note that this method is called by the default implementation of
`get_object` and may not be called if `get_object` is overridden. | 1.544572 | 1.506942 | 1.024971 |
@wraps(view_func)
def wrapper(bot, update, **kwargs):
chat = Chat.objects.get(id=update.message.chat.id)
if chat.is_authenticated():
return view_func(bot, update, **kwargs)
from telegrambot.bot_views.login import LoginBotView
login_command_view = LoginBotView.as_... | def login_required(view_func) | Decorator for command views that checks that the chat is authenticated,
sends message with link for authenticated if necessary. | 3.756521 | 3.366732 | 1.115777 |
@wraps(func)
def pipe_util_wrapper(function, *args, **kwargs):
if isinstance(function, XObject):
function = ~function
original_function = function
if args or kwargs:
function = xpartial(function, *args, **kwargs)
name = lambda: '%s(%s)' % (get_name... | def pipe_util(func) | Decorator that handles X objects and partial application for pipe-utils. | 4.756761 | 4.434705 | 1.072622 |
@wraps(func)
def auto_string_formatter_wrapper(function, *args, **kwargs):
if isinstance(function, string_types):
function = StringFormatter(function)
return func(function, *args, **kwargs)
return auto_string_formatter_wrapper | def auto_string_formatter(func) | Decorator that handles automatic string formatting.
By converting a string argument to a function that does formatting on said
string. | 2.456007 | 2.667451 | 0.920732 |
@wraps(func)
def ds_builder_wrapper(function, *args, **kwargs):
try:
function = DSBuilder(function)
except NoBuilder:
pass
return func(function, *args, **kwargs)
return ds_builder_wrapper | def data_structure_builder(func) | Decorator to handle automatic data structure creation for pipe-utils. | 3.785172 | 3.549798 | 1.066306 |
@wraps(func)
def regex_condition_wrapper(condition, *args, **kwargs):
if isinstance(condition, string_types):
condition = maybe | partial(re.match, condition)
return func(condition, *args, **kwargs)
return regex_condition_wrapper | def regex_condition(func) | If a condition is given as string instead of a function, it is turned
into a regex-matching function. | 3.353076 | 3.234387 | 1.036696 |
f = partial(sorted, key=function)
f.attrs = {'descending': _descending_sort_by(function)}
return f | def sort_by(function) | Sorts an incoming sequence by using the given `function` as key.
>>> range(10) > sort_by(-X)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Supports automatic data-structure creation::
users > sort_by([X.last_name, X.first_name])
There is also a shortcut for ``sort_by(X)`` called ``sort``:
>>> [4, 5, 8... | 7.13179 | 14.62424 | 0.487669 |
def _take_first(iterable):
return islice(iterable, count)
return pipe | set_name('take_first(%s)' % count, _take_first) | def take_first(count) | Assumes an iterable on the input, returns an iterable with first `count`
items from the input (or possibly less, if there isn't that many).
>>> range(9000) > where(X % 100 == 0) | take_first(5) | tuple
(0, 100, 200, 300, 400) | 5.493203 | 6.895904 | 0.796589 |
def _drop_first(iterable):
g = (x for x in range(1, count + 1))
return dropwhile(
lambda i: unless(StopIteration, lambda: next(g))(), iterable)
return pipe | set_name('drop_first(%s)' % count, _drop_first) | def drop_first(count) | Assumes an iterable on the input, returns an iterable with identical items
except for the first `count`.
>>> range(10) > drop_first(5) | tuple
(5, 6, 7, 8, 9) | 7.034068 | 8.556079 | 0.822114 |
@pipe_util
@auto_string_formatter
@data_structure_builder
def construct_unless(function):
# a wrapper so we can re-use the decorators
def _unless(*args, **kwargs):
try:
return function(*args, **kwargs)
except exception_class_or_tuple:
... | def unless(exception_class_or_tuple, func, *args, **kwargs) | When `exception_class_or_tuple` occurs while executing `func`, it will
be caught and ``None`` will be returned.
>>> f = where(X > 10) | list | unless(IndexError, X[0])
>>> f([5, 8, 12, 4])
12
>>> f([1, 2, 3])
None | 5.641236 | 6.015335 | 0.937809 |
def _group_by(seq):
result = {}
for item in seq:
result.setdefault(function(item), []).append(item)
return dict_items(result)
return _group_by | def group_by(function) | Groups input sequence by `function`.
Returns an iterator over a sequence of tuples where the first item is a
result of `function` and the second one a list of items matching this
result.
Ordering of the resulting iterator is undefined, but ordering of the items
in the groups is preserved.
>>>... | 2.899941 | 4.33156 | 0.669491 |
f = partial(takewhile, pipe | condition | operator.not_)
f.attrs = {'including': take_until_including(condition)}
return f | def take_until(condition) | >>> [1, 4, 6, 4, 1] > take_until(X > 5) | list
[1, 4]
>>> [1, 4, 6, 4, 1] > take_until(X > 5).including | list
[1, 4, 6] | 17.154676 | 25.096085 | 0.68356 |
def take_until_including_(interable):
for i in interable:
if not condition(i):
yield i
else:
yield i
break
return take_until_including_ | def take_until_including(condition) | >>> [1, 4, 6, 4, 1] > take_until_including(X > 5) | list
[1, 4, 6] | 4.271143 | 4.536774 | 0.94145 |
any_x = any(isinstance(a, XObject) for a in xargs + tuple(xkwargs.values()))
use = lambda x, value: (~x)(value) if isinstance(x, XObject) else x
@wraps(func, assigned=filter(partial(hasattr, func), WRAPPER_ASSIGNMENTS))
def xpartially_applied(*func_args, **func_kwargs):
if any_x:
... | def xpartial(func, *xargs, **xkwargs) | Like :func:`functools.partial`, but can take an :class:`XObject`
placeholder that will be replaced with the first positional argument
when the partially applied function is called.
Useful when the function's positional arguments' order doesn't fit your
situation, e.g.:
>>> reverse_range = xpartial... | 3.416798 | 3.669575 | 0.931116 |
ut1 = jdays2000(utc_time) / 36525.0
theta = 67310.54841 + ut1 * (876600 * 3600 + 8640184.812866 + ut1 *
(0.093104 - ut1 * 6.2 * 10e-6))
return np.deg2rad(theta / 240.0) % (2 * np.pi) | def gmst(utc_time) | Greenwich mean sidereal utc_time, in radians.
As defined in the AIAA 2006 implementation:
http://www.celestrak.com/publications/AIAA/2006-6753/ | 2.945322 | 2.97762 | 0.989153 |
jdate = jdays2000(utc_time) / 36525.0
# mean anomaly, rad
m_a = np.deg2rad(357.52910 +
35999.05030 * jdate -
0.0001559 * jdate * jdate -
0.00000048 * jdate * jdate * jdate)
# mean longitude, deg
l_0 = 280.46645 + 36000.76983 * jdate... | def sun_ecliptic_longitude(utc_time) | Ecliptic longitude of the sun at *utc_time*. | 1.833817 | 1.836237 | 0.998682 |
jdate = jdays2000(utc_time) / 36525.0
eps = np.deg2rad(23.0 + 26.0 / 60.0 + 21.448 / 3600.0 -
(46.8150 * jdate + 0.00059 * jdate * jdate -
0.001813 * jdate * jdate * jdate) / 3600)
eclon = sun_ecliptic_longitude(utc_time)
x__ = np.cos(eclon)
y__ = np.c... | def sun_ra_dec(utc_time) | Right ascension and declination of the sun at *utc_time*. | 2.243438 | 2.211934 | 1.014243 |
lon = np.deg2rad(lon)
lat = np.deg2rad(lat)
ra_, dec = sun_ra_dec(utc_time)
h__ = _local_hour_angle(utc_time, lon, ra_)
return (np.arcsin(np.sin(lat) * np.sin(dec) +
np.cos(lat) * np.cos(dec) * np.cos(h__)),
np.arctan2(-np.sin(h__), (np.cos(lat) * np.tan(dec) ... | def get_alt_az(utc_time, lon, lat) | Return sun altitude and azimuth from *utc_time*, *lon*, and *lat*.
lon,lat in degrees
What is the unit of the returned angles and heights!? FIXME! | 2.344972 | 2.341781 | 1.001363 |
lon = np.deg2rad(lon)
lat = np.deg2rad(lat)
r_a, dec = sun_ra_dec(utc_time)
h__ = _local_hour_angle(utc_time, lon, r_a)
return (np.sin(lat) * np.sin(dec) + np.cos(lat) * np.cos(dec) * np.cos(h__)) | def cos_zen(utc_time, lon, lat) | Cosine of the sun-zenith angle for *lon*, *lat* at *utc_time*.
utc_time: datetime.datetime instance of the UTC time
lon and lat in degrees. | 2.794167 | 3.008419 | 0.928783 |
return np.rad2deg(np.arccos(cos_zen(utc_time, lon, lat))) | def sun_zenith_angle(utc_time, lon, lat) | Sun-zenith angle for *lon*, *lat* at *utc_time*.
lon,lat in degrees.
The angle returned is given in degrees | 3.567759 | 4.844622 | 0.736437 |
year = 365.256363004
# This is computed from
# http://curious.astro.cornell.edu/question.php?number=582
# AU = 149597870700.0
# a = 149598261000.0
# theta = (jdays2000(utc_time) - 2) * (2 * np.pi) / year
# e = 0.01671123
# r = a*(1-e*e)/(1+e * np.cos(theta))
# corr_me = (r / AU)... | def sun_earth_distance_correction(utc_time) | Calculate the sun earth distance correction, relative to 1 AU. | 5.295475 | 5.113848 | 1.035517 |
lon = np.deg2rad(lon)
lat = np.deg2rad(lat)
theta = (gmst(time) + lon) % (2 * np.pi)
c = 1 / np.sqrt(1 + F * (F - 2) * np.sin(lat)**2)
sq = c * (1 - F)**2
achcp = (A * c + alt) * np.cos(lat)
x = achcp * np.cos(theta) # kilometers
y = achcp * np.sin(theta)
z = (A * sq + alt) ... | def observer_position(time, lon, lat, alt) | Calculate observer ECI position.
http://celestrak.com/columns/v02n03/ | 3.470237 | 3.55167 | 0.977072 |
(pos_x, pos_y, pos_z), (vel_x, vel_y, vel_z) = astronomy.observer_position(
utc_time, sat_lon, sat_lat, sat_alt)
(opos_x, opos_y, opos_z), (ovel_x, ovel_y, ovel_z) = \
astronomy.observer_position(utc_time, lon, lat, alt)
lon = np.deg2rad(lon)
lat = np.deg2rad(lat)
theta = (as... | def get_observer_look(sat_lon, sat_lat, sat_alt, utc_time, lon, lat, alt) | Calculate observers look angle to a satellite.
http://celestrak.com/columns/v02n02/
utc_time: Observation time (datetime object)
lon: Longitude of observer position on ground in degrees east
lat: Latitude of observer position on ground in degrees north
alt: Altitude above sea-level (geoid) of obser... | 1.859959 | 1.943425 | 0.957052 |
# Propagate backwards to ascending node
dt = np.timedelta64(10, 'm')
t_old = utc_time
t_new = t_old - dt
pos0, vel0 = self.get_position(t_old, normalize=False)
pos1, vel1 = self.get_position(t_new, normalize=False)
while not (pos0[2] > 0 and pos1[2] < 0)... | def get_last_an_time(self, utc_time) | Calculate time of last ascending node relative to the
specified time | 2.54469 | 2.441108 | 1.042432 |
kep = self._sgdp4.propagate(utc_time)
pos, vel = kep2xyz(kep)
if normalize:
pos /= XKMPER
vel /= XKMPER * XMNPDA / SECDAY
return pos, vel | def get_position(self, utc_time, normalize=True) | Get the cartesian position and velocity from the satellite. | 14.489998 | 12.609093 | 1.149171 |
(pos_x, pos_y, pos_z), (vel_x, vel_y, vel_z) = self.get_position(
utc_time, normalize=True)
lon = ((np.arctan2(pos_y * XKMPER, pos_x * XKMPER) - astronomy.gmst(utc_time))
% (2 * np.pi))
lon = np.where(lon > np.pi, lon - np.pi * 2, lon)
lon = np.where... | def get_lonlatalt(self, utc_time) | Calculate sublon, sublat and altitude of satellite.
http://celestrak.com/columns/v02n03/ | 2.585639 | 2.520285 | 1.025931 |
utc_time = dt2np(utc_time)
(pos_x, pos_y, pos_z), (vel_x, vel_y, vel_z) = self.get_position(
utc_time, normalize=False)
(opos_x, opos_y, opos_z), (ovel_x, ovel_y, ovel_z) = \
astronomy.observer_position(utc_time, lon, lat, alt)
lon = np.deg2rad(lon)
... | def get_observer_look(self, utc_time, lon, lat, alt) | Calculate observers look angle to a satellite.
http://celestrak.com/columns/v02n02/
utc_time: Observation time (datetime object)
lon: Longitude of observer position on ground in degrees east
lat: Latitude of observer position on ground in degrees north
alt: Altitude above sea-le... | 2.046336 | 2.105156 | 0.972059 |
utc_time = np.datetime64(utc_time)
try:
dt = astronomy._days(utc_time - self.orbit_elements.an_time)
orbit_period = astronomy._days(self.orbit_elements.an_period)
except AttributeError:
pos_epoch, vel_epoch = self.get_position(self.tle.epoch,
... | def get_orbit_number(self, utc_time, tbus_style=False) | Calculate orbit number at specified time.
Optionally use TBUS-style orbit numbering (TLE orbit number + 1) | 3.344437 | 3.27911 | 1.019922 |
def elevation(minutes):
return self.get_observer_look(utc_time +
timedelta(
minutes=np.float64(minutes)),
lon, lat, alt)[1] - horizon
def ... | def get_next_passes(self, utc_time, length, lon, lat, alt, tol=0.001, horizon=0) | Calculate passes for the next hours for a given start time and a
given observer.
Original by Martin.
utc_time: Observation time (datetime object)
length: Number of hours to find passes (int)
lon: Longitude of observer position on ground (float)
lat: Latitude of observer... | 2.679006 | 2.608608 | 1.026987 |
warnings.warn("_get_time_at_horizon is replaced with get_next_passes",
DeprecationWarning)
if "precision" in kwargs:
precision = kwargs['precision']
else:
precision = timedelta(seconds=0.001)
if "max_iterations" in kwargs:
... | def _get_time_at_horizon(self, utc_time, obslon, obslat, **kwargs) | Get the time closest in time to *utc_time* when the
satellite is at the horizon relative to the position of an observer on
ground (altitude = 0)
Note: This is considered deprecated and it's functionality is currently
replaced by 'get_next_passes'. | 3.112823 | 2.970758 | 1.047821 |
x, y, z = query_point
lat = geodetic_lat(query_point)
lon = np.arctan2(y, x)
e2_ = (a * a - b * b) / (a * a)
n__ = a / np.sqrt(1 - e2_ * np.sin(lat)**2)
nx_ = n__ * np.cos(lat) * np.cos(lon)
ny_ = n__ * np.cos(lat) * np.sin(lon)
nz_ = (1 - e2_) * n__ * np.sin(lat)
return np.st... | def subpoint(query_point, a=A, b=B) | Get the point on the ellipsoid under the *query_point*. | 2.276157 | 2.173911 | 1.047033 |
n_axis = axis / vnorm(axis)
sin_angle = np.expand_dims(np.sin(angle / 2), 0)
if np.ndim(n_axis) == 1:
n_axis = np.expand_dims(n_axis, 1)
p__ = np.dot(n_axis, sin_angle)[:, np.newaxis]
else:
p__ = n_axis * sin_angle
q__ = Quaternion(np.cos(angle / 2), p__)
shape = ve... | def qrotate(vector, axis, angle) | Rotate *vector* around *axis* by *angle* (in radians).
*vector* is a matrix of column vectors, as is *axis*.
This function uses quaternion rotation. | 3.427689 | 3.528742 | 0.971363 |
if isinstance(orb, (list, tuple)):
tle1, tle2 = orb
orb = Orbital("mysatellite", line1=tle1, line2=tle2)
# get position and velocity for each time of each pixel
pos, vel = orb.get_position(times, normalize=False)
# now, get the vectors pointing to each pixel
vectors = sgeom.ve... | def compute_pixels(orb, sgeom, times, rpy=(0.0, 0.0, 0.0)) | Compute cartesian coordinates of the pixels in instrument scan. | 4.851889 | 4.822765 | 1.006039 |
if axis is None:
axis = np.ndim(m) - 1
return np.sqrt((m**2).sum(axis)) | def mnorm(m, axis=None) | norm of a matrix of vectors stacked along the *axis* dimension. | 2.627093 | 2.643929 | 0.993633 |
# TODO: yaw steering mode !
# Fake nadir: This is the intersection point between the satellite
# looking down at the centre of the ellipsoid and the surface of the
# ellipsoid. Nadir on the other hand is the point which vertical goes
# through the satellite...
#... | def vectors(self, pos, vel, roll=0.0, pitch=0.0, yaw=0.0) | Get unit vectors pointing to the different pixels.
*pos* and *vel* are column vectors, or matrices of column
vectors. Returns vectors as stacked rows. | 6.069442 | 6.258547 | 0.969784 |
# build the avhrr instrument (scan angles)
avhrr_inst = np.vstack(((scan_points / 1023.5 - 1)
* np.deg2rad(-scan_angle),
np.zeros((len(scan_points),))))
avhrr_inst = np.tile(
avhrr_inst[:, np.newaxis, :], [1, np.int(scans_nb), 1])
# ... | def avhrr(scans_nb, scan_points,
scan_angle=55.37, frequency=1 / 6.0, apply_offset=True) | Definition of the avhrr instrument.
Source: NOAA KLM User's Guide, Appendix J
http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/klm/html/j/app-j.htm | 3.418271 | 3.395672 | 1.006655 |
try:
offset = np.array([(t - scan_times[0]).seconds +
(t - scan_times[0]).microseconds / 1000000.0 for t in scan_times])
except TypeError:
offset = np.arange(scan_times) * frequency
scans_nb = len(offset)
avhrr_inst = np.vstack(((scan_points / 1023.5 - 1)... | def avhrr_gac(scan_times, scan_points,
scan_angle=55.37, frequency=0.5) | Definition of the avhrr instrument, gac version
Source: NOAA KLM User's Guide, Appendix J
http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/klm/html/j/app-j.htm | 3.904787 | 3.942678 | 0.990389 |
entire_width = np.arange(chn_pixels)
scan_points = entire_width[scan_indices.astype('int')]
scan_pixels = len(scan_points)
''' initial angle 55.84 deg replaced with 56.28 deg found in
VIIRS User's Guide from NESDIS, version 1.2 (09/10/2013).
Ref : NOAA Technical Report NESDIS 142.
See... | def viirs(scans_nb, scan_indices=slice(0, None),
chn_pixels=6400, scan_lines=32, scan_step=1) | Describe VIIRS instrument geometry, I-band by default.
VIIRS scans several lines simultaneously (there are 16 detectors for each
M-band, 32 detectors for each I-band) so the scan angles (and times) are
two-dimensional arrays, contrary to AVHRR for example.
scan_step: The increment in number of scans. E... | 7.858893 | 7.970052 | 0.986053 |
scan_len = 56 # 56 samples per scan
scan_rate = 6.4 # single scan, seconds
scan_angle = -49.5 # swath, degrees
sampling_interval = abs(scan_rate) / scan_len # single view, seconds
if edges_only:
scan_points = np.array([0, scan_len - 1])
else:
scan_points = np.arange(0,... | def hirs4(scans_nb, edges_only=False) | Describe HIRS/4 instrument geometry.
See:
- https://www.eumetsat.int/website/home/Satellites/CurrentSatellites/Metop/MetopDesign/HIRS/index.html
- https://www1.ncdc.noaa.gov/pub/data/satellite/publications/podguides/
N-15%20thru%20N-19/pdf/0.0%20NOAA%20KLM%20Users%20Guide.pdf
(NOAA KLM User... | 4.078012 | 3.97578 | 1.025714 |
if scan_points is None:
scan_len = 4000 # samples per scan
scan_points = np.arange(4000)
else:
scan_len = len(scan_points)
# scan_rate = 0.044 # single scan, seconds
scan_angle_west = 46.5 # swath, degrees
scan_angle_east = -22.1 # swath, degrees
# sampling_inte... | def olci(scans_nb, scan_points=None) | Definition of the OLCI instrument.
Source: Sentinel-3 OLCI Coverage
https://sentinel.esa.int/web/sentinel/user-guides/sentinel-3-olci/coverage | 3.952378 | 3.869811 | 1.021336 |
if scan_points is None:
scan_len = 42 # samples per scan
scan_points = np.arange(42)
else:
scan_len = len(scan_points)
scan_angle_inner = -25.0 # swath, degrees
scan_angle_outer = -53.0 # swath, degrees
scan_rate = 3.74747474747 # single scan, seconds
if scan_l... | def ascat(scan_nb, scan_points=None) | ASCAT make two scans one to the left and one to the right of the
sub-satellite track. | 3.541799 | 3.46351 | 1.022604 |
out_dict = {}
os.getenv('PPP_CONFIG_DIR', PKG_CONFIG_DIR)
platform_file = None
if 'PPP_CONFIG_DIR' in os.environ:
platform_file = os.path.join(os.environ['PPP_CONFIG_DIR'], 'platforms.txt')
if not platform_file or not os.path.isfile(platform_file):
platform_file = os.path.join(P... | def read_platform_numbers(in_upper=False, num_as_int=False) | Read platform numbers from $PPP_CONFIG_DIR/platforms.txt if available. | 2.081343 | 1.855094 | 1.121961 |
return Tle(platform, tle_file=tle_file, line1=line1, line2=line2) | def read(platform, tle_file=None, line1=None, line2=None) | Read TLE for `platform` from `tle_file`
File is read from `line1` to `line2`, from the newest file provided in the
TLES pattern, or from internet if none is provided. | 2.360886 | 3.52792 | 0.669201 |
with io.open(destination, mode="w", encoding="utf-8") as dest:
for url in TLE_URLS:
response = urlopen(url)
dest.write(response.read().decode("utf-8")) | def fetch(destination) | Fetch TLE from internet and save it to `destination`. | 3.477123 | 2.880279 | 1.207218 |
for line in [self._line1, self._line2]:
check = 0
for char in line[:-1]:
if char.isdigit():
check += int(char)
if char == "-":
check += 1
if (check % 10) != int(line[-1]):
raise ... | def _checksum(self) | Performs the checksum for the current TLE. | 4.331664 | 3.664046 | 1.182208 |
if self._line1 is not None and self._line2 is not None:
tle = self._line1.strip() + "\n" + self._line2.strip()
else:
def _open(filename):
return io.open(filename, 'rb')
if self._tle_file:
urls = (self._tle_file,)
... | def _read_tle(self) | Read TLE data. | 2.883332 | 2.863672 | 1.006866 |
def _read_tle_decimal(rep):
if rep[0] in ["-", " ", "+"]:
digits = rep[1:-2].strip()
val = rep[0] + "." + digits + "e" + rep[-2:]
else:
digits = rep[:-2].strip()
val = "." + digits + "e" + rep[-2:]
... | def _parse_tle(self) | Parse values from TLE data. | 2.282119 | 2.230404 | 1.023186 |
ver = platform.split('OS X ')[1]
build_range = range(*MACOSX_CHROME_BUILD_RANGE[ver])
build = choice(build_range)
mac_ver = ver.replace('.', '_') + '_' + str(build)
return 'Macintosh; Intel Mac OS X %s' % mac_ver | def fix_chrome_mac_platform(platform) | Chrome on Mac OS adds minor version number and uses underscores instead
of dots. E.g. platform for Firefox will be: 'Intel Mac OS X 10.11'
but for Chrome it will be 'Intel Mac OS X 10_11_6'.
:param platform: - string like "Macintosh; Intel Mac OS X 10.8"
:return: platform with version number including ... | 4.684684 | 4.856357 | 0.96465 |
if os_id == 'win':
platform_version = choice(OS_PLATFORM['win'])
cpu = choice(OS_CPU['win'])
if cpu:
platform = '%s; %s' % (platform_version, cpu)
else:
platform = platform_version
res = {
'platform_version': platform_version,
... | def build_system_components(device_type, os_id, navigator_id) | For given os_id build random platform and oscpu
components
Returns dict {platform_version, platform, ua_platform, oscpu}
platform_version is OS name used in different places
ua_platform goes to navigator.platform
platform is used in building navigator.userAgent
oscpu goes to navigator.oscpu | 2.054179 | 1.871807 | 1.097431 |
if navigator_id == 'firefox':
build_version, build_id = get_firefox_build()
if os_id in ('win', 'linux', 'mac'):
geckotrail = '20100101'
else:
geckotrail = build_version
res = {
'name': 'Netscape',
'product_sub': '20100101',
... | def build_app_components(os_id, navigator_id) | For given navigator_id build app features
Returns dict {name, product_sub, vendor, build_version, build_id} | 2.458482 | 2.154739 | 1.140965 |
choices = []
if isinstance(opt_value, six.string_types):
choices = [opt_value]
elif isinstance(opt_value, (list, tuple)):
choices = list(opt_value)
elif opt_value is None:
choices = default_value
else:
raise InvalidOption('Option %s has invalid'
... | def get_option_choices(opt_name, opt_value, default_value, all_choices) | Generate possible choices for the option `opt_name`
limited to `opt_value` value with default value
as `default_value` | 2.147544 | 2.160695 | 0.993914 |
if os is None:
default_dev_types = ['desktop']
else:
default_dev_types = list(DEVICE_TYPE_OS.keys())
dev_type_choices = get_option_choices(
'device_type', device_type, default_dev_types,
list(DEVICE_TYPE_OS.keys())
)
os_choices = get_option_choices('os', os, li... | def pick_config_ids(device_type, os, navigator) | Select one random pair (device_type, os_id, navigator_id) from
all possible combinations matching the given os and
navigator filters.
:param os: allowed os(es)
:type os: string or list/tuple or None
:param navigator: allowed browser engine(s)
:type navigator: string or list/tuple or None
:p... | 2.577158 | 2.565028 | 1.004729 |
if platform is not None:
os = platform
warn('The `platform` option is deprecated.'
' Use `os` option instead.', stacklevel=3)
device_type, os_id, navigator_id = (
pick_config_ids(device_type, os, navigator)
)
system = build_system_components(
device_typ... | def generate_navigator(os=None, navigator=None, platform=None,
device_type=None) | Generates web navigator's config
:param os: limit list of oses for generation
:type os: string or list/tuple or None
:param navigator: limit list of browser engines for generation
:type navigator: string or list/tuple or None
:param device_type: limit possible oses by device type
:type device_t... | 3.221648 | 2.841061 | 1.13396 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.