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 fetch(self, addon_id, data={}, **kwargs):
"""" Fetch addon for given Id Args: addon_id : Id for which addon object has to be retrieved Returns: addon dict for given subscription Id """ |
return super(Addon, self).fetch(addon_id, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, addon_id, data={}, **kwargs):
""" Delete addon for given id Args: addon_id : Id for which addon object has to be deleted """ |
return super(Addon, self).delete(addon_id, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, data={}, **kwargs):
"""" Fetch All Refund Returns: Refund dict """ |
return super(Refund, self).all(data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self, refund_id, data={}, **kwargs):
"""" Refund object for given paymnet Id Args: refund_id : Refund Id for which refund has to be retrieved Returns: Refund dict for given refund Id """ |
return super(Refund, self).fetch(refund_id, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, data={}, **kwargs):
"""" Fetch all Payment entities Returns: Dictionary of Payment data """ |
return super(Payment, self).all(data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self, payment_id, data={}, **kwargs):
"""" Fetch Payment for given Id Args: payment_id : Id for which payment object has to be retrieved Returns: Payment dict for given payment Id """ |
return super(Payment, self).fetch(payment_id, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def capture(self, payment_id, amount, data={}, **kwargs):
"""" Capture Payment for given Id Args: payment_id : Id for which payment object has to be retrieved Amount : Amount for which the payment has to be retrieved Returns: Payment dict after getting captured """ |
url = "{}/{}/capture".format(self.base_url, payment_id)
data['amount'] = amount
return self.post_url(url, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transfer(self, payment_id, data={}, **kwargs):
"""" Create Transfer for given Payment Id Args: payment_id : Id for which payment object has to be transfered Returns: Payment dict after getting transfered """ |
url = "{}/{}/transfers".format(self.base_url, payment_id)
return self.post_url(url, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transfers(self, payment_id, data={}, **kwargs):
"""" Fetches all transfer for given Payment Id Args: payment_id : Id for which payment object has to be refunded Amount : Amount for which the payment has to be refunded Returns: Payment dict after getting refunded """ |
url = "{}/{}/transfers".format(self.base_url, payment_id)
return self.get_url(url, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self, plan_id, data={}, **kwargs):
"""" Fetch Plan for given Id Args: plan_id : Id for which Plan object has to be retrieved Returns: Plan dict for given subscription Id """ |
return super(Plan, self).fetch(plan_id, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, data={}, **kwargs):
"""" Fetch all plan entities Returns: Dictionary of plan data """ |
return super(Plan, self).all(data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self, customer_id, token_id, data={}, **kwargs):
"""" Fetch Token for given Id and given customer Id Args: customer_id : Customer Id for which tokens have to be fetched token_id : Id for which TOken object has to be fetched Returns: Token dict for given token Id """ |
url = "{}/{}/tokens/{}".format(self.base_url, customer_id, token_id)
return self.get_url(url, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, customer_id, data={}, **kwargs):
"""" Get all tokens for given customer Id Args: customer_id : Customer Id for which tokens have to be fetched Returns: Token dicts for given cutomer Id """ |
url = "{}/{}/tokens".format(self.base_url, customer_id)
return self.get_url(url, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, customer_id, token_id, data={}, **kwargs):
"""" Delete Given Token For a Customer Args: customer_id : Customer Id for which tokens have to be deleted token_id : Id for which TOken object has to be deleted Returns: Dict for deleted token """ |
url = "{}/{}/tokens/{}".format(self.base_url, customer_id, token_id)
return self.delete_url(url, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, data={}, **kwargs):
"""" Fetch all Settlement entities Returns: Dictionary of Settlement data """ |
return super(Settlement, self).all(data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self, settlement_id, data={}, **kwargs):
"""" Fetch Settlement data for given Id Args: settlement_id : Id for which settlement object has to be retrieved Returns: settlement dict for given settlement id """ |
return super(Settlement, self).fetch(settlement_id, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare_string(self, expected_str, actual_str):
""" Returns True if the two strings are equal, False otherwise The time taken is independent of the number of characters that match For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when they have different lengths """ |
if len(expected_str) != len(actual_str):
return False
result = 0
for x, y in zip(expected_str, actual_str):
result |= ord(x) ^ ord(y)
return result == 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 all(self, data={}, **kwargs):
"""" Fetch all Transfer entities Returns: Dictionary of Transfer data """ |
if 'payment_id' in data:
url = "/payments/{}/transfers".format(data['payment_id'])
del data['payment_id']
return self.get_url(url, data, **kwargs)
return super(Transfer, self).all(data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self, transfer_id, data={}, **kwargs):
"""" Fetch Transfer for given Id Args: transfer_id : Id for which transfer object has to be retrieved Returns: Transfer dict for given transfer Id """ |
return super(Transfer, self).fetch(transfer_id, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reverse(self, transfer_id, data={}, **kwargs):
"""" Reverse Transfer from given id Args: transfer_id : Id for which transfer object has to be reversed Returns: Transfer Dict which was reversed """ |
url = "{}/{}/reversals".format(self.base_url, transfer_id)
return self.post_url(url, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reversals(self, transfer_id, data={}, **kwargs):
"""" Get all Reversal Transfer from given id Args: transfer_id : Id for which reversal transfer object has to be fetched Returns: Transfer Dict """ |
url = "{}/{}/reversals".format(self.base_url, transfer_id)
return self.get_url(url, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, method, path, **options):
""" Dispatches a request to the Razorpay HTTP API """ |
options = self._update_user_agent_header(options)
url = "{}{}".format(self.base_url, path)
response = getattr(self.session, method)(url, auth=self.auth,
verify=self.cert_path,
**options)
if ((response.status_code >= HTTP_STATUS_CODE.OK) and
(response.status_code < HTTP_STATUS_CODE.REDIRECT)):
return response.json()
else:
msg = ""
code = ""
json_response = response.json()
if 'error' in json_response:
if 'description' in json_response['error']:
msg = json_response['error']['description']
if 'code' in json_response['error']:
code = str(json_response['error']['code'])
if str.upper(code) == ERROR_CODE.BAD_REQUEST_ERROR:
raise BadRequestError(msg)
elif str.upper(code) == ERROR_CODE.GATEWAY_ERROR:
raise GatewayError(msg)
elif str.upper(code) == ERROR_CODE.SERVER_ERROR:
raise ServerError(msg)
else:
raise ServerError(msg) |
<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, params, **options):
""" Parses GET request options and dispatches a request """ |
return self.request('get', path, params=params, **options) |
<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, path, data, **options):
""" Parses POST request options and dispatches a request """ |
data, options = self._update_request(data, options)
return self.request('post', path, data=data, **options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patch(self, path, data, **options):
""" Parses PATCH request options and dispatches a request """ |
data, options = self._update_request(data, options)
return self.request('patch', path, data=data, **options) |
<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(self, path, data, **options):
""" Parses DELETE request options and dispatches a request """ |
data, options = self._update_request(data, options)
return self.request('delete', path, data=data, **options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, path, data, **options):
""" Parses PUT request options and dispatches a request """ |
data, options = self._update_request(data, options)
return self.request('put', path, data=data, **options) |
<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_request(self, data, options):
""" Updates The resource data and header options """ |
data = json.dumps(data)
if 'headers' not in options:
options['headers'] = {}
options['headers'].update({'Content-type': 'application/json'})
return data, options |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, data={}, **kwargs):
"""" Fetch all Invoice entities Returns: Dictionary of Invoice data """ |
return super(Invoice, self).all(data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self, invoice_id, data={}, **kwargs):
"""" Fetch Invoice for given Id Args: invoice_id : Id for which invoice object has to be retrieved Returns: Invoice dict for given invoice Id """ |
return super(Invoice, self).fetch(invoice_id, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cancel(self, invoice_id, **kwargs):
"""" Cancel an unpaid Invoice with given ID via API It can only be called on an invoice that is not in the paid state. Args: invoice_id : Id for cancel the invoice Returns: The response for the API will be the invoice entity, similar to create/update API response, with status attribute's value as cancelled """ |
url = "{}/{}/cancel".format(self.base_url, invoice_id)
return self.post_url(url, {}, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, invoice_id, **kwargs):
"""" Delete an invoice You can delete an invoice which is in the draft state. Args: invoice_id : Id for delete the invoice Returns: The response is always be an empty array like this - [] """ |
url = "{}/{}".format(self.base_url, invoice_id)
return self.delete_url(url, {}, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def issue(self, invoice_id, **kwargs):
"""" Issues an invoice in draft state Args: invoice_id : Id for delete the invoice Returns: Its response is the invoice entity, similar to create/update API response. Its status now would be issued. """ |
url = "{}/{}/issue".format(self.base_url, invoice_id)
return self.post_url(url, {}, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def edit(self, invoice_id, data={}, **kwargs):
"""" Update an invoice In draft state all the attributes are allowed. Args: invoice_id : Id for delete the invoice data : Dictionary having keys using which invoice have to be updated Returns: Its response is the invoice entity, similar to create/update API response. Its status now would be issued. Refer https://razorpay.com/docs/invoices/api/#entity-structure """ |
url = "{}/{}".format(self.base_url, invoice_id)
return self.patch_url(url, data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pad_added(self, element, pad):
"""The callback for GstElement's "pad-added" signal. """ |
# Decoded data is ready. Connect up the decoder, finally.
name = pad.query_caps(None).to_string()
if name.startswith('audio/x-raw'):
nextpad = self.conv.get_static_pad('sink')
if not nextpad.is_linked():
self._got_a_pad = True
pad.link(nextpad) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _no_more_pads(self, element):
"""The callback for GstElement's "no-more-pads" signal. """ |
# Sent when the pads are done adding (i.e., there are no more
# streams in the file). If we haven't gotten at least one
# decodable stream, raise an exception.
if not self._got_a_pad:
self.read_exc = NoStreamError()
self.ready_sem.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 _new_sample(self, sink):
"""The callback for appsink's "new-sample" signal. """ |
if self.running:
# New data is available from the pipeline! Dump it into our
# queue (or possibly block if we're full).
buf = sink.emit('pull-sample').get_buffer()
# We can't use Gst.Buffer.extract() to read the data as it crashes
# when called through PyGObject. We also can't use
# Gst.Buffer.extract_dup() because we have no way in Python to free
# the memory that it returns. Instead we get access to the actual
# data via Gst.Memory.map().
mem = buf.get_all_memory()
success, info = mem.map(Gst.MapFlags.READ)
if success:
data = info.data
mem.unmap(info)
self.queue.put(data)
else:
raise GStreamerError("Unable to map buffer memory while reading the file.")
return Gst.FlowReturn.OK |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unkown_type(self, uridecodebin, decodebin, caps):
"""The callback for decodebin's "unknown-type" signal. """ |
# This is called *before* the stream becomes ready when the
# file can't be read.
streaminfo = caps.to_string()
if not streaminfo.startswith('audio/'):
# Ignore non-audio (e.g., video) decode errors.
return
self.read_exc = UnknownTypeError(streaminfo)
self.ready_sem.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 close(self, force=False):
"""Close the file and clean up associated resources. Calling `close()` a second time has no effect. """ |
if self.running or force:
self.running = False
self.finished = True
# Unregister for signals, which we registered for above with
# `add_signal_watch`. (Without this, GStreamer leaks file
# descriptors.)
self.pipeline.get_bus().remove_signal_watch()
# Stop reading the file.
self.dec.set_property("uri", None)
# Block spurious signals.
self.sink.get_static_pad("sink").disconnect(self.caps_handler)
# Make space in the output queue to let the decoder thread
# finish. (Otherwise, the thread blocks on its enqueue and
# the interpreter hangs.)
try:
self.queue.get_nowait()
except queue.Empty:
pass
# Halt the pipeline (closing file).
self.pipeline.set_state(Gst.State.NULL)
# Delete the pipeline object. This seems to be necessary on Python
# 2, but not Python 3 for some reason: on 3.5, at least, the
# pipeline gets dereferenced automatically.
del self.pipeline |
<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_data(self, block_samples=1024):
"""Generates blocks of PCM data found in the file.""" |
old_width = self._file.getsampwidth()
while True:
data = self._file.readframes(block_samples)
if not data:
break
# Make sure we have the desired bitdepth and endianness.
data = audioop.lin2lin(data, old_width, TARGET_WIDTH)
if self._needs_byteswap and self._file.getcomptype() != 'sowt':
# Big-endian data. Swap endianness.
data = byteswap(data)
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 _gst_available():
"""Determine whether Gstreamer and the Python GObject bindings are installed. """ |
try:
import gi
except ImportError:
return False
try:
gi.require_version('Gst', '1.0')
except (ValueError, AttributeError):
return False
try:
from gi.repository import Gst # noqa
except ImportError:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def available_backends():
"""Returns a list of backends that are available on this system.""" |
# Standard-library WAV and AIFF readers.
from . import rawread
result = [rawread.RawAudioFile]
# Core Audio.
if _ca_available():
from . import macca
result.append(macca.ExtAudioFile)
# GStreamer.
if _gst_available():
from . import gstdec
result.append(gstdec.GstAudioFile)
# MAD.
if _mad_available():
from . import maddec
result.append(maddec.MadAudioFile)
# FFmpeg.
if ffdec.available():
result.append(ffdec.FFmpegAudioFile)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def audio_open(path, backends=None):
"""Open an audio file using a library that is available on this system. The optional `backends` parameter can be a list of audio file classes to try opening the file with. If it is not provided, `audio_open` tries all available backends. If you call this function many times, you can avoid the cost of checking for available backends every time by calling `available_backends` once and passing the result to each `audio_open` call. If all backends fail to read the file, a NoBackendError exception is raised. """ |
if backends is None:
backends = available_backends()
for BackendClass in backends:
try:
return BackendClass(path)
except DecodeError:
pass
# All backends failed!
raise NoBackendError() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def popen_multiple(commands, command_args, *args, **kwargs):
"""Like `subprocess.Popen`, but can try multiple commands in case some are not available. `commands` is an iterable of command names and `command_args` are the rest of the arguments that, when appended to the command name, make up the full first argument to `subprocess.Popen`. The other positional and keyword arguments are passed through. """ |
for i, command in enumerate(commands):
cmd = [command] + command_args
try:
return subprocess.Popen(cmd, *args, **kwargs)
except OSError:
if i == len(commands) - 1:
# No more commands to try.
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def available():
"""Detect if the FFmpeg backend can be used on this system.""" |
proc = popen_multiple(
COMMANDS,
['-version'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
creationflags=PROC_FLAGS,
)
proc.wait()
return (proc.returncode == 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 read_data(self, timeout=10.0):
"""Read blocks of raw PCM data from the file.""" |
# Read from stdout in a separate thread and consume data from
# the queue.
start_time = time.time()
while True:
# Wait for data to be available or a timeout.
data = None
try:
data = self.stdout_reader.queue.get(timeout=timeout)
if data:
yield data
else:
# End of file.
break
except queue.Empty:
# Queue read timed out.
end_time = time.time()
if not data:
if end_time - start_time >= timeout:
# Nothing interesting has happened for a while --
# FFmpeg is probably hanging.
raise ReadTimeoutError('ffmpeg output: {}'.format(
''.join(self.stderr_reader.queue.queue)
))
else:
start_time = end_time
# Keep waiting.
continue |
<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_info(self):
"""Reads the tool's output from its stderr stream, extracts the relevant information, and parses it. """ |
out_parts = []
while True:
line = self.proc.stderr.readline()
if not line:
# EOF and data not found.
raise CommunicationError("stream info not found")
# In Python 3, result of reading from stderr is bytes.
if isinstance(line, bytes):
line = line.decode('utf8', 'ignore')
line = line.strip().lower()
if 'no such file' in line:
raise IOError('file not found')
elif 'invalid data found' in line:
raise UnsupportedError()
elif 'duration:' in line:
out_parts.append(line)
elif 'audio:' in line:
out_parts.append(line)
self._parse_info(''.join(out_parts))
break |
<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_info(self, s):
"""Given relevant data from the ffmpeg output, set audio parameter fields on this object. """ |
# Sample rate.
match = re.search(r'(\d+) hz', s)
if match:
self.samplerate = int(match.group(1))
else:
self.samplerate = 0
# Channel count.
match = re.search(r'hz, ([^,]+),', s)
if match:
mode = match.group(1)
if mode == 'stereo':
self.channels = 2
else:
cmatch = re.match(r'(\d+)\.?(\d)?', mode)
if cmatch:
self.channels = sum(map(int, cmatch.group().split('.')))
else:
self.channels = 1
else:
self.channels = 0
# Duration.
match = re.search(
r'duration: (\d+):(\d+):(\d+).(\d)', s
)
if match:
durparts = list(map(int, match.groups()))
duration = (
durparts[0] * 60 * 60 +
durparts[1] * 60 +
durparts[2] +
float(durparts[3]) / 10
)
self.duration = duration
else:
# No duration found.
self.duration = 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 close(self):
"""Close the ffmpeg process used to perform the decoding.""" |
if hasattr(self, 'proc'):
# First check the process's execution status before attempting to
# kill it. This fixes an issue on Windows Subsystem for Linux where
# ffmpeg closes normally on its own, but never updates
# `returncode`.
self.proc.poll()
# Kill the process if it is still running.
if self.proc.returncode is None:
self.proc.kill()
self.proc.wait()
# Wait for the stream-reading threads to exit. (They need to
# stop reading before we can close the streams.)
if hasattr(self, 'stderr_reader'):
self.stderr_reader.join()
if hasattr(self, 'stdout_reader'):
self.stdout_reader.join()
# Close the stdout and stderr streams that were opened by Popen,
# which should occur regardless of if the process terminated
# cleanly.
self.proc.stdout.close()
self.proc.stderr.close()
# Close the handle to os.devnull, which is opened regardless of if
# a subprocess is successfully created.
self.devnull.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 read_blocks(self, block_size=4096):
"""Generates buffers containing PCM data for the audio file. """ |
while True:
out = self.mf.read(block_size)
if not out:
break
yield bytes(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 channels(self):
"""The number of channels.""" |
if self.mf.mode() == mad.MODE_SINGLE_CHANNEL:
return 1
elif self.mf.mode() in (mad.MODE_DUAL_CHANNEL,
mad.MODE_JOINT_STEREO,
mad.MODE_STEREO):
return 2
else:
# Other mode?
return 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 multi_char_literal(chars):
"""Emulates character integer literals in C. Given a string "abc", returns the value of the C single-quoted literal 'abc'. """ |
num = 0
for index, char in enumerate(chars):
shift = (len(chars) - index - 1) * 8
num |= ord(char) << shift
return num |
<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_url(cls, url):
"""Given a CFURL Python object, return an opened ExtAudioFileRef. """ |
file_obj = ctypes.c_void_p()
check(_coreaudio.ExtAudioFileOpenURL(
url._obj, ctypes.byref(file_obj)
))
return file_obj |
<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_client_format(self, desc):
"""Get the client format description. This describes the encoding of the data that the program will read from this object. """ |
assert desc.mFormatID == AUDIO_ID_PCM
check(_coreaudio.ExtAudioFileSetProperty(
self._obj, PROP_CLIENT_DATA_FORMAT, ctypes.sizeof(desc),
ctypes.byref(desc)
))
self._client_fmt = desc |
<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_file_format(self):
"""Get the file format description. This describes the type of data stored on disk. """ |
# Have cached file format?
if self._file_fmt is not None:
return self._file_fmt
# Make the call to retrieve it.
desc = AudioStreamBasicDescription()
size = ctypes.c_int(ctypes.sizeof(desc))
check(_coreaudio.ExtAudioFileGetProperty(
self._obj, PROP_FILE_DATA_FORMAT, ctypes.byref(size),
ctypes.byref(desc)
))
# Cache result.
self._file_fmt = desc
return desc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nframes(self):
"""Gets the number of frames in the source file.""" |
length = ctypes.c_long()
size = ctypes.c_int(ctypes.sizeof(length))
check(_coreaudio.ExtAudioFileGetProperty(
self._obj, PROP_LENGTH, ctypes.byref(size), ctypes.byref(length)
))
return length.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 setup(self, bitdepth=16):
"""Set the client format parameters, specifying the desired PCM audio data format to be read from the file. Must be called before reading from the file. """ |
fmt = self.get_file_format()
newfmt = copy.copy(fmt)
newfmt.mFormatID = AUDIO_ID_PCM
newfmt.mFormatFlags = \
PCM_IS_SIGNED_INT | PCM_IS_PACKED
newfmt.mBitsPerChannel = bitdepth
newfmt.mBytesPerPacket = \
(fmt.mChannelsPerFrame * newfmt.mBitsPerChannel // 8)
newfmt.mFramesPerPacket = 1
newfmt.mBytesPerFrame = newfmt.mBytesPerPacket
self.set_client_format(newfmt) |
<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_data(self, blocksize=4096):
"""Generates byte strings reflecting the audio data in the file. """ |
frames = ctypes.c_uint(blocksize // self._client_fmt.mBytesPerFrame)
buf = ctypes.create_string_buffer(blocksize)
buflist = AudioBufferList()
buflist.mNumberBuffers = 1
buflist.mBuffers[0].mNumberChannels = \
self._client_fmt.mChannelsPerFrame
buflist.mBuffers[0].mDataByteSize = blocksize
buflist.mBuffers[0].mData = ctypes.cast(buf, ctypes.c_void_p)
while True:
check(_coreaudio.ExtAudioFileRead(
self._obj, ctypes.byref(frames), ctypes.byref(buflist)
))
assert buflist.mNumberBuffers == 1
size = buflist.mBuffers[0].mDataByteSize
if not size:
break
data = ctypes.cast(buflist.mBuffers[0].mData,
ctypes.POINTER(ctypes.c_char))
blob = data[:size]
yield blob |
<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 audio file and free associated memory.""" |
if not self.closed:
check(_coreaudio.ExtAudioFileDispose(self._obj))
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 mount(self, url, app):
"Mount a sub-app at the url of current app."
# Inspired by Bottle. It might seem that dispatching to
# subapps would rather be handled by normal routes, but
# arguably, that's less efficient. Taking into account
# that paradigmatically there's difference between handing
# an action and delegating responisibilities to another
# app, Bottle's way was followed.
app.url = url
self.mounts.append(app) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _map(expr, func, rtype=None, resources=None, args=(), **kwargs):
""" Call func on each element of this sequence. :param func: lambda, function, :class:`odps.models.Function`, or str which is the name of :class:`odps.models.Funtion` :param rtype: if not provided, will be the dtype of this sequence :return: a new sequence :Example: """ |
name = None
if isinstance(func, FunctionWrapper):
if func.output_names:
if len(func.output_names) > 1:
raise ValueError('Map column has more than one name')
name = func.output_names[0]
if func.output_types:
rtype = rtype or func.output_types[0]
func = func._func
if rtype is None:
rtype = utils.get_annotation_rtype(func)
from ...models import Function
rtype = rtype or expr.dtype
output_type = types.validate_data_type(rtype)
if isinstance(func, six.string_types):
pass
elif isinstance(func, Function):
pass
elif inspect.isclass(func):
pass
elif not callable(func):
raise ValueError('`func` must be a function or a callable class')
collection_resources = utils.get_collection_resources(resources)
is_seq = isinstance(expr, SequenceExpr)
if is_seq:
return MappedExpr(_data_type=output_type, _func=func, _inputs=[expr, ],
_func_args=args, _func_kwargs=kwargs, _name=name,
_resources=resources, _collection_resources=collection_resources)
else:
return MappedExpr(_value_type=output_type, _func=func, _inputs=[expr, ],
_func_args=args, _func_kwargs=kwargs, _name=name,
_resources=resources, _collection_resources=collection_resources) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _hash(expr, func=None):
""" Calculate the hash value. :param expr: :param func: hash function :return: """ |
if func is None:
func = lambda x: hash(x)
return _map(expr, func=func, rtype=types.int64) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _isnull(expr):
""" Return a sequence or scalar according to the input indicating if the values are null. :param expr: sequence or scalar :return: sequence or scalar """ |
if isinstance(expr, SequenceExpr):
return IsNull(_input=expr, _data_type=types.boolean)
elif isinstance(expr, Scalar):
return IsNull(_input=expr, _value_type=types.boolean) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _notnull(expr):
""" Return a sequence or scalar according to the input indicating if the values are not null. :param expr: sequence or scalar :return: sequence or scalar """ |
if isinstance(expr, SequenceExpr):
return NotNull(_input=expr, _data_type=types.boolean)
elif isinstance(expr, Scalar):
return NotNull(_input=expr, _value_type=types.boolean) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fillna(expr, value):
""" Fill null with value. :param expr: sequence or scalar :param value: value to fill into :return: sequence or scalar """ |
if isinstance(expr, SequenceExpr):
return FillNa(_input=expr, _fill_value=value, _data_type=expr.dtype)
elif isinstance(expr, Scalar):
return FillNa(_input=expr, _fill_value=value, _value_type=expr.dtype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _isin(expr, values):
""" Return a boolean sequence or scalar showing whether each element is exactly contained in the passed `values`. :param expr: sequence or scalar :param values: `list` object or sequence :return: boolean sequence or scalar """ |
from .merge import _make_different_sources
if isinstance(values, SequenceExpr):
expr, values = _make_different_sources(expr, values)
if isinstance(expr, SequenceExpr):
return IsIn(_input=expr, _values=values, _data_type=types.boolean)
elif isinstance(expr, Scalar):
return IsIn(_input=expr, _values=values, _value_type=types.boolean) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _notin(expr, values):
""" Return a boolean sequence or scalar showing whether each element is not contained in the passed `values`. :param expr: sequence or scalar :param values: `list` object or sequence :return: boolean sequence or scalar """ |
if isinstance(expr, SequenceExpr):
return NotIn(_input=expr, _values=values, _data_type=types.boolean)
elif isinstance(expr, Scalar):
return NotIn(_input=expr, _values=values, _value_type=types.boolean) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _between(expr, left, right, inclusive=True):
""" Return a boolean sequence or scalar show whether each element is between `left` and `right`. :param expr: sequence or scalar :param left: left value :param right: right value :param inclusive: if true, will be left <= expr <= right, else will be left < expr < right :return: boolean sequence or scalar """ |
if isinstance(expr, SequenceExpr):
return Between(_input=expr, _left=left, _right=right,
_inclusive=inclusive, _data_type=types.boolean)
elif isinstance(expr, Scalar):
return Between(_input=expr, _left=left, _right=right,
_inclusive=inclusive, _value_type=types.boolean) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ifelse(expr, true_expr, false_expr):
""" Given a boolean sequence or scalar, if true will return the left, else return the right one. :param expr: sequence or scalar :param true_expr: :param false_expr: :return: sequence or scalar :Example: """ |
tps = (SequenceExpr, Scalar)
if not isinstance(true_expr, tps):
true_expr = Scalar(_value=true_expr)
if not isinstance(false_expr, tps):
false_expr = Scalar(_value=false_expr)
output_type = utils.highest_precedence_data_type(
*[true_expr.dtype, false_expr.dtype])
is_sequence = isinstance(expr, SequenceExpr) or \
isinstance(true_expr, SequenceExpr) or \
isinstance(false_expr, SequenceExpr)
if is_sequence:
return IfElse(_input=expr, _then=true_expr, _else=false_expr,
_data_type=output_type)
else:
return IfElse(_input=expr, _then=true_expr, _else=false_expr,
_value_type=output_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 _switch(expr, *args, **kw):
""" Similar to the case-when in SQL. Refer to the example below :param expr: :param args: :param kw: :return: sequence or scalar :Example: """ |
default = _scalar(kw.get('default'))
if len(args) <= 0:
raise errors.ExpressionError('Switch must accept more than one condition')
if all(isinstance(arg, tuple) and len(arg) == 2 for arg in args):
conditions, thens = zip(*args)
else:
conditions = [arg for i, arg in enumerate(args) if i % 2 == 0]
thens = [arg for i, arg in enumerate(args) if i % 2 == 1]
if len(conditions) == len(thens):
conditions, thens = _scalar(conditions), _scalar(thens)
else:
raise errors.ExpressionError('Switch should be called by case and then pairs')
if isinstance(expr, (Scalar, SequenceExpr)):
case = expr
else:
case = None
if not all(hasattr(it, 'dtype') and it.dtype == types.boolean for it in conditions):
raise errors.ExpressionError('Switch must be called by all boolean conditions')
res = thens if default is None else thens + [default, ]
output_type = utils.highest_precedence_data_type(*(it.dtype for it in res))
is_seq = isinstance(expr, SequenceExpr) or \
any(isinstance(it, SequenceExpr) for it in conditions) or \
any(isinstance(it, SequenceExpr) for it in res)
if case is not None:
is_seq = is_seq or isinstance(case, SequenceExpr)
kwargs = dict()
if is_seq:
kwargs['_data_type'] = output_type
else:
kwargs['_value_type'] = output_type
return Switch(_input=expr, _case=case, _conditions=conditions,
_thens=thens, _default=default, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cut(expr, bins, right=True, labels=None, include_lowest=False, include_under=False, include_over=False):
""" Return indices of half-open bins to which each value of `expr` belongs. :param expr: sequence or scalar :param bins: list of scalars :param right: indicates whether the bins include the rightmost edge or not. If right == True(the default), then the bins [1, 2, 3, 4] indicate (1, 2], (2, 3], (3, 4] :param labels: Usesd as labes for the resulting bins. Must be of the same length as the resulting bins. :param include_lowest: Whether the first interval should be left-inclusive or not. :param include_under: include the bin below the leftmost edge or not :param include_over: include the bin above the rightmost edge or not :return: sequence or scalar """ |
is_seq = isinstance(expr, SequenceExpr)
dtype = utils.highest_precedence_data_type(
*(types.validate_value_type(it) for it in labels)) \
if labels is not None else types.int64
kw = {}
if is_seq:
kw['_data_type'] = dtype
else:
kw['_value_type'] = dtype
return Cut(_input=expr, _bins=bins, _right=right, _labels=labels,
_include_lowest=include_lowest, _include_under=include_under,
_include_over=include_over, **kw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _int_to_datetime(expr):
""" Return a sequence or scalar that is the datetime value of the current numeric sequence or scalar. :param expr: sequence or scalar :return: sequence or scalar """ |
if isinstance(expr, SequenceExpr):
return IntToDatetime(_input=expr, _data_type=types.datetime)
elif isinstance(expr, Scalar):
return IntToDatetime(_input=expr, _value_type=types.datetime) |
<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_ddl(self, with_comments=True, if_not_exists=False):
""" Get DDL SQL statement for the given table. :param with_comments: append comment for table and each column :return: DDL statement """ |
shard_num = self.shard.shard_num if self.shard is not None else None
return self.gen_create_table_sql(
self.name, self.schema, self.comment if with_comments else None,
if_not_exists=if_not_exists, with_column_comments=with_comments,
lifecycle=self.lifecycle, shard_num=shard_num, project=self.project.name,
storage_handler=self.storage_handler, serde_properties=self.serde_properties,
location=self.location, resources=self.resources,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def head(self, limit, partition=None, columns=None):
""" Get the head records of a table or its partition. :param limit: records' size, 10000 at most :param partition: partition of this table :param columns: the columns which is subset of the table columns :type columns: list :return: records :rtype: list .. seealso:: :class:`odps.models.Record` """ |
if limit <= 0:
raise ValueError('limit number should >= 0.')
params = {'data': '', 'linenum': limit}
if partition is not None:
if not isinstance(partition, odps_types.PartitionSpec):
partition = odps_types.PartitionSpec(partition)
params['partition'] = str(partition)
if columns is not None and len(columns) > 0:
col_name = lambda col: col.name if isinstance(col, odps_types.Column) else col
params['cols'] = ','.join(col_name(col) for col in columns)
resp = self._client.get(self.resource(), params=params, stream=True)
with readers.RecordReader(self.schema, resp) as reader:
for record in reader:
yield record |
<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_reader(self, partition=None, **kw):
""" Open the reader to read the entire records from this table or its partition. :param partition: partition of this table :param reopen: the reader will reuse last one, reopen is true means open a new reader. :type reopen: bool :param endpoint: the tunnel service URL :param compress_option: compression algorithm, level and strategy :type compress_option: :class:`odps.tunnel.CompressOption` :param compress_algo: compression algorithm, work when ``compress_option`` is not provided, can be ``zlib``, ``snappy`` :param compress_level: used for ``zlib``, work when ``compress_option`` is not provided :param compress_strategy: used for ``zlib``, work when ``compress_option`` is not provided :param download_id: use existing download_id to download table contents :return: reader, ``count`` means the full size, ``status`` means the tunnel status :Example: """ |
from ..tunnel.tabletunnel import TableDownloadSession
reopen = kw.pop('reopen', False)
endpoint = kw.pop('endpoint', None)
download_id = kw.pop('download_id', None)
tunnel = self._create_table_tunnel(endpoint=endpoint)
if download_id is None:
download_ids = self._download_ids
download_id = download_ids.get(partition) if not reopen else None
download_session = tunnel.create_download_session(table=self, partition_spec=partition,
download_id=download_id, **kw)
if download_id and download_session.status != TableDownloadSession.Status.Normal:
download_session = tunnel.create_download_session(table=self, partition_spec=partition, **kw)
download_ids[partition] = download_session.id
class RecordReader(readers.AbstractRecordReader):
def __init__(self):
self._it = iter(self)
@property
def download_id(self):
return download_session.id
@property
def count(self):
return download_session.count
@property
def status(self):
return download_session.status
def __iter__(self):
for record in self.read():
yield record
def __next__(self):
return next(self._it)
next = __next__
def _iter(self, start=None, end=None, step=None):
count = self._calc_count(start, end, step)
return self.read(start=start, count=count, step=step)
def read(self, start=None, count=None, step=None,
compress=False, columns=None):
start = start or 0
step = step or 1
count = count*step if count is not None else self.count-start
if count == 0:
return
with download_session.open_record_reader(
start, count, compress=compress, columns=columns) as reader:
for record in reader[::step]:
yield record
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
return RecordReader() |
<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_partition(self, partition_spec, if_not_exists=False, async_=False, **kw):
""" Create a partition within the table. :param partition_spec: specification of the partition. :param if_not_exists: :param async_: :return: partition object :rtype: odps.models.partition.Partition """ |
async_ = kw.get('async', async_)
return self.partitions.create(partition_spec, if_not_exists=if_not_exists, async_=async_) |
<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_partition(self, partition_spec, if_exists=False, async_=False, **kw):
""" Delete a partition within the table. :param partition_spec: specification of the partition. :param if_exists: :param async_: """ |
async_ = kw.get('async', async_)
return self.partitions.delete(partition_spec, if_exists=if_exists, async_=async_) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exist_partitions(self, prefix_spec=None):
""" Check if partitions with provided conditions exist. :param prefix_spec: prefix of partition :return: whether partitions exist """ |
try:
next(self.partitions.iterate_partitions(spec=prefix_spec))
except StopIteration:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def truncate(self, async_=False, **kw):
""" truncate this table. :param async_: run asynchronously if True :return: None """ |
from .tasks import SQLTask
async_ = kw.get('async', async_)
task = SQLTask(name='SQLTruncateTableTask', query='truncate table %s.%s' % (self.project.name, self.name))
instance = self.project.parent[self._client.project].instances.create(task=task)
if not async_:
instance.wait_for_success()
else:
return 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 drop(self, async_=False, if_exists=False, **kw):
""" Drop this table. :param async_: run asynchronously if True :return: None """ |
async_ = kw.get('async', async_)
return self.parent.delete(self, async_=async_, if_exists=if_exists) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _strftime(expr, date_format):
""" Return formatted strings specified by date_format, which supports the same string format as the python standard library. Details of the string format can be found in python string format doc :param expr: :param date_format: date format string (e.g. “%Y-%m-%d”) :type date_format: str :return: """ |
return datetime_op(expr, Strftime, output_type=types.string,
_date_format=date_format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort_values(expr, by, ascending=True):
""" Sort the collection by values. `sort` is an alias name for `sort_values` :param expr: collection :param by: the sequence or sequences to sort :param ascending: Sort ascending vs. descending. Sepecify list for multiple sort orders. If this is a list of bools, must match the length of the by :return: Sorted collection :Example: """ |
if not isinstance(by, list):
by = [by, ]
by = [it(expr) if inspect.isfunction(it) else it for it in by]
return SortedCollectionExpr(expr, _sorted_fields=by, _ascending=ascending,
_schema=expr._schema) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def distinct(expr, on=None, *ons):
""" Get collection with duplicate rows removed, optionally only considering certain columns :param expr: collection :param on: sequence or sequences :return: dinstinct collection :Example: """ |
on = on or list()
if not isinstance(on, list):
on = [on, ]
on = on + list(ons)
on = [it(expr) if inspect.isfunction(it) else it for it in on]
return DistinctCollectionExpr(expr, _unique_fields=on, _all=(len(on) == 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 reshuffle(expr, by=None, sort=None, ascending=True):
""" Reshuffle data. :param expr: :param by: the sequence or scalar to shuffle by. RandomScalar as default :param sort: the sequence or scalar to sort. :param ascending: True if ascending else False :return: collection """ |
by = by or RandomScalar()
grouped = expr.groupby(by)
if sort:
grouped = grouped.sort_values(sort, ascending=ascending)
return ReshuffledCollectionExpr(_input=grouped, _schema=expr._schema) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def std_scale(expr, columns=None, with_means=True, with_std=True, preserve=False, suffix='_scaled', group=None):
""" Resize a data frame by mean and standard error. :param DataFrame expr: Input DataFrame :param bool with_means: Determine whether the output will be subtracted by means :param bool with_std: Determine whether the output will be divided by standard deviations :param bool preserve: Determine whether input data should be kept. If True, scaled input data will be appended to the data frame with `suffix` :param columns: Columns names to resize. If set to None, float or int-typed columns will be normalized if the column is not specified as a group column. :param group: determine scale groups. Scaling will be done in each group separately. :param str suffix: column suffix to be appended to the scaled columns. :return: resized data frame :rtype: DataFrame """ |
time_suffix = str(int(time.time()))
def calc_agg(expr, col):
return [
getattr(expr, col).mean().rename(col + '_mean_' + time_suffix),
getattr(expr, col).std(ddof=0).rename(col + '_std_' + time_suffix),
]
def do_scale(expr, col):
c = getattr(expr, col)
mean_expr = getattr(expr, col + '_mean_' + time_suffix)
if with_means:
c = c - mean_expr
mean_expr = Scalar(0)
if with_std:
std_expr = getattr(expr, col + '_std_' + time_suffix)
c = (std_expr == 0).ifelse(mean_expr, c / getattr(expr, col + '_std_' + time_suffix))
return c
return _scale_values(expr, columns, calc_agg, do_scale, preserve=preserve, suffix=suffix, group=group) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_kv(expr, columns=None, kv_delim=':', item_delim=',', dtype='float', fill_value=None):
""" Extract values in key-value represented columns into standalone columns. New column names will be the name of the key-value column followed by an underscore and the key. :param DataFrame expr: input DataFrame :param columns: the key-value columns to be extracted. :param str kv_delim: delimiter between key and value. :param str item_delim: delimiter between key-value pairs. :param str dtype: type of value columns to generate. :param fill_value: default value for missing key-value pairs. :return: extracted data frame :rtype: DataFrame :Example: name kv 0 name1 k1=1.0,k2=3.0,k5=10.0 1 name2 k2=3.0,k3=5.1 2 name3 k1=7.1,k7=8.2 3 name4 k2=1.2,k3=1.5 4 name5 k2=1.0,k9=1.1 name kv_k1 kv_k2 kv_k3 kv_k5 kv_k7 kv_k9 0 name1 1.0 3.0 Nan 10.0 Nan Nan 1 name2 Nan 3.0 5.1 Nan Nan Nan 2 name3 7.1 Nan Nan Nan 8.2 Nan 3 name4 Nan 1.2 1.5 Nan Nan Nan 4 name5 Nan 1.0 Nan Nan Nan 1.1 """ |
if columns is None:
columns = [expr._get_field(c) for c in expr.schema.names]
intact_cols = []
else:
columns = [expr._get_field(c) for c in utils.to_list(columns)]
name_set = set([c.name for c in columns])
intact_cols = [expr._get_field(c) for c in expr.schema.names if c not in name_set]
column_type = types.validate_data_type(dtype)
if any(not isinstance(c.dtype, types.String) for c in columns):
raise ExpressionError('Key-value columns must be strings.')
schema = DynamicSchema.from_lists([c.name for c in intact_cols], [c.dtype for c in intact_cols])
return ExtractKVCollectionExpr(_input=expr, _columns=columns, _intact=intact_cols, _schema=schema,
_column_type=column_type, _default=fill_value,
_kv_delimiter=kv_delim, _item_delimiter=item_delim) |
<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_kv(expr, columns=None, kv_delim=':', item_delim=',', kv_name='kv_col'):
""" Merge values in specified columns into a key-value represented column. :param DataFrame expr: input DataFrame :param columns: the columns to be merged. :param str kv_delim: delimiter between key and value. :param str item_delim: delimiter between key-value pairs. :param str kv_col: name of the new key-value column :return: converted data frame :rtype: DataFrame :Example: name k1 k2 k3 k5 k7 k9 0 name1 1.0 3.0 Nan 10.0 Nan Nan 1 name2 Nan 3.0 5.1 Nan Nan Nan 2 name3 7.1 Nan Nan Nan 8.2 Nan 3 name4 Nan 1.2 1.5 Nan Nan Nan 4 name5 Nan 1.0 Nan Nan Nan 1.1 name kv_col 0 name1 k1=1.0,k2=3.0,k5=10.0 1 name2 k2=3.0,k3=5.1 2 name3 k1=7.1,k7=8.2 3 name4 k2=1.2,k3=1.5 4 name5 k2=1.0,k9=1.1 """ |
if columns is None:
columns = [expr._get_field(c) for c in expr.schema.names]
intact_cols = []
else:
columns = [expr._get_field(c) for c in utils.to_list(columns)]
name_set = set([c.name for c in columns])
intact_cols = [expr._get_field(c) for c in expr.schema.names if c not in name_set]
mapped_cols = [c.isnull().ifelse(Scalar(''), c.name + kv_delim + c.astype('string')) for c in columns]
reduced_col = reduce(lambda a, b: (b == '').ifelse(a, (a == '').ifelse(b, a + item_delim + b)), mapped_cols)
return expr.__getitem__(intact_cols + [reduced_col.rename(kv_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 dropna(expr, how='any', thresh=None, subset=None):
""" Return object with labels on given axis omitted where alternately any or all of the data are missing :param DataFrame expr: input DataFrame :param how: can be ‘any’ or ‘all’. If 'any' is specified any NA values are present, drop that label. If 'all' is specified and all values are NA, drop that label. :param thresh: require that many non-NA values :param subset: Labels along other axis to consider, e.g. if you are dropping rows these would be a list of columns to include :return: DataFrame """ |
if subset is None:
subset = [expr._get_field(c) for c in expr.schema.names]
else:
subset = [expr._get_field(c) for c in utils.to_list(subset)]
if not subset:
raise ValueError('Illegal subset is provided.')
if thresh is None:
thresh = len(subset) if how == 'any' else 1
sum_exprs = reduce(operator.add, (s.notnull().ifelse(1, 0) for s in subset))
return expr.filter(sum_exprs >= thresh) |
<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_id(expr, id_col='append_id'):
""" Append an ID column to current column to form a new DataFrame. :param str id_col: name of appended ID field. :return: DataFrame with ID field :rtype: DataFrame """ |
if hasattr(expr, '_xflow_append_id'):
return expr._xflow_append_id(id_col)
else:
return _append_id(expr, id_col) |
<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(expr, frac, seed=None):
""" Split the current column into two column objects with certain ratio. :param float frac: Split ratio :return: two split DataFrame objects """ |
if hasattr(expr, '_xflow_split'):
return expr._xflow_split(frac, seed=seed)
else:
return _split(expr, frac, seed=seed) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def applymap(expr, func, rtype=None, resources=None, columns=None, excludes=None, args=(), **kwargs):
""" Call func on each element of this collection. :param func: lambda, function, :class:`odps.models.Function`, or str which is the name of :class:`odps.models.Funtion` :param rtype: if not provided, will be the dtype of this sequence :param columns: columns to apply this function on :param excludes: columns to skip when applying the function :return: a new collection :Example: """ |
if columns is not None and excludes is not None:
raise ValueError('`columns` and `excludes` cannot be provided at the same time.')
if not columns:
excludes = excludes or []
if isinstance(excludes, six.string_types):
excludes = [excludes]
excludes = set([c if isinstance(c, six.string_types) else c.name for c in excludes])
columns = set([c for c in expr.schema.names if c not in excludes])
else:
if isinstance(columns, six.string_types):
columns = [columns]
columns = set([c if isinstance(c, six.string_types) else c.name for c in columns])
mapping = [expr[c] if c not in columns
else expr[c].map(func, rtype=rtype, resources=resources, args=args, **kwargs)
for c in expr.schema.names]
return expr.select(*mapping) |
<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_string(self, size):
"""Reads up to 'size' bytes from the stream, stopping early only if we reach the end of the stream. Returns the bytes read as a string. """ |
if size < 0:
raise errors.DecodeError('Negative size %d' % size)
s = self._input.read(size)
if len(s) != size:
raise errors.DecodeError('String claims to have %d bytes, but read %d' % (size, len(s)))
self._pos += len(s) # Only advance by the number of bytes actually read.
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_little_endian32(self):
"""Interprets the next 4 bytes of the stream as a little-endian encoded, unsiged 32-bit integer, and returns that integer. """ |
try:
i = struct.unpack(wire_format.FORMAT_UINT32_LITTLE_ENDIAN,
self._input.read(4))
self._pos += 4
return i[0] # unpack() result is a 1-element tuple.
except struct.error as e:
raise errors.DecodeError(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 read_little_endian64(self):
"""Interprets the next 8 bytes of the stream as a little-endian encoded, unsiged 64-bit integer, and returns that integer. """ |
try:
i = struct.unpack(wire_format.FORMAT_UINT64_LITTLE_ENDIAN,
self._input.read(8))
self._pos += 8
return i[0] # unpack() result is a 1-element tuple.
except struct.error as e:
raise errors.DecodeError(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 read_varint32(self):
"""Reads a varint from the stream, interprets this varint as a signed, 32-bit integer, and returns the integer. """ |
i = self.read_varint64()
if not wire_format.INT32_MIN <= i <= wire_format.INT32_MAX:
raise errors.DecodeError('Value out of range for int32: %d' % i)
return int(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 read_var_uint32(self):
"""Reads a varint from the stream, interprets this varint as an unsigned, 32-bit integer, and returns the integer. """ |
i = self.read_var_uint64()
if i > wire_format.UINT32_MAX:
raise errors.DecodeError('Value out of range for uint32: %d' % i)
return 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 read_varint64(self):
"""Reads a varint from the stream, interprets this varint as a signed, 64-bit integer, and returns the integer. """ |
i = self.read_var_uint64()
if i > wire_format.INT64_MAX:
i -= (1 << 64)
return 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 read_var_uint64(self):
"""Reads a varint from the stream, interprets this varint as an unsigned, 64-bit integer, and returns the integer. """ |
i = self._read_varint_helper()
if not 0 <= i <= wire_format.UINT64_MAX:
raise errors.DecodeError('Value out of range for uint64: %d' % i)
return 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 _read_varint_helper(self):
"""Helper for the various varint-reading methods above. Reads an unsigned, varint-encoded integer from the stream and returns this integer. Does no bounds checking except to ensure that we read at most as many bytes as could possibly be present in a varint-encoded 64-bit number. """ |
result = 0
shift = 0
while 1:
if shift >= 64:
raise errors.DecodeError('Too many bytes when decoding varint.')
try:
b = ord(self._input.read(1))
except IndexError:
raise errors.DecodeError('Truncated varint.')
self._pos += 1
result |= ((b & 0x7f) << shift)
shift += 7
if not (b & 0x80):
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append_tag(self, field_number, wire_type):
"""Appends a tag containing field number and wire type information.""" |
self._stream.append_var_uint32(wire_format.pack_tag(field_number, wire_type)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.