Call the user's `compute` function on each window with a pre-built
        output array.
336143
def _compute(self, windows, dates, assets, mask):
        
        format_inputs = self._format_inputs
        compute = self.compute
        params = self.params
        ndim = self.ndim

        shape = (len(mask), 1) if ndim == 1 else mask.shape
        out = self._allocate_output(windows, shape)

        with self.ctx:
            for idx, date in enumerate(dates):
                # Never apply a mask to 1D outputs.
                out_mask = array([True]) if ndim == 1 else mask[idx]

                # Mask our inputs as usual.
                inputs_mask = mask[idx]

                masked_assets = assets[inputs_mask]
                out_row = out[idx][out_mask]
                inputs = format_inputs(windows, inputs_mask)

                compute(date, masked_assets, out_row, *inputs, **params)
                out[idx][out_mask] = out_row
        return out
947039
def run(input=sys.stdin, output=sys.stdout):
    
    """
    functions = []
    environments = dict()

    def _writejson(obj):
        obj = json.encode(obj)
        if isinstance(obj, unicode):
            obj = obj.encode('utf-8')
        output.write(obj)
        output.write('\n')
        output.flush()

    def _log(message):
        if not isinstance(message, basestring):
            message = json.encode(message)
        _writejson({'log': message})

    def reset(config=None):
        del functions[:]
        return True

    def add_fun(string):
        string = BOM_UTF8 + string.encode('utf-8')
        try:
            function = _compile(string, "map_compilation_error", "map")
        except CompileError as e:
            return e.args[0]
        functions.append(function)
        return True

    def map_doc(doc):
        results = []
        for function in functions:
            try:
                results.append([[key, value] for key, value in function(doc)])
            except Exception, e:
                log.error('runtime error in map function: %s', e,
                          exc_info=True)
                results.append([])
                _log(traceback.format_exc())
        return results

    def reduce(*cmd, **kwargs):
        code = BOM_UTF8 + cmd[0][0].encode('utf-8')
        args = cmd[1]

        try:
            function = _compile(code, "reduce_compilation_error", "reduce")
        except CompileError as e:
            return e.args[0]

        rereduce = kwargs.get('rereduce', False)
        results = []
        if rereduce:
            keys = None
            vals = args
        else:
            if args:
                keys, vals = zip(*args)
            else:
                keys = []
                vals = []
        if function.func_code.co_argcount == 3:
            results = function(keys, vals, rereduce)
        else:
            results = function(keys, vals)
        return [True, [results]]

    def rereduce(*cmd):
        # Note: weird kwargs is for Python 2.5 compat
        return reduce(*cmd, **{'rereduce': True})

    def ddoc_new(name, doc):
        env = dict()
        # key in design doc -> expected function name
        method_mapping = dict(filters='filter', views='map')
        for key, section in doc.iteritems():
            if key not in method_mapping:
                continue
            env[key] = dict()
            id_error = "%s_compilation_error" % (key)
            for f_name, func_str in section.iteritems():
                if isinstance(func_str, dict):
                    env[key][f_name] = dict()
                    for expected_name, code in func_str.iteritems():
                        try:
                            env[key][f_name][expected_name] = _compile(
                                code, id_error, expected_name)
                        except CompileError as e:
                            return e.args[0]
                else:
                    try:
                        expected_name = method_mapping[key]
                        env[key][f_name] = _compile(func_str, id_error,
                                                    expected_name)
                    except CompileError as e:
                        return e.args[0]
        environments[name] = env
        return True

    def ddoc_exec(ddoc_name, ref, args):
        e = environments[ddoc_name]
        for r in ref:
            e = e[r]
        function = e
        h = handlers[ref[0]]

        return h(*args, **{"function": function})

    def ddoc(*args):
        args = list(args)
        n = args.pop(0)
        if n == 'new':
            return ddoc_new(*args)
        return ddoc_exec(n, args.pop(0), args[0])

    def filter(rows, request, dbinfo=None, function=None):
        request['db'] = dbinfo
        results = []

        for row in rows:
            r = function(row, request)
            if r is True:
                results.append(True)
            else:
                results.append(False)

        return [True, results]

    def filter_view(rows, function=None):
        results = []

        for row in rows:
            r = function(row)
            try:
                r.next()
                results.append(True)
            except StopIteration:
                results.append(False)

        return [True, results]

    def _compile(func_str, error_id, f_name):
        globals_ = {}

        if func_str in ('_count', '_sum', '_stats'):
            # These are builtins which are not ment to be complited
            # by the python server
            return func_str

        try:
            exec func_str in {'log': _log}, globals_
        except Exception, e:
            log.error('runtime error in filter function: %s', e,
                      exc_info=True)
            raise CompileError({'error': {
                'id': error_id,
                'reason': e.args[0]}})
        err = {'error': {
            'id': error_id,
            'reason': ('string must eval to a function named %(f_name)s '
                       '(ex: "def %(f_name)s(doc, request): return True")' %
                       dict(f_name=f_name))}}
        if f_name not in globals_:
            raise CompileError(err)
        function = globals_.pop(f_name)
        if type(function) is not FunctionType:
            raise CompileError(err)
        # merge in remaining globals so that they are available in the function
        function.func_globals.update(globals_)
        return function


    handlers = {'reset': reset, 'add_fun': add_fun, 'map_doc': map_doc,
                'reduce': reduce, 'rereduce': rereduce, 'ddoc': ddoc,
                'filters': filter, 'views': filter_view}

    try:
        while True:
            line = input.readline()
            if not line:
                break
            try:
                cmd = json.decode(line)
                log.debug('Processing %r', cmd)
            except ValueError, e:
                log.error('Error: %s', e, exc_info=True)
                return 1
            else:
                retval = handlers[cmd[0]](*cmd[1:])
                log.debug('Returning  %r', retval)
                _writejson(retval)
    except KeyboardInterrupt:
        return 0
    except Exception, e:
        log.error('Error: %s', e, exc_info=True)
        return 1
942811
def _call(self, func, out=None, **kwargs):
        """"""
        mesh = self.grid.meshgrid
        if out is None:
            out = func(mesh, **kwargs)
        else:
            with writable_array(out) as out_arr:
                func(mesh, out=out_arr, **kwargs)
        return out
550472
def example_compute(self):
        
        a = matmul(self.x, self.w1)
        y = matmul(a, self.w2)

        sess = Session()
        sess.run(self.w1.initializer)
        sess.run(self.w2.initializer)
        print('第一种：', sess.run(y))
        sess.close()
699710
function(context) {
		if(context && typeof this._args[0] === 'function') {
			this._args[1] = context;
		} else if(context) {
			this._args[2] = context;
		}

		return new Compute(this._args[0], this._args[1], this._args[2], this._args[3]);
	}
580339
def compute(self, inputs, outputs):
    
    if len(self.queue) > 0:
      data = self.queue.pop()

    else:
      raise Exception("CoordinateSensor: No data to encode: queue is empty")

    outputs["resetOut"][0] = data["reset"]
    outputs["sequenceIdOut"][0] = data["sequenceId"]
    sdr = self.encoder.encode((numpy.array(data["coordinate"]), self.radius))
    outputs["dataOut"][:] = sdr

    if self.verbosity > 1:
      print "CoordinateSensor outputs:"
      print "Coordinate = ", data["coordinate"]
      print "sequenceIdOut: ", outputs["sequenceIdOut"]
      print "resetOut: ", outputs["resetOut"]
      print "dataOut: ", outputs["dataOut"].nonzero()[0]
660378
def array(self, name, data, **kwargs):
        """"""
        return self._write_op(self._array_nosync, name, data, **kwargs)
302145
def _allocate_output(self, windows, shape):
        
        if self.dtype == int64_dtype:
            return super(CustomClassifier, self)._allocate_output(
                windows,
                shape,
            )

        # This is a little bit of a hack.  We might not know what the
        # categories for a LabelArray are until it's actually been loaded, so
        # we need to look at the underlying data.
        return windows[0].data.empty_like(shape)
724442
synchronized void computeDominators() {
        boolean changed = true;
        boolean igonoreDirty;
        try {
            do {
                currentMultipleParents.rewind();
                igonoreDirty = !changed;
                changed = computeOneLevel(igonoreDirty);
                switchParents();
            } while (changed || !igonoreDirty);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        deleteBuffers();
        dirtySet = Collections.EMPTY_SET;
    }
1171800
def run(self, **kwargs):
        
        from calculate import compute
        self.app_main(**kwargs)

        # get the default output name
        output = osp.join(self.exp_config['expdir'], 'output.dat')

        # save the paths in the configuration
        self.exp_config['output'] = output

        # run the model
        data = np.loadtxt(self.exp_config['infile'])
        out = compute(data)
        # save the output
        self.logger.info('Saving output data to %s', osp.relpath(output))
        np.savetxt(output, out)

        # store some additional information in the configuration of the
        # experiment
        self.exp_config['mean'] = mean = float(out.mean())
        self.exp_config['std'] = std = float(out.std())
        self.logger.debug('Mean: %s, Standard deviation: %s', mean, std)
712898
def _call(self, x, out=None):
        """"""
        if out is None:
            out = self.range.element()

        ndim = self.range.ndim
        dx = self.range.cell_sides

        tmp = np.empty(out.shape, out.dtype, order=out.space.default_order)
        with writable_array(out) as out_arr:
            for axis in range(ndim):
                finite_diff(x[axis], axis=axis, dx=dx[axis],
                            method=self.method, pad_mode=self.pad_mode,
                            pad_const=self.pad_const,
                            out=tmp)
                if axis == 0:
                    out_arr[:] = tmp
                else:
                    out_arr += tmp

        return out
573448
def run_parallel_with_display(wf, n_threads, display):
    """"""
    LogQ = Queue()

    S = Scheduler(error_handler=display.error_handler)

    threading.Thread(
        target=patch,
        args=(LogQ.source, sink_map(display)),
        daemon=True).start()

    W = Queue() \
        >> branch(log_job_start >> LogQ.sink) \
        >> thread_pool(*repeat(worker, n_threads)) \
        >> branch(LogQ.sink)

    result = S.run(W, get_workflow(wf))
    LogQ.wait()

    return result
210017
private synchronized void precomputeLogs(int len) {
    if(len <= ilogs.length) {
      return; // Probably done by another thread.
    }
    double[] logs = Arrays.copyOf(ilogs, len);
    for(int i = ilogs.length; i < len; i++) {
      logs[i] = FastMath.log1p(i);
    }
    this.ilogs = logs;
  }
294233
def __make_computation(self, processing_id: str, inputs: typing.List[typing.Tuple[DisplayItem.DisplayItem, typing.Optional[Graphics.Graphic]]], region_list_map: typing.Mapping[str, typing.List[Graphics.Graphic]]=None, parameters: typing.Mapping[str, typing.Any]=None) -> DataItem.DataItem:
        
        region_list_map = region_list_map or dict()

        parameters = parameters or dict()

        processing_descriptions = self._processing_descriptions
        processing_description = processing_descriptions[processing_id]

        # first process the sources in the description. match them to the inputs (which are data item/crop graphic tuples)
        src_dicts = processing_description.get("sources", list())
        assert len(inputs) == len(src_dicts)
        src_names = list()
        src_texts = list()
        src_labels = list()
        regions = list()
        region_map = dict()
        for i, (src_dict, input) in enumerate(zip(src_dicts, inputs)):

            display_item = input[0]
            data_item = display_item.data_items[0] if display_item and len(display_item.data_items) > 0 else None

            if not data_item:
                return None

            # each source can have a list of requirements, check through them
            requirements = src_dict.get("requirements", list())
            for requirement in requirements:
                requirement_type = requirement["type"]
                if requirement_type == "dimensionality":
                    min_dimension = requirement.get("min")
                    max_dimension = requirement.get("max")
                    dimensionality = len(data_item.dimensional_shape)
                    if min_dimension is not None and dimensionality < min_dimension:
                        return None
                    if max_dimension is not None and dimensionality > max_dimension:
                        return None
                if requirement_type == "is_sequence":
                    if not data_item.is_sequence:
                        return None

            src_name = src_dict["name"]
            src_label = src_dict["label"]
            use_display_data = src_dict.get("use_display_data", True)
            xdata_property = "display_xdata" if use_display_data else "xdata"
            if src_dict.get("croppable"):
                xdata_property = "cropped_" + xdata_property
            elif src_dict.get("use_filtered_data", False):
                xdata_property = "filtered_" + xdata_property
            src_text = "{}.{}".format(src_name, xdata_property)
            src_names.append(src_name)
            src_texts.append(src_text)
            src_labels.append(src_label)

            # each source can have a list of regions to be matched to arguments or created on the source
            region_dict_list = src_dict.get("regions", list())
            src_region_list = region_list_map.get(src_name, list())
            assert len(region_dict_list) == len(src_region_list)
            for region_dict, region in zip(region_dict_list, src_region_list):
                region_params = region_dict.get("params", dict())
                region_type = region_dict["type"]
                region_name = region_dict["name"]
                region_label = region_params.get("label")
                if region_type == "point":
                    if region:
                        assert isinstance(region, Graphics.PointGraphic)
                        point_region = region
                    else:
                        point_region = Graphics.PointGraphic()
                        for k, v in region_params.items():
                            setattr(point_region, k, v)
                        if display_item:
                            display_item.add_graphic(point_region)
                    regions.append((region_name, point_region, region_label))
                    region_map[region_name] = point_region
                elif region_type == "line":
                    if region:
                        assert isinstance(region, Graphics.LineProfileGraphic)
                        line_region = region
                    else:
                        line_region = Graphics.LineProfileGraphic()
                        line_region.start = 0.25, 0.25
                        line_region.end = 0.75, 0.75
                        for k, v in region_params.items():
                            setattr(line_region, k, v)
                        if display_item:
                            display_item.add_graphic(line_region)
                    regions.append((region_name, line_region, region_params.get("label")))
                    region_map[region_name] = line_region
                elif region_type == "rectangle":
                    if region:
                        assert isinstance(region, Graphics.RectangleGraphic)
                        rect_region = region
                    else:
                        rect_region = Graphics.RectangleGraphic()
                        rect_region.center = 0.5, 0.5
                        rect_region.size = 0.5, 0.5
                        for k, v in region_params.items():
                            setattr(rect_region, k, v)
                        if display_item:
                            display_item.add_graphic(rect_region)
                    regions.append((region_name, rect_region, region_params.get("label")))
                    region_map[region_name] = rect_region
                elif region_type == "ellipse":
                    if region:
                        assert isinstance(region, Graphics.EllipseGraphic)
                        ellipse_region = region
                    else:
                        ellipse_region = Graphics.RectangleGraphic()
                        ellipse_region.center = 0.5, 0.5
                        ellipse_region.size = 0.5, 0.5
                        for k, v in region_params.items():
                            setattr(ellipse_region, k, v)
                        if display_item:
                            display_item.add_graphic(ellipse_region)
                    regions.append((region_name, ellipse_region, region_params.get("label")))
                    region_map[region_name] = ellipse_region
                elif region_type == "spot":
                    if region:
                        assert isinstance(region, Graphics.SpotGraphic)
                        spot_region = region
                    else:
                        spot_region = Graphics.SpotGraphic()
                        spot_region.center = 0.25, 0.75
                        spot_region.size = 0.1, 0.1
                        for k, v in region_params.items():
                            setattr(spot_region, k, v)
                        if display_item:
                            display_item.add_graphic(spot_region)
                    regions.append((region_name, spot_region, region_params.get("label")))
                    region_map[region_name] = spot_region
                elif region_type == "interval":
                    if region:
                        assert isinstance(region, Graphics.IntervalGraphic)
                        interval_region = region
                    else:
                        interval_region = Graphics.IntervalGraphic()
                        for k, v in region_params.items():
                            setattr(interval_region, k, v)
                        if display_item:
                            display_item.add_graphic(interval_region)
                    regions.append((region_name, interval_region, region_params.get("label")))
                    region_map[region_name] = interval_region
                elif region_type == "channel":
                    if region:
                        assert isinstance(region, Graphics.ChannelGraphic)
                        channel_region = region
                    else:
                        channel_region = Graphics.ChannelGraphic()
                        for k, v in region_params.items():
                            setattr(channel_region, k, v)
                        if display_item:
                            display_item.add_graphic(channel_region)
                    regions.append((region_name, channel_region, region_params.get("label")))
                    region_map[region_name] = channel_region

        # now extract the script (full script) or expression (implied imports and return statement)
        script = processing_description.get("script")
        if not script:
            expression = processing_description.get("expression")
            if expression:
                script = Symbolic.xdata_expression(expression)
        assert script

        # construct the computation
        script = script.format(**dict(zip(src_names, src_texts)))
        computation = self.create_computation(script)
        computation.label = processing_description["title"]
        computation.processing_id = processing_id
        # process the data item inputs
        for src_dict, src_name, src_label, input in zip(src_dicts, src_names, src_labels, inputs):
            in_display_item = input[0]
            secondary_specifier = None
            if src_dict.get("croppable", False):
                secondary_specifier = self.get_object_specifier(input[1])
            display_data_channel = in_display_item.display_data_channel
            computation.create_object(src_name, self.get_object_specifier(display_data_channel), label=src_label, secondary_specifier=secondary_specifier)
        # process the regions
        for region_name, region, region_label in regions:
            computation.create_object(region_name, self.get_object_specifier(region), label=region_label)
        # next process the parameters
        for param_dict in processing_description.get("parameters", list()):
            parameter_value = parameters.get(param_dict["name"], param_dict["value"])
            computation.create_variable(param_dict["name"], param_dict["type"], parameter_value, value_default=param_dict.get("value_default"),
                                        value_min=param_dict.get("value_min"), value_max=param_dict.get("value_max"),
                                        control_type=param_dict.get("control_type"), label=param_dict["label"])

        data_item0 = inputs[0][0].data_items[0]
        new_data_item = DataItem.new_data_item()
        prefix = "{} of ".format(processing_description["title"])
        new_data_item.title = prefix + data_item0.title
        new_data_item.category = data_item0.category

        self.append_data_item(new_data_item)

        new_display_item = self.get_display_item_for_data_item(new_data_item)

        # next come the output regions that get created on the target itself
        new_regions = dict()
        for out_region_dict in processing_description.get("out_regions", list()):
            region_type = out_region_dict["type"]
            region_name = out_region_dict["name"]
            region_params = out_region_dict.get("params", dict())
            if region_type == "interval":
                interval_region = Graphics.IntervalGraphic()
                for k, v in region_params.items():
                    setattr(interval_region, k, v)
                new_display_item.add_graphic(interval_region)
                new_regions[region_name] = interval_region

        # now come the connections between the source and target
        for connection_dict in processing_description.get("connections", list()):
            connection_type = connection_dict["type"]
            connection_src = connection_dict["src"]
            connection_src_prop = connection_dict.get("src_prop")
            connection_dst = connection_dict["dst"]
            connection_dst_prop = connection_dict.get("dst_prop")
            if connection_type == "property":
                if connection_src == "display_data_channel":
                    # TODO: how to refer to the data_items? hardcode to data_item0 for now.
                    display_item0 = self.get_display_item_for_data_item(data_item0)
                    display_data_channel0 = display_item0.display_data_channel if display_item0 else None
                    connection = Connection.PropertyConnection(display_data_channel0, connection_src_prop, new_regions[connection_dst], connection_dst_prop, parent=new_data_item)
                    self.append_connection(connection)
            elif connection_type == "interval_list":
                connection = Connection.IntervalListConnection(new_display_item, region_map[connection_dst], parent=new_data_item)
                self.append_connection(connection)

        # save setting the computation until last to work around threaded clone/merge operation bug.
        # the bug is that setting the computation triggers the recompute to occur on a thread.
        # the recompute clones the data item and runs the operation. meanwhile this thread
        # updates the connection. now the recompute finishes and merges back the data item
        # which was cloned before the connection was established, effectively reversing the
        # update that matched the graphic interval to the slice interval on the display.
        # the result is that the slice interval on the display would get set to the default
        # value of the graphic interval. so don't actually update the computation until after
        # everything is configured. permanent solution would be to improve the clone/merge to
        # only update data that had been changed. alternative implementation would only track
        # changes to the data item and then apply them again to the original during merge.
        self.set_data_item_computation(new_data_item, computation)

        return new_data_item
868790
def _compute(self, arrays, dates, assets, mask):
        
        return super(NumExprFilter, self)._compute(
            arrays,
            dates,
            assets,
            mask,
        ) & mask
219979
def precompute(config, soups):
  """"""
  show_toc = config.get('show_toc', {})
  page = {}
  pantsrefs = precompute_pantsrefs(soups)
  for p, soup in soups.items():
    title = get_title(soup) or p
    page[p] = PrecomputedPageInfo(title=title, show_toc=show_toc.get(p, True))
  return Precomputed(page=page, pantsref=pantsrefs)
490586
def run_matrix_in_parallel(self, process_data):
        """"""
        worker_data = [{'matrix': entry, 'pipeline': process_data.pipeline,
                        'model': process_data.model, 'options': process_data.options,
                        'hooks': process_data.hooks} for entry in self.matrix
                       if Matrix.can_process_matrix(entry, process_data.options.matrix_tags)]
        output = []
        success = True
        with closing(multiprocessing.Pool(multiprocessing.cpu_count())) as pool:
            for result in pool.map(matrix_worker, worker_data):
                output += result['output']
                if not result['success']:
                    success = False
        return {'success': success, 'output': output}