code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
url = "{}/{}/tokens/{}".format(self.base_url, customer_id, token_id) return self.delete_url(url, data, **kwargs)
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
2.534447
3.568689
0.71019
return super(Settlement, self).all(data, **kwargs)
def all(self, data={}, **kwargs)
Fetch all Settlement entities Returns: Dictionary of Settlement data
8.318167
6.452791
1.289081
return super(Settlement, self).fetch(settlement_id, data, **kwargs)
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
3.328862
5.825361
0.571443
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
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 l...
1.869174
1.835865
1.018144
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)
def all(self, data={}, **kwargs)
Fetch all Transfer entities Returns: Dictionary of Transfer data
3.71168
3.424854
1.083748
return super(Transfer, self).fetch(transfer_id, data, **kwargs)
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
3.670043
7.226347
0.50787
url = "{}/{}/reversals".format(self.base_url, transfer_id) return self.post_url(url, data, **kwargs)
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
3.143005
5.114616
0.614514
url = "{}/{}/reversals".format(self.base_url, transfer_id) return self.get_url(url, data, **kwargs)
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
2.915111
4.090376
0.712675
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) ...
def request(self, method, path, **options)
Dispatches a request to the Razorpay HTTP API
2.199098
2.163267
1.016563
return self.request('get', path, params=params, **options)
def get(self, path, params, **options)
Parses GET request options and dispatches a request
4.16622
4.186198
0.995228
data, options = self._update_request(data, options) return self.request('post', path, data=data, **options)
def post(self, path, data, **options)
Parses POST request options and dispatches a request
4.276852
4.142016
1.032553
data, options = self._update_request(data, options) return self.request('patch', path, data=data, **options)
def patch(self, path, data, **options)
Parses PATCH request options and dispatches a request
4.172472
4.079315
1.022836
data, options = self._update_request(data, options) return self.request('delete', path, data=data, **options)
def delete(self, path, data, **options)
Parses DELETE request options and dispatches a request
4.349806
4.309359
1.009386
data, options = self._update_request(data, options) return self.request('put', path, data=data, **options)
def put(self, path, data, **options)
Parses PUT request options and dispatches a request
4.412182
4.121165
1.070615
data = json.dumps(data) if 'headers' not in options: options['headers'] = {} options['headers'].update({'Content-type': 'application/json'}) return data, options
def _update_request(self, data, options)
Updates The resource data and header options
2.879496
2.637307
1.091832
return super(Invoice, self).all(data, **kwargs)
def all(self, data={}, **kwargs)
Fetch all Invoice entities Returns: Dictionary of Invoice data
7.58826
7.838604
0.968063
return super(Invoice, self).fetch(invoice_id, data, **kwargs)
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
3.493769
7.081579
0.49336
url = "{}/{}/notify_by/{}".format(self.base_url, invoice_id, medium) return self.post_url(url, {}, **kwargs)
def notify_by(self, invoice_id, medium, **kwargs)
Send/Resend notifications to customer via email/sms Args: invoice_id : Id for trigger notify medium : Medium for triggering notification via email or sms Returns: {"success": true}
3.413544
4.73949
0.720235
url = "{}/{}/cancel".format(self.base_url, invoice_id) return self.post_url(url, {}, **kwargs)
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...
3.761469
5.084078
0.739853
url = "{}/{}".format(self.base_url, invoice_id) return self.delete_url(url, {}, **kwargs)
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 - []
3.632143
4.25983
0.85265
url = "{}/{}/issue".format(self.base_url, invoice_id) return self.post_url(url, {}, **kwargs)
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.
3.985459
4.66903
0.853595
url = "{}/{}".format(self.base_url, invoice_id) return self.patch_url(url, data, **kwargs)
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 respon...
3.151989
4.665061
0.675659
# The sink has started to receive data, so the stream is ready. # This also is our opportunity to read information about the # stream. self.got_caps = True info = pad.get_current_caps().get_structure(0) # Stream attributes. self.channels = info.get_int('...
def _notify_caps(self, pad, args)
The callback for the sinkpad's "notify::caps" signal.
6.66398
6.445292
1.03393
# 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....
def _pad_added(self, element, pad)
The callback for GstElement's "pad-added" signal.
11.202391
7.265416
1.541879
# 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()
def _no_more_pads(self, element)
The callback for GstElement's "no-more-pads" signal.
11.914494
11.759794
1.013155
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 call...
def _new_sample(self, sink)
The callback for appsink's "new-sample" signal.
7.317842
6.292078
1.163025
# 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(streami...
def _unkown_type(self, uridecodebin, decodebin, caps)
The callback for decodebin's "unknown-type" signal.
9.781148
9.396173
1.040971
if not self.finished: if message.type == Gst.MessageType.EOS: # The file is done. Tell the consumer thread. self.queue.put(SENTINEL) if not self.got_caps: # If the stream ends before _notify_caps was called, this ...
def _message(self, bus, message)
The callback for GstBus's "message" signal (for two kinds of messages).
4.550233
4.423012
1.028763
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().rem...
def close(self, force=False)
Close the file and clean up associated resources. Calling `close()` a second time has no effect.
6.387958
6.326086
1.009781
assert len(s) % 2 == 0 parts = [] for i in range(0, len(s), 2): chunk = s[i:i + 2] newchunk = struct.pack('<h', *struct.unpack('>h', chunk)) parts.append(newchunk) return b''.join(parts)
def byteswap(s)
Swaps the endianness of the bytesting s, which must be an array of shorts (16-bit signed integers). This is probably less efficient than it should be.
2.400484
2.278813
1.053392
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) ...
def read_data(self, block_samples=1024)
Generates blocks of PCM data found in the file.
5.206687
4.906371
1.06121
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
def _gst_available()
Determine whether Gstreamer and the Python GObject bindings are installed.
2.05092
2.092071
0.98033
# 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(...
def available_backends()
Returns a list of backends that are available on this system.
4.857658
4.489953
1.081895
if backends is None: backends = available_backends() for BackendClass in backends: try: return BackendClass(path) except DecodeError: pass # All backends failed! raise NoBackendError()
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 ...
4.667288
4.611565
1.012083
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
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...
2.57671
2.481457
1.038386
proc = popen_multiple( COMMANDS, ['-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=PROC_FLAGS, ) proc.wait() return (proc.returncode == 0)
def available()
Detect if the FFmpeg backend can be used on this system.
5.935917
5.542258
1.071029
# 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)...
def read_data(self, timeout=10.0)
Read blocks of raw PCM data from the file.
4.118032
4.118471
0.999893
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 isins...
def _get_info(self)
Reads the tool's output from its stderr stream, extracts the relevant information, and parses it.
4.72641
4.4131
1.070995
# 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) ...
def _parse_info(self, s)
Given relevant data from the ffmpeg output, set audio parameter fields on this object.
2.326725
2.225528
1.045471
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.po...
def close(self)
Close the ffmpeg process used to perform the decoding.
4.79352
4.460367
1.074692
while True: out = self.mf.read(block_size) if not out: break yield bytes(out)
def read_blocks(self, block_size=4096)
Generates buffers containing PCM data for the audio file.
5.006595
4.22258
1.185672
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? ret...
def channels(self)
The number of channels.
5.217144
4.607276
1.132371
num = 0 for index, char in enumerate(chars): shift = (len(chars) - index - 1) * 8 num |= ord(char) << shift return num
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'.
3.581766
3.530381
1.014555
file_obj = ctypes.c_void_p() check(_coreaudio.ExtAudioFileOpenURL( url._obj, ctypes.byref(file_obj) )) return file_obj
def _open_url(cls, url)
Given a CFURL Python object, return an opened ExtAudioFileRef.
8.188467
4.758316
1.720875
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
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.
12.645077
12.351453
1.023772
# 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._...
def get_file_format(self)
Get the file format description. This describes the type of data stored on disk.
6.584892
6.15972
1.069025
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
def nframes(self)
Gets the number of frames in the source file.
5.6181
4.663018
1.204821
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.mB...
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.
3.989277
3.698988
1.078478
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 buflis...
def read_data(self, blocksize=4096)
Generates byte strings reflecting the audio data in the file.
3.274799
3.18722
1.027478
if not self.closed: check(_coreaudio.ExtAudioFileDispose(self._obj)) self.closed = True
def close(self)
Close the audio file and free associated memory.
18.00428
11.597615
1.552412
"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 #...
def mount(self, url, app)
Mount a sub-app at the url of current app.
21.464325
18.521599
1.158881
while True: call_item = call_queue.get(block=True) if call_item is None: # Wake up queue management thread result_queue.put(None) return try: r = call_item.fn(*call_item.args, **call_item.kwargs) except BaseException: e...
def _process_worker(call_queue, result_queue)
Evaluates calls from call_queue and places the results in result_queue. This worker is run in a separate process. Args: call_queue: A multiprocessing.Queue of _CallItems that will be read and evaluated by the worker. result_queue: A multiprocessing.Queue of _ResultItems that will w...
2.349785
2.291021
1.02565
nb_shutdown_processes = [0] def shutdown_one_process(): call_queue.put(None) nb_shutdown_processes[0] += 1 while True: _add_call_item_to_queue(pending_work_items, work_ids_queue, call_queue) result...
def _queue_management_worker(executor_reference, processes, pending_work_items, work_ids_queue, call_queue, result_queue)
Manages the communication between this process and the worker processes. This function is run in a local thread. Args: executor_reference: A weakref.ref to the ProcessPoolExecutor that owns this thread. Used to determine if the ProcessPoolExecutor has been garbage collected and...
3.627315
3.67764
0.986316
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_ty...
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: >>> df.id.map(lam...
2.876073
2.903679
0.990493
if func is None: func = lambda x: hash(x) return _map(expr, func=func, rtype=types.int64)
def _hash(expr, func=None)
Calculate the hash value. :param expr: :param func: hash function :return:
5.529132
7.346808
0.75259
if isinstance(expr, SequenceExpr): return IsNull(_input=expr, _data_type=types.boolean) elif isinstance(expr, Scalar): return IsNull(_input=expr, _value_type=types.boolean)
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
5.445272
5.042825
1.079806
if isinstance(expr, SequenceExpr): return NotNull(_input=expr, _data_type=types.boolean) elif isinstance(expr, Scalar): return NotNull(_input=expr, _value_type=types.boolean)
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
6.032432
5.263408
1.146108
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)
def _fillna(expr, value)
Fill null with value. :param expr: sequence or scalar :param value: value to fill into :return: sequence or scalar
3.717697
3.665892
1.014132
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...
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
4.608542
4.488914
1.02665
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)
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
4.629403
4.45488
1.039176
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, ...
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 ...
3.299638
3.288653
1.00334
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]) i...
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: >>> (df.id == 3).ifelse(df.id, df.fid.astype('int')) >>> df.isMale.ifelse(df.male_count, ...
2.701329
2.955323
0.914055
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 enumera...
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: >>> # if df.id == 3 then df.name >>> # elif df.id == df.fid.abs() then df.name + 'test' >>> # default: 'test' >>> df.id.switch(3, df.name, df.fid....
3.149837
3.350448
0.940124
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 retur...
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.894197
4.154671
0.937306
if isinstance(expr, SequenceExpr): return IntToDatetime(_input=expr, _data_type=types.datetime) elif isinstance(expr, Scalar): return IntToDatetime(_input=expr, _value_type=types.datetime)
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
5.719484
5.086218
1.124506
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, ...
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
3.699036
3.952508
0.935871
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) pa...
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::...
3.182161
2.993479
1.063031
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: downl...
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 compres...
2.614789
2.426061
1.077792
async_ = kw.get('async', async_) return self.partitions.create(partition_spec, if_not_exists=if_not_exists, async_=async_)
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
2.740264
3.444517
0.795544
async_ = kw.get('async', async_) return self.partitions.delete(partition_spec, if_exists=if_exists, async_=async_)
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_:
3.009775
3.991143
0.754114
try: next(self.partitions.iterate_partitions(spec=prefix_spec)) except StopIteration: return False return True
def exist_partitions(self, prefix_spec=None)
Check if partitions with provided conditions exist. :param prefix_spec: prefix of partition :return: whether partitions exist
5.039034
6.089962
0.827433
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_: ...
def truncate(self, async_=False, **kw)
truncate this table. :param async_: run asynchronously if True :return: None
5.775172
5.717134
1.010152
async_ = kw.get('async', async_) return self.parent.delete(self, async_=async_, if_exists=if_exists)
def drop(self, async_=False, if_exists=False, **kw)
Drop this table. :param async_: run asynchronously if True :return: None
3.804789
4.365368
0.871585
return datetime_op(expr, Strftime, output_type=types.string, _date_format=date_format)
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:
11.666073
21.875368
0.533297
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)
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 t...
5.405622
7.047012
0.76708
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))
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: >>> df.distinct(['name', 'id']) >>> df['name', 'id'].distinct()
5.692327
7.175793
0.793268
by = by or RandomScalar() grouped = expr.groupby(by) if sort: grouped = grouped.sort_values(sort, ascending=ascending) return ReshuffledCollectionExpr(_input=grouped, _schema=expr._schema)
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
5.977112
4.91603
1.215841
rows = [expr._get_field(r) for r in utils.to_list(rows)] columns = [expr._get_field(c) for c in utils.to_list(columns)] if values: values = utils.to_list(values) else: names = set(c.name for c in rows + columns) values = [n for n in expr.schema.names if n not in names] ...
def pivot(expr, rows, columns, values=None)
Produce ‘pivot’ table based on 3 columns of this DataFrame. Uses unique values from rows / columns and fills with values. :param expr: collection :param rows: use to make new collection's grouped rows :param columns: use to make new collection's columns :param values: values to use for populating n...
2.715114
3.042219
0.892478
id_vars = id_vars or [] id_vars = [expr._get_field(r) for r in utils.to_list(id_vars)] if not value_vars: id_names = set([c.name for c in id_vars]) value_vars = [expr._get_field(c) for c in expr.schema.names if c not in id_names] else: value_vars = [expr._get_field(c) for c ...
def melt(expr, id_vars=None, value_vars=None, var_name='variable', value_name='value', ignore_nan=False)
“Unpivots” a DataFrame from wide format to long format, optionally leaving identifier variables set. This function is useful to massage a DataFrame into a format where one or more columns are identifier variables (id_vars), while all other columns, considered measured variables (value_vars), are “unpivoted” ...
2.782531
3.07534
0.904788
time_suffix = str(int(time.time())) def calc_agg(expr, col): return [ getattr(expr, col).min().rename(col + '_min_' + time_suffix), getattr(expr, col).max().rename(col + '_max_' + time_suffix), ] def do_scale(expr, col): f_min, f_max = feature_range ...
def min_max_scale(expr, columns=None, feature_range=(0, 1), preserve=False, suffix='_scaled', group=None)
Resize a data frame by max / min values, i.e., (X - min(X)) / (max(X) - min(X)) :param DataFrame expr: input DataFrame :param feature_range: the target range to resize the value into, i.e., v * (b - a) + a :param bool preserve: determine whether input data should be kept. If True, scaled input data will be...
2.523363
2.729118
0.924608
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) ...
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...
2.643356
2.871888
0.920425
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 ...
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 ...
2.946538
3.268846
0.9014
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 ...
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 ...
3.289097
3.620508
0.908463
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' els...
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. :par...
3.326822
3.927624
0.847032
col_dict = OrderedDict([(c, expr._get_field(c)) for c in expr.schema.names]) if subset is None: sel_col_names = expr.schema.names else: # when c is in expr._fields, _get_field may do substitution which will cause error subset = (c.copy() if isinstance(c, Expr) else c for c in ut...
def fillna(expr, value=None, method=None, subset=None)
Fill NA/NaN values using the specified method :param DataFrame expr: input DataFrame :param method: can be ‘backfill’, ‘bfill’, ‘pad’, ‘ffill’ or None :param value: value to fill into :param subset: Labels along other axis to consider. :return: DataFrame
3.010448
3.110514
0.96783
if hasattr(expr, '_xflow_append_id'): return expr._xflow_append_id(id_col) else: return _append_id(expr, id_col)
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
3.112397
4.10969
0.757331
if hasattr(expr, '_xflow_split'): return expr._xflow_split(frac, seed=seed) else: return _split(expr, frac, seed=seed)
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
3.093799
4.074793
0.759253
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 isin...
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 :para...
1.904985
2.063592
0.92314
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 by...
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.
3.249021
3.252643
0.998886
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)
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.
5.195115
4.703584
1.104501
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)
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.
5.119276
4.651422
1.100583
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)
def read_varint32(self)
Reads a varint from the stream, interprets this varint as a signed, 32-bit integer, and returns the integer.
3.608939
3.372609
1.070073
i = self.read_var_uint64() if i > wire_format.UINT32_MAX: raise errors.DecodeError('Value out of range for uint32: %d' % i) return i
def read_var_uint32(self)
Reads a varint from the stream, interprets this varint as an unsigned, 32-bit integer, and returns the integer.
4.503251
4.151345
1.084769
i = self.read_var_uint64() if i > wire_format.INT64_MAX: i -= (1 << 64) return i
def read_varint64(self)
Reads a varint from the stream, interprets this varint as a signed, 64-bit integer, and returns the integer.
5.04999
4.605601
1.096489
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
def read_var_uint64(self)
Reads a varint from the stream, interprets this varint as an unsigned, 64-bit integer, and returns the integer.
5.03571
4.555343
1.105451
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 var...
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.
2.333448
2.485137
0.938961
self._stream.append_var_uint32(wire_format.pack_tag(field_number, wire_type))
def append_tag(self, field_number, wire_type)
Appends a tag containing field number and wire type information.
6.667199
6.584774
1.012517
zigzag_value = wire_format.zig_zag_encode(value) self._stream.append_var_uint32(zigzag_value)
def append_sint32(self, value)
Appends a 32-bit integer to our buffer, zigzag-encoded and then varint-encoded.
5.247184
4.73973
1.107064
zigzag_value = wire_format.zig_zag_encode(value) self._stream.append_var_uint64(zigzag_value)
def append_sint64(self, value)
Appends a 64-bit integer to our buffer, zigzag-encoded and then varint-encoded.
5.372933
4.734634
1.134815
sign = (value & 0x80000000) and -1 or 0 if value >> 32 != sign: raise errors.EncodeError('SFixed32 out of range: %d' % value) self._stream.append_little_endian32(value & 0xffffffff)
def append_sfixed32(self, value)
Appends a signed 32-bit integer to our buffer, in little-endian byte-order.
3.865233
3.900474
0.990965