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 inputAnalyzeCallback(self, *args, **kwargs): """ Test method for inputAnalzeCallback This method loops over the passed number of files, and optionally "delays" in each loop to simulate some analysis. The delay length is specified by the '--test <delay>' flag. """
b_status = False filesRead = 0 filesAnalyzed = 0 for k, v in kwargs.items(): if k == 'filesRead': d_DCMRead = v if k == 'path': str_path = v if len(args): at_data = args[0] str_path = at_data[0] d_read = at_data[1] b_status = True self.dp.qprint("analyzing:\n%s" % self.pp.pformat(d_read['l_file']), level = 5) if int(self.f_sleepLength): self.dp.qprint("sleeping for: %f" % self.f_sleepLength, level = 5) time.sleep(self.f_sleepLength) filesAnalyzed = len(d_read['l_file']) return { 'status': b_status, 'filesAnalyzed': filesAnalyzed, 'l_file': d_read['l_file'] }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def outputSaveCallback(self, at_data, **kwargs): """ Test method for outputSaveCallback Simply writes a file in the output tree corresponding to the number of files in the input tree. """
path = at_data[0] d_outputInfo = at_data[1] other.mkdir(self.str_outputDir) filesSaved = 0 other.mkdir(path) if not self.testType: str_outfile = '%s/file-ls.txt' % path else: str_outfile = '%s/file-count.txt' % path with open(str_outfile, 'w') as f: self.dp.qprint("saving: %s" % (str_outfile), level = 5) if not self.testType: f.write('%s`' % self.pp.pformat(d_outputInfo['l_file'])) else: f.write('%d\n' % d_outputInfo['filesAnalyzed']) filesSaved += 1 return { 'status': True, 'outputFile': str_outfile, 'filesSaved': filesSaved }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, *args, **kwargs): """ Probe the input tree and print. """
b_status = True d_probe = {} d_tree = {} d_stats = {} str_error = '' b_timerStart = False d_test = {} for k, v in kwargs.items(): if k == 'timerStart': b_timerStart = bool(v) if b_timerStart: other.tic() if not os.path.exists(self.str_inputDir): b_status = False self.dp.qprint( "input directory either not specified or does not exist.", comms = 'error' ) error.warn(self, 'inputDirFail', exitToOS = True, drawBox = True) str_error = 'error captured while accessing input directory' if b_status: str_origDir = os.getcwd() if self.b_relativeDir: os.chdir(self.str_inputDir) str_rootDir = '.' else: str_rootDir = self.str_inputDir d_probe = self.tree_probe( root = str_rootDir ) b_status = b_status and d_probe['status'] d_tree = self.tree_construct( l_files = d_probe['l_files'], constructCallback = self.dirsize_get ) b_status = b_status and d_tree['status'] if self.b_test: d_test = self.test_run(*args, **kwargs) b_status = b_status and d_test['status'] else: if self.b_stats or self.b_statsReverse: d_stats = self.stats_compute() self.dp.qprint('Total size (raw): %d' % d_stats['totalSize'], level = 1) self.dp.qprint('Total size (human): %s' % d_stats['totalSize_human'], level = 1) self.dp.qprint('Total files: %s' % d_stats['files'], level = 1) self.dp.qprint('Total dirs: %s' % d_stats['dirs'], level = 1) b_status = b_status and d_stats['status'] if self.b_jsonStats: print(json.dumps(d_stats, indent = 4, sort_keys = True)) if self.b_relativeDir: os.chdir(str_origDir) d_ret = { 'status': b_status, 'd_probe': d_probe, 'd_tree': d_tree, 'd_stats': d_stats, 'd_test': d_test, 'str_error': str_error, 'runTime': other.toc() } if self.b_json: print(json.dumps(d_ret, indent = 4, sort_keys = True)) return d_ret
<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_status(self, status, result=None): """ update operation status :param str status: New status :param cdumay_result.Result result: Execution result """
logger.info( "{}.SetStatus: {}[{}] status update '{}' -> '{}'".format( self.__class__.__name__, self.__class__.path, self.uuid, self.status, status ), extra=dict( kmsg=Message( self.uuid, entrypoint=self.__class__.path, params=self.params ).dump() ) ) return self.set_status(status, result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prerun(self): """ To execute before running message """
self.check_required_params() self._set_status("RUNNING") logger.debug( "{}.PreRun: {}[{}]: running...".format( self.__class__.__name__, self.__class__.path, self.uuid ), extra=dict( kmsg=Message( self.uuid, entrypoint=self.__class__.path, params=self.params ).dump() ) ) return self.prerun()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self, task): """ Find the next task :param kser.sequencing.task.Task task: previous task :return: The next task :rtype: kser.sequencing.task.Task or None """
uuid = str(task.uuid) for idx, otask in enumerate(self.tasks[:-1]): if otask.uuid == uuid: if self.tasks[idx + 1].status != 'SUCCESS': return self.tasks[idx + 1] else: uuid = self.tasks[idx + 1].uuid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def launch_next(self, task=None, result=None): """ Launch next task or finish operation :param kser.sequencing.task.Task task: previous task :param cdumay_result.Result result: previous task result :return: Execution result :rtype: cdumay_result.Result """
if task: next_task = self.next(task) if next_task: return next_task.send(result=result) else: return self.set_status(task.status, result) elif len(self.tasks) > 0: return self.tasks[0].send(result=result) else: return Result(retcode=1, stderr="Nothing to do, empty operation !")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_tasks(self, **kwargs): """ perfrom checks and build tasks :return: list of tasks :rtype: list(kser.sequencing.operation.Operation) """
params = self._prebuild(**kwargs) if not params: params = dict(kwargs) return self._build_tasks(**params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(self, **kwargs): """ create the operation and associate tasks :param dict kwargs: operation data :return: the controller :rtype: kser.sequencing.controller.OperationController """
self.tasks += self.compute_tasks(**kwargs) return self.finalize()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serve_dtool_directory(directory, port): """Serve the datasets in a directory over HTTP."""
os.chdir(directory) server_address = ("localhost", port) httpd = DtoolHTTPServer(server_address, DtoolHTTPRequestHandler) httpd.serve_forever()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(): """Command line utility for serving datasets in a directory over HTTP."""
parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "dataset_directory", help="Directory with datasets to be served" ) parser.add_argument( "-p", "--port", type=int, default=8081, help="Port to serve datasets on (default 8081)" ) args = parser.parse_args() if not os.path.isdir(args.dataset_directory): parser.error("Not a directory: {}".format(args.dataset_directory)) serve_dtool_directory(args.dataset_directory, args.port)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_url(self, suffix): """Return URL by combining server details with a path suffix."""
url_base_path = os.path.dirname(self.path) netloc = "{}:{}".format(*self.server.server_address) return urlunparse(( "http", netloc, url_base_path + "/" + suffix, "", "", ""))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_http_manifest(self): """Return http manifest. The http manifest is the resource that defines a dataset as HTTP enabled (published). """
base_path = os.path.dirname(self.translate_path(self.path)) self.dataset = dtoolcore.DataSet.from_uri(base_path) admin_metadata_fpath = os.path.join(base_path, ".dtool", "dtool") with open(admin_metadata_fpath) as fh: admin_metadata = json.load(fh) http_manifest = { "admin_metadata": admin_metadata, "manifest_url": self.generate_url(".dtool/manifest.json"), "readme_url": self.generate_url("README.yml"), "overlays": self.generate_overlay_urls(), "item_urls": self.generate_item_urls() } return bytes(json.dumps(http_manifest), "utf-8")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_GET(self): """Override inherited do_GET method. Include logic for returning a http manifest when the URL ends with "http_manifest.json". """
if self.path.endswith("http_manifest.json"): try: manifest = self.generate_http_manifest() self.send_response(200) self.end_headers() self.wfile.write(manifest) except dtoolcore.DtoolCoreTypeError: self.send_response(400) self.end_headers() else: super(DtoolHTTPRequestHandler, self).do_GET()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def indent(self, code, level=1): '''python's famous indent''' lines = code.split('\n') lines = tuple(self.indent_space*level + line for line in lines) return '\n'.join(lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve_authorization_code(self, redirect_func=None): """ retrieve authorization code to get access token """
request_param = { "client_id": self.client_id, "redirect_uri": self.redirect_uri, } if self.scope: request_param['scope'] = self.scope if self._extra_auth_params: request_param.update(self._extra_auth_params) r = requests.get(self.auth_uri, params=request_param, allow_redirects=False) url = r.headers.get('location') if self.local: webbrowser.open_new_tab(url) authorization_code = raw_input("Code: ") if self.validate_code(authorization_code): self.authorization_code = authorization_code else: return redirect_func(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve_token(self): """ retrieve access token with code fetched via retrieve_authorization_code method. """
if self.authorization_code: request_param = { "client_id": self.client_id, "client_secret": self.client_secret, "redirect_uri": self.redirect_uri, "code": self.authorization_code } if self._extra_token_params: request_param.update(self._extra_token_params) content_length = len(urlencode(request_param)) headers = { 'Content-Length': str(content_length), 'Content-Type': 'application/x-www-form-urlencoded' } r = requests.post(self.token_uri, data=request_param, headers=headers) jsondata = json.loads(r.text) self.access_token = jsondata return self.access_token else: print("authorization code is required before getting accesss token") print("Please call retrieve_authorization_code() beforehand")
<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_dict(self): '''Represents the setup section in form of key-value pairs. Returns ------- dict ''' mapping = dict() for attr in dir(self): if attr.startswith('_'): continue if not isinstance(getattr(self.__class__, attr), property): continue try: value = getattr(self, attr) except AttributeError: if attr in self._OPTIONAL_ATTRS: continue else: raise AttributeError( 'Required attribute "{0}" does not exist on ' 'instance of type "{1}.'.format( attr, self.__class__.__name__ ) ) mapping[attr] = value return mapping
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mtime(path): """Get the modification time of a file, or -1 if the file does not exist. """
if not os.path.exists(path): return -1 stat = os.stat(path) return stat.st_mtime
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_coin_link(copper, silver=0, gold=0): """Encode a chat link for an amount of coins. """
return encode_chat_link(gw2api.TYPE_COIN, copper=copper, silver=silver, gold=gold)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status(self, status): """Sets the status of this StoreCreditPayment. :param status: The status of this StoreCreditPayment. :type: str """
allowed_values = ["pending", "awaitingRetry", "successful", "failed"] if status is not None and status not in allowed_values: raise ValueError( "Invalid value for `status` ({0}), must be one of {1}" .format(status, allowed_values) ) self._status = status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nmtoken_from_string(text): """ Returns a Nmtoken from a string. It is useful to produce XHTML valid values for the 'name' attribute of an anchor. CAUTION: the function is surjective: 2 different texts might lead to the same result. This is improbable on a single page. Nmtoken is the type that is a mixture of characters supported in attributes such as 'name' in HTML 'a' tag. For example, <a name="Articles%20%26%20Preprints"> should be tranformed to <a name="Articles372037263720Preprints"> using this function. http://www.w3.org/TR/2000/REC-xml-20001006#NT-Nmtoken Also note that this function filters more characters than specified by the definition of Nmtoken ('CombiningChar' and 'Extender' charsets are filtered out). """
text = text.replace('-', '--') return ''.join([(((not char.isalnum() and char not in [ '.', '-', '_', ':' ]) and str(ord(char))) or char) for char in text])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tidy_html(html_buffer, cleaning_lib='utidylib'): """ Tidy up the input HTML using one of the installed cleaning libraries. @param html_buffer: the input HTML to clean up @type html_buffer: string @param cleaning_lib: chose the preferred library to clean the HTML. One of: - utidylib - beautifulsoup @return: a cleaned version of the input HTML @note: requires uTidylib or BeautifulSoup to be installed. If the chosen library is missing, the input X{html_buffer} is returned I{as is}. """
if CFG_TIDY_INSTALLED and cleaning_lib == 'utidylib': options = dict(output_xhtml=1, show_body_only=1, merge_divs=0, wrap=0) try: output = str(tidy.parseString(html_buffer, **options)) except: output = html_buffer elif CFG_BEAUTIFULSOUP_INSTALLED and cleaning_lib == 'beautifulsoup': try: output = str(BeautifulSoup(html_buffer).prettify()) except: output = html_buffer else: output = html_buffer return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_html_markup(text, replacechar=' ', remove_escaped_chars_p=True): """ Remove HTML markup from text. @param text: Input text. @type text: string. @param replacechar: By which character should we replace HTML markup. Usually, a single space or an empty string are nice values. @type replacechar: string @param remove_escaped_chars_p: If True, also remove escaped characters like '&amp;', '&lt;', '&gt;' and '&quot;'. @type remove_escaped_chars_p: boolean @return: Input text with HTML markup removed. @rtype: string """
if not remove_escaped_chars_p: return RE_HTML_WITHOUT_ESCAPED_CHARS.sub(replacechar, text) return RE_HTML.sub(replacechar, text)
<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_html_select( options, name=None, selected=None, disabled=None, multiple=False, attrs=None, **other_attrs): """ Create an HTML select box. <select name="baz"> <option selected="selected" value="bar"> bar </option> <option value="foo"> foo </option> </select> <select name="baz"> <option value="foo"> oof </option> <option selected="selected" value="bar"> rab </option> </select> @param options: this can either be a sequence of strings, or a sequence of couples or a map of C{key->value}. In the former case, the C{select} tag will contain a list of C{option} tags (in alphabetical order), where the C{value} attribute is not specified. In the latter case, the C{value} attribute will be set to the C{key}, while the body of the C{option} will be set to C{value}. @type options: sequence or map @param name: the name of the form element. @type name: string @param selected: optional key(s)/value(s) to select by default. In case a map has been used for options. @type selected: string (or list of string) @param disabled: optional key(s)/value(s) to disable. @type disabled: string (or list of string) @param multiple: whether a multiple select box must be created. @type mutable: bool @param attrs: optional attributes to create the select tag. @type attrs: dict @param other_attrs: other optional attributes. @return: the HTML output. @rtype: string @note: the values and keys will be escaped for HTML. @note: it is important that parameter C{value} is always specified, in case some browser plugin play with the markup, for eg. when translating the page. """
body = [] if selected is None: selected = [] elif isinstance(selected, (str, unicode)): selected = [selected] if disabled is None: disabled = [] elif isinstance(disabled, (str, unicode)): disabled = [disabled] if name is not None and multiple and not name.endswith('[]'): name += "[]" if isinstance(options, dict): items = options.items() items.sort(lambda item1, item2: cmp(item1[1], item2[1])) elif isinstance(options, (list, tuple)): options = list(options) items = [] for item in options: if isinstance(item, (str, unicode)): items.append((item, item)) elif isinstance(item, (tuple, list)) and len(item) == 2: items.append(tuple(item)) else: raise ValueError( 'Item "%s" of incompatible type: %s' % (item, type(item))) else: raise ValueError('Options of incompatible type: %s' % type(options)) for key, value in items: option_attrs = {} if key in selected: option_attrs['selected'] = 'selected' if key in disabled: option_attrs['disabled'] = 'disabled' body.append( create_tag( "option", body=value, escape_body=True, value=key, attrs=option_attrs)) if attrs is None: attrs = {} if name is not None: attrs['name'] = name if multiple: attrs['multiple'] = 'multiple' return create_tag( "select", body='\n'.join(body), attrs=attrs, **other_attrs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wash( self, html_buffer, render_unallowed_tags=False, allowed_tag_whitelist=CFG_HTML_BUFFER_ALLOWED_TAG_WHITELIST, automatic_link_transformation=False, allowed_attribute_whitelist=CFG_HTML_BUFFER_ALLOWED_ATTRIBUTE_WHITELIST): """ Wash HTML buffer, escaping XSS attacks. @param html_buffer: text to escape @param render_unallowed_tags: if True, print unallowed tags escaping < and >. Else, only print content of unallowed tags. @param allowed_tag_whitelist: list of allowed tags @param allowed_attribute_whitelist: list of allowed attributes """
self.reset() self.result = '' self.nb = 0 self.previous_nbs = [] self.previous_type_lists = [] self.url = '' self.render_unallowed_tags = render_unallowed_tags self.automatic_link_transformation = automatic_link_transformation self.allowed_tag_whitelist = allowed_tag_whitelist self.allowed_attribute_whitelist = allowed_attribute_whitelist self.feed(html_buffer) self.close() return self.result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def template_from_filename(filename): """Returns the appropriate template name based on the given file name."""
ext = filename.split(os.path.extsep)[-1] if not ext in TEMPLATES_MAP: raise ValueError("No template for file extension {}".format(ext)) return TEMPLATES_MAP[ext]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dt2ts(dt): """Converts to float representing number of seconds since 1970-01-01 GMT."""
# Note: no assertion to really keep this fast assert isinstance(dt, (datetime.datetime, datetime.date)) ret = time.mktime(dt.timetuple()) if isinstance(dt, datetime.datetime): ret += 1e-6 * dt.microsecond return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dt2str(dt, flagSeconds=True): """Converts datetime object to str if not yet an str."""
if isinstance(dt, str): return dt return dt.strftime(_FMTS if flagSeconds else _FMT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time2seconds(t): """Returns seconds since 0h00."""
return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Fit(self, zxq): """Perform a 2D fit on 2D points then return parameters :param zxq: A list where each element is (z, transverse, charge) """
z, trans, Q = zip(*zxq) assert len(trans) == len(z) ndf = len(z) - 3 z = np.array(z) trans = np.array(trans) def dbexpl(t, p): return(p[0] - p[1] * t + p[2] * t ** 2) def residuals(p, data, t): err = data - dbexpl(t, p) return err doc = {} try: assert ndf > 0 p0 = [1, 0, 0] # initial guesses pbest = leastsq(residuals, p0, args=(trans, z), full_output=1) bestparams = pbest[0] good_of_fit = sum(pbest[2]['fvec'] ** 2) good_of_fit = float(good_of_fit / ndf) doc['params'] = list(bestparams) doc['gof'] = good_of_fit except: doc['gof'] = 'FAIL' doc['params'] = [0, 0, 0] return doc
<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_last_transverse_over_list(self, zxq): """ Get transverse coord at highest z :param zx: A list where each element is (z, transverse, charge) """
z_max = None x_of_interest = None for z, x, q in zxq: if z == None or z > z_max: x_of_interest = x return x_of_interest
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def item_details(item_id, lang="en"): """This resource returns a details about a single item. :param item_id: The item to query for. :param lang: The language to display the texts in. The response is an object with at least the following properties. Note that the availability of some properties depends on the type of the item. item_id (number): The item id. name (string): The name of the item. description (string): The item description. type (string): The item type. level (integer): The required level. rarity (string): The rarity. On of ``Junk``, ``Basic``, ``Fine``, ``Masterwork``, ``Rare``, ``Exotic``, ``Ascended`` or ``Legendary``. vendor_value (integer): The value in coins when selling to a vendor. icon_file_id (string): The icon file id to be used with the render service. icon_file_signature (string): The icon file signature to be used with the render service. game_types (list): The game types where the item is usable. Currently known game types are: ``Activity``, ``Dungeon``, ``Pve``, ``Pvp``, ``PvpLobby`` and ``WvW`` flags (list): Additional item flags. Currently known item flags are: ``AccountBound``, ``HideSuffix``, ``NoMysticForge``, ``NoSalvage``, ``NoSell``, ``NotUpgradeable``, ``NoUnderwater``, ``SoulbindOnAcquire``, ``SoulBindOnUse`` and ``Unique`` restrictions (list): Race restrictions: ``Asura``, ``Charr``, ``Human``, ``Norn`` and ``Sylvari``. Each item type has an `additional key`_ with information specific to that item type. .. _additional key: item-properties.html """
params = {"item_id": item_id, "lang": lang} cache_name = "item_details.%(item_id)s.%(lang)s.json" % params return get_cached("item_details.json", cache_name, params=params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recipe_details(recipe_id, lang="en"): """This resource returns a details about a single recipe. :param recipe_id: The recipe to query for. :param lang: The language to display the texts in. The response is an object with the following properties: recipe_id (number): The recipe id. type (string): The type of the produced item. output_item_id (string): The item id of the produced item. output_item_count (string): The amount of items produced. min_rating (string): The minimum rating of the recipe. time_to_craft_ms (string): The time it takes to craft the item. disciplines (list): A list of crafting disciplines that can use the recipe. flags (list): Additional recipe flags. Known flags: ``AutoLearned``: Set for recipes that don't have to be discovered. ``LearnedFromItem``: Set for recipes that need a recipe sheet. ingredients (list): A list of objects describing the ingredients for this recipe. Each object contains the following properties: item_id (string): The item id of the ingredient. count (string): The amount of ingredients required. """
params = {"recipe_id": recipe_id, "lang": lang} cache_name = "recipe_details.%(recipe_id)s.%(lang)s.json" % params return get_cached("recipe_details.json", cache_name, params=params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def requires_indieauth(f): """Wraps a Flask handler to require a valid IndieAuth access token. """
@wraps(f) def decorated(*args, **kwargs): access_token = get_access_token() resp = check_auth(access_token) if isinstance(resp, Response): return resp return f(*args, **kwargs) 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 check_auth(access_token): """This function contacts the configured IndieAuth Token Endpoint to see if the given token is a valid token and for whom. """
if not access_token: current_app.logger.error('No access token.') return deny('No access token found.') request = Request( current_app.config['TOKEN_ENDPOINT'], headers={"Authorization" : ("Bearer %s" % access_token)} ) contents = urlopen(request).read().decode('utf-8') token_data = parse_qs(contents) me = token_data['me'][0] client_id = token_data['client_id'][0] if me is None or client_id is None: current_app.logger.error("Invalid token [%s]" % contents) return deny('Invalid token') me, me_error = check_me(me) if me is None: current_app.logger.error("Invalid `me` value [%s]" % me_error) return deny(me_error) scope = token_data['scope'] if not isinstance(scope, str): scope = scope[0] valid_scopes = ('post','create', ) scope_ = scope.split() scope_valid = any((val in scope_) for val in valid_scopes) if not scope_valid: current_app.logger.error("Scope '%s' does not contain 'post' or 'create'." % scope) return deny("Scope '%s' does not contain 'post' or 'create'." % scope) g.user = { 'me': me, 'client_id': client_id, 'scope': scope, 'access_token': access_token }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect_db(config): """Connects to the specific database."""
rv = sqlite3.connect(config["database"]["uri"]) rv.row_factory = sqlite3.Row return rv
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def harvest_repo(root_url, archive_path, tag=None, archive_format='tar.gz'): """ Archives a specific tag in a specific Git repository. :param root_url: The URL to the Git repo - Supported protocols: git, ssh, http[s]. :param archive_path: A temporary path to clone the repo to - Must end in .git :param tag: The path to which the .tar.gz will go to - Must end in the same as format (NOT inside clone_path) :param format: One of the following: tar.gz / tar / zip """
if not git_exists(): raise Exception("Git not found. It probably needs installing.") clone_path = mkdtemp(dir=cfg['CFG_TMPDIR']) git = get_which_git() call([git, 'clone', root_url, clone_path]) chdir(clone_path) if tag: call([git, 'archive', '--format=' + archive_format, '-o', archive_path, tag]) else: call([git, 'archive', '--format=' + archive_format, '-o', archive_path, 'HEAD']) try: rmtree(clone_path) except OSError as e: # Reraise unless ENOENT: No such file or directory # (ok if directory has already been deleted) if e.errno != errno.ENOENT: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gregorian_to_julian(day): """Convert a datetime.date object to its corresponding Julian day. :param day: The datetime.date to convert to a Julian day :returns: A Julian day, as an integer """
before_march = 1 if day.month < MARCH else 0 # # Number of months since March # month_index = day.month + MONTHS_PER_YEAR * before_march - MARCH # # Number of years (year starts on March) since 4800 BC # years_elapsed = day.year - JULIAN_START_YEAR - before_march total_days_in_previous_months = (153 * month_index + 2) // 5 total_days_in_previous_years = 365 * years_elapsed total_leap_days = ( (years_elapsed // 4) - (years_elapsed // 100) + (years_elapsed // 400) ) return sum([ day.day, total_days_in_previous_months, total_days_in_previous_years, total_leap_days, -32045, # Offset to get January 1, 4713 equal to 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 sun_declination(day): """Compute the declination angle of the sun for the given date. Uses the Spencer Formula (found at http://www.illustratingshadows.com/www-formulae-collection.pdf) :param day: The datetime.date to compute the declination angle for :returns: The angle, in degrees, of the angle of declination """
day_of_year = day.toordinal() - date(day.year, 1, 1).toordinal() day_angle = 2 * pi * day_of_year / 365 declination_radians = sum([ 0.006918, 0.001480*sin(3*day_angle), 0.070257*sin(day_angle), 0.000907*sin(2*day_angle), -0.399912*cos(day_angle), -0.006758*cos(2*day_angle), -0.002697*cos(3*day_angle), ]) return degrees(declination_radians)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def equation_of_time(day): """Compute the equation of time for the given date. Uses formula described at https://en.wikipedia.org/wiki/Equation_of_time#Alternative_calculation :param day: The datetime.date to compute the equation of time for :returns: The angle, in radians, of the Equation of Time """
day_of_year = day.toordinal() - date(day.year, 1, 1).toordinal() # pylint: disable=invalid-name # # Distance Earth moves from solstice to January 1 (so about 10 days) # A = EARTH_ORIBITAL_VELOCITY * (day_of_year + 10) # # Distance Earth moves from solstice to day_of_year # 2 is the number of days from Jan 1 to periheleon # This is the result of a lot of constants collapsing # B = A + 1.914 * sin(radians(EARTH_ORIBITAL_VELOCITY * (day_of_year - 2))) # # Compute "the difference between the angles moved at mean speed, and at # the corrected speed projected onto the equatorial plane, and [divide] by # 180 to get the difference in 'half turns'" # movement_on_equatorial_plane = degrees( atan2( tan(radians(B)), cos(EARTH_AXIS_TILT) ) ) eot_half_turns = (A - movement_on_equatorial_plane) / 180 result = 720 * (eot_half_turns - int(eot_half_turns + 0.5)) return radians(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_zuhr_utc(day, longitude): """Compute the UTC floating point time for Zuhr given date and longitude. This function is necessary since all other prayer times are based on the time for Zuhr :param day: The day to compute Zuhr adhan for :param longitude: Longitude of the place of interest :returns: The UTC time for Zuhr, as a floating point number in [0, 24) """
eot = equation_of_time(day) # # Formula as described by PrayTime.org doesn't work in Eastern hemisphere # because it expects to be subtracting a negative longitude. +abs() should # do the trick # zuhr_time_utc = 12 + (abs(longitude) / 15) - eot return abs(zuhr_time_utc) % 24
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_time_at_sun_angle(day, latitude, angle): """Compute the floating point time difference between mid-day and an angle. All the prayers are defined as certain angles from mid-day (Zuhr). This formula is taken from praytimes.org/calculation :param day: The day to which to compute for :param longitude: Longitude of the place of interest :angle: The angle at which to compute the time :returns: The floating point time delta between Zuhr and the angle, the sign of the result corresponds to the sign of the angle """
positive_angle_rad = radians(abs(angle)) angle_sign = abs(angle)/angle latitude_rad = radians(latitude) declination = radians(sun_declination(day)) numerator = -sin(positive_angle_rad) - sin(latitude_rad) * sin(declination) denominator = cos(latitude_rad) * cos(declination) time_diff = degrees(acos(numerator/denominator)) / 15 return time_diff * angle_sign
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_at_shadow_length(day, latitude, multiplier): """Compute the time at which an object's shadow is a multiple of its length. Specifically, determine the time the length of the shadow is a multiple of the object's length + the length of the object's shadow at noon This is used in the calculation for Asr time. Hanafi uses a multiplier of 2, and everyone else uses a multiplier of 1 Algorithm taken almost directly from PrayTimes.org code :param day: The day which to compute for :param latitude: The latitude of the place of interest :param: multiplier: The multiplier of the object's length :returns: The floating point time delta between Zuhr and the time at which the lenghth of the shadow is as defined """
latitude_rad = radians(latitude) declination = radians(sun_declination(day)) angle = arccot( multiplier + tan(abs(latitude_rad - declination)) ) numerator = sin(angle) - sin(latitude_rad)*sin(declination) denominator = cos(latitude_rad) * cos(declination) return degrees(acos(numerator/denominator)) / 15
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse_range_header(range): ''' Parse a range header as used by the dojo Json Rest store. :param str range: The content of the range header to be parsed. eg. `items=0-9` :returns: A dict with keys start, finish and number or `False` if the range is invalid. ''' match = re.match('^items=([0-9]+)-([0-9]+)$', range) if match: start = int(match.group(1)) finish = int(match.group(2)) if finish < start: finish = start return { 'start': start, 'finish': finish, 'number': finish - start + 1 } 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 on(self, event): """ Returns a wrapper for the given event. Usage: @dispatch.on("my_event") def handle_my_event(foo, bar, baz): """
handler = self._handlers.get(event, None) if not handler: raise ValueError("Unknown event '{}'".format(event)) return handler.register
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, event, keys): """ Register a new event with available keys. Raises ValueError when the event has already been registered. Usage: dispatch.register("my_event", ["foo", "bar", "baz"]) """
if self.running: raise RuntimeError("Can't register while running") handler = self._handlers.get(event, None) if handler is not None: raise ValueError("Event {} already registered".format(event)) self._handlers[event] = EventHandler(event, keys, loop=self.loop)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister(self, event): """ Remove all registered handlers for an event. Silent return when event was not registered. Usage: dispatch.unregister("my_event") dispatch.unregister("my_event") # no-op """
if self.running: raise RuntimeError("Can't unregister while running") self._handlers.pop(event, 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 trigger(self, event, kwargs): """ Enqueue an event for processing """
await self._queue.put((event, kwargs)) self._resume_processing.set()
<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 _task(self): """ Main queue processor """
if self._handlers.values(): start_tasks = [h.start() for h in self._handlers.values()] await asyncio.wait(start_tasks, loop=self.loop) while self.running: if self.events: event, kwargs = await self._queue.get() handler = self._handlers.get(event, None) if handler: handler(kwargs) else: # Resume on either the next `trigger` call or a `stop` await self._resume_processing.wait() self._resume_processing.clear() # Give all the handlers a chance to complete their pending tasks tasks = [handler.stop() for handler in self._handlers.values()] if tasks: await asyncio.wait(tasks, loop=self.loop) # Let the shutdown process continue await self._complete_shutdown()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restriction(lam, mu, orbitals, U, beta): """Equation that determines the restriction on lagrange multipier"""
return 2*orbitals*fermi_dist(-(mu + lam), beta) - expected_filling(-1*lam, orbitals, U, beta)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pressision_try(orbitals, U, beta, step): """perform a better initial guess of lambda no improvement"""
mu, lam = main(orbitals, U, beta, step) mu2, lam2 = linspace(0, U*orbitals, step), zeros(step) for i in range(99): lam2[i+1] = fsolve(restriction, lam2[i], (mu2[i+1], orbitals, U, beta)) plot(mu2, 2*orbitals*fermi_dist(-(mu2+lam2), beta), label='Test guess') legend(loc=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 spin_z(particles, index): """Generates the spin_z projection operator for a system of N=particles and for the selected spin index name. where index=0..N-1"""
mat = np.zeros((2**particles, 2**particles)) for i in range(2**particles): ispin = btest(i, index) if ispin == 1: mat[i, i] = 1 else: mat[i, i] = -1 return 1/2.*mat
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spin_gen(particles, index, gauge=1): """Generates the generic spin operator in z basis for a system of N=particles and for the selected spin index name. where index=0..N-1 The gauge term sets the behavoir for a system away from half-filling"""
mat = np.zeros((2**particles, 2**particles)) flipper = 2**index for i in range(2**particles): ispin = btest(i, index) if ispin == 1: mat[i ^ flipper, i] = 1 else: mat[i ^ flipper, i] = gauge return mat
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def revoke(self, token, pipe=None): """\ Revokes the key associated with the given revokation token. If the token does not exist, a :class:`KeyError <KeyError>` is thrown. Otherwise `None` is returned. If `pipe` is given, then a :class:`RevokeError <shorten.RevokeError>` will not be thrown if the key does not exist. The n-th from last result should be checked like so: :: pipe = redis.Pipeline() store.revoke(token, pipe=pipe) results = pipe.execute() if not results[-1]: raise RevokeError(token) :param pipe: a Redis pipeline. If `None`, the token will be revoked immediately. Otherwise they must be extracted from the pipeline results (see above). """
p = self.redis.pipeline() if pipe is None else pipe formatted_token = self.format_token(token) try: p.watch(formatted_token) # Get the key immediately key = p.get(formatted_token) formatted_key = self.format_key(key) # Make this atomic p.multi() p.delete(formatted_key, formatted_token) if pipe is None: if not p.execute()[-1]: raise RevokeError(token, 'token not found') except WatchError: raise finally: if pipe is None: p.reset()
<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 oauth(request): """Oauth example."""
provider = request.match_info.get('provider') client, _ = await app.ps.oauth.login(provider, request) user, data = await client.user_info() response = ( "<a href='/'>back</a><br/><br/>" "<ul>" "<li>ID: {u.id}</li>" "<li>Username: {u.username}</li>" "<li>First, last name: {u.first_name}, {u.last_name}</li>" "<li>Email: {u.email}</li>" "<li>Link: {u.link}</li>" "<li>Picture: {u.picture}</li>" "<li>Country, city: {u.country}, {u.city}</li>" "</ul>" ).format(u=user) response += "<code>%s</code>" % html.escape(repr(data)) 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 BeginOfEventAction(self, event): """Save event number"""
self.log.info("Simulating event %s", event.GetEventID()) self.sd.setEventNumber(event.GetEventID())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def EndOfEventAction(self, event): """At the end of an event, grab sensitive detector hits then run processor loop"""
self.log.debug('Processesing simulated event %d', event.GetEventID()) docs = self.sd.getDocs() self.sd.clearDocs() for processor in self.processors: docs = processor.process(docs) if not docs: self.log.warning('%s did not return documents in process()!', processor.__class__.__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 generate_handler(): """Create the Blockade user and give them permissions."""
logger.debug("[#] Setting up user, group and permissions") client = boto3.client("iam", region_name=PRIMARY_REGION) # Create the user try: response = client.create_user( UserName=BLOCKADE_USER ) except client.exceptions.EntityAlreadyExistsException: logger.debug("[!] Blockade user already exists") logger.info("[#] %s user successfully created" % (BLOCKADE_USER)) # Create the role try: logger.debug("[#] Creating %s role" % (BLOCKADE_ROLE)) response = client.create_role( RoleName=BLOCKADE_ROLE, AssumeRolePolicyDocument=BLOCKADE_ROLE_POLICY, Description="Allow a user to manage the administration of Blockade." ) except client.exceptions.EntityAlreadyExistsException: logger.debug("[!] Blockade role already exists") logger.info("[#] %s role successfully created" % (BLOCKADE_ROLE)) # Create the group try: logger.debug("[#] Creating %s group" % (BLOCKADE_GROUP)) response = client.create_group( GroupName=BLOCKADE_GROUP, ) except client.exceptions.EntityAlreadyExistsException: logger.debug("[!] Blockade group already exists") logger.info("[#] %s group successfully created" % (BLOCKADE_GROUP)) # Generate all policy items logger.debug("[#] Creating Blockade IAM policies") for label in BLOCKADE_POLICIES: logger.debug("[#] Creating %s policy" % (label)) try: response = client.create_policy( PolicyName=label, PolicyDocument=POLICIES[label], Description="Generated policy from Blockade bootstrap tool" ) except client.exceptions.EntityAlreadyExistsException: logger.debug("[!] Blockade policy %s already exists" % (label)) logger.info("[#] Blockade %s policy successfully created" % (label)) logger.info("[#] Blockade policies successfully created") # Attach policies to all entity types iam = boto3.resource('iam') account_id = iam.CurrentUser().arn.split(':')[4] for label in BLOCKADE_POLICIES + ['PushToCloud', 'APIGatewayAdmin']: logger.debug("[#] Attaching %s policy" % (label)) arn = 'arn:aws:iam::{id}:policy/{policy}'.format(id=account_id, policy=label) if label == 'PushToCloud': arn = "arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs" if label == 'APIGatewayAdmin': arn = "arn:aws:iam::aws:policy/AmazonAPIGatewayAdministrator" client.attach_role_policy(RoleName=BLOCKADE_ROLE, PolicyArn=arn) client.attach_group_policy(GroupName=BLOCKADE_GROUP, PolicyArn=arn) logger.info("[#] Blockade policies successfully attached") logger.debug("[#] Adding %s to %s group" % (BLOCKADE_USER, BLOCKADE_GROUP)) response = client.add_user_to_group( GroupName=BLOCKADE_GROUP, UserName=BLOCKADE_USER ) logger.info("[#] %s user is part of %s group" % (BLOCKADE_USER, BLOCKADE_GROUP)) 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 remove_handler(): """Remove the user, group and policies for Blockade."""
logger.debug("[#] Removing user, group and permissions for Blockade") client = boto3.client("iam", region_name=PRIMARY_REGION) iam = boto3.resource('iam') account_id = iam.CurrentUser().arn.split(':')[4] try: logger.debug("[#] Removing %s from %s group" % (BLOCKADE_USER, BLOCKADE_GROUP)) response = client.remove_user_from_group( GroupName=BLOCKADE_GROUP, UserName=BLOCKADE_USER ) except client.exceptions.NoSuchEntityException: logger.debug("[!] Blockade user already removed from group") for label in BLOCKADE_POLICIES + ['PushToCloud', 'APIGatewayAdmin']: logger.debug("[#] Removing %s policy" % (label)) arn = 'arn:aws:iam::{id}:policy/{policy}'.format(id=account_id, policy=label) if label == 'PushToCloud': arn = "arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs" if label == 'APIGatewayAdmin': arn = "arn:aws:iam::aws:policy/AmazonAPIGatewayAdministrator" try: response = client.detach_group_policy( GroupName=BLOCKADE_GROUP, PolicyArn=arn) except: pass try: response = client.detach_role_policy( RoleName=BLOCKADE_ROLE, PolicyArn=arn) except: pass try: response = client.delete_policy(PolicyArn=arn) except Exception as e: print(e) pass logger.debug("[#] Removed all policies") try: logger.debug("[#] Deleting %s user" % (BLOCKADE_USER)) response = client.delete_user( UserName=BLOCKADE_USER ) except client.exceptions.NoSuchEntityException: logger.debug("[!] %s user already deleted" % (BLOCKADE_USER)) try: logger.debug("[#] Removing %s group" % (BLOCKADE_GROUP)) response = client.delete_group(GroupName=BLOCKADE_GROUP) except: logger.debug("[!] Group already removed") try: logger.debug("[#] Removing %s role" % (BLOCKADE_ROLE)) response = client.delete_role(RoleName=BLOCKADE_ROLE) except: logger.debug("[!] Role already removed") 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 generate_s3_bucket(): """Create the blockade bucket if not already there."""
logger.debug("[#] Setting up S3 bucket") client = boto3.client("s3", region_name=PRIMARY_REGION) buckets = client.list_buckets() matches = [x for x in buckets.get('Buckets', list()) if x['Name'].startswith(S3_BUCKET)] if len(matches) > 0: logger.debug("[*] Bucket already exists") return matches.pop() response = client.create_bucket( Bucket=S3_BUCKET, CreateBucketConfiguration={ 'LocationConstraint': PRIMARY_REGION } ) logger.info("[#] Successfully setup the S3 bucket") 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 remove_s3_bucket(): """Remove the Blockade bucket."""
logger.debug("[#] Removing S3 bucket") client = boto3.client("s3", region_name=PRIMARY_REGION) buckets = client.list_buckets() matches = [x for x in buckets.get('Buckets', list()) if x['Name'].startswith(S3_BUCKET_NAME)] if len(matches) == 0: return match = matches.pop()['Name'] try: response = client.list_objects_v2( Bucket=match, ) except client.exceptions.NoSuchBucket: logger.info("[!] S3 bucket already deleted") return True while response['KeyCount'] > 0: logger.debug('[*] Deleting %d objects from bucket %s' % (len(response['Contents']), match)) response = client.delete_objects( Bucket=match, Delete={ 'Objects': [{'Key': obj['Key']} for obj in response['Contents']] } ) response = client.list_objects_v2( Bucket=match, ) logger.debug('[#] Deleting bucket %s' % match) response = client.delete_bucket( Bucket=match ) logger.info("[#] Successfully deleted the S3 bucket") 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 generate_dynamodb_tables(): """Create the Blockade DynamoDB tables."""
logger.debug("[#] Setting up DynamoDB tables") client = boto3.client('dynamodb', region_name=PRIMARY_REGION) existing_tables = client.list_tables()['TableNames'] responses = list() for label in DYNAMODB_TABLES: if label in existing_tables: logger.debug("[*] Table %s already exists" % (label)) continue kwargs = { 'TableName': label, 'ProvisionedThroughput': { 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5 } } kwargs.update(DYNAMODB_SCHEMAS[label]) response = client.create_table(**kwargs) responses.append(response) logger.debug("[#] Successfully setup DynamoDB table %s" % (label)) logger.info("[#] Successfully setup DynamoDB tables") return responses
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_dynamodb_tables(): """Remove the Blockade DynamoDB tables."""
logger.debug("[#] Removing DynamoDB tables") client = boto3.client('dynamodb', region_name=PRIMARY_REGION) responses = list() for label in DYNAMODB_TABLES: logger.debug("[*] Removing %s table" % (label)) try: response = client.delete_table( TableName=label ) except client.exceptions.ResourceNotFoundException: logger.info("[!] Table %s already removed" % (label)) continue responses.append(response) logger.debug("[*] Removed %s table" % (label)) logger.info("[#] Successfully removed DynamoDB tables") return responses
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_lambda_functions(): """Create the Blockade lambda functions."""
logger.debug("[#] Setting up the Lambda functions") aws_lambda = boto3.client('lambda', region_name=PRIMARY_REGION) functions = aws_lambda.list_functions().get('Functions') existing_funcs = [x['FunctionName'] for x in functions] iam = boto3.resource('iam') account_id = iam.CurrentUser().arn.split(':')[4] responses = list() for label in LAMBDA_FUNCTIONS: if label in existing_funcs: logger.debug("[*] Lambda function %s already exists" % (label)) continue dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path = dir_path.replace('/cli', '/aws') kwargs = { 'Runtime': 'python2.7', 'Role': 'arn:aws:iam::{0}:role/{1}'.format(account_id, BLOCKADE_ROLE), 'Timeout': 3, 'MemorySize': 128, 'Publish': True, 'Code': { 'ZipFile': open("{0}/lambda-zips/{1}.zip".format(dir_path, label), 'rb').read() } } kwargs.update(LAMBDA_SCHEMA[label]) logger.debug("[#] Setting up the %s Lambda function" % (label)) response = aws_lambda.create_function(**kwargs) responses.append(response) logger.debug("[#] Successfully setup Lambda function %s" % (label)) logger.info("[#] Successfully setup Lambda functions") return responses
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_lambda_functions(): """Remove the Blockade Lambda functions."""
logger.debug("[#] Removing the Lambda functions") client = boto3.client('lambda', region_name=PRIMARY_REGION) responses = list() for label in LAMBDA_FUNCTIONS: try: response = client.delete_function( FunctionName=label, ) except client.exceptions.ResourceNotFoundException: logger.info("[!] Function %s already removed" % (label)) continue responses.append(response) logger.debug("[*] Removed %s function" % (label)) logger.info("[#] Successfully removed Lambda functions") return responses
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_api_gateway(): """Create the Blockade API Gateway REST service."""
logger.debug("[#] Setting up the API Gateway") client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] if len(matches) > 0: logger.debug("[#] API Gateway already setup") return matches.pop() response = client.create_rest_api( name=API_GATEWAY, description='REST-API to power the Blockade service' ) logger.info("[#] Successfully setup the API Gateway") 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 generate_admin_resource(): """Create the Blockade admin resource for the REST services."""
logger.debug("[#] Setting up the admin resource") client = boto3.client('apigateway', region_name=PRIMARY_REGION) existing = get_api_gateway_resource("admin") if existing: logger.debug("[#] API admin resource already created") return True matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] match = matches.pop() resource_id = get_api_gateway_resource('/') response = client.create_resource( restApiId=match.get('id'), parentId=resource_id, pathPart='admin' ) logger.info("[#] Successfully setup the admin resource") 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 get_api_gateway_resource(name): """Get the resource associated with our gateway."""
client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] match = matches.pop() resources = client.get_resources(restApiId=match.get('id')) resource_id = None for item in resources.get('items', list()): if item.get('pathPart', '/') != name: continue resource_id = item['id'] return resource_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_api_gateway(): """Remove the Blockade REST API service."""
logger.debug("[#] Removing API Gateway") client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] if len(matches) == 0: logger.info("[!] API Gateway already removed") return True match = matches.pop() response = client.delete_rest_api( restApiId=match.get('id') ) logger.info("[#] Removed API Gateway") 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 method_delegate(**methods): """ Construct a renderer that delegates based on the request's HTTP method. """
methods = {k.upper(): v for k, v in iteritems(methods)} if PY3: methods = {k.encode("utf-8"): v for k, v in iteritems(methods)} def render(request): renderer = methods.get(request.method) if renderer is None: return Response(code=405) return renderer(request) return render
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def traverse(path, request, resource): """ Traverse a root resource, retrieving the appropriate child for the request. """
path = path.lstrip(b"/") for component in path and path.split(b"/"): if getattr(resource, "is_leaf", False): break resource = resource.get_child(name=component, request=request) return resource
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def escape_shell_arg(shell_arg): """Escape shell argument shell_arg by placing it within single-quotes. Any single quotes found within the shell argument string will be escaped. @param shell_arg: The shell argument to be escaped. @type shell_arg: string @return: The single-quote-escaped value of the shell argument. @rtype: string @raise TypeError: if shell_arg is not a string. @see: U{http://mail.python.org/pipermail/python-list/2005-October/346957.html} """
if isinstance(shell_arg, six.text_type): msg = "ERROR: escape_shell_arg() expected string argument but " \ "got '%s' of type '%s'." % (repr(shell_arg), type(shell_arg)) raise TypeError(msg) return "'%s'" % shell_arg.replace("'", r"'\''")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retry_mkstemp(suffix='', prefix='tmp', directory=None, max_retries=3): """ Make mkstemp more robust against AFS glitches. """
if directory is None: directory = current_app.config['CFG_TMPSHAREDDIR'] for retry_count in range(1, max_retries + 1): try: tmp_file_fd, tmp_file_name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=directory) except OSError as e: if e.errno == 19 and retry_count <= max_retries: # AFS Glitch? time.sleep(10) else: raise else: break return tmp_file_fd, tmp_file_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 declarative_fields(cls_filter, meta_base=type, extra_attr_name='base_fields'): """ Metaclass that converts Field attributes to a dictionary called 'base_fields', taking into account parent class 'cls_filter'. """
def __new__(cls, name, bases, attrs): attrs[extra_attr_name] = fields = get_declared_fields(bases, attrs, cls_filter, extra_attr_name=extra_attr_name) attrs[extra_attr_name + '_names'] = set(fields.keys()) new_class = meta_base.__new__(cls, name, bases, attrs) return new_class return type('', (meta_base,), {'__new__': __new__})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def started(generator_function): """ starts a generator when created """
@wraps(generator_function) def wrapper(*args, **kwargs): g = generator_function(*args, **kwargs) next(g) return g 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 add_log_error(self, x, flag_also_show=False, E=None): """Sets text of labelError."""
if len(x) == 0: x = "(empty error)" tb.print_stack() x_ = x if E is not None: a99.get_python_logger().exception(x_) else: a99.get_python_logger().info("ERROR: {}".format(x_)) x = '<span style="color: {0!s}">{1!s}</span>'.format(a99.COLOR_ERROR, x) self._add_log_no_logger(x, False) if flag_also_show: a99.show_error(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 check_user(user, password): """check the auth for user and password."""
return ((user == attowiki.user or attowiki.user is None) and (password == attowiki.password or attowiki.password is 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 view_meta_index(): """List all the available .rst files in the directory. view_meta_index is called by the 'meta' url : /__index__ """
rst_files = [filename[2:-4] for filename in sorted(glob.glob("./*.rst"))] rst_files.reverse() return template('index', type="view", filelist=rst_files, name="__index__", extended_name=None, history=[], gitref=None, is_repo=check_repo())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view_cancel_edit(name=None): """Cancel the edition of an existing page. Then render the last modification status .. note:: this is a bottle view if no page name is given, do nothing (it may leave some .tmp. files in the directory). Keyword Arguments: :name: (str) -- name of the page (OPTIONAL) Returns: bottle response object """
if name is None: return redirect('/') else: files = glob.glob("{0}.rst".format(name)) if len(files) > 0: reset_to_last_commit() return redirect('/' + name) else: return abort(404)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view_edit(name=None): """Edit or creates a new page. .. note:: this is a bottle view if no page name is given, creates a new page. Keyword Arguments: :name: (str) -- name of the page (OPTIONAL) Returns: bottle response object """
response.set_header('Cache-control', 'no-cache') response.set_header('Pragma', 'no-cache') if name is None: # new page return template('edit', type="edit", name=name, extended_name=None, is_repo=check_repo(), history=[], gitref=None, today=datetime.datetime.now().strftime("%Y%m%d"), content="") else: files = glob.glob("{0}.rst".format(name)) if len(files) > 0: file_handle = open(files[0], 'r') return template('edit', type="edit", name=name, extended_name=None, is_repo=check_repo(), history=[], gitref=None, today=datetime.datetime.now().strftime("%Y%m%d"), content=file_handle.read()) else: return abort(404)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view_pdf(name=None): """Render a pdf file based on the given page. .. note:: this is a bottle view Keyword Arguments: :name: (str) -- name of the rest file (without the .rst extension) MANDATORY """
if name is None: return view_meta_index() files = glob.glob("{0}.rst".format(name)) if len(files) > 0: file_handle = open(files[0], 'r') dest_filename = name + '.pdf' doctree = publish_doctree(file_handle.read()) try: produce_pdf(doctree_content=doctree, filename=dest_filename) except: raise else: return static_file(dest_filename, root='', download=True) else: return abort(404)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view_page(name=None): """Serve a page name. .. note:: this is a bottle view * if the view is called with the POST method, write the new page content to the file, commit the modification and then display the html rendering of the restructured text file * if the view is called with the GET method, directly display the html rendering of the restructured text file Keyword Arguments: :name: (str) -- name of the rest file (without the .rst extension) OPTIONAL if no filename is given, first try to find a "index.rst" file in the directory and serve it. If not found, serve the meta page __index__ Returns: bottle response object """
if request.method == 'POST': if name is None: # new file if len(request.forms.filename) > 0: name = request.forms.filename if name is not None: filename = "{0}.rst".format(name) file_handle = open(filename, 'w') file_handle.write(request.forms.content.encode('utf-8')) file_handle.close() add_file_to_repo(filename) commit(filename) response.set_header('Cache-control', 'no-cache') response.set_header('Pragma', 'no-cache') if name is None: # we try to find an index file index_files = glob.glob("./[Ii][Nn][Dd][Ee][Xx].rst") if len(index_files) == 0: # not found # redirect to __index__ return view_meta_index() else: name = index_files[0][2:-4] files = glob.glob("{0}.rst".format(name)) if len(files) > 0: file_handle = open(files[0], 'r') html_body = publish_parts(file_handle.read(), writer=AttowikiWriter(), settings=None, settings_overrides=None)['html_body'] history = commit_history("{0}.rst".format(name)) return template('page', type="view", name=name, extended_name=None, is_repo=check_repo(), history=history, gitref=None, content=html_body) else: return static_file(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 view_quick_save_page(name=None): """Quick save a page. .. note:: this is a bottle view * this view must be called with the PUT method write the new page content to the file, and not not commit or redirect Keyword Arguments: :name: (str) -- name of the rest file (without the .rst extension) Returns: bottle response object (200 OK) """
response.set_header('Cache-control', 'no-cache') response.set_header('Pragma', 'no-cache') if request.method == 'PUT': if name is None: # new file if len(request.forms.filename) > 0: name = request.forms.filename if name is not None: filename = "{0}.rst".format(name) file_handle = open(filename, 'w') content = request.body.read() content = content.decode('utf-8') file_handle.write(content.encode('utf-8')) file_handle.close() return "OK" else: return abort(404)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getHelp(arg=None): """ This function provides interactive manuals and tutorials. """
if arg==None: print('--------------------------------------------------------------') print('Hello, this is an interactive help system of HITRANonline API.') print('--------------------------------------------------------------') print('Run getHelp(.) with one of the following arguments:') print(' tutorial - interactive tutorials on HAPI') print(' units - units used in calculations') print(' index - index of available HAPI functions') elif arg=='tutorial': print('-----------------------------------') print('This is a tutorial section of help.') print('-----------------------------------') print('Please choose the subject of tutorial:') print(' data - downloading the data and working with it') print(' spectra - calculating spectral functions') print(' plotting - visualizing data with matplotlib') print(' python - Python quick start guide') elif arg=='python': print_python_tutorial() elif arg=='data': print_data_tutorial() elif arg=='spectra': print_spectra_tutorial() elif arg=='plotting': print_plotting_tutorial() elif arg=='index': print('------------------------------') print('FETCHING DATA:') print('------------------------------') print(' fetch') print(' fetch_by_ids') print('') print('------------------------------') print('WORKING WITH DATA:') print('------------------------------') print(' db_begin') print(' db_commit') print(' tableList') print(' describe') print(' select') print(' sort') print(' extractColumns') print(' getColumn') print(' getColumns') print(' dropTable') print('') print('------------------------------') print('CALCULATING SPECTRA:') print('------------------------------') print(' profiles') print(' partitionSum') print(' absorptionCoefficient_HT') print(' absorptionCoefficient_Voigt') print(' absorptionCoefficient_SDVoigt') print(' absorptionCoefficient_Lorentz') print(' absorptionCoefficient_Doppler') print(' transmittanceSpectrum') print(' absorptionSpectrum') print(' radianceSpectrum') print('') print('------------------------------') print('CONVOLVING SPECTRA:') print('------------------------------') print(' convolveSpectrum') print(' slit_functions') print('') print('------------------------------') print('INFO ON ISOTOPOLOGUES:') print('------------------------------') print(' ISO_ID') print(' abundance') print(' molecularMass') print(' moleculeName') print(' isotopologueName') print('') print('------------------------------') print('MISCELLANEOUS:') print('------------------------------') print(' getStickXY') print(' read_hotw') elif arg == ISO: print_iso() elif arg == ISO_ID: print_iso_id() elif arg == profiles: print_profiles() elif arg == slit_functions: print_slit_functions() else: help(arg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convolveSpectrumSame(Omega,CrossSection,Resolution=0.1,AF_wing=10., SlitFunction=SLIT_RECTANGULAR): """ Convolves cross section with a slit function with given parameters. """
step = Omega[1]-Omega[0] x = arange(-AF_wing,AF_wing+step,step) slit = SlitFunction(x,Resolution) print('step=') print(step) print('x=') print(x) print('slitfunc=') print(SlitFunction) CrossSectionLowRes = convolve(CrossSection,slit,mode='same')*step return Omega,CrossSectionLowRes,None,None,slit
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_db(self, couch, dbname): """Setup and configure DB """
# Avoid race condition of two creating db my_db = None self.log.debug('Setting up DB: %s' % dbname) if dbname not in couch: self.log.info("DB doesn't exist so creating DB: %s", dbname) try: my_db = couch.create(dbname) except: self.log.critical("Race condition caught") raise RuntimeError("Race condition caught when creating DB") try: auth_doc = {} auth_doc['_id'] = '_design/auth' auth_doc['language'] = 'javascript' auth_doc['validate_doc_update'] = """ function(newDoc, oldDoc, userCtx) { if (userCtx.roles.indexOf('_admin') !== -1) { return; } else { throw({forbidden: 'Only admins may edit the database'}); } } """ my_db.save(auth_doc) except: self.log.error('Could not set permissions of %s' % dbname) else: my_db = couch[dbname] return my_db
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit(self, force=False): """Commit data to couchdb Compared to threshold (unless forced) then sends data to couch """
self.log.debug('Bulk commit requested') size = sys.getsizeof(self.docs) self.log.debug('Size of docs in KB: %d', size) if size > self.commit_threshold or force: self.log.info('Commiting %d KB to CouchDB' % size) self.my_db.update(self.docs) self.docs = []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, doc): """Save a doc to cache """
self.log.debug('save()') self.docs.append(doc) self.commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(address, channel, key, loop=None): """Starts a new Interactive client. Takes the remote address of the Tetris robot, as well as the channel number and auth key to use. Additionally, it takes a list of handler. This should be a dict of protobuf wire IDs to handler functions (from the .proto package). """
if loop is None: loop = asyncio.get_event_loop() socket = yield from websockets.connect(address+"/robot", loop=loop) conn = Connection(socket, loop) yield from conn.send(_create_handshake(channel, key)) return conn
<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_handshake(channel, key): """ Creates and returns a Handshake packet that authenticates on the channel with the given stream key. """
hsk = Handshake() hsk.channel = channel hsk.streamKey = key return hsk
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shell_source(script): """Sometime you want to emulate the action of "source" in bash, settings some environment variables. Here is a way to do it."""
pipe = subprocess.Popen( ". %s; env" % script, stdout=subprocess.PIPE, shell=True) output = pipe.communicate()[0].decode() env = {} for line in output.splitlines(): try: keyval = line.split("=", 1) env[keyval[0]] = keyval[1] except: pass os.environ.update(env)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nll(data, model): """ Negative log likelihood given data and a model Parameters {0} {1} Returns ------- float Negative log likelihood Examples --------- 237.6871819262054 235.2841347820297 """
try: log_lik_vals = model.logpmf(data) except: log_lik_vals = model.logpdf(data) return -np.sum(log_lik_vals)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lrt(data, model_full, model_reduced, df=None): """ Compare two nested models using a likelihood ratio test Parameters {0} model_full : obj A frozen scipy distribution object representing the full model (more complex model). model_reduced : scipy distribution object A frozen scipy distribution object representing the reduced model (simpler model). df : int The degrees of freedom for the lrt (optional). If none, df is calculated as the difference between the number of parameters in the full and reduced models. Returns ------- tuple G^2 statistic, p-value Notes ----- Parameters of distribution objects must be given as keyword arguments. Ex. ``norm = stats.norm(loc=0, scale=1)`` A p-value < alpha suggests significant evidence for the full (more complex) model. In other words, the null hypothesis is that the reduced model is correct The LRT only applies to nested models. The G^2 statistic and G-test rely on the assumption that the test statistic is approximately chi-squared distributed. This assumption breaks down for small samples sizes. Examples -------- (15.33429080890221, 9.0066719644695982e-05) """
# Calculate G^2 statistic ll_full = nll(data, model_full) * -1 ll_reduced = nll(data, model_reduced) * -1 test_stat = 2 * (ll_full - ll_reduced) # Set df if necessary if not df: df = ( len(model_full.args) + len(model_full.kwds) - len(model_reduced.args) - len(model_reduced.kwds) ) return test_stat, stats.chisqprob(test_stat, 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 AIC(data, model, params=None, corrected=True): """ Akaike Information Criteria given data and a model Parameters {0} {1} params : int Number of parameters in the model. If None, calculated from model object. corrected : bool If True, calculates the small-sample size correct AICC. Default True. Returns ------- float AIC(C) value Notes ----- AICC should be used when the number of observations is < 40. Examples -------- 765.51518598676421 777.05165086534805 765.51518598676421 765.39147464655798 References .. [#] Burnham, K and Anderson, D. (2002) Model Selection and Multimodel Inference: A Practical and Information-Theoretic Approach (p. 66). New York City, USA: Springer. """
n = len(data) # Number of observations L = nll(data, model) if not params: k = len(model.kwds) + len(model.args) else: k = params if corrected: aic_value = 2 * k + 2 * L + (2 * k * (k + 1)) / (n - k - 1) else: aic_value = 2 * k + 2 * L return aic_value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AIC_compare(aic_list): """ Calculates delta AIC and AIC weights from a list of AIC values Parameters aic_list : iterable AIC values from set of candidat models Returns tuple First element contains the delta AIC values, second element contains the relative AIC weights. Notes ----- AIC weights can be interpreted as the probability that a given model is the best model in the set. Examples -------- (array([ 0. , 19.11806518]), array([ 9.99929444e-01, 7.05560486e-05])) """
aic_values = np.array(aic_list) minimum = np.min(aic_values) delta = aic_values - minimum values = np.exp(-delta / 2) weights = values / np.sum(values) return delta, weights
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sum_of_squares(obs, pred): """ Sum of squares between observed and predicted data Parameters obs : iterable Observed data pred : iterable Predicted data Returns ------- float Sum of squares Notes ----- The length of observed and predicted data must match. """
return np.sum((np.array(obs) - np.array(pred)) ** 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def r_squared(obs, pred, one_to_one=False, log_trans=False): """ R^2 value for a regression of observed and predicted data Parameters obs : iterable Observed data pred : iterable Predicted data one_to_one : bool If True, calculates the R^2 based on the one-to-one line (see [#]_), and if False, calculates the standard R^2 based on a linear regression. Default False. log_trans : bool If True, log transforms obs and pred before R^2 calculation. Returns ------- float R^2 value Notes ----- Using the traditional R^2 to compare the fit of observed and predicted values may be misleading as the relationship may not be one-to-one but the R^2 value may be quite high. The one-to-one option alleviates this problem. Note that with the one-to-one option R^2 can be negative. Examples -------- 0.99336568326291697 -6.8621799432144988 0.97651897660174425 0.97591430200514639 References .. [#] White, E., Thibault, K., & Xiao, X. (2012). Characterizing the species abundance distributions across taxa and ecosystems using a simple maximum entropy model. Ecology, 93(8), 1772-8 """
if log_trans: obs = np.log(obs) pred = np.log(pred) if one_to_one: r_sq = 1 - (sum_of_squares(obs, pred) / sum_of_squares(obs, np.mean(obs))) else: b0, b1, r, p_value, se = stats.linregress(obs, pred) r_sq = r ** 2 return r_sq
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def preston_bin(data, max_num): """ Bins data on base 2 using Preston's method Parameters data : array-like Data to be binned max_num : float The maximum upper value of the data Returns ------- tuple (binned_data, bin_edges) Notes ----- Uses Preston's method of binning, which has exclusive lower boundaries and inclusive upper boundaries. Densities are not split between bins. Examples -------- (array([4, 0, 1, 3, 1, 0, 2]), array([ 1., 2., 3., 5., 9., 17., 33., 65.])) References .. [#] Preston, F. (1962). The canonical distribution of commonness and rarity. Ecology, 43, 185-215 """
log_ub = np.ceil(np.log2(max_num)) # Make an exclusive lower bound in keeping with Preston if log_ub == 0: boundaries = np.array([0, 1]) elif log_ub == 1: boundaries = np.arange(1, 4) else: boundaries = 2 ** np.arange(0, log_ub + 1) boundaries = np.insert(boundaries, 2, 3) boundaries[3:] = boundaries[3:] + 1 hist_data = np.histogram(data, bins=boundaries) return hist_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url_to_parts(url): """ Split url urlsplit style, but return path as a list and query as a dict """
if not url: return None scheme, netloc, path, query, fragment = _urlsplit(url) if not path or path == '/': path = [] else: path = path.strip('/').split('/') if not query: query = {} else: query = _parse_qs(query) return _urllib_parse.SplitResult(scheme, netloc, path, query, fragment)