output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Register markdown for flatpages.
How would you explain what the following Python 3 function does def register(): admin.site.unregister(FlatPage) admin.site.register(FlatPage, LocalFlatPageAdmin)
As a Python code analyst, you investigate and solve complex coding mysteries
Render a given value using the MARKDOWN_EXTENSIONS setting.
Can you generate the documentation for the following Python 3 function def markdown(value, arg=None): extensions = (arg and arg.split(',')) or settings.MARKDOWN_EXTENSIONS return _markdown(value, extensions=extensions, safe=False)
As a Python code composer, you craft elegant and concise scripts.
def markdown_safe(value, arg=None): """ Render markdown over a given value, optionally using varios extensions. Default extensions could be defined which MARKDOWN_EXTENSIONS option. Enables safe mode, which strips raw HTML and only returns HTML generated by markdown. :returns: A rendered markdown...
Can you create a Python 3 function that renders a given value optionally using MARKDOWN_EXTENSIONS.
As a python code expert, you are capable of creating scripts from specifications.
Enable markdown editor for given textarea.
Given the following Python 3 function, write the documentation def markdown_editor(selector): return dict( selector=selector, extra_settings=mark_safe(simplejson.dumps( dict(previewParserPath=reverse('django_markdown_preview')))))
As a Python code composer, you craft elegant and concise scripts.
Add css requirements to HTML.
Can you generate the documentation for the following Python 3 function def markdown_media_css(): return dict( CSS_SET=posixpath.join( settings.MARKDOWN_SET_PATH, settings.MARKDOWN_SET_NAME, 'style.css' ), CSS_SKIN=posixpath.join( 'django_markdown', 'skins', settings.M...
You are a Python code generator, capable of creating scripts from specifications.
def convert(source, to, format=None, extra_args=(), encoding='utf-8'): """Convert given `source` from `format` `to` another. `source` may be either a file path or a string to be converted. It's possible to pass `extra_args` if needed. In case `format` is not provided, it will try to invert the format ...
Implement a Python 3 function for converting given source from format to another.
As a Python code translator, you convert algorithms and pseudocode into Python.
Dynamic preprocessor for Pandoc formats. Return 2 lists. from_formats and to_formats.
Given the following Python 3 function, write the documentation def get_pandoc_formats(): try: p = subprocess.Popen( ['pandoc', '-h'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) except OSError: raise OSError("You probably do not have pandoc installed.") ...
As a Python code analyst, you investigate and solve complex coding mysteries
Render the tag with the necessary initialization.
Explain what the following Python 3 code does def render(self, name, value, attrs=None, renderer=None): html = super(MarkdownWidget, self).render(name, value, attrs, renderer) attrs = self.build_attrs(attrs) html += editor_js_initialization("#%s" % attrs['id']) return mark_safe(html)
As a Python code analyst, you investigate and solve complex coding mysteries
Add InlineGraphvizPreprocessor to the Markdown instance.
Given the following Python 3 function, write the documentation def extendMarkdown(self, md, md_globals): md.registerExtension(self) md.preprocessors.add('graphviz_block', InlineGraphvizPreprocessor(md), "_begin")
As a Python code composer, you craft elegant and concise scripts.
Match and generate dot code blocks.
Can you tell what is the following Python 3 function doing def run(self, lines): text = "\n".join(lines) while 1: m = BLOCK_RE.search(text) if m: command = m.group('command') # Whitelist command, prevent command injection. if comma...
You are a Python code generator, capable of creating scripts from specifications.
def post(self, command, data=None): """Post data to API.""" now = calendar.timegm(datetime.datetime.now().timetuple()) if now > self.expiration: auth = self.__open("/oauth/token", data=self.oauth) self.__sethead(auth['access_token']) return self.__open("%s%s" % (s...
Can you implement a function in Python 3 that posts data to API.
As a python code expert, you are capable of creating scripts from specifications.
Use raw urlopen command.
Here you have a function in Python 3, explain what it does def __open(self, url, headers=None, data=None, baseurl=""): headers = headers or {} if not baseurl: baseurl = self.baseurl req = Request("%s%s" % (baseurl, url), headers=headers) _LOGGER.debug(url) try: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def update(self): """Update the parking brake sensor.""" self._controller.update(self._id, wake_if_asleep=False) data = self._controller.get_drive_params(self._id) if data: if not data['shift_state'] or data['shift_state'] == 'P': self.__state = True ...
Can you implement a function in Python 3 that updates the parking brake sensor.
You are a Python code architect, reviewing and designing scalable and efficient code
def update(self): """Update the HVAC state.""" self._controller.update(self._id, wake_if_asleep=False) data = self._controller.get_climate_params(self._id) if data: if time.time() - self.__manual_update_time > 60: self.__is_auto_conditioning_on = (data ...
Can you implement a function in Python 3 that updates the HVAC state.
As a Python code analyst, you investigate and solve complex coding mysteries
def set_temperature(self, temp): """Set both the driver and passenger temperature to temp.""" temp = round(temp, 1) self.__manual_update_time = time.time() data = self._controller.command(self._id, 'set_temps', {"driver_temp": temp, ...
Write a Python 3 function that can set both the driver and passenger temperature to temp.
You are a Python code architect, reviewing and designing scalable and efficient code
def set_status(self, enabled): """Enable or disable the HVAC.""" self.__manual_update_time = time.time() if enabled: data = self._controller.command(self._id, 'auto_conditioning_start', wake_if_as...
Implement a function in Python 3 to enable or disable the HVAC.
As a python code expert, you are capable of creating scripts from specifications.
def update(self): """Update the charging state of the Tesla Vehicle.""" self._controller.update(self._id, wake_if_asleep=False) data = self._controller.get_charging_params(self._id) if data and (time.time() - self.__manual_update_time > 60): if data['charging_state'] != "Char...
Can you implement a function in Python 3 that updates the charging state of the Tesla Vehicle.
You are a Python code generator, capable of creating scripts from specifications.
Start charging the Tesla Vehicle.
Explain what the following Python 3 code does def start_charge(self): if not self.__charger_state: data = self._controller.command(self._id, 'charge_start', wake_if_asleep=True) if data and data['response']['result']: self.__cha...
You are a Python code architect, reviewing and designing scalable and efficient code
def stop_charge(self): """Stop charging the Tesla Vehicle.""" if self.__charger_state: data = self._controller.command(self._id, 'charge_stop', wake_if_asleep=True) if data and data['response']['result']: self.__charger_...
Create a Python 3 function for stopping charging the Tesla Vehicle.
You are a Python code architect, reviewing and designing scalable and efficient code
def update(self): """Update the status of the range setting.""" self._controller.update(self._id, wake_if_asleep=False) data = self._controller.get_charging_params(self._id) if data and (time.time() - self.__manual_update_time > 60): self.__maxrange_state = data['charge_to_ma...
Implement a Python 3 function for updating the status of the range setting.
You are a Python code generator, capable of creating scripts from specifications.
Set the charger to max range for trips.
Can you generate the documentation for the following Python 3 function def set_max(self): if not self.__maxrange_state: data = self._controller.command(self._id, 'charge_max_range', wake_if_asleep=True) if data['response']['result']: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Set the charger to standard range for daily commute.
How would you explain what the following Python 3 function does def set_standard(self): if self.__maxrange_state: data = self._controller.command(self._id, 'charge_standard', wake_if_asleep=True) if data and data['response']['result']: ...
As a python code expert, you are capable of creating scripts from specifications.
def unlock(self): """Unlock the doors and extend handles where applicable.""" if self.__lock_state: data = self._controller.command(self._id, 'door_unlock', wake_if_asleep=True) if data['response']['result']: self.__lock...
How would you code a function in Python 3 to unlock the doors and extend handles where applicable.
As a Python code translator, you convert algorithms and pseudocode into Python.
def lock(self): """Close the charger door.""" if not self.__lock_state: data = self._controller.command(self._id, 'charge_port_door_close', wake_if_asleep=True) if data['response']['result']: self.__lock_state = True ...
Can you write a function in Python 3 where it closes the charger door.
As a Python code composer, you craft elegant and concise scripts.
def wake_up(func): # pylint: disable=no-self-argument # issue is use of wraps on classmethods which should be replaced: # https://hynek.me/articles/decorators/ """Wrap a API f so it will attempt to wake the vehicle if asleep. The command f is run once if the vehicle_id was la...
Can you create a Python 3 function that wraps a API f so it will attempt to wake the vehicle if asleep. The command f is run once if the vehicle_id was last reported online. Assuming f returns None and wake_if_asleep is True, 5 attempts will be made to wake the vehicle to reissue the command. In addition, if there is a...
You are a Python code analyst, evaluating scripts for potential improvements.
def post(self, vehicle_id, command, data=None, wake_if_asleep=True): # pylint: disable=unused-argument """Send post command to the vehicle_id. This is a wrapped function by wake_up. Parameters ---------- vehicle_id : string Identifier for the car on the own...
Can you create a Python 3 function that sends a command to the vehicle_id.
As a Python code composer, you craft elegant and concise scripts.
Send get command to the vehicle_id.
Can you generate the documentation for the following Python 3 function def get(self, vehicle_id, command, wake_if_asleep=False): # pylint: disable=unused-argument """Send get command to the vehicle_id. This is a wrapped function by wake_up. Parameters ---------- vehicl...
You are a Python code analyst, evaluating scripts for potential improvements.
def data_request(self, vehicle_id, name, wake_if_asleep=False): """Get requested data from vehicle_id. Parameters ---------- vehicle_id : string Identifier for the car on the owner-api endpoint. Confusingly it is not the vehicle_id field for identifying the car a...
Write a Python 3 script to get requested data from vehicle_id.
You are a Python code generator, capable of creating scripts from specifications.
Post a command to the vehicle_id.
Here you have a function in Python 3, explain what it does def command(self, vehicle_id, name, data=None, wake_if_asleep=True): data = data or {} return self.post(vehicle_id, 'command/%s' % name, data, wake_if_asleep=wake_if_asleep)
You are a Python code generator, capable of creating scripts from specifications.
This command updates all the vehicle attributes in the cache.
Can you tell what is the following Python 3 function doing def update(self, car_id=None, wake_if_asleep=False, force=False): cur_time = time.time() with self.__lock: # Update the online cars using get_vehicles() last_update = self._last_attempted_update_time if (forc...
You are a Python code architect, reviewing and designing scalable and efficient code
def update(self): """Update the battery state.""" self._controller.update(self._id, wake_if_asleep=False) data = self._controller.get_charging_params(self._id) if data: self.__battery_level = data['battery_level'] self.__charging_state = data['charging_state']
Create a Python 3 function for updating the battery state.
You are a Python code generator, capable of creating scripts from specifications.
def update(self): """Update the battery range state.""" self._controller.update(self._id, wake_if_asleep=False) data = self._controller.get_charging_params(self._id) if data: self.__battery_range = data['battery_range'] self.__est_battery_range = data['est_battery...
Can you create a Python 3 function that updates the battery range state.
As a Python code analyst, you investigate and solve complex coding mysteries
def assumed_state(self): # pylint: disable=protected-access """Return whether the data is from an online vehicle.""" return (not self._controller.car_online[self.id()] and (self._controller._last_update_time[self.id()] - self._controller._last_wake_up_time[self.i...
Write a Python 3 script to return whether the data is from an online vehicle.
You are a Python code architect, reviewing and designing scalable and efficient code
def update(self): """Update the current GPS location.""" self._controller.update(self._id, wake_if_asleep=False) data = self._controller.get_drive_params(self._id) if data: self.__longitude = data['longitude'] self.__latitude = data['latitude'] self.__...
Write a Python 3 function that can update the current GPS location.
As a Python code analyst, you investigate and solve complex coding mysteries
Update the odometer and the unit of measurement based on GUI.
Can you generate a brief explanation for the following Python 3 code def update(self): self._controller.update(self._id, wake_if_asleep=False) data = self._controller.get_state_params(self._id) if data: self.__odometer = data['odometer'] data = self._controller.get_gui_params...
As a Python code translator, you convert algorithms and pseudocode into Python.
def lc(**kwargs): """ Create parameters for a new light curve dataset. Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_dataset` :parameter **kwargs: defaults for the values of any of the parameters :return: a :class:`phoebe.parameters.p...
How would you implement a function in Python 3 that creates a parameter set for a new light curve dataset.
As a Python code analyst, you investigate and solve complex coding mysteries
def rv(**kwargs): """ Create parameters for a new radial velocity dataset. Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_dataset` :parameter **kwargs: defaults for the values of any of the parameters :return: a :class:`phoebe.paramete...
Can you implement a function in Python 3 that creates parameters for a new radial velocity dataset.
As a Python code analyst, you investigate and solve complex coding mysteries
Create parameters for a new line profile dataset.
Given the following Python 3 function, write the documentation def lp(**kwargs): obs_params = [] #obs_params += [FloatParameter(qualifier='statweight', value = kwargs.get('statweight', 1.0), default_unit=u.dimensionless_unscaled, description='Statistical weight in overall fitting')] syn_params, constraint...
You are a Python code architect, reviewing and designing scalable and efficient code
def etv(**kwargs): """ Create parameters for a new eclipse timing variations dataset. Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_dataset` :parameter **kwargs: default for the values of any of the ParameterSet :return: a :class:`pho...
Write a Python 3 function that can create a ParameterSet for a new eclipse timing variations dataset.
You are a Python code generator, capable of creating scripts from specifications.
def orb(**kwargs): """ Create parameters for a new orbit dataset. Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_dataset` :parameter **kwargs: defaults for the values of any of the parameters :return: a :class:`phoebe.parameters.parame...
Write a Python 3 script to create a new orbit dataset.
You are a Python code analyst, evaluating scripts for potential improvements.
Creates a parameter set for a new mesh dataset.
Can you tell what is the following Python 3 function doing def mesh(**kwargs): obs_params = [] syn_params, constraints = mesh_syn(syn=False, **kwargs) obs_params += syn_params.to_list() obs_params += [SelectParameter(qualifier='include_times', value=kwargs.get('include_times', []), description='appen...
You are a Python code architect, reviewing and designing scalable and efficient code
def phoebe(**kwargs): """ Compute options for using the PHOEBE 2.0 backend. Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_compute` Please see :func:`phoebe.backend.backends.phoebe` for a list of sources to cite when using this backend...
Can you create a Python 3 function that returns a new set of parameters for using the PHOEBE 2. 0 backend.
As a Python code composer, you craft elegant and concise scripts.
def legacy(**kwargs): """ Compute options for using the PHOEBE 1.0 legacy backend (must be installed). Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_compute` Please see :func:`phoebe.backend.backends.legacy` for a list of sources to ...
How would you implement a function in Python 3 that generates a new set of parameters for using the PHOEBE 1. 0 legacy backend.
As a Python code composer, you craft elegant and concise scripts.
def photodynam(**kwargs): """ Compute options for using Josh Carter's 'photodynam' code as a backend (must be installed). Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_compute` Please see :func:`phoebe.backend.backends.photodynam` for...
Implement a function in Python 3 to return a ParameterSet that can be used to create a new a for use with photodynam.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a ParameterSet that can be used to create synthetics in a new John Southworth dataset.
Here you have a function in Python 3, explain what it does def jktebop(**kwargs): if not conf.devel: raise NotImplementedError("'jktebop' backend not officially supported for this release. Enable developer mode to test.") params = [] params += [BoolParameter(qualifier='enabled', copy_for={'contex...
As a Python code translator, you convert algorithms and pseudocode into Python.
Decorator for views that require a team be supplied wither via a slug in the the url pattern or already set on the request object.
Can you generate the documentation for the following Python 3 function def team_required(func=None): def decorator(view_func): @functools.wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): slug = kwargs.pop("slug", None) if not ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Decorator for views that require only a team but also that a user be logged in and be the manager or owner of that team.
Can you generate the documentation for the following Python 3 function def manager_required(func=None): def decorator(view_func): @team_required @login_required @functools.wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): r...
You are a Python code generator, capable of creating scripts from specifications.
Return the next possible completion for text.
Can you generate a brief explanation for the following Python 3 code def complete(self, text, state): if self.use_main_ns: self.namespace = __main__.__dict__ if state == 0: self.matches = self.attr_matches(text) try: return self.matches[state] except I...
As a Python code composer, you craft elegant and concise scripts.
def attr_matches(self, text): """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluable in self.namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class insta...
Write a Python 3 script for computing matches when the given text contains a dot.
You are a Python code architect, reviewing and designing scalable and efficient code
def _extract_from_bundle(b, compute, times=None, allow_oversample=False, by_time=True, **kwargs): """ Extract a list of sorted times and the datasets that need to be computed at each of those times. Any backend can then loop through these times and see what quantities are neede...
Write a Python 3 function that can extract a list of sorted times and the datasets that need to be computed at each of those times. Any backend can then loop through these times and see what quantities are needed for that time step. Empty copies of synthetics for each applicable dataset are then created and returned so...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _create_syns(b, needed_syns): """ Create empty synthetics :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter list needed_syns: list of dictionaries containing kwargs to access the dataset (dataset, component, kind) :return: :class:`phoebe.parameters.parameters.Parameter...
Write a Python 3 function that can create empty synthetics for all the needed_syns
As a Python code composer, you craft elegant and concise scripts.
Make a packet from kwargs
Given the following Python 3 function, write the documentation def _make_packet(qualifier, value, time, info, **kwargs): packet = {'dataset': kwargs.get('dataset', info['dataset']), 'component': kwargs.get('component', info['component']), 'kind': kwargs.get('kind', info['kind']), ...
You are a Python code generator, capable of creating scripts from specifications.
def run_checks(self, b, compute, times=[], **kwargs): """ run any sanity checks to make sure the parameters and options are legal for this backend. If they are not, raise an error here to avoid errors within the workers. Any physics-checks that are backend-independent should be...
Write a Python 3 function that can run any sanity checks for the given backend
You are a Python code architect, reviewing and designing scalable and efficient code
fills synsets with new ones
Can you tell what is the following Python 3 function doing def _fill_syns(self, new_syns, rpacketlists_per_worker): # TODO: move to BaseBackendByDataset or BaseBackend? logger.debug("rank:{}/{} {}._fill_syns".format(mpi.myrank, mpi.nprocs, self.__class__.__name__)) for packetlists in rpacketlis...
You are a Python code analyst, evaluating scripts for potential improvements.
run the packet and return a list of synapses
Can you generate the documentation for the following Python 3 function def run(self, b, compute, times=[], **kwargs): self.run_checks(b, compute, times, **kwargs) logger.debug("rank:{}/{} calling get_packet_and_syns".format(mpi.myrank, mpi.nprocs)) packet, new_syns = self.get_packet_and_syns(b,...
As a python code expert, you are capable of creating scripts from specifications.
def compute_volume(sizes, centers, normals): """ Compute the numerical volume of a convex mesh :parameter array sizes: array of sizes of triangles :parameter array centers: array of centers of triangles (x,y,z) :parameter array normals: array of normals of triangles (will normalize if not already) ...
Can you implement a function in Python 3 that computes the numerical volume of a convex mesh
As a Python code composer, you craft elegant and concise scripts.
def euler_trans_matrix(etheta, elongan, eincl): """ Get the transformation matrix R to translate/rotate a mesh according to euler angles. The matrix is R(long,incl,theta) = Rz(pi).Rz(long).Rx(incl).Rz(theta) Rz(long).Rx(-incl).Rz(theta).Rz(pi) where Rx(u) = 1, 0, ...
Write a Python 3 function for getting the transformation matrix R to translate a mesh according to the euler angles.
You are a Python code analyst, evaluating scripts for potential improvements.
def spin_in_system(incl, long_an): """ Spin in the plane of sky of a star given its inclination and "long_an" incl - inclination of the star in the plane of sky long_an - longitude of ascending node (equator) of the star in the plane of sky Return: spin - in plane of sky """ ...
Implement a function in Python 3 to return the spin in the plane of a sky of a resource in the system.
You are a Python code generator, capable of creating scripts from specifications.
def spin_in_roche(s, etheta, elongan, eincl): """ Transform the spin s of a star on Kerpler orbit with etheta - true anomaly elongan - longitude of ascending node eincl - inclination from in the plane of sky reference frame into the Roche reference frame. """ # m = Rz(long).Rx(-i...
Create a Python 3 function to transform the spin s of a star on Kerpler orbit with the specified anomaly elongan and inclination elongan and eincl.
You are a Python code generator, capable of creating scripts from specifications.
Transform any Nx3 position array by translating to a center - of - mass position vector and applying an euler transformation to the positions of the n - mass entry.
Can you generate the documentation for the following Python 3 function def transform_position_array(array, pos, euler, is_normal, reverse=False): trans_matrix = euler_trans_matrix(*euler) if not reverse: trans_matrix = trans_matrix.T if isinstance(array, ComputedColumn): array = array.for_...
As a python code expert, you are capable of creating scripts from specifications.
Transform any Nx3 velocity vector array by adding the center - of - mass vel and applying an euler transformation.
Make a summary of the following Python 3 code def transform_velocity_array(array, pos_array, vel, euler, rotation_vel=(0,0,0)): trans_matrix = euler_trans_matrix(*euler) # v_{rot,i} = omega x r_i with omega = rotation_vel rotation_component = np.cross(rotation_vel, pos_array, axisb=1) orbital_comp...
You are a Python code analyst, evaluating scripts for potential improvements.
Transform a wd - style mesh to a dictionary of meshes.
Can you generate a brief explanation for the following Python 3 code def wd_grid_to_mesh_dict(the_grid, q, F, d): # WD returns a list of triangles with 9 coordinates (v1x, v1y, v1z, v2x, ...) triangles_9N = the_grid[:,4:13] new_mesh = {} # force the mesh to be computed at centers rather than the PHOEB...
You are a Python code architect, reviewing and designing scalable and efficient code
def averages(self): """ Access to the average of the values at the vertices for each triangle. If the quantities are defined at centers instead of vertices, this will return None. Also see :method:`centers`. :return: numpy array or None """ if not self.mesh._com...
Implement a function in Python 3 to return the average of the values at each triangle.
You are a Python code analyst, evaluating scripts for potential improvements.
def weighted_averages(self): """ Access to the weighted averages of the values at the vertices for each triangle based on the weights provided by mesh.weights. This is most useful for partially visible triangles when using libphoebe's eclipse detection that returns weights for e...
How would you code a function in Python 3 to return the weighted averages of the values at each vertex in the mesh.
You are a Python code generator, capable of creating scripts from specifications.
def set_for_computations(self, value): """ Set the quantities, either at the vertices or centers depending on the settings of the mesh (mesh._compute_at_vertices) """ if self.mesh._compute_at_vertices: self._vertices = value else: self._centers = v...
Write a Python 3 script to set the quantities at which the user has requested the compute.
As a Python code translator, you convert algorithms and pseudocode into Python.
Update the value of a column or multiple columns by passing as a dict.
Make a summary of the following Python 3 code def update_columns_dict(self, kwargs): # make sure to do the geometric things that are needed for some of the # ComputedColumns first for key in ('triangles', 'vertices', 'centers', 'vnormals', 'tnormals'): if key in kwargs.keys(): ...
As a python code expert, you are capable of creating scripts from specifications.
Returns the coordinates of the center of the star for each element in the species.
Can you tell what is the following Python 3 function doing def coords_for_observations(self): if self._compute_at_vertices: return self.vertices - self._pos_center else: return self.centers - self._pos_center
As a python code expert, you are capable of creating scripts from specifications.
Return the coordinates of the center of the star for each element in the species.
Given the following Python 3 function, write the documentation def coords_for_computations(self): # TODO: need to subtract the position offset if a Mesh (in orbit) if self._compute_at_vertices: if self.pvertices is not None: return self.pvertices - self._pos_center ...
As a Python code analyst, you investigate and solve complex coding mysteries
def rs(self): """ Return the radius of each element (either vertices or centers depending on the setting in the mesh) with respect to the center of the star. NOTE: unscaled (ComputedColumn) """ rs = np.linalg.norm(self.coords_for_computations, axis=1) ...
Write a Python 3 script to return the radius of each element in the mesh
As a Python code analyst, you investigate and solve complex coding mysteries
def rprojs(self): """ Return the projected (in xy/uv plane) radius of each element (either vertices or centers depending on the setting in the mesh) with respect to the center of the star. NOTE: unscaled (ComputedColumn) """ # TODO: should this be moved ...
Implement a function in Python 3 to return the projected radius of each element in the star with respect to the center of the star.
As a Python code composer, you craft elegant and concise scripts.
Returns the cosbetas of the current column.
Make a summary of the following Python 3 code def cosbetas(self): coords = self.coords_for_computations norms = self.normals_for_computations # TODO: ditch the list comprehension... I know I figured out how to do # this (ie along an axis) with np.dot somewhere else # cosbetas = ...
As a Python code composer, you craft elegant and concise scripts.
def areas_si(self): """ TODO: add documentation """ if self._areas is not None: return (self.areas*u.solRad**2).to(u.m**2).value else: return None
Write a Python 3 script to return the area in si of the assessment.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a new instance of this class from a protobuf mesh.
Given the following Python 3 function, write the documentation def from_proto(cls, proto_mesh, scale): mesh = cls(**proto_mesh.items()) mesh._copy_roche_values() mesh._scale_mesh(scale=scale) return mesh
As a Python code composer, you craft elegant and concise scripts.
def _scale_mesh(self, scale): """ TODO: add documentation """ pos_ks = ['vertices', 'centers'] # TODO: scale velocities??? # handle scale self.update_columns_dict({k: self[k]*scale for k in pos_ks}) self.update_columns(areas=self.areas*(scale**2)) ...
Create a Python 3 function to scale the mesh of the current object
You are a Python code architect, reviewing and designing scalable and efficient code
Turn a ProtoMesh into a Mesh scaled and placed in orbit.
Can you tell what is the following Python 3 function doing def from_proto(cls, proto_mesh, scale, pos, vel, euler, euler_vel, rotation_vel=(0,0,0), component_com_x=None): """ Turn a ProtoMesh into a Mesh scaled and placed in orbit. ...
You are a Python code generator, capable of creating scripts from specifications.
def from_scaledproto(cls, scaledproto_mesh, pos, vel, euler, euler_vel, rotation_vel=(0,0,0), component_com_x=None): """ TODO: add documentation """ mesh = cls(**scaledproto_mesh.items()) # roche coordin...
Create a Python 3 function for creating a new mesh from a scaledproto mesh.
You are a Python code architect, reviewing and designing scalable and efficient code
Return the array of visibilities for the current locale.
Given the following Python 3 function, write the documentation def visibilities(self): if self._visibilities is not None: return self._visibilities else: return np.ones(self.Ntriangles)
As a Python code translator, you convert algorithms and pseudocode into Python.
def weights(self): """ TODO: add documentation (Nx3) """ if self._weights is not None and len(self._weights): return self._weights else: return np.full((self.Ntriangles, 3), 1./3)
How would you code a function in Python 3 to return a numpy array of the 3 - dimensional weights of the current instance of the class.
You are a Python code generator, capable of creating scripts from specifications.
def update_columns_dict(self, kwargs): """ TODO: add documentation """ super(Mesh, self).update_columns_dict(kwargs) # if kwargs.get('vnormals', None) is not None or kwargs.get('tnormals', None) is not None: # self._compute_mus() if kwargs.get('triangles', No...
Implement a Python 3 function for updating the columns of the object with the values from kwargs.
You are a Python code generator, capable of creating scripts from specifications.
update the columns of all components in the current mesh
Explain what the following Python 3 code does def update_columns(self, field, value_dict, inds=None, computed_type=None): if not isinstance(value_dict, dict): value_dict = {comp_no: value_dict for comp_no in self._dict.keys()} for comp, value in value_dict.items(): if computed_...
You are a Python code generator, capable of creating scripts from specifications.
get_column returns a dictionary of the components of the current object
Make a summary of the following Python 3 code def get_column(self, field, components=None, computed_type='for_observations'): def get_field(c, field, computed_type): if c not in self._dict.keys() and self._parent_envelope_of[c] in self._dict.keys(): mesh = self._dict[self._parent_en...
As a Python code translator, you convert algorithms and pseudocode into Python.
get_column_flat - get a single merged value from all meshes
Explain what the following Python 3 code does def get_column_flat(self, field, components=None, computed_type='for_observations'): return self.pack_column_flat(self.get_column(field, components, computed_type), components, offset=field=='...
You are a Python code generator, capable of creating scripts from specifications.
Pack a column into a flat array.
Make a summary of the following Python 3 code def pack_column_flat(self, value, components=None, offset=False): if components: if isinstance(components, str): components = [components] elif isinstance(components, list): components = components ...
You are a Python code analyst, evaluating scripts for potential improvements.
def unpack_column_flat(self, value, components=None, offset=False, computed_type=None): """ TODO: add documentation TODO: needs testing """ if components: if isinstance(components, str): components = [components] else: components = ...
Write a Python 3 script for unpacking the flat array of values into a dictionary.
You are a Python code architect, reviewing and designing scalable and efficient code
Set a flat column of the log record.
Can you generate a brief explanation for the following Python 3 code def set_column_flat(self, field, value, components=None, computed_type=None): value_dict = self.unpack_column_flat(value, components, computed_type=computed_type) self.update_columns(field, value_dict, computed_type=computed_type)
As a Python code analyst, you investigate and solve complex coding mysteries
Replace elements in the specified component with new_submesh.
Explain what the following Python 3 code does def replace_elements(self, inds, new_submesh, component): self._dict[component] = np.hstack([self._dict[component][~inds], new_submesh])
You are a Python code analyst, evaluating scripts for potential improvements.
def dynamics_from_bundle(b, times, compute=None, return_euler=False, **kwargs): """ Parse parameters in the bundle and call :func:`dynamics`. See :func:`dynamics` for more detailed information. NOTE: you must either provide compute (the label) OR all relevant options as kwargs (ltte) Args: ...
Can you write a function in Python 3 where it parses parameters in the bundle and call dynamics.
As a Python code translator, you convert algorithms and pseudocode into Python.
def dynamics(times, periods, eccs, smas, t0_perpasses, per0s, long_ans, incls, dpdts, deccdts, dperdts, components, t0=0.0, vgamma=0.0, mass_conservation=True, ltte=False, return_euler=False): """ Compute the positions and velocites of each star in their nested Keplerian orbits at a ...
Write a Python 3 function that can compute the positions and velocites of each star in their nested Keplerian orbits at a given list of times. See :func:`dynamics_from_bundle` for a wrapper around this function which automatically handles passing everything in the correct order and in the correct units. Args: times: (i...
You are a Python code generator, capable of creating scripts from specifications.
Creates a parameter set that can be used to create a spot in a non - empty sequence.
Given the following Python 3 function, write the documentation def spot(feature, **kwargs): params = [] params += [FloatParameter(qualifier="colat", value=kwargs.get('colat', 0.0), default_unit=u.deg, description='Colatitude of the center of the spot wrt spin axes')] params += [FloatParameter(qualifier="l...
You are a Python code generator, capable of creating scripts from specifications.
Creates a parameter set for a pulsation feature
Can you tell what is the following Python 3 function doing def pulsation(feature, **kwargs): if not conf.devel: raise NotImplementedError("'pulsation' feature not officially supported for this release. Enable developer mode to test.") params = [] params += [FloatParameter(qualifier='radamp', val...
As a python code expert, you are capable of creating scripts from specifications.
def anim_to_html(anim): """ adapted from: http://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/ This function converts and animation object from matplotlib into HTML which can then be embedded in an IPython notebook. This requires ffmpeg to be installed in order to build the in...
How would you implement a function in Python 3 that converts an animation object from matplotlib into HTML which can then be displayed in an IPython notebook.
As a Python code translator, you convert algorithms and pseudocode into Python.
load the lc data file into a dictionary with lc data
How would you explain what the following Python 3 function does def load_lc_data(filename, indep, dep, indweight=None, mzero=None, dir='./'): """ load dictionary with lc data """ if '/' in filename: path, filename = os.path.split(filename) else: # TODO: this needs to change to be di...
You are a Python code architect, reviewing and designing scalable and efficient code
def load_rv_data(filename, indep, dep, indweight=None, dir='./'): """ load dictionary with rv data. """ if '/' in filename: path, filename = os.path.split(filename) else: path = dir load_file = os.path.join(path, filename) rvdata = np.loadtxt(load_file) d ={} d['p...
Implement a function in Python 3 to load the rv data file into a dictionary with rv data.
As a python code expert, you are capable of creating scripts from specifications.
This function will remove the dataset from the RV and passband from the RV and passband of the RV.
Can you generate the documentation for the following Python 3 function def det_dataset(eb, passband, dataid, comp, time): """ Since RV datasets can have values related to each component in phoebe2, but are component specific in phoebe1 , it is important to determine which dataset to add parameters to. This...
As a python code expert, you are capable of creating scripts from specifications.
Converts a WD style grid size N to the number of triangles on the surface.
Make a summary of the following Python 3 code def N_to_Ntriangles(N): theta = np.array([np.pi/2*(k-0.5)/N for k in range(1, N+1)]) phi = np.array([[np.pi*(l-0.5)/Mk for l in range(1, Mk+1)] for Mk in np.array(1 + 1.3*N*np.sin(theta), dtype=int)]) Ntri = 2*np.array([len(p) for p in phi]).sum() return N...
As a Python code composer, you craft elegant and concise scripts.
returns the potential for a given component
Given the following Python 3 function, write the documentation def pot_for_component(pot, q, component=1, reverse=False): # currently only used by legacy wrapper: consider moving/removing if component==1: return pot elif component==2: if reverse: return pot/q + 0.5*(q-1)/q ...
You are a Python code analyst, evaluating scripts for potential improvements.
calculate the misaligned critical requiv
Can you generate the documentation for the following Python 3 function def roche_misaligned_critical_requiv(q, F, d, s, scale=1.0): volume_critical = libphoebe.roche_misaligned_critical_volume(q, F, d, s) logger.debug("libphoebe.roche_misaligned_critical_volume(q={}, F={}, d={}, s={}) => {}".format(q, F, d, s, ...
You are a Python code architect, reviewing and designing scalable and efficient code
def rpole_to_pot_aligned(rpole, sma, q, F, d, component=1): """ Transforms polar radius to surface potential """ q = q_for_component(q, component=component) rpole_ = np.array([0, 0, rpole/sma]) logger.debug("libphoebe.roche_Omega(q={}, F={}, d={}, rpole={})".format(q, F, d, rpole_)) pot = li...
How would you code a function in Python 3 to transform polar radius to surface potential
As a python code expert, you are capable of creating scripts from specifications.
Transforms surface potential to polar radius
Can you tell what is the following Python 3 function doing def pot_to_rpole_aligned(pot, sma, q, F, d, component=1): q = q_for_component(q, component=component) Phi = pot_for_component(pot, q, component=component) logger.debug("libphobe.roche_pole(q={}, F={}, d={}, Omega={})".format(q, F, d, pot)) retur...
As a Python code translator, you convert algorithms and pseudocode into Python.
r Computes a value of the asynchronous eccentric Roche potential.
Here you have a function in Python 3, explain what it does def BinaryRoche (r, D, q, F, Omega=0.0): return 1.0/sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]) + q*(1.0/sqrt((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])-r[0]/D/D) + 0.5*F*F*(1+q)*(r[0]*r[0]+r[1]*r[1]) - Omega
You are a Python code architect, reviewing and designing scalable and efficient code