Merge the read blocks and resample if necessary.

    Args:
        buffer (list): A list of blocks of samples.
        n_channels (int): The number of channels of the input data.

    Returns:
        np.array: The samples
768893
def process_buffer(buffer, n_channels):
    
    samples = np.concatenate(buffer)

    if n_channels > 1:
        samples = samples.reshape((-1, n_channels)).T
        samples = librosa.to_mono(samples)

    return samples
1310099
async def read(self, n=None):
        
        if self._streamed:
            return b''
        buffer = []
        async for body in self:
            buffer.append(body)
        return b''.join(buffer)
693999
def readBuffer(self, newLength):
        
        result = Buffer(self.buf, self.offset, newLength)
        self.skip(newLength)
        return result
1348041
protected Sample createSampleObject(List<? extends ByteBuffer> nals) {
        byte[] sizeInfo = new byte[nals.size() * 4];
        ByteBuffer sizeBuf = ByteBuffer.wrap(sizeInfo);
        for (ByteBuffer b : nals) {
            sizeBuf.putInt(b.remaining());
        }

        ByteBuffer[] data = new ByteBuffer[nals.size() * 2];

        for (int i = 0; i < nals.size(); i++) {
            data[2 * i] = ByteBuffer.wrap(sizeInfo, i * 4, 4);
            data[2 * i + 1] = nals.get(i);
        }

        return new SampleImpl(data, getCurrentSampleEntry());
    }
143900
def create_sampler(self, inputs, targets, input_reader=None, target_reader=None, 
        input_transform=None, target_transform=None, co_transform=None,
        input_return_processor=None, target_return_processor=None, co_return_processor=None):
        
        pass
718380
def sample_batch_trajectories(self, rollout_length, history_length):
        
        # Sample from up to total size
        if self.current_size < self.buffer_capacity:
            if rollout_length + 1 > self.current_size:
                raise VelException("Not enough elements in the buffer to sample the rollout")

            # -1 because we cannot take the last one
            return np.random.choice(self.current_size - rollout_length) + rollout_length - 1
        else:
            if rollout_length + history_length > self.current_size:
                raise VelException("Not enough elements in the buffer to sample the rollout")

            candidate = np.random.choice(self.buffer_capacity)

            # These are the elements we cannot draw, as then we don't have enough history
            forbidden_ones = (
                    np.arange(self.current_idx, self.current_idx + history_length + rollout_length - 1)
                    % self.buffer_capacity
            )

            # Exclude these frames for learning as they may have some part of history overwritten
            while candidate in forbidden_ones:
                candidate = np.random.choice(self.buffer_capacity)

            return candidate
474788
def _new_sample(self, sink):
        
        if self.running:
            # New data is available from the pipeline! Dump it into our
            # queue (or possibly block if we're full).
            buf = sink.emit('pull-sample').get_buffer()

            # We can't use Gst.Buffer.extract() to read the data as it crashes
            # when called through PyGObject. We also can't use
            # Gst.Buffer.extract_dup() because we have no way in Python to free
            # the memory that it returns. Instead we get access to the actual
            # data via Gst.Memory.map().
            mem = buf.get_all_memory()
            success, info = mem.map(Gst.MapFlags.READ)
            if success:
                data = info.data
                mem.unmap(info)
                self.queue.put(data)
            else:
                raise GStreamerError("Unable to map buffer memory while reading the file.")
        return Gst.FlowReturn.OK
407760
def set_data(self, data_buffer):
        
        if len(data_buffer) % (self.sample_width * self.channels) != 0:
            raise ValueError("length of data_buffer must be a multiple of (sample_width * channels)")
        self._buffer = data_buffer
        self._index = 0
        self._left = 0 if self._buffer is None else len(self._buffer)
1057811
def recv(self, timeout=None):
        
        with self.lock:
            if timeout != None:
                if self.readable(timeout) == False:
                    return None
            data = self._raw_recv()
            segments = data.split()

            if segments[1] == 'JOIN':
                who = self._from_(segments[0][1:])
                channel = segments[2][1:]
                if channel not in self.channels:
                    self.stepback(append=False)
                    return 'JOIN', self.join_(channel, process_only=True)
                else:
                    self.channels[channel]['USERS'][who[0]] = \
                    ['', '', '', '', '']
                return 'JOIN', (who, channel)

            elif segments[1] == 'PART':
                who = self._from_(segments[0].replace(':', '', 1))
                channel = segments[2]
                del self.channels[channel]['USERS'][who[0]]
                try:
                    reason = ' '.join(segments[3:]).replace(':', '', 1)
                    return 'PART', (who, channel, reason)
                except IndexError:
                    who = self._from_(segments[0].replace(':', '', 1))
                    return 'PART', (who, channel, '')

            elif segments[1] == 'PRIVMSG':
                who = self._from_(segments[0].replace(':', '', 1))
                msg = ' '.join(segments[3:]).replace(':', '', 1)
                rvalue = 'PRIVMSG', (who, segments[2], msg)

                if msg.find('\001') == 0:
                    rctcp = self.ctcp_decode(msg)
                    return 'CTCP', (rvalue[1][0], rvalue[1][1], rctcp)
                else:
                    return rvalue

            elif segments[1] == 'NOTICE':
                who = self._from_(segments[0].replace(':', '', 1))
                msg = ' '.join(segments[3:]).replace(':', '', 1)
                if msg.find('\001') == 0:
                    msg = self.ctcp_decode(msg)
                    return 'CTCP_REPLY', (who, segments[2], msg)
                return 'NOTICE', (who, segments[2], msg)

            elif segments[1] == 'MODE':
                mode = ' '.join(segments[3:]).replace(':', '', 1)
                who = self._from_(segments[0][1:])
                target = segments[2]
                if target != self.current_nick:
                    self.parse_cmode_string(mode, target)
                    return 'MODE', (who, segments[2], mode)
                else:
                    return 'MODE', (who, mode.replace(':', '', 1))

            elif segments[1] == 'KICK':
                who = self._from_(segments[0].replace(':', '', 1))
                if self.current_nick == segments[3]:
                    del self.channels[segments[2]]
                else:
                    del self.channels[segments[2]]['USERS'][segments[3]]
                reason = ' '.join(segments[4:]).replace(':', '', 1)
                return 'KICK', (who, segments[2], segments[3], reason)

            elif segments[1] == 'INVITE':
                who = self._from_(segments[0].replace(':', '', 1))
                channel = segments[3].replace(':', '', 1)
                return 'INVITE', (who, segments[2], channel)

            elif segments[1] == 'NICK':
                who = self._from_(segments[0].replace(':', '', 1))
                new_nick = ' '.join(segments[2:]).replace(':', '', 1)
                if self.current_nick == who[0]:
                    self.current_nick = new_nick
                for channel in self.channels:
                    if who[0] in self.channels[channel]['USERS']:
                        priv_level = self.channels[channel]['USERS'][who[0]]
                        del self.channels[channel]['USERS'][who[0]]
                        self.channels[channel]['USERS'][new_nick] = priv_level
                return 'NICK', (who, new_nick)

            elif segments[1] == 'TOPIC':
                who = self._from_(segments[0].replace(':', '', 1))
                channel = segments[2]
                topic = ' '.join(segments[3:]).replace(':', '', 1)
                self.channels[channel]['TOPIC'] = topic
                return 'TOPIC', (who, channel, topic)

            elif segments[1] == 'QUIT':
                who = self._from_(segments[0].replace(':', '', 1))
                msg = ' '.join(segments[2:]).replace(':', '', 1)
                for channel in self.channels:
                    if who[0] in self.channels[channel]['USERS']:
                        del self.channels[channel]['USERS'][who[0]]
                return 'QUIT', (who, msg)

            elif segments[1] == '250':
                self.lusers['HIGHESTCONNECTIONS'] = segments[6]
                self.lusers['TOTALCONNECTIONS'] = segments[9][1:]
                return 'LUSERS', self.lusers

            elif segments[1] == '251':
                self.lusers['USERS'] = segments[5]
                self.lusers['INVISIBLE'] = segments[8]
                self.lusers['SERVERS'] = segments[11]
                return 'LUSERS', self.lusers

            elif segments[1] == '252':
                self.lusers['OPERATORS'] = segments[3]
                return 'LUSERS', self.lusers

            elif segments[1] == '253':
                self.lusers['UNKNOWN'] = segments[3]
                return 'LUSERS', self.lusers

            elif segments[1] == '254':
                self.lusers['CHANNELS'] = segments[3]
                return 'LUSERS', self.lusers

            elif segments[1] == '255':
                self.lusers['CLIENTS'] = segments[5]
                self.lusers['LSERVERS'] = segments[8]
                return 'LUSERS', self.lusers

            elif segments[1] == '265':
                self.lusers['LOCALUSERS'] = segments[6]
                self.lusers['LOCALMAX'] = segments[8]
                return 'LUSERS', self.lusers

            elif segments[1] == '266':
                self.lusers['GLOBALUSERS'] = segments[6]
                self.lusers['GLOBALMAX'] = segments[8]
                return 'LUSERS', self.lusers

            elif segments[0] == 'ERROR':
                self.quit()
                return 'ERROR', ' '.join(segments[1:]).replace(':', '', 1)
            else:
                self.stepback(append=False)
                return 'UNKNOWN', self._recv(rm_first=False)
31423
public void getChannelSamples(int channel, double[] interleavedSamples,
                                  double[] channelSamples) {
        int nbChannels = getFormat().getChannels();
        for (int i = 0; i < channelSamples.length; i++) {
            channelSamples[i] = interleavedSamples[nbChannels * i + channel];
        }
    }
853608
public void addSamplesToMD5(int[] samples, int count, int channels,
      int sampleSize) {
    int bytesPerSample = sampleSize/8;
    if(sampleSize%8 != 0)
      bytesPerSample++;
    if(_dataMD5 == null || _dataMD5.length < count*bytesPerSample*channels) {
      _dataMD5 = new byte[count*bytesPerSample*channels];
    }
    byte[] dataMD5 = _dataMD5;
    splitSamplesToBytes(samples, count*channels, bytesPerSample, dataMD5);
    md.update(dataMD5, 0, count*bytesPerSample*channels);
  }
38139
def sample(self, N=1):
        
        if not self.filt:
            self.forward()
        paths = np.empty((len(self.filt), N), np.int)
        paths[-1, :] = rs.multinomial(self.filt[-1], M=N)
        log_trans = np.log(self.hmm.trans_mat)
        for t, f in reversed(list(enumerate(self.filt[:-1]))):
            for n in range(N):
                probs = rs.exp_and_normalise(log_trans[:, paths[t + 1, n]] + np.log(f))
                paths[t, n] = rs.multinomial_once(probs)
        return paths
1019298
private void mixChannelIntoBuffers(final int[] leftBuffer, final int[] rightBuffer, final int startIndex, final int endIndex, final ChannelMemory actMemo)
	{
		for (int i=startIndex; i<endIndex; i++)
		{
			// Retrieve the Sampledata for this point (interpolated, if necessary)
			long sample = actMemo.currentSample.getInterpolatedSample(doISP, actMemo.currentSamplePos, actMemo.currentTuningPos);

			// Resonance Filters
			if (actMemo.filterOn) sample = doResonance(actMemo, sample);

			// Volume Ramping (deClick) Left!
			long volL = actMemo.actRampVolLeft;
			if ((actMemo.deltaVolLeft>0 && volL>actMemo.actVolumeLeft) ||
				(actMemo.deltaVolLeft<0 && volL<actMemo.actVolumeLeft))
			{
				volL = actMemo.actRampVolLeft = actMemo.actVolumeLeft;
				actMemo.deltaVolLeft = 0;
			}
			else
			{
				actMemo.actRampVolLeft += actMemo.deltaVolLeft;
			}
			// Volume Ramping (deClick) Right!
			long volR = actMemo.actRampVolRight;
			if ((actMemo.deltaVolRight>0 && volR>actMemo.actVolumeRight) ||
				(actMemo.deltaVolRight<0 && volR<actMemo.actVolumeRight))
			{
				volR = actMemo.actRampVolRight = actMemo.actVolumeRight;
				actMemo.deltaVolRight = 0;
			}
			else
			{
				actMemo.actRampVolRight += actMemo.deltaVolRight;
			}
			
			// Fit into volume for the two channels
			leftBuffer[i] += (int)((sample * volL) >> Helpers.MAXVOLUMESHIFT);
			rightBuffer[i]+= (int)((sample * volR) >> Helpers.MAXVOLUMESHIFT);

			// Now fit the loops of the current Sample
			fitIntoLoops(actMemo);
			if (actMemo.instrumentFinished) break;
		}
	}
180542
def packet_get_samples_per_frame(data, fs):
    """"""

    data_pointer = ctypes.c_char_p(data)

    result = _packet_get_nb_frames(data_pointer, ctypes.c_int(fs))
    if result < 0:
        raise OpusError(result)

    return result
1085678
def byte_to_channels(self, byte):
        
        # pylint: disable-msg=R0201
        assert isinstance(byte, int)
        assert byte >= 0
        assert byte < 256
        result = []
        for offset in range(0, 8):
            if byte & (1 << offset):
                result.append(offset + 1)
        return result
561558
def _feed_buffer(self, n=1):
        
        buffer = bytearray(self._stream.read())
        while len(buffer) < n:
            try:
                message = yield from self._protocol.recv()
            except ConnectionClosed:
                message = None
            if message is None:
                break
            if not isinstance(message, bytes):
                raise TypeError("message must be bytes")
            buffer.extend(message)
        self._stream = io.BytesIO(buffer)
384745
def decode_buffer(buffer: dict) -> np.ndarray:
    
    buf = np.frombuffer(buffer['data'], dtype=buffer['dtype'])
    return buf.reshape(buffer['shape'])