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 _get_content(data, which_content): """ get the content that could be hidden in the middle of "content" or "summary detail" from the data of the provider """
content = '' if data.get(which_content): if isinstance(data.get(which_content), feedparser.FeedParserDict): content = data.get(which_content)['value'] elif not isinstance(data.get(which_content), str): if 'value' in data.get(which_content)[0]: content = data.get(which_content)[0].value else: content = data.get(which_content) return 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 get_request_token(self, request): """ request the token to the external service """
if self.oauth == 'oauth1': oauth = OAuth1Session(self.consumer_key, client_secret=self.consumer_secret) request_token = oauth.fetch_request_token(self.REQ_TOKEN) # Save the request token information for later request.session['oauth_token'] = request_token['oauth_token'] request.session['oauth_token_secret'] = request_token['oauth_token_secret'] return request_token else: callback_url = self.callback_url(request) oauth = OAuth2Session(client_id=self.consumer_key, redirect_uri=callback_url, scope=self.scope) authorization_url, state = oauth.authorization_url(self.AUTH_URL) return authorization_url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_data(self, trigger_id, **data): """ let's save the data don't want to handle empty title nor content otherwise this will produce an Exception by the Evernote's API :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_id: int :type data: dict :return: the status of the save statement :rtype: boolean """
# set the title and content of the data title, content = super(ServiceEvernote, self).save_data(trigger_id, **data) # get the evernote data of this trigger trigger = Evernote.objects.get(trigger_id=trigger_id) # initialize notestore process note_store = self._notestore(trigger_id, data) if isinstance(note_store, evernote.api.client.Store): # note object note = self._notebook(trigger, note_store) # its attributes note = self._attributes(note, data) # its footer content = self._footer(trigger, data, content) # its title note.title = limit_content(title, 255) # its content note = self._content(note, content) # create a note return EvernoteMgr.create_note(note_store, note, trigger_id, data) else: # so its note an evernote object, so something wrong happens return note_store
<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_evernote_client(self, token=None): """ get the token from evernote """
if token: return EvernoteClient(token=token, sandbox=self.sandbox) else: return EvernoteClient(consumer_key=self.consumer_key, consumer_secret=self.consumer_secret, sandbox=self.sandbox)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth(self, request): """ let's auth the user to the Service """
client = self.get_evernote_client() request_token = client.get_request_token(self.callback_url(request)) # Save the request token information for later request.session['oauth_token'] = request_token['oauth_token'] request.session['oauth_token_secret'] = request_token['oauth_token_secret'] # Redirect the user to the Evernote authorization URL # return the URL string which will be used by redirect() # from the calling func return client.get_authorize_url(request_token)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_context_data(self, **kwargs): """ get the data of the view data are : 1) number of triggers enabled 2) number of triggers disabled 3) number of activated services 4) list of activated services by the connected user """
triggers_enabled = triggers_disabled = services_activated = () context = super(TriggerListView, self).get_context_data(**kwargs) if self.kwargs.get('trigger_filtered_by'): page_link = reverse('trigger_filter_by', kwargs={'trigger_filtered_by': self.kwargs.get('trigger_filtered_by')}) elif self.kwargs.get('trigger_ordered_by'): page_link = reverse('trigger_order_by', kwargs={'trigger_ordered_by': self.kwargs.get('trigger_ordered_by')}) else: page_link = reverse('home') if self.request.user.is_authenticated: # get the enabled triggers triggers_enabled = TriggerService.objects.filter( user=self.request.user, status=1).count() # get the disabled triggers triggers_disabled = TriggerService.objects.filter( user=self.request.user, status=0).count() # get the activated services user_service = UserService.objects.filter(user=self.request.user) """ List of triggers activated by the user """ context['trigger_filter_by'] = user_service """ number of service activated for the current user """ services_activated = user_service.count() """ which triggers are enabled/disabled """ context['nb_triggers'] = {'enabled': triggers_enabled, 'disabled': triggers_disabled} """ Number of services activated """ context['nb_services'] = services_activated context['page_link'] = page_link context['fire'] = settings.DJANGO_TH.get('fire', False) return context
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def datas(self): """ read the data from a given URL or path to a local file """
data = feedparser.parse(self.URL_TO_PARSE, agent=self.USER_AGENT) # when chardet says # >>> chardet.detect(data) # {'confidence': 0.99, 'encoding': 'utf-8'} # bozo says sometimes # >>> data.bozo_exception # CharacterEncodingOverride('document declared as us-ascii, but parsed as utf-8', ) # invalid Feed # so I remove this detection :( # the issue come from the server that return a charset different from the feeds # it is not related to Feedparser but from the HTTP server itself if data.bozo == 1: data.entries = '' return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalcallback(request, **kwargs): """ let's do the callback of the related service after the auth request from UserServiceCreateView """
default_provider.load_services() service_name = kwargs.get('service_name') service_object = default_provider.get_service(service_name) lets_callback = getattr(service_object, 'callback') # call the auth func from this class # and redirect to the external service page # to auth the application django-th to access to the user # account details return render_to_response(lets_callback(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 filter_that(self, criteria, data): ''' this method just use the module 're' to check if the data contain the string to find ''' import re prog = re.compile(criteria) return True if prog.match(data) else 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 load_services(self, services=settings.TH_SERVICES): """ get the service from the settings """
kwargs = {} for class_path in services: module_name, class_name = class_path.rsplit('.', 1) klass = import_from_path(class_path) service = klass(None, **kwargs) self.register(class_name, service)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recycle(): """ the purpose of this tasks is to recycle the data from the cache with version=2 in the main cache """
# http://niwinz.github.io/django-redis/latest/#_scan_delete_keys_in_bulk for service in cache.iter_keys('th_*'): try: # get the value from the cache version=2 service_value = cache.get(service, version=2) # put it in the version=1 cache.set(service, service_value) # remote version=2 cache.delete_pattern(service, version=2) except ValueError: pass logger.info('recycle of cache done!')
<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(self, *args, **options): """ get all the digest data to send to each user """
now = arrow.utcnow().to(settings.TIME_ZONE) now = now.date() digest = Digest.objects.filter(date_end=str(now)).order_by('user', 'date_end') users = digest.distinct('user') subject = 'Your digester' msg_plain = render_to_string('digest/email.txt', {'digest': digest, 'subject': subject}) msg_html = render_to_string('digest/email.html', {'digest': digest, 'subject': subject}) message = msg_plain from_email = settings.ADMINS recipient_list = () for user in users: recipient_list += (user.user.email,) send_mail(subject, message, from_email, recipient_list, html_message=msg_html)
<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_notebook(note_store, my_notebook): """ get the notebook from its name """
notebook_id = 0 notebooks = note_store.listNotebooks() # get the notebookGUID ... for notebook in notebooks: if notebook.name.lower() == my_notebook.lower(): notebook_id = notebook.guid break return notebook_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_notebook(note_store, my_notebook, notebook_id): """ create a notebook """
if notebook_id == 0: new_notebook = Types.Notebook() new_notebook.name = my_notebook new_notebook.defaultNotebook = False notebook_id = note_store.createNotebook(new_notebook).guid return notebook_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_note_attribute(data): """ add the link of the 'source' in the note """
na = False if data.get('link'): na = Types.NoteAttributes() # add the url na.sourceURL = data.get('link') # add the object to the note return na
<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_primitive(val): """ Checks if the passed value is a primitive type. True True True False False :param val: value to check :return: True if value is a primitive, else False """
return isinstance(val, (str, bool, float, complex, bytes, six.text_type) + six.string_types + six.integer_types)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_every(parts, iterable): """ Split an iterable into parts of length parts [[1, 2], [3, 4]] :param iterable: iterable to split :param parts: number of chunks :return: return the iterable split in parts """
return takewhile(bool, (list(islice(iterable, parts)) for _ in 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 compute_partition_size(result, processes): """ Attempts to compute the partition size to evenly distribute work across processes. Defaults to 1 if the length of result cannot be determined. :param result: Result to compute on :param processes: Number of processes to use :return: Best partition size """
try: return max(math.ceil(len(result) / processes), 1) except TypeError: return 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 evaluate(self, sequence): """ Compute the lineage on the sequence. :param sequence: Sequence to compute :return: Evaluated sequence """
last_cache_index = self.cache_scan() transformations = self.transformations[last_cache_index:] return self.engine.evaluate(sequence, transformations)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrap(value): """ Wraps the passed value in a Sequence if it is not a primitive. If it is a string argument it is expanded to a list of characters. 1 ['a', 'b', 'c'] functional.pipeline.Sequence :param value: value to wrap :return: wrapped or not wrapped value """
if is_primitive(value): return value if isinstance(value, (dict, set)) or is_namedtuple(value): return value elif isinstance(value, collections.Iterable): try: if type(value).__name__ == 'DataFrame': import pandas if isinstance(value, pandas.DataFrame): return Sequence(value.values) except ImportError: # pragma: no cover pass return Sequence(value) else: return 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 cartesian(self, *iterables, **kwargs): """ Returns the cartesian product of the passed iterables with the specified number of repetitions. The keyword argument `repeat` is read from kwargs to pass to itertools.cartesian. [(0, 0), (0, 1), (1, 0), (1, 1)] :param iterables: elements for cartesian product :param kwargs: the variable `repeat` is read from kwargs :return: cartesian product """
return self._transform(transformations.cartesian_t(iterables, kwargs.get('repeat', 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 drop(self, n): """ Drop the first n elements of the sequence. [3, 4, 5] :param n: number of elements to drop :return: sequence without first n elements """
if n <= 0: return self._transform(transformations.drop_t(0)) else: return self._transform(transformations.drop_t(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 drop_right(self, n): """ Drops the last n elements of the sequence. [1, 2, 3] :param n: number of elements to drop :return: sequence with last n elements dropped """
return self._transform(transformations.CACHE_T, transformations.drop_right_t(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 take(self, n): """ Take the first n elements of the sequence. [1, 2] :param n: number of elements to take :return: first n elements of sequence """
if n <= 0: return self._transform(transformations.take_t(0)) else: return self._transform(transformations.take_t(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 count(self, func): """ Counts the number of elements in the sequence which satisfy the predicate func. 2 :param func: predicate to count elements on :return: count of elements that satisfy predicate """
n = 0 for element in self: if func(element): n += 1 return 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 reduce(self, func, *initial): """ Reduce sequence of elements using func. API mirrors functools.reduce 6 :param func: two parameter, associative reduce function :param initial: single optional argument acting as initial value :return: reduced value using func """
if len(initial) == 0: return _wrap(reduce(func, self)) elif len(initial) == 1: return _wrap(reduce(func, self, initial[0])) else: raise ValueError('reduce takes exactly one optional parameter for initial 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 product(self, projection=None): """ Takes product of elements in sequence. 24 1 1 :param projection: function to project on the sequence before taking the product :return: product of elements in sequence """
if self.empty(): if projection: return projection(1) else: return 1 if self.size() == 1: if projection: return projection(self.first()) else: return self.first() if projection: return self.map(projection).reduce(mul) else: return self.reduce(mul)
<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(self, projection=None): """ Takes sum of elements in sequence. 10 3 :param projection: function to project on the sequence before taking the sum :return: sum of elements in sequence """
if projection: return sum(self.map(projection)) else: return sum(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 average(self, projection=None): """ Takes the average of elements in the sequence 1.5 :param projection: function to project on the sequence before taking the average :return: average of elements in the sequence """
length = self.size() if projection: return sum(self.map(projection)) / length else: return sum(self) / length
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sliding(self, size, step=1): """ Groups elements in fixed size blocks by passing a sliding window over them. The last window has at least one element but may have less than size elements :param size: size of sliding window :param step: step size between windows :return: sequence of sliding windows """
return self._transform(transformations.sliding_t(_wrap, size, step))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sorted(self, key=None, reverse=False): """ Uses python sort and its passed arguments to sort the input. [1, 2, 3, 4] :param key: sort using key function :param reverse: return list reversed or not :return: sorted sequence """
return self._transform(transformations.sorted_t(key=key, reverse=reverse))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slice(self, start, until): """ Takes a slice of the sequence starting at start and until but not including until. [2] [2, 3] :param start: starting index :param until: ending index :return: slice including start until but not including until """
return self._transform(transformations.slice_t(start, until))
<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_list(self, n=None): """ Converts sequence to list of elements. list functional.pipeline.Sequence [1, 2, 3] :param n: Take n elements of sequence if not None :return: list of elements in sequence """
if n is None: self.cache() return self._base_sequence else: return self.cache().take(n).list()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_jsonl(self, path, mode='wb', compression=None): """ Saves the sequence to a jsonl file. Each element is mapped using json.dumps then written with a newline separating each element. :param path: path to write file :param mode: mode to write in, defaults to 'w' to overwrite contents :param compression: compression format """
with universal_write_open(path, mode=mode, compression=compression) as output: output.write((self.map(json.dumps).make_string('\n') + '\n').encode('utf-8'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_csv(self, path, mode=WRITE_MODE, dialect='excel', compression=None, newline='', **fmtparams): """ Saves the sequence to a csv file. Each element should be an iterable which will be expanded to the elements of each row. :param path: path to write file :param mode: file open mode :param dialect: passed to csv.writer :param fmtparams: passed to csv.writer """
if 'b' in mode: newline = None with universal_write_open(path, mode=mode, compression=compression, newline=newline) as output: csv_writer = csv.writer(output, dialect=dialect, **fmtparams) for row in self: csv_writer.writerow([six.u(str(element)) for element in row])
<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_sqlite3_by_table(self, conn, table_name): """ Saves the sequence to the specified table of sqlite3 database. Each element can be a dictionary, namedtuple, tuple or list. Target table must be created in advance. :param conn: path or sqlite connection, cursor :param table_name: table name string """
def _insert_item(item): if isinstance(item, dict): cols = ', '.join(item.keys()) placeholders = ', '.join('?' * len(item)) sql = 'INSERT INTO {} ({}) VALUES ({})'.format(table_name, cols, placeholders) conn.execute(sql, tuple(item.values())) elif is_namedtuple(item): cols = ', '.join(item._fields) placeholders = ', '.join('?' * len(item)) sql = 'INSERT INTO {} ({}) VALUES ({})'.format(table_name, cols, placeholders) conn.execute(sql, item) elif isinstance(item, (list, tuple)): placeholders = ', '.join('?' * len(item)) sql = 'INSERT INTO {} VALUES ({})'.format(table_name, placeholders) conn.execute(sql, item) else: raise TypeError('item must be one of dict, namedtuple, tuple or list got {}' .format(type(item))) self.for_each(_insert_item)
<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_sqlite3(self, conn, target, *args, **kwargs): """ Saves the sequence to sqlite3 database. Target table must be created in advance. The table schema is inferred from the elements in the sequence if only target table name is supplied. .to_sqlite3('users.db', 'INSERT INTO user (id, name) VALUES (?, ?)') :param conn: path or sqlite connection, cursor :param target: SQL query string or table name :param args: passed to sqlite3.connect :param kwargs: passed to sqlite3.connect """
# pylint: disable=no-member insert_regex = re.compile(r'(insert|update)\s+into', flags=re.IGNORECASE) if insert_regex.match(target): insert_f = self._to_sqlite3_by_query else: insert_f = self._to_sqlite3_by_table if isinstance(conn, (sqlite3.Connection, sqlite3.Cursor)): insert_f(conn, target) conn.commit() elif isinstance(conn, str): with sqlite3.connect(conn, *args, **kwargs) as input_conn: insert_f(input_conn, target) input_conn.commit() else: raise ValueError('conn must be a must be a file path or sqlite3 Connection/Cursor')
<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_pandas(self, columns=None): # pylint: disable=import-error """ Converts sequence to a pandas DataFrame using pandas.DataFrame.from_records :param columns: columns for pandas to use :return: DataFrame of sequence """
import pandas return pandas.DataFrame.from_records(self.to_list(), columns=columns)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self, path, delimiter=None, mode='r', buffering=-1, encoding=None, errors=None, newline=None): """ Reads and parses input files as defined. If delimiter is not None, then the file is read in bulk then split on it. If it is None (the default), then the file is parsed as sequence of lines. The rest of the options are passed directly to builtins.open with the exception that write/append file modes is not allowed. [u'tent\\n'] :param path: path to file :param delimiter: delimiter to split joined text on. if None, defaults to per line split :param mode: file open mode :param buffering: passed to builtins.open :param encoding: passed to builtins.open :param errors: passed to builtins.open :param newline: passed to builtins.open :return: output of file depending on options wrapped in a Sequence via seq """
if not re.match('^[rbt]{1,3}$', mode): raise ValueError('mode argument must be only have r, b, and t') file_open = get_read_function(path, self.disable_compression) file = file_open(path, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline) if delimiter is None: return self(file) else: return self(''.join(list(file)).split(delimiter))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def csv(self, csv_file, dialect='excel', **fmt_params): """ Reads and parses the input of a csv stream or file. csv_file can be a filepath or an object that implements the iterator interface (defines next() or __next__() depending on python version). [['1', 'tent', '300'], ['2', 'food', '100']] :param csv_file: path to file or iterator object :param dialect: dialect of csv, passed to csv.reader :param fmt_params: options passed to csv.reader :return: Sequence wrapping csv file """
if isinstance(csv_file, str): file_open = get_read_function(csv_file, self.disable_compression) input_file = file_open(csv_file) elif hasattr(csv_file, 'next') or hasattr(csv_file, '__next__'): input_file = csv_file else: raise ValueError('csv_file must be a file path or implement the iterator interface') csv_input = csvapi.reader(input_file, dialect=dialect, **fmt_params) return self(csv_input).cache(delete_lineage=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jsonl(self, jsonl_file): """ Reads and parses the input of a jsonl file stream or file. Jsonl formatted files must have a single valid json value on each line which is parsed by the python json module. {u'date': u'10/09', u'message': u'hello anyone there?', u'user': u'bob'} :param jsonl_file: path or file containing jsonl content :return: Sequence wrapping jsonl file """
if isinstance(jsonl_file, str): file_open = get_read_function(jsonl_file, self.disable_compression) input_file = file_open(jsonl_file) else: input_file = jsonl_file return self(input_file).map(jsonapi.loads).cache(delete_lineage=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json(self, json_file): """ Reads and parses the input of a json file handler or file. Json files are parsed differently depending on if the root is a dictionary or an array. 1) If the json's root is a dictionary, these are parsed into a sequence of (Key, Value) pairs 2) If the json's root is an array, these are parsed into a sequence of entries [u'sarah', {u'date_created': u'08/08', u'news_email': True, u'email': u'sarah@gmail.com'}] :param json_file: path or file containing json content :return: Sequence wrapping jsonl file """
if isinstance(json_file, str): file_open = get_read_function(json_file, self.disable_compression) input_file = file_open(json_file) json_input = jsonapi.load(input_file) elif hasattr(json_file, 'read'): json_input = jsonapi.load(json_file) else: raise ValueError('json_file must be a file path or implement the iterator interface') if isinstance(json_input, list): return self(json_input) else: return self(six.viewitems(json_input))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sqlite3(self, conn, sql, parameters=None, *args, **kwargs): """ Reads input by querying from a sqlite database. [(1, 'Tom')] :param conn: path or sqlite connection, cursor :param sql: SQL query string :param parameters: Parameters for sql query :return: Sequence wrapping SQL cursor """
if parameters is None: parameters = () if isinstance(conn, (sqlite3api.Connection, sqlite3api.Cursor)): return self(conn.execute(sql, parameters)) elif isinstance(conn, str): with sqlite3api.connect(conn, *args, **kwargs) as input_conn: return self(input_conn.execute(sql, parameters)) else: raise ValueError('conn must be a must be a file path or sqlite3 Connection/Cursor')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def full(self): """Return True if there are maxsize items in the queue. Note: if the Queue was initialized with maxsize=0 (the default), then full() is never True. """
if self._parent._maxsize <= 0: return False else: return self.qsize() >= self._parent._maxsize
<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 join(self): """Block until all items in the queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer calls task_done() to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks. """
while True: with self._parent._sync_mutex: if self._parent._unfinished_tasks == 0: break await self._parent._finished.wait()
<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, to_dir, compressionlevel=9): u""" Save compressed compiled dictionary data. :param to_dir: directory to save dictionary data :compressionlevel: (Optional) gzip compression level. default is 9 """
if os.path.exists(to_dir) and not os.path.isdir(to_dir): raise Exception('Not a directory : %s' % to_dir) elif not os.path.exists(to_dir): os.makedirs(to_dir, mode=int('0755', 8)) _save(os.path.join(to_dir, FILE_USER_FST_DATA), self.compiledFST[0], compressionlevel) _save(os.path.join(to_dir, FILE_USER_ENTRIES_DATA), pickle.dumps(self.entries), compressionlevel)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def analyze(self, text): u""" Analyze the input text with custom CharFilters, Tokenizer and TokenFilters. :param text: unicode string to be tokenized :return: token generator. emitted element type depends on the output of the last TokenFilter. (e.g., ExtractAttributeFilter emits strings.) """
for cfilter in self.char_filters: text = cfilter.filter(text) tokens = self.tokenizer.tokenize(text, stream=True, wakati=False) for tfilter in self.token_filters: tokens = tfilter.filter(tokens) return tokens
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compileFST(fst): u""" convert FST to byte array representing arcs """
arcs = [] address = {} pos = 0 for (num, s) in enumerate(fst.dictionary.values()): for i, (c, v) in enumerate(sorted(s.trans_map.items(), reverse=True)): bary = bytearray() flag = 0 output_size, output = 0, bytes() if i == 0: flag += FLAG_LAST_ARC if v['output']: flag += FLAG_ARC_HAS_OUTPUT output_size = len(v['output']) output = v['output'] # encode flag, label, output_size, output, relative target address bary += pack('b', flag) if PY3: bary += pack('B', c) else: bary += pack('c', c) if output_size > 0: bary += pack('I', output_size) bary += output next_addr = address.get(v['state'].id) assert next_addr is not None target = (pos + len(bary) + 4) - next_addr assert target > 0 bary += pack('I', target) # add the arc represented in bytes if PY3: arcs.append(bytes(bary)) else: arcs.append(b''.join(chr(b) for b in bary)) # address count up pos += len(bary) if s.is_final(): bary = bytearray() # final state flag = FLAG_FINAL_ARC output_count = 0 if s.final_output and any(len(e) > 0 for e in s.final_output): # the arc has final output flag += FLAG_ARC_HAS_FINAL_OUTPUT output_count = len(s.final_output) if not s.trans_map: flag += FLAG_LAST_ARC # encode flag, output size, output bary += pack('b', flag) if output_count: bary += pack('I', output_count) for out in s.final_output: output_size = len(out) bary += pack('I', output_size) if output_size: bary += out # add the arc represented in bytes if PY3: arcs.append(bytes(bary)) else: arcs.append(b''.join(chr(b) for b in bary)) # address count up pos += len(bary) address[s.id] = pos logger.debug('compiled arcs size: %d' % len(arcs)) arcs.reverse() return b''.join(arcs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenize(self, text, stream=False, wakati=False, baseform_unk=True, dotfile=''): u""" Tokenize the input text. :param text: unicode string to be tokenized :param stream: (Optional) if given True use stream mode. default is False. :param wakati: (Optinal) if given True returns surface forms only. default is False. :param baseform_unk: (Optional) if given True sets base_form attribute for unknown tokens. default is True. :param dotfile: (Optional) if specified, graphviz dot file is output to the path for later visualizing of the lattice graph. This option is ignored when the input length is larger than MAX_CHUNK_SIZE or running on stream mode. :return: list of tokens (stream=False, wakati=False) or token generator (stream=True, wakati=False) or list of string (stream=False, wakati=True) or string generator (stream=True, wakati=True) """
if self.wakati: wakati = True if stream: return self.__tokenize_stream(text, wakati, baseform_unk, '') elif dotfile and len(text) < Tokenizer.MAX_CHUNK_SIZE: return list(self.__tokenize_stream(text, wakati, baseform_unk, dotfile)) else: return list(self.__tokenize_stream(text, wakati, baseform_unk, ''))
<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_ip(request, real_ip_only=False, right_most_proxy=False): """ Returns client's best-matched ip-address, or None @deprecated - Do not edit """
best_matched_ip = None warnings.warn('get_ip is deprecated and will be removed in 3.0.', DeprecationWarning) for key in defs.IPWARE_META_PRECEDENCE_ORDER: value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip() if value is not None and value != '': ips = [ip.strip().lower() for ip in value.split(',')] if right_most_proxy and len(ips) > 1: ips = reversed(ips) for ip_str in ips: if ip_str and is_valid_ip(ip_str): if not ip_str.startswith(NON_PUBLIC_IP_PREFIX): return ip_str if not real_ip_only: loopback = defs.IPWARE_LOOPBACK_PREFIX if best_matched_ip is None: best_matched_ip = ip_str elif best_matched_ip.startswith(loopback) and not ip_str.startswith(loopback): best_matched_ip = ip_str return best_matched_ip
<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_real_ip(request, right_most_proxy=False): """ Returns client's best-matched `real` `externally-routable` ip-address, or None @deprecated - Do not edit """
warnings.warn('get_real_ip is deprecated and will be removed in 3.0.', DeprecationWarning) return get_ip(request, real_ip_only=True, right_most_proxy=right_most_proxy)
<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_ipv6(ip_str): """ Check the validity of an IPv6 address """
try: socket.inet_pton(socket.AF_INET6, ip_str) except socket.error: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_request_meta(request, key): """ Given a key, it returns a cleaned up version of the value from request.META, or None """
value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip() if value == '': return None return 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 get_ips_from_string(ip_str): """ Given a string, it returns a list of one or more valid IP addresses """
ip_list = [] for ip in ip_str.split(','): clean_ip = ip.strip().lower() if clean_ip: ip_list.append(clean_ip) ip_count = len(ip_list) if ip_count > 0: if is_valid_ip(ip_list[0]) and is_valid_ip(ip_list[-1]): return ip_list, ip_count return [], 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 parse_args(sys_argv, usage): """ Return an OptionParser for the script. """
args = sys_argv[1:] parser = OptionParser(usage=usage) options, args = parser.parse_args(args) template, context = args return template, context
<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(template, context=None, **kwargs): """ Return the given template string rendered using the given context. """
renderer = Renderer() return renderer.render(template, context, **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 _get_value(context, key): """ Retrieve a key's value from a context item. Returns _NOT_FOUND if the key does not exist. The ContextStack.get() docstring documents this function's intended behavior. """
if isinstance(context, dict): # Then we consider the argument a "hash" for the purposes of the spec. # # We do a membership test to avoid using exceptions for flow control # (e.g. catching KeyError). if key in context: return context[key] elif type(context).__module__ != _BUILTIN_MODULE: # Then we consider the argument an "object" for the purposes of # the spec. # # The elif test above lets us avoid treating instances of built-in # types like integers and strings as objects (cf. issue #81). # Instances of user-defined classes on the other hand, for example, # are considered objects by the test above. try: attr = getattr(context, key) except AttributeError: # TODO: distinguish the case of the attribute not existing from # an AttributeError being raised by the call to the attribute. # See the following issue for implementation ideas: # http://bugs.python.org/issue7559 pass else: # TODO: consider using EAFP here instead. # http://docs.python.org/glossary.html#term-eafp if callable(attr): return attr() return attr return _NOT_FOUND
<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(*context, **kwargs): """ Build a ContextStack instance from a sequence of context-like items. This factory-style method is more general than the ContextStack class's constructor in that, unlike the constructor, the argument list can itself contain ContextStack instances. Here is an example illustrating various aspects of this method: 'cat' 'spinach' 'gold' Arguments: *context: zero or more dictionaries, ContextStack instances, or objects with which to populate the initial context stack. None arguments will be skipped. Items in the *context list are added to the stack in order so that later items in the argument list take precedence over earlier items. This behavior is the same as the constructor's. **kwargs: additional key-value data to add to the context stack. As these arguments appear after all items in the *context list, in the case of key conflicts these values take precedence over all items in the *context list. This behavior is the same as the constructor's. """
items = context context = ContextStack() for item in items: if item is None: continue if isinstance(item, ContextStack): context._stack.extend(item._stack) else: context.push(item) if kwargs: context.push(kwargs) return context
<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, name): """ Resolve a dotted name against the current context stack. This function follows the rules outlined in the section of the spec regarding tag interpolation. This function returns the value as is and does not coerce the return value to a string. Arguments: name: a dotted or non-dotted name. default: the value to return if name resolution fails at any point. Defaults to the empty string per the Mustache spec. This method queries items in the stack in order from last-added objects to first (last in, first out). The value returned is the value of the key in the first item that contains the key. If the key is not found in any item in the stack, then the default value is returned. The default value defaults to None. In accordance with the spec, this method queries items in the stack for a key differently depending on whether the item is a hash, object, or neither (as defined in the module docstring): (1) Hash: if the item is a hash, then the key's value is the dictionary value of the key. If the dictionary doesn't contain the key, then the key is considered not found. (2) Object: if the item is an an object, then the method looks for an attribute with the same name as the key. If an attribute with that name exists, the value of the attribute is returned. If the attribute is callable, however (i.e. if the attribute is a method), then the attribute is called with no arguments and that value is returned. If there is no attribute with the same name as the key, then the key is considered not found. (3) Neither: if the item is neither a hash nor an object, then the key is considered not found. *Caution*: Callables are handled differently depending on whether they are dictionary values, as in (1) above, or attributes, as in (2). The former are returned as-is, while the latter are first called and that value returned. Here is an example to illustrate: True 'Hi Bob!' TODO: explain the rationale for this difference in treatment. """
if name == '.': try: return self.top() except IndexError: raise KeyNotFoundError(".", "empty context stack") parts = name.split('.') try: result = self._get_simple(parts[0]) except KeyNotFoundError: raise KeyNotFoundError(name, "first part") for part in parts[1:]: # The full context stack is not used to resolve the remaining parts. # From the spec-- # # 5) If any name parts were retained in step 1, each should be # resolved against a context stack containing only the result # from the former resolution. If any part fails resolution, the # result should be considered falsey, and should interpolate as # the empty string. # # TODO: make sure we have a test case for the above point. result = _get_value(result, part) # TODO: consider using EAFP here instead. # http://docs.python.org/glossary.html#term-eafp if result is _NOT_FOUND: raise KeyNotFoundError(name, "missing %s" % repr(part)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_simple(self, name): """ Query the stack for a non-dotted name. """
for item in reversed(self._stack): result = _get_value(item, name) if result is not _NOT_FOUND: return result raise KeyNotFoundError(name, "part missing")
<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_unicode_soft(self, s): """ Convert a basestring to unicode, preserving any unicode subclass. """
# We type-check to avoid "TypeError: decoding Unicode is not supported". # We avoid the Python ternary operator for Python 2.4 support. if isinstance(s, unicode): return s return self.unicode(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 unicode(self, b, encoding=None): """ Convert a byte string to unicode, using string_encoding and decode_errors. Arguments: b: a byte string. encoding: the name of an encoding. Defaults to the string_encoding attribute for this instance. Raises: TypeError: Because this method calls Python's built-in unicode() function, this method raises the following exception if the given string is already unicode: TypeError: decoding Unicode is not supported """
if encoding is None: encoding = self.string_encoding # TODO: Wrap UnicodeDecodeErrors with a message about setting # the string_encoding and decode_errors attributes. return unicode(b, encoding, self.decode_errors)
<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_loader(self): """ Create a Loader instance using current attributes. """
return Loader(file_encoding=self.file_encoding, extension=self.file_extension, to_unicode=self.unicode, search_dirs=self.search_dirs)
<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_load_template(self): """ Return a function that loads a template by name. """
loader = self._make_loader() def load_template(template_name): return loader.load_name(template_name) return load_template
<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_load_partial(self): """ Return a function that loads a partial by name. """
if self.partials is None: return self._make_load_template() # Otherwise, create a function from the custom partial loader. partials = self.partials def load_partial(name): # TODO: consider using EAFP here instead. # http://docs.python.org/glossary.html#term-eafp # This would mean requiring that the custom partial loader # raise a KeyError on name not found. template = partials.get(name) if template is None: raise TemplateNotFoundError("Name %s not found in partials: %s" % (repr(name), type(partials))) # RenderEngine requires that the return value be unicode. return self._to_unicode_hard(template) return load_partial
<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_missing_tags_strict(self): """ Return whether missing_tags is set to strict. """
val = self.missing_tags if val == MissingTags.strict: return True elif val == MissingTags.ignore: return False raise Exception("Unsupported 'missing_tags' value: %s" % repr(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 _make_render_engine(self): """ Return a RenderEngine instance for rendering. """
resolve_context = self._make_resolve_context() resolve_partial = self._make_resolve_partial() engine = RenderEngine(literal=self._to_unicode_hard, escape=self._escape_to_unicode, resolve_context=resolve_context, resolve_partial=resolve_partial, to_str=self.str_coerce) return engine
<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_object(self, obj, *context, **kwargs): """ Render the template associated with the given object. """
loader = self._make_loader() # TODO: consider an approach that does not require using an if # block here. For example, perhaps this class's loader can be # a SpecLoader in all cases, and the SpecLoader instance can # check the object's type. Or perhaps Loader and SpecLoader # can be refactored to implement the same interface. if isinstance(obj, TemplateSpec): loader = SpecLoader(loader) template = loader.load(obj) else: template = loader.load_object(obj) context = [obj] + list(context) return self._render_string(template, *context, **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 render_name(self, template_name, *context, **kwargs): """ Render the template with the given name using the given context. See the render() docstring for more information. """
loader = self._make_loader() template = loader.load_name(template_name) return self._render_string(template, *context, **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 render_path(self, template_path, *context, **kwargs): """ Render the template at the given path using the given context. Read the render() docstring for more information. """
loader = self._make_loader() template = loader.read(template_path) return self._render_string(template, *context, **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 _render_string(self, template, *context, **kwargs): """ Render the given template string using the given context. """
# RenderEngine.render() requires that the template string be unicode. template = self._to_unicode_hard(template) render_func = lambda engine, stack: engine.render(template, stack) return self._render_final(render_func, *context, **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 render(self, template, *context, **kwargs): """ Render the given template string, view template, or parsed template. Returns a unicode string. Prior to rendering, this method will convert a template that is a byte string (type str in Python 2) to unicode using the string_encoding and decode_errors attributes. See the constructor docstring for more information. Arguments: template: a template string that is unicode or a byte string, a ParsedTemplate instance, or another object instance. In the final case, the function first looks for the template associated to the object by calling this class's get_associated_template() method. The rendering process also uses the passed object as the first element of the context stack when rendering. *context: zero or more dictionaries, ContextStack instances, or objects with which to populate the initial context stack. None arguments are skipped. Items in the *context list are added to the context stack in order so that later items in the argument list take precedence over earlier items. **kwargs: additional key-value data to add to the context stack. As these arguments appear after all items in the *context list, in the case of key conflicts these values take precedence over all items in the *context list. """
if is_string(template): return self._render_string(template, *context, **kwargs) if isinstance(template, ParsedTemplate): render_func = lambda engine, stack: template.render(engine, stack) return self._render_final(render_func, *context, **kwargs) # Otherwise, we assume the template is an object. return self._render_object(template, *context, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(path): """ Read and return the contents of a text file as a unicode string. """
# This function implementation was chosen to be compatible across Python 2/3. f = open(path, 'rb') # We avoid use of the with keyword for Python 2.4 support. try: b = f.read() finally: f.close() return b.decode(FILE_ENCODING)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_html_comments(text): """Strip HTML comments from a unicode string."""
lines = text.splitlines(True) # preserve line endings. # Remove HTML comments (which we only allow to take a special form). new_lines = filter(lambda line: not line.startswith("<!--"), lines) return "".join(new_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 convert_md_to_rst(md_path, rst_temp_path): """ Convert the contents of a file from Markdown to reStructuredText. Returns the converted text as a Unicode string. Arguments: md_path: a path to a UTF-8 encoded Markdown file to convert. rst_temp_path: a temporary path to which to write the converted contents. """
# Pandoc uses the UTF-8 character encoding for both input and output. command = "pandoc --write=rst --output=%s %s" % (rst_temp_path, md_path) print("converting with pandoc: %s to %s\n-->%s" % (md_path, rst_temp_path, command)) if os.path.exists(rst_temp_path): os.remove(rst_temp_path) os.system(command) if not os.path.exists(rst_temp_path): s = ("Error running: %s\n" " Did you install pandoc per the %s docstring?" % (command, __file__)) sys.exit(s) return read(rst_temp_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_object_directory(self, obj): """ Return the directory containing an object's defining class. Returns None if there is no such directory, for example if the class was defined in an interactive Python session, or in a doctest that appears in a text file (rather than a Python file). """
if not hasattr(obj, '__module__'): return None module = sys.modules[obj.__module__] if not hasattr(module, '__file__'): # TODO: add a unit test for this case. return None path = module.__file__ return os.path.dirname(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 make_template_name(self, obj): """ Return the canonical template name for an object instance. This method converts Python-style class names (PEP 8's recommended CamelCase, aka CapWords) to lower_case_with_underscords. Here is an example with code: 'hello_world' """
template_name = obj.__class__.__name__ def repl(match): return '_' + match.group(0).lower() return re.sub('[A-Z]', repl, template_name)[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 make_file_name(self, template_name, template_extension=None): """ Generate and return the file name for the given template name. Arguments: template_extension: defaults to the instance's extension. """
file_name = template_name if template_extension is None: template_extension = self.template_extension if template_extension is not False: file_name += os.path.extsep + template_extension return file_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_path(self, search_dirs, file_name): """ Search for the given file, and return the path. Returns None if the file is not found. """
for dir_path in search_dirs: file_path = os.path.join(dir_path, file_name) if os.path.exists(file_path): return file_path 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 _find_path_required(self, search_dirs, file_name): """ Return the path to a template with the given file name. """
path = self._find_path(search_dirs, file_name) if path is None: raise TemplateNotFoundError('File %s not found in dirs: %s' % (repr(file_name), repr(search_dirs))) 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 find_name(self, template_name, search_dirs): """ Return the path to a template with the given name. Arguments: template_name: the name of the template. search_dirs: the list of directories in which to search. """
file_name = self.make_file_name(template_name) return self._find_path_required(search_dirs, file_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_object(self, obj, search_dirs, file_name=None): """ Return the path to a template associated with the given object. """
if file_name is None: # TODO: should we define a make_file_name() method? template_name = self.make_template_name(obj) file_name = self.make_file_name(template_name) dir_path = self.get_object_directory(obj) if dir_path is not None: search_dirs = [dir_path] + search_dirs path = self._find_path_required(search_dirs, file_name) 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 unicode(self, s, encoding=None): """ Convert a string to unicode using the given encoding, and return it. This function uses the underlying to_unicode attribute. Arguments: s: a basestring instance to convert to unicode. Unlike Python's built-in unicode() function, it is okay to pass unicode strings to this function. (Passing a unicode string to Python's unicode() with the encoding argument throws the error, "TypeError: decoding Unicode is not supported.") encoding: the encoding to pass to the to_unicode attribute. Defaults to None. """
if isinstance(s, unicode): return unicode(s) return self.to_unicode(s, encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, path, encoding=None): """ Read the template at the given path, and return it as a unicode string. """
b = common.read(path) if encoding is None: encoding = self.file_encoding return self.unicode(b, encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_file(self, file_name): """ Find and return the template with the given file name. Arguments: file_name: the file name of the template. """
locator = self._make_locator() path = locator.find_file(file_name, self.search_dirs) return self.read(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 load_name(self, name): """ Find and return the template with the given template name. Arguments: name: the name of the template. """
locator = self._make_locator() path = locator.find_name(name, self.search_dirs) return self.read(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 load_object(self, obj): """ Find and return the template associated to the given object. Arguments: obj: an instance of a user-defined class. search_dirs: the list of directories in which to search. """
locator = self._make_locator() path = locator.find_object(obj, self.search_dirs) return self.read(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 parse(template, delimiters=None): """ Parse a unicode template string and return a ParsedTemplate instance. Arguments: template: a unicode template string. delimiters: a 2-tuple of delimiters. Defaults to the package default. Examples: ['Hey ', _SectionNode(key='who', index_begin=12, index_end=21, parsed=[_EscapeNode(key='name'), '!'])] """
if type(template) is not unicode: raise Exception("Template is not unicode: %s" % type(template)) parser = _Parser(delimiters) return parser.parse(template)
<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, template): """ Parse a template string starting at some index. This method uses the current tag delimiter. Arguments: template: a unicode string that is the template to parse. index: the index at which to start parsing. Returns: a ParsedTemplate instance. """
self._compile_delimiters() start_index = 0 content_end_index, parsed_section, section_key = None, None, None parsed_template = ParsedTemplate() states = [] while True: match = self._template_re.search(template, start_index) if match is None: break match_index = match.start() end_index = match.end() matches = match.groupdict() # Normalize the matches dictionary. if matches['change'] is not None: matches.update(tag='=', tag_key=matches['delims']) elif matches['raw'] is not None: matches.update(tag='&', tag_key=matches['raw_name']) tag_type = matches['tag'] tag_key = matches['tag_key'] leading_whitespace = matches['whitespace'] # Standalone (non-interpolation) tags consume the entire line, # both leading whitespace and trailing newline. did_tag_begin_line = match_index == 0 or template[match_index - 1] in END_OF_LINE_CHARACTERS did_tag_end_line = end_index == len(template) or template[end_index] in END_OF_LINE_CHARACTERS is_tag_interpolating = tag_type in ['', '&'] if did_tag_begin_line and did_tag_end_line and not is_tag_interpolating: if end_index < len(template): end_index += template[end_index] == '\r' and 1 or 0 if end_index < len(template): end_index += template[end_index] == '\n' and 1 or 0 elif leading_whitespace: match_index += len(leading_whitespace) leading_whitespace = '' # Avoid adding spurious empty strings to the parse tree. if start_index != match_index: parsed_template.add(template[start_index:match_index]) start_index = end_index if tag_type in ('#', '^'): # Cache current state. state = (tag_type, end_index, section_key, parsed_template) states.append(state) # Initialize new state section_key, parsed_template = tag_key, ParsedTemplate() continue if tag_type == '/': if tag_key != section_key: raise ParsingError("Section end tag mismatch: %s != %s" % (tag_key, section_key)) # Restore previous state with newly found section data. parsed_section = parsed_template (tag_type, section_start_index, section_key, parsed_template) = states.pop() node = self._make_section_node(template, tag_type, tag_key, parsed_section, section_start_index, match_index) else: node = self._make_interpolation_node(tag_type, tag_key, leading_whitespace) parsed_template.add(node) # Avoid adding spurious empty strings to the parse tree. if start_index != len(template): parsed_template.add(template[start_index:]) return parsed_template
<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_interpolation_node(self, tag_type, tag_key, leading_whitespace): """ Create and return a non-section node for the parse tree. """
# TODO: switch to using a dictionary instead of a bunch of ifs and elifs. if tag_type == '!': return _CommentNode() if tag_type == '=': delimiters = tag_key.split() self._change_delimiters(delimiters) return _ChangeNode(delimiters) if tag_type == '': return _EscapeNode(tag_key) if tag_type == '&': return _LiteralNode(tag_key) if tag_type == '>': return _PartialNode(tag_key, leading_whitespace) raise Exception("Invalid symbol for interpolation tag: %s" % repr(tag_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 _make_section_node(self, template, tag_type, tag_key, parsed_section, section_start_index, section_end_index): """ Create and return a section node for the parse tree. """
if tag_type == '#': return _SectionNode(tag_key, parsed_section, self._delimiters, template, section_start_index, section_end_index) if tag_type == '^': return _InvertedNode(tag_key, parsed_section) raise Exception("Invalid symbol for section tag: %s" % repr(tag_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 _find(self, spec): """ Find and return the path to the template associated to the instance. """
if spec.template_path is not None: return spec.template_path dir_path, file_name = self._find_relative(spec) locator = self.loader._make_locator() if dir_path is None: # Then we need to search for the path. path = locator.find_object(spec, self.loader.search_dirs, file_name=file_name) else: obj_dir = locator.get_object_directory(spec) path = os.path.join(obj_dir, dir_path, file_name) 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 load(self, spec): """ Find and return the template associated to a TemplateSpec instance. Returns the template as a unicode string. Arguments: spec: a TemplateSpec instance. """
if spec.template is not None: return self.loader.unicode(spec.template, spec.template_encoding) path = self._find(spec) return self.loader.read(path, spec.template_encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_string(self, context, name): """ Get a value from the given context as a basestring instance. """
val = self.resolve_context(context, name) if callable(val): # Return because _render_value() is already a string. return self._render_value(val(), context) if not is_string(val): return self.to_str(val) return 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 fetch_section_data(self, context, name): """ Fetch the value of a section as a list. """
data = self.resolve_context(context, name) # From the spec: # # If the data is not of a list type, it is coerced into a list # as follows: if the data is truthy (e.g. `!!data == true`), # use a single-element list containing the data, otherwise use # an empty list. # if not data: data = [] else: # The least brittle way to determine whether something # supports iteration is by trying to call iter() on it: # # http://docs.python.org/library/functions.html#iter # # It is not sufficient, for example, to check whether the item # implements __iter__ () (the iteration protocol). There is # also __getitem__() (the sequence protocol). In Python 2, # strings do not implement __iter__(), but in Python 3 they do. try: iter(data) except TypeError: # Then the value does not support iteration. data = [data] else: if is_string(data) or isinstance(data, dict): # Do not treat strings and dicts (which are iterable) as lists. data = [data] # Otherwise, treat the value as a list. return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render_value(self, val, context, delimiters=None): """ Render an arbitrary value. """
if not is_string(val): # In case the template is an integer, for example. val = self.to_str(val) if type(val) is not unicode: val = self.literal(val) return self.render(val, context, delimiters)
<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(self, template, context_stack, delimiters=None): """ Render a unicode template string, and return as unicode. Arguments: template: a template string of type unicode (but not a proper subclass of unicode). context_stack: a ContextStack instance. """
parsed_template = parse(template, delimiters) return parsed_template.render(self, context_stack)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate(self, script): """ Evaluate script in page frame. :param script: The script to evaluate. """
if WEBENGINE: return self.dom.runJavaScript("{}".format(script)) else: return self.dom.evaluateJavaScript("{}".format(script))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_input_value(self, selector, value): """Set the value of the input matched by given selector."""
script = 'document.querySelector("%s").setAttribute("value", "%s")' script = script % (selector, value) self.evaluate(script)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Simple test."""
from spyder.utils.qthelpers import qapplication app = qapplication() widget = NotebookClient(plugin=None, name='') widget.show() widget.set_url('http://google.com') sys.exit(app.exec_())