_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q33500
GroupMixin.descendants
train
def descendants(self, include_clip=True): """ Return a generator to iterate over all descendant layers. Example:: # Iterate over all layers for layer in psd.descendants(): print(layer) # Iterate over all layers in reverse order f...
python
{ "resource": "" }
q33501
Artboard.compose
train
def compose(self, bbox=None, **kwargs): """ Compose the artboard. See :py:func:`~psd_tools.compose` for available extra arguments. :param bbox: Viewport tuple (left, top, right, bottom). :return: :py:class:`PIL.Image`, or `None` if there is no pixel. """ from ps...
python
{ "resource": "" }
q33502
SmartObjectLayer.smart_object
train
def smart_object(self): """ Associated smart object. :return: :py:class:`~psd_tools.api.smart_object.SmartObject`. """ if not hasattr(self, '_smart_object'): self._smart_object = SmartObject(self) return self._smart_object
python
{ "resource": "" }
q33503
ShapeLayer.stroke
train
def stroke(self): """Property for strokes.""" if not hasattr(self, '_stroke'): self._stroke = None stroke = self.tagged_blocks.get_data('VECTOR_STROKE_DATA') if stroke: self._stroke = Stroke(stroke) return self._stroke
python
{ "resource": "" }
q33504
read_fmt
train
def read_fmt(fmt, fp): """ Reads data from ``fp`` according to ``fmt``. """ fmt = str(">" + fmt) fmt_size = struct.calcsize(fmt) data = fp.read(fmt_size) assert len(data) == fmt_size, 'read=%d, expected=%d' % ( len(data), fmt_size ) return struct.unpack(fmt, data)
python
{ "resource": "" }
q33505
write_fmt
train
def write_fmt(fp, fmt, *args): """ Writes data to ``fp`` according to ``fmt``. """ fmt = str(">" + fmt) fmt_size = struct.calcsize(fmt) written = write_bytes(fp, struct.pack(fmt, *args)) assert written == fmt_size, 'written=%d, expected=%d' % ( written, fmt_size ) return writ...
python
{ "resource": "" }
q33506
write_bytes
train
def write_bytes(fp, data): """ Write bytes to the file object and returns bytes written. :return: written byte size """ pos = fp.tell() fp.write(data) written = fp.tell() - pos assert written == len(data), 'written=%d, expected=%d' % ( written, len(data) ) return written
python
{ "resource": "" }
q33507
read_length_block
train
def read_length_block(fp, fmt='I', padding=1): """ Read a block of data with a length marker at the beginning. :param fp: file-like :param fmt: format of the length marker :return: bytes object """ length = read_fmt(fmt, fp)[0] data = fp.read(length) assert len(data) == length, (len...
python
{ "resource": "" }
q33508
write_length_block
train
def write_length_block(fp, writer, fmt='I', padding=1, **kwargs): """ Writes a block of data with a length marker at the beginning. Example:: with io.BytesIO() as fp: write_length_block(fp, lambda f: f.write(b'\x00\x00')) :param fp: file-like :param writer: function object tha...
python
{ "resource": "" }
q33509
reserve_position
train
def reserve_position(fp, fmt='I'): """ Reserves the current position for write. Use with `write_position`. :param fp: file-like object :param fmt: format of the reserved position :return: the position """ position = fp.tell() fp.seek(struct.calcsize(str('>' + fmt)), 1) return p...
python
{ "resource": "" }
q33510
write_position
train
def write_position(fp, position, value, fmt='I'): """ Writes a value to the specified position. :param fp: file-like object :param position: position of the value marker :param value: value to write :param fmt: format of the value :return: written byte size """ current_position = fp...
python
{ "resource": "" }
q33511
read_padding
train
def read_padding(fp, size, divisor=2): """ Read padding bytes for the given byte size. :param fp: file-like object :param divisor: divisor of the byte alignment :return: read byte size """ remainder = size % divisor if remainder: return fp.read(divisor - remainder) return b'...
python
{ "resource": "" }
q33512
write_padding
train
def write_padding(fp, size, divisor=2): """ Writes padding bytes given the currently written size. :param fp: file-like object :param divisor: divisor of the byte alignment :return: written byte size """ remainder = size % divisor if remainder: return write_bytes(fp, struct.pack...
python
{ "resource": "" }
q33513
is_readable
train
def is_readable(fp, size=1): """ Check if the file-like object is readable. :param fp: file-like object :param size: byte size :return: bool """ read_size = len(fp.read(size)) fp.seek(-read_size, 1) return read_size == size
python
{ "resource": "" }
q33514
read_be_array
train
def read_be_array(fmt, count, fp): """ Reads an array from a file with big-endian data. """ arr = array.array(str(fmt)) if hasattr(arr, 'frombytes'): arr.frombytes(fp.read(count * arr.itemsize)) else: arr.fromstring(fp.read(count * arr.itemsize)) return fix_byteorder(arr)
python
{ "resource": "" }
q33515
be_array_from_bytes
train
def be_array_from_bytes(fmt, data): """ Reads an array from bytestring with big-endian data. """ arr = array.array(str(fmt), data) return fix_byteorder(arr)
python
{ "resource": "" }
q33516
be_array_to_bytes
train
def be_array_to_bytes(arr): """ Writes an array to bytestring with big-endian data. """ data = fix_byteorder(arr) if hasattr(arr, 'tobytes'): return data.tobytes() else: return data.tostring()
python
{ "resource": "" }
q33517
new_registry
train
def new_registry(attribute=None): """ Returns an empty dict and a @register decorator. """ registry = {} def register(key): def decorator(func): registry[key] = func if attribute: setattr(func, attribute, key) return func return de...
python
{ "resource": "" }
q33518
stop
train
def stop(): """Stop the server, invalidating any viewer URLs. This allows any previously-referenced data arrays to be garbage collected if there are no other references to them. """ global global_server if global_server is not None: ioloop = global_server.ioloop def stop_ioloop(...
python
{ "resource": "" }
q33519
defer_callback
train
def defer_callback(callback, *args, **kwargs): """Register `callback` to run in the server event loop thread.""" start() global_server.ioloop.add_callback(lambda: callback(*args, **kwargs))
python
{ "resource": "" }
q33520
compute_near_isotropic_downsampling_scales
train
def compute_near_isotropic_downsampling_scales(size, voxel_size, dimensions_to_downsample, max_scales=DEFAULT_MAX_DOWNSAMPLING_SCALES, ...
python
{ "resource": "" }
q33521
compute_two_dimensional_near_isotropic_downsampling_scales
train
def compute_two_dimensional_near_isotropic_downsampling_scales( size, voxel_size, max_scales=float('inf'), max_downsampling=DEFAULT_MAX_DOWNSAMPLING, max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE): """Compute a list of successive downsampling factors for 2-d tiles.""" ...
python
{ "resource": "" }
q33522
json_encoder_default
train
def json_encoder_default(obj): """JSON encoder function that handles some numpy types.""" if isinstance(obj, numbers.Integral) and (obj < min_safe_integer or obj > max_safe_integer): return str(obj) if isinstance(obj, np.integer): return str(obj) elif isinstance(obj, np.floating): ...
python
{ "resource": "" }
q33523
StateHandler._on_state_changed
train
def _on_state_changed(self): """Invoked when the viewer state changes.""" raw_state, generation = self.state.raw_state_and_generation if generation != self._last_generation: self._last_generation = generation self._send_update(raw_state, generation)
python
{ "resource": "" }
q33524
future_then_immediate
train
def future_then_immediate(future, func): """Returns a future that maps the result of `future` by `func`. If `future` succeeds, sets the result of the returned future to `func(future.result())`. If `future` fails or `func` raises an exception, the exception is stored in the returned future. If `future...
python
{ "resource": "" }
q33525
downsample_with_averaging
train
def downsample_with_averaging(array, factor): """Downsample x by factor using averaging. @return: The downsampled array, of the same type as x. """ factor = tuple(factor) output_shape = tuple(int(math.ceil(s / f)) for s, f in zip(array.shape, factor)) temp = np.zeros(output_shape, dtype=np.floa...
python
{ "resource": "" }
q33526
downsample_with_striding
train
def downsample_with_striding(array, factor): """Downsample x by factor using striding. @return: The downsampled array, of the same type as x. """ return array[tuple(np.s_[::f] for f in factor)]
python
{ "resource": "" }
q33527
EquivalenceMap._get_representative
train
def _get_representative(self, obj): """Finds and returns the root of the set containing `obj`.""" if obj not in self._parents: self._parents[obj] = obj self._weights[obj] = 1 self._prev_next[obj] = [obj, obj] self._min_values[obj] = obj return...
python
{ "resource": "" }
q33528
EquivalenceMap.members
train
def members(self, x): """Yields the members of the equivalence class containing `x`.""" if x not in self._parents: yield x return cur_x = x while True: yield cur_x cur_x = self._prev_next[cur_x][1] if cur_x == x: ...
python
{ "resource": "" }
q33529
EquivalenceMap.sets
train
def sets(self): """Returns the equivalence classes as a set of sets.""" sets = {} for x in self._parents: sets.setdefault(self[x], set()).add(x) return frozenset(frozenset(v) for v in six.viewvalues(sets))
python
{ "resource": "" }
q33530
EquivalenceMap.to_json
train
def to_json(self): """Returns the equivalence classes a sorted list of sorted lists.""" sets = self.sets() return sorted(sorted(x) for x in sets)
python
{ "resource": "" }
q33531
EquivalenceMap.delete_set
train
def delete_set(self, x): """Removes the equivalence class containing `x`.""" if x not in self._parents: return members = list(self.members(x)) for v in members: del self._parents[v] del self._weights[v] del self._prev_next[v] de...
python
{ "resource": "" }
q33532
EquivalenceMap.isolate_element
train
def isolate_element(self, x): """Isolates `x` from its equivalence class.""" members = list(self.members(x)) self.delete_set(x) self.union(*(v for v in members if v != x))
python
{ "resource": "" }
q33533
quaternion_slerp
train
def quaternion_slerp(a, b, t): """Spherical linear interpolation for unit quaternions. This is based on the implementation in the gl-matrix package: https://github.com/toji/gl-matrix """ if a is None: a = unit_quaternion() if b is None: b = unit_quaternion() # calc cosine ...
python
{ "resource": "" }
q33534
GreedyMulticut.remove_edge_from_heap
train
def remove_edge_from_heap(self, segment_ids): """Remove an edge from the heap.""" self._initialize_heap() key = normalize_edge(segment_ids) if key in self.edge_map: self.edge_map[key][0] = None self.num_valid_edges -= 1
python
{ "resource": "" }
q33535
TrackableState.txn
train
def txn(self, overwrite=False, lock=True): """Context manager for a state modification transaction.""" if lock: self._lock.acquire() try: new_state, existing_generation = self.state_and_generation new_state = copy.deepcopy(new_state) yield new_stat...
python
{ "resource": "" }
q33536
LocalVolume.invalidate
train
def invalidate(self): """Mark the data invalidated. Clients will refetch the volume.""" with self._mesh_generator_lock: self._mesh_generator_pending = None self._mesh_generator = None self._dispatch_changed_callbacks()
python
{ "resource": "" }
q33537
save_md
train
def save_md(p, *vsheets): 'pipe tables compatible with org-mode' with p.open_text(mode='w') as fp: for vs in vsheets: if len(vsheets) > 1: fp.write('# %s\n\n' % vs.name) fp.write('|' + '|'.join('%-*s' % (col.width or options.default_width, markdown_escape(col.name...
python
{ "resource": "" }
q33538
load_pyobj
train
def load_pyobj(name, pyobj): 'Return Sheet object of appropriate type for given sources in `args`.' if isinstance(pyobj, list) or isinstance(pyobj, tuple): if getattr(pyobj, '_fields', None): # list of namedtuple return SheetNamedTuple(name, pyobj) else: return SheetList...
python
{ "resource": "" }
q33539
PyobjColumns
train
def PyobjColumns(obj): 'Return columns for each public attribute on an object.' return [ColumnAttr(k, type(getattr(obj, k))) for k in getPublicAttrs(obj)]
python
{ "resource": "" }
q33540
DictKeyColumns
train
def DictKeyColumns(d): 'Return a list of Column objects from dictionary keys.' return [ColumnItem(k, k, type=deduceType(d[k])) for k in d.keys()]
python
{ "resource": "" }
q33541
SheetList
train
def SheetList(name, src, **kwargs): 'Creates a Sheet from a list of homogenous dicts or namedtuples.' if not src: status('no content in ' + name) return if isinstance(src[0], dict): return ListOfDictSheet(name, source=src, **kwargs) elif isinstance(src[0], tuple): if ge...
python
{ "resource": "" }
q33542
SheetFreqTable.reload
train
def reload(self): 'Generate histrow for each row and then reverse-sort by length.' self.rows = [] # if len(self.origCols) == 1 and self.origCols[0].type in (int, float, currency): # self.numericBinning() # else: self.discreteBinning() # automatically add cache ...
python
{ "resource": "" }
q33543
saveToClipboard
train
def saveToClipboard(sheet, rows, filetype=None): 'copy rows from sheet to system clipboard' filetype = filetype or options.save_filetype vs = copy(sheet) vs.rows = rows status('copying rows to clipboard') clipboard().save(vs, filetype)
python
{ "resource": "" }
q33544
_Clipboard.copy
train
def copy(self, value): 'Copy a cell to the system clipboard.' with tempfile.NamedTemporaryFile() as temp: with open(temp.name, 'w', encoding=options.encoding) as fp: fp.write(str(value)) p = subprocess.Popen( self.command, stdin=o...
python
{ "resource": "" }
q33545
_Clipboard.save
train
def save(self, vs, filetype): 'Copy rows to the system clipboard.' # use NTF to generate filename and delete file on context exit with tempfile.NamedTemporaryFile(suffix='.'+filetype) as temp: saveSheets(temp.name, vs) sync(1) p = subprocess.Popen( ...
python
{ "resource": "" }
q33546
LogSheet.amendPrevious
train
def amendPrevious(self, targethash): 'amend targethash with current index, then rebase newer commits on top' prevBranch = loggit_all('rev-parse', '--symbolic-full-name', '--abbrev-ref', 'HEAD').strip() ret = loggit_all('commit', '-m', 'MERGE '+targethash) # commit index to viewed branch ...
python
{ "resource": "" }
q33547
save_html
train
def save_html(p, *vsheets): 'Save vsheets as HTML tables in a single file' with open(p.resolve(), 'w', encoding='ascii', errors='xmlcharrefreplace') as fp: for sheet in vsheets: fp.write('<h2 class="sheetname">%s</h2>\n'.format(sheetname=html.escape(sheet.name))) fp.write('<ta...
python
{ "resource": "" }
q33548
tsv_trdict
train
def tsv_trdict(vs): 'returns string.translate dictionary for replacing tabs and newlines' if options.safety_first: delim = options.get('delimiter', vs) return {ord(delim): options.get('tsv_safe_tab', vs), # \t 10: options.get('tsv_safe_newline', vs), # \n 13: options.get...
python
{ "resource": "" }
q33549
save_tsv_header
train
def save_tsv_header(p, vs): 'Write tsv header for Sheet `vs` to Path `p`.' trdict = tsv_trdict(vs) delim = options.delimiter with p.open_text(mode='w') as fp: colhdr = delim.join(col.name.translate(trdict) for col in vs.visibleCols) + '\n' if colhdr.strip(): # is anything but whitespac...
python
{ "resource": "" }
q33550
save_tsv
train
def save_tsv(p, vs): 'Write sheet to file `fn` as TSV.' delim = options.get('delimiter', vs) trdict = tsv_trdict(vs) save_tsv_header(p, vs) with p.open_text(mode='a') as fp: for dispvals in genAllValues(vs.rows, vs.visibleCols, trdict, format=True): fp.write(delim.join(dispvals...
python
{ "resource": "" }
q33551
append_tsv_row
train
def append_tsv_row(vs, row): 'Append `row` to vs.source, creating file with correct headers if necessary. For internal use only.' if not vs.source.exists(): with contextlib.suppress(FileExistsError): parentdir = vs.source.parent.resolve() if parentdir: os.makedirs...
python
{ "resource": "" }
q33552
TsvSheet.reload_sync
train
def reload_sync(self): 'Perform synchronous loading of TSV file, discarding header lines.' header_lines = options.get('header', self) delim = options.get('delimiter', self) with self.source.open_text() as fp: # get one line anyway to determine number of columns l...
python
{ "resource": "" }
q33553
load_csv
train
def load_csv(vs): 'Convert from CSV, first handling header row specially.' with vs.source.open_text() as fp: for i in range(options.skip): wrappedNext(fp) # discard initial lines if options.safety_first: rdr = csv.reader(removeNulls(fp), **csvoptions()) else: ...
python
{ "resource": "" }
q33554
save_csv
train
def save_csv(p, sheet): 'Save as single CSV file, handling column names as first line.' with p.open_text(mode='w') as fp: cw = csv.writer(fp, **csvoptions()) colnames = [col.name for col in sheet.visibleCols] if ''.join(colnames): cw.writerow(colnames) for r in Progre...
python
{ "resource": "" }
q33555
currency_multiplier
train
def currency_multiplier(src_currency, dest_currency): 'returns equivalent value in USD for an amt of currency_code' if src_currency == 'USD': return 1.0 usd_mult = currency_rates()[src_currency] if dest_currency == 'USD': return usd_mult return usd_mult/currency_rates()[dest_currency...
python
{ "resource": "" }
q33556
moveVisibleCol
train
def moveVisibleCol(sheet, fromVisColIdx, toVisColIdx): 'Move visible column to another visible index in sheet.' toVisColIdx = min(max(toVisColIdx, 0), sheet.nVisibleCols) fromColIdx = sheet.columns.index(sheet.visibleCols[fromVisColIdx]) toColIdx = sheet.columns.index(sheet.visibleCols[toVisColIdx]) ...
python
{ "resource": "" }
q33557
moveListItem
train
def moveListItem(L, fromidx, toidx): "Move element within list `L` and return element's new index." r = L.pop(fromidx) L.insert(toidx, r) return toidx
python
{ "resource": "" }
q33558
urlcache
train
def urlcache(url, cachesecs=24*60*60): 'Returns Path object to local cache of url contents.' p = Path(os.path.join(options.visidata_dir, 'cache', urllib.parse.quote(url, safe=''))) if p.exists(): secs = time.time() - p.stat().st_mtime if secs < cachesecs: return p if not p.p...
python
{ "resource": "" }
q33559
fillNullValues
train
def fillNullValues(col, rows): 'Fill null cells in col with the previous non-null value' lastval = None nullfunc = isNullFunc() n = 0 rowsToFill = list(rows) for r in Progress(col.sheet.rows, 'filling'): # loop over all rows try: val = col.getValue(r) except Exceptio...
python
{ "resource": "" }
q33560
saveSheets
train
def saveSheets(fn, *vsheets, confirm_overwrite=False): 'Save sheet `vs` with given filename `fn`.' givenpath = Path(fn) # determine filetype to save as filetype = '' basename, ext = os.path.splitext(fn) if ext: filetype = ext[1:] filetype = filetype or options.save_filetype if...
python
{ "resource": "" }
q33561
open_txt
train
def open_txt(p): 'Create sheet from `.txt` file at Path `p`, checking whether it is TSV.' with p.open_text() as fp: if options.delimiter in next(fp): # peek at the first line return open_tsv(p) # TSV often have .txt extension return TextSheet(p.name, p)
python
{ "resource": "" }
q33562
loadInternalSheet
train
def loadInternalSheet(klass, p, **kwargs): 'Load internal sheet of given klass. Internal sheets are always tsv.' vs = klass(p.name, source=p, **kwargs) options._set('encoding', 'utf8', vs) if p.exists(): vd.sheets.insert(0, vs) vs.reload.__wrapped__(vs) vd.sheets.pop(0) retu...
python
{ "resource": "" }
q33563
namedlist
train
def namedlist(objname, fieldnames): 'like namedtuple but editable' class NamedListTemplate(list): __name__ = objname _fields = fieldnames def __init__(self, L=None, **kwargs): if L is None: L = [None]*len(fieldnames) super().__init__(L) ...
python
{ "resource": "" }
q33564
Host.get_by_ip
train
def get_by_ip(cls, ip): 'Returns Host instance for the given ip address.' ret = cls.hosts_by_ip.get(ip) if ret is None: ret = cls.hosts_by_ip[ip] = [Host(ip)] return ret
python
{ "resource": "" }
q33565
threadProfileCode
train
def threadProfileCode(func, *args, **kwargs): 'Toplevel thread profile wrapper.' with ThreadProfiler(threading.current_thread()) as prof: try: prof.thread.status = threadProfileCode.__wrapped__(func, *args, **kwargs) except EscapeException as e: prof.thread.status = e
python
{ "resource": "" }
q33566
combineColumns
train
def combineColumns(cols): 'Return Column object formed by joining fields in given columns.' return Column("+".join(c.name for c in cols), getter=lambda col,row,cols=cols,ch=' ': ch.join(c.getDisplayValue(row) for c in cols))
python
{ "resource": "" }
q33567
cancelThread
train
def cancelThread(*threads, exception=EscapeException): 'Raise exception on another thread.' for t in threads: ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(t.ident), ctypes.py_object(exception))
python
{ "resource": "" }
q33568
git_all
train
def git_all(*args, git=maybeloggit, **kwargs): 'Return entire output of git command.' try: cmd = git(*args, _err_to_out=True, _decode_errors='replace', **kwargs) out = cmd.stdout except sh.ErrorReturnCode as e: status('exit_code=%s' % e.exit_code) out = e.stdout out = o...
python
{ "resource": "" }
q33569
git_lines
train
def git_lines(*args, git=maybeloggit, **kwargs): 'Generator of stdout lines from given git command' err = io.StringIO() try: for line in git('--no-pager', _err=err, *args, _decode_errors='replace', _iter=True, _bg_exc=False, **kwargs): yield line[:-1] # remove EOL except sh.ErrorRet...
python
{ "resource": "" }
q33570
git_iter
train
def git_iter(sep, *args, git=maybeloggit, **kwargs): 'Generator of chunks of stdout from given git command, delineated by sep character' bufsize = 512 err = io.StringIO() chunks = [] try: for data in git('--no-pager', *args, _decode_errors='replace', _out_bufsize=bufsize, _iter=True, _err=err...
python
{ "resource": "" }
q33571
InvertedCanvas.scaleY
train
def scaleY(self, canvasY): 'returns plotter y coordinate, with y-axis inverted' plotterY = super().scaleY(canvasY) return (self.plotviewBox.ymax-plotterY+4)
python
{ "resource": "" }
q33572
Path.resolve
train
def resolve(self): 'Resolve pathname shell variables and ~userdir' return os.path.expandvars(os.path.expanduser(self.fqpn))
python
{ "resource": "" }
q33573
Plotter.getPixelAttrRandom
train
def getPixelAttrRandom(self, x, y): 'weighted-random choice of attr at this pixel.' c = list(attr for attr, rows in self.pixels[y][x].items() for r in rows if attr and attr not in self.hiddenAttrs) return random.choice(c) if c else 0
python
{ "resource": "" }
q33574
Plotter.getPixelAttrMost
train
def getPixelAttrMost(self, x, y): 'most common attr at this pixel.' r = self.pixels[y][x] c = sorted((len(rows), attr, rows) for attr, rows in list(r.items()) if attr and attr not in self.hiddenAttrs) if not c: return 0 _, attr, rows = c[-1] if isinstance(self...
python
{ "resource": "" }
q33575
Plotter.rowsWithin
train
def rowsWithin(self, bbox): 'return list of deduped rows within bbox' ret = {} for y in range(bbox.ymin, bbox.ymax+1): for x in range(bbox.xmin, bbox.xmax+1): for attr, rows in self.pixels[y][x].items(): if attr not in self.hiddenAttrs: ...
python
{ "resource": "" }
q33576
Canvas.setCursorSize
train
def setCursorSize(self, p): 'sets width based on diagonal corner p' self.cursorBox = BoundingBox(self.cursorBox.xmin, self.cursorBox.ymin, p.x, p.y) self.cursorBox.w = max(self.cursorBox.w, self.canvasCharWidth) self.cursorBox.h = max(self.cursorBox.h, self.canvasCharHeight)
python
{ "resource": "" }
q33577
Canvas.fixPoint
train
def fixPoint(self, plotterPoint, canvasPoint): 'adjust visibleBox.xymin so that canvasPoint is plotted at plotterPoint' self.visibleBox.xmin = canvasPoint.x - self.canvasW(plotterPoint.x-self.plotviewBox.xmin) self.visibleBox.ymin = canvasPoint.y - self.canvasH(plotterPoint.y-self.plotviewBox.ym...
python
{ "resource": "" }
q33578
Canvas.zoomTo
train
def zoomTo(self, bbox): 'set visible area to bbox, maintaining aspectRatio if applicable' self.fixPoint(self.plotviewBox.xymin, bbox.xymin) self.zoomlevel=max(bbox.w/self.canvasBox.w, bbox.h/self.canvasBox.h)
python
{ "resource": "" }
q33579
Canvas.checkCursor
train
def checkCursor(self): 'override Sheet.checkCursor' if self.cursorBox: if self.cursorBox.h < self.canvasCharHeight: self.cursorBox.h = self.canvasCharHeight*3/4 if self.cursorBox.w < self.canvasCharWidth: self.cursorBox.w = self.canvasCharWidth*3/4...
python
{ "resource": "" }
q33580
Canvas.scaleX
train
def scaleX(self, x): 'returns plotter x coordinate' return round(self.plotviewBox.xmin+(x-self.visibleBox.xmin)*self.xScaler)
python
{ "resource": "" }
q33581
Canvas.scaleY
train
def scaleY(self, y): 'returns plotter y coordinate' return round(self.plotviewBox.ymin+(y-self.visibleBox.ymin)*self.yScaler)
python
{ "resource": "" }
q33582
Canvas.render
train
def render(self, h, w): 'resets plotter, cancels previous render threads, spawns a new render' self.needsRefresh = False cancelThread(*(t for t in self.currentThreads if t.name == 'plotAll_async')) self.labels.clear() self.resetCanvasDimensions(h, w) self.render_async()
python
{ "resource": "" }
q33583
Canvas.render_sync
train
def render_sync(self): 'plots points and lines and text onto the Plotter' self.setZoom() bb = self.visibleBox xmin, ymin, xmax, ymax = bb.xmin, bb.ymin, bb.xmax, bb.ymax xfactor, yfactor = self.xScaler, self.yScaler plotxmin, plotymin = self.plotviewBox.xmin, self.plotvi...
python
{ "resource": "" }
q33584
nextColRegex
train
def nextColRegex(sheet, colregex): 'Go to first visible column after the cursor matching `colregex`.' pivot = sheet.cursorVisibleColIndex for i in itertools.chain(range(pivot+1, len(sheet.visibleCols)), range(0, pivot+1)): c = sheet.visibleCols[i] if re.search(colregex, c.name, regex_flags()...
python
{ "resource": "" }
q33585
searchRegex
train
def searchRegex(vd, sheet, moveCursor=False, reverse=False, **kwargs): 'Set row index if moveCursor, otherwise return list of row indexes.' def findMatchingColumn(sheet, row, columns, func): 'Find column for which func matches the displayed value in this row' for c in columns: ...
python
{ "resource": "" }
q33586
clipstr
train
def clipstr(s, dispw): '''Return clipped string and width in terminal display characters. Note: width may differ from len(s) if East Asian chars are 'fullwidth'.''' w = 0 ret = '' ambig_width = options.disp_ambig_width for c in s: if c != ' ' and unicodedata.category(c) in ('Cc', 'Zs', ...
python
{ "resource": "" }
q33587
cursesMain
train
def cursesMain(_scr, sheetlist): 'Populate VisiData object with sheets from a given list.' colors.setup() for vs in sheetlist: vd().push(vs) # first push does a reload status('Ctrl+H opens help') return vd().run(_scr)
python
{ "resource": "" }
q33588
SettingsMgr.iter
train
def iter(self, obj=None): 'Iterate through all keys considering context of obj. If obj is None, uses the context of the top sheet.' if obj is None and vd: obj = vd.sheet for o in self._mappings(obj): for k in self.keys(): for o2 in self[k]: ...
python
{ "resource": "" }
q33589
VisiData.status
train
def status(self, *args, priority=0): 'Add status message to be shown until next action.' k = (priority, args) self.statuses[k] = self.statuses.get(k, 0) + 1 if self.statusHistory: prevpri, prevargs, prevn = self.statusHistory[-1] if prevpri == priority and prevar...
python
{ "resource": "" }
q33590
VisiData.callHook
train
def callHook(self, hookname, *args, **kwargs): 'Call all functions registered with `addHook` for the given hookname.' r = [] for f in self.hooks[hookname]: try: r.append(f(*args, **kwargs)) except Exception as e: exceptionCaught(e) ...
python
{ "resource": "" }
q33591
VisiData.checkForFinishedThreads
train
def checkForFinishedThreads(self): 'Mark terminated threads with endTime.' for t in self.unfinishedThreads: if not t.is_alive(): t.endTime = time.process_time() if getattr(t, 'status', None) is None: t.status = 'ended'
python
{ "resource": "" }
q33592
VisiData.sync
train
def sync(self, expectedThreads=0): 'Wait for all but expectedThreads async threads to finish.' while len(self.unfinishedThreads) > expectedThreads: time.sleep(.3) self.checkForFinishedThreads()
python
{ "resource": "" }
q33593
VisiData.editText
train
def editText(self, y, x, w, record=True, **kwargs): 'Wrap global editText with `preedit` and `postedit` hooks.' v = self.callHook('preedit') if record else None if not v or v[0] is None: with EnableCursor(): v = editText(self.scr, y, x, w, **kwargs) else: ...
python
{ "resource": "" }
q33594
VisiData.input
train
def input(self, prompt, type='', defaultLast=False, **kwargs): 'Get user input, with history of `type`, defaulting to last history item if no input and defaultLast is True.' if type: histlist = list(self.lastInputs[type].keys()) ret = self._inputLine(prompt, history=histlist, **k...
python
{ "resource": "" }
q33595
VisiData._inputLine
train
def _inputLine(self, prompt, **kwargs): 'Add prompt to bottom of screen and get line of input from user.' self.inInput = True rstatuslen = self.drawRightStatus(self.scr, self.sheets[0]) attr = 0 promptlen = clipdraw(self.scr, self.windowHeight-1, 0, prompt, attr, w=self.windowWid...
python
{ "resource": "" }
q33596
VisiData.getkeystroke
train
def getkeystroke(self, scr, vs=None): 'Get keystroke and display it on status bar.' k = None try: k = scr.get_wch() self.drawRightStatus(scr, vs or self.sheets[0]) # continue to display progress % except curses.error: return '' # curses timeout ...
python
{ "resource": "" }
q33597
VisiData.exceptionCaught
train
def exceptionCaught(self, exc=None, **kwargs): 'Maintain list of most recent errors and return most recent one.' if isinstance(exc, ExpectedException): # already reported, don't log return self.lastErrors.append(stacktrace()) if kwargs.get('status', True): status...
python
{ "resource": "" }
q33598
VisiData.drawLeftStatus
train
def drawLeftStatus(self, scr, vs): 'Draw left side of status bar.' cattr = CursesAttr(colors.color_status) attr = cattr.attr error_attr = cattr.update_attr(colors.color_error, 1).attr warn_attr = cattr.update_attr(colors.color_warning, 2).attr sep = options.disp_status_se...
python
{ "resource": "" }
q33599
VisiData.drawRightStatus
train
def drawRightStatus(self, scr, vs): 'Draw right side of status bar. Return length displayed.' rightx = self.windowWidth-1 ret = 0 for rstatcolor in self.callHook('rstatus', vs): if rstatcolor: try: rstatus, coloropt = rstatcolor ...
python
{ "resource": "" }