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 create(self, password, username, realm=None):
""" Creates a storage password. A `StoragePassword` can be identified by <username>, or by <realm>:<username> if the optional realm parameter is also provided. :param password: The password for the credentials - this is the only part of the credentials that will be stored securely. :type name: ``string`` :param username: The username for the credentials. :type name: ``string`` :param realm: The credential realm. (optional) :type name: ``string`` :return: The :class:`StoragePassword` object created. """ |
if not isinstance(username, basestring):
raise ValueError("Invalid name: %s" % repr(username))
if realm is None:
response = self.post(password=password, name=username)
else:
response = self.post(password=password, realm=realm, name=username)
if response.status != 201:
raise ValueError("Unexpected status code %s returned from creating a stanza" % response.status)
entries = _load_atom_entries(response)
state = _parse_atom_entry(entries[0])
storage_password = StoragePassword(self.service, self._entity_path(state), state=state, skip_refresh=True)
return storage_password |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, username, password, roles, **params):
"""Creates a new user. This function makes two roundtrips to the server, plus at most two more if the ``autologin`` field of :func:`connect` is set to ``True``. :param username: The username. :type username: ``string`` :param password: The password. :type password: ``string`` :param roles: A single role or list of roles for the user. :type roles: ``string`` or ``list`` :param params: Additional arguments (optional). For a list of available parameters, see `User authentication parameters <http://dev.splunk.com/view/SP-CAAAEJ6#userauthparams>`_ on Splunk Developer Portal. :type params: ``dict`` :return: The new user. :rtype: :class:`User` **Example**:: import splunklib.client as client users = c.users boris = users.create("boris", "securepassword", roles="user") hilda = users.create("hilda", "anotherpassword", roles=["user","power"]) """ |
if not isinstance(username, basestring):
raise ValueError("Invalid username: %s" % str(username))
username = username.lower()
self.post(name=username, password=password, roles=roles, **params)
# splunkd doesn't return the user in the POST response body,
# so we have to make a second round trip to fetch it.
response = self.get(username)
entry = _load_atom(response, XNAME_ENTRY).entry
state = _parse_atom_entry(entry)
entity = self.item(
self.service,
urllib.parse.unquote(state.links.alternate),
state=state)
return entity |
<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_attribute(mcs, attribute_name, attribute_value):
""" decides whether the given attribute should be excluded from tracing or not """ |
if attribute_name == '__module__':
return True
elif hasattr(attribute_value, '_trace_disable'):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_columns(self):
"""Creates the treeview stuff""" |
tv = self.view['tv_categories']
# sets the model
tv.set_model(self.model)
# creates the columns
cell = gtk.CellRendererText()
tvcol = gtk.TreeViewColumn('Name', cell)
def cell_data_func(col, cell, mod, it):
if mod[it][0]: cell.set_property('text', mod[it][0].name)
return
tvcol.set_cell_data_func(cell, cell_data_func)
tv.append_column(tvcol)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_curr_model_view(self, model, select):
"""A currency has been added, or an existing curreny has been selected, and needs to be shown on the right side of the dialog""" |
v = self.view.add_currency_view(select)
self.curreny = CurrencyCtrl(model, v)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_modification(self):
"""Modifications on the right side need to be committed""" |
self.__changing_model = True
if self.adding_model: self.model.add(self.adding_model)
elif self.editing_model and self.editing_iter:
# notifies the currencies model
path = self.model.get_path(self.editing_iter)
self.model.row_changed(path, self.editing_iter)
pass
self.view.remove_currency_view()
self.adding_model = None
self.editing_model = None
self.editing_iter = None
self.curreny = None
self.unselect()
self.__changing_model = False
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_selection_changed(self, sel):
"""The user changed selection""" |
m, self.editing_iter = sel.get_selected()
if self.editing_iter:
self.editing_model = m[self.editing_iter][0]
self.show_curr_model_view(self.editing_model, False)
else: self.view.remove_currency_view()
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_estimates(positions, estimates):
""" Plots density, and probability estimates. Parameters positions : iterable of float Paragraph positions for which densities, and probabilities were estimated. estimates : six-tuple of (sequence of float) Estimates of P(relevant), p(position), p(position | relevant), P(position, relevant), and P(relevant | position). Returns ------- matplotlib.figure.Figure The plotted figure. """ |
x = list(positions)
fig = plt.figure(figsize=(SUBPLOT_WIDTH * len(estimates), FIGURE_HEIGHT))
for i, (title, y) in enumerate(zip(ESTIMATE_TITLES, estimates)):
ax = fig.add_subplot(1, len(estimates), i + 1)
ax.plot(x, y, linewidth=LINE_WIDTH, c=LINE_COLOR)
ax.title.set_text(title)
ax.set_xlim(0, 1)
ax.set_xlabel("position")
ax.set_ylabel("$\\hat P$")
ax.grid()
return fig |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(self, options, conf):
""" Get filetype option to specify additional filetypes to watch. """ |
Plugin.configure(self, options, conf)
if options.filetype:
self.filetypes += options.filetype |
<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_multipart_params(func):
""" A middleware that parses the multipart request body and adds the parsed content to the `multipart_params` attribute. This middleware also merges the parsed value with the existing `params` attribute in same way as `wrap_form_params` is doing. """ |
def wrapper(request, *args, **kwargs):
ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
if ctype == "multipart/form-data":
if isinstance(pdict['boundary'], str):
pdict['boundary'] = pdict['boundary'].encode()
params = {}
mp = MultipartParser(BytesIO(request.body), pdict['boundary'])
for part in mp:
params[part.name] = {
"filename": part.filename,
"file": part.file,
}
request.params = merge_dicts(getattr(request, "params", None), params)
request.multipart_params = params
return func(request, *args, **kwargs)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, code):
"""Core API method for appending to the source code stream. It can take the following as input. *Strings* The processor is called if specified. String values from the processed stream are added after newlines are alided and indented. Other values are recursed on. Multiple adjacent newlines which straddle appends are alided to produce a single newline. To insert multiple newlines, they must be adjacent in the same string passed to append. *Callables* Callables taking no arguments are called and their return value recursed on if not ``None`` or ``self``. Callables taking one argument are called with ``self`` and their return value is recursed on if not ``None`` or ``self``. *Iterables* The items recursed on. *Expressions* If ``code._CG_expression`` is defined, that value is recursed on. If ``code._CG_context`` is defined, its value will be appended to the processor using ``append``, if possible, while recursing. *Convertables* See :data:`convert`. """ |
# support one-shot push and pop of dictionaries using operators
pop_next = self._pop_next
if pop_next:
self._pop_next = False
if isinstance(code, str):
# Strings are processed, then indented appropriately
for token in self._process(code):
prev = self.last_string
prev_ends_with_nl = prev is None or prev.endswith('\n')
token_starts_with_nl = token.startswith("\n")
indent_depth = self.indent_depth
if prev_ends_with_nl:
if indent_depth > 0:
self.code_builder.append(self.indent_str)
if token_starts_with_nl:
token = token[1:]
if indent_depth > 0:
token = cypy.re_nonend_newline.sub(
"\n" + self.indent_str, token)
if token != "":
self.code_builder.append(token)
else: self._process_nonstrings(code)
if pop_next:
self.pop_context()
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 lines(self, code):
"""Fixes indentation for multiline strings before appending.""" |
if isinstance(code, str):
fix_indentation = self.fix_indentation
if fix_indentation:
code = fix_indentation(code)
return self.append(code)
else:
return self.append(code) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def last_string(self):
"""The last entry in code_builder, or ``None`` if none so far.""" |
cb = self.code_builder
len_cb = len(cb)
if len_cb > 0:
return cb[len_cb - 1]
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pop_context(self):
"""Pops the last set of keyword arguments provided to the processor.""" |
processor = getattr(self, 'processor', None)
if processor is not None:
pop_context = getattr(processor, 'pop_context', None)
if pop_context is None:
pop_context = getattr(processor, 'pop', None)
if pop_context is not None:
return pop_context()
if self._pop_next:
self._pop_next = 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 unescape(inp, quote='"'):
""" Unescape `quote` in string `inp`. Example usage:: >> unescape('hello \\"') 'hello "' Args: inp (str):
String in which `quote` will be unescaped. quote (char, default "):
Specify which character will be unescaped. Returns: str: Unescaped string. """ |
if len(inp) < 2:
return inp
output = ""
unesc = False
for act in inp:
if act == quote and unesc:
output = output[:-1]
output += act
if act == "\\":
unesc = not unesc
else:
unesc = False
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def escape(inp, quote='"'):
""" Escape `quote` in string `inp`. Example usage:: 'hello \\"' 'hello \\\\"' Args: inp (str):
String in which `quote` will be escaped. quote (char, default "):
Specify which character will be escaped. Returns: str: Escaped string. """ |
output = ""
for c in inp:
if c == quote:
output += '\\'
output += c
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, channel):
"""Read single ADC Channel""" |
checked_channel = self._check_channel_no(channel)
self.i2c.write_raw8(checked_channel | self._dac_enabled)
reading = self.i2c.read_raw8()
reading = self.i2c.read_raw8()
return reading / 255.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 set(self, channel, state):
"""Set DAC value and enable output""" |
checked_val = self._check_dac_val(channel, state)
self._dac_enabled = 0x40
self.i2c.write8(self._dac_enabled, checked_val * 255) |
<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_optional_env(key):
""" Return the value of an optional environment variable, and use the provided default if it's not set. """ |
environment_variable_value = os.environ.get(key)
if environment_variable_value:
return environment_variable_value
elif key in CONSTANTS:
return CONSTANTS[key]
else:
raise Exception("The variable {1} is not set".format(key)) |
<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_datetime_with_default(value, default_value):
""" Converts value into Date or returns default when conversion is not possible. :param value: the value to convert. :param default_value: the default value. :return: Date value or default when conversion is not supported. """ |
result = DateTimeConverter.to_nullable_datetime(value)
return result if result != None else DateTimeConverter.to_utc_datetime(default_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 close(self):
"""Close the cursor""" |
if self.closed or self.connection.closed:
return
self._cursor.close()
self.closed = 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 acquire(self, lock_transactions=None):
""" Acquire the connection locks. :param lock_transactions: `bool`, acquire the transaction lock (`self.lock_transactions` is the default value) """ |
if not self.personal_lock.acquire(timeout=self.lock_timeout):
raise LockTimeoutError(self)
self.with_count += 1
if lock_transactions is None:
lock_transactions = self.lock_transactions
if lock_transactions and self.db_state.active_connection is not self:
if not self.db_state.transaction_lock.acquire(timeout=self.lock_timeout):
self.personal_lock.release()
raise LockTimeoutError(self)
self.db_state.active_connection = self
if not self.db_state.lock.acquire(timeout=self.lock_timeout):
self.personal_lock.release()
if lock_transactions:
self.db_state.active_connection = None
self.db_state.transaction_lock.release()
raise LockTimeoutError(self)
try:
# If the connection is closed, an exception is thrown
in_transaction = self.in_transaction
except sqlite3.ProgrammingError:
in_transaction = False
self.was_in_transaction = in_transaction |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def release(self, lock_transactions=None):
""" Release the connection locks. :param lock_transactions: `bool`, release the transaction lock (`self.lock_transactions` is the default value) """ |
self.personal_lock.release()
self.with_count -= 1
if lock_transactions is None:
lock_transactions = self.lock_transactions
if not lock_transactions:
self.db_state.lock.release()
return
try:
# If the connection is closed, an exception is thrown
in_transaction = self.in_transaction
except sqlite3.ProgrammingError:
in_transaction = False
# The transaction lock should be released only if:
# 1) the connection was previously in a transaction and now it isn't
# 2) the connection wasn't previously in a transaction and still isn't
if (self.was_in_transaction and not in_transaction) or not in_transaction:
if self.with_count == 0: # This is for nested with statements
self.db_state.active_connection = None
self.db_state.transaction_lock.release()
self.db_state.lock.release() |
<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_type_code(value):
""" Gets TypeCode for specific value. :param value: value whose TypeCode is to be resolved. :return: the TypeCode that corresponds to the passed object's type. """ |
if value == None:
return TypeCode.Unknown
if not isinstance(value, type):
value = type(value)
if value is list:
return TypeCode.Array
elif value is tuple:
return TypeCode.Array
elif value is set:
return TypeCode.Array
elif value is bool:
return TypeCode.Boolean
elif value is int:
return TypeCode.Integer
# elif value is long:
# return TypeCode.Long
elif value is float:
return TypeCode.Float
elif value is str:
return TypeCode.String
# elif value is unicode:
# return TypeCode.String
elif value is datetime:
return TypeCode.DateTime
elif value is dict:
return TypeCode.Map
return TypeCode.Object |
<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_type_with_default(value_type, value, default_value):
""" Converts value into an object type specified by Type Code or returns default value when conversion is not possible. :param value_type: the TypeCode for the data type into which 'value' is to be converted. :param value: the value to convert. :param default_value: the default value to return if conversion is not possible (returns None). :return: object value of type corresponding to TypeCode, or default value when conversion is not supported. """ |
result = TypeConverter.to_nullable_type(value_type, value)
return result if result != None else default_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 to_string(type):
""" Converts a TypeCode into its string name. :param type: the TypeCode to convert into a string. :return: the name of the TypeCode passed as a string value. """ |
if type == None:
return "unknown"
elif type == TypeCode.Unknown:
return "unknown"
elif type == TypeCode.String:
return "string"
elif type == TypeCode.Integer:
return "integer"
elif type == TypeCode.Long:
return "long"
elif type == TypeCode.Float:
return "float"
elif type == TypeCode.Double:
return "double"
elif type == TypeCode.Duration:
return "duration"
elif type == TypeCode.DateTime:
return "datetime"
elif type == TypeCode.Object:
return "object"
elif type == TypeCode.Enum:
return "enum"
elif type == TypeCode.Array:
return "array"
elif type == TypeCode.Map:
return "map"
else:
return "unknown" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_netsh_command(netsh_args):
"""Execute a netsh command and return the output.""" |
devnull = open(os.devnull, 'w')
command_raw = 'netsh interface ipv4 ' + netsh_args
return int(subprocess.call(command_raw, stdout=devnull)) |
<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_array(raw_array):
"""Parse a WMIC array.""" |
array_strip_brackets = raw_array.replace('{', '').replace('}', '')
array_strip_spaces = array_strip_brackets.replace('"', '').replace(' ', '')
return array_strip_spaces.split(',') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def llcs(s1, s2):
'''length of the longest common sequence
This implementation takes O(len(s1) * len(s2)) time and
O(min(len(s1), len(s2))) space.
Use only with short strings.
>>> llcs('a.b.cd','!a!b!c!!!d!')
4
'''
m, n = len(s1), len(s2)
if m < n: # ensure n <= m, to use O(min(n,m)) space
m, n = n, m
s1, s2 = s2, s1
l = [0] * (n+1)
for i in range(m):
p = 0
for j in range(n):
t = 1 if s1[i] == s2[j] else 0
p, l[j+1] = l[j+1], max(p+t, l[j], l[j+1])
return l[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 lcsr(s1, s2):
'''longest common sequence ratio
>>> lcsr('ab', 'abcd')
0.5
'''
if s1 == s2:
return 1.0
return llcs(s1, s2) / max(1, len(s1), len(s2)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def lcp(s1, s2):
'''longest common prefix
>>> lcp('abcdx', 'abcdy'), lcp('', 'a'), lcp('x', 'yz')
(4, 0, 0)
'''
i = 0
for i, (c1, c2) in enumerate(zip(s1, s2)):
if c1 != c2:
return i
return min(len(s1), len(s2)) |
<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(data, b64_encode=True, uri_encode=True):
"""Serializes a python dictionary into a Gzip, Base64 encoded string :param data: Python dictionary or list to serialize :param b64_encode: If True, the message will be compressed using Gzip and encoded using Base64 :param uri_encode: If True, the message will be encoded with the urllib.parse.quote_plus to be used as a value of a URI parameter :return: Serialized data string, encoded if `encode` is `True` 'H4sIANRnb1oC/6tWSkxPVbJSMDbUUVDKS8wFsZW88jPylID8xOTk/NK8EqBQtVJmCpAyNDIHChelpmfm5xUD+dFKocEghcHuSrG1tQCN2YKETAAAAA==' 'H4sIAOdnb1oC%2F6tWSkxPVbJSMDbUUVDKS8wFsZW88jPylID8xOTk%2FNK8EqBQtVJmCpAyNDIHChelpmfm5xUD%2BdFKocEghcHuSrG1tQCN2YKETAAAAA%3D%3D' = """ |
if not isinstance(data, dict):
raise RuntimeError("Only dictionaries are supported. The following is not a dictionary:\n %s", data)
message = json.dumps(data)
if b64_encode:
message = jsonuri.io.compress(message).decode('utf-8')
if uri_encode:
message = urllib.parse.quote_plus(message)
return message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init(self, width, len_):
"""Initializes internal data representation of the BinArray to all-0. The internal data representation is simply tightly-packed bits of all words, starting from LSB, split into bytes and stored in a bytearray. The unused trailing padding bits in the last byte must always be set to 0. """ |
self._width = width
self._len = len_
bits = len_ * width
self._data = bytearray(BinInt(bits).ceildiv(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 _locate(self, idx):
"""Locates an element in the internal data representation. Returns starting byte index, starting bit index in the starting byte, and one past the final byte index. """ |
start = idx * self._width
end = (idx + 1) * self._width
sbyte, sbit = divmod(start, 8)
ebyte = BinInt(end).ceildiv(8)
return sbyte, sbit, ebyte |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def repack(self, to_width, *, msb_first, start=0, start_bit=0, length=None):
"""Extracts a part of a BinArray's data and converts it to a BinArray of a different width. For the purposes of this conversion, words in this BinArray are joined side-by-side, starting from a given start index (defaulting to 0), skipping ``start_bit`` first bits of the first word, then the resulting stream is split into ``to_width``-sized words and ``length`` first such words are returned as a new BinArray. If ``msb_first`` is False, everything proceeds with little endian ordering: the first word provides the least significant bits of the combined stream, ``start_bit`` skips bits starting from the LSB, and the first output word is made from the lowest bits of the combined stream. Otherwise (``msb_first`` is True), everything proceeds with big endian ordering: the first word provides the most significant bits of the combined stream, ``start_bit`` skips bits starting from the MSB, and the first output word is made from the highest bits of the combined stream. ``start_bits`` must be smaller than the width of the input word. It is an error to request a larger length than can be provided from the input array. If ``length`` is not provided, this function returns as many words as can be extracted. For example, consider a 10-to-3 repack with start_bit=2, length=4 msb_first=True: +---------+-+-+-+-+-+-+-+-+-+-+ +---------+-+-+-+-+-+-+-+-+-+-+ +---------+-+-+-+-+-+-+-+-+-+-+ | start |X|X|a|b|c|d|e|f|g|h| +---------+-+-+-+-+-+-+-+-+-+-+ | start+1 |i|j|k|l|X|X|X|X|X|X| +---------+-+-+-+-+-+-+-+-+-+-+ +---------+-+-+-+-+-+-+-+-+-+-+ is repacked to: +-+-+-+-+ |0|a|b|c| +-+-+-+-+ |1|d|e|f| +-+-+-+-+ |2|g|h|i| +-+-+-+-+ |3|j|k|l| +-+-+-+-+ The same repack for msb_first=False is performed as follows: +---------+-+-+-+-+-+-+-+-+-+-+ +---------+-+-+-+-+-+-+-+-+-+-+ +---------+-+-+-+-+-+-+-+-+-+-+ | start |h|g|f|e|d|c|b|a|X|X| +---------+-+-+-+-+-+-+-+-+-+-+ | start+1 |X|X|X|X|X|X|l|k|j|i| +---------+-+-+-+-+-+-+-+-+-+-+ +---------+-+-+-+-+-+-+-+-+-+-+ into: +-+-+-+-+ |0|c|b|a| +-+-+-+-+ |1|f|e|d| +-+-+-+-+ |2|i|h|g| +-+-+-+-+ |3|l|k|j| +-+-+-+-+ """ |
to_width = operator.index(to_width)
if not isinstance(msb_first, bool):
raise TypeError('msb_first must be a bool')
available = self.repack_data_available(
to_width, start=start, start_bit=start_bit)
if length is None:
length = available
else:
length = operator.index(length)
if length > available:
raise ValueError('not enough data available')
if length < 0:
raise ValueError('length cannot be negative')
start = operator.index(start)
start_bit = operator.index(start_bit)
pos = start
accum = BinWord(0, 0)
if start_bit:
accum = self[pos]
pos += 1
rest = accum.width - start_bit
if msb_first:
accum = accum.extract(0, rest)
else:
accum = accum.extract(start_bit, rest)
res = BinArray(width=to_width, length=length)
for idx in range(length):
while len(accum) < to_width:
cur = self[pos]
pos += 1
if msb_first:
accum = BinWord.concat(cur, accum)
else:
accum = BinWord.concat(accum, cur)
rest = accum.width - to_width
if msb_first:
cur = accum.extract(rest, to_width)
accum = accum.extract(0, rest)
else:
cur = accum.extract(0, to_width)
accum = accum.extract(to_width, rest)
res[idx] = cur
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 repack_data_available(src_width, to_width, *, # noqa: N805 src_length=None, start=None, start_bit=0):
"""Calculates the maximum number of words that can be requested from a repack invocation with the given settings. This function can be called either on a BinArray instance (assuming its width as the source width), or on the BinArray class (passing the source width as an extra first argument). If called in the second form, ``src_length`` must be provided. Otherwise, it will default to the number of words in the source array from the given ``start`` index (defaulting to 0) until the end. """ |
start_bit = operator.index(start_bit)
if isinstance(src_width, BinArray):
self = src_width
if src_length is None:
if start is None:
start = 0
else:
start = operator.index(start)
if start < 0:
raise ValueError('start must not be negative')
src_length = len(self) - start
start = None
src_width = self.width
if src_length is None:
raise TypeError('no length given')
if start is not None:
raise TypeError('start is redundant with explicit src_length')
src_width = operator.index(src_width)
to_width = operator.index(to_width)
src_length = operator.index(src_length)
start_bit = operator.index(start_bit)
if src_width <= 0:
raise ValueError('source width must be positive')
if to_width <= 0:
raise ValueError('destination width must be positive')
if src_length < 0:
raise ValueError('src_length must not be negative')
if start_bit not in range(src_width):
raise ValueError('start bit must be in [0, src_width)')
if src_length == 0 and start_bit != 0:
raise ValueError(
'src_length must be positive if start_bit is not zero')
return (src_width * src_length - start_bit) // to_width |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def bucket_to_dataframe(name, buckets, append_name=None):
'''A function that turns elasticsearch aggregation buckets into dataframes
:param name: The name of the bucket (will be a column in the dataframe)
:type name: str
:param bucket: a bucket from elasticsearch results
:type bucket: list[dict]
:returns: pandas.DataFrame
'''
expanded_buckets = []
for item in buckets:
if type(item) is dict:
single_dict = item
else:
single_dict = item.to_dict()
single_dict[name] = single_dict.pop('doc_count')
if append_name:
persistance_dict = single_dict.copy()
for key in persistance_dict.keys():
single_dict[append_name + '.' + key] = single_dict.pop(key)
expanded_buckets.append(single_dict)
return pd.DataFrame(expanded_buckets) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def agg_to_two_dim_dataframe(agg):
'''A function that takes an elasticsearch response with aggregation and returns the names of all bucket value pairs
:param agg: an aggregation from elasticsearch results
:type agg: elasticsearch response.aggregation.agg_name object
:returns: pandas data frame of one or two dimetions depending on input data
'''
expanded_agg = []
for bucket in agg.buckets:
bucket_as_dict = bucket.to_dict()
if dict not in [type(item) for item in bucket_as_dict.values()]:
return bucket_to_dataframe('doc_count', agg.buckets)
else:
lower_level_dict = [item for item in bucket_as_dict.keys() if type(bucket_as_dict[item]) is dict]
if len(lower_level_dict) > 1:
raise ValueError('Two dimensional data can only convert a 2 level aggregation (with 1 aggregation at each level)')
name_of_lower_level = lower_level_dict[0]
single_level_dataframe = bucket_to_dataframe(bucket.key,
bucket[name_of_lower_level]['buckets'],
name_of_lower_level)
expanded_agg.append(single_level_dataframe)
merged_results = merge_dataframes(*expanded_agg)
# rearrange to get key as first col
cols = merged_results.columns.tolist()
indices_of_keys = [i for i, s in enumerate(cols) if 'key' in s]
all_other_cols = [i for i in range(0, len(cols)) if i not in indices_of_keys]
new_col_order = indices_of_keys + all_other_cols
return merged_results[new_col_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 merge_dataframes(*dfs):
'''A helper function for merging two dataframes that have the same indices, duplicate columns are removed
:param dfs: a list of dataframes to be merged (note: they must have the same indices)
:type dfs: list[pandas.DataFrame]
:returns: pandas.DataFrame -- a merged dataframe
'''
merged_dataframe = pd.concat(dfs, axis=1, join_axes=[dfs[0].index])
return merged_dataframe.transpose().drop_duplicates().transpose() |
<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(self):
"""Decodes the mission files into dictionaries""" |
LOGGER.debug('decoding lua tables')
if not self.zip_content:
self.unzip()
LOGGER.debug('reading map resource file')
with open(str(self.map_res_file), encoding=ENCODING) as stream:
self._map_res, self._map_res_qual = SLTP().decode(stream.read())
LOGGER.debug('reading l10n file')
with open(str(self.dictionary_file), encoding=ENCODING) as stream:
self._l10n, self._l10n_qual = SLTP().decode(stream.read())
LOGGER.debug('reading mission file')
with open(str(self.mission_file), encoding=ENCODING) as stream:
mission_data, self._mission_qual = SLTP().decode(stream.read())
self._mission = Mission(mission_data, self._l10n)
LOGGER.debug('gathering resources')
for file in Path(self.temp_dir, 'l10n', 'DEFAULT').iterdir():
if file.name in ('dictionary', 'mapResource'):
continue
LOGGER.debug('found resource: %s', file.name)
self._resources.add(file.name)
LOGGER.debug('decoding 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 unzip(self, overwrite: bool = False):
""" Flattens a MIZ file into the temp dir Args: overwrite: allow overwriting exiting files """ |
if self.zip_content and not overwrite:
raise FileExistsError(str(self.temp_dir))
LOGGER.debug('unzipping miz to temp dir')
try:
with ZipFile(str(self.miz_path)) as zip_file:
LOGGER.debug('reading infolist')
self.zip_content = [f.filename for f in zip_file.infolist()]
self._extract_files_from_zip(zip_file)
except BadZipFile:
raise BadZipFile(str(self.miz_path))
except: # noqa: E722
LOGGER.exception('error while unzipping miz file: %s', self.miz_path)
raise
LOGGER.debug('checking miz content')
# noinspection PyTypeChecker
for miz_item in ['mission', 'options', 'warehouses', 'l10n/DEFAULT/dictionary', 'l10n/DEFAULT/mapResource']:
if not Path(self.temp_dir.joinpath(miz_item)).exists():
LOGGER.error('missing file in miz: %s', miz_item)
raise FileNotFoundError(miz_item)
self._check_extracted_content()
LOGGER.debug('all files have been found, miz successfully unzipped') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def lis(seq, indices=False):
'''longest increasing subsequence
>>> lis([1, 2, 5, 3, 4])
[1, 2, 3, 4]
'''
if not seq:
return []
# prevs[i] is the index of the previous element in the longest subsequence
# containing element i
prevs = [None] * len(seq)
# tails[i] is the pair (elem, index) of the lowest element of any
# subsequence with length i + 1
tails = [(seq[0], 0)]
for i, elem in enumerate(seq[1:], start=1):
if elem > tails[-1][0]:
prevs[i] = tails[-1][1]
tails.append((elem, i))
continue
# let's find a tail that we can extend
k = bisect(tails, (elem, -1))
if tails[k][0] > elem:
tails[k] = (elem, i)
if k > 0:
prevs[i] = tails[k - 1][1]
_, i = tails[-1]
subseq = []
while i is not None:
subseq.append(i if indices else seq[i])
i = prevs[i]
return subseq[::-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 __fix_bases(base_classes, have_mt):
"""This function check whether base_classes contains a Model instance. If not, choose the best fitting class for model. Furthermore, it makes the list in a cannonical ordering form in a way that ic can be used as memoization key""" |
fixed = list(base_classes)
contains_model = False
for b in fixed:
if isinstance(fixed, Model): contains_model = True; break
pass
# adds a model when user is lazy
if not contains_model:
if have_mt:
from gtkmvc3.model_mt import ModelMT
fixed.insert(0, ModelMT)
else: fixed.insert(0, Model)
pass
class ModelFactoryWrap (object):
__metaclass__ = get_noconflict_metaclass(tuple(fixed), (), ())
def __init__(self, *args, **kwargs): pass
pass
fixed.append(ModelFactoryWrap)
fixed.sort()
return tuple(fixed) |
<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(base_classes=(), have_mt=False):
"""Use this static method to build a model class that possibly derives from other classes. If have_mt is True, then returned class will take into account multi-threading issues when dealing with observable properties.""" |
good_bc = ModelFactory.__fix_bases(base_classes, have_mt)
print "Base classes are:", good_bc
key = "".join(map(str, good_bc))
if key in ModelFactory.__memoized:
return ModelFactory.__memoized[key]
cls = new.classobj('', good_bc, {'__module__': '__main__', '__doc__': None})
ModelFactory.__memoized[key] = cls
return cls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _authentication(request_fun):
"""Decorator to handle autologin and authentication errors. *request_fun* is a function taking no arguments that needs to be run with this ``Context`` logged into Splunk. ``_authentication``'s behavior depends on whether the ``autologin`` field of ``Context`` is set to ``True`` or ``False``. If it's ``False``, then ``_authentication`` aborts if the ``Context`` is not logged in, and raises an ``AuthenticationError`` if an ``HTTPError`` of status 401 is raised in *request_fun*. If it's ``True``, then ``_authentication`` will try at all sensible places to log in before issuing the request. If ``autologin`` is ``False``, ``_authentication`` makes one roundtrip to the server if the ``Context`` is logged in, or zero if it is not. If ``autologin`` is ``True``, it's less deterministic, and may make at most three roundtrips (though that would be a truly pathological case). :param request_fun: A function of no arguments encapsulating the request to make to the server. **Example**:: import splunklib.binding as binding c.logout() def f():
c.get("/services") return 42 print _authentication(f) """ |
@wraps(request_fun)
def wrapper(self, *args, **kwargs):
if self.token is _NoAuthenticationToken:
# Not yet logged in.
if self.autologin and self.username and self.password:
# This will throw an uncaught
# AuthenticationError if it fails.
self.login()
else:
# Try the request anyway without authentication.
# Most requests will fail. Some will succeed, such as
# 'GET server/info'.
with _handle_auth_error("Request aborted: not logged in."):
return request_fun(self, *args, **kwargs)
try:
# Issue the request
return request_fun(self, *args, **kwargs)
except HTTPError as he:
if he.status == 401 and self.autologin:
# Authentication failed. Try logging in, and then
# rerunning the request. If either step fails, throw
# an AuthenticationError and give up.
with _handle_auth_error("Autologin failed."):
self.login()
with _handle_auth_error(
"Autologin succeeded, but there was an auth error on "
"next request. Something is very wrong."):
return request_fun(self, *args, **kwargs)
elif he.status == 401 and not self.autologin:
raise AuthenticationError(
"Request failed: Session is not logged in.", he)
else:
raise
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, path_segment, owner=None, app=None, sharing=None, **query):
"""Performs a GET operation from the REST path segment with the given namespace and query. This method is named to match the HTTP method. ``get`` makes at least one round trip to the server, one additional round trip for each 303 status returned, and at most two additional round trips if the ``autologin`` field of :func:`connect` is set to ``True``. If *owner*, *app*, and *sharing* are omitted, this method uses the default :class:`Context` namespace. All other keyword arguments are included in the URL as query parameters. :raises AuthenticationError: Raised when the ``Context`` object is not logged in. :raises HTTPError: Raised when an error occurred in a GET operation from *path_segment*. :param path_segment: A REST path segment. :type path_segment: ``string`` :param owner: The owner context of the namespace (optional). :type owner: ``string`` :param app: The app context of the namespace (optional). :type app: ``string`` :param sharing: The sharing mode of the namespace (optional). :type sharing: ``string`` :param query: All other keyword arguments, which are used as query parameters. :type query: ``string`` :return: The response from the server. :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status`` **Example**:: c.get('apps/local') == \\ 'headers': [('content-length', '26208'), ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'), ('server', 'Splunkd'), ('connection', 'close'), ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'), ('date', 'Fri, 11 May 2012 16:30:35 GMT'), ('content-type', 'text/xml; charset=utf-8')], 'reason': 'OK', 'status': 200} c.get('nonexistant/path') # raises HTTPError c.logout() c.get('apps/local') # raises AuthenticationError """ |
path = self.authority + self._abspath(path_segment, owner=owner,
app=app, sharing=sharing)
logging.debug("GET request to %s (body: %s)", path, repr(query))
response = self.http.get(path, self._auth_headers, **query)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, url, headers=None, **kwargs):
"""Sends a POST request to a URL. :param url: The URL. :type url: ``string`` :param headers: A list of pairs specifying the headers for the HTTP response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``). :type headers: ``list`` :param kwargs: Additional keyword arguments (optional). If the argument is ``body``, the value is used as the body for the request, and the keywords and their arguments will be URL encoded. If there is no ``body`` keyword argument, all the keyword arguments are encoded into the body of the request in the format ``x-www-form-urlencoded``. :type kwargs: ``dict`` :returns: A dictionary describing the response (see :class:`HttpLib` for its structure). :rtype: ``dict`` """ |
if headers is None: headers = []
headers.append(("Content-Type", "application/x-www-form-urlencoded")),
# We handle GET-style arguments and an unstructured body. This is here
# to support the receivers/stream endpoint.
if 'body' in kwargs:
body = kwargs.pop('body')
if len(kwargs) > 0:
url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True)
else:
body = _encode(**kwargs)
message = {
'method': "POST",
'headers': headers,
'body': body
}
return self.request(url, message) |
<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_proxy_model(self, model):
"""Create a sort filter proxy model for the given model :param model: the model to wrap in a proxy :type model: :class:`QtGui.QAbstractItemModel` :returns: a new proxy model that can be used for sorting and filtering :rtype: :class:`QtGui.QAbstractItemModel` :raises: None """ |
proxy = ReftrackSortFilterModel(self)
proxy.setSourceModel(model)
model.rowsInserted.connect(self.sort_model)
return 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 setup_filter(self, ):
"""Create a checkbox for every reftrack type so one can filter them :returns: None :rtype: None :raises: None """ |
types = self.refobjinter.types.keys()
for i, t in enumerate(types):
cb = QtGui.QCheckBox("%s" % t)
cb.setChecked(True)
cb.toggled.connect(self.update_filter)
self.typecbmap[t] = cb
self.typefilter_grid.addWidget(cb, int(i / 4), i % 4) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def switch_showfilter_icon(self, toggled):
"""Switch the icon on the showfilter_tb :param toggled: the state of the button :type toggled: :class:`bool` :returns: None :rtype: None :raises: None """ |
at = QtCore.Qt.DownArrow if toggled else QtCore.Qt.RightArrow
self.showfilter_tb.setArrowType(at) |
<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_addnew_win(self, *args, **kwargs):
"""Open a new window so the use can choose to add new reftracks :returns: None :rtype: None :raises: NotImplementedError """ |
if self.reftrackadderwin:
self.reftrackadderwin.close()
self.reftrackadderwin = ReftrackAdderWin(self.refobjinter, self.root, parent=self)
self.reftrackadderwin.destroyed.connect(self.addnewwin_destroyed)
self.reftrackadderwin.show() |
<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_filter(self, *args, **kwargs):
"""Update the filter :returns: None :rtype: None :raises: NotImplementedError """ |
forbidden_statuses = []
if not self.loaded_checkb.isChecked():
forbidden_statuses.append(reftrack.Reftrack.LOADED)
if not self.unloaded_checkb.isChecked():
forbidden_statuses.append(reftrack.Reftrack.UNLOADED)
if not self.imported_checkb.isChecked():
forbidden_statuses.append(reftrack.Reftrack.IMPORTED)
if not self.empty_checkb.isChecked():
forbidden_statuses.append(None)
self.proxy.set_forbidden_statuses(forbidden_statuses)
forbidden_types = []
for typ, cb in self.typecbmap.items():
if not cb.isChecked():
forbidden_types.append(typ)
self.proxy.set_forbidden_types(forbidden_types)
forbidden_uptodate = []
if not self.old_checkb.isChecked():
forbidden_uptodate.append(False)
if not self.newest_checkb.isChecked():
forbidden_uptodate.append(True)
self.proxy.set_forbidden_uptodate(forbidden_uptodate)
forbidden_alien = [] if self.alien_checkb.isChecked() else [True]
self.proxy.set_forbidden_alien(forbidden_alien)
self.proxy.setFilterWildcard(self.search_le.text()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort_model(self, *args, **kwargs):
"""Sort the proxy model :returns: None :rtype: None :raises: None """ |
self.proxy.sort(17) # sort the identifier
self.proxy.sort(2) # sort the element
self.proxy.sort(1) # sort the elementgrp
self.proxy.sort(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 add_selected(self, ):
"""Create a new reftrack with the selected element and type and add it to the root. :returns: None :rtype: None :raises: NotImplementedError """ |
browser = self.shot_browser if self.browser_tabw.currentIndex() == 1 else self.asset_browser
selelements = browser.selected_indexes(2)
if not selelements:
return
seltypes = browser.selected_indexes(3)
if not seltypes:
return
elementi = selelements[0]
typi = seltypes[0]
if not elementi.isValid() or not typi.isValid():
return
element = elementi.internalPointer().internal_data()
typ = typi.internalPointer().internal_data()[0]
reftrack.Reftrack(self.root, self.refobjinter, typ=typ, element=element) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_ensemble(ensemble, options):
""" Prints out the ensemble composition at each size """ |
# set output file name
size = len(ensemble)
filename = '%s_%s_queries.csv' % (options.outname, size)
file = os.path.join(os.getcwd(), filename)
f = open(file, 'w')
out = ', '.join(ensemble)
f.write(out)
f.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup_blob(hash_value):
""" Combines all given arguments to create clean title-tags values. All arguments are divided by a " " seperator and HTML tags are to be removed. """ |
try:
blob = BlobStorage.objects.get(sha256=hash_value)
except:
return "Blob not found"
return blob.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 comet_view(self, request):
""" This is dumb function, it just passes everything it gets into the message stream. Something else in the stream should be responsible for asynchronously figuring out what to do with all these messages. """ |
request_id = self.id_for_request(request)
if not request_id:
request.write(HttpResponse(403).as_bytes())
request.finish()
return
data = {
'headers': request.headers,
'arguments': request.arguments,
'remote_ip': request.remote_ip,
'request_id': request_id,
}
message_kind = 'comet-%s' % (request.method,)
if request.method == 'POST':
data['body'] = simplejson.loads(request.body)
request.write(HttpResponse(201).as_bytes())
request.finish()
else:
self.pending_requests[request_id].append(request)
self.publish(Message(message_kind, datetime.now(), 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 sshagent_run(cmd):
""" Helper function. Runs a command with SSH agent forwarding enabled. Note:: Fabric (and paramiko) can't forward your SSH agent. This helper uses your system's ssh to do so. """ |
# Handle context manager modifications
wrapped_cmd = _prefix_commands(_prefix_env_vars(cmd), 'remote')
try:
host, port = env.host_string.split(':')
return local(
u"ssh -p %s -A -o StrictHostKeyChecking=no %s@%s '%s'" % (
port, env.user, host, wrapped_cmd
)
)
except ValueError:
return local(
u"ssh -A -o StrictHostKeyChecking=no %s@%s '%s'" % (
env.user, env.host_string, wrapped_cmd
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_object(obj):
"""Return a JSON serializable type for ``o``. Args: obj (:py:class:`object`):
the object to be serialized. Raises: :py:class:`AttributeError`: when ``o`` is not a Python object. Returns: (dict):
JSON serializable type for the given object. """ |
LOGGER.debug('as_object(%s)', obj)
if isinstance(obj, datetime.date):
return as_date(obj)
elif hasattr(obj, '__dict__'):
# populate dict with visible attributes
out = {k: obj.__dict__[k] for k in obj.__dict__ if not k.startswith('_')}
# populate dict with property names and values
for k, v in (
(p, getattr(obj, p))
for p, _ in inspect.getmembers(
obj.__class__,
lambda x: isinstance(x, property))
):
out[k] = v
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_date(dat):
"""Return the RFC3339 UTC string representation of the given date and time. Args: dat (:py:class:`datetime.date`):
the object/type to be serialized. Raises: TypeError: when ``o`` is not an instance of ``datetime.date``. Returns: (str) JSON serializable type for the given object. """ |
LOGGER.debug('as_date(%s)', dat)
return strict_rfc3339.timestamp_to_rfc3339_utcoffset(
calendar.timegm(dat.timetuple())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chunks(iterable, chunk):
"""Yield successive n-sized chunks from an iterable.""" |
for i in range(0, len(iterable), chunk):
yield iterable[i:i + 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 integrate(self, function, lower_bound, upper_bound):
""" Calculates the integral of the given one dimensional function in the interval from lower_bound to upper_bound, with the simplex integration method. """ |
ret = 0.0
n = self.nsteps
xStep = (float(upper_bound) - float(lower_bound)) / float(n)
self.log_info("xStep" + str(xStep))
x = lower_bound
val1 = function(x)
self.log_info("val1: " + str(val1))
for i in range(n):
x = (i + 1) * xStep + lower_bound
self.log_info("x: " + str(x))
val2 = function(x)
self.log_info("val2: " + str(val2))
ret += 0.5 * xStep * (val1 + val2)
val1 = val2
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sam_iter(handle, start_line=None, headers=False):
"""Iterate over SAM file and return SAM entries Args: handle (file):
SAM file handle, can be any iterator so long as it it returns subsequent "lines" of a SAM entry start_line (str):
Next SAM entry, if 'handle' has been partially read and you want to start iterating at the next entry, read the next SAM entry and pass it to this variable when calling sam_iter. See 'Examples.' headers (bool):
Yields headers if True, else skips lines starting with "@" Yields: SamEntry: class containing all SAM data, yields str for headers if headers options is True then yields GamEntry for entries Examples: The following two examples demonstrate how to use sam_iter. Note: These doctests will not pass, examples are only in doctest format as per convention. bio_utils uses pytests for testing. """ |
# Speed tricks: reduces function calls
split = str.split
strip = str.strip
next_line = next
if start_line is None:
line = next_line(handle) # Read first B6/M8 entry
else:
line = start_line # Set header to given header
# Check if input is text or bytestream
if (isinstance(line, bytes)):
def next_line(i):
return next(i).decode('utf-8')
line = strip(line.decode('utf-8'))
else:
line = strip(line)
# A manual 'for' loop isn't needed to read the file properly and quickly,
# unlike fasta_iter and fastq_iter, but it is necessary begin iterating
# partway through a file when the user gives a starting line.
try: # Manually construct a for loop to improve speed by using 'next'
while True: # Loop until StopIteration Exception raised
split_line = split(line, '\t')
if line.startswith('@') and not headers:
line = strip(next_line(handle))
continue
elif line.startswith('@') and headers:
yield line
line = strip(next_line(handle))
continue
data = SamEntry()
data.qname = split_line[0]
try: # Differentiate between int and hex bit flags
data.flag = int(split_line[1])
except ValueError:
data.flag = split_line[1]
data.rname = split_line[2]
data.pos = int(split_line[3])
data.mapq = int(split_line[4])
data.cigar = split_line[5]
data.rnext = split_line[6]
data.pnext = int(split_line[7])
data.tlen = int(split_line[8])
data.seq = split_line[9]
data.qual = split_line[10]
line = strip(next_line(handle)) # Raises StopIteration at EOF
yield data
except StopIteration: # Yield last SAM entry
yield 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 write(self):
"""Return SAM formatted string Returns: str: SAM formatted string containing entire SAM entry """ |
return '{0}\t{1}\t{2}\t{3}\t{4}\t' \
'{5}\t{6}\t{7}\t{8}\t{9}\t' \
'{10}{11}'.format(self.qname,
str(self.flag),
self.rname,
str(self.pos),
str(self.mapq),
self.cigar,
self.rnext,
str(self.pnext),
str(self.tlen),
self.seq,
self.qual,
os.linesep) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, request_path, data=None, do_authentication=True, is_json=True):
""" Core "worker" for making requests and parsing JSON responses. If `is_json` is ``True``, `data` should be a dictionary which will be JSON-encoded. """ |
uri = self.api_uri % request_path
request = urllib2.Request(uri)
# Build up the request
if is_json:
request.add_header("Content-Type", "application/json")
if data is not None:
request.add_data(json.dumps(data))
elif data is not None:
request.add_data(data)
if do_authentication:
if self.client_id is None or self.client_secret is None:
raise Exception(u"You need to supply a client_id and client_secret to perform an authenticated request")
basic_auth = base64.b64encode("%s:%s" % (self.client_id, self.client_secret))
request.add_header("Authorization", "Basic %s" % basic_auth)
try:
response = self._make_request(request)
except Exception as inst:
raise # automatically re-raises the exception
if 'status' in response:
# Grab the status info if it exists
self._last_status_code = response['status']['code']
if 'message' in response['status']:
self._last_status_message = response['status']['message']
if 'data' in response:
return response['data']
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_request(self, request):
""" Does the magic of actually sending the request and parsing the response """ |
# TODO: I'm sure all kinds of error checking needs to go here
try:
response_raw = urllib2.urlopen(request)
except urllib2.HTTPError, e:
print e.read()
raise
response_str = response_raw.read()
response = json.loads(response_str)
self._last_request = request
self._last_response = response_raw
self._last_response_str = response_str
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_member(self, address, **kwargs):
""" Add a member to a group. All Fiesta membership options can be passed in as keyword arguments. Some valid options include: - `group_name`: Since each member can access a group using their own name, you can override the `group_name` in this method. By default, the group will have the name specified on the class level `default_name` property. - `display_name` is the full name of the user that they will see throughout the UI if this is a new account. - `welcome_message` should be a dictionary specified according to the docs. If you set it to ``False``, no message will be sent. See http://docs.fiesta.cc/list-management-api.html#message for formatting details. .. seealso:: `Fiesta API documentation <http://docs.fiesta.cc/list-management-api.html#adding-members>`_ """ |
path = 'membership/%s' % self.id
kwargs["address"] = address
if "group_name" not in kwargs and self.default_name:
kwargs["group_name"] = self.default_name
response_data = self.api.request(path, kwargs)
if 'user_id' in response_data:
user_id = response_data['user_id']
return FiestaUser(user_id, address=address, groups=[self])
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 send_message(self, subject=None, text=None, markdown=None, message_dict=None):
""" Helper function to send a message to a group """ |
message = FiestaMessage(self.api, self, subject, text, markdown, message_dict)
return message.send() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_application(self, application_id, **kwargs):
""" Add an application to a group. `application_id` is the name of the application to add. Any application options can be specified as kwargs. """ |
path = 'group/%s/application' % self.id
data = {'application_id': application_id}
if kwargs:
data["options"] = kwargs
self.api.request(path, 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 send(self, group_id=None, message_dict=None):
""" Send this current message to a group. `message_dict` can be a dictionary formatted according to http://docs.fiesta.cc/list-management-api.html#messages If message is provided, this method will ignore object-level variables. """ |
if self.group is not None and self.group.id is not None:
group_id = self.group.id
path = 'message/%s' % group_id
if message_dict is not None:
request_data = {
'message': message_dict,
}
else:
subject = self.subject
text = self.text
markdown = self.markdown
request_data = {
'message': {},
}
if subject:
request_data['message']['subject'] = subject
if text:
request_data['message']['text'] = text
if markdown:
request_data['message']['markdown'] = markdown
response_data = self.api.request(path, request_data)
self.id = response_data['message_id']
self.thread_id = response_data['thread_id']
self.sent_message = FiestaMessage(self.api, response_data['message']) |
<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_ui(self, ):
"""Setup the ui :returns: None :rtype: None :raises: None """ |
labels = self.reftrack.get_option_labels()
self.browser = ComboBoxBrowser(len(labels), headers=labels)
self.browser_vbox.addWidget(self.browser) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select(self, ):
"""Store the selected taskfileinfo self.selected and accept the dialog :returns: None :rtype: None :raises: None """ |
s = self.browser.selected_indexes(self.browser.get_depth()-1)
if not s:
return
i = s[0].internalPointer()
if i:
tfi = i.internal_data()
self.selected = tfi
self.accept() |
<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_icons(self, ):
"""Setup the icons of the ui :returns: None :rtype: None :raises: None """ |
iconbtns = [("menu_border_24x24.png", self.menu_tb),
("duplicate_border_24x24.png", self.duplicate_tb),
("delete_border_24x24.png", self.delete_tb),
("reference_border_24x24.png", self.reference_tb),
("load_border_24x24.png", self.load_tb),
("unload_border_24x24.png", self.unload_tb),
("replace_border_24x24.png", self.replace_tb),
("import_border_24x24.png", self.importref_tb),
("import_border_24x24.png", self.importtf_tb),
("alien.png", self.alien_tb),
("imported.png", self.imported_tb)]
for iconname, btn in iconbtns:
i = get_icon(iconname, asicon=True)
btn.setIcon(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 set_maintext(self, index):
"""Set the maintext_lb to display text information about the given reftrack :param index: the index :type index: :class:`QtGui.QModelIndex` :returns: None :rtype: None :raises: None """ |
dr = QtCore.Qt.DisplayRole
text = ""
model = index.model()
for i in (1, 2, 3, 5, 6):
new = model.index(index.row(), i, index.parent()).data(dr)
if new is not None:
text = " | ".join((text, new)) if text else new
self.maintext_lb.setText(text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_identifiertext(self, index):
"""Set the identifier text on the identifier_lb :param index: the index :type index: :class:`QtGui.QModelIndex` :returns: None :rtype: None :raises: None """ |
dr = QtCore.Qt.DisplayRole
t = index.model().index(index.row(), 17, index.parent()).data(dr)
if t is None:
t = -1
else:
t = t+1
self.identifier_lb.setText("#%s" % t) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_type_icon(self, index):
"""Set the type icon on type_icon_lb :param index: the index :type index: :class:`QtGui.QModelIndex` :returns: None :rtype: None :raises: None """ |
icon = index.model().index(index.row(), 0, index.parent()).data(QtCore.Qt.DecorationRole)
if icon:
pix = icon.pixmap(self.type_icon_lb.size())
self.type_icon_lb.setPixmap(pix)
else:
self.type_icon_lb.setPixmap(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 disable_restricted(self, ):
"""Disable the restricted buttons :returns: None :rtype: None :raises: None """ |
todisable = [(self.reftrack.duplicate, self.duplicate_tb),
(self.reftrack.delete, self.delete_tb),
(self.reftrack.reference, self.reference_tb),
(self.reftrack.replace, self.replace_tb),]
for action, btn in todisable:
res = self.reftrack.is_restricted(action)
btn.setDisabled(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 hide_restricted(self, ):
"""Hide the restricted buttons :returns: None :rtype: None :raises: None """ |
tohide = [((self.reftrack.unload, self.unload_tb),
(self.reftrack.load, self.load_tb)),
((self.reftrack.import_file, self.importtf_tb),
(self.reftrack.import_reference, self.importref_tb))]
for (action1, btn1), (action2, btn2) in tohide:
res1 = self.reftrack.is_restricted(action1)
res2 = self.reftrack.is_restricted(action2)
if res1 != res2:
btn1.setEnabled(True)
btn1.setHidden(res1)
btn2.setHidden(res2)
else: # both are restricted, then show one but disable it
btn1.setDisabled(True)
btn1.setVisible(True)
btn2.setVisible(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 set_top_bar_color(self, index):
"""Set the color of the upper frame to the background color of the reftrack status :param index: the index :type index: :class:`QtGui.QModelIndex` :returns: None :rtype: None :raises: None """ |
dr = QtCore.Qt.ForegroundRole
c = index.model().index(index.row(), 8, index.parent()).data(dr)
if not c:
c = self.upper_fr_default_bg_color
self.upper_fr.setStyleSheet('background-color: rgb(%s, %s, %s)' % (c.red(), c.green(), c.blue())) |
<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_menu(self, ):
"""Setup the menu that the menu_tb button uses :returns: None :rtype: None :raises: None """ |
self.menu = QtGui.QMenu(self)
actions = self.reftrack.get_additional_actions()
self.actions = []
for a in actions:
if a.icon:
qaction = QtGui.QAction(a.icon, a.name, self)
else:
qaction = QtGui.QAction(a.name, self)
qaction.setCheckable(a.checkable)
qaction.setChecked(a.checked)
qaction.setEnabled(a.enabled)
qaction.triggered.connect(a.action)
self.actions.append(qaction)
self.menu.addAction(qaction)
self.menu_tb.setMenu(self.menu) |
<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_taskfileinfo_selection(self, ):
"""Return a taskfileinfo that the user chose from the available options :returns: the chosen taskfileinfo :rtype: :class:`jukeboxcore.filesys.TaskFileInfo` :raises: None """ |
sel = OptionSelector(self.reftrack)
sel.exec_()
return sel.selected |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reference(self, ):
"""Reference a file :returns: None :rtype: None :raises: None """ |
tfi = self.get_taskfileinfo_selection()
if tfi:
self.reftrack.reference(tfi) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_file(self, ):
"""Import a file :returns: None :rtype: None :raises: NotImplementedError """ |
tfi = self.get_taskfileinfo_selection()
if tfi:
self.reftrack.import_file(tfi) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace(self, ):
"""Replace the current reftrack :returns: None :rtype: None :raises: None """ |
tfi = self.get_taskfileinfo_selection()
if tfi:
self.reftrack.replace(tfi) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def delete_renditions_if_master_has_changed(sender, instance, **kwargs):
'''if master file as changed delete all renditions'''
try:
obj = sender.objects.get(pk=instance.pk)
except sender.DoesNotExist:
pass # Object is new, so field hasn't technically changed.
else:
if not obj.master == instance.master: # Field has changed
obj.master.delete(save=False)
instance.delete_all_renditions() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def photo_post_delete_handler(sender, **kwargs):
'''delete image when rows is gone from database'''
instance = kwargs.get('instance')
instance.master.delete(save=False)
instance.delete_all_renditions() |
<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_rendition_size(self, width=0, height=0):
'''returns real rendition URL'''
if width == 0 and height == 0:
return (self.master_width, self.master_height)
target_width = int(width)
target_height = int(height)
ratio = self.master_width / float(self.master_height)
if target_height == 0 and target_width != 0:
target_height = int(target_width / ratio)
if target_height != 0 and target_width == 0:
target_width = int(target_height * ratio)
return target_width, target_height |
<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_rendition_url(self, width=0, height=0):
'''get the rendition URL for a specified size
if the renditions does not exists it will be created
'''
if width == 0 and height == 0:
return self.get_master_url()
target_width, target_height = self.get_rendition_size(width, height)
key = '%sx%s' % (target_width, target_height)
if not self.renditions:
self.renditions = {}
rendition_name = self.renditions.get(key, False)
if not rendition_name:
rendition_name = self.make_rendition(target_width, target_height)
return default_storage.url(rendition_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def delete_all_renditions(self):
'''delete all renditions and rendition dict'''
if self.renditions:
for r in self.renditions.values():
default_storage.delete(r)
self.renditions = {} |
<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_rendition(self, width, height):
'''build a rendition
0 x 0 -> will give master URL
only width -> will make a renditions with master's aspect ratio
width x height -> will make an image potentialy cropped
'''
image = Image.open(self.master)
format = image.format
target_w = float(width)
target_h = float(height)
if (target_w == 0):
target_w = self.master_width
if (target_h == 0):
target_h = self.master_height
rendition_key = '%dx%d' % (target_w, target_h)
if rendition_key in self.renditions:
return self.renditions[rendition_key]
if (target_w != self.master_width or target_h != self.master_height):
r = target_w / target_h
R = float(self.master_width) / self.master_height
if r != R:
if r > R:
crop_w = self.master_width
crop_h = crop_w / r
x = 0
y = int(self.master_height - crop_h) >> 1
else:
crop_h = self.master_height
crop_w = crop_h * r
x = int(self.master_width - crop_w) >> 1
y = 0
image = image.crop((x, y, int(crop_w + x), int(crop_h + y)))
image.thumbnail((int(target_w), int(target_h)), Image.ANTIALIAS)
filename, ext = os.path.splitext(self.get_master_filename())
rendition_name = '%s/%s_%s%s' % (
IMAGE_DIRECTORY,
filename,
rendition_key,
ext
)
fd = BytesIO()
image.save(fd, format)
default_storage.save(rendition_name, fd)
self.renditions[rendition_key] = rendition_name
self.save()
return rendition_name
return self.master.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 execute_actioncollection(obj, actioncollection, confirm=True):
"""Execute the given actioncollection with the given object :param obj: the object to be processed :param actioncollection: :type actioncollection: :class:`ActionCollection` :param confirm: If True, ask the user to continue, if actions failed. :type confirm: :class:`bool` :returns: An action status. If the execution fails but the user confirms, the status will be successful. :rtype: :class:`ActionStatus` :raises: None """ |
actioncollection.execute(obj)
status = actioncollection.status()
if status.value == ActionStatus.SUCCESS or not confirm:
return status
ard = ActionReportDialog(actioncollection)
confirmed = ard.exec_()
if confirmed:
msg = "User confirmed to continue although the status was: %s" % status.message,
s = ActionStatus.SUCCESS
tb = status.traceback
else:
s = status.value
msg = "User aborted the actions because the status was: %s" % status.message,
tb = status.traceback
return ActionStatus(s, msg, tb) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def release(self):
"""Create a release 1. Perform Sanity checks on work file. 2. Copy work file to releasefile location. 3. Perform cleanup actions on releasefile. :returns: True if successfull, False if not. :rtype: bool :raises: None """ |
log.info("Releasing: %s", self._workfile.get_fullpath())
ac = self.build_actions()
ac.execute(self)
s = ac.status().value
if not s == ActionStatus.SUCCESS:
ard = ActionReportDialog(ac)
ard.exec_()
pass
return s == ActionStatus.SUCCESS |
<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_actions(self):
"""Create an ActionCollection that will perform sanity checks, copy the file, create a database entry and perform cleanup actions and in case of a failure clean everything up. :param work: the workfile :type work: :class:`JB_File` :param release: the releasefile :type release: :class:`JB_File` :param checks: the action collection object with sanity checks It should accept a :class:`JB_File` as object for execute. :type checks: :class:`ActionCollection` :param cleanup: a action collection object that holds cleanup actions for the given file. It should accept a :class:`JB_File` as object for execute. :type cleanup: :class:`ActionCollection` :param comment: comment for the release :type comment: :class:`str` :returns: An ActionCollection ready to execute. :rtype: :class:`ActionCollection` :raises: None """ |
checkau = ActionUnit("Sanity Checks",
"Check the workfile. If the file is not conform, ask the user to continue.",
self.sanity_check)
copyau = ActionUnit("Copy File",
"Copy the workfile to the releasefile location.",
self.copy,
depsuccess=[checkau])
dbau = ActionUnit("Create DB entry",
"Create an entry in the database for the releasefile",
self.create_db_entry,
depsuccess=[copyau])
cleanau = ActionUnit("Cleanup",
"Cleanup the releasefile. If something fails, ask the user to continue.",
self.cleanup,
depsuccess=[dbau])
deletefau1 = ActionUnit("Delete the releasefile.",
"In case the db entry creation fails, delete the releasefile.",
self.delete_releasefile,
depfail=[dbau])
deletefau2 = ActionUnit("Delete the releasefile.",
"In case the cleanup fails, delete the releasefile.",
self.delete_releasefile,
depsuccess=[copyau],
depfail=[cleanau])
deletedbau = ActionUnit("Delete the database entry.",
"In case the cleanup fails, delete the database entry",
self.delete_db_entry,
depsuccess=[dbau],
depfail=[cleanau])
return ActionCollection([checkau, copyau, dbau, cleanau, deletefau1, deletefau2, deletedbau]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sanity_check(self, release):
"""Perform sanity checks on the workfile of the given release This is inteded to be used in a action unit. :param release: the release with the workfile and sanity checks :type release: :class:`Release` :returns: the action status of the sanity checks :rtype: :class:`ActionStatus` :raises: None """ |
log.info("Performing sanity checks.")
return execute_actioncollection(release._workfile, actioncollection=release._checks, confirm=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 copy(self, release):
"""Copy the workfile of the given release to the releasefile location This is inteded to be used in a action unit. :param release: the release with the release and workfile :type release: :class:`Release` :returns: an action status :rtype: :class:`ActionStatus` :raises: None """ |
workfp = release._workfile.get_fullpath()
releasefp = release._releasefile.get_fullpath()
copy_file(release._workfile, release._releasefile)
return ActionStatus(ActionStatus.SUCCESS,
msg="Copied %s to %s location." % (workfp,
releasefp)) |
<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_db_entry(self, release):
"""Create a db entry for releasefile of the given release Set _releasedbentry and _commentdbentry of the given release file This is inteded to be used in a action unit. :param release: the release with the releasefile and comment :type release: :class:`Release` :returns: an action status :rtype: :class:`ActionStatus` :raises: ValidationError, If the comment could not be created, the TaskFile is deleted and the Exception is propagated. """ |
log.info("Create database entry with comment: %s", release.comment)
tfi = release._releasefile.get_obj()
tf, note = tfi.create_db_entry(release.comment)
release._releasedbentry = tf
release._commentdbentry = note
return ActionStatus(ActionStatus.SUCCESS,
msg="Created database entry for the release filw with comment: %s" % release.comment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup(self, release):
"""Perform cleanup actions on the releasefile of the given release This is inteded to be used in a action unit. :param release: the release with the releasefile and cleanup actions :type release: :class:`Release` :returns: the action status of the cleanup actions :rtype: :class:`ActionStatus` :raises: None """ |
log.info("Performing cleanup.")
return execute_actioncollection(release._releasefile, actioncollection=release._cleanup, confirm=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 delete_releasefile(self, release):
"""Delete the releasefile of the given release This is inteded to be used in a action unit. :param release: the release with the releasefile :type release: :class:`Release` :returns: an action status :rtype: :class:`ActionStatus` :raises: None """ |
fp = release._releasefile.get_fullpath()
log.info("Deleting release file %s", fp)
delete_file(release._releasefile)
return ActionStatus(ActionStatus.SUCCESS,
msg="Deleted %s" % fp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_db_entry(self, release):
"""Delete the db entries for releasefile and comment of the given release :param release: the release with the releasefile and comment db entries :type release: :class:`Release` :returns: an action status :rtype: :class:`ActionStatus` :raises: None """ |
log.info("Delete database entry for file.")
release._releasedbentry.delete()
log.info("Delete database entry for comment.")
release._commentdbentry.delete()
return ActionStatus(ActionStatus.SUCCESS,
msg="Deleted database entries for releasefile and comment") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def socket_reader(connection: socket, buffer_size: int = 1024):
""" read data from adb socket """ |
while connection is not None:
try:
buffer = connection.recv(buffer_size)
# no output
if not len(buffer):
raise ConnectionAbortedError
except ConnectionAbortedError:
# socket closed
print('connection aborted')
connection.close()
yield None
except OSError:
# still operate connection after it was closed
print('socket closed')
connection.close()
yield None
else:
yield buffer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.