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 hoist_event(self, e):
""" Hoist an xcb_generic_event_t to the right xcffib structure. """ |
if e.response_type == 0:
return self._process_error(ffi.cast("xcb_generic_error_t *", e))
# We mask off the high bit here because events sent with SendEvent have
# this bit set. We don't actually care where the event came from, so we
# just throw this away. Maybe we could e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self, value, greedy=True):
""" Greedy serialization requires the value to either be a column or convertible to a column, whereas non-greedy seriali... |
if greedy and not isinstance(value, Column):
value = self.normalize(value)
if isinstance(value, Column):
return value.id
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 describe(profile, description):
""" Generate a query by describing it as a series of actions and parameters to those actions. These map directly to Query met... |
api_type = description.pop('type', 'core')
api = getattr(profile, api_type)
return refine(api.query, description) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refine(query, description):
""" Refine a query from a dictionary of parameters that describes it. See `describe` for more information. """ |
for attribute, arguments in description.items():
if hasattr(query, attribute):
attribute = getattr(query, attribute)
else:
raise ValueError("Unknown query method: " + attribute)
# query descriptions are often automatically generated, and
# may include empty... |
<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(self, key=None, value=None, **kwargs):
""" `set` is a way to add raw properties to the request, for features that this module does not support or support... |
serialize = partial(self.api.columns.serialize, greedy=False)
if key and value:
self.raw[key] = serialize(value)
elif key or kwargs:
properties = key or kwargs
for key, value in properties.items():
self.raw[key] = serialize(value)
el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def description(self):
""" A list of the metrics this query will ask for. """ |
if 'metrics' in self.raw:
metrics = self.raw['metrics']
head = metrics[0:-1] or metrics[0:1]
text = ", ".join(head)
if len(metrics) > 1:
tail = metrics[-1]
text = text + " and " + tail
else:
text = 'n/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 sort(self, *columns, **options):
""" Return a new query which will produce results sorted by one or more metrics or dimensions. You may use plain strings for... |
sorts = self.meta.setdefault('sort', [])
for column in columns:
if isinstance(column, Column):
identifier = column.id
elif isinstance(column, utils.basestring):
descending = column.startswith('-') or options.get('descending', 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 filter(self, value=None, exclude=False, **selection):
""" Most of the actual functionality lives on the Column object and the `all` and `any` functions. """ |
filters = self.meta.setdefault('filters', [])
if value and len(selection):
raise ValueError("Cannot specify a filter string and a filter keyword selection at the same time.")
elif value:
value = [value]
elif len(selection):
value = select(self.api.co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def range(self, start=None, stop=None, months=0, days=0):
""" Return a new query that fetches metrics within a certain date range. ```python query.range('2014-01... |
start, stop = utils.date.range(start, stop, months, days)
self.raw.update({
'start_date': start,
'end_date': stop,
})
return 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 segment(self, value=None, scope=None, metric_scope=None, **selection):
""" Return a new query, limited to a segment of all users or sessions. Accepts segment... |
"""
Technical note to self about segments:
* users or sessions
* sequence or condition
* scope (perHit, perSession, perUser -- gte primary scope)
Multiple conditions can be ANDed or ORed together; these two are equivalent
users::condition::ga:revenue>10;g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next(self):
""" Return a new query with a modified `start_index`. Mainly used internally to paginate through results. """ |
step = self.raw.get('max_results', 1000)
start = self.raw.get('start_index', 1) + step
self.raw['start_index'] = start
return 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 get(self):
""" Run the query and return a `Report`. This method transparently handles paginated results, so even for results that are larger than the maximum... |
cursor = self
report = None
is_complete = False
is_enough = False
while not (is_enough or is_complete):
chunk = cursor.execute()
if report:
report.append(chunk.raw[0], cursor)
else:
report = chunk
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def valid(self):
""" Valid credentials are not necessarily correct, but they contain all necessary information for an authentication attempt. """ |
two_legged = self.client_email and self.private_key
three_legged = self.client_id and self.client_secret
return two_legged or three_legged or 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 complete(self):
""" Complete credentials are valid and are either two-legged or include a token. """ |
return self.valid and (self.access_token or self.refresh_token or self.type == 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 revoke(client_id, client_secret, client_email=None, private_key=None, access_token=None, refresh_token=None, identity=None, prefix=None, suffix=None):
""" Gi... |
if client_email and private_key:
raise ValueError('Two-legged OAuth does not use revokable tokens.')
credentials = oauth.Credentials.find(
complete=True,
interactive=False,
identity=identity,
client_id=client_id,
client_secret=client_secret,
access_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vectorize(fn):
""" Allows a method to accept one or more values, but internally deal only with a single item, and returning a list or a single item depending... |
@functools.wraps(fn)
def vectorized_method(self, values, *vargs, **kwargs):
wrap = not isinstance(values, (list, tuple))
should_unwrap = not kwargs.setdefault('wrap', False)
unwrap = wrap and should_unwrap
del kwargs['wrap']
if wrap:
values = [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 webproperties(self):
""" A list of all web properties on this account. You may select a specific web property using its name, its id or an index. ```python a... |
raw_properties = self.service.management().webproperties().list(
accountId=self.id).execute()['items']
_webproperties = [WebProperty(raw, self) for raw in raw_properties]
return addressable.List(_webproperties, indices=['id', 'name'], insensitive=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 profiles(self):
""" A list of all profiles on this web property. You may select a specific profile using its name, its id or an index. ```python property.pro... |
raw_profiles = self.account.service.management().profiles().list(
accountId=self.account.id,
webPropertyId=self.id).execute()['items']
profiles = [Profile(raw, self) for raw in raw_profiles]
return addressable.List(profiles, indices=['id', 'name'], insensitive=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 check_output_input(*popenargs, **kwargs):
"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a Cal... |
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
if 'input' in kwargs:
if 'stdin' in kwargs:
raise ValueError('stdin and input arguments may not both be used.')
inputdata = kwargs['input']
del kwargs['input']
kwar... |
<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_token_indices(self, tokens):
"""If `apply_encoding_options` is inadequate, one can retrieve tokens from `self.token_counts`, filter with a desired str... |
start_index = len(self.special_token)
indices = list(range(len(tokens) + start_index))
# prepend because the special tokens come in the beginning
tokens_with_special = self.special_token + list(tokens)
self._token2idx = dict(list(zip(tokens_with_special, indices)))
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 apply_encoding_options(self, min_token_count=1, limit_top_tokens=None):
"""Applies the given settings for subsequent calls to `encode_texts` and `decode_text... |
if not self.has_vocab:
raise ValueError("You need to build the vocabulary using `build_vocab` "
"before using `apply_encoding_options`")
if min_token_count < 1:
raise ValueError("`min_token_count` should atleast be 1")
# Remove tokens with f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_texts(self, texts, unknown_token="<UNK>", verbose=1, **kwargs):
"""Encodes the given texts using internal vocabulary with optionally applied encoding ... |
if not self.has_vocab:
raise ValueError(
"You need to build the vocabulary using `build_vocab` before using `encode_texts`")
if unknown_token and unknown_token not in self.special_token:
raise ValueError(
"Your special token (" + unknown_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 decode_texts(self, encoded_texts, unknown_token="<UNK>", inplace=True):
"""Decodes the texts using internal vocabulary. The list structure is maintained. Arg... |
if len(self._token2idx) == 0:
raise ValueError(
"You need to build vocabulary using `build_vocab` before using `decode_texts`")
if not isinstance(encoded_texts, list):
# assume it's a numpy array
encoded_texts = encoded_texts.tolist()
if not... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_vocab(self, texts, verbose=1, **kwargs):
"""Builds the internal vocabulary and computes various statistics. Args: texts: The list of text items to enco... |
if self.has_vocab:
logger.warn(
"Tokenizer already has existing vocabulary. Overriding and building new vocabulary.")
progbar = Progbar(len(texts), verbose=verbose, interval=0.25)
count_tracker = utils._CountTracker()
self._token_counts.clear()
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 build_embedding_weights(word_index, embeddings_index):
"""Builds an embedding matrix for all words in vocab using embeddings_index """ |
logger.info('Loading embeddings for all words in the corpus')
embedding_dim = list(embeddings_index.values())[0].shape[-1]
# setting special tokens such as UNK and PAD to 0
# all other words are also set to 0.
embedding_weights = np.zeros((len(word_index), embedding_dim))
for word, i in word_... |
<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_embeddings_index(embedding_type='glove.42B.300d', embedding_dims=None, embedding_path=None, cache=True):
"""Retrieves embeddings index from embedding nam... |
if embedding_path is not None:
embedding_type = embedding_path # identify embedding by path
embeddings_index = _EMBEDDINGS_CACHE.get(embedding_type)
if embeddings_index is not None:
return embeddings_index
if embedding_path is None:
embedding_type_obj = get_embedding_type(em... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def equal_distribution_folds(y, folds=2):
"""Creates `folds` number of indices that has roughly balanced multi-label distribution. Args: y: The multi-label outpu... |
n, classes = y.shape
# Compute sample distribution over classes
dist = y.sum(axis=0).astype('float')
dist /= dist.sum()
index_list = []
fold_dist = np.zeros((folds, classes), dtype='float')
for _ in range(folds):
index_list.append([])
for i in range(n):
if i < folds:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_model(self, token_encoder_model, sentence_encoder_model, trainable_embeddings=True, output_activation='softmax'):
"""Builds a model that first encodes ... |
if not isinstance(token_encoder_model, SequenceEncoderBase):
raise ValueError("`token_encoder_model` should be an instance of `{}`".format(
SequenceEncoderBase))
if not isinstance(sentence_encoder_model, SequenceEncoderBase):
raise ValueError("`sentence_encoder_m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_save(X, y, tokenizer, proc_data_path, max_len=400, train=False, ngrams=None, limit_top_tokens=None):
"""Process text and save as Dataset """ |
if train and limit_top_tokens is not None:
tokenizer.apply_encoding_options(limit_top_tokens=limit_top_tokens)
X_encoded = tokenizer.encode_texts(X)
if ngrams is not None:
X_encoded = tokenizer.add_ngrams(X_encoded, n=ngrams, train=train)
X_padded = tokenizer.pad_sequences(
X... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_data(X, y, ratio=(0.8, 0.1, 0.1)):
"""Splits data into a training, validation, and test set. Args: X: text data y: data labels ratio: the ratio for spl... |
assert(sum(ratio) == 1 and len(ratio) == 3)
X_train, X_rest, y_train, y_rest = train_test_split(
X, y, train_size=ratio[0])
X_val, X_test, y_val, y_test = train_test_split(
X_rest, y_rest, train_size=ratio[1])
return X_train, X_val, X_test, y_train, y_val, y_test |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_data_split(X, y, tokenizer, proc_data_dir, **kwargs):
"""Setup data while splitting into a training, validation, and test set. Args: X: text data, y: d... |
X_train, X_val, X_test, y_train, y_val, y_test = split_data(X, y)
# only build vocabulary on training data
tokenizer.build_vocab(X_train)
process_save(X_train, y_train, tokenizer, path.join(
proc_data_dir, 'train.bin'), train=True, **kwargs)
process_save(X_val, y_val, tokenizer, path.join... |
<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_data_split(proc_data_dir):
"""Loads a split dataset Args: proc_data_dir: Directory with the split and processed data Returns: (Training Data, Validation... |
ds_train = Dataset.load(path.join(proc_data_dir, 'train.bin'))
ds_val = Dataset.load(path.join(proc_data_dir, 'val.bin'))
ds_test = Dataset.load(path.join(proc_data_dir, 'test.bin'))
return ds_train, ds_val, ds_test |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_model(self, token_encoder_model, trainable_embeddings=True, output_activation='softmax'):
"""Builds a model using the given `text_model` Args: token_en... |
if not isinstance(token_encoder_model, SequenceEncoderBase):
raise ValueError("`token_encoder_model` should be an instance of `{}`".format(
SequenceEncoderBase))
if not token_encoder_model.allows_dynamic_length() and self.max_tokens is None:
raise ValueError("Th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _softmax(x, dim):
"""Computes softmax along a specified dim. Keras currently lacks this feature. """ |
if K.backend() == 'tensorflow':
import tensorflow as tf
return tf.nn.softmax(x, dim)
elif K.backend() is 'cntk':
import cntk
return cntk.softmax(x, dim)
elif K.backend() == 'theano':
# Theano cannot softmax along an arbitrary dim.
# So, we will shuffle `dim`... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _apply_options(self, token):
"""Applies various filtering and processing options on token. Returns: The processed token. None if filtered. """ |
# Apply work token filtering.
if token.is_punct and self.remove_punct:
return None
if token.is_stop and self.remove_stop_words:
return None
if token.is_digit and self.remove_digits:
return None
if token.is_oov and self.exclude_oov:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _append(lst, indices, value):
"""Adds `value` to `lst` list indexed by `indices`. Will create sub lists as required. """ |
for i, idx in enumerate(indices):
# We need to loop because sometimes indices can increment by more than 1 due to missing tokens.
# Example: Sentence with no words after filtering words.
while len(lst) <= idx:
# Update max counts whenever a new sublist is created.
# ... |
<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(self, indices):
"""Updates counts based on indices. The algorithm tracks the index change at i and update global counts for all indices beyond i with ... |
# Initialize various lists for the first time based on length of indices.
if self._prev_indices is None:
self._prev_indices = indices
# +1 to track token counts in the last index.
self._local_counts = np.full(len(indices) + 1, 1)
self._local_counts[-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 read_folder(directory):
"""read text files in directory and returns them as array Args: directory: where the text files are Returns: Array of text """ |
res = []
for filename in os.listdir(directory):
with io.open(os.path.join(directory, filename), encoding="utf-8") as f:
content = f.read()
res.append(content)
return res |
<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_pos_neg_data(path, folder, limit):
"""returns array with positive and negative examples""" |
training_pos_path = os.path.join(path, folder, 'pos')
training_neg_path = os.path.join(path, folder, 'neg')
X_pos = read_folder(training_pos_path)
X_neg = read_folder(training_neg_path)
if limit is None:
X = X_pos + X_neg
else:
X = X_pos[:limit] + X_neg[:limit]
y = [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 set_value(self, number: (float, int)):
""" Sets the value of the graphic :param number: the number (must be between 0 and \ 'max_range' or the scale will peg... |
self.canvas.delete('all')
self.canvas.create_image(0, 0, image=self.image, anchor='nw')
number = number if number <= self.max_value else self.max_value
number = 0.0 if number < 0.0 else number
radius = 0.9 * self.size/2.0
angle_in_radians = (2.0 * cmath.pi / 3.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 _draw_background(self, divisions=10):
""" Draws the background of the dial :param divisions: the number of divisions between 'ticks' shown on the dial :retur... |
self.canvas.create_arc(2, 2, self.size-2, self.size-2,
style=tk.PIESLICE, start=-60, extent=30,
fill='red')
self.canvas.create_arc(2, 2, self.size-2, self.size-2,
style=tk.PIESLICE, start=-30, extent=60,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_axes(self):
""" Removes all existing series and re-draws the axes. :return: None """ |
self.canvas.delete('all')
rect = 50, 50, self.w - 50, self.h - 50
self.canvas.create_rectangle(rect, outline="black")
for x in self.frange(0, self.x_max - self.x_min + 1, self.x_tick):
value = Decimal(self.x_min + x)
if self.x_min <= value <= self.x_max:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_point(self, x, y, visible=True, color='black', size=5):
""" Places a single point on the grid :param x: the x coordinate :param y: the y coordinate :par... |
xp = (self.px_x * (x - self.x_min)) / self.x_tick
yp = (self.px_y * (self.y_max - y)) / self.y_tick
coord = 50 + xp, 50 + yp
if visible:
# divide down to an appropriate size
size = int(size/2) if int(size/2) > 1 else 1
x, y = coord
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 plot_line(self, points: list, color='black', point_visibility=False):
""" Plot a line of points :param points: a list of tuples, each tuple containing an (x,... |
last_point = ()
for point in points:
this_point = self.plot_point(point[0], point[1],
color=color, visible=point_visibility)
if last_point:
self.canvas.create_line(last_point + this_point, fill=color)
last_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 frange(start, stop, step, digits_to_round=3):
""" Works like range for doubles :param start: starting value :param stop: ending value :param step: the increm... |
while start < stop:
yield round(start, digits_to_round)
start += 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 _load_new(self, img_data: str):
""" Load a new image. :param img_data: the image data as a base64 string :return: None """ |
self._image = tk.PhotoImage(data=img_data)
self._image = self._image.subsample(int(200 / self._size),
int(200 / self._size))
self._canvas.delete('all')
self._canvas.create_image(0, 0, image=self._image, anchor='nw')
if self._user_clic... |
<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_grey(self, on: bool=False):
""" Change the LED to grey. :param on: Unused, here for API consistency with the other states :return: None """ |
self._on = False
self._load_new(led_grey) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _redraw(self):
""" Forgets the current layout and redraws with the most recent information :return: None """ |
for row in self._rows:
for widget in row:
widget.grid_forget()
offset = 0 if not self.headers else 1
for i, row in enumerate(self._rows):
for j, widget in enumerate(row):
widget.grid(row=i+offset, column=j) |
<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_row(self, row_number: int=-1):
""" Removes a specified row of data :param row_number: the row to remove (defaults to the last row) :return: None """ |
if len(self._rows) == 0:
return
row = self._rows.pop(row_number)
for widget in row:
widget.destroy() |
<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_row(self, data: list):
""" Add a row of data to the current widget :param data: a row of data :return: None """ |
# validation
if self.headers:
if len(self.headers) != len(data):
raise ValueError
if len(data) != self.num_of_columns:
raise ValueError
offset = 0 if not self.headers else 1
row = list()
for i, element in enumerate(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 _read_as_dict(self):
""" Read the data contained in all entries as a list of dictionaries with the headers as the dictionary keys :return: list of dicts cont... |
data = list()
for row in self._rows:
row_data = OrderedDict()
for i, header in enumerate(self.headers):
row_data[header.cget('text')] = row[i].get()
data.append(row_data)
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 _read_as_table(self):
""" Read the data contained in all entries as a list of lists containing all of the data :return: list of dicts containing all tabular ... |
rows = list()
for row in self._rows:
rows.append([row[i].get() for i in range(self.num_of_columns)])
return rows |
<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_row(self, key: str, default: str=None, unit_label: str=None, enable: bool=None):
""" Add a single row and re-draw as necessary :param key: the name and d... |
self.keys.append(ttk.Label(self, text=key))
self.defaults.append(default)
self.unit_labels.append(
ttk.Label(self, text=unit_label if unit_label else '')
)
self.enables.append(enable)
self.values.append(ttk.Entry(self))
row_offset = 1 if self.title ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
""" Clears all entries. :return: None """ |
for i in range(len(self.values)):
self.values[i].delete(0, tk.END)
if self.defaults[i] is not None:
self.values[i].insert(0, self.defaults[i]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self):
""" Retrieve the GUI elements for program use. :return: a dictionary containing all \ of the data from the key/value entries """ |
data = dict()
for label, entry in zip(self.keys, self.values):
data[label.cget('text')] = entry.get()
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 add(self, string: (str, list)):
""" Clear the contents of the entry field and insert the contents of string. :param string: an str containing the text to dis... |
if len(self._entries) == 1:
self._entries[0].delete(0, 'end')
self._entries[0].insert(0, string)
else:
if len(string) != len(self._entries):
raise ValueError('the "string" list must be '
'equal to the number of entries... |
<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_callback(self, callback: callable):
""" Add a callback on change :param callback: callable function :return: None """ |
def internal_callback(*args):
try:
callback()
except TypeError:
callback(self.get())
self._var.trace('w', internal_callback) |
<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(self, value: int):
""" Set the current value :param value: :return: None """ |
max_value = int(''.join(['1' for _ in range(self._bit_width)]), 2)
if value > max_value:
raise ValueError('the value {} is larger than '
'the maximum value {}'.format(value, max_value))
self._value = value
self._text_update() |
<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_bit(self, position: int):
""" Returns the bit value at position :param position: integer between 0 and <width>, inclusive :return: the value at position ... |
if position > (self._bit_width - 1):
raise ValueError('position greater than the bit width')
if self._value & (1 << position):
return 1
else:
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 toggle_bit(self, position: int):
""" Toggles the value at position :param position: integer between 0 and 7, inclusive :return: None """ |
if position > (self._bit_width - 1):
raise ValueError('position greater than the bit width')
self._value ^= (1 << position)
self._text_update() |
<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_bit(self, position: int):
""" Sets the value at position :param position: integer between 0 and 7, inclusive :return: None """ |
if position > (self._bit_width - 1):
raise ValueError('position greater than the bit width')
self._value |= (1 << position)
self._text_update() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_bit(self, position: int):
""" Clears the value at position :param position: integer between 0 and 7, inclusive :return: None """ |
if position > (self._bit_width - 1):
raise ValueError('position greater than the bit width')
self._value &= ~(1 << position)
self._text_update() |
<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_admin(admin_site, model, admin_class):
""" Register model in the admin, ignoring any previously registered models. Alternatively it could be used i... |
try:
admin_site.register(model, admin_class)
except admin.sites.AlreadyRegistered:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _monkey_inline(model, admin_class_instance, metadata_class, inline_class, admin_site):
""" Monkey patch the inline onto the given admin_class instance. """ |
if model in metadata_class._meta.seo_models:
# *Not* adding to the class attribute "inlines", as this will affect
# all instances from this class. Explicitly adding to instance attribute.
admin_class_instance.__dict__['inlines'] = admin_class_instance.inlines + [inline_class]
# Bec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _with_inline(func, admin_site, metadata_class, inline_class):
""" Decorator for register function that adds an appropriate inline.""" |
def register(model_or_iterable, admin_class=None, **options):
# Call the (bound) function we were given.
# We have to assume it will be bound to admin_site
func(model_or_iterable, admin_class, **options)
_monkey_inline(model_or_iterable, admin_site._registry[model_or_iterable], ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auto_register_inlines(admin_site, metadata_class):
""" This is a questionable function that automatically adds our metadata inline to all relevant models in ... |
inline_class = get_inline(metadata_class)
for model, admin_class_instance in admin_site._registry.items():
_monkey_inline(model, admin_class_instance, metadata_class, inline_class, admin_site)
# Monkey patch the register method to automatically add an inline for this site.
# _with_inline() is... |
<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_linked_metadata(obj, name=None, context=None, site=None, language=None):
""" Gets metadata linked from the given object. """ |
# XXX Check that 'modelinstance' and 'model' metadata are installed in backends
# I believe that get_model() would return None if not
Metadata = _get_metadata_model(name)
InstanceMetadata = Metadata._meta.get_model('modelinstance')
ModelMetadata = Metadata._meta.get_model('model')
content_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 __instances(self):
""" Cache instances, allowing generators to be used and reused. This fills a cache as the generator gets emptied, eventually reading exclu... |
for instance in self.__instances_cache:
yield instance
for instance in self.__instances_original:
self.__instances_cache.append(instance)
yield instance |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resolve_value(self, name):
""" Returns an appropriate value for the given name. This simply asks each of the instances for a value. """ |
for instance in self.__instances():
value = instance._resolve_value(name)
if value:
return value
# Otherwise, return an appropriate default value (populate_from)
# TODO: This is duplicated in meta_models. Move this to a common home.
if name in se... |
<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_formatted_data(cls, path, context=None, site=None, language=None):
""" Return an object to conveniently access the appropriate values. """ |
return FormattedMetadata(cls(), cls._get_instances(path, context, site, language), path, site, language) |
<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(options):
""" Validates the application of this backend to a given metadata """ |
try:
if options.backends.index('modelinstance') > options.backends.index('model'):
raise Exception("Metadata backend 'modelinstance' must come before 'model' backend")
except ValueError:
raise Exception("Metadata backend 'modelinstance' must be installed in order... |
<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_elements(self, elements):
""" Takes elements from the metadata class and creates a base model for all backend models . """ |
self.elements = elements
for key, obj in elements.items():
obj.contribute_to_class(self.metadata, key)
# Create the common Django fields
fields = {}
for key, obj in elements.items():
if obj.editable:
field = obj.get_field()
... |
<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_backend(self, backend):
""" Builds a subclass model for the given backend """ |
md_type = backend.verbose_name
base = backend().get_model(self)
# TODO: Rename this field
new_md_attrs = {'_metadata': self.metadata, '__module__': __name__ }
new_md_meta = {}
new_md_meta['verbose_name'] = '%s (%s)' % (self.verbose_name, md_type)
new_md_meta['ve... |
<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(self):
""" Discover certain illegal configurations """ |
if not self.editable:
assert self.populate_from is not NotSet, u"If field (%s) is not editable, you must set populate_from" % self.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 populate_all_metadata():
""" Create metadata instances for all models in seo_models if empty. Once you have created a single metadata instance, this will not... |
for Metadata in registry.values():
InstanceMetadata = Metadata._meta.get_model('modelinstance')
if InstanceMetadata is not None:
for model in Metadata._meta.seo_models:
populate_metadata(model, InstanceMetadata) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populate(self):
""" Populate this list with all views that take no arguments. """ |
from django.conf import settings
from django.core import urlresolvers
self.append(("", ""))
urlconf = settings.ROOT_URLCONF
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
# Collect base level views
for key, value in resolver.reverse_dict.items():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def block_splitter(data, block_size):
""" Creates a generator by slicing ``data`` into chunks of ``block_size``. [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]] If ``da... |
buf = []
for i, datum in enumerate(data):
buf.append(datum)
if len(buf) == block_size:
yield buf
buf = []
# If there's anything leftover (a partial block),
# yield it as well.
if buf:
yield buf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def round_geom(geom, precision=None):
"""Round coordinates of a geometric object to given precision.""" |
if geom['type'] == 'Point':
x, y = geom['coordinates']
xp, yp = [x], [y]
if precision is not None:
xp = [round(v, precision) for v in xp]
yp = [round(v, precision) for v in yp]
new_coords = tuple(zip(xp, yp))[0]
if geom['type'] in ['LineString', 'MultiPoi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(input, verbose, quiet, output_format, precision, indent):
"""Convert text read from the first positional argument, stdin, or a file to GeoJSON and write ... |
verbosity = verbose - quiet
configure_logging(verbosity)
logger = logging.getLogger('geomet')
# Handle the case of file, stream, or string input.
try:
src = click.open_file(input).readlines()
except IOError:
src = [input]
stdout = click.get_text_stream('stdout')
# Re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_geom_type(type_bytes):
"""Get the GeoJSON geometry type label from a WKB type byte string. :param type_bytes: 4 byte string in big endian byte order con... |
# slice off the high byte, which may contain the SRID flag
high_byte = type_bytes[0]
if six.PY3:
high_byte = bytes([high_byte])
has_srid = high_byte == b'\x20'
if has_srid:
# replace the high byte with a null byte
type_bytes = as_bin_str(b'\x00' + type_bytes[1:])
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dumps(obj, big_endian=True):
""" Dump a GeoJSON-like `dict` to a WKB string. .. note:: The dimensions of the generated WKB will be inferred from the first ve... |
geom_type = obj['type']
meta = obj.get('meta', {})
exporter = _dumps_registry.get(geom_type)
if exporter is None:
_unsupported_geom_type(geom_type)
# Check for empty geometries. GeometryCollections have a slightly different
# JSON/dict structure, but that's handled.
coords_or_geom... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dump_point(obj, big_endian, meta):
""" Dump a GeoJSON-like `dict` to a point WKB string. :param dict obj: GeoJson-like `dict` object. :param bool big_endian... |
coords = obj['coordinates']
num_dims = len(coords)
wkb_string, byte_fmt, _ = _header_bytefmt_byteorder(
'Point', num_dims, big_endian, meta
)
wkb_string += struct.pack(byte_fmt, *coords)
return wkb_string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dump_linestring(obj, big_endian, meta):
""" Dump a GeoJSON-like `dict` to a linestring WKB string. Input parameters and output are similar to :func:`_dump_p... |
coords = obj['coordinates']
vertex = coords[0]
# Infer the number of dimensions from the first vertex
num_dims = len(vertex)
wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(
'LineString', num_dims, big_endian, meta
)
# append number of vertices in linestring
wkb_st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dump_multipoint(obj, big_endian, meta):
""" Dump a GeoJSON-like `dict` to a multipoint WKB string. Input parameters and output are similar to :funct:`_dump_... |
coords = obj['coordinates']
vertex = coords[0]
num_dims = len(vertex)
wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(
'MultiPoint', num_dims, big_endian, meta
)
point_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['Point']
if big_endian:
point_type = BIG_ENDIAN... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dump_multilinestring(obj, big_endian, meta):
""" Dump a GeoJSON-like `dict` to a multilinestring WKB string. Input parameters and output are similar to :fun... |
coords = obj['coordinates']
vertex = coords[0][0]
num_dims = len(vertex)
wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(
'MultiLineString', num_dims, big_endian, meta
)
ls_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['LineString']
if big_endian:
ls_type = BIG... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dump_multipolygon(obj, big_endian, meta):
""" Dump a GeoJSON-like `dict` to a multipolygon WKB string. Input parameters and output are similar to :funct:`_d... |
coords = obj['coordinates']
vertex = coords[0][0][0]
num_dims = len(vertex)
wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(
'MultiPolygon', num_dims, big_endian, meta
)
poly_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['Polygon']
if big_endian:
poly_type = BI... |
<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_point(big_endian, type_bytes, data_bytes):
""" Convert byte data for a Point to a GeoJSON `dict`. :param bool big_endian: If `True`, interpret the ``da... |
endian_token = '>' if big_endian else '<'
if type_bytes == WKB_2D['Point']:
coords = struct.unpack('%sdd' % endian_token,
as_bin_str(take(16, data_bytes)))
elif type_bytes == WKB_Z['Point']:
coords = struct.unpack('%sddd' % endian_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 dumps(obj, decimals=16):
""" Dump a GeoJSON-like `dict` to a WKT string. """ |
try:
geom_type = obj['type']
exporter = _dumps_registry.get(geom_type)
if exporter is None:
_unsupported_geom_type(geom_type)
# Check for empty cases
if geom_type == 'GeometryCollection':
if len(obj['geometries']) == 0:
return 'GEOME... |
<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_wkt(tokens):
""" Since the tokenizer treats "-" and numeric strings as separate values, combine them and yield them as a single token. This utility... |
negative = False
for t in tokens:
if t == '-':
negative = True
continue
else:
if negative:
yield '-%s' % t
else:
yield t
negative = 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 _round_and_pad(value, decimals):
""" Round the input value to `decimals` places, and pad with 0's if the resulting value is less than `decimals`. :param valu... |
if isinstance(value, int) and decimals != 0:
# if we get an int coordinate and we have a non-zero value for
# `decimals`, we want to create a float to pad out.
value = float(value)
elif decimals == 0:
# if get a `decimals` value of 0, we want to return an int.
return re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dump_point(obj, decimals):
""" Dump a GeoJSON-like Point object to WKT. :param dict obj: A GeoJSON-like `dict` representing a Point. :param int decimals: in... |
coords = obj['coordinates']
pt = 'POINT (%s)' % ' '.join(_round_and_pad(c, decimals)
for c in coords)
return pt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dump_linestring(obj, decimals):
""" Dump a GeoJSON-like LineString object to WKT. Input parameters and return value are the LINESTRING equivalent to :func:`... |
coords = obj['coordinates']
ls = 'LINESTRING (%s)'
ls %= ', '.join(' '.join(_round_and_pad(c, decimals)
for c in pt) for pt in coords)
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 _dump_polygon(obj, decimals):
""" Dump a GeoJSON-like Polygon object to WKT. Input parameters and return value are the POLYGON equivalent to :func:`_dump_poi... |
coords = obj['coordinates']
poly = 'POLYGON (%s)'
rings = (', '.join(' '.join(_round_and_pad(c, decimals)
for c in pt) for pt in ring)
for ring in coords)
rings = ('(%s)' % r for r in rings)
poly %= ', '.join(rings)
return poly |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dump_multipoint(obj, decimals):
""" Dump a GeoJSON-like MultiPoint object to WKT. Input parameters and return value are the MULTIPOINT equivalent to :func:`... |
coords = obj['coordinates']
mp = 'MULTIPOINT (%s)'
points = (' '.join(_round_and_pad(c, decimals)
for c in pt) for pt in coords)
# Add parens around each point.
points = ('(%s)' % pt for pt in points)
mp %= ', '.join(points)
return mp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dump_multilinestring(obj, decimals):
""" Dump a GeoJSON-like MultiLineString object to WKT. Input parameters and return value are the MULTILINESTRING equiva... |
coords = obj['coordinates']
mlls = 'MULTILINESTRING (%s)'
linestrs = ('(%s)' % ', '.join(' '.join(_round_and_pad(c, decimals)
for c in pt) for pt in linestr) for linestr in coords)
mlls %= ', '.join(ls for ls in linestrs)
return mlls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dump_multipolygon(obj, decimals):
""" Dump a GeoJSON-like MultiPolygon object to WKT. Input parameters and return value are the MULTIPOLYGON equivalent to :... |
coords = obj['coordinates']
mp = 'MULTIPOLYGON (%s)'
polys = (
# join the polygons in the multipolygon
', '.join(
# join the rings in a polygon,
# and wrap in parens
'(%s)' % ', '.join(
# join the points in a ring,
# and w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dump_geometrycollection(obj, decimals):
""" Dump a GeoJSON-like GeometryCollection object to WKT. Input parameters and return value are the GEOMETRYCOLLECTI... |
gc = 'GEOMETRYCOLLECTION (%s)'
geoms = obj['geometries']
geoms_wkt = []
for geom in geoms:
geom_type = geom['type']
geoms_wkt.append(_dumps_registry.get(geom_type)(geom, decimals))
gc %= ','.join(geoms_wkt)
return gc |
<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_params(self, **kwargs):
"""Merge shared params and new params.""" |
request_params = copy.deepcopy(self._shared_request_params)
for key, value in iteritems(kwargs):
if isinstance(value, dict) and key in request_params:
# ensure we don't lose dict values like headers or cookies
request_params[key].update(value)
els... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sanitize_request_params(self, request_params):
"""Remove keyword arguments not used by `requests`""" |
if 'verify_ssl' in request_params:
request_params['verify'] = request_params.pop('verify_ssl')
return dict((key, val) for key, val in request_params.items()
if key in self._VALID_REQUEST_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 pre_send(self, request_params):
"""Override this method to modify sent request parameters""" |
for adapter in itervalues(self.adapters):
adapter.max_retries = request_params.get('max_retries', 0)
return request_params |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.