Maps nets to new sets of nets according to a custom function

    :param transform_func:
        Function signature: func(orig_net (logicnet)) -> keep_orig_net (bool)
    :return:
762215
def net_transform(transform_func, block=None, **kwargs):
    
    block = working_block(block)
    with set_working_block(block, True):
        for net in block.logic.copy():
            keep_orig_net = transform_func(net, **kwargs)
            if not keep_orig_net:
                block.logic.remove(net)
753666
def starmap_t(func):
    
    return Transformation('starmap({})'.format(name(func)),
                          partial(starmap, func),
                          {ExecutionStrategies.PARALLEL})
403219
def map(cls, iterable, func, *a, **kw):
    

    return cls(func(x, *a, **kw) for x in iterable)
172252
def transformation(func):
    """"""
    @wraps(func)
    def func_as_transformation(*args, **kwargs):
        
        # When using transforms that return new ndarrays we lose the
        # jicimagelib.image.Image type and the history of the image.
        # One therefore needs to:
        #  - Extract the history from the input jicimagelib.image.Image.
        #  - Apply the transformation, which may return a numpy ndarray.
        #  - Force the image to the jicimagelib.image.Image type.
        #  - Re-attach the extracted history
        if hasattr(args[0], 'history'):
            # Working on jicimagelib.Image.
            history = args[0].history
        else:
            # Working on something without a history, e.g. a ndarray stack.
            history = []
        image = func(*args, **kwargs)
        image = Image.from_array(image, log_in_history=False)
        image.history = history

        image.history.append('Applied {} transform'.format(func.__name__))
        if AutoWrite.on:
            fpath = AutoName.name(func)
            try:
                if AutoWrite.auto_safe_dtype:
                    safe_range_im = 255 * normalise(image)
                    pil_im = PIL.Image.fromarray(safe_range_im.astype(np.uint8))
                else:
                    pil_im = PIL.Image.fromarray(image)
            except TypeError:
                # Give a more meaningful error message.
                raise(TypeError(
                    "Cannot handle this data type: {}".format(image.dtype)))
            pil_im.save(fpath)
        return image
    return func_as_transformation
663362
def create_transform(self, rule):
        
        try:
            name, value = next(iter(rule.items()))
        except AttributeError:
            name, value = rule, None
        try:
            return self.REGISTRY[name](value, conf=self.conf)
        except KeyError:
            raise RuntimeError(
                "Unknown transform: %r" % (name,)
            )
1323286
def _build_register_function(universe: bool, in_place: bool):  # noqa: D202
    

    def register(func):
        """Tag a transformation function.

        :param func: A function
        :return: The same function, with additional properties added
        """
        return _register_function(func.__name__, func, universe, in_place)

    return register
33109
def _makes_clone(_func, *args, **kw):
    
    self = args[0]._clone()
    _func(self, *args[1:], **kw)
    return self
1129352
def transform(func, data):
    
    out = []
    for r in data:
        out.append(func(r))
    return out
671623
def _process_transform(self, data, transform, step_size):
    '''
    
    '''
    if isinstance(transform, (list,tuple,set)):
      return { t : self._transform(data,t,step_size) for t in transform }
    elif isinstance(transform, dict):
      return { tn : self._transform(data,tf,step_size) for tn,tf in transform.items() }
    return self._transform(data,transform,step_size)
207084
def slice_transform(func, self, X, *vargs, **kwargs):
    
    X = X if self.apply_ind is None else X[:, self.apply_ind]
    return func(self, X, *vargs, **kwargs)
649541
def memoize(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        """ wrap it up and store info in a cache """
        cache = args[0].memoized
        refresh = args[0].refresh_interval
        use_cache = args[0].use_cache

        # short circuit if not using cache
        if use_cache is False:
            return func(*args, **kwargs)

        if func.__name__ not in cache:
            cache[func.__name__] = dict()
            if "defaults" not in cache:
                cache["defaults"] = dict()
            cache["defaults"][func.__name__] = parse_all_arguments(func)
        # build a key; should also consist of the default values
        defaults = cache["defaults"][func.__name__].copy()
        for key, val in kwargs.items():
            defaults[key] = val
        tmp = list()
        tmp.extend(args[1:])
        for k in sorted(defaults.keys()):
            tmp.append("({0}: {1})".format(k, defaults[k]))

        # handle possible unicode characters
        if sys.version_info < (3, 0):
            tmp = [unicode(x) for x in tmp]
        key = " - ".join(tmp)

        # set the value in the cache if missing or needs to be refreshed
        if key not in cache[func.__name__]:
            cache[func.__name__][key] = (time.time(), func(*args, **kwargs))
        else:
            tmp = cache[func.__name__][key]
            # determine if we need to refresh the data...
            if refresh is not None and time.time() - tmp[0] > refresh:
                cache[func.__name__][key] = (time.time(), func(*args, **kwargs))
        return cache[func.__name__][key][1]

    return wrapper
1172902
def _transform_coordinates(
            self,
            func: Callable[[Union[int, float], Union[int, float]],
                           Tuple[Union[int, float], Union[int, float]]]
    ) -> None:
        """"""

        def func_x(x: Union[int, float]) -> Union[int, float]:
            return func(x, 0)[0]

        def func_y(y: Union[int, float]) -> Union[int, float]:
            return func(0, y)[1]

        self.entries = {
            cast(Tuple[int, int], func(int(x), int(y))): v
            for (x, y), v in self.entries.items()
        }
        self.vertical_lines = [
            _VerticalLine(func_x(x), func_y(y1), func_y(y2), emph)
            for x, y1, y2, emph in self.vertical_lines]
        self.horizontal_lines = [
            _HorizontalLine(func_y(y), func_x(x1), func_x(x2), emph)
            for y, x1, x2, emph in self.horizontal_lines]
        self.horizontal_padding = {
            int(func_x(int(x))): padding
            for x, padding in self.horizontal_padding.items()
        }
        self.vertical_padding = {
            int(func_y(int(y))): padding
            for y, padding in self.vertical_padding.items()
        }
163733
function mapTransform (args, math, scope) {
    let x, callback

    if (args[0]) {
      x = args[0].compile().evaluate(scope)
    }

    if (args[1]) {
      if (isSymbolNode(args[1]) || isFunctionAssignmentNode(args[1])) {
        // a function pointer, like filter([3, -2, 5], myTestFunction)
        callback = args[1].compile().evaluate(scope)
      } else {
        // an expression like filter([3, -2, 5], x > 0)
        callback = compileInlineExpression(args[1], math, scope)
      }
    }

    return map(x, callback)
  }
682168
function onNextTransform (transform, next) {
      // check if we should handle this filePath
      function shouldProcess (filePath, done) {
        done(!!multimatch(filePath, transform.pattern, transform.opts).length)
      }

      // transform the path
      function process (filePath, complete) {
        var filename = path.basename(filePath),
            pathParts = path.dirname(filePath).split(path.sep)

        // we'll get an empty arrary if we overslice
        pathParts = pathParts.slice(transform.by)
        pathParts.push(filename)

        var newPath = pathParts.join(path.sep),
            fileData = files[filePath]

        // don't need the old fileData anymore,
        // since we are re-adding with the new path
        delete files[filePath]
        files[newPath] = fileData

        complete()
      }

      // we do this for each option as the last may have modified the collection
      async.filter(Object.keys(files), shouldProcess, function (results) {
        async.each(results, process, next)
      })
    }
651342
def wrap_connection(func_, *args, **kwargs):
    
    if not args[-1]:
        new_args = list(args)
        new_args[-1] = connect()
        args = tuple(new_args)
    return func_(*args, **kwargs)
1226812
def decoratable_funcdef_stmt_handle(self, original, loc, tokens, is_async=False):
        """"""
        if len(tokens) == 1:
            decorators, funcdef = "", tokens[0]
        elif len(tokens) == 2:
            decorators, funcdef = tokens
        else:
            raise CoconutInternalException("invalid function definition tokens", tokens)

        # extract information about the function
        raw_lines = funcdef.splitlines(True)
        def_stmt = raw_lines.pop(0)
        func_name, func_args, func_params = None, None, None
        with self.complain_on_err():
            func_name, func_args, func_params = parse(self.split_func_name_args_params, def_stmt)

        undotted_name = None  # the function __name__ if func_name is a dotted name
        if func_name is not None:
            if "." in func_name:
                undotted_name = func_name.rsplit(".", 1)[-1]
                def_stmt = def_stmt.replace(func_name, undotted_name)

        # handle async functions
        if is_async:
            if not self.target:
                raise self.make_err(
                    CoconutTargetError,
                    "async function definition requires a specific target",
                    original, loc,
                    target="sys",
                )
            elif self.target_info >= (3, 5):
                def_stmt = "async " + def_stmt
            else:
                decorators += "@_coconut.asyncio.coroutine\n"

            # only Python 3.3+ supports returning values inside generators
            if self.target_info < (3, 3):
                func_code = self.transform_returns(raw_lines, is_async=True)
            else:
                func_code = "".join(raw_lines)

        # handle normal functions
        else:
            # tre does not work with decorators, though tco does
            attempt_tre = func_name is not None and not decorators
            if attempt_tre:
                use_mock = func_args and func_args != func_params[1:-1]
                func_store = tre_store_var + "_" + str(self.tre_store_count)
                self.tre_store_count += 1
                tre_return_grammar = self.tre_return(func_name, func_args, func_store, use_mock)
            else:
                use_mock = func_store = tre_return_grammar = None

            func_code, tco, tre = self.transform_returns(
                raw_lines,
                tre_return_grammar,
                use_mock,
            )

            if tre:
                comment, rest = split_leading_comment(func_code)
                indent, base, dedent = split_leading_trailing_indent(rest, 1)
                base, base_dedent = split_trailing_indent(base)
                docstring, base = self.split_docstring(base)
                func_code = (
                    comment + indent
                    + (docstring + "\n" if docstring is not None else "")
                    + (
                        "def " + tre_mock_var + func_params + ": return " + func_args + "\n"
                        if use_mock else ""
                    ) + "while True:\n"
                        + openindent + base + base_dedent
                        + ("\n" if "\n" not in base_dedent else "") + "return None"
                        + ("\n" if "\n" not in dedent else "") + closeindent + dedent
                    + func_store + " = " + (func_name if undotted_name is None else undotted_name) + "\n"
                )
            if tco:
                decorators += "@_coconut_tco\n"  # binds most tightly

        out = decorators + def_stmt + func_code
        if undotted_name is not None:
            out += func_name + " = " + undotted_name + "\n"
        return out
616383
def _transform_should_cast(self, func_nm):
        
        return (self.size().fillna(0) > 0).any() and (
            func_nm not in base.cython_cast_blacklist)