INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Called on new threads installs the real tracer.
def _installation_trace(self, frame_unused, event_unused, arg_unused): """Called on new threads, installs the real tracer.""" # Remove ourselves as the trace function sys.settrace(None) # Install the real tracer. fn = self._start_tracer() # Invoke the real trace function ...
Start collecting trace information.
def start(self): """Start collecting trace information.""" if self._collectors: self._collectors[-1].pause() self._collectors.append(self) #print("Started: %r" % self._collectors, file=sys.stderr) # Check to see whether we had a fullcoverage tracer installed. ...
Stop collecting trace information.
def stop(self): """Stop collecting trace information.""" #print >>sys.stderr, "Stopping: %r" % self._collectors assert self._collectors assert self._collectors[-1] is self self.pause() self.tracers = [] # Remove this Collector from the stack, and resume the one ...
Pause tracing but be prepared to resume.
def pause(self): """Pause tracing, but be prepared to `resume`.""" for tracer in self.tracers: tracer.stop() stats = tracer.get_stats() if stats: print("\nCoverage.py tracer stats:") for k in sorted(stats.keys()): pr...
Resume tracing after a pause.
def resume(self): """Resume tracing after a `pause`.""" for tracer in self.tracers: tracer.start() threading.settrace(self._installation_trace)
Return the line data collected.
def get_line_data(self): """Return the line data collected. Data is { filename: { lineno: None, ...}, ...} """ if self.branch: # If we were measuring branches, then we have to re-build the dict # to show line data. line_data = {} for f, a...
Create a new code cell with input and output
def new_code_cell(code=None, prompt_number=None): """Create a new code cell with input and output""" cell = NotebookNode() cell.cell_type = u'code' if code is not None: cell.code = unicode(code) if prompt_number is not None: cell.prompt_number = int(prompt_number) return cell
Create a new text cell.
def new_text_cell(text=None): """Create a new text cell.""" cell = NotebookNode() if text is not None: cell.text = unicode(text) cell.cell_type = u'text' return cell
Create a notebook by name id and a list of worksheets.
def new_notebook(cells=None): """Create a notebook by name, id and a list of worksheets.""" nb = NotebookNode() if cells is not None: nb.cells = cells else: nb.cells = [] return nb
Shorthand for assert a == b %r ! = %r % ( a b )
def eq_(a, b, msg=None): """Shorthand for 'assert a == b, "%r != %r" % (a, b) """ if not a == b: raise AssertionError(msg or "%r != %r" % (a, b))
check a result dict for errors and raise CompositeError if any exist. Passthrough otherwise.
def collect_exceptions(rdict_or_list, method='unspecified'): """check a result dict for errors, and raise CompositeError if any exist. Passthrough otherwise.""" elist = [] if isinstance(rdict_or_list, dict): rlist = rdict_or_list.values() else: rlist = rdict_or_list for r in rlis...
render one or all of my tracebacks to a list of lines
def render_traceback(self, excid=None): """render one or all of my tracebacks to a list of lines""" lines = [] if excid is None: for (en,ev,etb,ei) in self.elist: lines.append(self._get_engine_str(ei)) lines.extend((etb or 'No traceback available').spl...
Call this at Python startup to perhaps measure coverage.
def process_startup(): """Call this at Python startup to perhaps measure coverage. If the environment variable COVERAGE_PROCESS_START is defined, coverage measurement is started. The value of the variable is the config file to use. There are two ways to configure your Python installation to invok...
Return the canonical directory of the module or file morf.
def _canonical_dir(self, morf): """Return the canonical directory of the module or file `morf`.""" return os.path.split(CodeUnit(morf, self.file_locator).filename)[0]
Return the source file for filename.
def _source_for_file(self, filename): """Return the source file for `filename`.""" if not filename.endswith(".py"): if filename[-4:-1] == ".py": filename = filename[:-1] elif filename.endswith("$py.class"): # jython filename = filename[:-9] + ".py"...
Decide whether to trace execution in filename with a reason.
def _should_trace_with_reason(self, filename, frame): """Decide whether to trace execution in `filename`, with a reason. This function is called from the trace function. As each new file name is encountered, this function determines whether it is traced or not. Returns a pair of value...
Decide whether to trace execution in filename.
def _should_trace(self, filename, frame): """Decide whether to trace execution in `filename`. Calls `_should_trace_with_reason`, and returns just the decision. """ canonical, reason = self._should_trace_with_reason(filename, frame) if self.debug.should('trace'): if ...
Use msg as a warning.
def _warn(self, msg): """Use `msg` as a warning.""" self._warnings.append(msg) sys.stderr.write("Coverage.py warning: %s\n" % msg)
Update the source_match matcher with latest imported packages.
def _check_for_packages(self): """Update the source_match matcher with latest imported packages.""" # Our self.source_pkgs attribute is a list of package names we want to # measure. Each time through here, we see if we've imported any of # them yet. If so, we add its file to source_mat...
Start measuring code coverage.
def start(self): """Start measuring code coverage. Coverage measurement actually occurs in functions called after `start` is invoked. Statements in the same scope as `start` won't be measured. Once you invoke `start`, you must also call `stop` eventually, or your process might...
Clean up on process shutdown.
def _atexit(self): """Clean up on process shutdown.""" if self._started: self.stop() if self.auto_data: self.save()
Exclude source lines from execution consideration.
def exclude(self, regex, which='exclude'): """Exclude source lines from execution consideration. A number of lists of regular expressions are maintained. Each list selects lines that are treated differently during reporting. `which` determines which list is modified. The "exclude" li...
Return a compiled regex for the given exclusion list.
def _exclude_regex(self, which): """Return a compiled regex for the given exclusion list.""" if which not in self._exclude_re: excl_list = getattr(self.config, which + "_list") self._exclude_re[which] = join_regex(excl_list) return self._exclude_re[which]
Save the collected coverage data to the data file.
def save(self): """Save the collected coverage data to the data file.""" data_suffix = self.data_suffix if data_suffix is True: # If data_suffix was a simple true value, then make a suffix with # plenty of distinguishing information. We do this here in # `sav...
Combine together a number of similarly - named coverage data files.
def combine(self): """Combine together a number of similarly-named coverage data files. All coverage data files whose name starts with `data_file` (from the coverage() constructor) will be read, and combined together into the current measurements. """ aliases = None ...
Get the collected data and reset the collector.
def _harvest_data(self): """Get the collected data and reset the collector. Also warn about various problems collecting data. """ if not self._measured: return self.data.add_line_data(self.collector.get_line_data()) self.data.add_arc_data(self.collector.get...
Like analysis2 but doesn t return excluded line numbers.
def analysis(self, morf): """Like `analysis2` but doesn't return excluded line numbers.""" f, s, _, m, mf = self.analysis2(morf) return f, s, m, mf
Analyze a module.
def analysis2(self, morf): """Analyze a module. `morf` is a module or a filename. It will be analyzed to determine its coverage statistics. The return value is a 5-tuple: * The filename for the module. * A list of line numbers of executable statements. * A list of lin...
Analyze a single morf or code unit.
def _analyze(self, it): """Analyze a single morf or code unit. Returns an `Analysis` object. """ self._harvest_data() if not isinstance(it, CodeUnit): it = code_unit_factory(it, self.file_locator)[0] return Analysis(self, it)
Write a summary report to file.
def report(self, morfs=None, show_missing=True, ignore_errors=None, file=None, # pylint: disable=W0622 omit=None, include=None ): """Write a summary report to `file`. Each module in `morfs` is listed, with counts of statements, ex...
Annotate a list of modules.
def annotate(self, morfs=None, directory=None, ignore_errors=None, omit=None, include=None): """Annotate a list of modules. Each module in `morfs` is annotated. The source is written to a new file, named with a ",cover" suffix, with each line prefixed with a marker ...
Generate an HTML report.
def html_report(self, morfs=None, directory=None, ignore_errors=None, omit=None, include=None, extra_css=None, title=None): """Generate an HTML report. The HTML is written to `directory`. The file "index.html" is the overview starting point, with links to more detailed page...
Generate an XML report of coverage results.
def xml_report(self, morfs=None, outfile=None, ignore_errors=None, omit=None, include=None): """Generate an XML report of coverage results. The report is compatible with Cobertura reports. Each module in `morfs` is included in the report. `outfile` is the path to w...
Return a list of ( key value ) pairs showing internal information.
def sysinfo(self): """Return a list of (key, value) pairs showing internal information.""" import coverage as covmod import platform, re try: implementation = platform.python_implementation() except AttributeError: implementation = "unknown" inf...
Display a Python object in all frontends.
def display(*objs, **kwargs): """Display a Python object in all frontends. By default all representations will be computed and sent to the frontends. Frontends can decide which representation is used and how. Parameters ---------- objs : tuple of objects The Python objects to display. ...
Display the pretty ( default ) representation of an object.
def display_pretty(*objs, **kwargs): """Display the pretty (default) representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw text data to display. raw : bool Are the data objects raw data or Python objects ...
Display the HTML representation of an object.
def display_html(*objs, **kwargs): """Display the HTML representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw HTML data to display. raw : bool Are the data objects raw data or Python objects that need to b...
Display the SVG representation of an object.
def display_svg(*objs, **kwargs): """Display the SVG representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw svg data to display. raw : bool Are the data objects raw data or Python objects that need to be ...
Display the PNG representation of an object.
def display_png(*objs, **kwargs): """Display the PNG representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw png data to display. raw : bool Are the data objects raw data or Python objects that need to be ...
Display the JPEG representation of an object.
def display_jpeg(*objs, **kwargs): """Display the JPEG representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw JPEG data to display. raw : bool Are the data objects raw data or Python objects that need to b...
Display the LaTeX representation of an object.
def display_latex(*objs, **kwargs): """Display the LaTeX representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw latex data to display. raw : bool Are the data objects raw data or Python objects that need t...
Display the JSON representation of an object.
def display_json(*objs, **kwargs): """Display the JSON representation of an object. Note that not many frontends support displaying JSON. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw json data to display. raw : bool Are...
Display the Javascript representation of an object.
def display_javascript(*objs, **kwargs): """Display the Javascript representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw javascript data to display. raw : bool Are the data objects raw data or Python obje...
Clear the output of the current cell receiving output. Optionally each of stdout/ stderr or other non - stream data ( e. g. anything produced by display () ) can be excluded from the clear event. By default everything is cleared. Parameters ---------- stdout: bool [ default: True ] Whether to clear stdout. stderr: bool...
def clear_output(stdout=True, stderr=True, other=True): """Clear the output of the current cell receiving output. Optionally, each of stdout/stderr or other non-stream data (e.g. anything produced by display()) can be excluded from the clear event. By default, everything is cleared. P...
Reload the raw data from file or URL.
def reload(self): """Reload the raw data from file or URL.""" if self.filename is not None: with open(self.filename, self._read_flags) as f: self.data = f.read() elif self.url is not None: try: import urllib2 response = urll...
Check for an update for pip.
def pip_version_check(session): """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ import pip # imported here to prevent circular import...
Find the full path to a command using which.
def _find_cmd(cmd): """Find the full path to a command using which.""" path = sp.Popen(['/usr/bin/env', 'which', cmd], stdout=sp.PIPE, stderr=sp.PIPE).communicate()[0] return py3compat.bytes_to_str(path)
Run a command and return its stdout/ stderr as a string.
def getoutput_pexpect(self, cmd): """Run a command and return its stdout/stderr as a string. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- output : str A string containing the combination of std...
Execute a command in a subshell.
def system(self, cmd): """Execute a command in a subshell. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- int : child's exitstatus """ # Get likely encoding for the output. enc = DE...
Forward read events from an FD over a socket.
def forward_read_events(fd, context=None): """Forward read events from an FD over a socket. This method wraps a file in a socket pair, so it can be polled for read events by select (specifically zmq.eventloop.ioloop) """ if context is None: context = zmq.Context.instance() push = contex...
Loop through lines in self. fd and send them over self. sock.
def run(self): """Loop through lines in self.fd, and send them over self.sock.""" line = self.fd.readline() # allow for files opened in unicode mode if isinstance(line, unicode): send = self.sock.send_unicode else: send = self.sock.send while line:...
Return a launcher for a given clsname and kind.
def find_launcher_class(clsname, kind): """Return a launcher for a given clsname and kind. Parameters ========== clsname : str The full name of the launcher class, either with or without the module path, or an abbreviation (MPI, SSH, SGE, PBS, LSF, WindowsHPC). kind : str ...
Start the app for the stop subcommand.
def start(self): """Start the app for the stop subcommand.""" try: pid = self.get_pid_from_file() except PIDFileError: self.log.critical( 'Could not read pid file, cluster is probably not running.' ) # Here I exit with a unusual exi...
import and instantiate a Launcher based on importstring
def build_launcher(self, clsname, kind=None): """import and instantiate a Launcher based on importstring""" try: klass = find_launcher_class(clsname, kind) except (ImportError, KeyError): self.log.fatal("Could not import launcher class: %r"%clsname) self.exit(...
Start the app for the engines subcommand.
def start(self): """Start the app for the engines subcommand.""" self.log.info("IPython cluster: started") # First see if the cluster is already running # Now log and daemonize self.log.info( 'Starting engines with [daemon=%r]' % self.daemonize ) # TO...
Start the app for the start subcommand.
def start(self): """Start the app for the start subcommand.""" # First see if the cluster is already running try: pid = self.get_pid_from_file() except PIDFileError: pass else: if self.check_pid(pid): self.log.critical( ...
Create a new wx app or return an exiting one.
def get_app_wx(*args, **kwargs): """Create a new wx app or return an exiting one.""" import wx app = wx.GetApp() if app is None: if not kwargs.has_key('redirect'): kwargs['redirect'] = False app = wx.PySimpleApp(*args, **kwargs) return app
Is the wx event loop running.
def is_event_loop_running_wx(app=None): """Is the wx event loop running.""" if app is None: app = get_app_wx() if hasattr(app, '_in_event_loop'): return app._in_event_loop else: return app.IsMainLoopRunning()
Start the wx event loop in a consistent manner.
def start_event_loop_wx(app=None): """Start the wx event loop in a consistent manner.""" if app is None: app = get_app_wx() if not is_event_loop_running_wx(app): app._in_event_loop = True app.MainLoop() app._in_event_loop = False else: app._in_event_loop = True
Create a new qt4 app or return an existing one.
def get_app_qt4(*args, **kwargs): """Create a new qt4 app or return an existing one.""" from IPython.external.qt_for_kernel import QtGui app = QtGui.QApplication.instance() if app is None: if not args: args = ([''],) app = QtGui.QApplication(*args, **kwargs) return app
Is the qt4 event loop running.
def is_event_loop_running_qt4(app=None): """Is the qt4 event loop running.""" if app is None: app = get_app_qt4(['']) if hasattr(app, '_in_event_loop'): return app._in_event_loop else: # Does qt4 provide a other way to detect this? return False
Start the qt4 event loop in a consistent manner.
def start_event_loop_qt4(app=None): """Start the qt4 event loop in a consistent manner.""" if app is None: app = get_app_qt4(['']) if not is_event_loop_running_qt4(app): app._in_event_loop = True app.exec_() app._in_event_loop = False else: app._in_event_loop = Tr...
Check namespace packages __init__ for declare_namespace
def check_package(self, package, package_dir): """Check namespace packages' __init__ for declare_namespace""" try: return self.packages_checked[package] except KeyError: pass init_py = _build_py.check_package(self, package, package_dir) self.packages_chec...
Return a blank canvas to annotate.
def blank_canvas(width, height): """Return a blank canvas to annotate. :param width: xdim (int) :param height: ydim (int) :returns: :class:`jicbioimage.illustrate.Canvas` """ canvas = np.zeros((height, width, 3), dtype=np.uint8) return canvas.view(Canvas)
Draw a cross on the canvas.
def draw_cross(self, position, color=(255, 0, 0), radius=4): """Draw a cross on the canvas. :param position: (row, col) tuple :param color: RGB tuple :param radius: radius of the cross (int) """ y, x = position for xmod in np.arange(-radius, radius+1, 1): ...
Draw a line between pos1 and pos2 on the canvas.
def draw_line(self, pos1, pos2, color=(255, 0, 0)): """Draw a line between pos1 and pos2 on the canvas. :param pos1: position 1 (row, col) tuple :param pos2: position 2 (row, col) tuple :param color: RGB tuple """ r1, c1 = tuple([int(round(i, 0)) for i in pos1]) ...
Write text at x y top left corner position.
def text_at(self, text, position, color=(255, 255, 255), size=12, antialias=False, center=False): """Write text at x, y top left corner position. By default the x and y coordinates represent the top left hand corner of the text. The text can be centered vertically and horizontal...
Return a canvas from a grayscale image.
def from_grayscale(im, channels_on=(True, True, True)): """Return a canvas from a grayscale image. :param im: single channel image :channels_on: channels to populate with input image :returns: :class:`jicbioimage.illustrate.Canvas` """ xdim, ydim = im.shape canva...
Returns a unique ID of a given length. User version = 2 for cross - systems uniqueness.
def get_uuid(length=32, version=1): """ Returns a unique ID of a given length. User `version=2` for cross-systems uniqueness. """ if version == 1: return uuid.uuid1().hex[:length] else: return uuid.uuid4().hex[:length]
Converts a dict to an encoded URL. Example: given data = { a: 1 b: 2 } it returns a = 1&b = 2
def get_dict_to_encoded_url(data): """ Converts a dict to an encoded URL. Example: given data = {'a': 1, 'b': 2}, it returns 'a=1&b=2' """ unicode_data = dict([(k, smart_str(v)) for k, v in data.items()]) encoded = urllib.urlencode(unicode_data) return encoded
Converts an encoded URL to a dict. Example: given string = a = 1&b = 2 it returns { a: 1 b: 2 }
def get_encoded_url_to_dict(string): """ Converts an encoded URL to a dict. Example: given string = 'a=1&b=2' it returns {'a': 1, 'b': 2} """ data = urllib.parse.parse_qsl(string, keep_blank_values=True) data = dict(data) return data
Build a unique key from get data
def get_unique_key_from_get(get_dict): """ Build a unique key from get data """ site = Site.objects.get_current() key = get_dict_to_encoded_url(get_dict) cache_key = '{}_{}'.format(site.domain, key) return hashlib.md5(cache_key).hexdigest()
Given a decimal number returns a string bitfield of length = len Example: given deci_num = 1 and len = 10 it return 0000000001
def tobin(deci_num, len=32): """ Given a decimal number, returns a string bitfield of length = len Example: given deci_num = 1 and len = 10, it return 0000000001 """ bitstr = "".join(map(lambda y: str((deci_num >> y) & 1), range(len - 1, -1, -1))) return bitstr
Validates and email address. Note: valid emails must follow the <name >
def is_valid_email(email): """ Validates and email address. Note: valid emails must follow the <name>@<domain><.extension> patterns. """ try: validate_email(email) except ValidationError: return False if simple_email_re.match(email): return True return False
Returns domain name portion of a URL
def get_domain(url): """ Returns domain name portion of a URL """ if 'http' not in url.lower(): url = 'http://{}'.format(url) return urllib.parse.urlparse(url).hostname
Returns a dictionary from a URL params
def get_url_args(url): """ Returns a dictionary from a URL params """ url_data = urllib.parse.urlparse(url) arg_dict = urllib.parse.parse_qs(url_data.query) return arg_dict
Trains a k - nearest neighbors classifier for face recognition.
def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False): """ Trains a k-nearest neighbors classifier for face recognition. :param train_dir: directory that contains a sub-directory for each known person, with its name. (View in source code to see train_dir ex...
Recognizes faces in given image using a trained KNN classifier
def predict(X_img_path, knn_clf=None, model_path=None, distance_threshold=0.6): """ Recognizes faces in given image using a trained KNN classifier :param X_img_path: path to image to be recognized :param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified. ...
Shows the face recognition results visually.
def show_prediction_labels_on_image(img_path, predictions): """ Shows the face recognition results visually. :param img_path: path to image to be recognized :param predictions: results of the predict function :return: """ pil_image = Image.open(img_path).convert("RGB") draw = ImageDraw....
Convert a dlib rect object to a plain tuple in ( top right bottom left ) order
def _rect_to_css(rect): """ Convert a dlib 'rect' object to a plain tuple in (top, right, bottom, left) order :param rect: a dlib 'rect' object :return: a plain tuple representation of the rect in (top, right, bottom, left) order """ return rect.top(), rect.right(), rect.bottom(), rect.left()
Make sure a tuple in ( top right bottom left ) order is within the bounds of the image.
def _trim_css_to_bounds(css, image_shape): """ Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image. :param css: plain tuple representation of the rect in (top, right, bottom, left) order :param image_shape: numpy shape of the image array :return: a trimmed plain...
Given a list of face encodings compare them to a known face encoding and get a euclidean distance for each comparison face. The distance tells you how similar the faces are.
def face_distance(face_encodings, face_to_compare): """ Given a list of face encodings, compare them to a known face encoding and get a euclidean distance for each comparison face. The distance tells you how similar the faces are. :param faces: List of face encodings to compare :param face_to_compa...
Loads an image file (. jpg. png etc ) into a numpy array
def load_image_file(file, mode='RGB'): """ Loads an image file (.jpg, .png, etc) into a numpy array :param file: image file name or file object to load :param mode: format to convert the image to. Only 'RGB' (8-bit RGB, 3 channels) and 'L' (black and white) are supported. :return: image contents as...
Returns an array of bounding boxes of human faces in a image
def _raw_face_locations(img, number_of_times_to_upsample=1, model="hog"): """ Returns an array of bounding boxes of human faces in a image :param img: An image (as a numpy array) :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller face...
Returns an array of bounding boxes of human faces in a image
def face_locations(img, number_of_times_to_upsample=1, model="hog"): """ Returns an array of bounding boxes of human faces in a image :param img: An image (as a numpy array) :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces. ...
Returns an 2d array of bounding boxes of human faces in a image using the cnn face detector If you are using a GPU this can give you much faster results since the GPU can process batches of images at once. If you aren t using a GPU you don t need this function.
def batch_face_locations(images, number_of_times_to_upsample=1, batch_size=128): """ Returns an 2d array of bounding boxes of human faces in a image using the cnn face detector If you are using a GPU, this can give you much faster results since the GPU can process batches of images at once. If you aren'...
Given an image returns a dict of face feature locations ( eyes nose etc ) for each face in the image
def face_landmarks(face_image, face_locations=None, model="large"): """ Given an image, returns a dict of face feature locations (eyes, nose, etc) for each face in the image :param face_image: image to search :param face_locations: Optionally provide a list of face locations to check. :param model:...
Given an image return the 128 - dimension face encoding for each face in the image.
def face_encodings(face_image, known_face_locations=None, num_jitters=1): """ Given an image, return the 128-dimension face encoding for each face in the image. :param face_image: The image that contains one or more faces :param known_face_locations: Optional - the bounding boxes of each face if you al...
Parses the given data type string to a: class: DataType. The data type string format equals to: class: DataType. simpleString except that top level struct type can omit the struct< > and atomic types use typeName () as their format e. g. use byte instead of tinyint for: class: ByteType. We can also use int as a short n...
def _parse_datatype_string(s): """ Parses the given data type string to a :class:`DataType`. The data type string format equals to :class:`DataType.simpleString`, except that top level struct type can omit the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use ``byte`` instead ...
Return the Catalyst datatype from the size of integers.
def _int_size_to_type(size): """ Return the Catalyst datatype from the size of integers. """ if size <= 8: return ByteType if size <= 16: return ShortType if size <= 32: return IntegerType if size <= 64: return LongType
Infer the DataType from obj
def _infer_type(obj): """Infer the DataType from obj """ if obj is None: return NullType() if hasattr(obj, '__UDT__'): return obj.__UDT__ dataType = _type_mappings.get(type(obj)) if dataType is DecimalType: # the precision and scale of `obj` may be different from row to...
Infer the schema from dict/ namedtuple/ object
def _infer_schema(row, names=None): """Infer the schema from dict/namedtuple/object""" if isinstance(row, dict): items = sorted(row.items()) elif isinstance(row, (tuple, list)): if hasattr(row, "__fields__"): # Row items = zip(row.__fields__, tuple(row)) elif hasattr(ro...
Return whether there is NullType in dt or not
def _has_nulltype(dt): """ Return whether there is NullType in `dt` or not """ if isinstance(dt, StructType): return any(_has_nulltype(f.dataType) for f in dt.fields) elif isinstance(dt, ArrayType): return _has_nulltype((dt.elementType)) elif isinstance(dt, MapType): return _has_...
Create a converter to drop the names of fields in obj
def _create_converter(dataType): """Create a converter to drop the names of fields in obj """ if not _need_converter(dataType): return lambda x: x if isinstance(dataType, ArrayType): conv = _create_converter(dataType.elementType) return lambda row: [conv(v) for v in row] elif i...
Make a verifier that checks the type of obj against dataType and raises a TypeError if they do not match.
def _make_type_verifier(dataType, nullable=True, name=None): """ Make a verifier that checks the type of obj against dataType and raises a TypeError if they do not match. This verifier also checks the value of obj against datatype and raises a ValueError if it's not within the allowed range, e.g. u...
Convert Spark data type to pyarrow type
def to_arrow_type(dt): """ Convert Spark data type to pyarrow type """ import pyarrow as pa if type(dt) == BooleanType: arrow_type = pa.bool_() elif type(dt) == ByteType: arrow_type = pa.int8() elif type(dt) == ShortType: arrow_type = pa.int16() elif type(dt) == Integ...
Convert a schema from Spark to Arrow
def to_arrow_schema(schema): """ Convert a schema from Spark to Arrow """ import pyarrow as pa fields = [pa.field(field.name, to_arrow_type(field.dataType), nullable=field.nullable) for field in schema] return pa.schema(fields)
Convert pyarrow type to Spark data type.
def from_arrow_type(at): """ Convert pyarrow type to Spark data type. """ import pyarrow.types as types if types.is_boolean(at): spark_type = BooleanType() elif types.is_int8(at): spark_type = ByteType() elif types.is_int16(at): spark_type = ShortType() elif types.is_...
Convert schema from Arrow to Spark.
def from_arrow_schema(arrow_schema): """ Convert schema from Arrow to Spark. """ return StructType( [StructField(field.name, from_arrow_type(field.type), nullable=field.nullable) for field in arrow_schema])
Convert timezone aware timestamps to timezone - naive in the specified timezone or local timezone.
def _check_series_localize_timestamps(s, timezone): """ Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone. If the input series is not a timestamp series, then the same series is returned. If the input series is a timestamp series, then a converted series is...