text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all_posts(self): """Get all_posts, reloading the site if needed."""
rev = self.db.get('site:rev') if int(rev) != self.revision: self.reload_site() return self._all_posts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pages(self): """Get pages, reloading the site if needed."""
rev = self.db.get('site:rev') if int(rev) != self.revision: self.reload_site() return self._pages
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def options(self): """ Dictionary of options which affect the curve fitting algorithm. Must contain the key `fit_function` which must be set to the function that will perform the fit. All other options are passed as keyword arguments to the `fit_function`. The default options use `scipy.optimize.curve_fit`. If `fit_function` has the special value `lmfit`, then [lmfit][1] is used for the fit and all other options are passed as keyword arguments to [`lmfit.minimize`][2]. When using [lmfit][1], additional control of the fit is obtained by overriding `scipy_data_fitting.Fit.lmfit_fcn2min`. Any other function may be used for `fit_function` that satisfies the following criteria: * Must accept the following non-keyword arguments in this order (even if unused in the fitting function): 1. Function to fit, see `scipy_data_fitting.Fit.function`. 2. Independent values: see `scipy_data_fitting.Data.array`. 3. Dependent values: see `scipy_data_fitting.Data.array`. 4. List of the initial fitting parameter guesses in same order as given by `scipy_data_fitting.Fit.fitting_parameters`. The initial guesses will be scaled by their prefix before being passed. * Can accept any keyword arguments set in `scipy_data_fitting.Fit.options`. For example, this is how one could pass error values to the fitting function. * Must return an object whose first element is a list or array of the values of the fitted parameters (and only those values) in same order as given by `scipy_data_fitting.Fit.fitting_parameters`. Default: #!python { 'fit_function': scipy.optimize.curve_fit, 'maxfev': 1000, } [1]: http://lmfit.github.io/lmfit-py/ [2]: http://lmfit.github.io/lmfit-py/fitting.html#the-minimize-function """
if not hasattr(self, '_options'): self._options = { 'fit_function': scipy.optimize.curve_fit, 'maxfev': 1000, } return self._options
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def limits(self): """ Limits to use for the independent variable whenever creating a linespace, plot, etc. Defaults to `(-x, x)` where `x` is the largest absolute value of the data corresponding to the independent variable. If no such values are negative, defaults to `(0, x)` instead. """
if not hasattr(self, '_limits'): xmax = max(abs(self.data.array[0])) xmin = min(self.data.array[0]) x_error = self.data.error[0] if isinstance(x_error, numpy.ndarray): if x_error.ndim == 0: xmax = xmax + x_error if xmin < 0: self._limits = (-xmax, xmax) else: self._limits = (0, xmax) return self._limits
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fixed_values(self): """ A flat tuple of all values corresponding to `scipy_data_fitting.Fit.fixed_parameters` and `scipy_data_fitting.Fit.constants` after applying any prefixes. The values mimic the order of those lists. """
values = [] values.extend([ prefix_factor(param) * param['value'] for param in self.fixed_parameters ]) values.extend([ prefix_factor(const) * get_constant(const['value']) for const in self.constants ]) return tuple(values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def function(self): """ The function passed to the `fit_function` specified in `scipy_data_fitting.Fit.options`, and used by `scipy_data_fitting.Fit.pointspace` to generate plots, etc. Its number of arguments and their order is determined by items 1, 2, and 3 as listed in `scipy_data_fitting.Fit.all_variables`. All parameter values will be multiplied by their corresponding prefix before being passed to this function. By default, it is a functional form of `scipy_data_fitting.Fit.expression` converted using `scipy_data_fitting.Model.lambdify`. See also `scipy_data_fitting.Fit.lambdify_options`. """
if not hasattr(self,'_function'): function = self.model.lambdify(self.expression, self.all_variables, **self.lambdify_options) self._function = lambda *x: function(*(x + self.fixed_values)) return self._function
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def curve_fit(self): """ Fits `scipy_data_fitting.Fit.function` to the data and returns the output from the specified curve fit function. See `scipy_data_fitting.Fit.options` for details on how to control or override the the curve fitting algorithm. """
if not hasattr(self,'_curve_fit'): options = self.options.copy() fit_function = options.pop('fit_function') independent_values = self.data.array[0] dependent_values = self.data.array[1] if fit_function == 'lmfit': self._curve_fit = lmfit.minimize( self.lmfit_fcn2min, self.lmfit_parameters, args=(independent_values, dependent_values, self.data.error), **options) else: p0 = [ prefix_factor(param) * param['guess'] for param in self.fitting_parameters ] self._curve_fit = fit_function( self.function, independent_values, dependent_values, p0, **options) return self._curve_fit
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fitted_parameters(self): """ A tuple of fitted values for the `scipy_data_fitting.Fit.fitting_parameters`. The values in this tuple are not scaled by the prefix, as they are passed back to `scipy_data_fitting.Fit.function`, e.g. in most standard use cases these would be the SI values. If no fitting parameters were specified, this will just return an empty tuple. """
if hasattr(self,'_fitted_parameters'): return self._fitted_parameters if not self.fitting_parameters: return tuple() if self.options['fit_function'] == 'lmfit': return tuple( self.curve_fit.params[key].value for key in sorted(self.curve_fit.params) ) else: return tuple(self.curve_fit[0])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fitted_function(self): """ A function of the single independent variable after partially evaluating `scipy_data_fitting.Fit.function` at the `scipy_data_fitting.Fit.fitted_parameters`. """
function = self.function fitted_parameters = self.fitted_parameters return lambda x: function(x, *fitted_parameters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def computed_fitting_parameters(self): """ A list identical to what is set with `scipy_data_fitting.Fit.fitting_parameters`, but in each dictionary, the key `value` is added with the fitted value of the quantity. The reported value is scaled by the inverse prefix. """
fitted_parameters = [] for (i, v) in enumerate(self.fitting_parameters): param = v.copy() param['value'] = self.fitted_parameters[i] * prefix_factor(param)**(-1) fitted_parameters.append(param) return fitted_parameters
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pointspace(self, **kwargs): """ Returns a dictionary with the keys `data` and `fit`. `data` is just `scipy_data_fitting.Data.array`. `fit` is a two row [`numpy.ndarray`][1], the first row values correspond to the independent variable and are generated using [`numpy.linspace`][2]. The second row are the values of `scipy_data_fitting.Fit.fitted_function` evaluated on the linspace. For both `fit` and `data`, each row will be scaled by the corresponding inverse prefix if given in `scipy_data_fitting.Fit.independent` or `scipy_data_fitting.Fit.dependent`. Any keyword arguments are passed to [`numpy.linspace`][2]. [1]: http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html [2]: http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html """
scale_array = numpy.array([ [prefix_factor(self.independent)**(-1)], [prefix_factor(self.dependent)**(-1)] ]) linspace = numpy.linspace(self.limits[0], self.limits[1], **kwargs) return { 'data': self.data.array * scale_array, 'fit': numpy.array([linspace, self.fitted_function(linspace)]) * scale_array }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_json(self, path, points=50, meta=None): """ Write the results of the fit to a json file at `path`. `points` will define the length of the `fit` array. If `meta` is given, a `meta` key be added with the given value. The json object has the form #!text { 'meta': meta } """
pointspace = self.pointspace(num=points) fit_points = numpy.dstack(pointspace['fit'])[0] data_points = numpy.dstack(pointspace['data'])[0] fit = [ [ point[0], point[1] ] for point in fit_points ] data = [ [ point[0], point[1] ] for point in data_points ] obj = {'data': data, 'fit': fit} if meta: obj['meta'] = meta f = open(path, 'w') json.dump(obj, f) f.close
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_for_doc(nb): """ Cleans the notebook to be suitable for inclusion in the docs. """
new_cells = [] for cell in nb.worksheets[0].cells: # Remove the pylab inline line. if "input" in cell and cell["input"].strip() == "%pylab inline": continue # Remove output resulting from the stream/trace method chaining. if "outputs" in cell: outputs = [_i for _i in cell["outputs"] if "text" not in _i or not _i["text"].startswith("<obspy.core")] cell["outputs"] = outputs new_cells.append(cell) nb.worksheets[0].cells = new_cells return nb
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_call_back(self, func): """sets callback function for updating the plot. in the callback function implement the logic of reading of serial input also the further processing of the signal if necessary has to be done in this callbak function."""
self.timer.add_callback(func) self.timer.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_self(self, func): """define your callback function with the decorator @plotter.plot_self. in the callback function set the data of lines in the plot using self.lines[i][j].set_data(your data)"""
def func_wrapper(): func() try: self.manager.canvas.draw() except ValueError as ve: print(ve) pass except RuntimeError as RtE: print(RtE) pass except Exception as e: print(e) pass return func_wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(cls, **kwargs): """ The meat. Filtering using Django model style syntax. All kwargs are translated into attributes on the underlying objects. If the attribute is not found, it looks for a similar key in the tags. There are a couple comparisons to check against as well: exact: check strict equality iexact: case insensitive exact like: check against regular expression ilike: case insensitive like contains: check if string is found with attribute icontains: case insensitive contains startswith: check if attribute value starts with the string istartswith: case insensitive startswith endswith: check if attribute value ends with the string iendswith: case insensitive startswith isnull: check if the attribute does not exist """
qs = cls.all() for key in kwargs: qs = filter(lambda i: make_compare(key, kwargs[key], i), qs) return qs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reconnect_redis(self): '''Reconnect to redis. :return: Redis client instance :rettype: redis.Redis ''' if self.shared_client and Storage.storage: return Storage.storage storage = Redis( port=self.context.config.REDIS_RESULT_STORAGE_SERVER_PORT, host=self.context.config.REDIS_RESULT_STORAGE_SERVER_HOST, db=self.context.config.REDIS_RESULT_STORAGE_SERVER_DB, password=self.context.config.REDIS_RESULT_STORAGE_SERVER_PASSWORD ) if self.shared_client: Storage.storage = storage return storage
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_key_from_request(self): '''Return a key for the current request url. :return: The storage key for the current url :rettype: string ''' path = "result:%s" % self.context.request.url if self.is_auto_webp(): path += '/webp' return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_max_age(self): '''Return the TTL of the current request. :returns: The TTL value for the current request. :rtype: int ''' default_ttl = self.context.config.RESULT_STORAGE_EXPIRATION_SECONDS if self.context.request.max_age == 0: return self.context.request.max_age return default_ttl
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def put(self, bytes): '''Save to redis :param bytes: Bytes to write to the storage. :return: Redis key for the current url :rettype: string ''' key = self.get_key_from_request() result_ttl = self.get_max_age() logger.debug( "[REDIS_RESULT_STORAGE] putting `{key}` with ttl `{ttl}`".format( key=key, ttl=result_ttl ) ) storage = self.get_storage() storage.set(key, bytes) if result_ttl > 0: storage.expireat( key, datetime.now() + timedelta( seconds=result_ttl ) ) return key
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get(self): '''Get the item from redis.''' key = self.get_key_from_request() result = self.get_storage().get(key) return result if result else None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def last_updated(self): '''Return the last_updated time of the current request item :return: A DateTime object :rettype: datetetime.datetime ''' key = self.get_key_from_request() max_age = self.get_max_age() if max_age == 0: return datetime.fromtimestamp(Storage.start_time) ttl = self.get_storage().ttl(key) if ttl >= 0: return datetime.now() - timedelta( seconds=( max_age - ttl ) ) if ttl == -1: # Per Redis docs: -1 is no expiry, -2 is does not exists. return datetime.fromtimestamp(Storage.start_time) # Should never reach here. It means the storage put failed or the item # somehow does not exists anymore. return datetime.now()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_of_lists_to_dict(l): """ Convert list of key,value lists to dict [['id', 1], ['id', 2], ['id', 3], ['foo': 4]] {'id': [1, 2, 3], 'foo': [4]} """
d = {} for key, val in l: d.setdefault(key, []).append(val) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dumps(number): """Dumps an integer into a base36 string. :param number: the 10-based integer. :returns: the base36 string. """
if not isinstance(number, integer_types): raise TypeError('number must be an integer') if number < 0: return '-' + dumps(-number) value = '' while number != 0: number, index = divmod(number, len(alphabet)) value = alphabet[index] + value return value or '0'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acl_middleware(callback): """Returns a aiohttp_auth.acl middleware factory for use by the aiohttp application object. Args: callback: This is a callable which takes a user_id (as returned from the auth.get_auth function), and expects a sequence of permitted ACL groups to be returned. This can be a empty tuple to represent no explicit permissions, or None to explicitly forbid this particular user_id. Note that the user_id passed may be None if no authenticated user exists. Returns: A aiohttp middleware factory. """
async def _acl_middleware_factory(app, handler): async def _middleware_handler(request): # Save the policy in the request request[GROUPS_KEY] = callback # Call the next handler in the chain return await handler(request) return _middleware_handler return _acl_middleware_factory
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def get_user_groups(request): """Returns the groups that the user in this request has access to. This function gets the user id from the auth.get_auth function, and passes it to the ACL callback function to get the groups. Args: request: aiohttp Request object Returns: If the ACL callback function returns None, this function returns None. Otherwise this function returns the sequence of group permissions provided by the callback, plus the Everyone group. If user_id is not None, the AuthnticatedUser group and the user_id are added to the groups returned by the function Raises: RuntimeError: If the ACL middleware is not installed """
acl_callback = request.get(GROUPS_KEY) if acl_callback is None: raise RuntimeError('acl_middleware not installed') user_id = await get_auth(request) groups = await acl_callback(user_id) if groups is None: return None user_groups = (Group.AuthenticatedUser, user_id) if user_id is not None else () return set(itertools.chain(groups, (Group.Everyone,), user_groups))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def get_permitted(request, permission, context): """Returns true if the one of the groups in the request has the requested permission. The function takes a request, a permission to check for and a context. A context is a sequence of ACL tuples which consist of a Allow/Deny action, a group, and a sequence of permissions for that ACL group. For example:: context = [(Permission.Allow, 'view_group', ('view',)), (Permission.Allow, 'edit_group', ('view', 'edit')),] ACL tuple sequences are checked in order, with the first tuple that matches the group the user is a member of, and includes the permission passed to the function, to be the matching ACL group. If no ACL group is found, the function returns False. Groups and permissions need only be immutable objects, so can be strings, numbers, enumerations, or other immutable objects. Args: request: aiohttp Request object permission: The specific permission requested. context: A sequence of ACL tuples Returns: The function gets the groups by calling get_user_groups() and returns true if the groups are Allowed the requested permission, false otherwise. Raises: RuntimeError: If the ACL middleware is not installed """
groups = await get_user_groups(request) if groups is None: return False for action, group, permissions in context: if group in groups: if permission in permissions: return action == Permission.Allow return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def molecular_weight(elements): """ Return molecular weight of a molecule. Parameters elements : numpy.ndarray An array of all elements (type: str) in a molecule. Returns ------- numpy.float64 A molecular weight of a molecule. """
return (np.array([atomic_mass[i.upper()] for i in elements]).sum())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dlf_notation(atom_key): """Return element for atom key using DL_F notation."""
split = list(atom_key) element = '' number = False count = 0 while number is False: element = "".join((element, split[count])) count += 1 if is_number(split[count]) is True: number = True # In case of for example Material Studio output, integers can also be # in the beginning of the string. As the dlf_notation decipher function # is very general in use, we have to make sure these integers are deleted. # In standard DL_F notation the string will never start with integer so it # will not affect the functionality towards it. # EDIT2: also the '?' atoms, you can delete them manually or somewhere else element = "".join(i for i in element if not is_number(i)) element = "".join(i for i in element if i != '?') return element
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def opls_notation(atom_key): """Return element for OPLS forcefield atom key."""
# warning for Ne, He, Na types overlap conflicts = ['ne', 'he', 'na'] if atom_key in conflicts: raise _AtomKeyConflict(( "One of the OPLS conflicting " "atom_keys has occured '{0}'. " "For how to solve this issue see the manual or " "MolecularSystem._atom_key_swap() doc string.").format(atom_key)) for element in opls_atom_keys: if atom_key in opls_atom_keys[element]: return element # In case if atom_key was not found in the OPLS keys dictionary raise _AtomKeyError(( "OPLS atom key {0} was not found in OPLS keys dictionary.").format( atom_key))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decipher_atom_key(atom_key, forcefield): """ Return element for deciphered atom key. This functions checks if the forcfield specified by user is supported and passes the atom key to the appropriate function for deciphering. Parameters atom_key : str The atom key which is to be deciphered. forcefield : str The forcefield to which the atom key belongs to. Returns ------- str A string that is the periodic table element equvalent of forcefield atom key. """
load_funcs = { 'DLF': dlf_notation, 'DL_F': dlf_notation, 'OPLS': opls_notation, 'OPLSAA': opls_notation, 'OPLS2005': opls_notation, 'OPLS3': opls_notation, } if forcefield.upper() in load_funcs.keys(): return load_funcs[forcefield.upper()](atom_key) else: raise _ForceFieldError( ("Unfortunetely, '{0}' forcefield is not supported by pyWINDOW." " For list of supported forcefields see User's Manual or " "MolecularSystem._decipher_atom_keys() function doc string." ).format(forcefield))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_com(elements, coordinates, com_adjust=np.zeros(3)): """ Return coordinates translated by some vector. Parameters elements : numpy.ndarray An array of all elements (type: str) in a molecule. coordinates : numpy.ndarray An array containing molecule's coordinates. com_adjust : numpy.ndarray (default = [0, 0, 0]) Returns ------- numpy.ndarray Translated array of molecule's coordinates. """
com = center_of_mass(elements, coordinates) com = np.array([com - com_adjust] * coordinates.shape[0]) return coordinates - com
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_dim(elements, coordinates): """ Return the maximum diameter of a molecule. Parameters elements : numpy.ndarray An array of all elements (type: str) in a molecule. coordinates : numpy.ndarray An array containing molecule's coordinates. Returns ------- """
atom_vdw_vertical = np.matrix( [[atomic_vdw_radius[i.upper()]] for i in elements]) atom_vdw_horizontal = np.matrix( [atomic_vdw_radius[i.upper()] for i in elements]) dist_matrix = euclidean_distances(coordinates, coordinates) vdw_matrix = atom_vdw_vertical + atom_vdw_horizontal re_dist_matrix = dist_matrix + vdw_matrix final_matrix = np.triu(re_dist_matrix) i1, i2 = np.unravel_index(final_matrix.argmax(), final_matrix.shape) maxdim = final_matrix[i1, i2] return i1, i2, maxdim
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pore_diameter(elements, coordinates, com=None): """Return pore diameter of a molecule."""
if com is None: com = center_of_mass(elements, coordinates) atom_vdw = np.array([[atomic_vdw_radius[x.upper()]] for x in elements]) dist_matrix = euclidean_distances(coordinates, com.reshape(1, -1)) re_dist_matrix = dist_matrix - atom_vdw index = np.argmin(re_dist_matrix) pored = re_dist_matrix[index][0] * 2 return (pored, index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def opt_pore_diameter(elements, coordinates, bounds=None, com=None, **kwargs): """Return optimised pore diameter and it's COM."""
args = elements, coordinates if com is not None: pass else: com = center_of_mass(elements, coordinates) if bounds is None: pore_r = pore_diameter(elements, coordinates, com=com)[0] / 2 bounds = ( (com[0]-pore_r, com[0]+pore_r), (com[1]-pore_r, com[1]+pore_r), (com[2]-pore_r, com[2]+pore_r) ) minimisation = minimize( correct_pore_diameter, x0=com, args=args, bounds=bounds) pored = pore_diameter(elements, coordinates, com=minimisation.x) return (pored[0], pored[1], minimisation.x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_gyration_tensor(elements, coordinates): """ Return the gyration tensor of a molecule. The gyration tensor should be invariant to the molecule's position. The known formulas for the gyration tensor have the correction for the centre of mass of the molecule, therefore, the coordinates are first corrected for the centre of mass and essentially shifted to the origin. Parameters elements : numpy.ndarray The array containing the molecule's elemental data. coordinates : numpy.ndarray The array containing the Cartesian coordinates of the molecule. Returns ------- numpy.ndarray The gyration tensor of a molecule invariant to the molecule's position. """
# First calculate COM for correction. com = centre_of_mass(elements, coordinates) # Correct the coordinates for the COM. coordinates = coordinates - com # Calculate diagonal and then other values of the matrix. diag = np.sum(coordinates**2, axis=0) xy = np.sum(coordinates[:, 0] * coordinates[:, 1]) xz = np.sum(coordinates[:, 0] * coordinates[:, 2]) yz = np.sum(coordinates[:, 1] * coordinates[:, 2]) S = np.array([[diag[0], xy, xz], [xy, diag[1], yz], [xz, yz, diag[2]]]) / coordinates.shape[0] return (S)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_inertia_tensor(elements, coordinates): """ Return the tensor of inertia a molecule. Parameters elements : numpy.ndarray The array containing the molecule's elemental data. coordinates : numpy.ndarray The array containing the Cartesian coordinates of the molecule. Returns ------- numpy.ndarray The tensor of inertia of a molecule. """
pow2 = coordinates**2 molecular_weight = np.array( [[atomic_mass[e.upper()]] for e in elements]) diag_1 = np.sum(molecular_weight * (pow2[:, 1] + pow2[:, 2])) diag_2 = np.sum(molecular_weight * (pow2[:, 0] + pow2[:, 2])) diag_3 = np.sum(molecular_weight * (pow2[:, 0] + pow2[:, 1])) mxy = np.sum(-molecular_weight * coordinates[:, 0] * coordinates[:, 1]) mxz = np.sum(-molecular_weight * coordinates[:, 0] * coordinates[:, 2]) myz = np.sum(-molecular_weight * coordinates[:, 1] * coordinates[:, 2]) inertia_tensor = np.array([[diag_1, mxy, mxz], [mxy, diag_2, myz], [mxz, myz, diag_3]]) / coordinates.shape[0] return (inertia_tensor)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_vector(vector): """ Normalize a vector. A new vector is returned, the original vector is not modified. Parameters vector : np.array The vector to be normalized. Returns ------- np.array The normalized vector. """
v = np.divide(vector, np.linalg.norm(vector)) return np.round(v, decimals=4)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotation_matrix_arbitrary_axis(angle, axis): """ Return a rotation matrix of `angle` radians about `axis`. Parameters angle : int or float The size of the rotation in radians. axis : numpy.array A 3 element aray which represents a vector. The vector is the axis about which the rotation is carried out. Returns ------- numpy.array A 3x3 array representing a rotation matrix. """
axis = normalize_vector(axis) a = np.cos(angle / 2) b, c, d = axis * np.sin(angle / 2) e11 = np.square(a) + np.square(b) - np.square(c) - np.square(d) e12 = 2 * (b * c - a * d) e13 = 2 * (b * d + a * c) e21 = 2 * (b * c + a * d) e22 = np.square(a) + np.square(c) - np.square(b) - np.square(d) e23 = 2 * (c * d - a * b) e31 = 2 * (b * d - a * c) e32 = 2 * (c * d + a * b) e33 = np.square(a) + np.square(d) - np.square(b) - np.square(c) return np.array([[e11, e12, e13], [e21, e22, e23], [e31, e32, e33]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unit_cell_to_lattice_array(cryst): """Return parallelpiped unit cell lattice matrix."""
a_, b_, c_, alpha, beta, gamma = cryst # Convert angles from degrees to radians. r_alpha = np.deg2rad(alpha) r_beta = np.deg2rad(beta) r_gamma = np.deg2rad(gamma) # Calculate unit cell volume that is neccessary. volume = a_ * b_ * c_ * ( 1 - np.cos(r_alpha)**2 - np.cos(r_beta)**2 - np.cos(r_gamma)**2 + 2 * np.cos(r_alpha) * np.cos(r_beta) * np.cos(r_gamma))**0.5 # Create the orthogonalisation Matrix (M^-1) - lattice matrix a_x = a_ a_y = b_ * np.cos(r_gamma) a_z = c_ * np.cos(r_beta) b_x = 0 b_y = b_ * np.sin(r_gamma) b_z = c_ * ( np.cos(r_alpha) - np.cos(r_beta) * np.cos(r_gamma)) / np.sin(r_gamma) c_x = 0 c_y = 0 c_z = volume / (a_ * b_ * np.sin(r_gamma)) lattice_array = np.array( [[a_x, a_y, a_z], [b_x, b_y, b_z], [c_x, c_y, c_z]]) return lattice_array
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lattice_array_to_unit_cell(lattice_array): """Return crystallographic param. from unit cell lattice matrix."""
cell_lengths = np.sqrt(np.sum(lattice_array**2, axis=0)) gamma_r = np.arccos(lattice_array[0][1] / cell_lengths[1]) beta_r = np.arccos(lattice_array[0][2] / cell_lengths[2]) alpha_r = np.arccos( lattice_array[1][2] * np.sin(gamma_r) / cell_lengths[2] + np.cos(beta_r) * np.cos(gamma_r) ) cell_angles = [ np.rad2deg(alpha_r), np.rad2deg(beta_r), np.rad2deg(gamma_r) ] return np.append(cell_lengths, cell_angles)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fractional_from_cartesian(coordinate, lattice_array): """Return a fractional coordinate from a cartesian one."""
deorthogonalisation_M = np.matrix(np.linalg.inv(lattice_array)) fractional = deorthogonalisation_M * coordinate.reshape(-1, 1) return np.array(fractional.reshape(1, -1))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cartisian_from_fractional(coordinate, lattice_array): """Return cartesian coordinate from a fractional one."""
orthogonalisation_M = np.matrix(lattice_array) orthogonal = orthogonalisation_M * coordinate.reshape(-1, 1) return np.array(orthogonal.reshape(1, -1))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cart2frac_all(coordinates, lattice_array): """Convert all cartesian coordinates to fractional."""
frac_coordinates = deepcopy(coordinates) for coord in range(frac_coordinates.shape[0]): frac_coordinates[coord] = fractional_from_cartesian( frac_coordinates[coord], lattice_array) return frac_coordinates
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def frac2cart_all(frac_coordinates, lattice_array): """Convert all fractional coordinates to cartesian."""
coordinates = deepcopy(frac_coordinates) for coord in range(coordinates.shape[0]): coordinates[coord] = cartisian_from_fractional(coordinates[coord], lattice_array) return coordinates
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def angle_between_vectors(x, y): """Calculate the angle between two vectors x and y."""
first_step = abs(x[0] * y[0] + x[1] * y[1] + x[2] * y[2]) / ( np.sqrt(x[0]**2 + x[1]**2 + x[2]**2) * np.sqrt(y[0]**2 + y[1]**2 + y[2]**2)) second_step = np.arccos(first_step) return (second_step)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vector_analysis(vector, coordinates, elements_vdw, increment=1.0): """Analyse a sampling vector's path for window analysis purpose."""
# Calculate number of chunks if vector length is divided by increment. chunks = int(np.linalg.norm(vector) // increment) # Create a single chunk. chunk = vector / chunks # Calculate set of points on vector's path every increment. vector_pathway = np.array([chunk * i for i in range(chunks + 1)]) analysed_vector = np.array([ np.amin( euclidean_distances(coordinates, i.reshape(1, -1)) - elements_vdw) for i in vector_pathway ]) if all(i > 0 for i in analysed_vector): pos = np.argmin(analysed_vector) # As first argument we need to give the distance from the origin. dist = np.linalg.norm(chunk * pos) return np.array( [dist, analysed_vector[pos] * 2, *chunk * pos, *vector])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optimise_xy(xy, *args): """Return negative pore diameter for x and y coordinates optimisation."""
z, elements, coordinates = args window_com = np.array([xy[0], xy[1], z]) return -pore_diameter(elements, coordinates, com=window_com)[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optimise_z(z, *args): """Return pore diameter for coordinates optimisation in z direction."""
x, y, elements, coordinates = args window_com = np.array([x, y, z]) return pore_diameter(elements, coordinates, com=window_com)[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rand(self, n=1): """ Generate random samples from the distribution Parameters n : int, optional(default=1) The number of samples to generate Returns ------- out : array_like The generated samples """
if n == 1: return self._rand1() else: out = np.empty((n, self._p, self._p)) for i in range(n): out[i] = self._rand1() return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _c0(self): "the logarithm of normalizing constant in pdf" h_df = self.df / 2 p, S = self._p, self.S return h_df * (logdet(S) + p * logtwo) + lpgamma(p, h_df)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _genA(self): """ Generate the matrix A in the Bartlett decomposition A is a lower triangular matrix, with A(i, j) ~ sqrt of Chisq(df - i + 1) when i == j ~ Normal() when i > j """
p, df = self._p, self.df A = np.zeros((p, p)) for i in range(p): A[i, i] = sqrt(st.chi2.rvs(df - i)) for j in range(p-1): for i in range(j+1, p): A[i, j] = np.random.randn() return A
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _rand1(self): "generate a single random sample" Z = _unwhiten_cf(self._S_cf, self._genA()) return Z.dot(Z.T)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_file(self, filepath): """ This function opens any type of a readable file and decompose the file object into a list, for each line, of lists containing splitted line strings using space as a spacer. Parameters filepath : :class:`str` The full path or a relative path to any type of file. Returns ------- :class:`dict` Returns a dictionary containing the molecular information extracted from the input files. This information will vary with file type and information stored in it. The data is sorted into lists that contain one feature for example key atom_id: [atom_id_1, atom_id_2] Over the process of analysis this dictionary will be updated with new data. """
self.file_path = filepath _, self.file_type = os.path.splitext(filepath) _, self.file_name = os.path.split(filepath) with open(filepath) as ffile: self.file_content = ffile.readlines() return (self._load_funcs[self.file_type]())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump2json(self, obj, filepath, override=False, **kwargs): """ Dump a dictionary into a JSON dictionary. Uses the json.dump() function. Parameters obj : :class:`dict` A dictionary to be dumpped as JSON file. filepath : :class:`str` The filepath for the dumped file. override : :class:`bool` If True, any file in the filepath will be override. (default=False) """
# We make sure that the object passed by the user is a dictionary. if isinstance(obj, dict): pass else: raise _NotADictionary( "This function only accepts dictionaries as input") # We check if the filepath has a json extenstion, if not we add it. if str(filepath[-4:]) == 'json': pass else: filepath = ".".join((str(filepath), "json")) # First we check if the file already exists. If yes and the override # keyword is False (default), we will raise an exception. Otherwise # the file will be overwritten. if override is False: if os.path.isfile(filepath): raise _FileAlreadyExists( "The file {0} already exists. Use a different filepath, " "or set the 'override' kwarg to True.".format(filepath)) # We dump the object to the json file. Additional kwargs can be passed. with open(filepath, 'w+') as json_file: json.dump(obj, json_file, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, data, update=False, **kwargs): """ Creates a new object pretreated input data. .. code-block:: python DBSession.sacrud(Users).create({'name': 'Vasya', 'sex': 1}) Support JSON: .. code-block:: python DBSession.sacrud(Users).create('{"name": "Vasya", "sex": 1}') For adding multiple data for m2m or m2o use endinng `[]`, ex.: .. code-block:: python DBSession.sacrud(Users).create( {'name': 'Vasya', 'sex': 1, 'groups[]': ['["id", 1]', '["id", 2]']} ) """
data = unjson(data) if update is True: obj = get_obj_by_request_data(self.session, self.table, data) else: obj = None return self._add(obj, data, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, *pk): """ Return a list of entries in the table or single entry if there is an pk. .. code-block:: python # All users DBSession.sacrud(Users).read() # Composite primary_key DBSession.sacrud(User2Groups).read({'user_id': 4, 'group_id': 2}) # Multiple rows primary_keys = [ {'user_id': 4, 'group_id': 2}, {'user_id': 4, 'group_id': 3}, {'user_id': 1, 'group_id': 1}, {'user_id': 19, 'group_id': 2} ] DBSession.sacrud(User2Groups).read(*primary_keys) # JSON using primary_keys = '''[ {"user_id": 4, "group_id": 2}, {"user_id": 4, "group_id": 3}, {"user_id": 1, "group_id": 1}, {"user_id": 19, "group_id": 2} ]''' DBSession.sacrud(User2Groups).read(primary_keys) # Delete DBSession.sacrud(User2Groups).read(*primary_keys)\ .delete(synchronize_session=False) # Same, but work with only not composite primary key DBSession.sacrud(Users).read((5, 10)) # as list DBSession.sacrud(Users).read('[5, 10]') # as JSON DBSession.sacrud(Users).read('{"id": 5}') # as JSON explicit pk DBSession.sacrud(Users).read(5, "1", 2) # as *args DBSession.sacrud(Users).read(42) # single """
pk = [unjson(obj) for obj in pk] if len(pk) == 1: # like ([1,2,3,4,5], ) return get_obj(self.session, self.table, pk[0]) elif len(pk) > 1: # like (1, 2, 3, 4, 5) return get_obj(self.session, self.table, pk) return self.session.query(self.table)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add(self, obj, data, **kwargs): """ Update the object directly. .. code-block:: python DBSession.sacrud(Users)._add(UserObj, {'name': 'Gennady'}) """
if isinstance(obj, sqlalchemy.orm.query.Query): obj = obj.one() obj = self.preprocessing(obj=obj or self.table)\ .add(self.session, data, self.table) self.session.add(obj) if kwargs.get('commit', self.commit) is True: try: self.session.commit() except AssertionError: transaction.commit() return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _delete(self, obj, **kwargs): """ Delete the object directly. .. code-block:: python DBSession.sacrud(Users)._delete(UserObj) If you no needed commit session .. code-block:: python DBSession.sacrud(Users, commit=False)._delete(UserObj) """
if isinstance(obj, sqlalchemy.orm.query.Query): obj = obj.one() obj = self.preprocessing(obj=obj).delete() self.session.delete(obj) if kwargs.get('commit', self.commit) is True: try: self.session.commit() except AssertionError: transaction.commit() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticated(self, user_token, **validation_context): """Checks if user is authenticated using token passed in argument :param user_token: string representing token :param validation_context: Token.validate optional keyword arguments """
token = self.token_storage.get(user_token) if token and token.validate(user_token, **validation_context): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def group_authenticated(self, user_token, group): """Checks if user represented by token is in group. :param user_token: string representing token :param group: group's name """
if self.authenticated(user_token): token = self.token_storage.get(user_token) groups = self.get_groups(token.username) if group in groups: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_groups(self, username): """Returns list of groups in which user is. :param username: name of Linux user """
groups = [] for group in grp.getgrall(): if username in group.gr_mem: groups.append(group.gr_name) return groups
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth_required(self, view): """Decorator which checks if user is authenticated Decorator for Flask's view which blocks not authenticated requests :param view: Flask's view function """
@functools.wraps(view) def decorated(*args, **kwargs): log.info("Trying to get access to protected resource: '%s'", view.__name__) if request.method == 'POST': token = request.form['token'] if self.development or self.authenticated(token): return view(*args, **kwargs) else: log.warning("User has not been authorized to get access to resource: %s", view.__name__) else: log.warning("Bad request type! Expected 'POST', actual '%s'", request.method) return abort(403) return decorated
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def group_required(self, group): """Decorator which checks if user is in group Decorator for Flask's view which blocks requests from not authenticated users or if user is not member of specified group :param group: group's name """
def decorator(view): @functools.wraps(view) def decorated(*args, **kwargs): log.info("Trying to get access to resource: %s protected by group: %s", view.__name__, group) if request.method == 'POST': token = request.form['token'] if self.development or self.group_authenticated(token, group): return view(*args, **kwargs) else: log.warning("User has not been authorized to get access to resource: %s", view.__name__) else: log.error("Bad request type! Expected 'POST', actual '%s'", request.method) return abort(403) return decorated return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pyc2py(filename): """ Find corresponding .py name given a .pyc or .pyo """
if re.match(".*py[co]$", filename): if PYTHON3: return re.sub(r'(.*)__pycache__/(.+)\.cpython-%s.py[co]$' % PYVER, '\\1\\2.py', filename) else: return filename[:-1] return filename
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_file_cache(filename=None): """Clear the file cache. If no filename is given clear it entirely. if a filename is given, clear just that filename."""
global file_cache, file2file_remap, file2file_remap_lines if filename is not None: if filename in file_cache: del file_cache[filename] pass else: file_cache = {} file2file_remap = {} file2file_remap_lines = {} pass return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_file_format_cache(): """Remove syntax-formatted lines in the cache. Use this when you change the Pygments syntax or Token formatting and want to redo how files may have previously been syntax marked."""
for fname, cache_info in file_cache.items(): for format, lines in cache_info.lines.items(): if 'plain' == format: continue file_cache[fname].lines[format] = None pass pass pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_script(script, text, opts={}): """Cache script if it is not already cached."""
global script_cache if script not in script_cache: update_script_cache(script, text, opts) pass return script
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_file(filename, reload_on_change=False, opts=default_opts): """Cache filename if it is not already cached. Return the expanded filename for it in the cache or nil if we can not find the file."""
filename = pyc2py(filename) if filename in file_cache: if reload_on_change: checkcache(filename) pass else: opts['use_linecache_lines'] = True update_cache(filename, opts) pass if filename in file_cache: return file_cache[filename].path else: return None return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_cached(file_or_script): """Return True if file_or_script is cached"""
if isinstance(file_or_script, str): return unmap_file(file_or_script) in file_cache else: return is_cached_script(file_or_script) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def path(filename): """Return full filename path for filename"""
filename = unmap_file(filename) if filename not in file_cache: return None return file_cache[filename].path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remap_file_lines(from_path, to_path, line_map_list): """Adds line_map list to the list of association of from_file to to to_file"""
from_path = pyc2py(from_path) cache_file(to_path) remap_entry = file2file_remap_lines.get(to_path) if remap_entry: new_list = list(remap_entry.from_to_pairs) + list(line_map_list) else: new_list = line_map_list # FIXME: look for duplicates ? file2file_remap_lines[to_path] = RemapLineEntry( from_path, tuple(sorted(new_list, key=lambda t: t[0])) ) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sha1(filename): """Return SHA1 of filename."""
filename = unmap_file(filename) if filename not in file_cache: cache_file(filename) if filename not in file_cache: return None pass if file_cache[filename].sha1: return file_cache[filename].sha1.hexdigest() sha1 = hashlib.sha1() for line in file_cache[filename].lines['plain']: sha1.update(line.encode('utf-8')) pass file_cache[filename].sha1 = sha1 return sha1.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size(filename, use_cache_only=False): """Return the number of lines in filename. If `use_cache_only' is False, we'll try to fetch the file if it is not cached."""
filename = unmap_file(filename) if filename not in file_cache: if not use_cache_only: cache_file(filename) if filename not in file_cache: return None pass return len(file_cache[filename].lines['plain'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maxline(filename, use_cache_only=False): """Return the maximum line number filename after taking into account line remapping. If no remapping then this is the same as size"""
if filename not in file2file_remap_lines: return size(filename, use_cache_only) max_lineno = -1 remap_line_entry = file2file_remap_lines.get(filename) if not remap_line_entry: return size(filename, use_cache_only) for t in remap_line_entry.from_to_pairs: max_lineno = max(max_lineno, t[1]) if max_lineno == -1: return size(filename, use_cache_only) else: return max_lineno
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def remember_ticket(self, request, ticket): """Called to store the ticket data for a request. Ticket data is stored in the aiohttp_session object Args: request: aiohttp Request object. ticket: String like object representing the ticket to be stored. """
session = await get_session(request) session[self.cookie_name] = ticket
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def forget_ticket(self, request): """Called to forget the ticket data a request Args: request: aiohttp Request object. """
session = await get_session(request) session.pop(self.cookie_name, '')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def get_ticket(self, request): """Called to return the ticket for a request. Args: request: aiohttp Request object. Returns: A ticket (string like) object, or None if no ticket is available for the passed request. """
session = await get_session(request) return session.get(self.cookie_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth_middleware(policy): """Returns a aiohttp_auth middleware factory for use by the aiohttp application object. Args: policy: A authentication policy with a base class of AbstractAuthentication. """
assert isinstance(policy, AbstractAuthentication) async def _auth_middleware_factory(app, handler): async def _middleware_handler(request): # Save the policy in the request request[POLICY_KEY] = policy # Call the next handler in the chain response = await handler(request) # Give the policy a chance to handle the response await policy.process_response(request, response) return response return _middleware_handler return _auth_middleware_factory
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def get_auth(request): """Returns the user_id associated with a particular request. Args: request: aiohttp Request object. Returns: The user_id associated with the request, or None if no user is associated with the request. Raises: RuntimeError: Middleware is not installed """
auth_val = request.get(AUTH_KEY) if auth_val: return auth_val auth_policy = request.get(POLICY_KEY) if auth_policy is None: raise RuntimeError('auth_middleware not installed') request[AUTH_KEY] = await auth_policy.get(request) return request[AUTH_KEY]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def remember(request, user_id): """Called to store and remember the userid for a request Args: request: aiohttp Request object. user_id: String representing the user_id to remember Raises: RuntimeError: Middleware is not installed """
auth_policy = request.get(POLICY_KEY) if auth_policy is None: raise RuntimeError('auth_middleware not installed') return await auth_policy.remember(request, user_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def forget(request): """Called to forget the userid for a request Args: request: aiohttp Request object Raises: RuntimeError: Middleware is not installed """
auth_policy = request.get(POLICY_KEY) if auth_policy is None: raise RuntimeError('auth_middleware not installed') return await auth_policy.forget(request)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def debounce(wait): """ Decorator that will postpone a functions execution until after wait seconds have elapsed since the last time it was invoked. """
def decorator(fn): def debounced(*args, **kwargs): def call_it(): fn(*args, **kwargs) try: debounced.t.cancel() except(AttributeError): pass debounced.t = threading.Timer(wait, call_it) debounced.t.start() return debounced return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def process_response(self, request, response): """Called to perform any processing of the response required. This function stores any cookie data in the COOKIE_AUTH_KEY as a cookie in the response object. If the value is a empty string, the associated cookie is deleted instead. This function requires the response to be a aiohttp Response object, and assumes that the response has not started if the remember or forget functions are called during the request. Args: request: aiohttp Request object. response: response object returned from the handled view Raises: RuntimeError: Raised if response has already started. """
await super().process_response(request, response) if COOKIE_AUTH_KEY in request: if response.started: raise RuntimeError("Cannot save cookie into started response") cookie = request[COOKIE_AUTH_KEY] if cookie == '': response.del_cookie(self.cookie_name) else: response.set_cookie(self.cookie_name, cookie)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_args(): ''' Parse CLI args ''' parser = argparse.ArgumentParser(description='Process args') parser.Add_argument( '-H', '--host', required=True, action='store', help='Remote host to connect to' ) parser.add_argument( '-P', '--port', type=int, default=443, action='store', help='Port to connect on' ) parser.add_argument( '-u', '--user', required=True, action='store', help='User name to use when connecting to host' ) parser.add_argument( '-p', '--password', required=False, action='store', help='Password to use when connecting to host' ) parser.add_argument( '-s', '--ssl', required=False, action='store_true', help='Use SSL' ) parser.add_argument( '-k', '--skip-ssl-verification', required=False, default=False, action='store_true', help='Skip SSL certificate validation' ) parser.add_argument( '-n', '--dryrun', required=False, action='store_true', default=False, help='Dry run. Don\'t annotate any VM' ) parser.add_argument( '-v', '--verbose', action='store_true', default=False, help='Verbose output' ) return parser.parse_args()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def remember(self, request, user_id): """Called to store the userid for a request. This function creates a ticket from the request and user_id, and calls the abstract function remember_ticket() to store the ticket. Args: request: aiohttp Request object. user_id: String representing the user_id to remember """
ticket = self._new_ticket(request, user_id) await self.remember_ticket(request, ticket)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def get(self, request): """Gets the user_id for the request. Gets the ticket for the request using the get_ticket() function, and authenticates the ticket. Args: request: aiohttp Request object. Returns: The userid for the request, or None if the ticket is not authenticated. """
ticket = await self.get_ticket(request) if ticket is None: return None try: # Returns a tuple of (user_id, token, userdata, validuntil) now = time.time() fields = self._ticket.validate(ticket, self._get_ip(request), now) # Check if we need to reissue a ticket if (self._reissue_time is not None and now >= (fields.valid_until - self._reissue_time)): # Reissue our ticket, and save it in our request. request[_REISSUE_KEY] = self._new_ticket(request, fields.user_id) return fields.user_id except TicketError as e: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def process_response(self, request, response): """If a reissue was requested, only reiisue if the response was a valid 2xx response """
if _REISSUE_KEY in request: if (response.started or not isinstance(response, web.Response) or response.status < 200 or response.status > 299): return await self.remember_ticket(request, request[_REISSUE_KEY])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acl_required(permission, context): """Returns a decorator that checks if a user has the requested permission from the passed acl context. This function constructs a decorator that can be used to check a aiohttp's view for authorization before calling it. It uses the get_permission() function to check the request against the passed permission and context. If the user does not have the correct permission to run this function, it raises HTTPForbidden. Args: permission: The specific permission requested. context: Either a sequence of ACL tuples, or a callable that returns a sequence of ACL tuples. For more information on ACL tuples, see get_permission() Returns: A decorator which will check the request passed has the permission for the given context. The decorator will raise HTTPForbidden if the user does not have the correct permissions to access the view. """
def decorator(func): @wraps(func) async def wrapper(*args): request = args[-1] if callable(context): context = context() if await get_permitted(request, permission, context): return await func(*args) raise web.HTTPForbidden() return wrapper return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_version_2(dataset): """Checks if json-stat version attribute exists and is equal or greater \ than 2.0 for a given dataset. Args: dataset (OrderedDict): data in JSON-stat format, previously \ deserialized to a python object by \ json.load() or json.loads(), Returns: bool: True if version exists and is equal or greater than 2.0, \ False otherwise. For datasets without the version attribute, \ always return False. """
if float(dataset.get('version')) >= 2.0 \ if dataset.get('version') else False: return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unnest_collection(collection, df_list): """Unnest collection structure extracting all its datasets and converting \ them to Pandas Dataframes. Args: collection (OrderedDict): data in JSON-stat format, previously \ deserialized to a python object by \ json.load() or json.loads(), df_list (list): list variable which will contain the converted \ datasets. Returns: Nothing. """
for item in collection['link']['item']: if item['class'] == 'dataset': df_list.append(Dataset.read(item['href']).write('dataframe')) elif item['class'] == 'collection': nested_collection = request(item['href']) unnest_collection(nested_collection, df_list)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dimensions(js_dict, naming): """Get dimensions from input data. Args: js_dict (dict): dictionary containing dataset data and metadata. naming (string, optional): dimension naming. Possible values: 'label' \ or 'id'. Returns: dimensions (list): list of pandas data frames with dimension \ category data. dim_names (list): list of strings with dimension names. """
dimensions = [] dim_names = [] if check_version_2(js_dict): dimension_dict = js_dict else: dimension_dict = js_dict['dimension'] for dim in dimension_dict['id']: dim_name = js_dict['dimension'][dim]['label'] if not dim_name: dim_name = dim if naming == 'label': dim_label = get_dim_label(js_dict, dim) dimensions.append(dim_label) dim_names.append(dim_name) else: dim_index = get_dim_index(js_dict, dim) dimensions.append(dim_index) dim_names.append(dim) return dimensions, dim_names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dim_label(js_dict, dim, input="dataset"): """Get label from a given dimension. Args: js_dict (dict): dictionary containing dataset data and metadata. dim (string): dimension name obtained from JSON file. Returns: dim_label(pandas.DataFrame): DataFrame with label-based dimension data. """
if input == 'dataset': input = js_dict['dimension'][dim] label_col = 'label' elif input == 'dimension': label_col = js_dict['label'] input = js_dict else: raise ValueError try: dim_label = input['category']['label'] except KeyError: dim_index = get_dim_index(js_dict, dim) dim_label = pd.concat([dim_index['id'], dim_index['id']], axis=1) dim_label.columns = ['id', 'label'] else: dim_label = pd.DataFrame(list(zip(dim_label.keys(), dim_label.values())), index=dim_label.keys(), columns=['id', label_col]) # index must be added to dim label so that it can be sorted try: dim_index = input['category']['index'] except KeyError: dim_index = pd.DataFrame(list(zip([dim_label['id'][0]], [0])), index=[0], columns=['id', 'index']) else: if type(dim_index) is list: dim_index = pd.DataFrame(list(zip(dim_index, range(0, len(dim_index)))), index=dim_index, columns=['id', 'index']) else: dim_index = pd.DataFrame(list(zip(dim_index.keys(), dim_index.values())), index=dim_index.keys(), columns=['id', 'index']) dim_label = pd.merge(dim_label, dim_index, on='id').sort_index(by='index') return dim_label
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dim_index(js_dict, dim): """Get index from a given dimension. Args: js_dict (dict): dictionary containing dataset data and metadata. dim (string): dimension name obtained from JSON file. Returns: dim_index (pandas.DataFrame): DataFrame with index-based dimension data. """
try: dim_index = js_dict['dimension'][dim]['category']['index'] except KeyError: dim_label = get_dim_label(js_dict, dim) dim_index = pd.DataFrame(list(zip([dim_label['id'][0]], [0])), index=[0], columns=['id', 'index']) else: if type(dim_index) is list: dim_index = pd.DataFrame(list(zip(dim_index, range(0, len(dim_index)))), index=dim_index, columns=['id', 'index']) else: dim_index = pd.DataFrame(list(zip(dim_index.keys(), dim_index.values())), index=dim_index.keys(), columns=['id', 'index']) dim_index = dim_index.sort_index(by='index') return dim_index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_values(js_dict, value='value'): """Get values from input data. Args: js_dict (dict): dictionary containing dataset data and metadata. value (string, optional): name of the value column. Defaults to 'value'. Returns: values (list): list of dataset values. """
values = js_dict[value] if type(values) is list: if type(values[0]) is not dict or tuple: return values # being not a list of dicts or tuples leaves us with a dict... values = {int(key): value for (key, value) in values.items()} if js_dict.get('size'): max_val = np.prod(np.array((js_dict['size']))) else: max_val = np.prod(np.array((js_dict['dimension']['size']))) vals = max_val * [None] for (key, value) in values.items(): vals[key] = value values = vals return values
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_df_row(dimensions, naming='label', i=0, record=None): """Generate row dimension values for a pandas dataframe. Args: dimensions (list): list of pandas dataframes with dimension labels \ generated by get_dim_label or get_dim_index methods. naming (string, optional): dimension naming. Possible values: 'label' \ or 'id'. i (int): dimension list iteration index. Default is 0, it's used in the \ recursive calls to the method. record (list): list of values representing a pandas dataframe row, \ except for the value column. Default is empty, it's used \ in the recursive calls to the method. Yields: list: list with pandas dataframe column values except for value column """
check_input(naming) if i == 0 or record is None: record = [] for dimension in dimensions[i][naming]: record.append(dimension) if len(record) == len(dimensions): yield record if i + 1 < len(dimensions): for row in get_df_row(dimensions, naming, i + 1, record): yield row if len(record) == i + 1: record.pop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_json_stat(datasets, naming='label', value='value'): """Decode JSON-stat formatted data into pandas.DataFrame object. Args: datasets(OrderedDict, list): data in JSON-stat format, previously \ deserialized to a python object by \ json.load() or json.loads(), for example.\ Both List and OrderedDict are accepted \ as inputs. naming(string, optional): dimension naming. Possible values: 'label' or 'id'.Defaults to 'label'. value (string, optional): name of the value column. Defaults to 'value'. Returns: results(list): list of pandas.DataFrame with imported data. """
warnings.warn( "Shouldn't use this function anymore! Now use read() methods of" "Dataset, Collection or Dimension.", DeprecationWarning ) check_input(naming) results = [] if type(datasets) is list: for idx, element in enumerate(datasets): for dataset in element: js_dict = datasets[idx][dataset] results.append(generate_df(js_dict, naming, value)) elif isinstance(datasets, OrderedDict) or type(datasets) is dict or \ isinstance(datasets, Dataset): if 'class' in datasets: if datasets['class'] == 'dataset': js_dict = datasets results.append(generate_df(js_dict, naming, value)) else: # 1.00 bundle type for dataset in datasets: js_dict = datasets[dataset] results.append(generate_df(js_dict, naming, value)) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(path): """Send a request to a given URL accepting JSON format and return a \ deserialized Python object. Args: path (str): The URI to be requested. Returns: response: Deserialized JSON Python object. Raises: HTTPError: the HTTP error returned by the requested server. InvalidURL: an invalid URL has been requested. Exception: generic exception. """
headers = {'Accept': 'application/json'} try: requested_object = requests.get(path, headers=headers) requested_object.raise_for_status() except requests.exceptions.HTTPError as exception: LOGGER.error((inspect.stack()[0][3]) + ': HTTPError = ' + str(exception.response.status_code) + ' ' + str(exception.response.reason) + ' ' + str(path)) raise except requests.exceptions.InvalidURL as exception: LOGGER.error('URLError = ' + str(exception.reason) + ' ' + str(path)) raise except Exception: import traceback LOGGER.error('Generic exception: ' + traceback.format_exc()) raise else: response = requested_object.json() return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth_required(func): """Utility decorator that checks if a user has been authenticated for this request. Allows views to be decorated like: @auth_required def view_func(request): pass providing a simple means to ensure that whoever is calling the function has the correct authentication details. Args: func: Function object being decorated and raises HTTPForbidden if not Returns: A function object that will raise web.HTTPForbidden() if the passed request does not have the correct permissions to access the view. """
@wraps(func) async def wrapper(*args): if (await get_auth(args[-1])) is None: raise web.HTTPForbidden() return await func(*args) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_partial(parser, token): """ Inserts the output of a view, using fully qualified view name, or view name from urls.py. IMPORTANT: the calling template must receive a context variable called 'request' containing the original HttpRequest. This means you should be OK with permissions and other session state. (Note that every argument will be evaluated against context except for the names of any keyword arguments.) """
args = [] kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError( '%r tag requires one or more arguments' % token.contents.split()[0] ) tokens.pop(0) # tag name view_name = tokens.pop(0) for token in tokens: equals = token.find('=') if equals == -1: args.append(token) else: kwargs[str(token[:equals])] = token[equals+1:] return ViewNode(view_name, args, kwargs)