text:
package org.apache.kafka.test;

import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.consumer.OffsetResetStrategy;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.metrics.Metrics;
import org.apache.kafka.common.record.TimestampType;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.utils.MockTime;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.StreamsMetrics;
import org.apache.kafka.streams.processor.StateStore;
import org.apache.kafka.streams.processor.TaskId;
import org.apache.kafka.streams.processor.TopologyBuilder;
import org.apache.kafka.streams.processor.internals.GlobalProcessorContextImpl;
import org.apache.kafka.streams.processor.internals.GlobalStateManagerImpl;
import org.apache.kafka.streams.processor.internals.GlobalStateUpdateTask;
import org.apache.kafka.streams.processor.internals.InternalProcessorContext;
import org.apache.kafka.streams.processor.internals.MockStreamsMetrics;
import org.apache.kafka.streams.processor.internals.ProcessorContextImpl;
import org.apache.kafka.streams.processor.internals.ProcessorRecordContext;
import org.apache.kafka.streams.processor.internals.ProcessorTopology;
import org.apache.kafka.streams.processor.internals.StateDirectory;
import org.apache.kafka.streams.processor.internals.StoreChangelogReader;
import org.apache.kafka.streams.processor.internals.StreamTask;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.internals.ThreadCache;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

/**
 * This class makes it easier to write tests to verify the behavior of topologies created with a {@link TopologyBuilder}.
 * You can test simple topologies that have a single processor, or very complex topologies that have multiple sources, processors,
 * and sinks. And because it starts with a {@link TopologyBuilder}, you can create topologies specific to your tests or you
 * can use and test code you already have that uses a builder to create topologies. Best of all, the class works without a real
 * Kafka broker, so the tests execute very quickly with very little overhead.
 *

 * Using the ProcessorTopologyTestDriver in tests is easy: simply instantiate the driver with a {@link StreamsConfig} and a
 * TopologyBuilder, use the driver to supply an input message to the topology, and then use the driver to read and verify any
 * messages output by the topology.
 *

 * Although the driver doesn't use a real Kafka broker, it does simulate Kafka {@link org.apache.kafka.clients.consumer.Consumer}s
 * and {@link org.apache.kafka.clients.producer.Producer}s that read and write raw {@code byte[]} messages. You can either deal
 * with messages that have {@code byte[]} keys and values, or you can supply the {@link Serializer}s and {@link Deserializer}s
 * that the driver can use to convert the keys and values into objects.
 *
 *
Driver setup

 *

 * In order to create a ProcessorTopologyTestDriver instance, you need a TopologyBuilder and a {@link StreamsConfig}. The
 * configuration needs to be representative of what you'd supply to the real topology, so that means including several key
 * properties. For example, the following code fragment creates a configuration that specifies a local Kafka broker list
 * (which is needed but not used), a timestamp extractor, and default serializers and deserializers for string keys and values:
 *
 *

 * StringSerializer strSerializer = new StringSerializer();
 * StringDeserializer strDeserializer = new StringDeserializer();
 * Properties props = new Properties();
 * props.setProperty(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9091");
 * props.setProperty(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, CustomTimestampExtractor.class.getName());
 * props.setProperty(StreamsConfig.KEY_SERIALIZER_CLASS_CONFIG, strSerializer.getClass().getName());
 * props.setProperty(StreamsConfig.KEY_DESERIALIZER_CLASS_CONFIG, strDeserializer.getClass().getName());
 * props.setProperty(StreamsConfig.VALUE_SERIALIZER_CLASS_CONFIG, strSerializer.getClass().getName());
 * props.setProperty(StreamsConfig.VALUE_DESERIALIZER_CLASS_CONFIG, strDeserializer.getClass().getName());
 * StreamsConfig config = new StreamsConfig(props);
 * TopologyBuilder builder = ...
 * ProcessorTopologyTestDriver driver = new ProcessorTopologyTestDriver(config, builder);
 *

 *
 *
Processing messages

 *

 * Your test can supply new input records on any of the topics that the topology's sources consume. Here's an example of an
 * input message on the topic named {@code input-topic}:
 *
 *

 * driver.process("input-topic", "key1", "value1", strSerializer, strSerializer);
 *

 *
 * Immediately, the driver will pass the input message through to the appropriate source that consumes the named topic,
 * and will invoke the processor(s) downstream of the source. If your topology's processors forward messages to sinks,
 * your test can then consume these output messages to verify they match the expected outcome. For example, if our topology
 * should have generated 2 messages on {@code output-topic-1} and 1 message on {@code output-topic-2}, then our test can
 * obtain these messages using the {@link #readOutput(String, Deserializer, Deserializer)} method:
 *
 *

 * ProducerRecord<String, String> record1 = driver.readOutput("output-topic-1", strDeserializer, strDeserializer);
 * ProducerRecord<String, String> record2 = driver.readOutput("output-topic-1", strDeserializer, strDeserializer);
 * ProducerRecord<String, String> record3 = driver.readOutput("output-topic-2", strDeserializer, strDeserializer);
 *

 *
 * Again, our example topology generates messages with string keys and values, so we supply our string deserializer instance
 * for use on both the keys and values. Your test logic can then verify whether these output records are correct.
 *

 * Finally, when completed, make sure your tests {@link #close()} the driver to release all resources and
 * {@link org.apache.kafka.streams.processor.Processor}s.
 *
 *
Processor state

 *

 * Some processors use Kafka {@link StateStore state storage}, so this driver class provides the {@link #getStateStore(String)}
 * and {@link #getKeyValueStore(String)} methods so that your tests can check the underlying state store(s) used by your
 * topology's processors. In our previous example, after we supplied a single input message and checked the three output messages,
 * our test could also check the key value store to verify the processor correctly added, removed, or updated internal state.
 * Or, our test might have pre-populated some state before submitting the input message, and verified afterward that the
 * processor(s) correctly updated the state.
 */
public class ProcessorTopologyTestDriver {

    private final static String APPLICATION_ID = "test-driver-application";
    private final static int PARTITION_ID = 0;
    private final static TaskId TASK_ID = new TaskId(0, PARTITION_ID);

    private final ProcessorTopology topology;
    private final MockProducer<byte[], byte[]> producer;
    private final Map<String, TopicPartition> partitionsByTopic = new HashMap<>();
    private final Map<TopicPartition, AtomicLong> offsetsByTopicPartition = new HashMap<>();
    private final Map<String, Queue<ProducerRecord<byte[], byte[]>>> outputRecordsByTopic = new HashMap<>();
    private final Set<String> internalTopics = new HashSet<>();
    private final Map<String, TopicPartition> globalPartitionsByTopic = new HashMap<>();
    private StreamTask task;
    private GlobalStateUpdateTask globalStateTask;

    /**
     * Create a new test driver instance.
     * @param config the stream configuration for the topology
     * @param builder the topology builder that will be used to create the topology instance
     */
    public ProcessorTopologyTestDriver(final StreamsConfig config,
                                       final TopologyBuilder builder) {
        topology = builder.setApplicationId(APPLICATION_ID).build(null);
        final ProcessorTopology globalTopology  = builder.buildGlobalStateTopology();

        // Set up the consumer and producer ...
        final Consumer<byte[], byte[]> consumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST);
        final Serializer<byte[]> bytesSerializer = new ByteArraySerializer();
        producer = new MockProducer<byte[], byte[]>(true, bytesSerializer, bytesSerializer) {
            @Override
            public List<PartitionInfo> partitionsFor(final String topic) {
                return Collections.singletonList(new PartitionInfo(topic, PARTITION_ID, null, null, null));
            }
        };

        // Identify internal topics for forwarding in process ...
        for (final TopologyBuilder.TopicsInfo topicsInfo : builder.topicGroups().values()) {
            internalTopics.addAll(topicsInfo.repartitionSourceTopics.keySet());
        }

        // Set up all of the topic+partition information and subscribe the consumer to each ...
        for (final String topic : topology.sourceTopics()) {
            final TopicPartition tp = new TopicPartition(topic, PARTITION_ID);
            partitionsByTopic.put(topic, tp);
            offsetsByTopicPartition.put(tp, new AtomicLong());
        }

        consumer.assign(offsetsByTopicPartition.keySet());

        final StateDirectory stateDirectory = new StateDirectory(APPLICATION_ID, TestUtils.tempDirectory().getPath(), Time.SYSTEM);
        final StreamsMetrics streamsMetrics = new MockStreamsMetrics(new Metrics());
        final ThreadCache cache = new ThreadCache("mock", 1024 * 1024, streamsMetrics);

        if (globalTopology != null) {
            final MockConsumer<byte[], byte[]> globalConsumer = createGlobalConsumer();
            for (final String topicName : globalTopology.sourceTopics()) {
                final List<PartitionInfo> partitionInfos = new ArrayList<>();
                partitionInfos.add(new PartitionInfo(topicName, 1, null, null, null));
                globalConsumer.updatePartitions(topicName, partitionInfos);
                final TopicPartition partition = new TopicPartition(topicName, 1);
                globalConsumer.updateEndOffsets(Collections.singletonMap(partition, 0L));
                globalPartitionsByTopic.put(topicName, partition);
                offsetsByTopicPartition.put(partition, new AtomicLong());
            }
            final GlobalStateManagerImpl stateManager = new GlobalStateManagerImpl(globalTopology, globalConsumer, stateDirectory);
            globalStateTask = new GlobalStateUpdateTask(globalTopology,
                                                        new GlobalProcessorContextImpl(config, stateManager, streamsMetrics, cache),
                                                        stateManager
            );
            globalStateTask.initialize();
        }

        if (!partitionsByTopic.isEmpty()) {
            task = new StreamTask(TASK_ID,
                                  APPLICATION_ID,
                                  partitionsByTopic.values(),
                                  topology,
                                  consumer,
                                  new StoreChangelogReader(
                                      createRestoreConsumer(topology.storeToChangelogTopic()),
                                      Time.SYSTEM,
                                      5000),
                                  config,
                                  streamsMetrics, stateDirectory,
                                  cache,
                                  new MockTime(),
                                  producer);
        }
    }

    /**
     * Send an input message with the given key, value and timestamp on the specified topic to the topology, and then commit the messages.
     *
     * @param topicName the name of the topic on which the message is to be sent
     * @param key the raw message key
     * @param value the raw message value
     * @param timestamp the raw message timestamp
     */
    private void process(final String topicName,
                         final byte[] key,
                         final byte[] value,
                         final long timestamp) {

        final TopicPartition tp = partitionsByTopic.get(topicName);
        if (tp != null) {
            // Add the record ...
            final long offset = offsetsByTopicPartition.get(tp).incrementAndGet();
            task.addRecords(tp, records(new ConsumerRecord<>(tp.topic(), tp.partition(), offset, timestamp, TimestampType.CREATE_TIME, 0L, 0, 0, key, value)));
            producer.clear();

            // Process the record ...
            task.process();
            ((InternalProcessorContext) task.context()).setRecordContext(new ProcessorRecordContext(timestamp, offset, tp.partition(), topicName));
            task.commit();

            // Capture all the records sent to the producer ...
            for (final ProducerRecord<byte[], byte[]> record : producer.history()) {
                Queue<ProducerRecord<byte[], byte[]>> outputRecords = outputRecordsByTopic.get(record.topic());
                if (outputRecords == null) {
                    outputRecords = new LinkedList<>();
                    outputRecordsByTopic.put(record.topic(), outputRecords);
                }
                outputRecords.add(record);

                // Forward back into the topology if the produced record is to an internal or a source topic ...
                if (internalTopics.contains(record.topic()) || topology.sourceTopics().contains(record.topic())) {
                    process(record.topic(), record.key(), record.value(), record.timestamp());
                }
            }
        } else {
            final TopicPartition global = globalPartitionsByTopic.get(topicName);
            if (global == null) {
                throw new IllegalArgumentException("Unexpected topic: " + topicName);
            }
            final long offset = offsetsByTopicPartition.get(global).incrementAndGet();
            globalStateTask.update(new ConsumerRecord<>(global.topic(), global.partition(), offset, timestamp, TimestampType.CREATE_TIME, 0L, 0, 0, key, value));
            globalStateTask.flushState();
        }
    }

    /**
     * Send an input message with the given key and value on the specified topic to the topology.
     *
     * @param topicName the name of the topic on which the message is to be sent
     * @param key the raw message key
     * @param value the raw message value
     */
    public void process(final String topicName,
                        final byte[] key,
                        final byte[] value) {
        process(topicName, key, value, 0L);
    }

    /**
     * Send an input message with the given key and value on the specified topic to the topology.
     *
     * @param topicName the name of the topic on which the message is to be sent
     * @param key the raw message key
     * @param value the raw message value
     * @param keySerializer the serializer for the key
     * @param valueSerializer the serializer for the value
     */
    public <K, V> void process(final String topicName,
                               final K key,
                               final V value,
                               final Serializer<K> keySerializer,
                               final Serializer<V> valueSerializer) {
        process(topicName, keySerializer.serialize(topicName, key), valueSerializer.serialize(topicName, value));
    }

    /**
     * Read the next record from the given topic. These records were output by the topology during the previous calls to
     * {@link #process(String, byte[], byte[])}.
     *
     * @param topic the name of the topic
     * @return the next record on that topic, or null if there is no record available
     */
    public ProducerRecord<byte[], byte[]> readOutput(final String topic) {
        final Queue<ProducerRecord<byte[], byte[]>> outputRecords = outputRecordsByTopic.get(topic);
        if (outputRecords == null) {
            return null;
        }
        return outputRecords.poll();
    }

    /**
     * Read the next record from the given topic. These records were output by the topology during the previous calls to
     * {@link #process(String, byte[], byte[])}.
     *
     * @param topic the name of the topic
     * @param keyDeserializer the deserializer for the key type
     * @param valueDeserializer the deserializer for the value type
     * @return the next record on that topic, or null if there is no record available
     */
    public <K, V> ProducerRecord<K, V> readOutput(final String topic,
                                                  final Deserializer<K> keyDeserializer,
                                                  final Deserializer<V> valueDeserializer) {
        final ProducerRecord<byte[], byte[]> record = readOutput(topic);
        if (record == null) {
            return null;
        }
        final K key = keyDeserializer.deserialize(record.topic(), record.key());
        final V value = valueDeserializer.deserialize(record.topic(), record.value());
        return new ProducerRecord<>(record.topic(), record.partition(), record.timestamp(), key, value);
    }

    private Iterable<ConsumerRecord<byte[], byte[]>> records(final ConsumerRecord<byte[], byte[]> record) {
        return Collections.singleton(record);
    }

    /**
     * Get the {@link StateStore} with the given name. The name should have been supplied via
     * {@link #ProcessorTopologyTestDriver(StreamsConfig, TopologyBuilder) this object's constructor}, and is
     * presumed to be used by a Processor within the topology.
     *

     * This is often useful in test cases to pre-populate the store before the test case instructs the topology to
     * {@link #process(String, byte[], byte[]) process an input message}, and/or to check the store afterward.
     *
     * @param name the name of the store
     * @return the state store, or null if no store has been registered with the given name
     * @see #getKeyValueStore(String)
     */
    public StateStore getStateStore(final String name) {
        return ((ProcessorContextImpl) task.context()).getStateMgr().getStore(name);
    }

    /**
     * Get the {@link KeyValueStore} with the given name. The name should have been supplied via
     * {@link #ProcessorTopologyTestDriver(StreamsConfig, TopologyBuilder) this object's constructor}, and is
     * presumed to be used by a Processor within the topology.
     *

     * This is often useful in test cases to pre-populate the store before the test case instructs the topology to
     * {@link #process(String, byte[], byte[]) process an input message}, and/or to check the store afterward.
     *

     *
     * @param name the name of the store
     * @return the key value store, or null if no {@link KeyValueStore} has been registered with the given name
     * @see #getStateStore(String)
     */
    @SuppressWarnings("unchecked")
    public <K, V> KeyValueStore<K, V> getKeyValueStore(final String name) {
        final StateStore store = getStateStore(name);
        return store instanceof KeyValueStore ? (KeyValueStore<K, V>) getStateStore(name) : null;
    }

    /**
     * Close the driver, its topology, and all processors.
     */
    public void close() {
        if (task != null) {
            task.close(true);
        }
        if (globalStateTask != null) {
            try {
                globalStateTask.close();
            } catch (final IOException e) {
                // ignore
            }
        }
    }

    /**
     * Utility method that creates the {@link MockConsumer} used for restoring state, which should not be done by this
     * driver object unless this method is overwritten with a functional consumer.
     *
     * @param storeToChangelogTopic the map of the names of the stores to the changelog topics
     * @return the mock consumer; never null
     */
    private MockConsumer<byte[], byte[]> createRestoreConsumer(final Map<String, String> storeToChangelogTopic) {
        final MockConsumer<byte[], byte[]> consumer = new MockConsumer<byte[], byte[]>(OffsetResetStrategy.LATEST) {
            @Override
            public synchronized void seekToEnd(final Collection<TopicPartition> partitions) {}

            @Override
            public synchronized void seekToBeginning(final Collection<TopicPartition> partitions) {}

            @Override
            public synchronized long position(final TopicPartition partition) {
                return 0L;
            }
        };
        // For each store ...
        for (final Map.Entry<String, String> storeAndTopic: storeToChangelogTopic.entrySet()) {
            final String topicName = storeAndTopic.getValue();
            // Set up the restore-state topic ...
            // consumer.subscribe(new TopicPartition(topicName, 1));
            // Set up the partition that matches the ID (which is what ProcessorStateManager expects) ...
            final List<PartitionInfo> partitionInfos = new ArrayList<>();
            partitionInfos.add(new PartitionInfo(topicName, PARTITION_ID, null, null, null));
            consumer.updatePartitions(topicName, partitionInfos);
            consumer.updateEndOffsets(Collections.singletonMap(new TopicPartition(topicName, PARTITION_ID), 0L));
        }
        return consumer;
    }

    private MockConsumer<byte[], byte[]> createGlobalConsumer() {
        return new MockConsumer<byte[], byte[]>(OffsetResetStrategy.LATEST) {
            @Override
            public synchronized void seekToEnd(final Collection<TopicPartition> partitions) {}

            @Override
            public synchronized void seekToBeginning(final Collection<TopicPartition> partitions) {}

            @Override
            public synchronized long position(final TopicPartition partition) {
                return 0L;
            }
        };
    }

}


text:
function [x,zo,xs]=estnoisem(yf,tz,pp)
%ESTNOISEM - estimate noise spectrum using minimum statistics
%
% Usage:    ninc=round(0.016*fs);   % frame increment [fs=sample frequency]
%           ovf=2;                  % overlap factor
%           f=rfft(enframe(s,hanning(ovf*ninc,'periodic'),ninc),ovf*ninc,2);
%           f=f.*conj(f);           % convert to power spectrum
%           x=estnoisem(f,ninc/fs); % estimate the noise power spectrum
%
% Inputs:
%   yf      input power spectra (one row per frame)
%   tz      frame increment in seconds
%           Alternatively, the input state from a previous call (see below)
%   pp      algorithm parameters [optional]
%
% Outputs:
%   x       estimated noise power spectra (one row per frame)
%   zo      output state
%   xs      estimated std error of x (one row per frame)
%           xs seems often to be an underestimate by a factor of 2 or 3
%
% The algorithm parameters are defined in reference [1] from which equation
% numbers are given in parentheses. They are as follows:
%
%        pp.taca      % (11): smoothing time constant for alpha_c [0.0449 seconds]
%        pp.tamax     % (3): max smoothing time constant [0.392 seconds]
%        pp.taminh    % (3): min smoothing time constant (upper limit) [0.0133 seconds]
%        pp.tpfall    % (12): time constant for P to fall [0.064 seconds]
%        pp.tbmax     % (20): max smoothing time constant [0.0717 seconds]
%        pp.qeqmin    % (23): minimum value of Qeq [2]
%        pp.qeqmax    % max value of Qeq per frame [14]
%        pp.av        % (23)+13 lines: fudge factor for bc calculation  [2.12]
%        pp.td        % time to take minimum over [1.536 seconds]
%        pp.nu        % number of subwindows to use [3]
%        pp.qith      % Q-inverse thresholds to select maximum noise slope [0.03 0.05 0.06 Inf ]
%        pp.nsmdb     % corresponding noise slope thresholds in dB/second   [47 31.4 15.7 4.1]
%
% Example use:      y=enframe(s,w,ni);                  % divide speech signal s(n) into
%                                                       % overlapping frames using window w(n)
%                   yf=rfft(y,nf,2);                    % take fourier transform
%                   dp=estnoisem(yf.*conj(yf),tinc);    % estimate the noise
%
% If convenient, you can call estnoisem in chunks of arbitrary size. Thus the following are equivalent:
%
%                   (a) dp=estnoisem(yp(1:300),tinc);
%
%                   (b) [dp(1:100),z]=estnoisem(yp(1:100),tinc);
%                       [dp(101:200),z]=estnoisem(yp(101:200),z);
%                       [dp(201:300),z]=estnoisem(yp(201:300),z);

% This is intended to be a precise implementation of [1] with Table III
% replaced by the updated table 5 from [2]. The only deliberate algorithm
% change is the introduction of a minimum value for 1/Qeq in equation (23).
% This change only affects the first few frames and improves the
% convergence of the algorithm. A minor improveemnt was reported in [3] but
% this has not yet been included.
%
% Refs:
%    [1] Rainer Martin.
%        Noise power spectral density estimation based on optimal smoothing and minimum statistics.
%        IEEE Trans. Speech and Audio Processing, 9(5):504-512, July 2001.
%    [2] Rainer Martin.
%        Bias compensation methods for minimum statistics noise power spectral density estimation
%        Signal Processing, 2006, 86, 1215-1229
%    [3] Dirk Mauler and Rainer Martin
%        Noise power spectral density estimation on highly correlated data
%        Proc IWAENC, 2006

%	   Copyright (C) Mike Brookes 2008
%      Version: $Id: estnoisem.m 1718 2012-03-31 16:40:41Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[nr,nrf]=size(yf);          % number of frames and freq bins
x=zeros(nr,nrf);            % initialize output arrays
xs=zeros(nr,nrf);           % will hold std error in the future
if isempty(yf) && isstruct(tz)             % no real data
    zo=tz;              % just keep the same state
else
    if isstruct(tz)       % take parameters from a previous call
        nrcum=tz.nrcum;
        p=tz.p;          % smoothed power spectrum
        ac=tz.ac;               % correction factor (9)
        sn2=tz.sn2;              % estimated noise power
        pb=tz.pb;               % smoothed noisy speech power (20)
        pb2=tz.pb2;
        pminu=tz.pminu;
        actmin=tz.actmin;   % Running minimum estimate
        actminsub=tz.actminsub;           % sub-window minimum estimate
        subwc=tz.subwc;                   % force a buffer switch on first loop
        actbuf=tz.actbuf;  % buffer to store subwindow minima
        ibuf=tz.ibuf;
        lminflag=tz.lminflag;      % flag to remember local minimum
        tinc=tz.tinc;     % frame increment
        qq=tz.qq;         % parameter structure
    else
        tinc = tz;          % second argument is frame increment
        nrcum=0;            % no frames so far
        % default algorithm constants

        qq.taca=0.0449;    % smoothing time constant for alpha_c = -tinc/log(0.7) in equ (11)
        qq.tamax=0.392;    % max smoothing time constant in (3) = -tinc/log(0.96)
        qq.taminh=0.0133;    % min smoothing time constant (upper limit) in (3) = -tinc/log(0.3)
        qq.tpfall=0.064;   % time constant for P to fall (12)
        qq.tbmax=0.0717;   % max smoothing time constant in (20) = -tinc/log(0.8)
        qq.qeqmin=2;       % minimum value of Qeq (23)
        qq.qeqmax=14;      % max value of Qeq per frame
        qq.av=2.12;             % fudge factor for bc calculation (23 + 13 lines)
        qq.td=1.536;       % time to take minimum over
        qq.nu=8;           % number of subwindows
        qq.qith=[0.03 0.05 0.06 Inf]; % noise slope thresholds in dB/s
        qq.nsmdb=[47 31.4 15.7 4.1];

        if nargin>=3 && ~isempty(pp)
            qqn=fieldnames(qq);
            for i=1:length(qqn)
                if isfield(pp,qqn{i})
                    qq.(qqn{i})=pp.(qqn{i});
                end
            end
        end
    end

    % unpack parameter structure

    taca=qq.taca;    % smoothing time constant for alpha_c = -tinc/log(0.7) in equ (11)
    tamax=qq.tamax;    % max smoothing time constant in (3) = -tinc/log(0.96)
    taminh=qq.taminh;    % min smoothing time constant (upper limit) in (3) = -tinc/log(0.3)
    tpfall=qq.tpfall;   % time constant for P to fall (12)
    tbmax=qq.tbmax;   % max smoothing time constant in (20) = -tinc/log(0.8)
    qeqmin=qq.qeqmin;       % minimum value of Qeq (23)
    qeqmax=qq.qeqmax;      % max value of Qeq per frame
    av=qq.av;             % fudge factor for bc calculation (23 + 13 lines)
    td=qq.td;       % time to take minimum over
    nu=qq.nu;           % number of subwindows
    qith=qq.qith; % noise slope thresholds in dB/s
    nsmdb=qq.nsmdb;   % maximum permitted +ve noise slope in dB/s

    % derived algorithm constants

    aca=exp(-tinc/taca); % smoothing constant for alpha_c in equ (11) = 0.7
    acmax=aca;          % min value of alpha_c = 0.7 in equ (11) also = 0.7
    amax=exp(-tinc/tamax); % max smoothing constant in (3) = 0.96
    aminh=exp(-tinc/taminh); % min smoothing constant (upper limit) in (3) = 0.3
    bmax=exp(-tinc/tbmax); % max smoothing constant in (20) = 0.8
    snrexp = -tinc/tpfall;
    nv=round(td/(tinc*nu));    % length of each subwindow in frames
    if nv<4            % algorithm doesn't work for miniscule frames
        nv=4;
        nu=max(round(td/(tinc*nv)),1);
    end
    nd=nu*nv;           % length of total window in frames
    [md,hd]=mhvals(nd); % calculate the constants M(D) and H(D) from Table III
    [mv,hv]=mhvals(nv); % calculate the constants M(D) and H(D) from Table III
    nsms=10.^(nsmdb*nv*tinc/10);  % [8 4 2 1.2] in paper
    qeqimax=1/qeqmin;  % maximum value of Qeq inverse (23)
    qeqimin=1/qeqmax; % minumum value of Qeq per frame inverse

    if isempty(yf)      % provide dummy initialization
        ac=1;               % correction factor (9)
        subwc=nv;                   % force a buffer switch on first loop
        ibuf=0;
        p=x;          % smoothed power spectrum
        sn2=p;              % estimated noise power
        pb=p;               % smoothed noisy speech power (20)
        pb2=pb.^2;
        pminu=p;
        actmin=repmat(Inf,1,nrf);   % Running minimum estimate
        actminsub=actmin;           % sub-window minimum estimate
        actbuf=repmat(Inf,nu,nrf);  % buffer to store subwindow minima
        lminflag=zeros(1,nrf);      % flag to remember local minimum
    else

        if ~nrcum       % initialize values for first frame
            p=yf(1,:);          % smoothed power spectrum
            ac=1;               % correction factor (9)
            sn2=p;              % estimated noise power
            pb=p;               % smoothed noisy speech power (20)
            pb2=pb.^2;
            pminu=p;
            actmin=repmat(Inf,1,nrf);   % Running minimum estimate
            actminsub=actmin;           % sub-window minimum estimate
            subwc=nv;                   % force a buffer switch on first loop
            actbuf=repmat(Inf,nu,nrf);  % buffer to store subwindow minima
            ibuf=0;
            lminflag=zeros(1,nrf);      % flag to remember local minimum
        end

        % loop for each frame

        for t=1:nr              % we use t instead of lambda in the paper
            yft=yf(t,:);        % noise speech power spectrum
            acb=(1+(sum(p)./sum(yft)-1).^2).^(-1);  % alpha_c-bar(t)  (9)
            ac=aca*ac+(1-aca)*max(acb,acmax);       % alpha_c(t)  (10)
            ah=amax*ac.*(1+(p./sn2-1).^2).^(-1);    % alpha_hat: smoothing factor per frequency (11)
            snr=sum(p)/sum(sn2);
            ah=max(ah,min(aminh,snr^snrexp));       % lower limit for alpha_hat (12)

            p=ah.*p+(1-ah).*yft;            % smoothed noisy speech power (3)
            b=min(ah.^2,bmax);              % smoothing constant for estimating periodogram variance (22 + 2 lines)
            pb=b.*pb + (1-b).*p;            % smoothed periodogram (20)
            pb2=b.*pb2 + (1-b).*p.^2;     	% smoothed periodogram squared (21)

            qeqi=max(min((pb2-pb.^2)./(2*sn2.^2),qeqimax),qeqimin/(t+nrcum));   % Qeq inverse (23)
            qiav=sum(qeqi)/nrf;             % Average over all frequencies (23+12 lines) (ignore non-duplication of DC and nyquist terms)
            bc=1+av*sqrt(qiav);             % bias correction factor (23+11 lines)
            bmind=1+2*(nd-1)*(1-md)./(qeqi.^(-1)-2*md);      % we use the simplified form (17) instead of (15)
            bminv=1+2*(nv-1)*(1-mv)./(qeqi.^(-1)-2*mv);      % same expression but for sub windows
            kmod=bc*p.*bmind<actmin;        % Frequency mask for new minimum
            if any(kmod)
                actmin(kmod)=bc*p(kmod).*bmind(kmod);
                actminsub(kmod)=bc*p(kmod).*bminv(kmod);
            end
            if subwc>1 && subwc<nv              % middle of buffer - allow a local minimum
                lminflag=lminflag | kmod;    	% potential local minimum frequency bins
                pminu=min(actminsub,pminu);
                sn2=pminu;
            else
                if subwc>=nv                    % end of buffer - do a buffer switch
                    ibuf=1+rem(ibuf,nu);     	% increment actbuf storage pointer
                    actbuf(ibuf,:)=actmin;    	% save sub-window minimum
                    pminu=min(actbuf,[],1);
                    i=find(qiav<qith);
                    nsm=nsms(i(1));          	% noise slope max
                    lmin=lminflag & ~kmod & actminsub<nsm*pminu & actminsub>pminu;
                    if any(lmin)
                        pminu(lmin)=actminsub(lmin);
                        actbuf(:,lmin)=repmat(pminu(lmin),nu,1);
                    end
                    lminflag(:)=0;
                    actmin(:)=Inf;
                    subwc=0;
                end
            end
            subwc=subwc+1;
            x(t,:)=sn2;
            qisq=sqrt(qeqi);
            % empirical formula for standard error based on Fig 15 of [2]
            xs(t,:)=sn2.*sqrt(0.266*(nd+100*qisq).*qisq/(1+0.005*nd+6/nd)./(0.5*qeqi.^(-1)+nd-1));
        end
    end
    if nargout>1    % we need to store the state for next time
        zo.nrcum=nrcum+nr;      % number of frames so far
        zo.p=p;          % smoothed power spectrum
        zo.ac=ac;               % correction factor (9)
        zo.sn2=sn2;              % estimated noise power
        zo.pb=pb;               % smoothed noisy speech power (20)
        zo.pb2=pb2;
        zo.pminu=pminu;
        zo.actmin=actmin;   % Running minimum estimate
        zo.actminsub=actminsub;           % sub-window minimum estimate
        zo.subwc=subwc;                   % force a buffer switch on first loop
        zo.actbuf=actbuf;  % buffer to store subwindow minima
        zo.ibuf=ibuf;
        zo.lminflag=lminflag;      % flag to remember local minimum
        zo.tinc=tinc;     % must be the last one
        zo.qq=qq;
    end
    if ~nargout
        clf;
        subplot(212);
        plot((1:nr)*tinc,10*log10([sum(yf,2) sum(x,2)]))
        ylabel('Frame Energy (dB)');
        xlabel(sprintf('Time (s)   [%d ms frame incr]',round(tinc*1000)));
        axisenlarge([-1 -1.05]);
        legend('input','noise','Location','Best');
        subplot(211);
        plot(1:nrf,10*log10([sum(yf,1)'/nr sum(x,1)'/nr]))
        ylabel('Power (dB)');
        xlabel('Frequency bin');
        axisenlarge([-1 -1.05]);
        legend('input','noise','Location','Best');
    end
end

function [m,h,d]=mhvals(d)
% Values are taken from Table 5 in [2]
%[2] R. Martin,"Bias compensation methods for minimum statistics noise power
%               spectral density estimation", Signal Processing Vol 86, pp1215-1229, 2006.

% approx: plot(d.^(-0.5),[m 1-d.^(-0.5)],'x-'), plot(d.^0.5,h,'x-')
persistent dmh
if isempty(dmh)
    dmh=[
        1   0       0;
        2   0.26    0.15;
        5   0.48    0.48;
        8   0.58    0.78;
        10  0.61    0.98;
        15  0.668   1.55;
        20  0.705   2;
        30  0.762   2.3;
        40  0.8     2.52;
        60  0.841   3.1;
        80  0.865   3.38;
        120 0.89    4.15;
        140 0.9     4.35;
        160 0.91    4.25;
        180 0.92    3.9;
        220 0.93    4.1;
        260 0.935   4.7;
        300 0.94    5];
end

if nargin>=1
    i=find(d<=dmh(:,1));
    if isempty(i)
        i=size(dmh,1);
        j=i;
    else
        i=i(1);
        j=i-1;
    end
    if d==dmh(i,1)
        m=dmh(i,2);
        h=dmh(i,3);
    else
        qj=sqrt(dmh(i-1,1));    % interpolate using sqrt(d)
        qi=sqrt(dmh(i,1));
        q=sqrt(d);
        h=dmh(i,3)+(q-qi)*(dmh(j,3)-dmh(i,3))/(qj-qi);
        m=dmh(i,2)+(qi*qj/q-qj)*(dmh(j,2)-dmh(i,2))/(qi-qj);
    end
else
    d=dmh(:,1);
    m=dmh(:,2);
    h=dmh(:,3);
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.stanbol</groupId>
    <artifactId>stanbol-parent</artifactId>
    <version>6-SNAPSHOT</version>
    <relativePath>../../parent</relativePath>
  </parent>

  <groupId>org.apache.stanbol</groupId>
  <artifactId>org.apache.stanbol.launchers.full</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Apache Stanbol Launchers Full Launcher</name>
  <description>Runnable jar that runs the full Stanbol configuration</description>

  <scm>
    <connection>
      scm:svn:http://svn.apache.org/repos/asf/stanbol/trunk/launchers/full/
    </connection>
    <developerConnection>
      scm:svn:https://svn.apache.org/repos/asf/stanbol/trunk/launchers/full/
    </developerConnection>
    <url>http://stanbol.apache.org/</url>
  </scm>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-clean-plugin</artifactId>
        <configuration>
          <filesets>
            <fileset>
              <directory>.</directory>
              <includes>
                <include>stanbol/**</include>
                <include>*.log</include>
              </includes>
            </fileset>
          </filesets>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.sling</groupId>
        <artifactId>maven-launchpad-plugin</artifactId>
        <!--
          TODO the maven-launchpad-plugin can also generate a war file and
          Karaf description, we could add this. See
          http://sling.apache.org/site/maven-launchpad-plugin.html
        -->
        <executions>
          <execution>
            <id>prepare-package</id>
            <goals>
              <goal>prepare-package</goal>
            </goals>
            <configuration>
              <includeDefaultBundles>false</includeDefaultBundles>
              <!-- Standalone jar requires an OSGi http service implementation -->
              <jarWebSupport>
                <bundles>
                  <bundle>
                    <groupId>org.apache.felix</groupId>
                    <artifactId>org.apache.felix.http.servlet-api</artifactId>
                    <!-- explicit version is required (STANBOL-1402) -->
                    <version>${felix-servlet-api-version}</version>
                    <startLevel>1</startLevel>
                  </bundle>
                  <bundle>
                    <groupId>org.apache.felix</groupId>
                    <artifactId>org.apache.felix.http.jetty</artifactId>
                    <!-- explicit version is required (STANBOL-1402) -->
                    <version>${felix-jetty-version}</version>
                    <startLevel>3</startLevel>
                  </bundle>
                </bundles>
              </jarWebSupport>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
              <mainClass>org.apache.stanbol.launchpad.Main</mainClass>
              <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
            </manifest>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <createDependencyReducedPom>false</createDependencyReducedPom>
              <artifactSet>
              <!-- Use this to in/exclude only specific dependencies -->
                <includes>
                  <include>org.apache.stanbol:org.apache.stanbol.commons.launchpad</include>
                  <include>org.apache.sling:org.apache.sling.launchpad.base</include>
                </includes>
              </artifactSet>
              <!-- transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ComponentsXmlResourceTransformer" />
              </transformers -->
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.rat</groupId>
        <artifactId>apache-rat-plugin</artifactId>
        <configuration>
          <excludes></excludes>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <version>1.7</version>
        <configuration>
          <target>
            <property name="vm.args" value=""/>
            <java fork="true" jar="${project.build.directory}/${project.build.finalName}.jar"
                dir="${project.build.directory}">
              <jvmarg line="-Xmx1024m -XX:MaxPermSize=256M ${vm.args}"/>
            </java>
          </target>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <!-- The Apache Stanbol lauchpad -->
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.commons.launchpad</artifactId>
      <version>1.0.0-SNAPSHOT</version>
    </dependency>
    <dependency>
      <!-- maven-launchpad-plugin builds on the launchpad.base app -->
      <groupId>org.apache.sling</groupId>
      <artifactId>org.apache.sling.launchpad.base</artifactId>
      <classifier>app</classifier>
    </dependency>

    <!-- OSGi Framemework Bundle List -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.osgiframework</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <!-- Clerezza RDF bundles -->
    <dependency>
      <groupId>org.apache.clerezza.provisioning</groupId>
      <artifactId>rdf</artifactId>
      <version>0.1</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <!-- Clerezza Jena TDB storage (used by Ontonet) -->
    <dependency>
      <groupId>org.apache.clerezza.provisioning</groupId>
      <artifactId>rdf.tdb</artifactId>
      <version>0.1</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <!-- Stanbol Commons Bundle List -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.stanbolcommons</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <!-- Security Support -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.security</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <!-- Clerezza zz> Shell Bundle List  -->
    <dependency>
      <groupId>org.apache.clerezza.provisioning</groupId>
      <artifactId>shell</artifactId>
      <version>0.1</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <!-- Stanbol Data Bundle List -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.defaultdata</artifactId>
      <version>1.1.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>
    <!-- include all OpenNLP models in the full launcher  -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.opennlp</artifactId>
      <version>1.1.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <!-- Stanbol Enhancer Bundle List -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.enhancer</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.enhancer-engines-restricted</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <!-- Stanbol Entityhub Bundle List(s) -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.entityhub.core</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.entityhub.clerezza</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.entityhub.sesame</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>
    <!-- Marmotta integration with the Entityhub -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.marmotta.kiwi</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <!-- Stanbol Ontology Manager Bundle List -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.ontologymanager</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <!-- Stanbol Rules Bundle List  -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.rules</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <!-- Stanbol Reasoners Bundle List -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.reasoners</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

    <!-- Language Extras -->
    <!-- Basic Cinese language support (STANBOL-855) -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.languageextras.smartcn</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>
    <!-- Japanese Language Support  -->
    <dependency>
      <groupId>org.apache.stanbol</groupId>
      <artifactId>org.apache.stanbol.launchers.bundlelists.languageextras.kuromoji</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>partialbundlelist</type>
      <scope>provided</scope>
    </dependency>

  </dependencies>
</project>


text:
/*
 *
 *
 *
 */
package com.yhy.core.utils;

import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 支持HMAC-SHA1消息签名 及 DES/AES对称加密的工具类.
 * 支持Hex与Base64两种编码方式.
 *
 * @author YHY
 * @version 2014-10-21
 */
public abstract class Cryptos {

	public static final String AES_KEY = "YND_AES_KEY";

	private static final String AES = "AES";
	private static final String AES_CBC = "AES/CBC/PKCS5Padding";
	private static final String HMACSHA1 = "HmacSHA1";

	private static final int DEFAULT_HMACSHA1_KEYSIZE = 160; // RFC2401
	private static final int DEFAULT_AES_KEYSIZE = 128;
	private static final int DEFAULT_IVSIZE = 16;

	// -- HMAC-SHA1 funciton --//
	/**
	 * 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节.
	 *
	 * @param input 原始输入字符数组
	 * @param key HMAC-SHA1密钥
	 */
	public static byte[] hmacSha1(byte[] input, byte[] key) {
		try {
			SecretKey secretKey = new SecretKeySpec(key, HMACSHA1);
			Mac mac = Mac.getInstance(HMACSHA1);
			mac.init(secretKey);
			return mac.doFinal(input);
		} catch (GeneralSecurityException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 校验HMAC-SHA1签名是否正确.
	 *
	 * @param expected 已存在的签名
	 * @param input 原始输入字符串
	 * @param key 密钥
	 */
	public static boolean isMacValid(byte[] expected, byte[] input, byte[] key) {
		byte[] actual = hmacSha1(input, key);
		return Arrays.equals(expected, actual);
	}

	/**
	 * 生成HMAC-SHA1密钥,返回字节数组,长度为160位(20字节).
	 * HMAC-SHA1算法对密钥无特殊要求, RFC2401建议最少长度为160位(20字节).
	 */
	public static byte[] generateHmacSha1Key() {
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance(HMACSHA1);
			keyGenerator.init(DEFAULT_HMACSHA1_KEYSIZE);
			SecretKey secretKey = keyGenerator.generateKey();
			return secretKey.getEncoded();
		} catch (GeneralSecurityException e) {
			throw Exceptions.unchecked(e);
		}
	}

	// -- AES funciton --//
	/**
	 * 使用AES加密原始字符串.
	 *
	 * @param input 原始输入字符数组
	 * @param key 符合AES要求的密钥
	 */
	public static byte[] aesEncrypt(byte[] input, byte[] key) {
		return aes(input, key, Cipher.ENCRYPT_MODE);
	}

	/**
	 * 使用AES加密原始字符串.
	 *
	 * @param input 原始输入字符数组
	 * @param key 符合AES要求的密钥
	 */
	public static String aesEncrypt(String input, String key) {
		byte[] aesKey = generateAesKey(key);
		byte[] encryptResult = aes(input.getBytes(Charsets.UTF8), aesKey, Cipher.ENCRYPT_MODE);
		return Encodes.encodeHex(encryptResult);
	}

	/**
	 * 使用AES加密原始字符串.
	 *
	 * @param input 原始输入字符数组
	 * @param key 符合AES要求的密钥
	 * @param iv 初始向量
	 */
	public static byte[] aesEncrypt(byte[] input, byte[] key, byte[] iv) {
		return aes(input, key, iv, Cipher.ENCRYPT_MODE);
	}

	/**
	 * 使用AES解密字符串, 返回原始字符串.
	 *
	 * @param input Hex编码的加密字符串
	 * @param key 符合AES要求的密钥
	 */
	public static String aesDecrypt(byte[] input, byte[] key) {
		byte[] decryptResult = aes(input, key, Cipher.DECRYPT_MODE);
		return new String(decryptResult, Charsets.UTF8);
	}

	/**
	 * 使用AES解密字符串, 返回原始字符串.
	 *
	 * @param input Hex编码的加密字符串
	 * @param key 符合AES要求的密钥
	 */
	public static String aesDecrypt(String input, String key) {
		byte[] aesKey = generateAesKey(key);
		byte[] decryptFrom = Encodes.decodeHex(input);
		byte[] decryptResult = aes(decryptFrom, aesKey, Cipher.DECRYPT_MODE);
		return new String(decryptResult, Charsets.UTF8);
	}

	/**
	 * 使用AES解密字符串, 返回原始字符串.
	 *
	 * @param input Hex编码的加密字符串
	 * @param key 符合AES要求的密钥
	 * @param iv 初始向量
	 */
	public static String aesDecrypt(byte[] input, byte[] key, byte[] iv) {
		byte[] decryptResult = aes(input, key, iv, Cipher.DECRYPT_MODE);
		return new String(decryptResult, Charsets.UTF8);
	}

	/**
	 * 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
	 *
	 * @param input 原始字节数组
	 * @param key 符合AES要求的密钥
	 * @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
	 */
	private static byte[] aes(byte[] input, byte[] key, int mode) {
		try {
			SecretKeySpec secretKey = new SecretKeySpec(key, AES);
			Cipher cipher = Cipher.getInstance(AES);
			cipher.init(mode, secretKey);
			return cipher.doFinal(input);
		} catch (GeneralSecurityException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
	 *
	 * @param input 原始字节数组
	 * @param key 符合AES要求的密钥
	 * @param iv 初始向量
	 * @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
	 */
	private static byte[] aes(byte[] input, byte[] key, byte[] iv, int mode) {
		try {
			SecretKeySpec secretKey = new SecretKeySpec(key, AES);
			IvParameterSpec ivSpec = new IvParameterSpec(iv);
			Cipher cipher = Cipher.getInstance(AES_CBC);
			cipher.init(mode, secretKey, ivSpec);
			return cipher.doFinal(input);
		} catch (GeneralSecurityException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 生成AES密钥,返回字节数组, 默认长度为128位(16字节).
	 */
	public static byte[] generateAesKey() {
		return generateAesKey(DEFAULT_AES_KEYSIZE);
	}

	/**
	 * 生成AES密钥,可选长度为128,192,256位.
	 */
	public static byte[] generateAesKey(int keysize) {
		return generateAesKey(keysize, AES_KEY);
	}

	/**
	 * 生成AES密钥,可选长度为128,192,256位.
	 */
	public static byte[] generateAesKey(String key) {
		return generateAesKey(DEFAULT_AES_KEYSIZE, key);
	}

	/**
	 * 生成AES密钥,可选长度为128,192,256位.
	 */
	public static byte[] generateAesKey(int keysize, String key) {
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
			//防止linux下 随机生成key
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");
			secureRandom.setSeed(key.getBytes());
			keyGenerator.init(keysize, secureRandom);
			SecretKey secretKey = keyGenerator.generateKey();
			return secretKey.getEncoded();
		} catch (GeneralSecurityException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 生成随机向量,默认大小为cipher.getBlockSize(), 16字节.
	 */
	public static byte[] generateIV() {
		try {
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");
			byte[] bytes = new byte[DEFAULT_IVSIZE];
			secureRandom.nextBytes(bytes);
			return bytes;
		} catch (NoSuchAlgorithmException e) {
			throw Exceptions.unchecked(e);
		} catch (NoSuchProviderException e) {
			throw Exceptions.unchecked(e);
		}
	}
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta name="description" content="">
	<meta name="author" content="">

	<title>Denunciar buraco</title>

	<link rel="shortcut icon" href="img/logotb.png" type="image/x-icon"/>

	<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

	<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
	<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
	<link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
	<link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
	<link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

	<link href="css/agency.min.css" rel="stylesheet">

    				<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
    					Toggle navigation Menu
    				</button>
    				Tapa Buraco

    						Serviços

    							Localização
    							Denunciar
    							Estatísticas

    						Portfolio

    						Sobre

    						Time

    						Contato

    					Copyright © Your Website 2016

Privacy Policy

Terms of Use


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EventStore
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=false)]
    public class CachingInfoAttribute : Attribute
    {
        public MaxStaleness MaxStaleness { get; private set; }

        public CachingInfoAttribute(MaxStaleness maxStaleness)
        {
            MaxStaleness = maxStaleness;
        }
    }
}


text:
package jibe.tools.fsm.annotations;

import jibe.tools.fsm.api.EventType;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Inherited
@Target({ ElementType.TYPE, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface TimerEvent {
    String fsm() default "";

    long period();

    EventType type();

    long delay() default 0;

    TimeUnit timeUnit() default TimeUnit.MILLISECONDS;
}


text:
package nl.fontys.epic.commands;

import nl.fontys.epic.TextAdventure;
import nl.fontys.epic.core.Inventory;
import nl.fontys.epic.core.Item;
import nl.fontys.epic.core.Player;
import nl.fontys.epic.core.Room;
import nl.fontys.epic.commands.CommandResponse.ResponseType;

/**
 *
 * @author miguel
 */
public class DropCommand implements Command {

    @Override
    public CommandResponse handle(String[] args, TextAdventure adventure) throws CommandException {
        if (args.length < 1 || args[0].trim().isEmpty()) {
            throw new CommandException("You have to specify something to drop");
        } else {
            String itemId = args[0];
            Player player = adventure.getPlayer();
            Inventory inventory = player.getInventory();
            Item item = inventory.fetch(itemId);
            if (item != null) {
                Room room = adventure.getCurrentRoom();
                Inventory items = room.getItems(player.getPosition().x, player.getPosition().y);
                items.add(item);
                return new SimpleCommandResponse("You dropped " + itemId);
            } else {
                return new SimpleCommandResponse("Unable to drop " + itemId, ResponseType.ERROR);
            }
        }
    }

}


text:
using namespace BloombergLP;

// ----------------------------------------------------------------------------

namespace {
    class Value {
        bool bv;
        int  iv;
        char cv;
    public:
        typedef batgen::TupleMembers<
            batgen::TupleConstMember<bool, Value, &Value::bv>,
            batgen::TupleConstMember<int,  Value, &Value::iv>,
            batgen::TupleConstMember<char, Value, &Value::cv>
        > tuple;

        Value(bool bv, int iv, char cv) : bv(bv), iv(iv), cv(cv) {}
    };
}

// ----------------------------------------------------------------------------

TEST_CASE("breathing test", "[batgen::tuple]") {
    REQUIRE(batgen::TupleSize<Value>::value == 3);

    Value value(true, 17, 'a');

    REQUIRE(batgen::get<0>(value));
    REQUIRE(batgen::get<1>(value) == 17);
    REQUIRE(batgen::get<2>(value) == 'a');
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('subjects', '0002_auto_20170827_2018'),
        ('surveys', '0009_auto_20171022_2034'),
        ('treatment', '0006_request_processed'),
    ]

    operations = [
        migrations.AddField(
            model_name='stage',
            name='subjects',
            field=models.ManyToManyField(to='subjects.Subject'),
        ),
        migrations.AddField(
            model_name='stage',
            name='surveys',
            field=models.ManyToManyField(to='surveys.Survey'),
        ),
    ]


text:
from logging import info, error
from re import findall, sub

from utility.html_downloader import get_html_string

from src.model.strategy_interface import StrategyInterface

class DanbooruStrategy(StrategyInterface):
    prefix = 'dan'

    def download_url(self, url):
        url = self.unquote_url(url).replace("utf8=✓&", "").replace("&ms=1", '')

        if "tags=" in url:
            self._download_by_tag(url=url)
        elif "posts" in url:
            self._download_list(prefix="", urls=[url])
        else:
            error("NO STRATEGY")

    def get_artist(self, data):
        # in sankaku
        artist = findall('author"\shref="/posts\?tags=([^"]*)', data)
        if len(artist):
            return artist[0]
        # no else
        return 'unknown artist'

    def get_original_url(self, data):
        return findall('Size:\s<a href="([^"]*)', data)[0]

    def _download_by_tag(self, url):

        url = sub(r'(page=\d+&?)', '', url)
        site_url, tag = url.split("?tags=")

        for page in range(1, 200):
            page_url = url + '&page=' + str(page)
            info(page_url)
            page_images = findall('href="/posts(/\d+)', get_html_string(page_url))

            self._download_list(prefix=site_url, urls=page_images, sub_dirs=tag)

            if len(page_images) < 20:
                return
            # no else


text:
import ddt
from unittest import mock

from nova.compute import pci_placement_translator as ppt
from nova import exception
from nova.objects import fields
from nova.objects import pci_device
from nova import test

def dev(v, p):
    return pci_device.PciDevice(vendor_id=v, product_id=p)

# NOTE(gibi): Most of the nova.compute.pci_placement_translator module is
# covered with functional tests in
# nova.tests.functional.libvirt.test_pci_in_placement
@ddt.ddt
class TestTranslator(test.NoDBTestCase):
    def setUp(self):
        super().setUp()
        patcher = mock.patch(
            "nova.compute.pci_placement_translator."
            "_is_placement_tracking_enabled")
        self.addCleanup(patcher.stop)
        patcher.start()

    def test_translator_skips_devices_without_matching_spec(self):
        """As every PCI device in the PciTracker is created by matching a
        PciDeviceSpec the translator should always be able to look up the spec
        for a device. But if cannot then the device will be skipped and warning
        will be emitted.
        """
        pci_tracker = mock.Mock()
        pci_tracker.pci_devs = pci_device.PciDeviceList(
            objects=[
                pci_device.PciDevice(
                    address="0000:81:00.0",
                    status=fields.PciDeviceStatus.AVAILABLE,
                    instance_uuid=None,
                )
            ]
        )
        # So we have a device but there is no spec for it
        pci_tracker.dev_filter.get_devspec = mock.Mock(return_value=None)
        pci_tracker.dev_filter.specs = []
        # we expect that the provider_tree is not touched as the device without
        # spec is skipped, we assert that with the NonCallableMock
        provider_tree = mock.NonCallableMock()

        ppt.update_provider_tree_for_pci(
            provider_tree, "fake-node", pci_tracker, {}, [])

        self.assertIn(
            "Device spec is not found for device 0000:81:00.0 in "
            "[pci]device_spec. Ignoring device in Placement resource view. "
            "This should not happen. Please file a bug.",
            self.stdlog.logger.output
        )

    @ddt.unpack
    @ddt.data(
        (None, set()),
        ("", set()),
        ("a", {"CUSTOM_A"}),
        ("a,b", {"CUSTOM_A", "CUSTOM_B"}),
        ("HW_GPU_API_VULKAN", {"HW_GPU_API_VULKAN"}),
        ("CUSTOM_FOO", {"CUSTOM_FOO"}),
        ("custom_bar", {"CUSTOM_BAR"}),
        ("custom-bar", {"CUSTOM_CUSTOM_BAR"}),
        ("CUSTOM_a", {"CUSTOM_A"}),
        ("a@!#$b123X", {"CUSTOM_A_B123X"}),
        # Note that both trait names are normalized to the same trait
        ("a!@b,a###b", {"CUSTOM_A_B"}),
    )
    def test_trait_normalization(self, trait_names, expected_traits):
        self.assertEqual(
            expected_traits | {"COMPUTE_MANAGED_PCI_DEVICE"},
            ppt._get_traits_for_dev({"traits": trait_names})
        )

    @ddt.unpack
    @ddt.data(
        (dev(v='1234', p='5678'), None, "CUSTOM_PCI_1234_5678"),
        (dev(v='1234', p='5678'), "", "CUSTOM_PCI_1234_5678"),
        (dev(v='1234', p='5678'), "PGPU", "PGPU"),
        (dev(v='1234', p='5678'), "pgpu", "PGPU"),
        (dev(v='1234', p='5678'), "foobar", "CUSTOM_FOOBAR"),
        (dev(v='1234', p='5678'), "custom_foo", "CUSTOM_FOO"),
        (dev(v='1234', p='5678'), "CUSTOM_foo", "CUSTOM_FOO"),
        (dev(v='1234', p='5678'), "custom_FOO", "CUSTOM_FOO"),
        (dev(v='1234', p='5678'), "CUSTOM_FOO", "CUSTOM_FOO"),
        (dev(v='1234', p='5678'), "custom-foo", "CUSTOM_CUSTOM_FOO"),
        (dev(v='1234', p='5678'), "a###b", "CUSTOM_A_B"),
        (dev(v='123a', p='567b'), "", "CUSTOM_PCI_123A_567B"),
    )
    def test_resource_class_normalization(self, pci_dev, rc_name, expected_rc):
        self.assertEqual(
            expected_rc,
            ppt._get_rc_for_dev(pci_dev, {"resource_class": rc_name})
        )

    def test_dependent_device_pf_then_vf(self):
        pv = ppt.PlacementView(
            "fake-node", instances_under_same_host_resize=[])
        pf = pci_device.PciDevice(
            address="0000:81:00.0",
            dev_type=fields.PciDeviceType.SRIOV_PF
        )
        vf = pci_device.PciDevice(
            address="0000:81:00.1",
            parent_addr=pf.address,
            dev_type=fields.PciDeviceType.SRIOV_VF
        )

        pv._add_dev(pf, {"resource_class": "foo"})
        ex = self.assertRaises(
            exception.PlacementPciDependentDeviceException,
            pv._add_dev,
            vf,
            {"resource_class": "bar"}
        )

        self.assertEqual(
            "Configuring both 0000:81:00.1 and 0000:81:00.0 in "
            "[pci]device_spec is not supported. Either the parent PF or its "
            "children VFs can be configured.",
            str(ex),
        )

    def test_dependent_device_vf_then_pf(self):
        pv = ppt.PlacementView(
            "fake-node", instances_under_same_host_resize=[])
        pf = pci_device.PciDevice(
            address="0000:81:00.0",
            dev_type=fields.PciDeviceType.SRIOV_PF
        )
        vf = pci_device.PciDevice(
            address="0000:81:00.1",
            parent_addr=pf.address,
            dev_type=fields.PciDeviceType.SRIOV_VF
        )
        vf2 = pci_device.PciDevice(
            address="0000:81:00.2",
            parent_addr=pf.address,
            dev_type=fields.PciDeviceType.SRIOV_VF
        )

        pv._add_dev(vf, {"resource_class": "foo"})
        pv._add_dev(vf2, {"resource_class": "foo"})
        ex = self.assertRaises(
            exception.PlacementPciDependentDeviceException,
            pv._add_dev,
            pf,
            {"resource_class": "bar"}
        )

        self.assertEqual(
            "Configuring both 0000:81:00.0 and 0000:81:00.1,0000:81:00.2 in "
            "[pci]device_spec is not supported. Either the parent PF or its "
            "children VFs can be configured.",
            str(ex),
        )

    def test_mixed_rc_for_sibling_vfs(self):
        pv = ppt.PlacementView(
            "fake-node", instances_under_same_host_resize=[])
        vf1, vf2, vf3, vf4 = [
            pci_device.PciDevice(
                address="0000:81:00.%d" % f,
                parent_addr="0000:71:00.0",
                dev_type=fields.PciDeviceType.SRIOV_VF)
            for f in range(0, 4)
        ]

        pv._add_dev(vf1, {"resource_class": "a", "traits": "foo,bar,baz"})
        # order is irrelevant
        pv._add_dev(vf2, {"resource_class": "a", "traits": "foo,baz,bar"})
        # but missing trait is rejected
        ex = self.assertRaises(
            exception.PlacementPciMixedTraitsException,
            pv._add_dev,
            vf3,
            {"resource_class": "a", "traits": "foo,bar"},
        )
        self.assertEqual(
            "VFs from the same PF cannot be configured with different set of "
            "'traits' in [pci]device_spec. We got "
            "COMPUTE_MANAGED_PCI_DEVICE,CUSTOM_BAR,CUSTOM_FOO for "
            "0000:81:00.2 and "
            "COMPUTE_MANAGED_PCI_DEVICE,CUSTOM_BAR,CUSTOM_BAZ,CUSTOM_FOO "
            "for 0000:81:00.0,0000:81:00.1.",
            str(ex),
        )
        # as well as additional trait
        ex = self.assertRaises(
            exception.PlacementPciMixedTraitsException,
            pv._add_dev,
            vf4,
            {"resource_class": "a", "traits": "foo,bar,baz,extra"}
        )
        self.assertEqual(
            "VFs from the same PF cannot be configured with different set of "
            "'traits' in [pci]device_spec. We got "
            "COMPUTE_MANAGED_PCI_DEVICE,CUSTOM_BAR,CUSTOM_BAZ,CUSTOM_EXTRA,"
            "CUSTOM_FOO for 0000:81:00.3 and COMPUTE_MANAGED_PCI_DEVICE,"
            "CUSTOM_BAR,CUSTOM_BAZ,CUSTOM_FOO for 0000:81:00.0,0000:81:00.1.",
            str(ex),
        )


text:
<composition xmlns="http://schemas.openehr.org/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="COMPOSITION" archetype_node_id="openEHR-EHR-COMPOSITION.minimal.v1">
  <name xsi:type="DV_TEXT">
    <value>Minimal</value>
  </name>
  <archetype_details>
    <archetype_id>
      <value>openEHR-EHR-COMPOSITION.minimal.v1</value>
    </archetype_id>
    <template_id>
      <value>minimal_instruction.en.v1</value>
    </template_id>
    <rm_version>1.0.2</rm_version>
  </archetype_details>
  <language>
    <terminology_id>
      <value>ISO_639-1</value>
    </terminology_id>
    <code_string>en</code_string>
  </language>
  <territory>
    <terminology_id>
      <value>ISO_3166-1</value>
    </terminology_id>
    <code_string>UY</code_string>
  </territory>
  <category>
    <value>event</value>
    <defining_code>
      <terminology_id>
        <value>openehr</value>
      </terminology_id>
      <code_string>433</code_string>
    </defining_code>
  </category>
  <composer xsi:type="PARTY_IDENTIFIED">
    <external_ref>
      <id xsi:type="HIER_OBJECT_ID">
        <value>28669252-d281-4c4b-b81f-9db0115b57b2</value>
      </id>
      <namespace>DEMOGRAPHIC</namespace>
      <type>PERSON</type>
    </external_ref>
    <name>Dr. House</name>
  </composer>
  <context>
    <start_time>
      <value>2021-10-18T22:27:45.466-03:00</value>
    </start_time>
    <setting>
      <value>emergency care</value>
      <defining_code>
        <terminology_id>
          <value>openehr</value>
        </terminology_id>
        <code_string>227</code_string>
      </defining_code>
    </setting>
    <participations>
      <function xsi:type="DV_TEXT">
        <value>legal guardian consent author</value>
      </function>
      <performer xsi:type="PARTY_RELATED">
        <name>Charles Connor</name>
        <relationship>
          <value>father</value>
          <defining_code>
            <terminology_id>
              <value>openehr</value>
            </terminology_id>
            <code_string>9</code_string>
          </defining_code>
        </relationship>
      </performer>
      <mode>
        <value>not specified</value>
        <defining_code>
          <terminology_id>
            <value>openehr</value>
          </terminology_id>
          <code_string>193</code_string>
        </defining_code>
      </mode>
    </participations>
  </context>
  <content xsi:type="INSTRUCTION" archetype_node_id="openEHR-EHR-INSTRUCTION.minimal.v1">
    <name xsi:type="DV_TEXT">
      <value>Minimal</value>
    </name>
    <archetype_details>
      <archetype_id>
        <value>openEHR-EHR-INSTRUCTION.minimal.v1</value>
      </archetype_id>
      <template_id>
        <value>minimal_instruction.en.v1</value>
      </template_id>
      <rm_version>1.0.2</rm_version>
    </archetype_details>
    <language>
      <terminology_id>
        <value>ISO_639-1</value>
      </terminology_id>
      <code_string>en</code_string>
    </language>
    <encoding>
      <terminology_id>
        <value>IANA_character-sets</value>
      </terminology_id>
      <code_string>UTF-8</code_string>
    </encoding>
    <subject xsi:type="PARTY_SELF" />
    <narrative>
      <value>xvSwSWWffCvyncMXbXLacuoPJbZy.YKDVWzfchCrwPgrkflsUpbfmhcOOJLruqbaATCnQJd,wmVehHvIEQlXRnPzaYzclYRFTjDVISQKlrjvGDMYBoCZKMn,UoMOzIsKrucLNazYCiGGQXWncTaUWXiPdwgriuZCQflywUB.lgfVeoQLgGIcniO,zrTgRRKSqEpMVpztp.DAdRCTjboyWIejdWgNLGzWVqlaJZCrjCQiqEEDqxfph,MqcnWezeV</value>
    </narrative>
    <activities archetype_node_id="at0001">
      <name xsi:type="DV_TEXT">
        <value>Current Activity</value>
      </name>
      <description xsi:type="ITEM_TREE" archetype_node_id="at0002">
        <name xsi:type="DV_TEXT">
          <value>Arbol</value>
        </name>
        <items xsi:type="ELEMENT" archetype_node_id="at0003">
          <name xsi:type="DV_TEXT">
            <value>duration</value>
          </name>
          <value xsi:type="DV_DURATION">
            <value>PT28M</value>
          </value>
        </items>
      </description>
      <timing>
        <value>P1D</value>
        <formalism>ISO8601</formalism>
      </timing>
      <action_archetype_id>openEHR-EHR-ACTION\.minimal\.v1</action_archetype_id>
    </activities>
  </content>
</composition>


text:
module.exports = function(app) {
  var express        = require('express');
  var accountsRouter = express.Router();

  accountsRouter.get('/1', function(req, res) {
    if (/Bearer .+/.test(req.headers.authorization)) {
      const response = {
        data: {
          type: 'accounts',
          id: '1',
          attributes: {
            login: 'letme',
            name: 'Some person'
          }
        }
      };

      // delay this a bit so we see the loading template
      setTimeout(function() {
        res.status(200).send(response);
      }, 1000);
    } else {
      res.status(401).end();
    }
  });

  app.use('/accounts', accountsRouter);
};


text:
RSpec.describe Regexp, '#random_example' do
  def self.random_example_matches(*regexps)
    regexps.each do |regexp|
      it "random example for /#{regexp.source}/" do
        random_example = regexp.random_example

        expect(random_example).to be_a String # Not an Array!
        expect(random_example)
          .to match(Regexp.new("\\A(?:#{regexp.source})\\z", regexp.options))
      end
    end
  end

  context 'smoke tests' do
    # Just a few "smoke tests", to ensure the basic method isn't broken.
    # Testing of the RegexpExamples::Parser class is all
    # covered by Regexp#examples test already.
    random_example_matches(
      /\w{10}/,
      /(we(need(to(go(deeper)?)?)?)?) \1/,
      /case insensitive/i,
      /front seat|back seat/, # Which seat will I take??
    )
  end
end


text:
package org.fife.rsta.ac.java.rjc.ast;

import org.fife.rsta.ac.java.rjc.lexer.Scanner;

public class EnumDeclaration extends AbstractTypeDeclarationNode {

//	private EnumBody enumBody;

	public EnumDeclaration(Scanner s, int offs, String name) {
		super(name, s.createOffset(offs), s.createOffset(offs+name.length()));
	}

	public String getTypeString() {
		return "enum";
	}

//	public void setEnumBody(EnumBody enumBody) {
//		this.enumBody = enumBody;
//	}

}


text:
namespace ash {
enum class AppListConfigType;

class APP_LIST_MODEL_EXPORT AppListItemObserver {
 public:
  // Invoked after item's icon is changed.
  // |config_type| The app list configuration type for which the item icon
  // changed.
  virtual void ItemIconChanged(AppListConfigType config_type) {}

  // Invoked after item's name is changed.
  virtual void ItemNameChanged() {}

  // Invoked when the item is about to be destroyed.
  virtual void ItemBeingDestroyed() {}

 protected:
  virtual ~AppListItemObserver() {}
};

}  // namespace ash

#endif  // ASH_APP_LIST_MODEL_APP_LIST_ITEM_OBSERVER_H_


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Configuration
{
  public partial class SettingsProperty
  {
    #region Methods and constructors
    public SettingsProperty(string name, Type propertyType, SettingsProvider provider, bool isReadOnly, Object defaultValue, SettingsSerializeAs serializeAs, SettingsAttributeDictionary attributes, bool throwOnErrorDeserializing, bool throwOnErrorSerializing)
    {
    }

    public SettingsProperty(System.Configuration.SettingsProperty propertyToCopy)
    {
      Contract.Requires(propertyToCopy != null);
    }

    public SettingsProperty(string name)
    {
    }
    #endregion

    #region Properties and indexers
    public virtual new SettingsAttributeDictionary Attributes
    {
      get
      {
        return default(SettingsAttributeDictionary);
      }
    }

    public virtual new Object DefaultValue
    {
      get
      {
        return default(Object);
      }
      set
      {
      }
    }

    public virtual new bool IsReadOnly
    {
      get
      {
        return default(bool);
      }
      set
      {
      }
    }

    public virtual new string Name
    {
      get
      {
        return default(string);
      }
      set
      {
      }
    }

    public virtual new Type PropertyType
    {
      get
      {
        return default(Type);
      }
      set
      {
      }
    }

    public virtual new SettingsProvider Provider
    {
      get
      {
        return default(SettingsProvider);
      }
      set
      {
      }
    }

    public virtual new SettingsSerializeAs SerializeAs
    {
      get
      {
        return default(SettingsSerializeAs);
      }
      set
      {
      }
    }

    public bool ThrowOnErrorDeserializing
    {
      get
      {
        return default(bool);
      }
      set
      {
      }
    }

    public bool ThrowOnErrorSerializing
    {
      get
      {
        return default(bool);
      }
      set
      {
      }
    }
    #endregion
  }
}