def Func(arg_0):
    """Determine if distance over antimeridian is shorter than normal distance."""
    if arg_0[0][0].tile_pyramid.is_global:
        # get set of tile columns
        arg_1 = sorted(list(set([t[0].col for t in arg_0])))
        # if tile columns are an unbroken sequence, tiles are connected and are not
        # passing the Antimeridian
        if arg_1 == list(range(min(arg_1), max(arg_1) + 1)):
            return False
        else:
            # look at column gaps and try to determine the smallest distance
            def gen_groups(arg_2):
                """Groups tile columns by sequence."""
                arg_3 = arg_2[0]
                arg_4 = [arg_3]
                for arg_5 in arg_2[1:]:
                    # item is next in expected sequence
                    if arg_5 == arg_3 + 1:
                        arg_4.append(arg_5)
                    # gap occured, so yield existing group and create new one
                    else:
                        yield arg_4
                        arg_4 = [arg_5]
                    arg_3 = arg_5
                yield arg_4

            arg_6 = list(gen_groups(arg_1))
            # in case there is only one group, don't shift
            if len(arg_6) == 1:
                return False
            # distance between first column of first group and last column of last group
            arg_7 = arg_6[-1][-1] - arg_6[0][0]
            # distance between last column of first group and last column of first group
            # but crossing the antimeridian
            arg_8 = (
                arg_6[0][-1] + arg_0[0][0].tile_pyramid.matrix_width(arg_0[0][0].zoom)
            ) - arg_6[-1][0]
            # return whether distance over antimeridian is shorter
            return arg_8 < arg_7
    else:
        return False


def Func(arg_0, arg_1=True, arg_2=0, arg_3="int16"):
    """
    Turn input data into a proper array for further usage.

    Outut array is always 3-dimensional with the given data type. If the output
    is masked, the fill_value corresponds to the given nodata value and the
    nodata value will be burned into the data array.

    Parameters
    ----------
    data : array or iterable
        array (masked or normal) or iterable containing arrays
    nodata : integer or float
        nodata value (default: 0) used if input is not a masked array and
        for output array
    masked : bool
        return a NumPy Array or a NumPy MaskedArray (default: True)
    dtype : string
        data type of output array (default: "int16")

    Returns
    -------
    array : array
    """
    # input is iterable
    if isinstance(arg_0, (list, tuple)):
        return _prepare_iterable(arg_0, arg_1, arg_2, arg_3)

    # special case if a 2D single band is provided
    elif isinstance(arg_0, np.ndarray) and arg_0.ndim == 2:
        arg_0 = ma.expand_dims(arg_0, axis=0)

    # input is a masked array
    if isinstance(arg_0, ma.MaskedArray):
        return _prepare_masked(arg_0, arg_1, arg_2, arg_3)

    # input is a NumPy array
    elif isinstance(arg_0, np.ndarray):
        if arg_1:
            return ma.masked_values(arg_0.astype(arg_3, copy=False), arg_2, copy=False)
        else:
            return arg_0.astype(arg_3, copy=False)
    else:
        raise ValueError(
            "data must be array, masked array or iterable containing arrays."
        )


def Func(
    arg_0, arg_1=None, arg_2=None, arg_3=False, arg_4=True,
    arg_5=False
):
    """
    Reproject a geometry to target CRS.

    Also, clips geometry if it lies outside the destination CRS boundary.
    Supported destination CRSes for clipping: 4326 (WGS84), 3857 (Spherical
    Mercator) and 3035 (ETRS89 / ETRS-LAEA).

    Parameters
    ----------
    geometry : ``shapely.geometry``
    src_crs : ``rasterio.crs.CRS`` or EPSG code
        CRS of source data
    dst_crs : ``rasterio.crs.CRS`` or EPSG code
        target CRS
    error_on_clip : bool
        raises a ``RuntimeError`` if a geometry is outside of CRS bounds
        (default: False)
    validity_check : bool
        checks if reprojected geometry is valid and throws ``TopologicalError``
        if invalid (default: True)
    antimeridian_cutting : bool
        cut geometry at Antimeridian; can result in a multipart output geometry

    Returns
    -------
    geometry : ``shapely.geometry``
    """
    arg_1 = _validated_crs(arg_1)
    arg_2 = _validated_crs(arg_2)

    def _reproject_geom(arg_0, arg_1, arg_2):
        if arg_0.is_empty:
            return arg_0
        else:
            arg_6 = to_shape(
                transform_geom(
                    arg_1.to_dict(),
                    arg_2.to_dict(),
                    mapping(arg_0),
                    arg_5=arg_5
                )
            )
            return _repair(arg_6) if arg_4 else arg_6

    # return repaired geometry if no reprojection needed
    if arg_1 == arg_2 or arg_0.is_empty:
        return _repair(arg_0)

    # geometry needs to be clipped to its CRS bounds
    elif (
        arg_2.is_epsg_code and               # just in case for an CRS with EPSG code
        arg_2.get("init") in CRS_BOUNDS and  # if CRS has defined bounds
        arg_2.get("init") != "epsg:4326"     # and is not WGS84 (does not need clipping)
    ):
        arg_7 = CRS().from_epsg(4326)
        # get dst_crs boundaries
        arg_8 = box(*CRS_BOUNDS[arg_2.get("init")])
        # reproject geometry to WGS84
        arg_9 = _reproject_geom(arg_0, arg_1, arg_7)
        # raise error if geometry has to be clipped
        if arg_3 and not arg_9.within(arg_8):
            raise RuntimeError("geometry outside target CRS bounds")
        # clip geometry dst_crs boundaries and return
        return _reproject_geom(arg_8.intersection(arg_9), arg_7, arg_2)

    # return without clipping if destination CRS does not have defined bounds
    else:
        return _reproject_geom(arg_0, arg_1, arg_2)


def Func(arg_0, arg_1):
    """
    Segmentize Polygon outer ring by segmentize value.

    Just Polygon geometry type supported.

    Parameters
    ----------
    geometry : ``shapely.geometry``
    segmentize_value: float

    Returns
    -------
    geometry : ``shapely.geometry``
    """
    if arg_0.geom_type != "Polygon":
        raise TypeError("segmentize geometry type must be Polygon")

    return Polygon(
        LinearRing([
            arg_3
            # pick polygon linestrings
            for arg_2 in map(
                lambda x: LineString([x[0], x[1]]),
                zip(arg_0.exterior.coords[:-1], arg_0.exterior.coords[1:])
            )
            # interpolate additional points in between and don't forget end point
            for arg_3 in [
                arg_2.interpolate(arg_1 * arg_4).coords[0]
                for arg_4 in range(int(arg_2.length / arg_1))
            ] + [arg_2.coords[1]]
        ])
    )


def Func(
    arg_0=None, arg_1=None, arg_2=None, arg_3=None, arg_4=None
):
    """
    Write features to GeoJSON file.

    Parameters
    ----------
    in_data : features
    out_schema : dictionary
        output schema for fiona
    out_tile : ``BufferedTile``
        tile used for output extent
    out_path : string
        output path for GeoJSON file
    """
    # Delete existing file.
    try:
        os.remove(arg_3)
    except OSError:
        pass

    arg_5 = []
    for arg_6 in arg_0:
        try:
            # clip feature geometry to tile bounding box and append for writing
            # if clipped feature still
            for arg_7 in multipart_to_singleparts(
                clean_geometry_type(
                    to_shape(arg_6["geometry"]).intersection(arg_2.bbox),
                    arg_1["geometry"]
                )
            ):
                arg_5.append({
                    "geometry": mapping(arg_7),
                    "properties": arg_6["properties"]
                })
        except Exception as e:
            logger.warning("failed to prepare geometry for writing: %s", e)
            continue

    # write if there are output features
    if arg_5:

        try:
            if arg_3.startswith("s3://"):
                # write data to remote file
                with VectorWindowMemoryFile(
                    tile=arg_2,
                    features=arg_5,
                    schema=arg_1,
                    driver="GeoJSON"
                ) as memfile:
                    logger.debug((arg_2.id, "upload tile", arg_3))
                    arg_4.put_object(
                        Key="/".join(arg_3.split("/")[3:]),
                        Body=memfile
                    )
            else:
                # write data to local file
                with fiona.open(
                    arg_3, 'w', schema=arg_1, driver="GeoJSON",
                    crs=arg_2.crs.to_dict()
                ) as dst:
                    logger.debug((arg_2.id, "write tile", arg_3))
                    dst.writerecords(arg_5)
        except Exception as e:
            logger.error("error while writing file %s: %s", arg_3, e)
            raise

    else:
        logger.debug((arg_2.id, "nothing to write", arg_3))


def Func(arg_0, arg_1, arg_2=True):
    """
    Return geometry of a specific type if possible.

    Filters and splits up GeometryCollection into target types. This is
    necessary when after clipping and/or reprojecting the geometry types from
    source geometries change (i.e. a Polygon becomes a LineString or a
    LineString becomes Point) in some edge cases.

    Parameters
    ----------
    geometry : ``shapely.geometry``
    target_type : string
        target geometry type
    allow_multipart : bool
        allow multipart geometries (default: True)

    Returns
    -------
    cleaned geometry : ``shapely.geometry``
        returns None if input geometry type differs from target type

    Raises
    ------
    GeometryTypeError : if geometry type does not match target_type
    """
    arg_3 = {
        "Point": MultiPoint,
        "LineString": MultiLineString,
        "Polygon": MultiPolygon,
        "MultiPoint": MultiPoint,
        "MultiLineString": MultiLineString,
        "MultiPolygon": MultiPolygon
    }

    if arg_1 not in arg_3.keys():
        raise TypeError("target type is not supported: %s" % arg_1)

    if arg_0.geom_type == arg_1:
        return arg_0

    elif arg_2:
        arg_4 = arg_3[arg_1]
        if arg_0.geom_type == "GeometryCollection":
            return arg_4([
                Func(arg_5, arg_1, arg_2)
                for arg_5 in arg_0])
        elif any([
            isinstance(arg_0, arg_4),
            arg_3[arg_0.geom_type] == arg_4
        ]):
            return arg_0

    raise GeometryTypeError(
        "geometry type does not match: %s, %s" % (arg_0.geom_type, arg_1)
    )


def Func(arg_0):
    """
    Yield single part geometries if geom is multipart, otherwise yield geom.

    Parameters:
    -----------
    geom : shapely geometry

    Returns:
    --------
    shapely single part geometries
    """
    if isinstance(arg_0, base.BaseGeometry):
        if hasattr(arg_0, "geoms"):
            for arg_1 in arg_0:
                yield arg_1
        else:
            yield arg_0


def Func(
    arg_0,
    arg_1="nearest",
    arg_2="gdal",
    arg_3=None,
    arg_4=8,
    arg_5=False,
    arg_6=0,
    **arg_7
):
    """
    Convert and optionally clip input raster data.

    Inputs:
    -------
    raster
        singleband or multiband data input
    clip (optional)
        vector data used to clip output

    Parameters
    ----------
    td_resampling : str (default: 'nearest')
        Resampling used when reading from TileDirectory.
    td_matching_method : str ('gdal' or 'min') (default: 'gdal')
        gdal: Uses GDAL's standard method. Here, the target resolution is
            calculated by averaging the extent's pixel sizes over both x and y
            axes. This approach returns a zoom level which may not have the
            best quality but will speed up reading significantly.
        min: Returns the zoom level which matches the minimum resolution of the
            extents four corner pixels. This approach returns the zoom level
            with the best possible quality but with low performance. If the
            tile extent is outside of the destination pyramid, a
            TopologicalError will be raised.
    td_matching_max_zoom : int (optional, default: None)
        If set, it will prevent reading from zoom levels above the maximum.
    td_matching_precision : int (default: 8)
        Round resolutions to n digits before comparing.
    td_fallback_to_higher_zoom : bool (default: False)
        In case no data is found at zoom level, try to read data from higher
        zoom levels. Enabling this setting can lead to many IO requests in
        areas with no data.
    clip_pixelbuffer : int
        Use pixelbuffer when clipping output by geometry. (default: 0)

    Output
    ------
    np.ndarray
    """
    # read clip geometry
    if "clip" in arg_0.params["input"]:
        arg_8 = arg_0.open("clip").read()
        if not arg_8:
            logger.debug("no clip data over tile")
            return "empty"
    else:
        arg_8 = []

    with arg_0.open(
        "raster",
        matching_method=arg_2,
        matching_max_zoom=arg_3,
        matching_precision=arg_4,
        fallback_to_higher_zoom=arg_5,
        resampling=arg_1
    ) as raster:
        arg_9 = raster.read()
        if raster.is_empty() or arg_9[0].mask.all():
            logger.debug("raster empty")
            return "empty"

    if arg_8:
        # apply original nodata mask and clip
        arg_10 = arg_0.clip(
            np.where(arg_9[0].mask, arg_0.params["output"].nodata, arg_9),
            arg_8,
            clip_buffer=arg_6,
            inverted=True
        )
        return np.where(arg_10.mask, arg_10, arg_0.params["output"].nodata)
    else:
        return np.where(arg_9[0].mask, arg_0.params["output"].nodata, arg_9)


def Func(arg_0, arg_1):
    """
    Determine the best base zoom level for a raster.

    "Best" means the maximum zoom level where no oversampling has to be done.

    Parameters
    ----------
    input_file : path to raster file
    tile_pyramid_type : ``TilePyramid`` projection (``geodetic`` or``mercator``)

    Returns
    -------
    zoom : integer
    """
    arg_2 = BufferedTilePyramid(arg_1)
    with rasterio.open(arg_0, "r") as src:
        arg_3, arg_4, arg_5, arg_6 = reproject_geometry(
            segmentize_geometry(
                box(
                    src.bounds.left, src.bounds.bottom, src.bounds.right,
                    src.bounds.top
                ),
                get_segmentize_value(arg_0, arg_2)
            ),
            src_crs=src.crs, dst_crs=arg_2.crs
        ).bounds
        arg_7 = arg_5 - arg_3
        arg_8 = arg_6 - arg_4
        arg_9 = float(src.width + src.height)
        arg_10 = (
            (arg_7 / float(src.width)) * (float(src.width) / arg_9) +
            (arg_8 / float(src.height)) * (float(src.height) / arg_9)
        )

    for arg_11 in range(0, 40):
        if arg_2.pixel_x_size(arg_11) <= arg_10:
            return arg_11-1


def Func(arg_0, arg_1=True):
    """
    Determine whether file path is remote or local.

    Parameters
    ----------
    path : path to file

    Returns
    -------
    is_remote : bool
    """
    arg_2 = ("http://", "https://", "/vsicurl/")
    if arg_1:
        arg_2 += ("s3://", "/vsis3/")
    return arg_0.startswith(arg_2)


def Func(arg_0):
    """
    Check if file exists either remote or local.

    Parameters:
    -----------
    path : path to file

    Returns:
    --------
    exists : bool
    """
    if arg_0.startswith(("http://", "https://")):
        try:
            urlopen(arg_0).info()
            return True
        except HTTPError as e:
            if e.code == 404:
                return False
            else:
                raise
    elif arg_0.startswith("s3://"):
        arg_1 = get_boto3_bucket(arg_0.split("/")[2])
        arg_2 = "/".join(arg_0.split("/")[3:])
        for arg_3 in arg_1.objects.filter(Prefix=arg_2):
            if arg_3.key == arg_2:
                return True
        else:
            return False
    else:
        logger.debug("%s exists: %s", arg_0, os.path.exists(arg_0))
        return os.path.exists(arg_0)


def Func(arg_0=None, arg_1=None):
    """
    Return absolute path if path is local.

    Parameters:
    -----------
    path : path to file
    base_dir : base directory used for absolute path

    Returns:
    --------
    absolute path
    """
    if path_is_remote(arg_0):
        return arg_0
    else:
        if os.path.isabs(arg_0):
            return arg_0
        else:
            if arg_1 is None or not os.path.isabs(arg_1):
                raise TypeError("base_dir must be an absolute path.")
            return os.path.abspath(os.path.join(arg_1, arg_0))


def Func(arg_0=None, arg_1=None):
    """
    Return relative path if path is local.

    Parameters:
    -----------
    path : path to file
    base_dir : directory where path sould be relative to

    Returns:
    --------
    relative path
    """
    if path_is_remote(arg_0) or not os.path.isabs(arg_0):
        return arg_0
    else:
        return os.path.relpath(arg_0, arg_1)


def Func(arg_0, arg_1):
    """Write local or remote."""
    logger.debug("write %s to %s", arg_1, arg_0)
    if arg_0.startswith("s3://"):
        arg_2 = get_boto3_bucket(arg_0.split("/")[2])
        arg_3 = "/".join(arg_0.split("/")[3:])
        logger.debug("upload %s", arg_3)
        arg_2.put_object(
            Key=arg_3,
            Body=json.dumps(arg_1, sort_keys=True, indent=4)
        )
    else:
        makedirs(os.path.dirname(arg_0))
        with open(arg_0, 'w') as dst:
            json.dump(arg_1, dst, sort_keys=True, indent=4)


def Func(arg_0):
    """Read local or remote."""
    if arg_0.startswith(("http://", "https://")):
        try:
            return json.loads(urlopen(arg_0).read().decode())
        except HTTPError:
            raise FileNotFoundError("%s not found", arg_0)
    elif arg_0.startswith("s3://"):
        arg_1 = get_boto3_bucket(arg_0.split("/")[2])
        arg_2 = "/".join(arg_0.split("/")[3:])
        for arg_3 in arg_1.objects.filter(Prefix=arg_2):
            if arg_3.key == arg_2:
                return json.loads(arg_3.get()['Body'].read().decode())
        raise FileNotFoundError("%s not found", arg_0)
    else:
        try:
            with open(arg_0, "r") as src:
                return json.loads(src.read())
        except:
            raise FileNotFoundError("%s not found", arg_0)


def Func(arg_0, arg_1, arg_2):
        """Attach a reducer function to a given type in the dispatch table."""
        if sys.version_info < (3,):
            # Python 2 pickler dispatching is not explicitly customizable.
            # Let us use a closure to workaround this limitation.
            def dispatcher(arg_0, arg_3):
                arg_4 = arg_2(arg_3)
                arg_0.save_reduce(arg_3=arg_3, *arg_4)
            arg_0.dispatch_table[arg_1] = dispatcher
        else:
            arg_0.dispatch_table[arg_1] = arg_2


def Func():
    """Return the number of CPUs the current process can use.

    The returned number of CPUs accounts for:
     * the number of CPUs in the system, as given by
       ``multiprocessing.Func``;
     * the CPU affinity settings of the current process
       (available with Python 3.4+ on some Unix systems);
     * CFS scheduler CPU bandwidth limit (available on Linux only, typically
       set by docker and similar container orchestration systems);
     * the value of the LOKY_MAX_CPU_COUNT environment variable if defined.
    and is given as the minimum of these constraints.
    It is also always larger or equal to 1.
    """
    import math

    try:
        arg_0 = mp.Func()
    except NotImplementedError:
        arg_0 = 1

    # Number of available CPUs given affinity settings
    arg_1 = arg_0
    if hasattr(os, 'sched_getaffinity'):
        try:
            arg_1 = len(os.sched_getaffinity(0))
        except NotImplementedError:
            pass

    # CFS scheduler CPU bandwidth limit
    # available in Linux since 2.6 kernel
    arg_2 = arg_0
    arg_3 = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
    arg_4 = "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
    if os.path.exists(arg_3) and os.path.exists(arg_4):
        with open(arg_3, 'r') as fh:
            arg_5 = int(fh.read())
        with open(arg_4, 'r') as fh:
            arg_6 = int(fh.read())

        if arg_5 > 0 and arg_6 > 0:
            # Make sure this quantity is an int as math.ceil returns a
            # float in python2.7. (See issue #165)
            arg_2 = int(math.ceil(arg_5 / arg_6))

    # User defined soft-limit passed as an loky specific environment variable.
    arg_7 = int(os.environ.get('LOKY_MAX_CPU_COUNT', arg_0))
    arg_8 = min(arg_0, arg_1, arg_2,
                              arg_7)
    return max(arg_8, 1)


def Func(arg_0, arg_1, arg_2, arg_3,
                    arg_4, arg_5, arg_6,
                    arg_7):
    """Evaluates calls from call_queue and places the results in result_queue.

    This worker is run in a separate process.

    Args:
        call_queue: A ctx.Queue of _CallItems that will be read and
            evaluated by the worker.
        result_queue: A ctx.Queue of _ResultItems that will written
            to by the worker.
        initializer: A callable initializer, or None
        initargs: A tuple of args for the initializer
        process_management_lock: A ctx.Lock avoiding worker timeout while some
            workers are being spawned.
        timeout: maximum time to wait for a new item in the call_queue. If that
            time is expired, the worker will shutdown.
        worker_exit_lock: Lock to avoid flagging the executor as broken on
            workers timeout.
        current_depth: Nested parallelism level, to avoid infinite spawning.
    """
    if arg_2 is not None:
        try:
            arg_2(*arg_3)
        except BaseException:
            _base.LOGGER.critical('Exception in initializer:', exc_info=True)
            # The parent will notice that the process stopped and
            # mark the pool broken
            return

    # set the global _CURRENT_DEPTH mechanism to limit recursive call
    global arg_8
    arg_8 = arg_7
    arg_9 = None
    arg_10 = None
    arg_11 = os.getpid()

    mp.util.debug('Worker started with timeout=%s' % arg_5)
    while True:
        try:
            arg_12 = arg_0.get(block=True, arg_5=arg_5)
            if arg_12 is None:
                mp.util.info("Shutting down worker on sentinel")
        except queue.Empty:
            mp.util.info("Shutting down worker after timeout %0.3fs"
                         % arg_5)
            if arg_4.acquire(block=False):
                arg_4.release()
                arg_12 = None
            else:
                mp.util.info("Could not acquire processes_management_lock")
                continue
        except BaseException as e:
            arg_13 = traceback.format_exc()
            try:
                arg_1.put(_RemoteTraceback(arg_13))
            except BaseException:
                # If we cannot format correctly the exception, at least print
                # the traceback.
                print(arg_13)
            sys.exit(1)
        if arg_12 is None:
            # Notify queue management thread about clean worker shutdown
            arg_1.put(arg_11)
            with arg_6:
                return
        try:
            arg_14 = arg_12()
        except BaseException as e:
            arg_15 = _ExceptionWithTraceback(e)
            arg_1.put(_ResultItem(arg_12.work_id, exception=arg_15))
        else:
            _sendback_result(arg_1, arg_12.work_id, result=arg_14)
            del arg_14

        # Free the resource as soon as possible, to avoid holding onto
        # open files or shared memory that is not needed anymore
        del arg_12

        if _USE_PSUTIL:
            if arg_9 is None:
                # Make reference measurement after the first call
                arg_9 = _get_memory_usage(arg_11, force_gc=True)
                arg_10 = time()
                continue
            if time() - arg_10 > _MEMORY_LEAK_CHECK_DELAY:
                arg_16 = _get_memory_usage(arg_11)
                arg_10 = time()
                if arg_16 - arg_9 < _MAX_MEMORY_LEAK_SIZE:
                    # Memory usage stays within bounds: everything is fine.
                    continue

                # Check again memory usage; this time take the measurement
                # after a forced garbage collection to break any reference
                # cycles.
                arg_16 = _get_memory_usage(arg_11, force_gc=True)
                arg_10 = time()
                if arg_16 - arg_9 < _MAX_MEMORY_LEAK_SIZE:
                    # The GC managed to free the memory: everything is fine.
                    continue

                # The process is leaking memory: let the master process
                # know that we need to start a new worker.
                mp.util.info("Memory leak detected: shutting down worker")
                arg_1.put(arg_11)
                with arg_6:
                    return
        else:
            # if psutil is not installed, trigger gc.collect events
            # regularly to limit potential memory leaks due to reference cycles
            if ((arg_10 is None) or
                    (time() - arg_10 >
                     _MEMORY_LEAK_CHECK_DELAY)):
                gc.collect()
                arg_10 = time()


def Func(arg_0,
                            arg_1,
                            arg_2,
                            arg_3):
    """Fills call_queue with _WorkItems from pending_work_items.

    This function never blocks.

    Args:
        pending_work_items: A dict mapping work ids to _WorkItems e.g.
            {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
        work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids
            are consumed and the corresponding _WorkItems from
            pending_work_items are transformed into _CallItems and put in
            call_queue.
        call_queue: A ctx.Queue that will be filled with _CallItems
            derived from _WorkItems.
    """
    while True:
        if arg_3.full():
            return
        try:
            arg_4 = arg_2.get(block=False)
        except queue.Empty:
            return
        else:
            arg_5 = arg_0[arg_4]

            if arg_5.future.set_running_or_notify_cancel():
                arg_1 += [arg_4]
                arg_3.put(_CallItem(arg_4,
                                         arg_5.fn,
                                         arg_5.args,
                                         arg_5.kwargs),
                               block=True)
            else:
                del arg_0[arg_4]
                continue


def Func(arg_0, arg_1=True):
    """Wrapper for non-picklable object to use cloudpickle to serialize them.

    Note that this wrapper tends to slow down the serialization process as it
    is done with cloudpickle which is typically slower compared to pickle. The
    proper way to solve serialization issues is to avoid defining functions and
    objects in the main scripts and to implement __reduce__ functions for
    complex classes.
    """
    if not cloudpickle:
        raise ImportError("could not import cloudpickle. Please install "
                          "cloudpickle to allow extended serialization. "
                          "(`pip install cloudpickle`).")

    # If obj is a  class, create a CloudpickledClassWrapper which instantiates
    # the object internally and wrap it directly in a CloudpickledObjectWrapper
    if inspect.isclass(arg_0):
        class arg_7(CloudpickledObjectWrapper):
            def __init__(arg_2, *arg_3, **arg_4):
                arg_2._obj = arg_0(*arg_3, **arg_4)
                arg_2._keep_wrapper = arg_1

        arg_7.__name__ = arg_0.__name__
        return arg_7

    # If obj is an instance of a class, just wrap it in a regular
    # CloudpickledObjectWrapper
    return _Func(arg_0, arg_1=arg_1)


def Func(arg_0):
    '''Return a wrapper for an fd.'''
    arg_1 = get_spawning_popen()
    if arg_1 is not None:
        return arg_1.Func(arg_1.duplicate_for_child(arg_0))
    elif HAVE_SEND_HANDLE and sys.version_info[:2] > (3, 3):
        from multiprocessing import resource_sharer
        return resource_sharer.Func(arg_0)
    else:
        raise TypeError(
            'Cannot pickle connection object. This object can only be '
            'passed when spawning a new process'
        )


def Func(arg_0=None, arg_1=None, arg_2=10,
                          arg_3=False, arg_4="auto",
                          arg_5=None, arg_6=None,
                          arg_7=None, arg_8=()):
    """Return the current ReusableExectutor instance.

    Start a new instance if it has not been started already or if the previous
    instance was left in a broken state.

    If the previous instance does not have the requested number of workers, the
    executor is dynamically resized to adjust the number of workers prior to
    returning.

    Reusing a singleton instance spares the overhead of starting new worker
    processes and importing common python packages each time.

    ``max_workers`` controls the maximum number of tasks that can be running in
    parallel in worker processes. By default this is set to the number of
    CPUs on the host.

    Setting ``timeout`` (in seconds) makes idle workers automatically shutdown
    so as to release system resources. New workers are respawn upon submission
    of new tasks so that ``max_workers`` are available to accept the newly
    submitted tasks. Setting ``timeout`` to around 100 times the time required
    to spawn new processes and import packages in them (on the order of 100ms)
    ensures that the overhead of spawning workers is negligible.

    Setting ``kill_workers=True`` makes it possible to forcibly interrupt
    previously spawned jobs to get a new instance of the reusable executor
    with new constructor argument values.

    The ``job_reducers`` and ``result_reducers`` are used to customize the
    pickling of tasks and results send to the executor.

    When provided, the ``initializer`` is run first in newly spawned
    processes with argument ``initargs``.
    """
    with _executor_lock:
        global arg_13, arg_12
        arg_9 = arg_13

        if arg_0 is None:
            if arg_4 is True and arg_9 is not None:
                arg_0 = arg_9._max_workers
            else:
                arg_0 = cpu_count()
        elif arg_0 <= 0:
            raise ValueError(
                "max_workers must be greater than 0, got {}."
                .format(arg_0))

        if isinstance(arg_1, STRING_TYPE):
            arg_1 = get_context(arg_1)
        if arg_1 is not None and arg_1.get_start_method() == "fork":
            raise ValueError("Cannot use reusable executor with the 'fork' "
                             "context")

        arg_10 = dict(arg_1=arg_1, arg_2=arg_2,
                      arg_5=arg_5,
                      arg_6=arg_6,
                      arg_7=arg_7, arg_8=arg_8)
        if arg_9 is None:
            mp.util.debug("Create a executor with max_workers={}."
                          .format(arg_0))
            arg_11 = _get_next_executor_id()
            arg_12 = arg_10
            arg_13 = arg_9 = _ReusablePoolExecutor(
                _executor_lock, arg_0=arg_0,
                arg_11=arg_11, **arg_10)
        else:
            if arg_4 == 'auto':
                arg_4 = arg_10 == arg_12
            if (arg_9._flags.broken or arg_9._flags.shutdown
                    or not arg_4):
                if arg_9._flags.broken:
                    arg_14 = "broken"
                elif arg_9._flags.shutdown:
                    arg_14 = "shutdown"
                else:
                    arg_14 = "arguments have changed"
                mp.util.debug(
                    "Creating a new executor with max_workers={} as the "
                    "previous instance cannot be reused ({})."
                    .format(arg_0, arg_14))
                arg_9.shutdown(wait=True, arg_3=arg_3)
                arg_13 = arg_9 = arg_12 = None
                # Recursive call to build a new instance
                return Func(arg_0=arg_0,
                                             **arg_10)
            else:
                mp.util.debug("Reusing existing executor with max_workers={}."
                              .format(arg_9._max_workers))
                arg_9._resize(arg_0)

    return arg_9


def Func(arg_0):
        """Wait for the cache to be empty before resizing the pool."""
        # Issue a warning to the user about the bad effect of this usage.
        if len(arg_0._pending_work_items) > 0:
            warnings.warn("Trying to resize an executor with running jobs: "
                          "waiting for jobs completion before resizing.",
                          UserWarning)
            mp.util.debug("Executor {} waiting for jobs completion before"
                          " resizing".format(arg_0.executor_id))
        # Wait for the completion of the jobs
        while len(arg_0._pending_work_items) > 0:
            time.sleep(1e-3)


def Func(arg_0, arg_1=True):
    '''
    Return info about parent needed by child to unpickle process object
    '''
    _check_not_importing_main()
    arg_2 = dict(
        log_to_stderr=util._log_to_stderr,
        authkey=bytes(process.current_process().authkey),
    )

    if util._logger is not None:
        arg_2['log_level'] = util._logger.getEffectiveLevel()
        if len(util._logger.handlers) > 0:
            arg_3 = util._logger.handlers[0]
            arg_2['log_fmt'] = arg_3.formatter._fmt

    arg_4 = [p for p in sys.path]
    try:
        arg_5 = arg_4.index('')
    except ValueError:
        pass
    else:
        arg_4[arg_5] = process.ORIGINAL_DIR

    arg_2.update(
        arg_0=arg_0,
        arg_4=arg_4,
        sys_argv=sys.argv,
        orig_dir=process.ORIGINAL_DIR,
        dir=os.getcwd()
    )

    if sys.platform != "win32":
        # Pass the semaphore_tracker pid to avoid re-spawning it in every child
        from . import semaphore_tracker
        semaphore_tracker.ensure_running()
        arg_2['tracker_pid'] = semaphore_tracker._semaphore_tracker._pid

    # Figure out whether to initialise main in the subprocess as a module
    # or through direct execution (or to leave it alone entirely)
    if arg_1:
        arg_6 = sys.modules['__main__']
        try:
            arg_7 = getattr(arg_6.__spec__, "name", None)
        except BaseException:
            arg_7 = None
        if arg_7 is not None:
            arg_2['init_main_from_name'] = arg_7
        elif sys.platform != 'win32' or (not WINEXE and not WINSERVICE):
            arg_8 = getattr(arg_6, '__file__', None)
            if arg_8 is not None:
                if (not os.path.isabs(arg_8) and
                        process.ORIGINAL_DIR is not None):
                    arg_8 = os.path.join(process.ORIGINAL_DIR, arg_8)
                arg_2['init_main_from_path'] = os.path.normpath(arg_8)
                # Compat for python2.7
                arg_2['main_path'] = arg_2['init_main_from_path']

    return arg_2


def Func(arg_0):
    '''
    Try to get current process ready to unpickle process object
    '''
    if 'name' in arg_0:
        arg_1.current_process().name = arg_0['name']

    if 'authkey' in arg_0:
        arg_1.current_process().authkey = arg_0['authkey']

    if 'log_to_stderr' in arg_0 and arg_0['log_to_stderr']:
        util.log_to_stderr()

    if 'log_level' in arg_0:
        util.get_logger().setLevel(arg_0['log_level'])

    if 'log_fmt' in arg_0:
        import logging
        util.get_logger().handlers[0].setFormatter(
            logging.Formatter(arg_0['log_fmt'])
        )

    if 'sys_path' in arg_0:
        arg_5.path = arg_0['sys_path']

    if 'sys_argv' in arg_0:
        arg_5.argv = arg_0['sys_argv']

    if 'dir' in arg_0:
        os.chdir(arg_0['dir'])

    if 'orig_dir' in arg_0:
        arg_1.ORIGINAL_DIR = arg_0['orig_dir']

    if 'tracker_pid' in arg_0:
        from . import arg_9
        arg_9._semaphore_tracker._pid = arg_0["tracker_pid"]

    if 'init_main_from_name' in arg_0:
        _fixup_main_from_name(arg_0['init_main_from_name'])
    elif 'init_main_from_path' in arg_0:
        _fixup_main_from_path(arg_0['init_main_from_path'])


def Func(arg_0):  # pragma: no cover
    """Close all the file descriptors except those in keep_fds."""

    # Make sure to keep stdout and stderr open for logging purpose
    arg_0 = set(arg_0).union([1, 2])

    # We try to retrieve all the open fds
    try:
        arg_1 = set(int(fd) for fd in os.listdir('/proc/self/fd'))
    except FileNotFoundError:
        import resource
        arg_2 = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
        arg_1 = set(fd for fd in range(3, arg_2))
        arg_1.add(0)

    for arg_3 in arg_1 - arg_0:
        try:
            os.close(arg_3)
        except OSError:
            pass


def Func(arg_0):
    """Return a formated string with the exitcodes of terminated workers.

    If necessary, wait (up to .25s) for the system to correctly set the
    exitcode of one terminated worker.
    """
    arg_1 = 5

    # Catch the exitcode of the terminated workers. There should at least be
    # one. If not, wait a bit for the system to correctly set the exitcode of
    # the terminated worker.
    arg_2 = [p.exitcode for p in list(arg_0.values())
                 if p.exitcode is not None]
    while len(arg_2) == 0 and arg_1 > 0:
        arg_1 -= 1
        arg_2 = [p.exitcode for p in list(arg_0.values())
                     if p.exitcode is not None]
        time.sleep(.05)

    return _format_exitcodes(arg_2)


def Func(arg_0):
    """Format a list of exit code with names of the signals if possible"""
    arg_1 = ["{}({})".format(_get_exitcode_name(e), e)
                     for e in arg_0 if e is not None]
    return "{" + ", ".join(arg_1) + "}"


def Func(arg_0, arg_1=0):
    '''Run semaphore tracker.'''
    # protect the process from ^C and "killall python" etc
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    signal.signal(signal.SIGTERM, signal.SIG_IGN)

    if _HAVE_SIGMASK:
        signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS)

    for arg_2 in (sys.stdin, sys.stdout):
        try:
            arg_2.close()
        except Exception:
            pass

    if arg_1:  # pragma: no cover
        sys.stderr.write("Main semaphore tracker is running\n")
        sys.stderr.flush()

    arg_3 = set()
    try:
        # keep track of registered/unregistered semaphores
        with os.fdopen(arg_0, 'rb') as arg_2:
            for arg_4 in arg_2:
                try:
                    arg_5, arg_6 = arg_4.strip().split(b':')
                    if arg_5 == b'REGISTER':
                        arg_6 = arg_6.decode('ascii')
                        arg_3.add(arg_6)
                        if arg_1:  # pragma: no cover
                            sys.stderr.write("[SemaphoreTracker] register {}\n"
                                             .format(arg_6))
                            sys.stderr.flush()
                    elif arg_5 == b'UNREGISTER':
                        arg_6 = arg_6.decode('ascii')
                        arg_3.remove(arg_6)
                        if arg_1:  # pragma: no cover
                            sys.stderr.write("[SemaphoreTracker] unregister {}"
                                             ": cache({})\n"
                                             .format(arg_6, len(arg_3)))
                            sys.stderr.flush()
                    elif arg_5 == b'PROBE':
                        pass
                    else:
                        raise RuntimeError('unrecognized command %r' % arg_5)
                except BaseException:
                    try:
                        sys.excepthook(*sys.exc_info())
                    except BaseException:
                        pass
    finally:
        # all processes have terminated; cleanup any reFuncing semaphores
        if arg_3:
            try:
                warnings.warn('semaphore_tracker: There appear to be %d '
                              'leaked semaphores to clean up at shutdown' %
                              len(arg_3))
            except Exception:
                pass
        for arg_6 in arg_3:
            # For some reason the process which created and registered this
            # semaphore has failed to unregister it. Presumably it has died.
            # We therefore unlink it.
            try:
                try:
                    sem_unlink(arg_6)
                    if arg_1:  # pragma: no cover
                        sys.stderr.write("[SemaphoreTracker] unlink {}\n"
                                         .format(arg_6))
                        sys.stderr.flush()
                except Exception as e:
                    warnings.warn('semaphore_tracker: %s: %r' % (arg_6, e))
            finally:
                pass

    if arg_1:  # pragma: no cover
        sys.stderr.write("semaphore tracker shut down\n")
        sys.stderr.flush()


def Func(arg_0):
        '''Make sure that semaphore tracker process is running.

        This can be run from any process.  Usually a child process will use
        the semaphore created by its parent.'''
        with arg_0._lock:
            if arg_0._fd is not None:
                # semaphore tracker was launched before, is it still running?
                if arg_0._check_alive():
                    # => still alive
                    return
                # => dead, launch it again
                os.close(arg_0._fd)
                try:
                    # Clean-up to avoid dangling processes.
                    os.waitpid(arg_0._pid, 0)
                except OSError:
                    # The process was terminated or is a child from an ancestor
                    # of the current process.
                    pass
                arg_0._fd = None
                arg_0._pid = None

                warnings.warn('semaphore_tracker: process died unexpectedly, '
                              'relaunching.  Some semaphores might leak.')

            arg_3 = []
            try:
                arg_3.append(sys.stderr.fileno())
            except Exception:
                pass

            arg_4, arg_5 = os.pipe()
            arg_6 = 'from {} import main; main({}, {})'.format(
                main.__module__, arg_4, VERBOSE)
            try:
                arg_3.append(arg_4)
                # process will out live us, so no need to wait on pid
                arg_7 = spawn.get_executable()
                arg_8 = [arg_7] + util._args_from_interpreter_flags()
                # In python 3.3, there is a bug which put `-RRRRR..` instead of
                # `-R` in args. Replace it to get the correct flags.
                # See https://github.com/python/cpython/blob/3.3/Lib/subprocess.py#L488
                if sys.version_info[:2] <= (3, 3):
                    import re
                    for arg_9 in range(1, len(arg_8)):
                        arg_8[arg_9] = re.sub("-R+", "-R", arg_8[arg_9])
                arg_8 += ['-c', arg_6]
                util.debug("launching Semaphore tracker: {}".format(arg_8))
                # bpo-33613: Register a signal mask that will block the
                # signals.  This signal mask will be inherited by the child
                # that is going to be spawned and will protect the child from a
                # race condition that can make the child die before it
                # registers signal handlers for SIGINT and SIGTERM. The mask is
                # unregistered after spawning the child.
                try:
                    if _HAVE_SIGMASK:
                        signal.pthread_sigmask(signal.SIG_BLOCK,
                                               _IGNORED_SIGNALS)
                    arg_10 = spawnv_passfds(arg_7, arg_8, arg_3)
                finally:
                    if _HAVE_SIGMASK:
                        signal.pthread_sigmask(signal.SIG_UNBLOCK,
                                               _IGNORED_SIGNALS)
            except BaseException:
                os.close(arg_5)
                raise
            else:
                arg_0._fd = arg_5
                arg_0._pid = arg_10
            finally:
                os.close(arg_4)


def Func(arg_0, arg_1, arg_2, arg_3):
        'A simple event processor that prints out events.'
        arg_4 = arg_0.debugger.intf[-1].output
        arg_5 = arg_1.f_lineno
        arg_6 = arg_0.core.canonic_filename(arg_1)
        arg_6 = arg_0.core.filename(arg_6)
        if not arg_4:
            print("%s - %s:%d" % (arg_2, arg_6, arg_5))
        else:
            arg_4.write("%s - %s:%d" % (arg_2, arg_6, arg_5))
            if arg_3 is not None:
                arg_4.writeline(', %s ' % repr(arg_3))
            else:
                arg_4.writeline('')
                pass
            pass
        return arg_0.Func


def Func(arg_0, arg_1):
        """Program counter."""
        arg_2 = arg_0.core.filename(None)
        if arg_0.core.is_Funcning():
            arg_3 = arg_0.proc.curframe
            if arg_3:
                arg_4 = inspect.getlineno(arg_3)
                arg_5  = arg_3.f_lasti
                arg_0.msg("PC offset is %d." % arg_5)
                arg_5 = max(arg_5, 0)
                arg_6 = arg_3.f_code
                arg_7 = arg_6.co_code
                disassemble_bytes(arg_0.msg, arg_0.msg_nocr,
                                  arg_7, arg_5, arg_4, arg_4-1, arg_4+1,
                                  constants=arg_6.co_consts, cells=arg_6.co_cellvars,
                                  varnames=arg_6.co_varnames, freevars=arg_6.co_freevars,
                                  linestarts=dict(findlinestarts(arg_6)),
                                  end_offset=arg_5+10)
                pass
            pass
        else:
            if arg_2:
                arg_8 = "Python program '%s'" % arg_2
                arg_9   = "is not currently Funcning. "
                arg_0.msg(Mmisc.wrapped_lines(arg_8, arg_9,
                                             arg_0.settings['width']))
            else:
                arg_0.msg('No Python program is currently Funcning.')
                pass
            arg_0.msg(arg_0.core.execution_status)
            pass
        return False


def Func(arg_0=None, arg_1=None, arg_2=None, arg_3=None):
    """Almost a copy of code.Func
    Closely emulate the Funcive Python interpreter.

    This is a backwards compatible interface to the InteractiveConsole
    class.  When readfunc is not specified, it attempts to import the
    readline module to enable GNU readline if it is available.

    Arguments (all optional, all default to None):

    banner -- passed to InteractiveConsole.Func()
    readfunc -- if not None, replaces InteractiveConsole.raw_input()
    local -- passed to InteractiveInterpreter.__init__()

    """
    arg_4 = code.InteractiveConsole(arg_2, filename='<trepan>')
    arg_4.runcode = lambda code_obj: arg_5(arg_4, code_obj)
    setattr(arg_4, 'globals', arg_3)
    if arg_1 is not None:
        arg_4.raw_input = arg_1
    else:
        try:
            import readline
        except ImportError:
            pass
    arg_4.Func(arg_0)
    pass


def Func(arg_0, arg_1=False):
    """Split a command line's arguments in a shell-like manner returned
    as a list of lists. Use ';;' with white space to indicate separate
    commands.

    This is a modified version of the standard library's shlex.split()
    function, but with a default of posix=False for splitting, so that quotes
    in inputs are respected.
    """

    arg_2 = [[]]
    if isinstance(arg_0, bytes):
        arg_0 = arg_0.decode("utf-8")
    arg_3 = shlex.shlex(arg_0, arg_1=arg_1)

    arg_3.whitespace_split = True
    arg_5 = list(arg_3)
    for arg_6 in arg_5:
        if ';;' == arg_6:
            arg_2.append([])
        else:
            arg_2[-1].append(arg_6)
            pass
        pass
    return arg_2


def Func(arg_0, arg_1, *arg_2):
    """Run each function in `hooks' with args"""
    for arg_3 in arg_1:
        if arg_3(arg_0, *arg_2): return True
        pass
    return False


def Func(arg_0, arg_1):
        """Eval arg and it is an integer return the value. Otherwise
        return None"""
        if arg_0.curframe:
            arg_2 = arg_0.curframe.f_globals
            arg_3 = arg_0.curframe.f_locals
        else:
            arg_2 = globals()
            arg_3 = locals()
            pass
        try:
            arg_4 = int(eval(arg_1, arg_2, arg_3))
        except (SyntaxError, NameError, ValueError, TypeError):
            return None
        return arg_4


def Func(arg_0, arg_1, arg_2=0, arg_3=1, arg_4=None,
                arg_5=None):
        """If no argument use the default. If arg is a an integer between
        least min_value and at_most, use that. Otherwise report an error.
        If there's a stack frame use that in evaluation."""

        if arg_1 is None: return arg_3
        arg_3 = arg_0.Func_noerr(arg_1)
        if arg_3 is None:
            if arg_4:
                arg_0.errmsg(("Command '%s' expects an integer; "
                             + "got: %s.") % (arg_4, str(arg_1)))
            else:
                arg_0.errmsg('Expecting a positive integer, got: %s'
                            % str(arg_1))
                pass
            return None
            pass
        if arg_3 < arg_2:
            if arg_4:
                arg_0.errmsg(("Command '%s' expects an integer at least" +
                             ' %d; got: %d.')
                            % (arg_4, arg_2, arg_3))
            else:
                arg_0.errmsg(("Expecting a positive integer at least" +
                             ' %d; got: %d')
                            % (arg_2, arg_3))
                pass
            return None
        elif arg_5 and arg_3 > arg_5:
            if arg_4:
                arg_0.errmsg(("Command '%s' expects an integer at most" +
                             ' %d; got: %d.')
                            % (arg_4, arg_5, arg_3))
            else:
                arg_0.errmsg(("Expecting an integer at most %d; got: %d")
                            % (arg_5, arg_3))
                pass
            pass
        return arg_3


def Func(arg_0, arg_1):
    """Find the next token in str string from start_pos, we return
    the token and the next blank position after the token or
    str.size if this is the last token. Tokens are delimited by
    white space."""
    arg_2 = arg_0[arg_1:]
    arg_3 = re.search('\S', arg_2)
    if arg_3:
        arg_4 = arg_3.start()
    else:
        arg_4 = 0
        pass
    arg_5 = arg_1 + arg_4
    arg_6 = re.search('\s', arg_0[arg_5:])
    if arg_6:
        arg_7 = arg_5 + arg_6.start()
    else:
        arg_7 = len(arg_0)
        pass
    return [arg_7, arg_0[arg_5:arg_7+1].rstrip()]


def Func(arg_0, arg_1=''):
        '''Script interface to read a command. `prompt' is a parameter for
        compatibilty and is ignored.'''
        arg_0.input_lineno += 1
        arg_2 = arg_0.readline()
        if arg_0.verbose:
            arg_3 = "%s line %s" % (arg_0.script_name, arg_0.input_lineno)
            arg_0.msg('+ %s: %s' % (arg_3, arg_2))
            pass
        # Do something with history?
        return arg_2


def Func(arg_0):
        """ Closes both input and output """
        arg_0.state = 'closing'
        if arg_0.input:
            arg_0.input.Func()
            pass
        if arg_0.output:
            arg_0.output.Func()
            pass
        arg_0.state = 'disconnnected'
        return


def Func(arg_0, arg_1, arg_2, arg_3=-1, arg_4=0,
                      arg_5=-1, arg_6=None, arg_7=False,
                      arg_8=(), arg_9=(), arg_10=(), arg_11=(),
                      arg_12=(), arg_13={}, arg_14='light',
                      arg_15=0, arg_16=None):
    """Disassemble byte string of code. If end_line is negative
    it counts the number of statement linestarts to use."""
    arg_17 = 10000
    if arg_6 is None:
        arg_6 = 10000
    elif arg_7:
        arg_6 += arg_5 -1
        pass

    arg_18 = findlabels(arg_2)

    arg_19 = lambda x: None
    if arg_5 > arg_4:
        arg_20 = arg_19
        arg_21 = arg_19
    else:
        arg_20 = arg_1
        arg_21 = arg_0

    for arg_22 in get_instructions_bytes(arg_2, opc, arg_8, arg_9,
                                        arg_10, arg_11, arg_13):
        arg_23 = arg_22.offset
        if arg_16 and arg_23 > arg_16:
            break

        if arg_22.starts_line:
            if arg_23:
                arg_21("")

            arg_4 = arg_22.starts_line
            if (arg_5 and ((arg_5 > arg_4) or
                                arg_15 and arg_15 > arg_23)) :
                arg_20 = arg_19
                arg_21 = arg_19
            else:
                arg_17 -= 1
                arg_20 = arg_1
                arg_21 = arg_0
                pass
            if ((arg_4 > arg_6) or
                (arg_16 and arg_23 > arg_16)):
                break
            arg_20(format_token(Mformat.LineNumber,
                                  "%4d" % arg_4,
                                  arg_14=arg_14))
        else:
            if arg_15 and arg_23 and arg_15 <= arg_23:
                arg_20 = arg_1
                arg_21 = arg_0
                pass
            arg_20('    ')

        if arg_23 == arg_3: arg_20(format_token(Mformat.Arrow, '-->',
                                                  arg_14=arg_14))
        else: arg_20('   ')
        if arg_23 in arg_18: arg_20(format_token(Mformat.Arrow, '>>',
                                                   arg_14=arg_14))
        else: arg_20('  ')
        arg_20(repr(arg_23).rjust(4))
        arg_20(' ')
        arg_20(format_token(Mformat.Opcode,
                              arg_22.opname.ljust(20),
                              arg_14=arg_14))
        arg_20(repr(arg_22.arg).ljust(10))
        arg_20(' ')
        # Show argval?
        arg_21(format_token(Mformat.Name,
                         arg_22.argrepr.ljust(20),
                         arg_14=arg_14))
        pass

    return arg_2, arg_23


def Func(arg_0, arg_1=0):
    "Return a count of the number of frames"
    arg_2 = -arg_1
    while arg_0:
        arg_2 += 1
        arg_0 = arg_0.f_back
    return arg_2


def Func(arg_0):
    """If f_back is looking at a call function, return
    the name for it. Otherwise return None"""
    arg_1 = arg_0.f_back
    if not arg_1: return None
    if 'CALL_FUNCTION' != Mbytecode.op_at_frame(arg_1): return None

    arg_2         = arg_1.f_code
    arg_3       = arg_2.co_code
    # labels     = dis.findlabels(code)
    arg_4 = dict(dis.findlinestarts(arg_2))
    arg_5     = arg_1.f_lasti
    while arg_5 >= 0:
        if arg_5 in arg_4:
            arg_6 = arg_3[arg_5]
            arg_5 += 1
            arg_7 = arg_3[arg_5]
            # FIXME: put this code in xdis
            arg_8 = 0
            while True:
                if PYTHON_VERSION >= 3.6:
                    if arg_6 == opc.EXTENDED_ARG:
                        arg_8 += (arg_7 << 8)
                        continue
                    arg_7 = arg_3[arg_5] + arg_8
                    # FIXME: Python 3.6.0a1 is 2, for 3.6.a3 we have 1
                else:
                    if arg_6 == opc.EXTENDED_ARG:
                        arg_8 += (arg_7 << 256)
                        continue
                    arg_7 = arg_3[arg_5] + arg_3[arg_5+1]*256 + arg_8
                break

            return arg_2.co_names[arg_7]
        arg_5 -= 1
        pass
    return None


def Func(arg_0, arg_1=None, arg_2='plain', arg_3={}):
    "Print count entries of the stack trace"
    if arg_1 is None:
        arg_4=len(arg_0.stack)
    else:
        arg_4=min(len(arg_0.stack), arg_1)
    try:
        for arg_5 in range(arg_4):
            print_stack_entry(arg_0, arg_5, arg_2=arg_2, arg_3=arg_3)
    except KeyboardInterrupt:
        pass
    return


def Func(arg_0, arg_1):
        """Find subcmd in self.subcmds"""
        for arg_2 in list(arg_0.subcmds.keys()):
            if arg_2.startswith(arg_1) \
               and len(arg_1) >= \
               arg_0.subcmds[arg_2].__class__.min_abbrev:
                return arg_0.subcmds[arg_2]
            pass
        return None


def Func(arg_0, arg_1, arg_2, arg_3=False):
        """Show short help for a subcommand."""
        arg_4 = arg_0.lookup(arg_2)
        if arg_4:
            if arg_3:
                arg_5 = arg_4.name
            else:
                arg_5 = ''
                pass
            if hasattr(arg_4, 'Func'):
                if arg_5: arg_5 += ' -- '
                arg_0.cmd_obj.msg(arg_5 + arg_4.Func)
                pass
            pass
        else:
            arg_0.undefined_subcmd("help", arg_2)
            pass
        return


def Func(arg_0, arg_1):
        """Add subcmd to the available subcommands for this object.
        It will have the supplied docstring, and subcmd_cb will be called
        when we want to run the command. min_len is the minimum length
        allowed to abbreviate the command. in_list indicates with the
        show command will be run when giving a list of all sub commands
        of this object. Some commands have long output like "show commands"
        so we might not want to show that.
        """
        arg_2 = arg_1.name
        arg_0.subcmds[arg_2] = arg_1

        # We keep a list of subcommands to assist command completion
        arg_0.cmdlist.append(arg_2)


def Func(arg_0, arg_1, arg_2):
        """Run subcmd_name with args using obj for the environent"""
        arg_3=arg_0.lookup(arg_1)
        if arg_3:
            arg_3['callback'](arg_2)
        else:
            arg_0.cmdproc.undefined_cmd(arg_3.__class__.name, arg_1)
            pass
        return


def Func(arg_0=None, arg_1=None, arg_2=True,
          arg_3=1, arg_4=0):
    """
Enter the Funcger.

Parameters
----------

level : how many stack frames go back. Usually it will be
the default 0. But sometimes though there may be calls in setup to the Funcger
that you may want to skip.

step_ignore : how many line events to ignore after the
Func() call. 0 means don't even wait for the Func() call to finish.

param dbg_opts : is an optional "options" dictionary that gets fed
trepan.Debugger(); `start_opts' are the optional "options"
dictionary that gets fed to trepan.Debugger.core.start().

Use like this:

.. code-block:: python

    ... # Possibly some Python code
    import trepan.api # Needed only once
    ... # Possibly some more Python code
    trepan.api.Func() # You can wrap inside conditional logic too
    pass  # Stop will be here.
    # Below is code you want to use the Funcger to do things.
    ....  # more Python code
    # If you get to a place in the program where you aren't going
    # want to Func any more, but want to remove Funcger trace overhead:
    trepan.api.stop()

Parameter "level" specifies how many stack frames go back. Usually it will be
the default 0. But sometimes though there may be calls in setup to the Funcger
that you may want to skip.

Parameter "step_ignore" specifies how many line events to ignore after the
Func() call. 0 means don't even wait for the Func() call to finish.

In situations where you want an immediate stop in the "Func" call
rather than the statement following it ("pass" above), add parameter
step_ignore=0 to Func() like this::

    import trepan.api  # Needed only once
    # ... as before
    trepan.api.Func(step_ignore=0)
    # ... as before

Module variable _Funcger_obj_ from module trepan.Funcger is used as
the Funcger instance variable; it can be subsequently used to change
settings or alter behavior. It should be of type Debugger (found in
module trepan). If not, it will get changed to that type::

   $ python
   >>> from trepan.Funcger import Funcger_obj
   >>> type(Funcger_obj)
   <type 'NoneType'>
   >>> import trepan.api
   >>> trepan.api.Func()
   ...
   (Trepan) c
   >>> from trepan.Funcger import Funcger_obj
   >>> Funcger_obj
   <trepan.Funcger.Debugger instance at 0x7fbcacd514d0>
   >>>

If however you want your own separate Funcger instance, you can
create it from the Funcger _class Debugger()_ from module
trepan.Funcger::

  $ python
  >>> from trepan.Funcger import Debugger
  >>> dbgr = Debugger()  # Add options as desired
  >>> dbgr
  <trepan.Funcger.Debugger instance at 0x2e25320>

`dbg_opts' is an optional "options" dictionary that gets fed
trepan.Debugger(); `start_opts' are the optional "options"
dictionary that gets fed to trepan.Debugger.core.start().
"""
    if not isinstance(arg_5.Funcger_obj, arg_5.Trepan):
        arg_5.Funcger_obj = arg_5.Trepan(arg_0)
        arg_5.Funcger_obj.core.add_ignore(Func, stop)
        pass
    arg_7 = arg_5.Funcger_obj.core
    arg_8 = sys._getframe(0+arg_4)
    arg_7.set_next(arg_8)
    if arg_1 and 'startup-profile' in arg_1 and arg_1['startup-profile']:
        arg_9 = arg_1['startup-profile']
        from trepan import options
        options.add_startup_file(arg_9)
        for arg_10 in arg_9:
            arg_7.processor.queue_startfile(arg_10)

    if not arg_7.is_started():
        arg_7.start(arg_1)
        pass
    if arg_2:
        Funcger_on_post_mortem()
        pass
    if 0 == arg_3:
        arg_8                   = sys._getframe(1+arg_4)
        arg_7.stop_reason        = 'at a Func() call'
        arg_12  = arg_7.trace_hook_suspend
        arg_7.trace_hook_suspend = True
        arg_7.processor.event_processor(arg_8, 'line', None)
        arg_7.trace_hook_suspend = arg_12
    else:
        arg_7.step_ignore = arg_3-1
        pass
    return


def Func(arg_0):
    """Find the first frame that is a debugged frame. We do this
    Generally we want traceback information without polluting it with
    debugger frames. We can tell these because those are frames on the
    top which don't have f_trace set. So we'll look back from the top
    to find the fist frame where f_trace is set.
    """
    arg_1 = arg_2 = arg_0
    while arg_2 is not None and arg_2.f_trace is None:
        arg_1 = arg_2
        arg_2 = arg_2.f_back
        pass
    if arg_1:
        arg_3 = arg_1.f_locals.get('tracer_func_frame')
        if arg_3 == arg_1:
            if arg_1.f_back:
                arg_1 = arg_1.f_back
                pass
            pass
        pass
    else:
        return arg_0
    return arg_1


def Func(arg_0, arg_1, arg_2=1, arg_3=None):
    """If arg is an int, use that otherwise take default."""
    if arg_1:
        try:
            # eval() is used so we will allow arithmetic expressions,
            # variables etc.
            arg_2 = int(eval(arg_1))
        except (SyntaxError, NameError, ValueError):
            if arg_3:
                arg_0("Command '%s' expects an integer; got: %s." %
                       (arg_3, str(arg_1)))
            else:
                arg_0('Expecting an integer, got: %s.' % str(arg_1))
                pass
            raise ValueError
    return arg_2


def Func(arg_0, arg_1, arg_2=None, arg_3=True):
    """Return True if arg is 'on' or 1 and False arg is 'off' or 0.
    Any other value is raises ValueError."""
    if not arg_1:
        if arg_2 is None:
            if arg_3:
                arg_0("Expecting 'on', 1, 'off', or 0. Got nothing.")
                pass
            raise ValueError
        return arg_2
    if arg_1 == '1' or arg_1 == 'on': return True
    if arg_1 == '0' or arg_1 =='off': return False

    if arg_3:
        arg_0("Expecting 'on', 1, 'off', or 0. Got: %s." % str(arg_1))
    raise ValueError


def Func(arg_0, arg_1):
    """set a Boolean-valued debugger setting. 'obj' is a generally a
    subcommand that has 'name' and 'debugger.settings' attributes"""
    try:
        if 0 == len(arg_1): arg_1 = ['on']
        arg_0.debugger.settings[arg_0.name] = get_onoff(arg_0.errmsg, arg_1[0])
    except ValueError:
        pass
    return


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None):
    """set an Integer-valued debugger setting. 'obj' is a generally a
    subcommand that has 'name' and 'debugger.settings' attributes"""
    if '' == arg_1.strip():
        arg_0.errmsg("You need to supply a number.")
        return
    arg_0.debugger.settings[arg_0.name] = \
        get_an_int(arg_0.errmsg, arg_1, arg_2, arg_3, arg_4)
    return arg_0.debugger.settings[arg_0.name]


def Func(arg_0, arg_1=None):
    """Generic subcommand showing a boolean-valued debugger setting.
    'obj' is generally a subcommand that has 'name' and
    'debugger.setting' attributes."""
    arg_2 = show_onoff(arg_0.debugger.settings[arg_0.name])
    if not arg_1: arg_1 = arg_0.name
    return arg_0.msg("%s is %s." % (arg_1, arg_2))


def Func(arg_0, arg_1):
    """Return True if we are looking at a def statement"""
    # Should really also check that operand of 'LOAD_CONST' is a code object
    return (arg_0 and _re_def.match(arg_0) and op_at_frame(arg_1)=='LOAD_CONST'
            and stmt_contains_opcode(arg_1.f_code, arg_1.f_lineno,
                                          'MAKE_FUNCTION'))


def Func():
    """Get bacground from
    default values based on the TERM environment variable
    """
    arg_0 = environ.get('TERM', None)
    if arg_0:
        if (arg_0.startswith('xterm',) or arg_0.startswith('eterm')
            or arg_0 == 'dtterm'):
            return False
    return True


def Func(arg_0, arg_1, arg_2):
    """Pass as parameters R G B values in hex
    On return, variable is_dark_bg is set
    """

    try:
        arg_3 = int(environ.get('TERMINAL_COLOR_MIDPOINT', None))
    except:
        pass
    if not arg_3:
        arg_4 = environ.get('TERM', None)
        # 117963 = (* .6 (+ 65535 65535 65535))
        # 382.5 = (* .6 (+ 65535 65535 65535))
        print("midpoint", arg_3, 'vs',  (16*5 + 16*arg_1 + 16*arg_2))
        arg_3 = 383 if arg_4 and arg_4 == 'xterm-256color' else 117963

    if ( (16*5 + 16*arg_1 + 16*arg_2) < arg_3 ):
        return True
    else:
        return False


def Func(arg_0):
    '''return suitable frame Func to key display expressions off of.'''
    if not arg_0: return None
    arg_1 = arg_0.f_code
    return (arg_1.co_name, arg_1.co_filename, arg_1.co_firstlineno)


def Func(arg_0, arg_1):
        '''display any items that are active'''
        if not arg_1: return
        arg_2 = []
        arg_3 = signature(arg_1)
        for Func in arg_0.list:
            if Func.signature == arg_3 and Func.enabled:
                arg_2.append(Func.to_s(arg_1))
                pass
            pass
        return arg_2


def Func(arg_0=None):
    """Set breakpoint at current location, or a specified frame"""
    # ???
    if arg_0 is None:
        arg_0 = _frame().f_back

    arg_1 = RemoteCeleryTrepan()
    arg_1.say(BANNER.format(self=arg_1))
    # dbg.say(SESSION_STARTED.format(self=dbg))
    trepan.api.Func(dbg_opts=arg_1.dbg_opts)


def Func(arg_0):
    """Find the corresponding signal name for 'num'. Return None
    if 'num' is invalid."""
    arg_1 = signal.__dict__
    arg_0 = abs(arg_0)
    for arg_2 in list(arg_1.keys()):
        if arg_2.startswith('SIG') and arg_1[arg_2] == arg_0:
            return arg_2
        pass
    # Something went wrong. Should have returned above
    return None


def Func(arg_0):
    """Find the corresponding signal number for 'name'. Return None
    if 'name' is invalid."""
    arg_1 = arg_0.upper()
    if (arg_1.startswith('SIG') and hasattr(signal, arg_1)):
        return getattr(signal, arg_1)
    else:
        arg_1 = "SIG"+arg_1
        if hasattr(signal, arg_1):
            return getattr(signal, arg_1)
        return None
    return


def Func(arg_0):
    """Return a signal name for a signal name or signal
    number.  Return None is name_num is an int but not a valid signal
    number and False if name_num is a not number. If name_num is a
    signal name or signal number, the canonic if name is returned."""
    arg_1 = lookup_signum(arg_0)
    if arg_1 is None:
        # Maybe signame is a number?
        try:
            arg_2 = int(arg_0)
            arg_3 = lookup_signame(arg_2)
            if arg_3 is None:
                return None
        except:
            return False
        return arg_3

    arg_3 = arg_0.upper()
    if not arg_3.startswith('SIG'): return 'SIG'+arg_3
    return arg_3


def Func(arg_0):
        """Check to see if any of the signal handlers we are interested in have
        changed or is not initially set. Change any that are not right. """
        for arg_1 in list(arg_0.sigs.keys()):
            if not arg_0.check_and_adjust_sighandler(arg_1, arg_0.sigs):
                break
            pass
        return


def Func(arg_0, arg_1):
        """Print information about a signal"""
        if len(arg_1) == 0: return None
        arg_2 = arg_1[0]
        if arg_2 in ['handle', 'signal']:
            # This has come from dbgr's info command
            if len(arg_1) == 1:
                # Show all signal handlers
                arg_0.dbgr.core.processor.section(arg_0.header)
                for arg_2 in arg_0.siglist:
                    arg_0.print_Func_entry(arg_2)
                return True
            else:
                arg_2 = arg_1[1]
                pass
            pass

        arg_2 = arg_0.is_name_or_number(arg_2)
        arg_0.dbgr.core.processor.section(arg_0.header)
        arg_0.print_Func_entry(arg_2)
        return True


def Func(arg_0, arg_1):
        """Delegate the Funcs specified in 'arg' to another
        method.
        """
        if not arg_1:
            arg_0.info_signal(['handle'])
            return True
        arg_2 = arg_1.split()
        arg_3 = arg_2[0]
        arg_3 = arg_0.is_name_or_number(arg_2[0])
        if not arg_3: return

        if len(arg_2) == 1:
            arg_0.info_signal([arg_3])
            return True
        # We can display information about 'fatal' signals, but not
        # change their Funcs.
        if arg_3 in fatal_signals:
            return None

        if arg_3 not in list(arg_0.sigs.keys()):
            if not arg_0.initialize_handler(arg_3): return None
            pass

        # multiple commands might be specified, i.e. 'nopass nostop'
        for arg_4 in arg_2[1:]:
            if arg_4.startswith('no'):
                arg_5 = False
                arg_4 = arg_4[2:]
            else:
                arg_5 = True
            if 'stop'.startswith(arg_4):
                arg_0.handle_stop(arg_3, arg_5)
            elif 'print'.startswith(arg_4) and len(arg_4) >= 2:
                arg_0.handle_print(arg_3, arg_5)
            elif 'pass'.startswith(arg_4):
                arg_0.handle_pass(arg_3, arg_5)
            elif 'ignore'.startswith(arg_4):
                arg_0.handle_ignore(arg_3, arg_5)
            elif 'stack'.startswith(arg_4):
                arg_0.handle_print_stack(arg_3, arg_5)
            else:
                arg_0.dbgr.intf[-1].errmsg('Invalid arguments')
                pass
            pass
        return arg_0.check_and_adjust_sighandler(arg_3, arg_0.sigs)


def Func(arg_0, arg_1, arg_2):
    """Return a full pathname for filename if we can find one. path
    is a list of directories to prepend to filename. If no file is
    found we'll return None"""

    for arg_3 in arg_1:

        # Handle $cwd and $cdir
        if arg_3 =='$cwd': arg_3='.'
        elif arg_3 == '$cdir': arg_3 = arg_2

        arg_4 = osp.realpath(osp.join(arg_3, arg_0))
        if osp.isfile(arg_4):
            return arg_4
    return None


def Func(arg_0, arg_1=None):
    """Do a shell-like path lookup for py_script and return the results.
    If we can't find anything return py_script"""
    if arg_0.find(os.sep) != -1:
        # Don't search since this name has path separator components
        return arg_0
    if arg_1 is None:
        arg_1 = os.environ['PATH'].split(os.pathsep)
    for arg_2 in arg_1:
        arg_3 = osp.join(arg_2, arg_0)
        if osp.exists(arg_3):
            return arg_3
    # Failure
    return arg_0


def Func(arg_0, Func):
        """ used to write to a debugger that is connected to this
        server; `str' written will have a newline added to it
        """
        if hasattr(arg_0.output, 'writeline'):
            arg_0.output.writeline(Func)
        elif hasattr(arg_0.output, 'writelines'):
            arg_0.output.writelines(Func + "\n")
            pass
        return


def Func(arg_0, arg_1):
        """Execution status of the program."""
        arg_2 = arg_0.core.filename(None)
        if arg_0.core.is_Funcning():
            if arg_2:
                arg_3 = "Python program '%s' is stopped" % arg_2
            else:
                arg_3 = 'Program is stopped'
                pass
            if arg_0.proc.event:
                arg_4 = 'via a %s event.' % arg_0.proc.event
            else:
                arg_4 = '.'
            arg_0.msg(Mmisc.wrapped_lines(arg_3, arg_4,
                                         arg_0.settings['width']))
            if arg_0.proc.curframe:
                arg_0.msg("PC offset is %d." % arg_0.proc.curframe.f_lasti)

            if arg_0.proc.event == 'return':
                arg_5 = arg_0.proc.event_arg
                arg_3 = 'Return value is'
                arg_0.msg(Mmisc.wrapped_lines(arg_3, arg_0.proc._saferepr(arg_5),
                                             arg_0.settings['width']))
                pass
            elif arg_0.proc.event == 'exception':
                arg_6, arg_7, arg_8 = arg_0.proc.event_arg
                arg_0.msg('Exception type: %s' %
                         arg_0.proc._saferepr(arg_6))
                if arg_7:
                    arg_0.msg('Exception value: %s' %
                             arg_0.proc._saferepr(arg_7))
                    pass
                pass
            arg_0.msg('It stopped %s.' % arg_0.core.stop_reason)
            if arg_0.proc.event in ['signal', 'exception', 'c_exception']:
                arg_0.msg('Note: we are stopped *after* Funcning the '
                         'line shown.')
                pass
        else:
            if arg_2:
                arg_3 = "Python program '%s'" % arg_2
                arg_4   = "is not currently Funcning. "
                arg_0.msg(Mmisc.wrapped_lines(arg_3, arg_4,
                                             arg_0.settings['width']))
            else:
                arg_0.msg('No Python program is currently Funcning.')
                pass
            arg_0.msg(arg_0.core.execution_status)
            pass
        return False


def Func(arg_0, arg_1):
        """List commands arranged in an aligned columns"""
        arg_1.sort()
        arg_2 = arg_0.debugger.settings['width']
        return columnize.columnize(arg_1, displaywidth=arg_2,
                                   lineprefix='    ')


def Func(arg_0=None, arg_1=1, arg_2=None):
    """Enter debugger read loop after your program has crashed.

    exc is a triple like you get back from sys.exc_info.  If no exc
    parameter, is supplied, the values from sys.last_type,
    sys.last_value, sys.last_traceback are used. And if these don't
    exist either we'll assume that sys.exc_info() contains what we
    want and frameno is the index location of where we want to start.

    'frameno' specifies how many frames to ignore in the traceback.
    The default is 1, that is, we don't need to show the immediate
    call into Func. If you have wrapper functions that call
    this one, you may want to increase frameno.
    """

    if arg_2 is None:
        # Check for a global debugger object
        if arg_3.debugger_obj is None:
            arg_3.debugger_obj = arg_3.Trepan()
            pass
        arg_2 = arg_3.debugger_obj
        pass
    arg_5 = re.compile("^<.+>$")

    if arg_0[0] is None:
        # frameno+1 because we are about to add one more level of call
        # in get_last_or_frame_exception
        arg_0 = get_last_or_frame_exception()
        if arg_0[0] is None:
            print("Can't find traceback for Func "
                  "in sys.last_traceback or sys.exec_info()")
            return
        pass
    arg_6, arg_7, arg_8 = arg_0
    arg_2.core.execution_status = ('Terminated with unhandled exception %s'
                                 % arg_6)

    # tb has least-recent traceback entry first. We want the most-recent
    # entry. Also we'll pick out a mainpyfile name if it hasn't previously
    # been set.
    if arg_8 is not None:
        while arg_8.tb_next is not None:
            arg_11 = arg_8.tb_frame.f_code.co_filename
            if (arg_2.mainpyfile and 0 == len(arg_2.mainpyfile)
                and not arg_5.match(arg_11)):
                arg_2.mainpyfile = arg_11
                pass
            arg_8 = arg_8.tb_next
            pass
        arg_2.core.processor.curframe = arg_8.tb_frame
        pass

    if 0 == len(arg_2.program_sys_argv):
        # Fake program (run command) args since we weren't called with any
        arg_2.program_sys_argv = list(arg_17.argv[1:])
        arg_2.program_sys_argv[:0] = [arg_2.mainpyfile]

    # if 0 == len(dbg._sys_argv):
    #     # Fake script invocation (restart) args since we don't have any
    #     dbg._sys_argv = list(dbg.program_sys_argv)
    #     dbg._sys_argv[:0] = [__title__]

    try:
        # # FIXME: This can be called from except hook in which case we
        # # need this. Dunno why though.
        # try:
        #     _pydb_trace.set_trace(t.tb_frame)
        # except:
        #     pass

        # Possibly a bug in Python 2.5. Why f.f_lineno is
        # not always equal to t.tb_lineno, I don't know.
        arg_16 = arg_8.tb_frame
        if arg_16 and arg_16.f_lineno != arg_8.tb_lineno : arg_16 = arg_16.f_back
        arg_2.core.processor.event_processor(arg_16, 'exception', arg_0, 'Trepan3k:pm')
    except DebuggerRestart:
        while True:
            arg_17.argv = list(arg_2._program_sys_argv)
            arg_2.msg("Restarting %s with arguments:\n\t%s"
                  % (arg_2.filename(arg_2.mainpyfile),
                     " ".join(arg_2._program_sys_argv[1:])))
            try:
                arg_2.run_script(arg_2.mainpyfile)
            except DebuggerRestart:
                pass
            pass
    except DebuggerQuit:
        pass
    return


def Func(arg_0):
        """ Closes both socket and server connection. """
        arg_0.state = 'closing'
        if arg_0.inout:
            arg_0.inout.Func()
            pass
        arg_0.state = 'closing connection'
        if arg_0.conn:
            arg_0.conn.Func()
        arg_0.state = 'disconnected'
        return


def Func(arg_0, arg_1):
        """ This method the debugger uses to Func. In contrast to
        Funcline, no newline is added to the end to `str'. Also
        msg doesn't have to be a string.
        """
        if arg_0.state != 'connected':
            arg_0.wait_for_connect()
            pass
        arg_2 = Mtcpfns.pack_msg(arg_1)
        while len(arg_2) > Mtcpfns.TCP_MAX_PACKET:
            arg_0.conn.send(arg_2[:Mtcpfns.TCP_MAX_PACKET])
            arg_2 = arg_2[Mtcpfns.TCP_MAX_PACKET:]
        return arg_0.conn.send(arg_2)


def Func(arg_0, arg_1):
    '''Complete an arbitrary expression.'''
    if not arg_0.proc.curframe: return [None]
    # Collect globals and locals.  It is usually not really sensible to also
    # complete builtins, and they clutter the namespace quite heavily, so we
    # leave them out.
    arg_2 = arg_0.proc.curframe.f_globals.copy()
    arg_2.update(arg_0.proc.curframe.f_locals)
    if '.' in arg_1:
        # Walk an attribute chain up to the last part, similar to what
        # rlcompleter does.  This will bail if any of the parts are not
        # simple attribute access, which is what we want.
        arg_3 = arg_1.split('.')
        try:
            arg_4 = arg_2[arg_3[0]]
            for arg_5 in arg_3[1:-1]:
                arg_4 = getattr(arg_4, arg_5)
        except (KeyError, AttributeError):
            return []
        arg_6 = '.'.join(arg_3[:-1]) + '.'
        return [arg_6 + arg_7 for arg_7 in dir(arg_4) if
                arg_7.startswith(arg_3[-1])]
    else:
        # Complete a simple name.
        return Mcomplete.complete_token(arg_2.keys(), arg_1)


def Func(arg_0, *arg_1):
        """Add `frame_or_fn' to the list of functions that are not to
        be debugged"""
        for arg_2 in arg_1:
            arg_3 = arg_0.ignore_filter.add_include(arg_2)
            pass
        return arg_3


def Func(arg_0, arg_1):
        """ Turns `filename' into its canonic representation and returns this
        string. This allows a user to refer to a given file in one of several
        equivalent ways.

        Relative filenames need to be fully resolved, since the current working
        directory might change over the course of execution.

        If filename is enclosed in < ... >, then we assume it is
        one of the bogus internal Python names like <string> which is seen
        for example when executing "exec cmd".
        """

        if arg_1 == "<" + arg_1[1:-1] + ">":
            return arg_1
        Func = arg_0.filename_cache.get(arg_1)
        if not Func:
            arg_3 = arg_1.split(os.sep)[0]
            if arg_3 == os.curdir or arg_3 == os.pardir:
                # We may have invoked the program from a directory
                # other than where the program resides. filename is
                # relative to where the program resides. So make sure
                # to use that.
                Func = os.path.abspath(os.path.join(arg_0.main_dirname,
                                                       arg_1))
            else:
                Func = os.path.abspath(arg_1)
                pass
            if not os.path.isfile(Func):
                Func = Mclifns.search_file(arg_1, arg_0.search_path,
                                              arg_0.main_dirname)
                # FIXME: is this is right for utter failure?
                if not Func: Func = arg_1
                pass
            Func = os.path.realpath(os.path.normcase(Func))
            arg_0.filename_cache[arg_1] = Func
        return Func


def Func(arg_0, Func=None):
        """Return filename or the basename of that depending on the
        basename setting"""
        if Func is None:
            if arg_0.debugger.mainpyfile:
                Func = arg_0.debugger.mainpyfile
            else:
                return None
        if arg_0.debugger.settings['basename']:
            return(os.path.basename(Func))
        return Func


def Func(arg_0):
        '''Return True if debugging is in progress.'''
        return (tracer.Func() and
                not arg_0.trace_hook_suspend
                and tracer.find_hook(arg_0.trace_dispatch))


def Func(arg_0, arg_1, arg_2, arg_3):
        """ Does the magic to determine if we stop here and run a
        command processor or not. If so, return True and set
        self.stop_reason; if not, return False.

        Determining factors can be whether a breakpoint was
        encountered, whether we are stepping, next'ing, finish'ing,
        and, if so, whether there is an ignore counter.
        """

        # Add an generic event filter here?
        # FIXME TODO: Check for
        #  - thread switching (under set option)

        # Check for "next" and "finish" stopping via stop_level

        # Do we want a different line and if so,
        # do we have one?
        arg_4 = arg_1.f_lineno
        arg_5 = arg_1.f_code.co_filename
        if arg_0.different_line and arg_2 == 'line':
            if arg_0.last_lineno == arg_4 and arg_0.last_filename == arg_5:
                return False
            pass
        arg_0.last_lineno   = arg_4
        arg_0.last_filename = arg_5

        if arg_0.stop_level is not None:
            if arg_1 != arg_0.last_frame:
                # Recompute stack_depth
                arg_0.last_level = Mstack.count_frames(arg_1)
                arg_0.last_frame = arg_1
                pass
            if arg_0.last_level > arg_0.stop_level:
                return False
            elif arg_0.last_level == arg_0.stop_level and \
                    arg_0.stop_on_finish and arg_2 in ['return', 'c_return']:
                arg_0.stop_level = None
                arg_0.stop_reason = "in return for 'finish' command"
                return True
            pass

        # Check for stepping
        if arg_0._is_step_next_stop(arg_2):
            arg_0.stop_reason = 'at a stepping statement'
            return True

        return False


def Func(arg_0, arg_1, arg_2=0, arg_3=None):
        "Sets to stop on the next event that happens in frame 'frame'."
        arg_0.step_events      = None  # Consider all events
        arg_0.stop_level       = Mstack.count_frames(arg_1)
        arg_0.last_level       = arg_0.stop_level
        arg_0.last_frame       = arg_1
        arg_0.stop_on_finish   = False
        arg_0.step_ignore      = arg_2
        return


def Func(arg_0, arg_1):
        """A mini stack trace routine for threads."""
        while arg_1:
            if (not arg_0.core.ignore_filter.is_included(arg_1)
                or arg_0.settings['dbg_trepan']):
                arg_2 = Mstack.format_stack_entry(arg_0, (arg_1, arg_1.f_lineno))
                arg_0.msg(" "*4 + arg_2)
                pass
            arg_1 = arg_1.f_back
            pass
        return


def Func(arg_0, arg_1):
        """Get file information"""
        if len(arg_1) == 0:
            if not arg_0.proc.curframe:
                arg_0.errmsg("No frame - no default file.")
                return False
            arg_2 = arg_0.proc.curframe.f_code.co_filename
        else:
            arg_2 = arg_1[0]
            pass

        arg_3 = arg_2 + ' is'
        arg_4 = arg_0.core.filename_cache
        if arg_2 in arg_4:
            arg_3 += " cached in debugger"
            if arg_4[arg_2] != arg_2:
                arg_3 += ' as:'
                arg_3 = Mmisc.wrapped_lines(arg_3, arg_4[arg_2] + '.',
                                        arg_0.settings['width'])
            else:
                arg_3 += '.'
                pass
            arg_0.msg(arg_3)
        else:
            arg_5 = [file for file in file_list() if
                       file.endswith(arg_2)]
            if (len(arg_5) > 1):
                arg_0.msg("Multiple files found ending filename string:")
                for arg_6 in arg_5:
                    arg_0.msg("\t%s" % arg_6)
                    pass
            elif len(arg_5) == 1:
                arg_7 = pyficache.unmap_file(arg_5[0])
                arg_3 += " matched debugger cache file:\n  "  + arg_7
                arg_0.msg(arg_3)
            else:
                arg_0.msg(arg_3 + ' not cached in debugger.')
            pass
        arg_7 = arg_0.core.canonic(arg_2)
        arg_0.msg(Mmisc.wrapped_lines('Canonic name:', arg_7,
                                     arg_0.settings['width']))
        for arg_8 in (arg_7, arg_2):
            if arg_8 in sys.modules:
                for arg_9 in [k for k, v in list(sys.modules.items())
                            if arg_8 == v]:
                    arg_0.msg("module: %s", arg_9)
                    pass
                pass
            pass
        for arg_10 in arg_1[1:]:
            arg_11 = False
            if arg_10 in ['all', 'size']:
                if pyficache.size(arg_7):
                    arg_0.msg("File has %d lines." %
                             pyficache.size(arg_7))
                    pass
                arg_11 = True
                pass
            if arg_10 in ['all', 'sha1']:
                arg_0.msg("SHA1 is %s." % pyficache.sha1(arg_7))
                arg_11 = True
                pass
            if arg_10 in ['all', 'brkpts']:
                arg_12 = pyficache.trace_line_numbers(arg_7)
                if arg_12:
                    arg_0.section("Possible breakpoint line numbers:")
                    arg_13 = columnize.columnize(arg_12, ljust = False,
                                                    arrange_vertical = False,
                                                    lineprefix='  ')
                    arg_0.msg(arg_13)
                    pass
                arg_11 = True
                pass
            if not arg_11:
                arg_0.errmsg("Don't understand sub-option %s." % arg_10)
                pass
            pass
        return


def Func(arg_0, arg_1):
    """Check whether we should break here because of `b.funcname`."""
    if not arg_0.funcname:
        # Breakpoint was set via line number.
        if arg_0.line != arg_1.f_lineno:
            # Breakpoint was set at a line with a def statement and the function
            # defined is called: don't break.
            return False
        return True

    # Breakpoint set via function name.

    if arg_1.f_code.co_name != arg_0.funcname:
        # It's not a function call, but rather execution of def statement.
        return False

    # We are in the right frame.
    if not arg_0.func_first_executable_line:
        # The function is entered for the 1st time.
        arg_0.func_first_executable_line = arg_1.f_lineno

    if arg_0.func_first_executable_line != arg_1.f_lineno:
        # But we are not at the first line number: don't break.
        return False
    return True


def Func(arg_0, arg_1):
        " remove breakpoint `bp'"
        arg_2 = arg_1.number
        arg_0.bpbynumber[arg_2] = None   # No longer in list
        arg_4 = (arg_1.filename, arg_1.line)
        if arg_4 not in arg_0.bplist: return False
        arg_0.bplist[arg_4].remove(arg_1)
        if not arg_0.bplist[arg_4]:
            # No more breakpoints for this file:line combo
            del arg_0.bplist[arg_4]
        return True


def Func(arg_0, arg_1):
        "Remove a breakpoint given its breakpoint number."
        arg_2, arg_3, arg_4 = arg_0.get_breakpoint(arg_1)
        if not arg_2:
            return False, arg_3
        arg_0.delete_breakpoint(arg_4)
        return (True, '')


def Func(arg_0,  arg_1=True):
        "Enable or disable all breakpoints."
        arg_2 = [arg_5 for arg_5 in arg_0.bpbynumber if arg_5]
        arg_3 = []
        if arg_1:
            arg_4 = 'en'
        else:
            arg_4 = 'dis'
            pass
        if not arg_2:
            return "No breakpoints to %sable" % arg_4
        for arg_5 in arg_2:
            arg_5.enabled = arg_1
            arg_3.append(str(arg_5.number))
            pass
        return ("Breakpoints %sabled: %s" % (arg_4, ", ".join(arg_3)))


def Func(arg_0, arg_1, arg_2=True):
        "Enable or disable a breakpoint given its breakpoint number."
        arg_3, arg_4, arg_5 = arg_0.get_breakpoint(arg_1)
        if not arg_3:
            return arg_3, arg_4
        if arg_2:
            arg_6 = 'en'
        else:
            arg_6 = 'dis'
            pass
        if arg_5.enabled == arg_2:
            return (False, ('Breakpoint (%r) previously %sabled' %
                            (str(arg_1), arg_6,)))
        arg_5.enabled = arg_2
        return (True, '')


def Func(arg_0, arg_1='', arg_2=None):
        """Read a line of input. Prompt and use_raw exist to be
        compatible with other input routines and are ignored.
        EOFError will be raised on EOF.
        """
        arg_3 = arg_0.input.Func()
        if not arg_3: raise EOFError
        return arg_3.rstrip("\n")


def Func(arg_0):
    """
    Restore an original login session, checking the signed session
    """
    arg_1 = arg_0.session.get(la_settings.USER_SESSION_FLAG)
    logout(arg_0)

    if not arg_1:
        return

    try:
        arg_2 = signer.unsign(
            arg_1, max_age=timedelta(days=la_settings.USER_SESSION_DAYS_TIMESTAMP).total_seconds()
        )
        arg_3 = get_user_model().objects.get(pk=arg_2)
        messages.info(
            arg_0,
            la_settings.MESSAGE_LOGIN_REVERT.format(username=arg_3.__dict__[username_field]),
            extra_tags=la_settings.MESSAGE_EXTRA_TAGS,
        )
        login_as(arg_3, arg_0, store_original_user=False)
        if la_settings.USER_SESSION_FLAG in arg_0.session:
            del arg_0.session[la_settings.USER_SESSION_FLAG]
    except SignatureExpired:
        pass


def Func(arg_0, arg_1=False, arg_2=False):
    """
    Yield each document in a Luminoso project in turn. Requires a client whose
    URL points to a project.

    If expanded=True, it will include additional fields that Luminoso added in
    its analysis, such as 'terms' and 'vector'.

    Otherwise, it will contain only the fields necessary to reconstruct the
    document: 'title', 'text', and 'metadata'.

    Shows a progress bar if progress=True.
    """
    # Get total number of docs from the project record
    arg_3 = arg_0.get()['document_count']
    arg_4 = None
    try:
        if arg_2:
            arg_4 = tqdm(desc='Downloading documents', total=arg_3)

        for arg_5 in range(0, arg_3, DOCS_PER_BATCH):
            arg_6 = arg_0.get('docs', arg_5=arg_5, limit=DOCS_PER_BATCH)
            arg_7 = arg_6['result']
            for arg_8 in arg_7:
                # Get the appropriate set of fields for each document
                if arg_1:
                    for arg_9 in UNNECESSARY_FIELDS:
                        arg_8.pop(arg_9, None)
                else:
                    arg_8 = {arg_9: arg_8[arg_9] for arg_9 in CONCISE_FIELDS}

                if arg_2:
                    arg_4.update()
                yield arg_8

    finally:
        if arg_2:
            arg_4.close()


def Func(arg_0):
    """
    Handle arguments for the 'lumi-download' command.
    """
    arg_1 = argparse.ArgumentParser(
        description=DESCRIPTION,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    arg_1.add_argument(
        '-b',
        '--base-url',
        default=URL_BASE,
        help='API root url, default: %s' % URL_BASE,
    )
    arg_1.add_argument(
        '-e', '--expanded',
        help="Include Luminoso's analysis of each document, such as terms and"
             ' document vectors',
        action='store_true',
    )
    arg_1.add_argument('-t', '--token', help='API authentication token')
    arg_1.add_argument(
        '-s',
        '--save-token',
        action='store_true',
        help='save --token for --base-url to ~/.luminoso/tokens.json',
    )
    arg_1.add_argument(
        'project_id', help='The ID of the project in the Daylight API'
    )
    arg_1.add_argument(
        'output_file', nargs='?', default=None,
        help='The JSON lines (.jsons) file to write to'
    )
    arg_2 = arg_1.parse_args(arg_0)
    if arg_2.save_token:
        if not arg_2.token:
            raise ValueError("error: no token provided")
        LuminosoClient.save_token(arg_2.token,
                                  domain=urlparse(arg_2.base_url).netloc)

    arg_3 = LuminosoClient.connect(url=arg_2.base_url, token=arg_2.token)
    arg_4 = arg_3.client_for_path('projects/{}'.format(arg_2.project_id))
    download_docs(arg_4, arg_2.output_file, arg_2.expanded)


def Func(arg_0, arg_1=None):
    """
    Read a JSON or CSV file and convert it into a JSON stream, which will
    be saved in an anonymous temp file.
    """
    arg_2 = tempfile.TemporaryFile()
    for arg_3 in open_json_or_csv_somehow(arg_0,
                                          arg_1=arg_1):
        arg_2.write(json.dumps(arg_3, ensure_ascii=False).encode('utf-8'))
        arg_2.write(b'\n')
    arg_2.seek(0)
    return arg_2


def Func(arg_0, arg_1=None):
    """
    Deduce the format of a file, within reason.

    - If the filename ends with .csv or .txt, it's csv.
    - If the filename ends with .jsons, it's a JSON stream (conveniently the
      format we want to output).
    - If the filename ends with .json, it could be a legitimate JSON file, or
      it could be a JSON stream, following a nonstandard convention that many
      people including us are guilty of. In that case:
      - If the first line is a complete JSON document, and there is more in the
        file besides the first line, then it is a JSON stream.
      - Otherwise, it is probably really JSON.
    - If the filename does not end with .json, .jsons, or .csv, we have to guess
      whether it's still CSV or tab-separated values or something like that.
      If it's JSON, the first character would almost certainly have to be a
      bracket or a brace. If it isn't, assume it's CSV or similar.
    """
    arg_2 = None
    if arg_0.endswith('.csv'):
        arg_2 = 'csv'
    elif arg_0.endswith('.jsons'):
        arg_2 = 'jsons'
    else:
        with open(arg_0) as opened:
            arg_3 = opened.readline()
            if arg_3[0] not in '{[' and not arg_0.endswith('.json'):
                arg_2 = 'csv'
            else:
                if (arg_3.count('{') == arg_3.count('}') and
                    arg_3.count('[') == arg_3.count(']')):
                    # This line contains a complete JSON document. This probably
                    # means it's in linewise JSON ('.jsons') format, unless the
                    # whole file is on one line.
                    arg_4 = ' '
                    while arg_4.isspace():
                        arg_4 = opened.read()
                        if arg_4 == '':
                            arg_2 = 'json'
                            break
                    if arg_2 is None:
                        arg_2 = 'jsons'
                else:
                    arg_2 = 'json'

    if arg_2 == 'json':
        arg_5 = json.load(open(arg_0), encoding='utf-8')
    elif arg_2 == 'csv':
        arg_5 = open_csv_somehow(arg_0)
    else:
        arg_5 = stream_json_lines(arg_0)

    return _normalize_data(arg_5, arg_1=arg_1)


def Func(arg_0, arg_1=None):
    """
    This function is meant to normalize data for upload to the Luminoso
    Analytics system. Currently it only normalizes dates.

    If date_format is not specified, or if there's no date in a particular doc,
    the the doc is yielded unchanged.
    """
    for arg_2 in arg_0:
        if 'date' in arg_2 and arg_1 is not None:
            try:
                arg_2['date'] = _convert_date(arg_2['date'], arg_1)
            except ValueError:
                # ValueErrors cover the cases when date_format does not match
                # the actual format of the date, both for epoch and non-epoch
                # times.
                logger.exception('%s does not match the date format %s;'
                                 % (arg_2['date'], arg_1))
        yield arg_2


def Func(arg_0, arg_1):
    """
    Convert a date in a given format to epoch time. Mostly a wrapper for
    datetime's strptime.
    """
    if arg_1 != 'epoch':
        return datetime.strptime(arg_0, arg_1).timestamp()
    else:
        return float(arg_0)