Crop the generator to a finite number of frames

	Return a generator which outputs the provided generator limited
	to enough samples to produce seconds seconds of audio (default 5s)
	at the provided frame rate.
422879
def crop(gens, seconds=5, cropper=None):
	'''
	
	'''
	if hasattr(gens, "next"):
		# single generator
		gens = (gens,)

	if cropper == None:
		cropper = lambda gen: itertools.islice(gen, 0, seconds * sampler.FRAME_RATE)

	cropped = [cropper(gen) for gen in gens]
	return cropped[0] if len(cropped) == 1 else cropped
583443
def bz2_compress_stream(src, level=9):
    
    compressor = bz2.BZ2Compressor(level)
    for block in src:
        encoded = compressor.compress(block)
        if encoded:
            yield encoded
    yield compressor.flush()
532110
def main(record_time, audio_sample_rate, audio_sample_width,
         audio_iter_size, audio_block_size, audio_flush_size):
    
    end_time = time.time() + record_time
    audio_device = SoundDeviceStream(sample_rate=audio_sample_rate,
                                     sample_width=audio_sample_width,
                                     block_size=audio_block_size,
                                     flush_size=audio_flush_size)
    stream = ConversationStream(source=audio_device,
                                sink=audio_device,
                                iter_size=audio_iter_size,
                                sample_width=audio_sample_width)
    samples = []
    logging.basicConfig(level=logging.INFO)
    logging.info('Starting audio test.')

    stream.start_recording()
    logging.info('Recording samples.')
    while time.time() < end_time:
        samples.append(stream.read(audio_block_size))
    logging.info('Finished recording.')
    stream.stop_recording()

    stream.start_playback()
    logging.info('Playing back samples.')
    while len(samples):
        stream.write(samples.pop(0))
    logging.info('Finished playback.')
    stream.stop_playback()

    logging.info('audio test completed.')
    stream.close()
784334
function downsample(e, sampleRate, outputSampleRate) {
    if (sampleRate <= outputSampleRate) return e;

    var t = e.length;
    sampleRate += 0.0;
    outputSampleRate += 0.0;

    var s = 0,
        o = sampleRate / outputSampleRate,
        u = Math.ceil(t * outputSampleRate / sampleRate),
        a = new Float32Array(u);

    for (var i = 0; i < u; i++) {
        a[i] = e[Math.floor(s)];
        s += o;
    }

    return a;
}
1149305
def vectorize_raw(audio: np.ndarray) -> np.ndarray:
    """"""
    if len(audio) == 0:
        raise InvalidAudio('Cannot vectorize empty audio!')
    return vectorizers[pr.vectorizer](audio)
593626
def _make_sampling_sequence(n):
    # type: (int) -> List[int]
    
    seq = list(range(5))
    i = 50
    while len(seq) < n:
        seq.append(i)
        i += 50
    return seq
377904
def * times
      result = self.slice 0, 0
      frames = self.slice 0..-1
      times.times do
        result.concat frames
      end
      result
    end
604440
async def recv(self):
        
        if self.readyState != 'live':
            raise MediaStreamError

        sample_rate = 8000
        samples = int(AUDIO_PTIME * sample_rate)

        if hasattr(self, '_timestamp'):
            self._timestamp += samples
            wait = self._start + (self._timestamp / sample_rate) - time.time()
            await asyncio.sleep(wait)
        else:
            self._start = time.time()
            self._timestamp = 0

        frame = AudioFrame(format='s16', layout='mono', samples=samples)
        for p in frame.planes:
            p.update(bytes(p.buffer_size))
        frame.pts = self._timestamp
        frame.sample_rate = sample_rate
        frame.time_base = fractions.Fraction(1, sample_rate)
        return frame
1229423
def get_frames(self):
        ""
        nb_frames = self.input_totalframes // self.output_blocksize

        if self.input_totalframes % self.output_blocksize == 0:
            nb_frames -= 1  # Last frame must send eod=True

        for index in xrange(0,
                            nb_frames * self.output_blocksize,
                            self.output_blocksize):
            yield (self.samples[index:index + self.output_blocksize], False)

        yield (self.samples[nb_frames * self.output_blocksize:], True)
954688
def resample(self,N):
        
        return rand.random(size=N)*(self.maxval - self.minval) + self.minval
1187954
def _file_chunks(self, data, chunk_size):
        
        for i in xrange(0, len(data), chunk_size):
            yield self.compressor(data[i:i+chunk_size])
265546
public long resample(final long samples, final Timebase oldRate)
	{
		try
		{
			return resample(samples, oldRate, false);
		}
		catch (ResamplingException e)
		{
			// should never happen
			throw new RuntimeException(e);
		}
	}
58107
def get_mix_gen(self, sample):
        
        def mix(length):
            result = "".join(random.choice(sample) for _ in xrange(length)).strip()
            if len(result) == length:
                return result
            return mix(length)
        return mix
869159
def basic_generator(in_size:int, n_channels:int, noise_sz:int=100, n_features:int=64, n_extra_layers=0, **conv_kwargs):
    ""
    cur_size, cur_ftrs = 4, n_features//2
    while cur_size < in_size:  cur_size *= 2; cur_ftrs *= 2
    layers = [conv_layer(noise_sz, cur_ftrs, 4, 1, transpose=True, **conv_kwargs)]
    cur_size = 4
    while cur_size < in_size // 2:
        layers.append(conv_layer(cur_ftrs, cur_ftrs//2, 4, 2, 1, transpose=True, **conv_kwargs))
        cur_ftrs //= 2; cur_size *= 2
    layers += [conv_layer(cur_ftrs, cur_ftrs, 3, 1, 1, transpose=True, **conv_kwargs) for _ in range(n_extra_layers)]
    layers += [conv2d_trans(cur_ftrs, n_channels, 4, 2, 1, bias=False), nn.Tanh()]
    return nn.Sequential(*layers)
1024870
def gen_chunks(self, gen):
        
        for data in gen:
            size = len(data)
            if size < self.chunk_size:
                yield data
            else:
                mv = buffer(data)
                offset = 0
                while offset < size:
                    nb = min(self.chunk_size, size - offset)
                    yield mv[offset:offset + nb]
                    offset += nb
902513
def generate(self, x, **kwargs):
    
    # Parse and save attack-specific parameters
    assert self.parse_params(**kwargs)

    if self.ord != np.inf:
      raise NotImplementedError(self.ord)
    eta = tf.random_uniform(tf.shape(x), -self.eps, self.eps,
                            dtype=self.tf_dtype)
    adv_x = x + eta
    if self.clip_min is not None or self.clip_max is not None:
      assert self.clip_min is not None and self.clip_max is not None
      adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max)

    return adv_x
174123
function Generator (fn, opts) {
	if (fn instanceof Function) {
		if (typeof opts === 'number') {
			opts = {duration: opts};
		}
		else {
			opts = opts || {};
		}
		opts.generate = fn;
	}
	else {
		opts = fn || {};
	}

	//sort out arguments
	opts = extend({
		//total duration of a stream
		duration: Infinity,

		//time repeat period, in seconds, or 1/frequency
		period: Infinity,

		//inferred from period
		//frequency: 0,

		/**
		 * Generate sample value for a time.
		 * Returns [L, R, ...] or a number for each channel
		 *
		 * @param {number} time current time
		 */
		generate: Math.random
	}, pcm.defaults, opts);

	//align frequency/period
	if (opts.frequency != null) {
		opts.period = 1 / opts.frequency;
	} else {
		opts.frequency = 1 / opts.period;
	}

	let time = 0, count = 0;

	return generate;

	//return sync source/map
	function generate (buffer) {
		if (!buffer) buffer = util.create(opts.samplesPerFrame, opts.channels, opts.sampleRate);

		//get audio buffer channels data in array
		var data = util.data(buffer);

		//enough?
		if (time + buffer.length / opts.sampleRate > opts.duration) return null;

		//generate [channeled] samples
		for (var i = 0; i < buffer.length; i++) {
			var moment = time + i / opts.sampleRate;

			//rotate by period
			if (opts.period !== Infinity) {
				moment %= opts.period;
			}

			var gen = opts.generate(moment);

			//treat null as end
			if (gen === null) {
				return gen;
			}

			//wrap number value
			if (!Array.isArray(gen)) {
				gen = [gen || 0];
			}

			//distribute generated data by channels
			for (var channel = 0; channel < buffer.numberOfChannels; channel++) {
				data[channel][i] = (gen[channel] == null ? gen[0] : gen[channel]);
			}
		}

		//update counters
		count += buffer.length;
		time = count / opts.sampleRate;

		return buffer;
	}
}