output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def view(): """Get a dictionary representation of current metrics.""" if not initialized: raise NotInitialized marshalled_metrics_mmap.seek(0) try: uwsgi.lock() marshalled_view = marshalled_metrics_mmap.read( MAX_MARSHALLED_VIEW_SIZE) finally: uwsgi.unloc...
Can you implement a function in Python 3 that gets a dictionary representation of current metrics.
You are a Python code analyst, evaluating scripts for potential improvements.
Record a timing delta
How would you explain what the following Python 3 function does def timer(module, name, delta, duration_units='milliseconds'): timer = get_metric('timers', module, name, Timer(duration_units)) timer.update(delta)
You are a Python code generator, capable of creating scripts from specifications.
def histogram(module, name, value): """ Record a value in a histogram: :: histogram(__name__, 'my_histogram', len(queue)) """ histogram = get_metric('histograms', module, name, Histogram()) histogram.update(value)
Create a Python 3 function for recording a value in a histogram
As a python code expert, you are capable of creating scripts from specifications.
Record an event s occurence in a counter
Here you have a function in Python 3, explain what it does def counter(module, name, count=1): counter = get_metric('counters', module, name, Counter()) counter.inc(count)
You are a Python code architect, reviewing and designing scalable and efficient code
Record a meter event rate
Here you have a function in Python 3, explain what it does def meter(module, name, count=1): meter = get_metric('meters', module, name, Meter()) meter.mark(count)
As a Python code analyst, you investigate and solve complex coding mysteries
Execute a command on a set of nodes.
Given the following Python 3 function, write the documentation def exec_command_on_nodes(nodes, cmd, label, conn_params=None): if isinstance(nodes, BASESTRING): nodes = [nodes] if conn_params is None: conn_params = DEFAULT_CONN_PARAMS logger.debug("Running %s on %s ", label, nodes) re...
As a python code expert, you are capable of creating scripts from specifications.
Write EMIRUUID header on reduction
Explain what the following Python 3 code does def convert_out(self, obj): newobj = super(ProcessedImageProduct, self).convert_out(obj) if newobj: hdulist = newobj.open() hdr = hdulist[0].header if 'EMIRUUID' not in hdr: hdr['EMIRUUID'] = str(uuid.uuid1...
You are a Python code generator, capable of creating scripts from specifications.
Verify the client ID client ID and client authentication method and access token.
Given the following Python 3 function, write the documentation def verify_client(endpoint_context, request, authorization_info): if not authorization_info: if 'client_id' in request and 'client_secret' in request: auth_info = ClientSecretPost(endpoint_context).verify(request) auth_i...
You are a Python code generator, capable of creating scripts from specifications.
def random_id(length): """Generates a random ID of given length""" def char(): """Generate single random char""" return random.choice(string.ascii_letters + string.digits) return "".join(char() for _ in range(length))
Write a Python 3 function that can generate a random ID of given length
You are a Python code architect, reviewing and designing scalable and efficient code
Context manager that closes the closable object.
Can you generate the documentation for the following Python 3 function def delayed_close(closable): close = getattr(closable, "close", None) if close: # we do not want the library to close file in case we need to # resume, hence make close a no-op # pylint: disable=unused-argument ...
As a python code expert, you are capable of creating scripts from specifications.
Store the connection between a Session ID and a User ID
Can you tell what is the following Python 3 function doing def map_sid2uid(self, sid, uid): self.set('sid2uid', sid, uid) self.set('uid2sid', uid, sid)
You are a Python code generator, capable of creating scripts from specifications.
Store the connection between a Session ID and a Subject ID.
Here you have a function in Python 3, explain what it does def map_sid2sub(self, sid, sub): self.set('sid2sub', sid, sub) self.set('sub2sid', sub, sid)
You are a Python code generator, capable of creating scripts from specifications.
def get_subs_by_uid(self, uid): """ Find all subject identifiers that is connected to a User ID. :param uid: A User ID :return: A set of subject identifiers """ res = set() for sid in self.get('uid2sid', uid): res |= set(self.get('sid2sub', sid)) ...
Create a Python 3 function to find all subject identifiers that are connected to a User ID.
As a Python code composer, you craft elegant and concise scripts.
def remove_sid2sub(self, sid, sub): """ Remove the connection between a session ID and a Subject :param sid: Session ID :param sub: Subject identifier ´ """ self.remove('sub2sid', sub, sid) self.remove('sid2sub', sid, sub)
Implement a function in Python 3 to remove the connection between a session ID and a Subject ID.
You are a Python code architect, reviewing and designing scalable and efficient code
Removes the connection between a session ID and a SubjectID.
Make a summary of the following Python 3 code def remove_sid2uid(self, sid, uid): self.remove('uid2sid', uid, sid) self.remove('sid2uid', sid, uid)
As a Python code composer, you craft elegant and concise scripts.
Remove all references to a specific Session ID
Explain what the following Python 3 code does def remove_session_id(self, sid): for uid in self.get('sid2uid', sid): self.remove('uid2sid', uid, sid) self.delete('sid2uid', sid) for sub in self.get('sid2sub', sid): self.remove('sub2sid', sub, sid) self.delete('si...
As a python code expert, you are capable of creating scripts from specifications.
def remove_uid(self, uid): """ Remove all references to a specific User ID :param uid: A User ID """ for sid in self.get('uid2sid', uid): self.remove('sid2uid', sid, uid) self.delete('uid2sid', uid)
Implement a Python 3 function for removing all references to a specific User ID
You are a Python code analyst, evaluating scripts for potential improvements.
def remove_sub(self, sub): """ Remove all references to a specific Subject ID :param sub: A Subject ID """ for _sid in self.get('sub2sid', sub): self.remove('sid2sub', _sid, sub) self.delete('sub2sid', sub)
Implement a function in Python 3 to remove all references to a specific Subject ID
As a python code expert, you are capable of creating scripts from specifications.
def up(force=True, env=None, **kwargs): "Starts a new experiment" inventory = os.path.join(os.getcwd(), "hosts") conf = Configuration.from_dictionnary(provider_conf) provider = Enos_vagrant(conf) roles, networks = provider.init() check_networks(roles, networks) env["roles"] = roles env["...
Write a Python 3 script to start a new experiment
You are a Python code architect, reviewing and designing scalable and efficient code
def get_public_attributes(cls, as_list=True): """ Return class attributes that are neither private nor magic. :param cls: class :param as_list: [True] set to False to return generator :return: only public attributes of class """ attrs = (a for a in dir(cls) if not a.startswith('_')) if ...
Write a Python 3 function that can return public attributes of class cls.
You are a Python code generator, capable of creating scripts from specifications.
def register(self, newitems, *args, **kwargs): """ Register newitems in registry. :param newitems: New items to add to registry. When registering new items, keys are not allowed to override existing keys in the registry. :type newitems: mapping :param arg...
How would you code a function in Python 3 to register new items in the internal registry.
As a Python code translator, you convert algorithms and pseudocode into Python.
def unregister(self, items): """ Remove items from registry. :param items: """ items = _listify(items) # get all members of Registry except private, special or class meta_names = (m for m in vars(self).iterkeys() if (not m.startswith('_') an...
How would you implement a function in Python 3 that removes items from the registry.
As a python code expert, you are capable of creating scripts from specifications.
Sets the meta attribute of the class with the meta class from bases and adds the meta - option attributes to the attributes of the class with the meta class from attributes.
Here you have a function in Python 3, explain what it does def set_meta(mcs, bases, attr): # pop the meta class from the attributes meta = attr.pop(mcs._meta_cls, types.ClassType(mcs._meta_cls, (), {})) # get a list of the meta public class attributes meta_attrs = get_public_attributes(m...
You are a Python code generator, capable of creating scripts from specifications.
Set parameters from a parameter file or from a parameter file.
Given the following Python 3 function, write the documentation def set_param_file_or_parameters(mcs, attr): meta = attr[mcs._meta_attr] # look for parameter file path in meta cls_path = getattr(meta, mcs._path_attr, None) cls_file = getattr(meta, mcs._file_attr, None) # read parameters ...
You are a Python code generator, capable of creating scripts from specifications.
Returns an instance of the class cls if it is known otherwise None.
Explain what the following Python 3 code does def factory(cls, **kwargs): for name, obj in inspect.getmembers(sys.modules[__name__]): if inspect.isclass(obj) and issubclass(obj, UserAuthnMethod): try: if obj.__name__ == cls: return obj(**kwargs) ex...
You are a Python code architect, reviewing and designing scalable and efficient code
Register new formulas and meta data.
Can you generate the documentation for the following Python 3 function def register(self, new_formulas, *args, **kwargs): kwargs.update(zip(self.meta_names, args)) # call super method, meta must be passed as kwargs! super(FormulaRegistry, self).register(new_formulas, **kwargs)
As a Python code composer, you craft elegant and concise scripts.
def import_formulas(self): """ Import formulas specified in :attr:`parameters`. :returns: formulas :rtype: dict """ # TODO: unit tests! # TODO: move this to somewhere else and call it "importy", maybe # core.__init__.py since a lot of modules might use it...
How would you implement a function in Python 3 that imports formulas specified in parameters.
You are a Python code generator, capable of creating scripts from specifications.
Create a new client for the reservation if nescessary.
Can you generate the documentation for the following Python 3 function def create_blazar_client(config, session): return blazar_client.Client(session=session, service_type="reservation", region_name=os.environ["OS_REGION_NAME"])
You are a Python code architect, reviewing and designing scalable and efficient code
This is a very specific decorator that can be used to be used on Interface classes. It will attempt to reconnect if the connection is closed and run the same method again.
Here you have a function in Python 3, explain what it does def reconnecting(count=None, backoff=None): # we get trixxy here so we can manipulate these values in the wrapped function, # this is one of the first times I wish we were on Python 3 # http://stackoverflow.com/a/9264845/5006 reconn_params = { ...
You are a Python code architect, reviewing and designing scalable and efficient code
Escapes a value so that it can be used in a mime header
Given the following Python 3 function, write the documentation def escape_header(val): if val is None: return None try: return quote(val, encoding="ascii", safe="/ ") except ValueError: return "utf-8''" + quote(val, encoding="utf-8", safe="/ ")
As a python code expert, you are capable of creating scripts from specifications.
def make_streams(name, value, boundary, encoding): """Generates one or more streams for each name, value pair""" filename = None mime = None # user passed in a special dict. if isinstance(value, collections.Mapping) and "name" in value and "value" in value: filename = value["name"] ...
Create a Python 3 function to generate one or more streams for each name value pair.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the length of the data stream.
Here you have a function in Python 3, explain what it does def len(self): # The len property is needed for requests. # requests checks __len__, then len # Since we cannot implement __len__ because python 32-bit uses 32-bit # sizes, we implement this instead. def stream_len(stream...
As a python code expert, you are capable of creating scripts from specifications.
def mk_pools(things, keyfnc=lambda x: x): "Indexes a thing by the keyfnc to construct pools of things." pools = {} sthings = sorted(things, key=keyfnc) for key, thingz in groupby(sthings, key=keyfnc): pools.setdefault(key, []).extend(list(thingz)) return pools
Write a Python 3 script for indexing a thing by the keyfnc to construct pools of things.
As a python code expert, you are capable of creating scripts from specifications.
def pick_things(pools, key, n): "Picks a maximum of n things in a dict of indexed pool of things." pool = pools.get(key) if not pool: return [] things = pool[:n] del pool[:n] return things
Write a Python 3 script for picking a maximum of n things in a dict of indexed pool of things.
You are a Python code architect, reviewing and designing scalable and efficient code
Open a volafile room and start listening to it.
Can you generate a brief explanation for the following Python 3 code def listen(room): def onmessage(m): """Print the new message and respond to it.""" print(m) if m.admin or m.nick == r.user.name: return if "parrot" in m.msg.lower(): r.post_chat("ayy lmao") ...
As a python code expert, you are capable of creating scripts from specifications.
def nscan_minmax_frontiers(y0_frontier_lower, y0_frontier_upper, resize=False): """Compute valid scan range for provided y0_frontier values. Parameters ---------- y0_frontier_lower : float Ordinate of the lower frontier. y0_frontier_upper : float Ordinate o...
Can you implement a function in Python 3 that computes valid scan range for provided y0_frontier lower and upper frontiers.
You are a Python code generator, capable of creating scripts from specifications.
def average_dtu_configurations(list_of_objects): """Return DtuConfiguration instance with averaged values. Parameters ---------- list_of_objects : python list List of DtuConfiguration instances to be averaged. Returns ------- result : DtuConfiguration instance Object with a...
Write a Python 3 function for returning the average DtuConfiguration instance with averaged values.
As a Python code composer, you craft elegant and concise scripts.
Returns a new DtuConfiguration instance with maximum differences.
Can you tell what is the following Python 3 function doing def maxdiff_dtu_configurations(list_of_objects): result = DtuConfiguration() if len(list_of_objects) == 0: return result list_of_members = result.__dict__.keys() # compute maximum difference for each member for member in list_of_...
As a python code expert, you are capable of creating scripts from specifications.
Define class object from header information in FITS file.
Explain what the following Python 3 code does def define_from_fits(cls, fitsobj, extnum=0): # read input FITS file with fits.open(fitsobj) as hdulist: image_header = hdulist[extnum].header return cls.define_from_header(image_header)
As a Python code analyst, you investigate and solve complex coding mysteries
Define class object from dictionary.
Here you have a function in Python 3, explain what it does def define_from_dictionary(cls, inputdict): self = DtuConfiguration() for item in self.__dict__: self.__dict__[item] = inputdict[item] return self
You are a Python code generator, capable of creating scripts from specifications.
def define_from_values(cls, xdtu, ydtu, zdtu, xdtu_0, ydtu_0, zdtu_0): """Define class object from from provided values. Parameters ---------- xdtu : float XDTU fits keyword value. ydtu : float YDTU fits keyword value. zdtu : float ZDT...
Can you implement a function in Python 3 that defines class object from provided values.
You are a Python code analyst, evaluating scripts for potential improvements.
def closeto(self, other, abserror): """Check that all the members are equal within provided absolute error. Parameters ---------- other : DtuConfiguration object DTU configuration instance to be compared with self. abserror : float Absolute maximum allowe...
Write a Python 3 script for checking that all the members are within the specified absolute error.
You are a Python code analyst, evaluating scripts for potential improvements.
Return dictionary structure rounded to a given precision.
Here you have a function in Python 3, explain what it does def outdict(self, ndigits=3): output = self.__dict__.copy() for item in output: output[item] = round(output[item], ndigits) return output
You are a Python code architect, reviewing and designing scalable and efficient code
Builds the list of endpoints for the given configuration.
Here you have a function in Python 3, explain what it does def build_endpoints(conf, endpoint_context, client_authn_method, issuer): if issuer.endswith('/'): _url = issuer[:-1] else: _url = issuer endpoint = {} for name, spec in conf.items(): try: kwargs = spec['kwa...
As a Python code analyst, you investigate and solve complex coding mysteries
Serializes using length : value format
Can you tell what is the following Python 3 function doing def lv_pack(*args): s = [] for a in args: s.append('{}:{}'.format(len(a), a)) return ''.join(s)
As a python code expert, you are capable of creating scripts from specifications.
Deserializes a string of the length : value format
Make a summary of the following Python 3 code def lv_unpack(txt): txt = txt.strip() res = [] while txt: l, v = txt.split(':', 1) res.append(v[:int(l)]) txt = v[int(l):] return res
As a Python code analyst, you investigate and solve complex coding mysteries
def init(self, force_deploy=False): """Reserve and deploys the vagrant boxes. Args: force_deploy (bool): True iff new machines should be started """ machines = self.provider_conf.machines networks = self.provider_conf.networks _networks = [] for netwo...
Can you create a Python 3 function that reserves and deploys the vagrant boxes.
You are a Python code architect, reviewing and designing scalable and efficient code
def destroy(self): """Destroy all vagrant box involved in the deployment.""" v = vagrant.Vagrant(root=os.getcwd(), quiet_stdout=False, quiet_stderr=True) v.destroy()
Can you create a Python 3 function that destroys all vagrant box involved in the deployment.
You are a Python code analyst, evaluating scripts for potential improvements.
Mark the passage of time and decay the current rate accordingly.
Given the following Python 3 function, write the documentation def tick(self): instant_rate = self.count / float(self.tick_interval_s) self.count = 0 if self.initialized: self.rate += (self.alpha * (instant_rate - self.rate)) else: self.rate = instant_rate ...
You are a Python code generator, capable of creating scripts from specifications.
def merge_odd_even_csu_configurations(conf_odd, conf_even): """Merge CSU configuration using odd- and even-numbered values. The CSU returned CSU configuration include the odd-numbered values from 'conf_odd' and the even-numbered values from 'conf_even'. Parameters ---------- conf_odd : CsuConf...
Can you create a Python 3 function that merges odd - and even - numbered CSU configurations into one CSU.
As a python code expert, you are capable of creating scripts from specifications.
Define class members directly from FITS header.
Explain what the following Python 3 code does def define_from_header(cls, image_header): self = CsuConfiguration() # declare lists to store configuration of CSU bars self._csu_bar_left = [] self._csu_bar_right = [] self._csu_bar_slit_center = [] self._csu_bar_slit_width...
You are a Python code architect, reviewing and designing scalable and efficient code
def outdict(self, ndigits=3): """Return dictionary structure rounded to a given precision.""" outdict = {} for i in range(EMIR_NBARS): ibar = i + 1 cbar = 'slitlet' + str(ibar).zfill(2) outdict[cbar] = {} outdict[cbar]['_csu_bar_left'] = \ ...
How would you code a function in Python 3 to return dictionary structure rounded to a given precision.
You are a Python code generator, capable of creating scripts from specifications.
Return list of slitlets which width is within given range.
Make a summary of the following Python 3 code def widths_in_range_mm( self, minwidth=EMIR_MINIMUM_SLITLET_WIDTH_MM, maxwidth=EMIR_MAXIMUM_SLITLET_WIDTH_MM ): """Return list of slitlets which width is within given range Parameters ---------- minwid...
You are a Python code analyst, evaluating scripts for potential improvements.
def encloses_annulus(x_min, x_max, y_min, y_max, nx, ny, r_in, r_out): '''Encloses function backported from old photutils''' gout = circular_overlap_grid(x_min, x_max, y_min, y_max, nx, ny, r_out, 1, 1) gin = circular_overlap_grid(x_min, x_max, y_min, y_max, nx, ny, r_in, 1, 1) return gout - gin
Create a Python 3 function for enclosing function backported from old photutils
You are a Python code generator, capable of creating scripts from specifications.
Compute background using anannulus
How would you explain what the following Python 3 function does def comp_back_with_annulus(img, xc, yc, r_in, r_out, frac=0.1): ''' center: [x,y], center of first pixel is [0,0] ''' x_min = -0.5 - xc x_max = img.shape[1] - 0.5 - xc y_min = -0.5 - yc y_max = img.shape[1] - 0.5 - yc mm = ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Main function for the rect_wpoly_for_mos command line tool.
Given the following Python 3 function, write the documentation def main(args=None): # parse command-line options parser = argparse.ArgumentParser(prog='rect_wpoly_for_mos') # required arguments parser.add_argument("input_list", help="TXT file with list JSON files derived from " ...
You are a Python code architect, reviewing and designing scalable and efficient code
Display a slitlet arrangement from CSUP keywords in FITS header.
Here you have a function in Python 3, explain what it does def display_slitlet_arrangement(fileobj, grism=None, spfilter=None, bbox=None, adjust=None, geometry=...
You are a Python code analyst, evaluating scripts for potential improvements.
Extract slitlet 2d image from image with original EMIR dimensions.
Given the following Python 3 function, write the documentation def extract_slitlet2d(self, image_2k2k): # protections naxis2, naxis1 = image_2k2k.shape if naxis1 != EMIR_NAXIS1: raise ValueError('Unexpected naxis1') if naxis2 != EMIR_NAXIS2: raise ValueError('Une...
You are a Python code generator, capable of creating scripts from specifications.
Rectify a 2d slitlet image.
Explain what the following Python 3 code does def rectify(self, slitlet2d, resampling, inverse=False): if resampling not in [1, 2]: raise ValueError("Unexpected resampling value=" + str(resampling)) # check image dimension naxis2, naxis1 = slitlet2d.shape if naxis1 != self....
As a python code expert, you are capable of creating scripts from specifications.
def ximshow_unrectified(self, slitlet2d): """Display unrectified image with spectrails and frontiers. Parameters ---------- slitlet2d : numpy array Array containing the unrectified slitlet image. """ title = "Slitlet#" + str(self.islitlet) ax = xims...
Write a Python 3 script for displaying unrectified image with spectrails and frontiers.
As a Python code analyst, you investigate and solve complex coding mysteries
Display rectified image with spectrails and frontiers.
Given the following Python 3 function, write the documentation def ximshow_rectified(self, slitlet2d_rect): title = "Slitlet#" + str(self.islitlet) + " (rectify)" ax = ximshow(slitlet2d_rect, title=title, first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig), show=F...
As a Python code composer, you craft elegant and concise scripts.
Return the type of Token and session id.
Given the following Python 3 function, write the documentation def info(self, token): verifier = JWT(key_jar=self.key_jar, allowed_sign_algs=[self.alg]) _payload = verifier.unpack(token) if is_expired(_payload['exp']): raise ToOld('Token has expired') return _payload['sid'], ...
You are a Python code architect, reviewing and designing scalable and efficient code
Evaluate whether the token has expired or not.
Explain what the following Python 3 code does def is_expired(self, token, when=0): verifier = JWT(key_jar=self.key_jar, allowed_sign_algs=[self.alg]) _payload = verifier.unpack(token) return is_expired(_payload['exp'], when)
As a python code expert, you are capable of creating scripts from specifications.
Create a new websocket.
Explain what the following Python 3 code does async def create_websocket(url: str, ssl: Optional[SSLContext] = None, headers: Optional[list] = None, subprotocols: Optional[list] = None): """ A more low-level form of open_websocket....
You are a Python code architect, reviewing and designing scalable and efficient code
async def open_websocket_client(sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[list] = None, subprotocols: Optional[list] = None): """Create a websocket on top of a socke...
How would you code a function in Python 3 to open a websocket on top of a socket.
As a Python code analyst, you investigate and solve complex coding mysteries
async def create_websocket_client(sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[List] = None, subprotocols: Optional[List[str]] = None): """ A more low-level...
Can you create a Python 3 function that creates a new websocket client.
As a Python code analyst, you investigate and solve complex coding mysteries
def range_mac(mac_start, mac_end, step=1): """Iterate over mac addresses (given as string).""" start = int(EUI(mac_start)) end = int(EUI(mac_end)) for i_mac in range(start, end, step): mac = EUI(int(EUI(i_mac)) + 1) ip = ['10'] + [str(int(i, 2)) for i in mac.bits().split('-')[-3:]] ...
Implement a function in Python 3 to iterate over the MAC addresses given as string.
As a Python code analyst, you investigate and solve complex coding mysteries
def _all(self, query): """Gets all rows of the query. Raises a NotFoundError if there are 0 rows""" if query.count() > 0: results = query.all() for result in results: if result.has_expired(self._expirations): raise NotFoundError ret...
Can you create a Python 3 function that gets all rows of the query. Raises a NotFoundError if there are 0 rows.
You are a Python code analyst, evaluating scripts for potential improvements.
def _put(self, item: SQLBaseObject): """Puts a item into the database. Updates lastUpdate column""" if item._dto_type in self._expirations and self._expirations[item._dto_type] == 0: # The expiration time has been set to 0 -> shoud not be cached return item.updated() ...
Create a Python 3 function to put a item into the database. Updates lastUpdate column
You are a Python code generator, capable of creating scripts from specifications.
Puts many items into the database. Updates lastUpdate column for each of them
Can you generate the documentation for the following Python 3 function def _put_many(self, items: Iterable[DtoObject], cls): if cls._dto_type in self._expirations and self._expirations[cls._dto_type] == 0: # The expiration time has been set to 0 -> shoud not be cached return sess...
You are a Python code architect, reviewing and designing scalable and efficient code
def filter(self, userinfo, user_info_claims=None): """ Return only those claims that are asked for. It's a best effort task; if essential claims are not present no error is flagged. :param userinfo: A dictionary containing the available info for one user :param user_info...
Create a Python 3 function for returning only those claims that are asked for.
As a Python code analyst, you investigate and solve complex coding mysteries
Construct a ChatMessage instance from raw protocol data.
Can you generate the documentation for the following Python 3 function def from_data(room, conn, data): files = list() rooms = dict() msg = str() for part in data["message"]: ptype = part["type"] if ptype == "text": val = part["value"] ...
You are a Python code analyst, evaluating scripts for potential improvements.
Create 2D rotation matrix
Explain what the following Python 3 code does def create_rot2d(angle): ca = math.cos(angle) sa = math.sin(angle) return np.array([[ca, -sa], [sa, ca]])
As a Python code composer, you craft elegant and concise scripts.
Detect objects in a region and return the brightest one
Can you tell what is the following Python 3 function doing def comp_centroid(data, bounding_box, debug_plot=False, plot_reference=None, logger=None): from matplotlib.patches import Ellipse if logger is None: logger = logging.getLogger(__name__) region = bounding_box.slice ref_x = region[1].st...
As a Python code composer, you craft elegant and concise scripts.
Sign and encrypt an IDToken
Make a summary of the following Python 3 code def sign_encrypt(self, session_info, client_id, code=None, access_token=None, user_info=None, sign=True, encrypt=False, extra_claims=None): """ Signed and or encrypt a IDToken :param session_info: Session in...
As a Python code analyst, you investigate and solve complex coding mysteries
Add layer class to model.
How would you explain what the following Python 3 function does def add(self, src_cls, module, package=None): # import module containing the layer class mod = importlib.import_module(module, package) # get layer class definition from the module self.sources[src_cls] = getattr(mod, src_cl...
As a python code expert, you are capable of creating scripts from specifications.
def add(self, data_source, module, package=None): """ Add data_source to model. Tries to import module, then looks for data source class definition. :param data_source: Name of data source to add. :type data_source: str :param module: Module in which data source resides....
Write a Python 3 script to add a data source to the model.
As a Python code composer, you craft elegant and concise scripts.
def open(self, data_source, *args, **kwargs): """ Open filename to get data for data_source. :param data_source: Data source for which the file contains data. :type data_source: str Positional and keyword arguments can contain either the data to use for the data source ...
Implement a function in Python 3 to open filename to get data for a specific data source.
You are a Python code analyst, evaluating scripts for potential improvements.
Load all data sources from the layer and open files with data for the data_source.
Can you generate the documentation for the following Python 3 function def load(self, rel_path=None): for k, v in self.layer.iteritems(): self.add(k, v['module'], v.get('package')) filename = v.get('filename') path = v.get('path') if filename: # de...
You are a Python code analyst, evaluating scripts for potential improvements.
Edit data layer. :param data_src: Name of :class:`DataSource` to edit. :type data_src: str :param value: Values to edit. :type value: dict
Can you tell what is the following Python 3 function doing def edit(self, data_src, value): # check if opening file if 'filename' in value: items = [k for k, v in self.reg.data_source.iteritems() if v == data_src] self.reg.unregister(items) # remove items fr...
As a Python code analyst, you investigate and solve complex coding mysteries
Adds a formula to the registry.
Can you generate the documentation for the following Python 3 function def add(self, formula, module, package=None): super(Formulas, self).add(formula, module, package) # only update layer info if it is missing! if formula not in self.layer: # copy formula source parameters to :attr:...
As a Python code composer, you craft elegant and concise scripts.
Load the current set of class names from the layer.
Here you have a function in Python 3, explain what it does def load(self, _=None): for k, v in self.layer.iteritems(): self.add(k, v['module'], v.get('package'))
As a Python code translator, you convert algorithms and pseudocode into Python.
Add a new calc to the layer.
Can you tell what is the following Python 3 function doing def add(self, calc, module, package=None): super(Calculations, self).add(calc, module, package) # only update layer info if it is missing! if calc not in self.layer: # copy calc source parameters to :attr:`Layer.layer` ...
You are a Python code generator, capable of creating scripts from specifications.
def add(self, output, module, package=None): """ Add output to """ super(Outputs, self).add(output, module, package) # only update layer info if it is missing! if output not in self.layer: # copy output source parameters to :attr:`Layer.layer` self...
Can you create a Python 3 function that adds output to the internal dictionary.
You are a Python code analyst, evaluating scripts for potential improvements.
Add simulation to layer.
Explain what the following Python 3 code does def add(self, sim, module, package=None): super(Simulations, self).add(sim, module, package) # only update layer info if it is missing! if sim not in self.layer: # copy simulation source parameters to :attr:`Layer.layer` self....
You are a Python code generator, capable of creating scripts from specifications.
Load all the sim_src files from the file system.
Can you generate a brief explanation for the following Python 3 code def load(self, rel_path=None): for k, v in self.layer.iteritems(): self.add(k, v['module'], v.get('package')) filename = v.get('filename') path = v.get('path') if filename: warnin...
As a python code expert, you are capable of creating scripts from specifications.
def f_solpos(times, latitude, longitude): """ Calculate solar position for lat/long at times. :param times: Python :class:`datetime.datetime` object. :type times: list :param latitude: latitude [degrees] :type latitude: float :param longitude: longitude [degrees] :type longitude: float ...
Create a Python 3 function for calculating solar position for lat / long at times.
As a Python code analyst, you investigate and solve complex coding mysteries
Calculate total irradiance of a single resource in a single resource in a single resource in a single resource in a single resource in a single resource in a single resource in a single resource in a single resource.
How would you explain what the following Python 3 function does def f_total_irrad(times, surface_tilt, surface_azimuth, solar_zenith, solar_azimuth, dni, ghi, dhi, dni_extra, am_abs, model='haydavies'): """ Calculate total irradiance :param times: timestamps :param s...
You are a Python code architect, reviewing and designing scalable and efficient code
Rescale the values in a numpy array to the z1z2 interval.
Explain what the following Python 3 code does def rescale_array_to_z1z2(array, z1z2=(-1.0, 1.0)): if type(array) is not np.ndarray: raise ValueError("array=" + str(array) + " must be a numpy.ndarray") array_min = array.min() array_max = array.max() z1, z2 = z1z2 delta = array_max - array_...
As a Python code translator, you convert algorithms and pseudocode into Python.
def rescale_array_from_z1z2(array_rs, coef_rs=None): """Restore the values in a numpy array rescaled to the [z1,z2] interval. The transformation is carried out following the relation array = (array_rs + c_flux)/b_flux as explained in Appendix B1 of Cardiel (2009, MNRAS, 396, 680) Parameters --...
Implement a Python 3 function for restoring the values in a numpy array rescaled to the [ z1 z2 interval.
As a python code expert, you are capable of creating scripts from specifications.
A class decorator to add Meta class attributes to the base class.
Here you have a function in Python 3, explain what it does def with_meta(class_to_decorate=None, add_init_kwargs=True): if class_to_decorate is None: return functools.partial(with_meta, add_init_kwargs=add_init_kwargs) if add_init_kwargs: def get_extra_args_function(self): return {...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a Struct containing all members of any contained meta class declarations from the given class or any of its base classes.
Here you have a function in Python 3, explain what it does def get_meta(cls): merged_attributes = Struct() for class_ in reversed(cls.mro()): if hasattr(class_, 'Meta'): for key, value in class_.Meta.__dict__.items(): merged_attributes[key] = value return merged_attribute...
You are a Python code generator, capable of creating scripts from specifications.
def creation_ordered(class_to_decorate): """ Class decorator that ensures that instances will be ordered after creation order when sorted. :type class_to_decorate: class :rtype: class """ next_index = functools.partial(next, itertools.count()) __init__orig = class_to_decorate....
Implement a Python 3 function for classing decorator that ensures that instances will be ordered after creation order when sorted. :type class_to_decorate: class :rtype: class
As a Python code analyst, you investigate and solve complex coding mysteries
def get_members(cls, member_class=None, is_member=None, sort_key=None, _parameter=None): """ Collect all class level attributes matching the given criteria. :param class member_class: Class(es) to collect :param is_member: Function to determine if an object should be collected :para...
Write a Python 3 script to return an ordered list of all class level attributes that match the given criteria.
You are a Python code analyst, evaluating scripts for potential improvements.
A class decorator that can be used to create a new hierarchy of classes that are defined in django models.
Make a summary of the following Python 3 code def declarative(member_class=None, parameter='members', add_init_kwargs=True, sort_key=default_sort_key, is_member=None): if member_class is None and is_member is None: raise TypeError("The @declarative decorator needs either a member_class parameter or an is_me...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_signature(func): """ :type func: Callable :rtype: str """ try: return object.__getattribute__(func, '__tri_declarative_signature') except AttributeError: pass try: if sys.version_info[0] < 3: # pragma: no mutate names, _, varkw, defaults ...
Can you implement a function in Python 3 that returns the signature of the function.
As a Python code analyst, you investigate and solve complex coding mysteries
Collect the namespace mappings from a dictionary of values.
Can you generate a brief explanation for the following Python 3 code def collect_namespaces(values): namespaces = {} result = dict(values) for key, value in values.items(): parts = key.split('__', 1) # pragma: no mutate if len(parts) == 2: prefix, name = parts if pre...
As a Python code translator, you convert algorithms and pseudocode into Python.
Extract mappings of the shape foo__bar baz 3 etc.
Given the following Python 3 function, write the documentation def extract_subkeys(kwargs, prefix, defaults=None): prefix += '__' result = {k[len(prefix):]: v for k, v in kwargs.items() if k.startswith(prefix)} if defaults is not None: return setdefaults(result, defaults) else: return r...
You are a Python code generator, capable of creating scripts from specifications.
def setdefaults(d, d2): """ :type d: dict :type d2: dict :rtype: dict """ for k, v in d2.items(): d.setdefault(k, v) return d
Write a Python 3 function for setting the default values of the object d to the values of d2.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get an attribute path as defined by a string separated by __.
Can you generate the documentation for the following Python 3 function def getattr_path(obj, path): path = path.split('__') for name in path: obj = getattr(obj, name) if obj is None: return None return obj
You are a Python code architect, reviewing and designing scalable and efficient code