Make predictions on a keyed dstream.
        Returns a transformed dstream object.
497412
def predictOnValues(self, dstream):
        
        self._validate(dstream)
        return dstream.mapValues(lambda x: self._model.predict(x))
443890
def get_prediction(self, features=None, tag=None, namespaces=None):
        """"""
        if features is not None:
            namespace = Namespace(features=features)
            self.add_namespace(namespace)
        result = self.send_example(tag=tag, namespaces=namespaces)
        return result
9323
def predictions(self):
        """"""
        for prediction in self.api.predictions(vid=self.vid)['prd']:
            pobj = Prediction.fromapi(self.api, prediction)
            pobj._busobj = self
            yield pobj
1343706
def from_stream(cls, stream):
        
        px_width, px_height = cls._dimensions_from_stream(stream)
        return cls(px_width, px_height, 72, 72)
585615
@Override
    public Map<String, Double> predict(Tuple predict) {
        KNNEngine engine = new KNNEngine(predict, trainingData, k);

        if (mode == 1) {
            engine.getDistance(engine.chebyshevDistance);
        } else if (mode == 2) {
            engine.getDistance(engine.manhattanDistance);
        } else {
            engine.getDistance(engine.euclideanDistance);
        }

        predict.label = engine.getResult();

        Map<String, Double> outputMap = new ConcurrentHashMap<>();
        trainingData.parallelStream().forEach(x -> outputMap.put(String.valueOf(x.id), (Double) x.getExtra().get(DISTANCE)));

        return outputMap;
    }
352997
private Collection<Integer> transform(StreamTransformation<?> transform) {

		if (alreadyTransformed.containsKey(transform)) {
			return alreadyTransformed.get(transform);
		}

		LOG.debug("Transforming " + transform);

		if (transform.getMaxParallelism() <= 0) {

			// if the max parallelism hasn't been set, then first use the job wide max parallelism
			// from the ExecutionConfig.
			int globalMaxParallelismFromConfig = env.getConfig().getMaxParallelism();
			if (globalMaxParallelismFromConfig > 0) {
				transform.setMaxParallelism(globalMaxParallelismFromConfig);
			}
		}

		// call at least once to trigger exceptions about MissingTypeInfo
		transform.getOutputType();

		Collection<Integer> transformedIds;
		if (transform instanceof OneInputTransformation<?, ?>) {
			transformedIds = transformOneInputTransform((OneInputTransformation<?, ?>) transform);
		} else if (transform instanceof TwoInputTransformation<?, ?, ?>) {
			transformedIds = transformTwoInputTransform((TwoInputTransformation<?, ?, ?>) transform);
		} else if (transform instanceof SourceTransformation<?>) {
			transformedIds = transformSource((SourceTransformation<?>) transform);
		} else if (transform instanceof SinkTransformation<?>) {
			transformedIds = transformSink((SinkTransformation<?>) transform);
		} else if (transform instanceof UnionTransformation<?>) {
			transformedIds = transformUnion((UnionTransformation<?>) transform);
		} else if (transform instanceof SplitTransformation<?>) {
			transformedIds = transformSplit((SplitTransformation<?>) transform);
		} else if (transform instanceof SelectTransformation<?>) {
			transformedIds = transformSelect((SelectTransformation<?>) transform);
		} else if (transform instanceof FeedbackTransformation<?>) {
			transformedIds = transformFeedback((FeedbackTransformation<?>) transform);
		} else if (transform instanceof CoFeedbackTransformation<?>) {
			transformedIds = transformCoFeedback((CoFeedbackTransformation<?>) transform);
		} else if (transform instanceof PartitionTransformation<?>) {
			transformedIds = transformPartition((PartitionTransformation<?>) transform);
		} else if (transform instanceof SideOutputTransformation<?>) {
			transformedIds = transformSideOutput((SideOutputTransformation<?>) transform);
		} else {
			throw new IllegalStateException("Unknown transformation: " + transform);
		}

		// need this check because the iterate transformation adds itself before
		// transforming the feedback edges
		if (!alreadyTransformed.containsKey(transform)) {
			alreadyTransformed.put(transform, transformedIds);
		}

		if (transform.getBufferTimeout() >= 0) {
			streamGraph.setBufferTimeout(transform.getId(), transform.getBufferTimeout());
		}
		if (transform.getUid() != null) {
			streamGraph.setTransformationUID(transform.getId(), transform.getUid());
		}
		if (transform.getUserProvidedNodeHash() != null) {
			streamGraph.setTransformationUserHash(transform.getId(), transform.getUserProvidedNodeHash());
		}

		if (!streamGraph.getExecutionConfig().hasAutoGeneratedUIDsEnabled()) {
			if (transform.getUserProvidedNodeHash() == null && transform.getUid() == null) {
				throw new IllegalStateException("Auto generated UIDs have been disabled " +
					"but no UID or hash has been assigned to operator " + transform.getName());
			}
		}

		if (transform.getMinResources() != null && transform.getPreferredResources() != null) {
			streamGraph.setResources(transform.getId(), transform.getMinResources(), transform.getPreferredResources());
		}

		return transformedIds;
	}
15715
def gen_ldm(src, dst):
        
        return ReilBuilder.build(ReilMnemonic.LDM, src, ReilEmptyOperand(), dst)
569633
def load_stream(self, stream):
        
        batches = super(ArrowStreamPandasSerializer, self).load_stream(stream)
        import pyarrow as pa
        for batch in batches:
            yield [self.arrow_to_pandas(c) for c in pa.Table.from_batches([batch]).itercolumns()]
548216
def postprocessor(prediction):
    """"""
    prediction = prediction.data.numpy()[0]
    top_predictions = prediction.argsort()[-3:][::-1]
    return [labels[prediction] for prediction in top_predictions]
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)
652401
def predictions(self):
        
        preds = javabridge.get_collection_wrapper(
            javabridge.call(self.jobject, "predictions", "()Ljava/util/ArrayList;"))
        if self.discard_predictions:
            result = None
        else:
            result = []
            for pred in preds:
                if is_instance_of(pred, "weka.classifiers.evaluation.NominalPrediction"):
                    result.append(NominalPrediction(pred))
                elif is_instance_of(pred, "weka.classifiers.evaluation.NumericPrediction"):
                    result.append(NumericPrediction(pred))
                else:
                    result.append(Prediction(pred))
        return result
1369045
def compute_transformed(context):
    """"""

    if context._._.transformed_key is not None:
        transformed_key = context._._transformed_key
    else:
        transformed_key = aes_kdf(
            context._.header.value.dynamic_header.transform_seed.data,
            context._.header.value.dynamic_header.transform_rounds.data,
            password=context._._.password,
            keyfile=context._._.keyfile
        )

    return transformed_key
464161
def _read_channel(channel, stream, start, duration):
    
    channel_type = lalframe.FrStreamGetTimeSeriesType(channel, stream)
    read_func = _fr_type_map[channel_type][0]
    d_type = _fr_type_map[channel_type][1]
    data = read_func(stream, channel, start, duration, 0)
    return TimeSeries(data.data.data, delta_t=data.deltaT, epoch=start,
                      dtype=d_type)
128814
def predict(self, input):
        

        assert self._mode == MpsGraphMode.Inference
        assert input.shape == self._ishape

        input_array = MpsFloatArray(input)
        result_handle = _ctypes.c_void_p()
        status_code = self._LIB.TCMPSPredictGraph(
            self.handle, input_array.handle, _ctypes.byref(result_handle))

        assert status_code == 0, "Error calling TCMPSPredictGraph"
        assert result_handle, "TCMPSPredictGraph unexpectedly returned NULL pointer"

        result = MpsFloatArray(result_handle)
        assert result.shape() == self._oshape

        return result
290808
def _mapped_std_streams(lookup_paths, streams=('stdin', 'stdout', 'stderr')):
    """"""
    # FIXME add device number too
    standard_inos = {}
    for stream in streams:
        try:
            stream_stat = os.fstat(getattr(sys, stream).fileno())
            key = stream_stat.st_dev, stream_stat.st_ino
            standard_inos[key] = stream
        except Exception:  # FIXME UnsupportedOperation
            pass
        # FIXME if not getattr(sys, stream).istty()

    def stream_inos(paths):
        """Yield tuples with stats and path."""
        for path in paths:
            try:
                stat = os.stat(path)
                key = (stat.st_dev, stat.st_ino)
                if key in standard_inos:
                    yield standard_inos[key], path
            except FileNotFoundError:  # pragma: no cover
                pass

    return dict(stream_inos(lookup_paths)) if standard_inos else {}
920682
def mutate_stream (instream, outstream):
    """"""

    chunk = None
    key = None
    data = None
    misclines = []

    for fullline in instream:
        line = fullline.split ('#', 1)[0]

        m = sectionre.match (line)
        if m is not None:
            # New chunk
            if chunk is not None:
                if key is not None:
                    chunk.data.set_one (key, data.strip ().decode ('utf8'))
                    key = data = None
                yield chunk
                chunk.emit (outstream)

            chunk = FileChunk ()
            for miscline in misclines:
                chunk._addLine (miscline, None)
            misclines = []
            chunk.data.section = m.group (1)
            chunk._addLine (fullline, None)
            continue

        if len (line.strip ()) == 0:
            if key is not None:
                chunk.data.set_one (key, data.strip ().decode ('utf8'))
                key = data = None
            if chunk is not None:
                chunk._addLine (fullline, None)
            else:
                misclines.append (fullline)
            continue

        m = escre.match (fullline)
        if m is not None:
            if chunk is None:
                raise InifileError ('key seen without section!')
            if key is not None:
                chunk.data.set_one (key, data.strip ().decode ('utf8'))
            key = m.group (1)
            data = m.group (2).replace (r'\"', '"').replace (r'\n', '\n').replace (r'\\', '\\')
            chunk.data.set_one (key, data.decode ('utf8'))
            chunk._addLine (fullline, key)
            key = data = None
            continue

        m = keyre.match (line)
        if m is not None:
            if chunk is None:
                raise InifileError ('key seen without section!')
            if key is not None:
                chunk.data.set_one (key, data.strip ().decode ('utf8'))
            key = m.group (1)
            data = m.group (2)
            if not data[-1].isspace ():
                data += ' '
            chunk._addLine (fullline, key)
            continue

        if line[0].isspace () and key is not None:
            data += line.strip () + ' '
            chunk._addLine (fullline, key)
            continue

        raise InifileError ('unparsable line: ' + line[:-1])

    if chunk is not None:
        if key is not None:
            chunk.data.set_one (key, data.strip ().decode ('utf8'))
        yield chunk
        chunk.emit (outstream)
596751
def _handle_predictions(self):
        """"""
        while self.running:
            chunk = self.stream.read(self.chunk_size)

            if self.is_paused:
                continue

            prob = self.engine.get_prediction(chunk)
            self.on_prediction(prob)
            if self.detector.update(prob):
                self.on_activation()