@param [LegoNXT::UsbConnection, LegoNXT::SerialConnection] connection The connection object.
 Plays a tone.

 @param [Integer] frequency Range: 200-1400Hz
 @param [Integer] duration in milliseconds (1/1000 of a second)
 @return [nil]
424977
def play_tone frequency, duration
      raise ArgumentError.new("Frequency must be between 200-1400Hz; got #{frequency}") if frequency < 200 || frequency > 1400
      transmit(
        DirectOps::NO_RESPONSE,
        DirectOps::PLAYTONE,
        word(frequency),
        word(duration)
      )
    end
1133652
function Connection(opts) {

    EventEmitter.call(this);

    opts = opts || {};

    _.defaults(opts, {
        host: 'localhost',
        port: '11211',
        reconnect: true,
        maxValueSize: 1048576
    });

    this.host = opts.host;
    this.port = opts.port;

    this.commandBuffer = new Immutable.List();

    if (opts.onConnect) {
        this.onConnect = opts.onConnect;
    }

    if (opts.onError) {
        this.onError = opts.onError;
    } else {
        this.onError = function onError(err) { this.emit('error'); console.error(err); };
    }
    this.bufferBeforeError = opts.bufferBeforeError;
    this.netTimeout = opts.netTimeout || 500;
    this.backoffLimit = opts.backoffLimit || 10000;
    this.reconnect = opts.reconnect;
    this.disconnecting = false;
    this.ready = false;
    this.backoff = opts.backoff || 10;
    this.maxValueSize = opts.maxValueSize;
    this.writeBuffer = new Immutable.List();

    this.connect();
}
920166
def attenuator_connection(self, connect=True):
        
        # all or none will be connected
        acquisition_modules = [self.explorer, self.protocoler, self.bs_calibrator, self.tone_calibrator, self.charter]
        if connect:
            if not acquisition_modules[0].player.attenuator_connected():
                #attempt to re-connect first
                for module in acquisition_modules:
                    success = module.player.connect_attenuator()
                if success is None:
                    StimulusModel.setMinVoltage(0.0)
                    return False
                else:
                    StimulusModel.setMinVoltage(0.005)
                    return True
            else:
                StimulusModel.setMinVoltage(0.005)
                return True
        else:
            for module in acquisition_modules:
                module.player.connect_attenuator(False)
            StimulusModel.setMinVoltage(0.0)
            return False
1024174
public ZooKeeperUpdatingListenerBuilder connectTimeout(Duration connectTimeout) {
        requireNonNull(connectTimeout, "connectTimeout");
        checkArgument(!connectTimeout.isZero() && !connectTimeout.isNegative(),
                      "connectTimeout: %s (expected: > 0)", connectTimeout);
        return connectTimeoutMillis(connectTimeout.toMillis());
    }
112969
def _jitter(self, durations, event, jitter_level, seed=None):
        
        np.random.seed(seed)

        if jitter_level <= 0:
            raise ValueError("The jitter level is less than zero, please select a jitter value greater than 0")

        event_times = durations[event != 0].copy()
        n = event_times.shape[0]

        # Determining extent to jitter event times up or down
        shift = np.random.uniform(low=-1, high=1, size=n) * jitter_level
        event_times += shift
        durations_jitter = event_times.align(durations)[0].fillna(durations)

        # Recursive call if event times are still tied after jitter
        if self._check_for_duplicates(durations=durations_jitter, events=event):
            return self._jitter(durations=durations_jitter, event=event, jitter_level=jitter_level, seed=seed)
        return durations_jitter
1136572
function FourierTransform(bufferSize, sampleRate) {
  this.bufferSize = bufferSize;
  this.sampleRate = sampleRate;
  this.bandwidth  = 2 / bufferSize * sampleRate / 2;

  this.spectrum   = new Float32Array(bufferSize/2);
  this.real       = new Float32Array(bufferSize);
  this.imag       = new Float32Array(bufferSize);

  this.peakBand   = 0;
  this.peak       = 0;

  /**
   * Calculates the *middle* frequency of an FFT band.
   *
   * @param {Number} index The index of the FFT band.
   *
   * @returns The middle frequency in Hz.
   */
  this.getBandFrequency = function(index) {
    return this.bandwidth * index + this.bandwidth / 2;
  };

  this.calculateSpectrum = function() {
    var spectrum  = this.spectrum,
        real      = this.real,
        imag      = this.imag,
        bSi       = 2 / this.bufferSize,
        sqrt      = Math.sqrt,
        rval, 
        ival,
        mag;

    for (var i = 0, N = bufferSize/2; i < N; i++) {
      rval = real[i];
      ival = imag[i];
      mag = bSi * sqrt(rval * rval + ival * ival);

      if (mag > this.peak) {
        this.peakBand = i;
        this.peak = mag;
      }

      spectrum[i] = mag;
    }
  };
}
198740
function( connection ) {
    this._users = []; // Collect high-level information about users
    this._channels = {}; // Collect high-level information about channels
    this.sessions = {}; // Sessions to user map

    // TODO: We are storing the users twice to avoid some looping. Is this the
    // best approach?

    /**
     * @summary Defines whether the connection has been succesffully handshaken.
     *
     * @description
     * The connection is considered `ready` when the server handshake has been
     * processed and the initial ping has been received.
     *
     * @name MumbleClient#ready
     * @type Boolean
     */
    this.ready = false;

    /**
     * @summary The internal {@link MumbleConnection} object.
     *
     * @description
     * The connection object is used for the low level access to the Mumble
     * protocol. Most developers should find a higher level APIs for the
     * functionality on the {@link MumbleClient} class instead.
     *
     * @name MumbleClient#connection
     * @type MumbleConnection
     */
    this.connection = connection;

    /**
     * @summary The server root channel.
     *
     * @name MumbleClient#rootChannel
     * @type Channel
     */
    this.rootChannel = undefined;

    /**
     * @summary The current user.
     *
     * @name MumbleClient#user
     * @type User
     */
    this.user = undefined;

    this._gotServerSync = false;
    this._gotInitialPing = false;

    // Generate list of free whisper target IDs.
    this.freeTargets = [];
    for( var i = 1; i <= 30; i++ ) {
        this.freeTargets.push( i );
    }

    /*
     * Forward all events from the connection
     */
    this.on( 'newListener', function( event, listener ) {
        connection.on( event, listener );
    } );

    connection.once( 'ping', this._initialPing.bind( this ) );
    connection.on( 'channelRemove', this._channelRemove.bind( this ) );
    connection.on( 'userRemove', this._userRemove.bind( this ) );
    connection.on( 'serverSync', this._serverSync.bind( this ) );
    connection.on( 'userState', this._userState.bind( this ) );
    connection.on( 'channelState', this._channelState.bind( this ) );
    connection.on( 'permissionQuery', this._permissionQuery.bind( this ) );
    connection.on( 'textMessage', this._textMessage.bind( this ) );
}
285093
def from_frequency(cls, freq):
        
        if 0 < freq <= 20000:
            return super(Tone, cls).__new__(cls, freq)
        raise ValueError('invalid frequency: %.2f' % freq)
254626
def filter_butter_plot_freqresponse(b, a, samplerate, numpoints=2000):
    # type: (Seq[float], Seq[float], int, int) -> None
    
    import matplotlib.pyplot as plt
    plt.figure(1)
    plt.clf()
    w, h = signal.freqz(b, a, worN=numpoints)
    plt.semilogx((samplerate*0.5/np.pi) * w, np.abs(h))
    plt.xlabel('Freq (Hz)')
    plt.ylabel('Gain')
    plt.grid(True)
    plt.show()
1005558
function () {
    var duration = 50;

    // Check if there is any data in the queue
    if (audioDataQueue.length > 0) {

        // Concatenate up to concatenateMaxChunks data arrays from the queue
        var concatenatedData = [];
        for (var i = 0; i < concatenateMaxChunks; i++) {
            if (audioDataQueue.length === 0) {
                break;
            }
            concatenatedData = concatenatedData.concat(audioDataQueue.shift());
        }

        // Play the audio
        duration = playAudio(concatenatedData) * 1000;
    }

    // Still capturing? Then call myself to continue consuming incoming data.
    if (window.audioinput && audioinput.isCapturing()) {
        timerGetNextAudio = setTimeout(getNextToPlay, duration);
    }
}
1139481
def send_heartbeat
      millis = Time.now.strftime('%s%L').to_i
      @bot.debug("Sending voice heartbeat at #{millis}")

      @client.send({
        op: 3,
        d: nil
      }.to_json)
    end
1100181
def modulate(data):
	'''
	 
	'''
	seconds_per_sample = 1.0 / audiogen.sampler.FRAME_RATE
	phase, seconds, bits = 0, 0, 0

	# construct generators
	clock = (x / BAUD_RATE for x in itertools.count(1))
	tones = (MARK_HZ if bit else SPACE_HZ for bit in data)

	for boundary, frequency in itertools.izip(clock, tones):
		# frequency of current symbol is determined by how much 
		# we advance the signal's phase in each audio frame
		phase_change_per_sample = TWO_PI / (audiogen.sampler.FRAME_RATE / frequency)

		# produce samples for the current symbol 
		# until we reach the next clock boundary
		while seconds < boundary:
			yield math.sin(phase)

			seconds += seconds_per_sample
			phase += phase_change_per_sample

			if phase > TWO_PI:
				phase -= TWO_PI

		bits += 1
		logger.debug("bits = %d, time = %.7f ms, expected time = %.7f ms, error = %.7f ms, baud rate = %.6f Hz" \
			% (bits, 1000 * seconds, 1000 * bits / BAUD_RATE, 1000 * (seconds - bits / BAUD_RATE), bits / seconds))
548745
function() {
		this.context = new AudioContext();
		this.sampleRate = this.context.sampleRate;
		this.gainNode = this.context.createGain();
		this.gainNode.connect( this.context.destination );
	}
156315
def play_internal
      count = 0
      @playing = true

      # Default play length (ms), will be adjusted later
      @length = IDEAL_LENGTH

      self.speaking = true
      loop do
        # Starting from the tenth packet, perform length adjustment every 100 packets (2 seconds)
        should_adjust_this_packet = (count % @adjust_interval == @adjust_offset)

        # If we should adjust, start now
        @length_adjust = Time.now.nsec if should_adjust_this_packet

        break unless @playing

        # If we should skip, get some data, discard it and go to the next iteration
        if @skips.positive?
          @skips -= 1
          yield
          next
        end

        # Track packet count, sequence and time (Discord requires this)
        count += 1
        increment_packet_headers

        # Get packet data
        buf = yield

        # Stop doing anything if the stop signal was sent
        break if buf == :stop

        # Proceed to the next packet if we got nil
        next unless buf

        # Track intermediate adjustment so we can measure how much encoding contributes to the total time
        @intermediate_adjust = Time.now.nsec if should_adjust_this_packet

        # Send the packet
        @udp.send_audio(buf, @sequence, @time)

        # Set the stream time (for tracking how long we've been playing)
        @stream_time = count * @length / 1000

        if @length_override # Don't do adjustment because the user has manually specified an override value
          @length = @length_override
        elsif @length_adjust # Perform length adjustment
          # Define the time once so it doesn't get inaccurate
          now = Time.now.nsec

          # Difference between length_adjust and now in ms
          ms_diff = (now - @length_adjust) / 1_000_000.0
          if ms_diff >= 0
            @length = if @adjust_average
                        (IDEAL_LENGTH - ms_diff + @length) / 2.0
                      else
                        IDEAL_LENGTH - ms_diff
                      end

            # Track the time it took to encode
            encode_ms = (@intermediate_adjust - @length_adjust) / 1_000_000.0
            @bot.debug("Length adjustment: new length #{@length} (measured #{ms_diff}, #{(100 * encode_ms) / ms_diff}% encoding)") if @adjust_debug
          end
          @length_adjust = nil
        end

        # If paused, wait
        sleep 0.1 while @paused

        if @length.positive?
          # Wait `length` ms, then send the next packet
          sleep @length / 1000.0
        else
          Discordrb::LOGGER.warn('Audio encoding and sending together took longer than Discord expects one packet to be (20 ms)! This may be indicative of network problems.')
        end
      end

      @bot.debug('Sending five silent frames to clear out buffers')

      5.times do
        increment_packet_headers
        @udp.send_audio(Encoder::OPUS_SILENCE, @sequence, @time)

        # Length adjustments don't matter here, we can just wait 20 ms since nobody is going to hear it anyway
        sleep IDEAL_LENGTH / 1000.0
      end

      @bot.debug('Performing final cleanup after stream ended')

      # Final cleanup
      stop_playing

      # Notify any stop_playing methods running right now that we have actually stopped
      @has_stopped_playing = true
    end
479669
def _freq_parser(self, freq):
        
        freq = freq.lower().strip()

        valid_keywords = [
            "days", "day", "d",
            "hours", "hour", "h",
            "minutes", "minute", "min", "m",
            "seconds", "second", "sec", "s",
            "weeks", "week", "w",
        ]
        error_message = "'%s' is invalid, use one of %s" % (
            freq, valid_keywords)

        try:
            # day
            for surfix in ["days", "day", "d"]:
                if freq.endswith(surfix):
                    freq = freq.replace(surfix, "")
                    return timedelta(days=int(freq))

            # hour
            for surfix in ["hours", "hour", "h"]:
                if freq.endswith(surfix):
                    freq = freq.replace(surfix, "")
                    return timedelta(hours=int(freq))

            # minute
            for surfix in ["minutes", "minute", "min", "m"]:
                if freq.endswith(surfix):
                    freq = freq.replace(surfix, "")
                    return timedelta(minutes=int(freq))

            # second
            for surfix in ["seconds", "second", "sec", "s"]:
                if freq.endswith(surfix):
                    freq = freq.replace(surfix, "")
                    return timedelta(seconds=int(freq))

            # week
            for surfix in ["weeks", "week", "w"]:
                if freq.endswith(surfix):
                    freq = freq.replace(surfix, "")
                    return timedelta(days=int(freq) * 7)
        except:
            pass

        raise ValueError(error_message)
966828
def timing(self, stat, time, sample_rate=1):
        
        stats = {stat: "%f|ms" % time}
        self.send(stats, sample_rate)
1122629
function sineGenerator(frequency, sampleRate, blockSize, callback, nbrBlocks = Infinity) {
  const self = {};

  const block = new Float32Array(blockSize);
  const tIncr = frameSize / sampleRate;
  const _2PI = 2 * Math.PI;

  let pIncr = frequency / sampleRate;
  let phase = 0;
  let timeoutId = null;
  let time = 0;
  let counter = 0;

  self.frequency = (frequency) => {
    // mult = _2PI * frequency;
    pIncr = frequency / sampleRate;
  }

  self.start = () => {
    (function createBlock() {
      for (let i = 0; i < blockSize; i++) {
        const value = Math.sin(phase * _2PI);
        block[i] = value;
        phase = (phase + pIncr) % 1;
      }

      callback(time, block);

      time += tIncr;
      counter += 1;

      if (counter < nbrBlocks) {
        timeoutId = setTimeout(createBlock, tIncr * 1000);
        // timeoutId = setTimeout(createBlock, 2000);
      }
    }());
  }

  self.stop = () => {
    clearTimeout(timeoutId);
  }

  return self;
}