/* Split Samples to bytes(for sending to MD5)
CURRENTLY ONLY MAY WORK FOR: sample sizes which are divisible by 8. Need
to create some audio to test with.
357096
private static final void splitSamplesToBytes(int[] samples, int totalSamples,
    int bytesPerSample, byte[] dataMD5) {
    int destIndexBase = 0;
    int i = 0;
    
    switch(bytesPerSample) {
      case 3:
        for(; i < totalSamples; i++) {
        dataMD5[destIndexBase++] = (byte)(samples[i]);
        dataMD5[destIndexBase++] = (byte)(samples[i] >> 8);
        dataMD5[destIndexBase++] = (byte)(samples[i] >> 16);
        }
        break;
      case 2:
        for(; i < totalSamples; i++) {
        dataMD5[destIndexBase++] = (byte)(samples[i]);
        dataMD5[destIndexBase++] = (byte)(samples[i] >> 8);
        }
        break;
      case 1:
        for(; i < totalSamples; i++) {
        dataMD5[i] = (byte)samples[i];
        }
    }
  }
177793
function (geoTiffData, byteOffset, numOfBytes, sampleFormat, isLittleEndian) {
                var res;

                switch (sampleFormat) {
                    case TiffConstants.SampleFormat.UNSIGNED:
                        res = this.getBytes(geoTiffData, byteOffset, numOfBytes, isLittleEndian, false);
                        break;
                    case TiffConstants.SampleFormat.SIGNED:
                        res = this.getBytes(geoTiffData, byteOffset, numOfBytes, isLittleEndian, true);
                        break;
                    case TiffConstants.SampleFormat.IEEE_FLOAT:
                        if (numOfBytes == 3) {
                            res = geoTiffData.getFloat32(byteOffset, isLittleEndian) >>> 8;
                        } else if (numOfBytes == 4) {
                            res = geoTiffData.getFloat32(byteOffset, isLittleEndian);
                        } else if (numOfBytes == 8) {
                            res = geoTiffData.getFloat64(byteOffset, isLittleEndian);
                        }
                        else {
                            Logger.log(Logger.LEVEL_WARNING, "Do not attempt to parse the data  not handled: " +
                                numOfBytes);
                        }
                        break;
                    case TiffConstants.SampleFormat.UNDEFINED:
                    default:
                        res = this.getBytes(geoTiffData, byteOffset, numOfBytes, isLittleEndian, false);
                        break;
                }

                return res;
            }
1135219
def sample_data(count: 5, mode: 'tabular')
      mode = mode.to_s.downcase
      unless SAMPLE_DATA_OUTPUT.include?(mode)
        raise Errors::InvalidConfigurationError, "Mode must be one of '#{SAMPLE_DATA_OUTPUT.join(', ')}'. Given: #{mode}"
      end
      samples = all { |x| x.limit(count) }.to_a
      return samples if mode == 'raw'
      return {} if samples.count == 0

      # tabular output
      schm = schema_inferrer.infer_schema(dataset: samples, extended: true)
      keys = schm.keys
      res = samples.map do |sample|
        keys.map do |key|
          value = record_value(record: sample, key: key)
          next if value.nil?
          [key, value]
        end.compact.to_h
      end

      res
    end
865148
function decodeSample$1(muLawSample) {
  /** @type {number} */
  let sign;
  /** @type {number} */
  let exponent;
  /** @type {number} */
  let mantissa;
  /** @type {number} */
  let sample;
  muLawSample = ~muLawSample;
  sign = (muLawSample & 0x80);
  exponent = (muLawSample >> 4) & 0x07;
  mantissa = muLawSample & 0x0F;
  sample = decodeTable[exponent] + (mantissa << (exponent+3));
  if (sign != 0) sample = -sample;
  return sample;
}
880618
public final static Sample append(List<Sample> samples) {
        if (samples.size() == 0) {
            return buildSample(0, new double[0]);
        }

        int sampleCount = 0;

        // append voices to each other
        double[] first = samples.get(0).getInterleavedSamples();
        sampleCount += samples.get(0).getSampleCount();

        double[][] samples_ary = new double[samples.size() - 1][];
        for (int i = 0; i < samples_ary.length; i++) {
            samples_ary[i] = samples.get(i + 1).getInterleavedSamples();
            sampleCount += samples.get(i + 1).getSampleCount();
        }

        double[] appended = concatAll(first, samples_ary);

        return buildSample(sampleCount, appended);
    }
438825
private DiffPart decodePaste(final int blockSize_S, final int blockSize_B,
			final BitReader r)
		throws DecodingException
	{

		if (blockSize_S < 1 || blockSize_B < 1) {
			throw new DecodingException("Invalid value for blockSize_S: "
					+ blockSize_S + " or blockSize_B: " + blockSize_B);
		}

		int s = r.read(blockSize_S);
		int b = r.read(blockSize_B);

		DiffPart part = new DiffPart(DiffAction.PASTE);
		part.setStart(s);
		part.setText(Integer.toString(b));

		r.skip();

		return part;
	}
1008836
private static ByteBuffer convertAudioBytes(byte[] audio_bytes, boolean two_bytes_data) {
		ByteBuffer dest = ByteBuffer.allocateDirect(audio_bytes.length);
		dest.order(ByteOrder.nativeOrder());
		ByteBuffer src = ByteBuffer.wrap(audio_bytes);
		src.order(ByteOrder.LITTLE_ENDIAN);
		if (two_bytes_data) {
			ShortBuffer dest_short = dest.asShortBuffer();
			ShortBuffer src_short = src.asShortBuffer();
			while (src_short.hasRemaining())
				dest_short.put(src_short.get());
		} else {
			while (src.hasRemaining())
				dest.put(src.get());
		}
		dest.rewind();
		return dest;
	}
534223
private void outputSamples() {
        int samples;
        while ((samples = vorbisDspState.synthesis_pcmout(_pcmf, _index)) > 0) {
            float[][] pcmf = _pcmf[0];
            bout = (samples < convsize ? samples : convsize);
            // convert doubles to 16 bit signed ints (host order) and
            // interleave
            for (i = 0; i < vorbisInfo.channels; i++) {
                int pointer = i * 2;
                //int ptr=i;
                int mono = _index[i];
                for (int j = 0; j < bout; j++) {
                    double fVal = pcmf[i][mono + j] * 32767.;
                    int val = (int) (fVal);
                    if (val > 32767) {
                        val = 32767;
                    }
                    if (val < -32768) {
                        val = -32768;
                    }
                    if (val < 0) {
                        val = val | 0x8000;
                    }
                    convbuffer[pointer] = (byte) (val);
                    convbuffer[pointer + 1] = (byte) (val >>> 8);
                    pointer += 2 * (vorbisInfo.channels);
                }
            }
            LOG.log(Level.FINE, "about to write: {0}", 2 * vorbisInfo.channels * bout);
            if (getCircularBuffer().availableWrite() < 2 * vorbisInfo.channels * bout) {
                LOG.log(Level.FINE, "Too much data in this data packet, better return, let the channel drain, and try again...");
                playState = playState_BufferFull;
                return;
            }
            getCircularBuffer().write(convbuffer, 0, 2 * vorbisInfo.channels * bout);
            if (bytes < bufferSize_) {
                LOG.log(Level.FINE, "Finished with final buffer of music?");
            }
            if (vorbisDspState.synthesis_read(bout) != 0) {
                LOG.log(Level.FINE, "VorbisDspState.synthesis_read returned -1.");
            }
        } // while(samples...)
        playState = playState_ReadData;
    }
242409
private function spread(
        $md5,
        $splitCount = 2
    ) {
        $path = '';

        for ($i = 0; $i < $splitCount; ++$i) {
            $path .= $md5 [$i] . '/';
        }

        $path .= substr(
            $md5,
            $splitCount
        );

        return $path;
    }
591616
def _bytes_to_values(self, bs, width=None):
        

        if self.bitdepth == 8:
            return bytearray(bs)
        if self.bitdepth == 16:
            return array('H',
                         struct.unpack('!%dH' % (len(bs) // 2), bs))

        assert self.bitdepth < 8
        if width is None:
            width = self.width
        # Samples per byte
        spb = 8 // self.bitdepth
        out = bytearray()
        mask = 2**self.bitdepth - 1
        shifts = [self.bitdepth * i
                  for i in reversed(list(range(spb)))]
        for o in bs:
            out.extend([mask & (o >> i) for i in shifts])
        return out[:width]
854444
public int samplesAvailableToEncode() {
    int available = 0;
    //sum all in blockQueue
    int channels = streamConfig.getChannelCount();
    for(BlockEncodeRequest ber : preparedRequests) {
      int[] block = ber.samples;
      available += block.length/channels;
    }
    if (unfilledRequest != null)
      available += unfilledRequest.count;
    return available;
  }
713640
def remove_sample(self, md5):
        """"""

        # Grab the sample
        record = self.database[self.sample_collection].find_one({'md5': md5})
        if not record:
            return

        # Delete it
        print 'Deleting sample: %s (%.2f MB)...' % (record['md5'], record['length']/1024.0/1024.0)
        self.database[self.sample_collection].remove({'md5': record['md5']})
        self.gridfs_handle.delete(record['__grid_fs'])

        # Print info
        print 'Sample Storage: %.2f out of %.2f MB' % (self.sample_storage_size(), self.samples_cap)
333838
function splitStr2Obj(source) {
    var result = {};
    each(
        source.split(','),
        function (key) {
            result[key] = key;
        }
    );
    return result;
}
272216
public SampleFormat[] getSupportedSampleFormats() {
		IntPointer sampleFormatsPointer = avCodec.sample_fmts();

		if (getType() != MediaType.AUDIO || sampleFormatsPointer == null)
			return null;

		List<SampleFormat> sampleFormats = new ArrayList<SampleFormat>();

		int format;
		int index = 0;
		while ((format = sampleFormatsPointer.get(index++)) != -1)
			sampleFormats.add(SampleFormat.byId(format));

		return sampleFormats.toArray(new SampleFormat[0]);
	}
1246275
public static MD5Digest fromBytes(byte[] md5Bytes, int offset) {
    byte[] md5BytesCopy = Arrays.copyOfRange(md5Bytes, offset, offset + MD5_BYTES_LENGTH);
    //TODO: Replace this with a version that encodes without needing a copy.
    String md5String = Hex.encodeHexString(md5BytesCopy);
    return new MD5Digest(md5String, md5BytesCopy);
  }
1205469
private void processAudioBox(SampleTableBox stbl, AudioSampleEntry ase, long scale) {
        // get codec
        String codecName = ase.getType();
        // set the audio codec here - may be mp4a or...
        setAudioCodecId(codecName);
        log.debug("Sample size: {}", ase.getSampleSize());
        long ats = ase.getSampleRate();
        // skip invalid audio time scale
        if (ats > 0) {
            audioTimeScale = ats * 1.0;
        }
        log.debug("Sample rate (audio time scale): {}", audioTimeScale);
        audioChannels = ase.getChannelCount();
        log.debug("Channels: {}", audioChannels);
        if (ase.getBoxes(ESDescriptorBox.class).size() > 0) {
            // look for esds
            ESDescriptorBox esds = ase.getBoxes(ESDescriptorBox.class).get(0);
            if (esds == null) {
                log.debug("esds not found in default path");
                // check for decompression param atom
                AppleWaveBox wave = ase.getBoxes(AppleWaveBox.class).get(0);
                if (wave != null) {
                    log.debug("wave atom found");
                    // wave/esds
                    esds = wave.getBoxes(ESDescriptorBox.class).get(0);
                    if (esds == null) {
                        log.debug("esds not found in wave");
                        // mp4a/esds
                        //AC3SpecificBox mp4a = wave.getBoxes(AC3SpecificBox.class).get(0);
                        //esds = mp4a.getBoxes(ESDescriptorBox.class).get(0);
                    }
                }
            }
            //mp4a: esds
            if (esds != null) {
                // http://stackoverflow.com/questions/3987850/mp4-atom-how-to-discriminate-the-audio-codec-is-it-aac-or-mp3
                ESDescriptor descriptor = esds.getEsDescriptor();
                if (descriptor != null) {
                    DecoderConfigDescriptor configDescriptor = descriptor.getDecoderConfigDescriptor();
                    AudioSpecificConfig audioInfo = configDescriptor.getAudioSpecificInfo();
                    if (audioInfo != null) {
                        audioDecoderBytes = audioInfo.getConfigBytes();
                        /* the first 5 (0-4) bits tell us about the coder used for aacaot/aottype
                         * http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio
                         0 - NULL
                         1 - AAC Main (a deprecated AAC profile from MPEG-2)
                         2 - AAC LC or backwards compatible HE-AAC 
                         3 - AAC Scalable Sample Rate
                         4 - AAC LTP (a replacement for AAC Main, rarely used)
                         5 - HE-AAC explicitly signaled (Non-backward compatible)
                        23 - Low Delay AAC
                        29 - HE-AACv2 explicitly signaled
                        32 - MP3on4 Layer 1
                        33 - MP3on4 Layer 2
                        34 - MP3on4 Layer 3
                        */
                        byte audioCoderType = audioDecoderBytes[0];
                        //match first byte
                        switch (audioCoderType) {
                            case 0x02:
                                log.debug("Audio type AAC LC");
                            case 0x11: //ER (Error Resilient) AAC LC
                                log.debug("Audio type ER AAC LC");
                            default:
                                audioCodecType = 1; //AAC LC
                                break;
                            case 0x01:
                                log.debug("Audio type AAC Main");
                                audioCodecType = 0; //AAC Main
                                break;
                            case 0x03:
                                log.debug("Audio type AAC SBR");
                                audioCodecType = 2; //AAC LC SBR
                                break;
                            case 0x05:
                            case 0x1d:
                                log.debug("Audio type AAC HE");
                                audioCodecType = 3; //AAC HE
                                break;
                            case 0x20:
                            case 0x21:
                            case 0x22:
                                log.debug("Audio type MP3");
                                audioCodecType = 33; //MP3
                                audioCodecId = "mp3";
                                break;
                        }
                        log.debug("Audio coder type: {} {} id: {}", new Object[] { audioCoderType, Integer.toBinaryString(audioCoderType), audioCodecId });
                    } else {
                        log.debug("Audio specific config was not found");
                        DecoderSpecificInfo info = configDescriptor.getDecoderSpecificInfo();
                        if (info != null) {
                            log.debug("Decoder info found: {}", info.getTag());
                            // qcelp == 5
                        }
                    }
                } else {
                    log.debug("No ES descriptor found");
                }
            }
        } else {
            log.debug("Audio sample entry had no descriptor");
        }
        processAudioStbl(stbl, scale);
    }
732951
def split_sequence_file_on_sample_ids_to_files(seqs,
                                               outdir):
    
    logger = logging.getLogger(__name__)
    logger.info('split_sequence_file_on_sample_ids_to_files'
                ' for file %s into dir %s' % (seqs, outdir))

    outputs = {}

    for bits in sequence_generator(seqs):
        sample = sample_id_from_read_id(bits[0])

        if sample not in outputs:
            outputs[sample] = open(join(outdir, sample + '.fasta'), 'w')
        outputs[sample].write(">%s\n%s\n" % (bits[0], bits[1]))
    for sample in outputs:
        outputs[sample].close()
    logger.info('split to %d files' % len(outputs))