Create a new stack object with limited extent from an exising stack object
489206
def stack_clip(s_orig, extent, out_stack_fn=None, copy=True, save=False):
    
    #Should check for valid extent

    #This is not memory efficient, but is much simpler
    #To be safe, if we are saving out, create a copy to avoid overwriting
    if copy or save:
        from copy import deepcopy
        print("Copying original DEMStack")
        s = deepcopy(s_orig)
    else:
        #Want to be very careful here, as we could overwrite the original file
        s = s_orig

    from pygeotools.lib import geolib
    gt = s.gt
    s_shape = s.ma_stack.shape[1:3]

    #Compute pixel bounds for input extent
    min_x_px, max_y_px = geolib.mapToPixel(extent[0], extent[1], gt)
    max_x_px, min_y_px = geolib.mapToPixel(extent[2], extent[3], gt)

    #Clip to stack extent and round to whole integers
    min_x_px = int(max(0, min_x_px)+0.5)
    max_x_px = int(min(s_shape[1], max_x_px)+0.5)
    min_y_px = int(max(0, min_y_px)+0.5)
    max_y_px = int(min(s_shape[0], max_y_px)+0.5)
  
    #Clip the stack
    x_slice = slice(min_x_px,max_x_px)
    y_slice = slice(min_y_px,max_y_px)
    s.ma_stack = s.ma_stack[:, y_slice, x_slice]

    #Now update geospatial info
    #This returns the pixel center in map coordinates
    #Want to remove 0.5 px offset for upper left corner in gt
    out_ul = geolib.pixelToMap(min_x_px - 0.5, min_y_px - 0.5, gt)
   
    #Update stack geotransform
    s.gt[0] = out_ul[0]
    s.gt[3] = out_ul[1]
    #Update new stack extent
    s.get_extent()

    #Check for and discard emtpy arrays 
    #Might be faster to reshape then np.ma.count(s.ma_stack, axis=1)
    count_list = np.array([i.count() for i in s.ma_stack])
    idx = count_list > 0 
    
    #Output subset with valid data in next extent
    #fn_list, source, error, error_dict_list, date_list, date_list_o
    #Note: no need to copy again
    s_sub = get_stack_subset(s, idx, out_stack_fn=out_stack_fn, copy=False, save=False) 

    print("Orig filename:", s_orig.stack_fn)
    print("Orig extent:", s_orig.extent)
    print("Orig dimensions:", s_orig.ma_stack.shape)
    print("Input extent:", extent)
    print("New filename:", s_sub.stack_fn)
    print("New extent:", s_sub.extent)
    print("New dimensions:", s_sub.ma_stack.shape)
    
    if save:
        if os.path.abspath(s_orig.stack_fn) == os.path.abspath(s_sub.stack_fn):
            print("Original stack would be overwritten!")
            print("Skipping save")
        else:
            s_sub.save = True
            s_sub.savestack()

    #The following should be unchanged by clip - it is more efficient to clip thes, but easier to regenerate
    #if s.stats:
    #stack_count, stack_mean, stack_min, stack_max, stack_std
    #s.stack_min = s.stack_min[y_slice, x_slice]
    #if s.datestack:
    #dt_ptp, dt_min, dt_max, dt_center
    #if s.med:
    #stack_med
    #if s.trend:
    #trend, intercept, detrended_std
    #Recompute stats/etc

    return s_sub
992072
function prepareStack(stack) {
	let lines = stack.split('\n').slice(1)

	if (lines.length > 500) {
		// Stack too big, probably this is caused by stack overflow
		// Remove middle values
		let skipped = lines.length - 500,
			top = lines.slice(0, 250),
			bottom = lines.slice(-250)
		lines = top.concat('--- skipped ' + skipped + ' frames ---', bottom)
	}

	return lines.map(line => line.trim().replace(/^at /, '').replace(basePath, '.'))
}
12111
def pop_arguments(instr, stack):
    
    needed = instr.stack_effect
    if needed >= 0:
        raise DecompilationError(
            "%s is does not have a negative stack effect" % instr
        )

    for popcount, to_pop in enumerate(reversed(stack), start=1):
        needed += to_pop.stack_effect
        if not needed:
            break
    else:
        raise DecompilationError(
            "Reached end of stack without finding inputs to %s" % instr,
        )

    popped = stack[-popcount:]
    stack[:] = stack[:-popcount]

    return popped
1248708
def _make_expr(toplevel, stack_builders):
    
    base_expr = _make_expr_internal(toplevel, stack_builders)
    if not toplevel._next_target_of:
        return base_expr

    subexprs = deque([base_expr])
    ops = deque([])
    while stack_builders and stack_builders[-1] in toplevel._next_target_of:
        jump = stack_builders.pop()
        if not isinstance(jump, _BOOLOP_JUMP_TYPES):
            raise DecompilationError(
                "Don't know how to decompile %s inside expression." % jump,
            )
        subexprs.appendleft(make_expr(stack_builders))
        ops.appendleft(_BOOLOP_JUMP_TO_AST_OP[type(jump)]())

    if len(subexprs) <= 1:
        raise DecompilationError(
            "Expected at least one JUMP instruction before expression."
        )

    return normalize_boolop(make_boolop(subexprs, ops))
1368999
def make_call_positionals(stack_builders, count):
    
    out = [make_expr(stack_builders) for _ in range(count)]
    out.reverse()
    return out
565425
def _pop_indent_stack(self, node, node_type=None, action=None):
        """"""
        indent = self._get_indent(node)
        indent_stack = copy.deepcopy(self._indent_stack)
        # Find enclosing scope
        while (len(indent_stack) > 1) and (
            (
                (indent <= indent_stack[-1]["level"])
                and (indent_stack[-1]["type"] != "module")
            )
            or (indent_stack[-1]["type"] == "prop")
        ):
            self._close_callable(node)
            indent_stack.pop()
        # Construct new callable name
        name = (
            (
                node.targets[0].id
                if hasattr(node.targets[0], "id")
                else node.targets[0].value.id
            )
            if node_type == "prop"
            else node.name
        )
        element_full_name = ".".join(
            [self._module]
            + [
                indent_dict["prefix"]
                for indent_dict in indent_stack
                if indent_dict["type"] != "module"
            ]
            + [name]
        ) + ("({0})".format(action) if action else "")
        # Add new callable entry to indentation stack
        self._indent_stack = indent_stack
        self._indent_stack.append(
            {
                "level": indent,
                "prefix": name,
                "type": node_type,
                "full_name": element_full_name,
                "lineno": node.lineno,
            }
        )
        return element_full_name
562364
private void stretch(IntStack stack, IAtom beg, IAtom end, double amount) {
        Point2d begPoint = beg.getPoint2d();
        Point2d endPoint = end.getPoint2d();

        if (begPoint.distance(endPoint) + amount > MAX_BOND_LENGTH)
            return;

        Vector2d vector = new Vector2d(endPoint.x - begPoint.x, endPoint.y - begPoint.y);
        vector.normalize();
        vector.scale(amount);

        for (int i = 0; i < stack.len; i++)
            atoms[stack.xs[i]].getPoint2d().add(vector);
    }
1022157
function fromStackProperty(stackString) {
  let chrome = /^\s*at (?:((?:\[object object\])?\S+(?: \[as \S+\])?) )?\(?((?:file|http|https):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
  let gecko = /^\s*(\S*)(?:\((.*?)\))?@((?:file|http|https).*?):(\d+)(?::(\d+))?\s*$/i;
  let lines = stackString.split('\n');
  let stack = [];
  let parts;

  for (let i = 0, j = lines.length; i < j; ++i) {
    if ((parts = gecko.exec(lines[i]))) {
      stack.push({
        url: parts[3],
        func: parts[1] || UNKNOWN_FUNCTION,
        args: parts[2] ? parts[2].split(',') : '',
        line: +parts[4],
        column: parts[5] ? +parts[5] : null
      });
    } else if ((parts = chrome.exec(lines[i]))) {
      stack.push({
        url: parts[2],
        func: parts[1] || UNKNOWN_FUNCTION,
        line: +parts[3],
        column: parts[4] ? +parts[4] : null
      });
    }
  }

  return stack.length ? stack : null;
}
477658
function( obj, type, stack ) {
                    stack = stack || [];
                    var inStack, res,
                        parser = this.parsers[ type || this.typeOf( obj ) ];

                    type = typeof parser;
                    inStack = inArray( obj, stack );

                    if ( inStack !== -1 ) {
                        return "recursion(" + ( inStack - stack.length ) + ")";
                    }
                    if ( type === "function" ) {
                        stack.push( obj );
                        res = parser.call( this, obj, stack );
                        stack.pop();
                        return res;
                    }
                    return ( type === "string" ) ? parser : this.parsers.error;
                }
1156075
def push_scope(self, callback=None):  # noqa
        

        if callback is not None:
            with self.push_scope() as scope:
                callback(scope)
            return None

        client, scope = self._stack[-1]
        new_layer = (client, copy.copy(scope))
        self._stack.append(new_layer)

        return _ScopeManager(self)
440210
def create(cls, *operands, **kwargs):
        """"""
        converted_operands = []
        for op in operands:
            if not isinstance(op, Scalar):
                op = ScalarValue.create(op)
            converted_operands.append(op)
        return super().create(*converted_operands, **kwargs)
1143805
private void doDrain(List<StackSize> stackSizes) {
        ListIterator<StackSize> iterator = stackSizes.listIterator(stackSizes.size());
        while (iterator.hasPrevious()) {
            StackSize current = iterator.previous();
            switch (current) {
                case SINGLE:
                    super.visitInsn(Opcodes.POP);
                    break;
                case DOUBLE:
                    super.visitInsn(Opcodes.POP2);
                    break;
                default:
                    throw new IllegalStateException("Unexpected stack size: " + current);
            }
        }
    }
867847
function extend( obj, ext ){
    for( var prop in ext ){
      obj[prop] = ext[prop]
    }
    return obj
  }
1006594
function appendExtension (obj, extension) {
  if (!obj.extensions) {
    obj.extensions = []
  }

  if (obj.extensions.indexOf(extension) === -1) {
    obj.extensions.push(extension)
  }
}
443518
function pushResultsArray(obj, size) {
  if (typeof obj === "string" && obj in stack) {
    stack[obj]["size"] = size;
    return;
  }
  if (!(obj.module in stack)) {
    stack[obj.module] = obj;
  }
}
872185
function extend() {
    let arg = arguments,
        target = arg[0] || {},
        deep = false,
        length = arg.length,
        i = 1,
        value, attr,
        copyIsArray;

    if (isBoolean(target)) {
        deep = target;
        target = arg[1] || {};
        i++;
    }

    for (; i < length; i++) {
        for (attr in arg[i]) {

            value = arg[i][attr];

            if (deep && (isPlainObject(value) || (copyIsArray = isArray(value)))) {

                let src = target[attr];

                if (copyIsArray) {
                    copyIsArray = false;
                    src = isArray(src) ? src : [];
                } else {
                    src = isPlainObject(src) ? src : {};
                }

                target[attr] = extend(deep, src, value);

            } else {
                target[attr] = value;
            }
        }
    }

    return target;
}
385989
def make_stack(env, stage, segment):
    

    import string
    import random
    from ambry.valuetype import ValueType

    column = segment['column']

    def make_line(column, t):
        preamble = []

        line_t = "v = {} # {}"

        if isinstance(t, type) and issubclass(t, ValueType):  # A valuetype class, from the datatype column.

            try:
                cc, fl = calling_code(t, t.__name__), file_loc()
            except TypeError:
                cc, fl = "{}(v)".format(t.__name__), file_loc()

            preamble.append("{} = resolve_value_type('{}') # {}".format(t.__name__, t.vt_code, fl))

        elif isinstance(t, type):  # A python type, from the datatype columns.
            cc, fl= "parse_{}(v, header_d)".format(t.__name__), file_loc()

        elif callable(env.get(t)):  # Transform function
            cc, fl = calling_code(env.get(t), t), file_loc()

        else:  # A transform generator, or python code.

            rnd = (''.join(random.choice(string.ascii_lowercase) for _ in range(6)))

            name = 'tg_{}_{}_{}'.format(column.name, stage, rnd)
            try:
                a, b, fl = rewrite_tg(env, name, t)
            except CodeGenError as e:
                raise CodeGenError("Failed to re-write pipe code '{}' in column '{}.{}': {} "
                                   .format(t, column.table.name, column.name, e))

            cc = str(a)

            if b:
                preamble.append("{} = {} # {}".format(name, b, fl))

        line = line_t.format(cc, fl)

        return line, preamble

    preamble = []

    try_lines = []

    for t in [segment['init'], segment['datatype']] + segment['transforms']:

        if not t:
            continue

        line, col_preamble = make_line(column, t)

        preamble += col_preamble
        try_lines.append(line)

    exception = None
    if segment['exception']:
        exception, col_preamble = make_line(column, segment['exception'])

    if len(try_lines) == 0:
        try_lines.append('pass # Empty pipe segment')

    assert len(try_lines) > 0, column.name

    return preamble, try_lines, exception