output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
how high in sorted list each key is. inverse permutation of sorter | Can you tell what is the following Python 3 function doing
def rank(self):
r = np.empty(self.size, np.int)
r[self.sorter] = np.arange(self.size)
return r | You are a Python code analyst, evaluating scripts for potential improvements. |
def unique(self):
"""returns a tuple of unique key columns"""
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)) | Can you create a Python 3 function that
returns a tuple of unique key columns | As a Python code composer, you craft elegant and concise scripts. |
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
"""
columns = [np.asarray(c) for c in columns]
row... | How would you code a function in Python 3 to
pack a sequence of columns into a recarray containing the input columns as struct fields | As a Python code composer, you craft elegant and concise scripts. |
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
arr... | Write a Python 3 function for
casting the given axis of an array to a void object | As a python code expert, you are capable of creating scripts from specifications. |
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... | Can you create a Python 3 function that
casts an array of void objects to a typed axis | You are a Python code generator, capable of creating scripts from specifications. |
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 ke... | Write a Python 3 function for
counting the number of times each key occurs in the input set | As a Python code analyst, you investigate and solve complex coding mysteries |
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 fo... | Write a Python 3 function that can
count the number of times each key occurs in the input set | As a python code expert, you are capable of creating scripts from specifications. |
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)
"""
if isinstance(keys, tuple):
n_keys = len(keys)
e... | Create a Python 3 function to
perform binning over the given axes of the keys | You are a Python code architect, reviewing and designing scalable and efficient code |
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
"""
i... | How would you implement a function in Python 3 that
returns the multiplicity of each key or how often it occurs in the set | As a Python code translator, you convert algorithms and pseudocode into Python. |
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[inde... | How would you code a function in Python 3 to
return the rank of the object in the pecking order. | As a Python code translator, you convert algorithms and pseudocode into Python. |
compute the mode or most frequent occuring key in a set
| Explain what the following Python 3 code does
def mode(keys, axis=semantics.axis_default, weights=None, return_indices=False):
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)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
compute indidence info matrix for a given boundary info between simplices | Explain what the following Python 3 code does
def incidence(boundary):
return GroupBy(boundary).split(np.arange(boundary.size) // boundary.shape[1]) | As a Python code analyst, you investigate and solve complex coding mysteries |
def all_unique(keys, axis=semantics.axis_default):
"""Returns true if all keys are unique"""
index = as_index(keys, axis)
return index.groups == index.size | Write a Python 3 function that can
return true if all keys are unique | You are a Python code architect, reviewing and designing scalable and efficient code |
returns true if any of the keys is unique | Explain what the following Python 3 code does
def any_unique(keys, axis=semantics.axis_default):
index = as_index(keys, axis)
return np.any(index.count == 1) | As a python code expert, you are capable of creating scripts from specifications. |
returns true of all keys are equal | Explain what the following Python 3 code does
def all_equal(keys, axis=semantics.axis_default):
index = as_index(keys, axis)
return index.groups == 1 | As a Python code analyst, you investigate and solve complex coding mysteries |
def is_uniform(keys, axis=semantics.axis_default):
"""returns true if all keys have equal multiplicity"""
index = as_index(keys, axis)
return index.uniform | Can you implement a function in Python 3 that
returns true if all keys have equal multiplicity | As a python code expert, you are capable of creating scripts from specifications. |
def get_inverses(self, keys):
"""
Returns
-------
Tuple of inverse indices
"""
return tuple([as_index(k, axis=0).inverse for k in keys]) | How would you implement a function in Python 3 that
returns tuples of inverse indices of the given keys | As a Python code analyst, you investigate and solve complex coding mysteries |
Place each entry in a table while asserting that each entry occurs once | How would you explain what the following Python 3 function does
def unique(self, values):
_, 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) | You are a Python code architect, reviewing and designing scalable and efficient code |
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, th... | Can you write a function in Python 3 where it
computes the set of unique keys within a node - level object | As a python code expert, you are capable of creating scripts from specifications. |
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 fo... | Implement a Python 3 function for
returning a boolean array indicating if each element of that is contained in this. | You are a Python code generator, capable of creating scripts from specifications. |
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
... | Implement a Python 3 function for
returning a bool for each element of this indicating if it is present in that. | As a python code expert, you are capable of creating scripts from specifications. |
Find indices such that this [ indices ] == that [ indices ] | Here you have a function in Python 3, explain what it does
def indices(this, that, axis=semantics.axis_default, missing='raise'):
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... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Given an array of keys and values remaps its entries corresponding to keys to values. | Can you tell what is the following Python 3 function doing
def remap(input, keys, values, missing='ignore', inplace=False):
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')... | As a Python code composer, you craft elegant and concise scripts. |
def _set_concatenate(sets):
"""concatenate indexable objects.
Parameters
----------
sets : iterable of indexable objects
Returns
-------
indexable object
handles both arrays and tuples of arrays
"""
def con(set):
# if not all():
# raise ValueError('concaten... | Create a Python 3 function to
concatenate indexable objects. Parameters ---------- sets : iterable of indexable objects Returns ------- indexable object handles both arrays and tuples of arrays | You are a Python code analyst, evaluating scripts for potential improvements. |
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 th... | Implement a function in Python 3 to
return the elements which occur n times over the sequence of sets | As a Python code analyst, you investigate and solve complex coding mysteries |
all unique items which occur in any one of the sets
Returns a new indexable object containing the union of all unique items in any of the sets
| Given the following Python 3 function, write the documentation
def union(*sets, **kwargs):
sets = _set_preprocess(sets, **kwargs)
return as_index( _set_concatenate(sets), axis=0, base=True).unique | You are a Python code analyst, evaluating scripts for potential improvements. |
returns the difference of all items in the set in the head set and all other items in the tail set | How would you explain what the following Python 3 function does
def difference(*sets, **kwargs):
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) | You are a Python code generator, capable of creating scripts from specifications. |
def _generate_div_id_chart(prefix="chart_id", digits=8):
"""Generate a random id for div chart.
"""
choices = (random.randrange(0, 52) for _ in range(digits))
return prefix + "".join((string.ascii_letters[x] for x in choices)) | How would you code a function in Python 3 to
generate a random id for div chart. | As a Python code analyst, you investigate and solve complex coding mysteries |
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
"""
if chart_type not in ("default", "stock"):
raise ValueErr... | Write a Python 3 script for
displaying you DataFrame with Highcharts. | As a Python code composer, you craft elegant and concise scripts. |
Filter the data for the series key in the list stored under the key series by "[...]". | Can you generate the documentation for the following Python 3 function
def _series_data_filter(data):
data = copy.deepcopy(data)
if "series" in data:
for series in data["series"]:
series["data"] = "[...]"
return data | You are a Python code architect, reviewing and designing scalable and efficient code |
Pretty print your Highcharts params into a JSON. | Can you generate a brief explanation for the following Python 3 code
def pretty_params(data, indent=2):
data_to_print = _series_data_filter(data)
print(json.dumps(data_to_print, indent=indent)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the additional params needed for polling. | Here you have a function in Python 3, explain what it does
def get_additional_params(self, **params):
# TODO: Move these params to their own vertical if needed.
polling_params = [
'locationschema',
'carrierschema',
'sorttype',
'sortorder',
'or... | You are a Python code generator, capable of creating scripts from specifications. |
Get all results by creating and polling the session. | Can you tell what is the following Python 3 function doing
def get_result(self, errors=GRACEFUL, **params):
additional_params = self.get_additional_params(**params)
return self.poll_session(
self.create_session(**params),
errors=errors,
**additional_params
) | As a Python code composer, you craft elegant and concise scripts. |
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 hea... | Implement a Python 3 function for
making a request to the specified service URL and returns the response. | You are a Python code generator, capable of creating scripts from specifications. |
Get the list of markets available for a given market | How would you explain what the following Python 3 function does
def get_markets(self, market):
url = "{url}/{market}".format(url=self.MARKET_SERVICE_URL,
market=market)
return self.make_request(url, headers=self._headers()) | As a python code expert, you are capable of creating scripts from specifications. |
This method returns a response object containing the location of the object. | Make a summary of the following Python 3 code
def location_autosuggest(self, **params):
service_url = "{url}/{params_path}".format(
url=self.LOCATION_AUTOSUGGEST_URL,
params_path=self._construct_params(
params, self.LOCATION_AUTOSUGGEST_PARAMS)
)
return se... | As a python code expert, you are capable of creating scripts from specifications. |
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... | How would you code a function in Python 3 to
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 :param tries - number of polls to perfo... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _construct_params(params, required_keys, opt_keys=None):
"""
Construct params list in order of given keys.
"""
try:
params_list = [params.pop(key) for key in required_keys]
except KeyError as e:
raise MissingParameter(
'Missing expected... | Create a Python 3 function to
construct params list from required_keys and opt_keys. | You are a Python code analyst, evaluating scripts for potential improvements. |
Create the session for the current user | How would you explain what the following Python 3 function does
def create_session(self, **params):
return self.make_request(self.PRICING_SESSION_URL,
method='post',
headers=self._session_headers(),
callback=lambd... | You are a Python code generator, capable of creating scripts from specifications. |
Request for booking details for a specific resource. | Can you tell what is the following Python 3 function doing
def request_booking_details(self, poll_url, **params):
return self.make_request("%s/booking" % poll_url,
method='put',
headers=self._headers(),
callback=l... | You are a Python code analyst, evaluating scripts for potential improvements. |
This method returns the cheapest price for the current date. | Can you generate a brief explanation for the following Python 3 code
def get_cheapest_price_by_date(self, **params):
service_url = "{url}/{params_path}".format(
url=self.BROWSE_DATES_SERVICE_URL,
params_path=self._construct_params(
params, self._REQ_PARAMS, self._OPT_PARA... | You are a Python code architect, reviewing and designing scalable and efficient code |
This method returns the cheapest price by route. | How would you explain what the following Python 3 function does
def get_cheapest_price_by_route(self, **params):
service_url = "{url}/{params_path}".format(
url=self.BROWSE_ROUTES_SERVICE_URL,
params_path=self._construct_params(
params, self._REQ_PARAMS, self._OPT_PARAMS)... | You are a Python code generator, capable of creating scripts from specifications. |
This method returns the cheapest quotes for the current locale. | Given the following Python 3 function, write the documentation
def get_cheapest_quotes(self, **params):
service_url = "{url}/{params_path}".format(
url=self.BROWSE_QUOTES_SERVICE_URL,
params_path=self._construct_params(
params, self._REQ_PARAMS, self._OPT_PARAMS)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_session(self, **params):
"""
Create the session
date format: YYYY-MM-DDThh:mm
location: ISO code
"""
required_keys = ('market', 'currency', 'locale', 'pickupplace',
'dropoffplace', 'pickupdatetime', 'dropoffdatetime',
... | Can you write a function in Python 3 where it
creates the session for the user. | You are a Python code generator, capable of creating scripts from specifications. |
def keyboard_field(value, args=None):
"""
Format keyboard /command field.
"""
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... | How would you implement a function in Python 3 that
formats keyboard /command field. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the QuerySet that will be used to look up the object. | Can you generate a brief explanation for the following Python 3 code
def get_queryset(self):
if self.queryset is None:
if self.model:
return self.model._default_manager.all()
else:
raise ImproperlyConfigured(
"%(cls)s is missing a Query... | As a Python code composer, you craft elegant and concise scripts. |
Decorator for command views that checks that the chat is authenticated and sends message with link for authenticated if necessary. | Can you generate a brief explanation for the following Python 3 code
def login_required(view_func):
@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)
fro... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Decorator to handle automatic data structure creation for pipe - utils.
| Here you have a function in Python 3, explain what it does
def data_structure_builder(func):
@wraps(func)
def ds_builder_wrapper(function, *args, **kwargs):
try:
function = DSBuilder(function)
except NoBuilder:
pass
return func(function, *args, **kwargs)
retu... | As a Python code analyst, you investigate and solve complex coding mysteries |
Decorator that turns a condition string instead of a function into a regex - matching function. | How would you explain what the following Python 3 function does
def regex_condition(func):
@wraps(func)
def regex_condition_wrapper(condition, *args, **kwargs):
if isinstance(condition, string_types):
condition = maybe | partial(re.match, condition)
return func(condition, *args, **kw... | You are a Python code architect, reviewing and designing scalable and efficient code |
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)``... | Implement a function in Python 3 to
sort an incoming sequence by using the given function as key. | You are a Python code architect, reviewing and designing scalable and efficient code |
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)
"""
def _take_first(iterable):
... | Write a Python 3 function that can
take the first count items from the input. | As a python code expert, you are capable of creating scripts from specifications. |
Returns an iterable with identical items
except for the first count items. | Make a summary of the following Python 3 code
def drop_first(count):
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) | You are a Python code analyst, evaluating scripts for potential improvements. |
A decorator that returns a new object that will not be caught while executing func. | Can you generate a brief explanation for the following Python 3 code
def unless(exception_class_or_tuple, func, *args, **kwargs):
@pipe_util
@auto_string_formatter
@data_structure_builder
def construct_unless(function):
# a wrapper so we can re-use the decorators
def _unless(*args, **kwa... | You are a Python code analyst, evaluating scripts for potential improvements. |
Groups input sequence by function. | Can you generate a brief explanation for the following Python 3 code
def group_by(function):
def _group_by(seq):
result = {}
for item in seq:
result.setdefault(function(item), []).append(item)
return dict_items(result)
return _group_by | You are a Python code generator, capable of creating scripts from specifications. |
take_until returns a list of nodes where condition is true | Given the following Python 3 function, write the documentation
def take_until(condition):
f = partial(takewhile, pipe | condition | operator.not_)
f.attrs = {'including': take_until_including(condition)}
return f | As a Python code composer, you craft elegant and concise scripts. |
Return a generator that yields the elements of the list of items in the list that satisfy the condition. | Make a summary of the following Python 3 code
def take_until_including(condition):
def take_until_including_(interable):
for i in interable:
if not condition(i):
yield i
else:
yield i
break
return take_until_including_ | You are a Python code architect, reviewing and designing scalable and efficient code |
A function that returns a new object which is a partial of the function func with the given arguments and keyword arguments. | Make a summary of the following Python 3 code
def xpartial(func, *xargs, **xkwargs):
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))
... | As a python code expert, you are capable of creating scripts from specifications. |
def sun_ecliptic_longitude(utc_time):
"""Ecliptic longitude of the sun at *utc_time*.
"""
jdate = jdays2000(utc_time) / 36525.0
# mean anomaly, rad
m_a = np.deg2rad(357.52910 +
35999.05030 * jdate -
0.0001559 * jdate * jdate -
0.00000048... | Create a Python 3 function for
returning the ecliptic longitude of the sun at the given UTC time. | As a python code expert, you are capable of creating scripts from specifications. |
Right ascension and declination of the sun at *utc_time*. | How would you explain what the following Python 3 function does
def sun_ra_dec(utc_time):
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... | As a Python code composer, you craft elegant and concise scripts. |
Return sun altitude and azimuth from the given time. | Can you generate a brief explanation for the following Python 3 code
def get_alt_az(utc_time, lon, lat):
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... | As a Python code composer, you craft elegant and concise scripts. |
Cosine of the sun - zenith angle for lon and lat at the UTC time. | Can you tell what is the following Python 3 function doing
def cos_zen(utc_time, lon, lat):
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__)) | You are a Python code architect, reviewing and designing scalable and efficient code |
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
"""
return np.rad2deg(np.arccos(cos_zen(utc_time, lon, lat))) | Create a Python 3 function for
returning sun - zonal angle at a given longitude and latitude. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def sun_earth_distance_correction(utc_time):
"""Calculate the sun earth distance correction, relative to 1 AU.
"""
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_t... | Can you create a Python 3 function that
calculates the sun earth distance correction relative to 1 AU. | As a Python code analyst, you investigate and solve complex coding mysteries |
Calculate observer ECI position. | Make a summary of the following Python 3 code
def observer_position(time, lon, lat, alt):
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 = achc... | You are a Python code analyst, evaluating scripts for potential improvements. |
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 posi... | Can you implement a function in Python 3 that
calculates the observer look angle to a satellite. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_last_an_time(self, utc_time):
"""Calculate time of last ascending node relative to the
specified time
"""
# 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... | How would you code a function in Python 3 to
calculate time of last ascending node relative to the timecluster. | As a Python code composer, you craft elegant and concise scripts. |
Get the cartesian position and velocity from the satellite. | Explain what the following Python 3 code does
def get_position(self, utc_time, normalize=True):
kep = self._sgdp4.propagate(utc_time)
pos, vel = kep2xyz(kep)
if normalize:
pos /= XKMPER
vel /= XKMPER * XMNPDA / SECDAY
return pos, vel | You are a Python code architect, reviewing and designing scalable and efficient code |
Calculate lon lat and alt of the satellite. | Make a summary of the following Python 3 code
def get_lonlatalt(self, utc_time):
(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))
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Calculate the observer look angle to a satellite. | How would you explain what the following Python 3 function does
def get_observer_look(self, utc_time, lon, lat, alt):
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, ov... | As a Python code composer, you craft elegant and concise scripts. |
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)
"""
utc_time = np.datetime64(utc_time)
try:
dt = astronomy._days(utc_time - self.orbit_elements.an_tim... | Write a Python 3 script to
calculate the orbit number at the specified time. | As a python code expert, you are capable of creating scripts from specifications. |
Calculate the next passes for a given observer. | Given the following Python 3 function, write the documentation
def get_next_passes(self, utc_time, length, lon, lat, alt, tol=0.001, horizon=0):
def elevation(minutes):
"""Compute the elevation."""
return self.get_observer_look(utc_time +
timede... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the time closest in time to utc_time when the satellite is at the horizon relative to the position of an observer on the base of the satellite. | Can you generate the documentation for the following Python 3 function
def _get_time_at_horizon(self, utc_time, obslon, obslat, **kwargs):
warnings.warn("_get_time_at_horizon is replaced with get_next_passes",
DeprecationWarning)
if "precision" in kwargs:
precision = kw... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the point on the ellipsoid under the query_point. | How would you explain what the following Python 3 function does
def subpoint(query_point, a=A, b=B):
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)
... | As a python code expert, you are capable of creating scripts from specifications. |
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.
"""
n_axis = axis / vnorm(axis)
sin_angle = np.expand_dims(np.sin(angle / 2), 0)
if np.ndim(n_axis) == 1:... | Can you create a Python 3 function that
rotates vector around axis by angle. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Compute the cartesian coordinates of the pixels in instrument scan. | Can you generate the documentation for the following Python 3 function
def compute_pixels(orb, sgeom, times, rpy=(0.0, 0.0, 0.0)):
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
... | As a python code expert, you are capable of creating scripts from specifications. |
def mnorm(m, axis=None):
"""norm of a matrix of vectors stacked along the *axis* dimension."""
if axis is None:
axis = np.ndim(m) - 1
return np.sqrt((m**2).sum(axis)) | Can you implement a function in Python 3 that
norms of a matrix of vectors stacked along the axis * dimension. | You are a Python code architect, reviewing and designing scalable and efficient code |
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.
"""
# TODO: yaw steering mode !
# Fake nadir: This is the... | Write a Python 3 function for
getting the unit vectors pointing to the different pixels. | As a Python code analyst, you investigate and solve complex coding mysteries |
Build the avhrr instrument for the given number of scans. | Explain what the following Python 3 code does
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
"""
... | As a Python code composer, you craft elegant and concise scripts. |
Return the avhrr instrument and gac version of the avhrr archive. | How would you explain what the following Python 3 function does
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-... | You are a Python code analyst, evaluating scripts for potential improvements. |
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) ar... | Can you create a Python 3 function that
describes the VIIRS instrument geometry I - band by default. | You are a Python code analyst, evaluating scripts for potential improvements. |
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%... | Can you create a Python 3 function that
describes HIRS 4 instrument geometry. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a ScanGeometry object for the OLCI instrument. | Explain what the following Python 3 code does
def olci(scans_nb, scan_points=None):
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 # s... | As a python code expert, you are capable of creating scripts from specifications. |
def read_platform_numbers(in_upper=False, num_as_int=False):
"""Read platform numbers from $PPP_CONFIG_DIR/platforms.txt if available."""
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[... | Write a Python 3 script for
reading platform numbers from the PPP_CONFIG_DIR. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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.
"""
return Tle(platform, tle_file=tle_file, line1=line1, line2=line2) | How would you code a function in Python 3 to
read TLE from tle_file line1 and line2. | You are a Python code generator, capable of creating scripts from specifications. |
def fetch(destination):
"""Fetch TLE from internet and save it to `destination`."""
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")) | Can you implement a function in Python 3 that
fetches TLE from internet and save it to destination. | As a python code expert, you are capable of creating scripts from specifications. |
def _checksum(self):
"""Performs the checksum for the current TLE."""
for line in [self._line1, self._line2]:
check = 0
for char in line[:-1]:
if char.isdigit():
check += int(char)
if char == "-":
check += 1
... | Write a Python 3 script for
performing the checksum for the current TLE. | You are a Python code generator, capable of creating scripts from specifications. |
def _parse_tle(self):
"""Parse values from TLE data."""
def _read_tle_decimal(rep):
"""Convert *rep* to decimal value."""
if rep[0] in ["-", " ", "+"]:
digits = rep[1:-2].strip()
val = rep[0] + "." + digits + "e" + rep[-2:]
else:
... | Implement a function in Python 3 to
parse the TLE data from the Aleph file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Fix Chrome on Mac OS X 10. 11. 6 platform. | Here you have a function in Python 3, explain what it does
def fix_chrome_mac_platform(platform):
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'... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 i... | Can you write a function in Python 3 where it
builds random system components for given os_id and navigator_id. | You are a Python code generator, capable of creating scripts from specifications. |
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}
"""
if navigator_id == 'firefox':
build_version, build_id = get_firefox_build()
if os_id in ('win', 'linux', 'mac'):
... | Implement a function in Python 3 to
build app components for given navigator_id | You are a Python code analyst, evaluating scripts for potential improvements. |
Generates possible choices for the option opt_name opt_value with default value as default_value as all_choices | Can you tell what is the following Python 3 function doing
def get_option_choices(opt_name, opt_value, default_value, all_choices):
choices = []
if isinstance(opt_value, six.string_types):
choices = [opt_value]
elif isinstance(opt_value, (list, tuple)):
choices = list(opt_value)
elif op... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 engin... | Can you create a Python 3 function that
selects one random pair of config ids from the given os and navigator filters. | You are a Python code architect, reviewing and designing scalable and efficient code |
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 ... | Write a Python 3 function that can
generate a web navigator s config. | You are a Python code architect, reviewing and designing scalable and efficient code |
def generate_user_agent(os=None, navigator=None, platform=None,
device_type=None):
"""
Generates HTTP User-Agent header
:param os: limit list of os for generation
:type os: string or list/tuple or None
:param navigator: limit list of browser engines for generation
:type ... | Can you create a Python 3 function that
generates HTTP User - Agent header for the current language. | You are a Python code architect, reviewing and designing scalable and efficient code |
Generates a web navigator s config with keys corresponding
to keys of Windows. navigator JavaScript object. | Make a summary of the following Python 3 code
def generate_navigator_js(os=None, navigator=None, platform=None,
device_type=None):
"""
Generates web navigator's config with keys corresponding
to keys of `windows.navigator` JavaScript object.
:param os: limit list of oses for g... | You are a Python code analyst, evaluating scripts for potential improvements. |
def more_data(pipe_out):
"""Check if there is more data left on the pipe
:param pipe_out: The os pipe_out
:rtype: bool
"""
r, _, _ = select.select([pipe_out], [], [], 0)
return bool(r) | Create a Python 3 function for
checking if there is more data left on the pipe_out | You are a Python code analyst, evaluating scripts for potential improvements. |
def read_pipe(pipe_out):
"""Read data on a pipe
Used to capture stdout data produced by libiperf
:param pipe_out: The os pipe_out
:rtype: unicode string
"""
out = b''
while more_data(pipe_out):
out += os.read(pipe_out, 1024)
return out.decode('utf-8') | Write a Python 3 function that can
read data on a pipe and return it as a unicode string | As a Python code composer, you craft elegant and concise scripts. |
The iperf3 instance role | Given the following Python 3 function, write the documentation
def role(self):
try:
self._role = c_char(
self.lib.iperf_get_test_role(self._test)
).value.decode('utf-8')
except TypeError:
self._role = c_char(
chr(self.lib.iperf_get_test... | As a python code expert, you are capable of creating scripts from specifications. |
Toggles json output of libiperf
Turning this off will output the iperf3 instance results to stdout and stderr | Can you tell what is the following Python 3 function doing
def json_output(self):
enabled = self.lib.iperf_get_test_json_output(self._test)
if enabled:
self._json_output = True
else:
self._json_output = False
return self._json_output | You are a Python code analyst, evaluating scripts for potential improvements. |
Toggles verbose output for the iperf3 instance | Given the following Python 3 function, write the documentation
def verbose(self):
enabled = self.lib.iperf_get_verbose(self._test)
if enabled:
self._verbose = True
else:
self._verbose = False
return self._verbose | You are a Python code architect, reviewing and designing scalable and efficient code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.