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 "delay...
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_p...
<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 fi...
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 ...
<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 ...
<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.__c...
<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, ...
<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 Non...
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...
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: ...
<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.contro...
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 808...
<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 = ...
<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...
<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 = re...
<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_par...
<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__, att...
<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....
<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: th...
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...
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: outp...
<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...
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...
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.endswit...
<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, allowe...
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_whi...
<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) 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 _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...
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 l...
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') toke...
<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 t...
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, '-...
<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 :return...
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_i...
<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/w...
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*co...
<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#Alternati...
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 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 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...
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 c...
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 =...
<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 ti...
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(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 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.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 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.regi...
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")...
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._handle...
<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. wher...
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>` ...
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 th...
<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, la...
<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 pro...
<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...
<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)) ...
<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 exis...
<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()[...
<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 exi...
<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 ...
<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.sp...
<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...
<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") ...
<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()...
<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 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 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") 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 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) ...
<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 ...
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, ...
<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_fiel...
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...
<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>'...
<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=[], ...
<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 n...
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: ...
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=...
<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 (...
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,...
<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 f...
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_handl...
<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 cont...
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: 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 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 argum...
<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 giv...
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,CrossSectio...
<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: ...
<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 ...
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 ...
<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....
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 dis...
# 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_red...
<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...
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 mode...
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 Retu...
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 dat...
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 v...
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(boundarie...
<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(...