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 _update_response_location_header(self, resource): """ Adds a new or replaces an existing Location header to the response headers pointing to the URL of the g...
location = resource_to_url(resource, request=self.request) loc_hdr = ('Location', location) hdr_names = [hdr[0].upper() for hdr in self.request.response.headerlist] try: idx = hdr_names.index('LOCATION') except ValueError: self.request.response.headerlist...
<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_request_representer(self): """ Returns a representer for the content type specified in the request. :raises HTTPUnsupportedMediaType: If the specified c...
try: mime_type = \ get_registered_mime_type_for_string(self.request.content_type) except KeyError: # The client sent a content type we do not support (415). raise HTTPUnsupportedMediaType() return as_representer(self.context, mime_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_request_data(self): """ Extracts the data from the representation submitted in the request body and returns it. This default implementation uses a r...
rpr = self._get_request_representer() return rpr.data_from_bytes(self.request.body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_conflict(self, name): """ Handles requests that triggered a conflict. Respond with a 409 "Conflict" """
err = HTTPConflict('Member "%s" already exists!' % name).exception return self.request.get_response(err)
<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(self): """ Implements user message checking for views. Checks if the current request has an explicit "ignore-message" parameter (a GUID) pointing to a ...
request = get_current_request() ignore_guid = request.params.get('ignore-message') coll = request.root['_messages'] vote = False if ignore_guid: ignore_mb = coll.get(ignore_guid) if not ignore_mb is None and ignore_mb.text == self.message.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_307_response(self): """ Creates a 307 "Temporary Redirect" response including a HTTP Warning header with code 299 that contains the user message recei...
request = get_current_request() msg_mb = UserMessageMember(self.message) coll = request.root['_messages'] coll.add(msg_mb) # Figure out the new location URL. qs = self.__get_new_query_string(request.query_string, self.message.slug...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mkdir(*args): """Create a directory specified by a sequence of subdirectories '/tmp/foo/bar/baz' True """
path = '' for chunk in args: path = os.path.join(path, chunk) if not os.path.isdir(path): os.mkdir(path) return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shell(cmd, *args, **kwargs): # type: (Union[str, unicode], *Union[str, unicode], **Any) ->Tuple[int, str] """ Execute shell command and return output Args: c...
if kwargs.get('rel_path') and not cmd.startswith("/"): cmd = os.path.join(kwargs['rel_path'], cmd) status = 0 try: output = subprocess.check_output( (cmd,) + args, stderr=kwargs.get('stderr')) except subprocess.CalledProcessError as e: if kwargs.get('raise_on_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 listen_for_events(): """Pubsub event listener Listen for events in the pubsub bus and calls the process function when somebody comes to play. """
import_event_modules() conn = redis_connection.get_connection() pubsub = conn.pubsub() pubsub.subscribe("eventlib") for message in pubsub.listen(): if message['type'] != 'message': continue data = loads(message["data"]) if 'name' in data: event_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 sendrequest(self, request): ''' Recieves a request xml as a string and posts it to the health service url specified in the settings.py ''' url = urlparse.urlparse(self.connection.healthserviceurl) conn = None if url.scheme == 'https': ...
<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, unit_of_work): """ Dump all resources that were modified by the given session back into the repository. """
MemoryRepository.commit(self, unit_of_work) if self.is_initialized: entity_classes_to_dump = set() for state in unit_of_work.iterator(): entity_classes_to_dump.add(type(state.entity)) for entity_cls in entity_classes_to_dump: self.__du...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_pdf_file(self): """Validate that the pdf_path configuration is set and the referenced file exists. Exits the program with status 1 if validation fa...
if self['pdf_path'] is None: self._logger.error('--pdf argument must be set') sys.exit(1) if not os.path.exists(self['pdf_path']): self._logger.error('Cannot find PDF ' + self['pdf_path']) sys.exit(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_docushare_url(handle, validate=True): """Get a docushare URL given document's handle. Parameters handle : `str` Handle name, such as ``'LDM-151'``. vali...
logger = structlog.get_logger(__name__) logger.debug('Using Configuration._get_docushare_url') # Make a short link to the DocuShare version page since # a) It doesn't immediately trigger a PDF download, # b) It gives the user extra information about the document before ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_defaults(self): """Create a `dict` of default configurations."""
defaults = { 'build_dir': None, 'build_datetime': datetime.datetime.now(dateutil.tz.tzutc()), 'pdf_path': None, 'extra_downloads': list(), 'environment': None, 'lsstdoc_tex_path': None, 'title': None, 'title_plain':...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_permissions_from_tuples(model, codename_tpls): """Creates custom permissions on model "model". """
if codename_tpls: model_cls = django_apps.get_model(model) content_type = ContentType.objects.get_for_model(model_cls) for codename_tpl in codename_tpls: app_label, codename, name = get_from_codename_tuple( codename_tpl, model_cls._meta.app_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 remove_historical_group_permissions(group=None, allowed_permissions=None): """Removes group permissions for historical models except those whose prefix is in...
allowed_permissions = allowed_permissions or ["view"] for action in allowed_permissions: for permission in group.permissions.filter( codename__contains="historical" ).exclude(codename__startswith=action): group.permissions.remove(permission)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def traversal(root): '''Tree traversal function that generates nodes. For each subtree, the deepest node is evaluated first. Then, the next-deepest nodes are evaluated until all the nodes in the subtree are generated.''' stack = [root] while len(stack) > 0: node = stack.pop() if ha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def firstPass(ASTs,verbose): '''Return a dictionary of function definition nodes, a dictionary of imported object names and a dictionary of imported module names. All three dictionaries use source file paths as keys.''' fdefs=dict() cdefs=dict() imp_obj_strs=dict() imp_mods=dict() for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def formatBodyNode(root,path): '''Format the root node for use as the body node.''' body = root body.name = "body" body.weight = calcFnWeight(body) body.path = path body.pclass = None return body
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def formatFunctionNode(node,path,stack): '''Add some helpful attributes to node.''' #node.name is already defined by AST module node.weight = calcFnWeight(node) node.path = path node.pclass = getCurrentClass(stack) return node
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getSourceFnDef(stack,fdefs,path): '''VERY VERY SLOW''' found = False for x in stack: if isinstance(x, ast.FunctionDef): for y in fdefs[path]: if ast.dump(x)==ast.dump(y): #probably causing the slowness found = True return y ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_database(mongo_uri, database_name): """ Delete a mongo database using pymongo. Mongo daemon assumed to be running. Inputs: - mongo_uri: A MongoDB URI....
client = pymongo.MongoClient(mongo_uri) client.drop_database(database_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 delete_collection(mongo_uri, database_name, collection_name): """ Delete a mongo document collection using pymongo. Mongo daemon assumed to be running. Input...
client = pymongo.MongoClient(mongo_uri) db = client[database_name] db.drop_collection(collection_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 create_staging_collection(resource): """ Helper function to create a staging collection for the given registered resource. :param resource: registered resour...
ent_cls = get_entity_class(resource) coll_cls = get_collection_class(resource) agg = StagingAggregate(ent_cls) return coll_cls.create_from_aggregate(agg)
<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(self): """Run the parser over the entire sourestring and return the results."""
try: return self.parse_top_level() except PartpyError as ex: self.error = True print(ex.pretty_print())
<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_top_level(self): """The top level parser will do a loop where it looks for a single contact parse and then eats all whitespace until there is no more i...
contacts = [] while not self.eos: contact = self.parse_contact() # match a contact expression. if not contact: # There was no contact so end file. break # This would be a nice place to put other expressions. contacts.append(contact) # s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_contact(self): """Parse a top level contact expression, these consist of a name expression a special char and an email expression. The characters found...
self.parse_whitespace() name = self.parse_name() # parse a name expression and get the string. if not name: # No name was found so shout it out. raise PartpyError(self, 'Expecting a name') self.parse_whitespace() # allow name and email to be delimited by either 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_name(self): """This function uses string patterns to match a title cased name. This is done in a loop until there are no more names to match so as to b...
name = [] while True: # Match the current char until it doesnt match the given pattern: # first char must be an uppercase alpha and the rest must be lower # cased alphas. part = self.match_string_pattern(spat.alphau, spat.alphal) if part == ''...
<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_development_container_name(self): """ Returns the development container name """
if self.__prefix: return "{0}:{1}-{2}-dev".format( self.__repository, self.__prefix, self.__branch) else: return "{0}:{1}-dev".format( self.__repository, self.__branch)
<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_build_container_tag(self): """ Return the build container tag """
if self.__prefix: return "{0}-{1}-{2}".format( self.__prefix, self.__branch, self.__version) else: return "{0}-{1}".format( self.__branch, self.__version)
<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_branch_container_tag(self): """ Returns the branch container tag """
if self.__prefix: return "{0}-{1}".format( self.__prefix, self.__branch) else: return "{0}".format(self.__branch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def custom_server_error(request, template_name='500.html', admin_template_name='500A.html'): """ 500 error handler. Displays a full trackback for superusers and ...
trace = None if request.user.is_authenticated() and (request.user.is_staff or request.user.is_superuser): try: import traceback, sys trace = traceback.format_exception(*(sys.exc_info())) if not request.user.is_superuser and trace: trace = trace[-1:] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_n_jobs(s): """ This function parses a "math"-like string as a function of CPU count. It is useful for specifying the number of jobs. For example, on an...
n_jobs = None N = cpu_count() if isinstance(s, int): n_jobs = s elif isinstance(s, float): n_jobs = int(s) elif isinstance(s, str): m = re.match(r'(\d*(?:\.\d*)?)?(\s*\*?\s*n)?$', s.strip()) if m is None: raise ValueError('Unable to parse n_jobs="{}"'.format(s)) k = flo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_settings_from_source(self, source): """ Loads the relevant settings from the specified ``source``. :returns: a standard :func:`dict` containing the set...
if not source: pass elif source == 'env_settings_uri': for env_settings_uri_key in self.env_settings_uri_keys: env_settings_uri = self._search_environ(env_settings_uri_key) if env_settings_uri: logger.debug('Found {} in the 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 get(self, key, *, default=None, cast_func=None, case_sensitive=None, raise_exception=None, warn_missing=None, use_cache=True, additional_sources=[]): """ Get...
case_sensitive = self.case_sensitive if case_sensitive is None else case_sensitive raise_exception = self.raise_exception if raise_exception is None else raise_exception warn_missing = self.warn_missing if warn_missing is None else warn_missing if not case_sensitive: key = key.lower()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _in_list(self, original_list, item): """ Check that an item as contained in a list. :param original_list: The list. :type original_list: list(object) :param ...
# pylint: disable=no-self-use for item_list in original_list: if item is item_list: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sort_results(self, results): """ Order the results. :param results: The disordened results. :type results: array.bs4.element.Tag :return: The ordened result...
parents = [] groups = [] for result in results: if not self._in_list(parents, result.parent): parents.append(result.parent) groups.append([]) groups[len(groups) - 1].append(result) else: groups[parents.inde...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fix_data_select(self): """ Replace all hyphens of data attributes for 'aaaaa', to avoid error in search. """
elements = self.document.select('*') for element in elements: attributes = element.attrs.keys() data_attributes = list() for attribute in attributes: if bool(re.findall('^data-', attribute)): data_attributes.append({ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_activity(activity, grouped_activity=None, *args, **kwargs): """ Given an activity, will attempt to render the matching template snippet for that activ...
template_name = 'activity_monitor/includes/models/{0.app_label}_{0.model}.html'.format(activity.content_type) try: tmpl = loader.get_template(template_name) except template.TemplateDoesNotExist: return None # we know we have a template, so render it content_object = activity.content...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_activity_count(date=None): """ Simple filter to get activity count for a given day. Defaults to today. """
if not date: today = datetime.datetime.now() - datetime.timedelta(hours = 24) return Activity.objects.filter(timestamp__gte=today).count() return Activity.objects.filter(timestamp__gte=date).count()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __root_path(self): """ Just checks the root path if set """
if self.root_path is not None: if os.path.isdir(self.root_path): sys.path.append(self.root_path) return raise RuntimeError('EverNode requires a valid root path.' ' Directory: %s does not exist' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_metadata(self, output_path): """Build a JSON-LD dataset for LSST Projectmeta. Parameters output_path : `str` File path where the ``metadata.jsonld`` sh...
if self._config.lsstdoc is None: self._logger.info('No known LSST LaTeX source (--tex argument). ' 'Not writing a metadata.jsonld file.') return # Build a JSON-LD dataset for the report+source repository. product_data = ltdclient.get_produc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_site(self): """Upload a previously-built site to LSST the Docs."""
if not os.path.isdir(self._config['build_dir']): message = 'Site not built at {0}'.format(self._config['build_dir']) self._logger.error(message) raise RuntimeError(message) ltdclient.upload(self._config)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def libraries(): """return installed library names."""
ls = libraries_dir().dirs() ls = [str(x.name) for x in ls] ls.sort() return ls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lib_examples(lib): """return library examples. EXAMPLE1,EXAMPLE2,.. """
d = lib_examples_dir(lib) if not d.exists(): return [] ls = d.dirs() ls = [x.name for x in ls] ls.sort() return ls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_eval(source, *args, **kwargs): """ eval without import """
source = source.replace('import', '') # import is not allowed return eval(source, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersect(self, **kwargs): """ Intersect a Line or Point Collection and the Shoreline Returns the point of intersection along the coastline Should also retur...
ls = None if "linestring" in kwargs: ls = kwargs.pop('linestring') spoint = Point(ls.coords[0]) epoint = Point(ls.coords[-1]) elif "start_point" and "end_point" in kwargs: spoint = kwargs.get('start_point') epoint = kwargs.get('end_po...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __bounce(self, **kwargs): """ Bounce off of the shoreline. NOTE: This does not work, but left here for future implementation feature = Linestring of two poin...
start_point = kwargs.pop('start_point') hit_point = kwargs.pop('hit_point') end_point = kwargs.pop('end_point') feature = kwargs.pop('feature') distance = kwargs.pop('distance') angle = kwargs.pop('angle') # Figure out the angle of the shoreline here (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 __reverse(self, **kwargs): """ Reverse particle just off of the shore in the direction that it came in. Adds a slight random factor to the distance and angle...
start_point = kwargs.pop('start_point') hit_point = kwargs.pop('hit_point') distance = kwargs.pop('distance') azimuth = kwargs.pop('azimuth') reverse_azimuth = kwargs.pop('reverse_azimuth') reverse_distance = kwargs.get('reverse_distance', None) if reverse_distan...
<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_feature_type_info(self): """ Gets FeatureType as a python dict. Transforms feature_name info into python dict. """
caps = self.get_capabilities() if caps is None: return None el = caps.find('{http://www.opengis.net/wfs}FeatureTypeList') for e in el.findall('{http://www.opengis.net/wfs}FeatureType'): if e.find('{http://www.opengis.net/wfs}Name').text == self._feature_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 extract_edges_from_callable(fn): """ This takes args and kwargs provided, and returns the names of the strings assigned. If a string is not provided for a va...
def extractor(*args, **kwargs): """ Because I don't think this technique is common in python... Service constructors were defined as: lambda c: c('a') In this function: fn = lambda c: c('a') fn(anything) # Results in anything('a') Her...
<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_and_bind(self, string): u'''Parse and execute single line of a readline init file.''' try: log(u'parse_and_bind("%s")' % string) if string.startswith(u'#'): return if string.startswith(u'set'): m = re.compile(ur'set\s+([-a-zA-...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _bell(self): u'''ring the bell if requested.''' if self.bell_style == u'none': pass elif self.bell_style == u'visible': raise NotImplementedError(u"Bellstyle visible is not implemented yet.") elif self.bell_style == u'audible': self.console.bell() ...
<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_list_attributes(element1, element2, attributes): """ Copy a list of attributes of a element for other element. :param element1: The element that have att...
for attribute in attributes: if element1.has_attribute(attribute): element2.set_attribute( attribute, element1.get_attribute(attribute) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def increase_in_list(list_to_increase, string_to_increase): """ Increase a item in a HTML list. :param list_to_increase: The list. :type list_to_increase: str :p...
if (bool(list_to_increase)) and (bool(string_to_increase)): if CommonFunctions.in_list(list_to_increase, string_to_increase): return list_to_increase return list_to_increase + ' ' + string_to_increase elif bool(list_to_increase): return list_to_incre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def in_list(list_to_search, string_to_search): """ Verify if the list contains the item. :param list_to_search: The list. :type list_to_search: str :param string...
if (bool(list_to_search)) and (bool(string_to_search)): elements = re.split('[ \n\t\r]+', list_to_search) for element in elements: if element == string_to_search: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid_element(element): """ Check that the element can be manipulated by HaTeMiLe. :param element: The element :type element: hatemile.util.html.htmldomel...
if element.has_attribute(CommonFunctions.DATA_IGNORE): return False else: parent_element = element.get_parent_element() if parent_element is not None: tag_name = parent_element.get_tag_name() if (tag_name != 'BODY') and (tag_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 get_joke(): """Returns a joke from the WebKnox one liner API. Returns None if unable to retrieve a joke. """
page = requests.get("https://api.chucknorris.io/jokes/random") if page.status_code == 200: joke = json.loads(page.content.decode("UTF-8")) return joke["value"] return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def burnin(self, n): """Remove the earliest n ensemble members from the MCMC output"""
self.sediment_rate = self.sediment_rate[:, n:] self.headage = self.headage[n:] self.sediment_memory = self.sediment_memory[n:] self.objective = self.objective[n:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_current_time(loop): """Cache the current time, since it is needed at the end of every keep-alive request to update the request timeout time :param loo...
global current_time current_time = time() loop.call_later(1, partial(update_current_time, 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 options(self, parser, env=None): """ Adds command-line options for this plugin. """
if env is None: env = os.environ env_opt_name = 'NOSE_%s' % self.__dest_opt_name.upper() parser.add_option("--%s" % self.__opt_name, dest=self.__dest_opt_name, type="string", default=env.get(env_opt_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 configure(self, options, conf): """ Configures the plugin. """
super(EverestNosePlugin, self).configure(options, conf) opt_val = getattr(options, self.__dest_opt_name, None) if opt_val: self.enabled = True EverestIni.ini_file_path = opt_val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, ami, count, config=None): """Create an instance using the launcher."""
return self.Launcher(config=config).launch(ami, count)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Launcher(self, config=None): """Provides a configurable launcher for EC2 instances."""
class _launcher(EC2ApiClient): """Configurable launcher for EC2 instances. Create the Launcher (passing an optional dict of its attributes), set its attributes (as described in the RunInstances API docs), then launch(). """ def __init__(self, aws, con...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def events(self, all_instances=None, instance_ids=None, filters=None): """a list of tuples containing instance Id's and event information"""
params = {} if filters: params["filters"] = make_filters(filters) if instance_ids: params['InstanceIds'] = instance_ids statuses = self.status(all_instances, **params) event_list = [] for status in statuses: if status.get("Events"): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, volume_ids=None, filters=None): """List EBS Volume info."""
params = {} if filters: params["filters"] = make_filters(filters) if isinstance(volume_ids, str): volume_ids = [volume_ids] return self.call("DescribeVolumes", VolumeIds=volume_ids, response_data_key="Volumes", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach(self, volume_id, instance_id, device_path): """Attach a volume to an instance, exposing it with a device name."""
return self.call("AttachVolume", VolumeId=volume_id, InstanceId=instance_id, Device=device_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detach(self, volume_id, instance_id='', device_path='', force=False): """Detach a volume from an instance."""
return self.call("DetachVolume", VolumeId=volume_id, InstanceId=instance_id, Device=device_path, force=force)
<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, *args, **kwargs): """ Overrides the save method """
self.slug = self.create_slug() super(Slugable, self).save(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_slug(self): """ Creates slug, checks if slug is unique, and loop if not """
name = self.slug_source counter = 0 # loops until slug is unique while True: if counter == 0: slug = slugify(name) else: # using the counter var to bump the slug name slug = slugify('{0} {1}'.format(name, str(counte...
<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_html(url, headers=None, timeout=None, errors="strict", wait_time=None, driver=None, zillow_only=False, cache_only=False, zillow_first=False, cache_first=F...
if wait_time is None: wait_time = Config.Crawler.wait_time # prepare url cache_url1 = prefix + url + "/" cache_url2 = prefix + url zillow_url = url only_flags = [zillow_only, cache_only] if sum(only_flags) == 0: first_flags = [zillow_first, cache_first] if sum(firs...
<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_paths(folder, ignore_endswith=ignore_endswith): '''Return hologram file paths Parameters ---------- folder: str or pathlib.Path Path to search folder ignore_endswith: list List of filename ending strings indicating which files should be ignored. ''' folder = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(func, args): """Call the function with args normalized and cast to the correct types. Args: func: The function to call. args: The arguments parsed by do...
assert hasattr(func, '__call__'), 'Cannot call func: {}'.format( func.__name__) raw_func = ( func if isinstance(func, FunctionType) else func.__class__.__call__) hints = collections.defaultdict(lambda: Any, get_type_hints(raw_func)) argspec = _getargspec(raw_func) named_args = {} ...
<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_callable(subcommand): # type: (config.RcliEntryPoint) -> Union[FunctionType, MethodType] """Return a callable object from the subcommand. Args: subcomman...
_LOGGER.debug( 'Creating callable from subcommand "%s".', subcommand.__name__) if isinstance(subcommand, ModuleType): _LOGGER.debug('Subcommand is a module.') assert hasattr(subcommand, 'Command'), ( 'Module subcommand must have callable "Command" class definition.') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getargspec(func): """Return a Python 3-like argspec object. Note: args contains varargs and varkw if they exist. This behavior differs from getargspec and g...
argspec = _getspec(func) args = list(argspec.args) if argspec.varargs: args += [argspec.varargs] if argspec[2]: # "keywords" in PY2 and "varkw" in PY3 args += [argspec[2]] return _ArgSpec(args, argspec.varargs, argspec[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 _normalize(args): # type: (Dict[str, Any]) -> Generator[Tuple[str, str, Any], None, None] """Yield a 3-tuple containing the key, a normalized key, and the va...
for k, v in six.iteritems(args): nk = re.sub(r'\W|^(?=\d)', '_', k).strip('_').lower() do_not_shadow = dir(six.moves.builtins) # type: ignore if keyword.iskeyword(nk) or nk in do_not_shadow: nk += '_' _LOGGER.debug('Normalized "%s" to "%s".', k, nk) yield k, nk,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self, filename=None): """Puts on destination as a temp file, renames on the destination. """
dst = os.path.join(self.dst_path, filename) src = os.path.join(self.src_path, filename) dst_tmp = os.path.join(self.dst_tmp, filename) self.put(src=src, dst=dst_tmp, callback=self.update_progress, confirm=True) self.rename(src=dst_tmp, dst=dst)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __create(self): """ Construct the email """
self.__data = json.dumps({ 'config_path': self.encode(self.config_path), 'subject': self.encode(self.__subject), 'text': self.encode(self.__text), 'html': self.encode(self.__html), 'files': self.__files, 'send_as_one': self.send_as_...
<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 async_get_camera_image(self, image_name, username=None, password=None): """ Grab a single image from the Xeoma web server Arguments: image_name: the na...
try: data = await self.async_fetch_image_data( image_name, username, password) if data is None: raise XeomaError('Unable to authenticate with Xeoma web ' 'server') return data except asyncio.TimeoutErr...
<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 async_fetch_image_data(self, image_name, username, password): """ Fetch image data from the Xeoma web server Arguments: image_name: the name of the ima...
params = {} cookies = self.get_session_cookie() if username is not None and password is not None: params['user'] = self.encode_user(username, password) else: params['user'] = '' async with aiohttp.ClientSession(cookies=cookies) as session: res...
<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 async_get_image_names(self): """ Parse web server camera view for camera image names """
cookies = self.get_session_cookie() try: async with aiohttp.ClientSession(cookies=cookies) as session: resp = await session.get( self._base_url ) t = await resp.text() match = re.findall('(?:\w|\d|")/(.*?)....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_session_cookie(self): """ Create a session cookie object for use by aiohttp """
if self._login is not None and self._password is not None: session_key = self.encode_user(self._login, self._password) return {'sessionkey': session_key} else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_sha256_digest(self, content): """Return the sha256 digest of the content in the header format the Merchant API expects. """
content_sha256 = base64.b64encode(SHA256.new(content).digest()) return 'SHA256=' + content_sha256
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sha256_sign(self, method, url, headers, body): """Sign the request with SHA256. """
d = '' sign_headers = method.upper() + '|' + url + '|' for key, value in sorted(headers.items()): if key.startswith('X-Mcash-'): sign_headers += d + key.upper() + '=' + value d = '&' rsa_signature = base64.b64encode( self.signer.s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_toolbox(self, filename): """ Creates a new Python toolbox where each task name is a GPTool in the toolbox. :param filename: the filename of the genera...
filename = os.path.splitext(filename)[0] label = os.path.basename(filename) # Get task information first so we can build the tool list tool_list = [] for task in self.tasks: tool_list.append(task.name) file_descriptor = os.open(filename + '.pyt', ...
<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_tool(self, task): """ Creates a new GPTool for the toolbox. """
gp_tool = dict(taskName=task.name, taskDisplayName=task.display_name, taskDescription=task.description, canRunInBackground=True, taskUri=task.uri) gp_tool['execute'] = self._execute_template.substitute(gp_tool)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_script(self, script_name): """Finds the script file and copies it into the toolbox"""
filename = os.path.abspath(script_name) with open(filename, 'r') as script_file: self.toolbox_file.write(script_file.read())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_relationship(self, relator, direction= RELATIONSHIP_DIRECTIONS.BIDIRECTIONAL): """ Create a relationship object for this attribute from the given relato...
if IEntity.providedBy(relator): # pylint:disable=E1101 rel = DomainRelationship(relator, self, direction=direction) elif IResource.providedBy(relator): # pylint:disable=E1101 rel = ResourceRelationship(relator, 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 register(self, app, options): """Register the blueprint to the mach9 app."""
url_prefix = options.get('url_prefix', self.url_prefix) # Routes for future in self.routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the router future.handler.__blueprintname__ = self.name # Prepend the...
<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_route(self, handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=False): """Create a blueprint route from a function. :param handler: func...
# Handle HTTPMethodView differently if hasattr(handler, 'view_class'): http_methods = ( 'GET', 'POST', 'PUT', 'HEAD', 'OPTIONS', 'PATCH', 'DELETE') methods = set() for method in http_methods: if getattr(handler.view_class, method.lower...
<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_boards_gui(hwpack=''): """remove boards by GUI."""
if not hwpack: if len(hwpack_names()) > 1: hwpack = psidialogs.choice(hwpack_names(), 'select hardware package to select board from!', title='select') else: hwpack = hwpack_names()[0] print('%s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def single(C, namespace=None): """An element maker with a single namespace that uses that namespace as the default"""
if namespace is None: B = C()._ else: B = C(default=namespace, _=namespace)._ return B
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersect(self, **kwargs): """ Intersect Point and Bathymetry returns bool """
end_point = kwargs.pop('end_point') depth = self.get_depth(location=end_point) # Bathymetry and a particle's depth are both negative down if depth < 0 and depth > end_point.depth: inter = True else: inter = False return inter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def react(self, **kwargs): """ The time of recation is ignored hereTime is ignored here and should be handled by whatever called this function. """
react_type = kwargs.get("type", self._type) if react_type == 'hover': return self.__hover(**kwargs) elif react_type == 'stick': pass elif react_type == 'reverse': return self.__reverse(**kwargs) else: raise ValueError("Bathymetry ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __hover(self, **kwargs): """ This hovers the particle 1m above the bathymetry WHERE IT WOULD HAVE ENDED UP. This is WRONG and we need to compute the location...
end_point = kwargs.pop('end_point') # The location argument here should be the point that intersected the bathymetry, # not the end_point that is "through" the bathymetry. depth = self.get_depth(location=end_point) return Location4D(latitude=end_point.latitude, longitude=end_poi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __reverse(self, **kwargs): """ If we hit the bathymetry, set the location to where we came from. """
start_point = kwargs.pop('start_point') return Location4D(latitude=start_point.latitude, longitude=start_point.longitude, depth=start_point.depth)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): # type: () -> typing.Any """Parse the command line options and launch the requested command. If the command is 'help' then print the help message for...
colorama.init(wrap=six.PY3) doc = usage.get_primary_command_usage() allow_subcommands = '<command>' in doc args = docopt(doc, version=settings.version, options_first=allow_subcommands) if sys.excepthook is sys.__excepthook__: sys.excepthook = log.excepthook try: ...
<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_subcommand(name): # type: (str) -> config.RcliEntryPoint """Return the function for the specified subcommand. Args: name: The name of a subcommand. Retu...
_LOGGER.debug('Accessing subcommand "%s".', name) if name not in settings.subcommands: raise ValueError( '"{subcommand}" is not a {command} command. \'{command} help -a\' ' 'lists all available subcommands.'.format( command=settings.command, subcommand=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 _run_command(argv): # type: (typing.List[str]) -> typing.Any """Run the command with the given CLI options and exit. Command functions are expected to have a...
command_name, argv = _get_command_and_argv(argv) _LOGGER.info('Running command "%s %s" with args: %s', settings.command, command_name, argv) subcommand = _get_subcommand(command_name) func = call.get_callable(subcommand) doc = usage.format_usage(subcommand.__doc__) args = _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 _get_command_and_argv(argv): # type: (typing.List[str]) -> typing.Tuple[str, typing.List[str]] """Extract the command name and arguments to pass to docopt. A...
command_name = argv[0] if not command_name: argv = argv[1:] elif command_name == settings.command: argv.remove(command_name) return command_name, argv