text:
require 'discordrb/voice/encoder'
require 'discordrb/voice/network'

# Voice support
module Discordrb::Voice
  # How long one voice packet should ideally be (20 ms as defined by Discord)
  IDEAL_LENGTH = 20.0

  # How many bytes of data to read (1920 bytes * 2 channels) from audio PCM data
  DATA_LENGTH = 1920 * 2

  # This class represents a connection to a Discord voice server and channel. It can be used to play audio files and
  # streams and to control playback on currently playing tracks. The method {Bot#voice_connect} can be used to connect
  # to a voice channel.
  #
  # discordrb does latency adjustments every now and then to improve playback quality. I made sure to put useful
  # defaults for the adjustment parameters, but if the sound is patchy or too fast (or the speed varies a lot) you
  # should check the parameters and adjust them to your connection: {VoiceBot#adjust_interval},
  # {VoiceBot#adjust_offset}, and {VoiceBot#adjust_average}.
  class VoiceBot
    # @return [Integer, nil] the amount of time the stream has been playing, or `nil` if nothing has been played yet.
    attr_reader :stream_time

    # @return [Encoder] the encoder used to encode audio files into the format required by Discord.
    attr_reader :encoder

    # discordrb will occasionally measure the time it takes to send a packet, and adjust future delay times based
    # on that data. This makes voice playback more smooth, because if packets are sent too slowly, the audio will
    # sound patchy, and if they're sent too quickly, packets will "pile up" and occasionally skip some data or
    # play parts back too fast. How often these measurements should be done depends a lot on the system, and if it's
    # done too quickly, especially on slow connections, the playback speed will vary wildly; if it's done too slowly
    # however, small errors will cause quality problems for a longer time.
    # @return [Integer] how frequently audio length adjustments should be done, in ideal packets (20 ms).
    attr_accessor :adjust_interval

    # This particular value is also important because ffmpeg may take longer to process the first few packets. It is
    # recommended to set this to 10 at maximum, otherwise it will take too long to make the first adjustment, but it
    # shouldn't be any higher than {#adjust_interval}, otherwise no adjustments will take place. If {#adjust_interval}
    # is at a value higher than 10, this value should not be changed at all.
    # @see #adjust_interval
    # @return [Integer] the packet number (1 packet = 20 ms) at which length adjustments should start.
    attr_accessor :adjust_offset

    # This value determines whether or not the adjustment length should be averaged with the previous value. This may
    # be useful on slower connections where latencies vary a lot. In general, it will make adjustments more smooth,
    # but whether that is desired behaviour should be tried on a case-by-case basis.
    # @see #adjust_interval
    # @return [true, false] whether adjustment lengths should be averaged with the respective previous value.
    attr_accessor :adjust_average

    # Disable the debug message for length adjustment specifically, as it can get quite spammy with very low intervals
    # @see #adjust_interval
    # @return [true, false] whether length adjustment debug messages should be printed
    attr_accessor :adjust_debug

    # If this value is set, no length adjustments will ever be done and this value will always be used as the length
    # (i. e. packets will be sent every N seconds). Be careful not to set it too low as to not spam Discord's servers.
    # The ideal length is 20 ms (accessible by the {Discordrb::Voice::IDEAL_LENGTH} constant), this value should be
    # slightly lower than that because encoding + sending takes time. Note that sending DCA files is significantly
    # faster than sending regular audio files (usually about four times as fast), so you might want to set this value
    # to something else if you're sending a DCA file.
    # @return [Float] the packet length that should be used instead of calculating it during the adjustments, in ms.
    attr_accessor :length_override

    # The factor the audio's volume should be multiplied with. `1` is no change in volume, `0` is completely silent,
    # `0.5` is half the default volume and `2` is twice the default.
    # @return [Float] the volume for audio playback, `1.0` by default.
    attr_accessor :volume

    def initialize(channel, bot, token, session, endpoint, encrypted)
      @bot = bot
      @ws = VoiceWS.new(channel, bot, token, session, endpoint)
      @udp = @ws.udp
      @udp.encrypted = encrypted

      @sequence = @time = 0
      @skips = 0

      @adjust_interval = 100
      @adjust_offset = 10
      @adjust_average = false
      @adjust_debug = true

      @volume = 1.0

      @encoder = Encoder.new
      @ws.connect
    end

    # @return [true, false] whether audio data sent will be encrypted.
    def encrypted?
      @udp.encrypted?
    end

    # Set the filter volume. This volume is applied as a filter for decoded audio data. It has the advantage that using
    # it is much faster than regular volume, but it can only be changed before starting to play something.
    # @param value [Integer] The value to set the volume to. For possible values, see {#volume}
    def filter_volume=(value)
      @encoder.filter_volume = value
    end

    # @see #filter_volume=
    # @return [Integer] the volume used as a filter for ffmpeg/avconv.
    def filter_volume
      @encoder.filter_volume
    end

    # Pause playback. This is not instant; it may take up to 20 ms for this change to take effect. (This is usually
    # negligible.)
    def pause
      @paused = true
    end

    # Continue playback. This change may take up to 100 ms to take effect, which is usually negligible.
    def continue
      @paused = false
    end

    # Skips to a later time in the song. It's impossible to go back without replaying the song.
    # @param secs [Float] How many seconds to skip forwards. Skipping will always be done in discrete intervals of
    #   0.05 seconds, so if the given amount is smaller than that, it will be rounded up.
    def skip(secs)
      @skips += (secs * (1000 / IDEAL_LENGTH)).ceil
    end

    # Sets whether or not the bot is speaking (green circle around user).
    # @param value [true, false] whether or not the bot should be speaking.
    def speaking=(value)
      @playing = value
      @ws.send_speaking(value)
    end

    # Stops the current playback entirely.
    def stop_playing
      @was_playing_before = @playing
      @speaking = false
      @playing = false
      sleep IDEAL_LENGTH / 1000.0 if @was_playing_before
    end

    # Permanently disconnects from the voice channel; to reconnect you will have to call {Bot#voice_connect} again.
    def destroy
      stop_playing
      @bot.voice_destroy(false)
      @ws.destroy
    end

    # Plays a stream of raw data to the channel. All playback methods are blocking, i. e. they wait for the playback to
    # finish before exiting the method. This doesn't cause a problem if you just use discordrb events/commands to
    # play stuff, as these are fully threaded, but if you don't want this behaviour anyway, be sure to call these
    # methods in separate threads.
    # @param encoded_io [IO] A stream of raw PCM data (s16le)
    def play(encoded_io)
      stop_playing if @playing
      @retry_attempts = 3

      play_internal do
        buf = nil

        # Read some data from the buffer
        begin
          buf = encoded_io.readpartial(DATA_LENGTH) if encoded_io
        rescue EOFError
          @bot.debug('EOF while reading, breaking immediately')
          break
        end

        # Check whether the buffer has enough data
        if !buf || buf.length != DATA_LENGTH
          @bot.debug("No data is available! Retrying #{@retry_attempts} more times")
          break if @retry_attempts == 0

          @retry_attempts -= 1
          next
        end

        # Adjust volume
        buf = @encoder.adjust_volume(buf, @volume) if @volume != 1.0

        # Encode data
        @encoder.encode(buf)
      end

      # If the stream is a process, kill it
      Process.kill('TERM', encoded_io.pid) if encoded_io.respond_to? :pid

      # Close the stream
      encoded_io.close
    end

    # Plays an encoded audio file of arbitrary format to the channel.
    # @see Encoder#encode_file
    # @see #play
    def play_file(file)
      play @encoder.encode_file(file)
    end

    # Plays a stream of encoded audio data of arbitrary format to the channel.
    # @see Encoder#encode_io
    # @see #play
    def play_io(io)
      play @encoder.encode_io(io)
    end

    # Plays a stream of audio data in the DCA format. This format has the advantage that no recoding has to be
    # done - the file contains the data exactly as Discord needs it.
    # @see https://github.com/bwmarrin/dca
    # @see #play
    def play_dca(file)
      stop_playing if @playing

      @bot.debug "Reading DCA file #{file}"
      input_stream = open(file)

      # Play the data, without re-encoding it to opus
      play_internal do
        begin
          # Read header
          header = input_stream.read(2).unpack('S')[0]
        rescue EOFError
          @bot.debug 'Finished DCA parsing'
          break
        end

        # Read bytes
        input_stream.read(header)
      end
    end

    alias_method :play_stream, :play_io

    private

    # Plays the data from the @io stream as Discord requires it
    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 > 0
          @skips -= 1
          yield
          next
        end

        # Track packet count, sequence and time (Discord requires this)
        count += 1
        (@sequence + 10 < 65_535) ? @sequence += 1 : @sequence = 0
        (@time + 9600 < 4_294_967_295) ? @time += 960 : @time = 0

        # Get packet data
        buf = yield
        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

        # Wait `length` ms, then send the next packet
        sleep @length / 1000.0
      end

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

      # Final cleanup
      stop_playing
    end
  end
end


text:
package org.apache.geode.internal.cache.control;

import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.internal.cache.control.InternalResourceManager.ResourceType;

/**
 *
 */
public interface ResourceEvent {
  public ResourceType getType();

  public boolean isLocal();

  public DistributedMember getMember();
}

redpajama_set_name: RedPajamaGithub


text:
import os, unittest
from test.test_support import run_unittest

if not hasattr(os, "openpty"):
    raise unittest.SkipTest, "No openpty() available."

class OpenptyTest(unittest.TestCase):
    def test(self):
        master, slave = os.openpty()
        if not os.isatty(slave):
            self.fail("Slave-end of pty is not a terminal.")

        os.write(slave, 'Ping!')
        self.assertEqual(os.read(master, 1024), 'Ping!')

def test_main():
    run_unittest(OpenptyTest)

if __name__ == '__main__':
    test_main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--<classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />-->

    <context id="mysql1" targetRuntime="MyBatis3">
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://192.168.1.212:3306?useUnicode=true"
                        userId="scrm"
                        password="scrm@123">
        </jdbcConnection>

        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <javaModelGenerator targetPackage="xyy.note.mybatis.mbg.model" targetProject="/Users/xyy/IdeaProjects/java-note/db-mybatis/src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mapper"  targetProject="/Users/xyy/IdeaProjects/java-note/db-mybatis/src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER" targetPackage="xyy.note.mybatis.mbg.mapper"  targetProject="/Users/xyy/IdeaProjects/java-note/db-mybatis/src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <table schema="test" tableName="account_info" domainObjectName="AccountInfo" enableSelectByExample="true">
            <property name="useActualColumnNames" value="true"/>
            <generatedKey column="ID" sqlStatement="DB2" identity="true" />
            <columnOverride column="DATE_FIELD" property="startDate" />
            <ignoreColumn column="FRED" />
            <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
        </table>

    </context>
</generatorConfiguration>


text:
angular.module('app.components.passwordMatch', [])
.directive('passwordMatch', ['$parse',function ($parse) {
  return {
    require: '?ngModel',
    restrict: 'A',
    link: function (scope, elem, attrs, ctrl) {

      if (!ctrl) {
        if (console && console.warn) {
          console.warn('ng-model attribute required');
        }
        return;
      }

      var passGetter = $parse(attrs.passwordMatch);

      scope.$watch(getPass, function () {
        ctrl.$$parseAndValidate();
      });

      ctrl.$validators.passwordMatch = function () {
        var pass = getPass();
        return ctrl.$viewValue === pass;
      };

      function getPass() {
        var pass = passGetter(scope);
        if (angular.isObject(pass) && pass.hasOwnProperty('$viewValue')) {
          pass = pass.$viewValue;
        }
        return pass;
      }
    }
  };
}]);


text:
Career Profile

A highly motivated and hardworking undergraduate in Computer Science & Engineering field.Interested in learning new technologies and to be updated with current trends in the field. Happy to help and support to anyone with my coding skills and knowledge.


text:
void setInputSource(int micInput) {
  switch (micInput) {

    case INPUT_PCBMICS:
      //Select Input
      myTympan.inputSelect(TYMPAN_INPUT_ON_BOARD_MIC); // use the on-board microphones
      earpieceShield.inputSelect(TYMPAN_INPUT_ON_BOARD_MIC);
      break;
    case INPUT_MICJACK_MIC:
      //Select Input
      myTympan.inputSelect(TYMPAN_INPUT_JACK_AS_MIC); // use the mic jack
      earpieceShield.inputSelect(TYMPAN_INPUT_JACK_AS_MIC);
      break;
    case INPUT_MICJACK_LINEIN:
      //Select Input
      myTympan.inputSelect(TYMPAN_INPUT_JACK_AS_LINEIN); // use the mic jack
      earpieceShield.inputSelect(TYMPAN_INPUT_JACK_AS_LINEIN);
      break;
    case INPUT_PDMMICS:
      //The Tympan earpieces use PDM Digital Microphones.  Choose this option for Tympan earpieces
      myTympan.enableDigitalMicInputs(true);
      earpieceShield.enableDigitalMicInputs(true);
      break;
  }

  // If turning on digital mics, enable them. Otherwise disable them.
  if (micInput==INPUT_PDMMICS)  {
    //Enable Digital Mic (enable analog inputs)
    myTympan.enableDigitalMicInputs(true);
    earpieceShield.enableDigitalMicInputs(true);
  }  else  {
    //Disable Digital Mic (enable analog inputs)
    myTympan.enableDigitalMicInputs(false);
    earpieceShield.enableDigitalMicInputs(false);
  }

}

//Sets the input mixer gain for a given mic channel.
//Mixes between front and rear microphone of each earpiece
void setInputMixer(int micChannelName, float gainVal) {
  const int LEFT_FRONT=0, LEFT_REAR=1, RIGHT_FRONT=2, RIGHT_REAR=3;

  //initialize to muted
  inputMixerL.gain(LEFT_FRONT, 0.0);
  inputMixerL.gain(LEFT_REAR,  0.0);
  inputMixerL.gain(RIGHT_FRONT,0.0);
  inputMixerL.gain(RIGHT_REAR, 0.0);
  inputMixerR.gain(LEFT_FRONT, 0.0);
  inputMixerR.gain(LEFT_REAR,  0.0);
  inputMixerR.gain(RIGHT_FRONT,0.0);
  inputMixerR.gain(RIGHT_REAR, 0.0);

  //turn on the desired channels
  switch (micChannelName) {
    case MIC_FRONT_LEFT:
      inputMixerL.gain(LEFT_FRONT,gainVal);
      Serial.print("Mic Left-Front, L-only: Gain ");
      break;
    case MIC_REAR_LEFT:
      inputMixerL.gain(LEFT_REAR,gainVal);
      Serial.print("Mic Left-Rear, L-only: Gain ");
      break;
    case MIC_FRONT_RIGHT:
      inputMixerR.gain(RIGHT_FRONT,gainVal);
      Serial.print("Mic Right-Front, R-only: Gain ");
      break;
    case MIC_REAR_RIGHT:
      Serial.print("Mic Right-Rear, R-only: Gain ");
      inputMixerR.gain(RIGHT_REAR,gainVal);
      break;
    case MIC_FRONT_BOTH:
      Serial.print("Front Mics, L/R: Gain ");
      inputMixerL.gain(LEFT_FRONT,gainVal);
      inputMixerR.gain(RIGHT_FRONT,gainVal);
      break;
    case MIC_REAR_BOTH:
      Serial.print("Rear Mics, L/R: Gain ");
      inputMixerL.gain(LEFT_REAR,gainVal);
      inputMixerR.gain(RIGHT_REAR,gainVal);
      break;
    case MIC_AIC0:
      Serial.print("Tympan AIC, L/R: Gain ");
      inputMixerL.gain(0,gainVal);
      inputMixerR.gain(1,gainVal);
      break;
    case MIC_AIC1:
      Serial.print("Earpiece Shield AIC, L/R: Gain ");
      inputMixerL.gain(2,gainVal);
      inputMixerR.gain(3,gainVal);
      break;
    case ALL_MICS:
      Serial.print("Front+Rear Mics, L/R: Gain ");
      inputMixerL.gain(LEFT_FRONT, gainVal);  //Left-Front Mic
      inputMixerL.gain(LEFT_REAR,  gainVal);  //Left-Rear Mic
      inputMixerR.gain(RIGHT_FRONT,gainVal);  //Right-Front Mic
      inputMixerR.gain(RIGHT_REAR, gainVal);  //Right-Rear Mic
      break;
  }
  Serial.println(gainVal);
}


text:
// <copyright file="TriangularTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>

using System;
using System.Linq;
using MathNet.Numerics.Distributions;
using NUnit.Framework;

namespace MathNet.Numerics.UnitTests.DistributionTests.Continuous
{
    using Random = System.Random;

    /// <summary>
    /// Triangular distribution tests.
    /// </summary>
    [TestFixture, Category("Distributions")]
    public class TriangularTests
    {
        /// <summary>
        /// Can create Triangular distribution.
        /// </summary>
        /// <param name="lower">Lower Bound.</param>
        /// <param name="upper">Upper Bound.</param>
        /// <param name="mode">Mode.</param>
        [TestCase(0.0, 0.0, 0.0)]
        [TestCase(-1.0, 1.0, 0.0)]
        [TestCase(1.0, 2.0, 1.0)]
        [TestCase(5.0, 25.0, 25.0)]
        [TestCase(1.0e-5, 1.0e5, 1.0e-3)]
        [TestCase(0.0, 1.0, 0.9)]
        [TestCase(-4.0, -0.5, -2.0)]
        [TestCase(-13.039, 8.42, 1.17)]
        public void CanCreateTriangular(double lower, double upper, double mode)
        {
            var n = new Triangular(lower, upper, mode);
            Assert.AreEqual(lower, n.LowerBound);
            Assert.AreEqual(upper, n.UpperBound);
            Assert.AreEqual(mode, n.Mode);
        }

        /// <summary>
        /// Triangular create fails with bad parameters.
        /// </summary>
        [TestCase(0.0, 1.0, -0.1)]
        [TestCase(0.0, 1.0, 1.1)]
        [TestCase(0.0, -1.0, 0.5)]
        [TestCase(2.0, 1.0, 1.5)]
        [TestCase(Double.NaN, 1.0, 0.5)]
        [TestCase(0.2, Double.NaN, 0.5)]
        [TestCase(0.5, 1.0, Double.NaN)]
        [TestCase(Double.NaN, Double.NaN, Double.NaN)]
        [TestCase(Double.NegativeInfinity, 1.0, 0.5)]
        [TestCase(0.0, Double.PositiveInfinity, 0.5)]
        public void TriangularCreateFailsWithBadParameters(double lower, double upper, double mode)
        {
            Assert.That(() => new Triangular(lower, upper, mode), Throws.ArgumentException);
        }

        /// <summary>
        /// Validate to string.
        /// </summary>
        [Test]
        public void ValidateToString()
        {
            var n = new Triangular(0d, 2d, 1d);
            Assert.AreEqual("Triangular(Lower = 0, Upper = 2, Mode = 1)", n.ToString());
        }

        // Todo: Add tests for:
        // - Mean,
        // - Entropy,
        // - Skewness,
        // - Mode (note: Mode is an input parameter for this distribution),
        // - Median
        // - Minimum (should be the same as LowerBound)
        // - Maximum (should be the same as UpperBound)

        /// <summary>
        /// Can sample static.
        /// </summary>
        [Test]
        public void CanSampleStatic()
        {
            Triangular.Sample(new Random(0), 2.0, 3.0, 2.5);
            Triangular.Sample(10.0, 100.0, 30.0);
        }

        /// <summary>
        /// Can sample sequence static.
        /// </summary>
        [Test]
        public void CanSampleSequenceStatic()
        {
            var ied = Triangular.Samples(new Random(0), 2.0, 3.0, 2.5);
            GC.KeepAlive(ied.Take(5).ToArray());
            ied = Triangular.Samples(10.0, 100.0, 30.0);
            GC.KeepAlive(ied.Take(5).ToArray());
        }

        /// <summary>
        /// Fail sample static with wrong parameters.
        /// </summary>
        [Test]
        public void FailSampleStatic()
        {
            Assert.That(() => Triangular.Sample(new Random(0), 1.0, -1.0, 0.1), Throws.ArgumentException);
        }

        /// <summary>
        /// Fail sample sequence static with wrong parameters.
        /// </summary>
        [Test]
        public void FailSampleSequenceStatic()
        {
            Assert.That(() => Triangular.Samples(new Random(0), 1.0, -1.0, 0.1).First(), Throws.ArgumentException);
        }

        /// <summary>
        /// Can sample.
        /// </summary>
        [Test]
        public void CanSample()
        {
            var n = new Triangular(0.1, 0.3, 0.2);
            n.Sample();
        }

        /// <summary>
        /// Can sample sequence.
        /// </summary>
        [Test]
        public void CanSampleSequence()
        {
            var n = new Triangular(0.1, 0.3, 0.2);
            var ied = n.Samples();
            GC.KeepAlive(ied.Take(5).ToArray());
        }

        // Todo: Add tests for:
        // - Density
        // - DensityLn
        // - Cumulative Dist.
        // - Inverse Cumulative Dist.
    }
}


text:
echo 'Runnning the experiment...'

python experiment_estimate_loss.py \
	--proto ../model/cifar10/cifar10_full.prototxt \
	--model ../model/cifar10/cifar10_full_iter_200000.caffemodel \
	--meanfile ../model/cifar10/mean.binaryproto \
	--data ..data/cifar10/cifar10_train_lmdb/ \
	--layer conv1 \
	--iterations 250 \
	--damage 0.25 \
	--repeat 1

echo 'Done.'


text:
package com.nixus.raop.zeroconf;

import java.util.Map;

public interface ZCServiceInfo {

    public String getType();
    public String getName();
    public String getHost();
    public int getPort();
    public Map<String,String> getProperties();
    public String getProtocol();

}


text:
package org.batfish.datamodel;

import static com.google.common.base.MoreObjects.firstNonNull;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.RuntimeJsonMappingException;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.batfish.common.BatfishException;
import org.batfish.common.util.BatfishObjectMapper;
import org.batfish.vendor.VendorStructureId;

/**
 * Filter list for IPV4 routes. Performs filtering on IPv4 prefixes with access-list-like behavior
 * (match in order, with an implicit "deny all" at the end).
 */
public class RouteFilterList implements Serializable {
  private static final String PROP_LINES = "lines";
  private static final String PROP_NAME = "name";
  private static final String PROP_VENDOR_STRUCTURE_ID = "vendorStructureId";

  private final Supplier<Set<Prefix>> _deniedCache;

  @Nonnull private List<RouteFilterLine> _lines;

  @Nullable private final String _name;

  @Nullable private final VendorStructureId _vendorStructureId;

  private final Supplier<Set<Prefix>> _permittedCache;

  private static class CacheSupplier implements Supplier<Set<Prefix>>, Serializable {

    @Override
    public Set<Prefix> get() {
      return Collections.newSetFromMap(new ConcurrentHashMap<>());
    }
  }

  @JsonCreator
  private static RouteFilterList create(
      @JsonProperty(PROP_NAME) @Nullable String name,
      @JsonProperty(PROP_LINES) @Nullable List<RouteFilterLine> lines,
      @JsonProperty(PROP_VENDOR_STRUCTURE_ID) @Nullable VendorStructureId vendorStructureId) {
    return new RouteFilterList(name, firstNonNull(lines, ImmutableList.of()), vendorStructureId);
  }

  /** Create and empty route filter list (with no lines) */
  public RouteFilterList(@Nullable String name) {
    this(name, ImmutableList.of());
  }

  public RouteFilterList(@Nullable String name, @Nonnull List<RouteFilterLine> lines) {
    this(name, lines, null);
  }

  public RouteFilterList(
      @Nullable String name,
      @Nonnull List<RouteFilterLine> lines,
      @Nullable VendorStructureId vendorStructureId) {
    _name = name;
    _deniedCache = Suppliers.memoize(new CacheSupplier());
    _permittedCache = Suppliers.memoize(new CacheSupplier());
    _lines = lines;
    _vendorStructureId = vendorStructureId;
  }

  public void addLine(RouteFilterLine r) {
    _lines = ImmutableList.<RouteFilterLine>builder().addAll(_lines).add(r).build();
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    } else if (!(o instanceof RouteFilterList)) {
      return false;
    }
    RouteFilterList other = (RouteFilterList) o;
    return other._lines.equals(_lines);
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(_lines);
  }

  @Nullable
  @JsonProperty(PROP_NAME)
  public String getName() {
    return _name;
  }

  /** The lines against which to check an IPV4 route */
  @Nonnull
  @JsonProperty(PROP_LINES)
  public List<RouteFilterLine> getLines() {
    return _lines;
  }

  @Nullable
  @JsonProperty(PROP_VENDOR_STRUCTURE_ID)
  public VendorStructureId getVendorStructureId() {
    return _vendorStructureId;
  }

  private boolean evaluatePrefix(Prefix prefix) {
    boolean accept = false;
    for (RouteFilterLine line : _lines) {
      if (line.getIpWildcard().containsIp(prefix.getStartIp())) {
        int prefixLength = prefix.getPrefixLength();
        SubRange range = line.getLengthRange();
        if (prefixLength >= range.getStart() && prefixLength <= range.getEnd()) {
          accept = line.getAction() == LineAction.PERMIT;
          break;
        }
      }
    }
    if (accept) {
      _permittedCache.get().add(prefix);
    } else {
      _deniedCache.get().add(prefix);
    }
    return accept;
  }

  /** Check if a given prefix is permitted by this filter list. */
  public boolean permits(Prefix prefix) {
    if (_deniedCache.get().contains(prefix)) {
      return false;
    } else if (_permittedCache.get().contains(prefix)) {
      return true;
    }
    return evaluatePrefix(prefix);
  }

  /**
   * Returns the set of {@link IpWildcard ips} that match this filter list.
   *
   * @throws BatfishException if any line in this {@link RouteFilterList} does not have an {@link
   *     LineAction#PERMIT} when matching.
   */
  @JsonIgnore
  public List<IpWildcard> getMatchingIps() {
    return getLines().stream()
        .map(
            rfLine -> {
              if (rfLine.getAction() != LineAction.PERMIT) {
                throw new BatfishException(
                    "Expected accept action for routerfilterlist from juniper");
              } else {
                return rfLine.getIpWildcard();
              }
            })
        .collect(Collectors.toList());
  }

  /** Set the list of lines against which to match a route's prefix. */
  public void setLines(@Nonnull List<RouteFilterLine> lines) {
    _lines = lines;
  }

  /**
   * Returns a JSON string that represents the definition of this object, ignoring any irrelevant
   * fields.
   *
   * <p>Can be used for JSON-based comparison in questions line compareSameName.
   */
  public String definitionJson() {
    try {
      return BatfishObjectMapper.writePrettyString(_lines);
    } catch (JsonProcessingException e) {
      throw new RuntimeJsonMappingException("Could not map lines to JSON");
    }
  }
}


text:
<?php

/**
 * Fields
 *
 * @author Jorge Gaitan
 */

namespace Kodazzi\Form;

use Kodazzi\Container\Service;
use Kodazzi\Orm\DatabaseManager;
use Kodazzi\Orm\Model;

abstract Class Field
{
	protected $template = 'form/default_row';
	protected $class_css = 'form-control';
	protected $max_length = null;
	protected $min_length = null;
	protected $value = null;
	protected $value_label = null;
	protected $name = null;
	protected $id_tag = null;
	protected $name_form = null;

	/**
	 * @var \Kodazzi\Form\Form
	 * @see \Kodazzi\Form\Form
	 */
	protected $form = null;

	protected $model_name = null;
	protected $is_valid = true;
	protected $is_required = true;
	protected $is_unique = false;
	protected $is_hidden = false;
	protected $is_disabled = false;
	protected $is_readonly = false;
	protected $is_display = true;
	protected $is_check = false;
	protected $msg_help = null;
	protected $msg_error = null;
	protected $placeholder = null;
	protected $msg_max_length = null;
	protected $msg_min_length = null;
	protected $msg_unique = null;
	protected $has_upload = false;
	protected $has_model = true;
	protected $has_many = false;
	protected $I18n;
	protected $config_fields  = array();
	protected $pattern  = null;
	protected $path_upload  = null;
	protected $field_value  = null;
	protected $field_option  = null;
	protected $other_attributes  = null;
	protected $format  = null;
	protected $id  = null;

	abstract public function valid();

	abstract public function renderField();

	public function setName($name)
	{
		$this->name = $name;
	}

	public function setNameForm($name)
	{
		$this->name_form = $name;
	}

	public function setForm($form = null)
	{
		if ($form != null && is_object($form))
		{
			$this->form = $form;
		}
		else
		{
			throw new \Exception('Se esperaba un objecto de formulario para el widget');
		}
	}

	public function setI18n( $I18n )
	{
		$this->I18n = $I18n;
	}

	public function setConfig( $config )
	{
		$name = $this->name;

		if( isset($config[ $name ]) && is_array( $config[ $name ] ) )
		{
			if( isset($config[ $name ][ 'label' ]) && $config[ $name ][ 'label' ] != '')
			{
				$this->setValueLabel( $config[ $name ][ 'label' ]);
			}

			if( isset($config[ $name ][ 'css' ]) && $config[ $name ][ 'css' ] != '')
			{
				$this->setClassCss( $config[ $name ][ 'css' ]);
			}

			if( isset($config[ $name ][ 'msg-help' ]) && $config[ $name ][ 'msg-help' ] != '')
			{
				$this->setHelp( $config[ $name ][ 'msg-help' ]);
			}

			if( isset($config[ $name ][ 'min-length' ]) && $config[ $name ][ 'min-length' ] != '')
			{
				$this->setMinLength( $config[ $name ][ 'min-length' ]);
			}

			if( isset($config[ $name ][ 'max-length' ]) && $config[ $name ][ 'max-length' ] != '')
			{
				$this->setMaxLength( $config[ $name ][ 'max-length' ]);
			}

			if( isset($config[ $name ][ 'pattern' ]) && $config[ $name ][ 'pattern' ] != '')
			{
				$this->setPattern( $config[ $name ][ 'pattern' ]);
			}

			if( isset($config[ $name ][ 'msg-error' ]) && $config[ $name ][ 'msg-error' ] != '')
			{
				$this->setError( $config[ $name ][ 'msg-error' ]);
			}

			if( isset($config[ $name ][ 'placeholder' ]) && $config[ $name ][ 'placeholder' ] != '')
			{
				$this->setPlaceholder( $config[ $name ][ 'placeholder' ]);
			}

			if( isset($config[ $name ][ 'field-value' ]) && $config[ $name ][ 'field-value' ] != '' && isset($config[ $name ][ 'field-option' ]) && $config[ $name ][ 'field-option' ] != '')
			{
				$this->setFieldsValueOption( $config[ $name ][ 'field-value' ], $config[ $name ][ 'field-option' ]);
			}

			if( isset($config[ $name ][ 'other-attributes' ]) && $config[ $name ][ 'other-attributes' ] != '' )
			{
				$this->setOtherAttributes( $config[ $name ][ 'other-attributes' ] );
			}
		}
	}

	/**************************************************************************/

	public  function setFieldsValueOption( $field_value, $field_option )
	{
		$this->field_value = $field_value;
		$this->field_option = $field_option;
	}

	public  function setOtherAttributes( $other_attributes )
	{
		$this->other_attributes = $other_attributes;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function renderLabel( $value = null, $attributes = '' )
	{
		$for = ($this->id) ? $this->id : $this->name_form . '_' . $this->name;;

		if (!$value)
		{
			$value = $this->getValueLabel();
		}

		return \Kodazzi\Helper\FormHtml::label( $for, $value, $attributes );
	}

	public function setPathUpload( $path )
	{
		$this->path_upload = $path;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function setValueLabel($name = null)
	{
		$this->value_label = $name;

		return $this;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function setDisabled($value = false)
	{
		if (!is_bool($value))
		{
			throw new \Exception("Tipo de parámetro incorrecto para 'setDisabled' ");
		}

		$this->is_disabled = $value;

		return $this;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function setReadonly($value = false)
	{
		if (!is_bool($value))
		{
			throw new \Exception("Tipo de parámetro incorrecto para 'setReadonly' ");
		}

		$this->is_readonly = $value;

		return $this;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function setRequired($bool = true)
	{
		if (!is_bool($bool))
		{
			throw new \Exception('El parámetro debe se boolean');
		}

		$this->is_required = $bool;

		return $this;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function setPattern($pattern)
	{
		$this->pattern = $pattern;

		return $this;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function setDisplay($bool = true)
	{
		if (!is_bool($bool))
		{
			throw new \Exception('El parámetro debe se boolean');
		}

		$this->is_display = $bool;

		return $this;
	}

    /**
     * @return \Kodazzi\Forms\Field
     */
	public function setClassCss($class)
	{
		$this->class_css = $class;

		return $this;
	}

    /**
     * @return \Kodazzi\Forms\Field
     */
	public function setMaxLength($length = 255, $msg = null)
	{
		if (!is_integer($length))
		{
			throw new \Exception("Tipo de parámetro incorrecto para 'set_max'.");
		}

		$this->msg_max_length = $msg;
		$this->max_length = $length;

		return $this;
	}

	/**
	 * @return \Kodazzi\Forms\Field
	 */
	public function setMinLength($length = 0, $msg = null)
	{
		if (!is_integer($length))
		{
			throw new \Exception("Tipo de parámetro incorrecto para 'set_min'.");
		}

		$this->msg_min_length = $msg;
		$this->min_length = $length;

		return $this;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function setHelp($msg = null)
	{
		$this->msg_help = $msg;

		return $this;
	}

	/**
	 * @return Field
	 */
	public function setPlaceholder($placeholder = null)
	{
		$this->placeholder = $placeholder;

		return $this;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function setError( $msg = null )
	{
		$this->msg_error = $msg;

		return $this;
	}

    /**
     * @return \Kodazzi\Forms\Field
     */
	public function setTemplate($template)
	{
		$this->template = $template;

		return $this;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function setValue($val)
	{
		$this->value = $val;

		return $this;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function setHidden( $bool = true )
	{
		if (!is_bool($bool))
		{
			throw new \Exception('El parametro debe ser boolean');
		}

		$this->is_hidden = $bool;

		return $this;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function setValid( $val )
	{
		$this->is_valid = (is_bool($val)) ? $val : true;

		return $this;
	}

	/**
	 * @return \Kodazzi\Form\Field
	 */
	public function setUnique( $value )
	{
		$this->is_unique = (is_bool($value)) ? $value : false;

		return $this;
	}

    /**
     * @return \Kodazzi\Form\Field
     */
    public function setFormat($format)
    {
        $this->format = $format;
    }

    /**
     * @return \Kodazzi\Form\Field
     */
    public function setId($id)
    {
        $this->id = $id;
    }

	/*************************************************************************************************/

	public function getValueLabel()
	{
		return ($this->value_label) ? $this->value_label : ucfirst(str_replace('_', ' ', $this->name));
	}

	public function getClassCss()
	{
		return $this->class_css;
	}

	public function getMaxLength()
	{
		return $this->max_length;
	}

	public function getHelp()
	{
		return $this->msg_help;
	}

	public function getError()
	{
		return $this->msg_error;
	}

	public function getValue()
	{
		return $this->value;
	}

	public function getForm()
	{
		return $this->form;
	}

	public function getNameForm()
	{
		return $this->name_form;
	}

	public function getIdTag()
	{
		return $this->name_form . '_' . $this->name;
	}

	public function getId()
	{
		return $this->id;
	}

	public function getName()
	{
		return $this->name;
	}

	public function getPattern()
	{
		return $this->pattern;
	}

	public function getTemplate()
	{
		return $this->template;
	}

    public function getPlaceholder()
    {
        return $this->placeholder;
    }

    public function getFormat()
    {
        return $this->format;
    }

	/************************************************************************/

	public function isHidden()
	{
		return $this->is_hidden;
	}

	public function isRequired()
	{
		return $this->is_required;
	}

	public function isValid()
	{
		return $this->is_valid;
	}

	public function isDisabled()
	{
		return $this->is_disabled;
	}

	public function isReadonly()
	{
		return $this->is_readonly;
	}

	public function isDisplay()
	{
		return $this->is_display;
	}

    public function isCheck()
    {
        return $this->is_check;
    }

	public function hasUpload()
	{
		return (is_bool($this->has_upload)) ? $this->has_upload : false;
	}

	public function hasMany()
	{
		return (is_bool($this->has_many)) ? $this->has_many : false;
	}

	public function validate( $data )
	{
		$type = strtoupper(basename( str_replace('\\', '/', get_class($this)) ));

		// No se valida los campos FILE o IMAGEN que estan vacios y son de un objeto viejo
		// En este punto no se actualiza el valor del campo y se utiliza facilmente en save()
		if ($type == 'FILE' || $type == 'IMAGE')
		{
			if (! $this->form->isNew() && ( $data == '' || $data == null ))
			{
				return true;
			}
		}

		/* Todos los campos menos Editor, File, Image y Table - se valida el minimo y maximo de caracteres */
		if (! in_array($type, array('EDITOR', 'FILE', 'IMAGE', 'TABLE')) )
		{
			if ( $this->max_length && strlen($data) > $this->max_length )
			{
				$msg = (!$this->msg_max_length) ? $this->I18n->get('form.max_length', 'Is Invalid.') : $this->msg_max_length;
				$this->msg_error = strtr($msg, array('%name%' => $this->getValueLabel(), '%max%' => $this->max_length));
				return false;
			}

			if ($this->min_length && strlen($data) < $this->min_length)
			{
				$msg = (!$this->msg_min_length) ? $this->I18n->get('form.min_length', 'Is Invalid.') : $this->msg_min_length;
				$this->msg_error = strtr($msg, array('%name%' => $this->getValueLabel(), '%min%' => $this->min_length));

				return false;
			}
		}

		// Envia el valor para ser procesado por le metodo valid() de cada campo
		$this->value = $data;

		// Llama al validador del widget
		if (! $this->valid())
		{
			$this->msg_error = ( $this->msg_error ) ? $this->msg_error : $this->I18n->get('form.'.strtolower($type), 'Is Invalid.');

			$this->value = null;

			return false;
		}

		if ($this->is_unique)
		{
            /**
             * @var $db Model
             */
            $Model = Service::get('database.manager')->model($this->form->getNameModel());

			if( $this->form->isNew() )
			{
				$exist = $Model->where($this->name, '=', $this->value)->exist();
			}
			else
			{
                $instanceModelo = $this->form->getModel();
                $fieldPrimary = $instanceModelo::primary;

                $exist = $Model->where($this->name, '=', $this->value)->andWhere($fieldPrimary, '<>', $instanceModelo->$fieldPrimary)->exist();
			}

			if( $exist )
			{
				$this->msg_error = $this->I18n->get('form.unique', 'Is unique.' );

				return false;
			}
		}

		// Si pasa las validaciones  transforma la data para evitar inyeccion sql
		if (! in_array($type, array('EDITOR', 'NOTE', 'FILE', 'IMAGE', 'FOREIGN', 'TABLE')) )
		{
			$this->value = htmlentities($this->value, ENT_QUOTES, 'UTF-8');
		}

		return true;
	}
}


text:
.monaco-workbench.nopanel .part.panel {
	display: none !important;
	visibility: hidden !important;
}

.monaco-workbench .part.panel.bottom .composite.title {
	border-top-width: 1px;
	border-top-style: solid;
}

.monaco-workbench.noeditorarea .part.panel.bottom .composite.title {
	border-top-width: 0; /* no border when editor area is hiden */
}

.monaco-workbench .part.panel.right {
	border-left-width: 1px;
	border-left-style: solid;
}

.monaco-workbench.noeditorarea .part.panel.right {
	border-left-width: 0; /* no border when editor area is hiden */
}

.monaco-workbench .part.panel.left {
	border-right-width: 1px;
	border-right-style: solid;
}

.monaco-workbench.noeditorarea .part.panel.left {
	border-right-width: 0; /* no border when editor area is hiden */
}


text:
package net.nemerosa.ontrack.job.orchestrator;

import net.nemerosa.ontrack.job.JobRegistration;

import java.util.stream.Stream;

@FunctionalInterface
public interface JobOrchestratorSupplier {

    Stream<JobRegistration> collectJobRegistrations();

}


text:
/* @internal */
namespace ts.codefix {
    const fixMissingMember = "fixMissingMember";
    const fixMissingFunctionDeclaration = "fixMissingFunctionDeclaration";
    const errorCodes = [
        Diagnostics.Property_0_does_not_exist_on_type_1.code,
        Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
        Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code,
        Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code,
        Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code,
        Diagnostics.Cannot_find_name_0.code
    ];

    registerCodeFix({
        errorCodes,
        getCodeActions(context) {
            const typeChecker = context.program.getTypeChecker();
            const info = getInfo(context.sourceFile, context.span.start, typeChecker, context.program);
            if (!info) {
                return undefined;
            }
            if (info.kind === InfoKind.Function) {
                const changes = textChanges.ChangeTracker.with(context, t => addFunctionDeclaration(t, context, info));
                return [createCodeFixAction(fixMissingFunctionDeclaration, changes, [Diagnostics.Add_missing_function_declaration_0, info.token.text], fixMissingFunctionDeclaration, Diagnostics.Add_all_missing_function_declarations)];
            }
            if (info.kind === InfoKind.Enum) {
                const changes = textChanges.ChangeTracker.with(context, t => addEnumMemberDeclaration(t, context.program.getTypeChecker(), info));
                return [createCodeFixAction(fixMissingMember, changes, [Diagnostics.Add_missing_enum_member_0, info.token.text], fixMissingMember, Diagnostics.Add_all_missing_members)];
            }
            return concatenate(getActionsForMissingMethodDeclaration(context, info), getActionsForMissingMemberDeclaration(context, info));
        },
        fixIds: [fixMissingMember, fixMissingFunctionDeclaration],
        getAllCodeActions: context => {
            const { program, fixId } = context;
            const checker = program.getTypeChecker();
            const seen = new Map<string, true>();
            const typeDeclToMembers = new Map<ClassOrInterface, ClassOrInterfaceInfo[]>();

            return createCombinedCodeActions(textChanges.ChangeTracker.with(context, changes => {
                eachDiagnostic(context, errorCodes, diag => {
                    const info = getInfo(diag.file, diag.start, checker, context.program);
                    if (!info || !addToSeen(seen, getNodeId(info.parentDeclaration) + "#" + info.token.text)) {
                        return;
                    }

                    if (fixId === fixMissingFunctionDeclaration) {
                        if (info.kind === InfoKind.Function) {
                            addFunctionDeclaration(changes, context, info);
                        }
                    }
                    else {
                        if (info.kind === InfoKind.Enum) {
                            addEnumMemberDeclaration(changes, checker, info);
                        }

                        if (info.kind === InfoKind.ClassOrInterface) {
                            const { parentDeclaration, token } = info;
                            const infos = getOrUpdate(typeDeclToMembers, parentDeclaration, () => []);
                            if (!infos.some(i => i.token.text === token.text)) {
                                infos.push(info);
                            }
                        }
                    }
                });

                typeDeclToMembers.forEach((infos, classDeclaration) => {
                    const supers = getAllSupers(classDeclaration, checker);
                    for (const info of infos) {
                        // If some superclass added this property, don't add it again.
                        if (supers.some(superClassOrInterface => {
                            const superInfos = typeDeclToMembers.get(superClassOrInterface);
                            return !!superInfos && superInfos.some(({ token }) => token.text === info.token.text);
                        })) continue;

                        const { parentDeclaration, declSourceFile, modifierFlags, token, call, isJSFile } = info;
                        // Always prefer to add a method declaration if possible.
                        if (call && !isPrivateIdentifier(token)) {
                            addMethodDeclaration(context, changes, call, token, modifierFlags & ModifierFlags.Static, parentDeclaration, declSourceFile);
                        }
                        else {
                            if (isJSFile && !isInterfaceDeclaration(parentDeclaration)) {
                                addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token, !!(modifierFlags & ModifierFlags.Static));
                            }
                            else {
                                const typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token);
                                addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, modifierFlags & ModifierFlags.Static);
                            }
                        }
                    }
                });
            }));
        },
    });

    const enum InfoKind { Enum, ClassOrInterface, Function }
    type Info = EnumInfo | ClassOrInterfaceInfo | FunctionInfo;

    interface EnumInfo {
        readonly kind: InfoKind.Enum;
        readonly token: Identifier;
        readonly parentDeclaration: EnumDeclaration;
    }

    interface ClassOrInterfaceInfo {
        readonly kind: InfoKind.ClassOrInterface;
        readonly call: CallExpression | undefined;
        readonly token: Identifier | PrivateIdentifier;
        readonly modifierFlags: ModifierFlags;
        readonly parentDeclaration: ClassOrInterface;
        readonly declSourceFile: SourceFile;
        readonly isJSFile: boolean;
    }

    interface FunctionInfo {
        readonly kind: InfoKind.Function;
        readonly call: CallExpression;
        readonly token: Identifier;
        readonly sourceFile: SourceFile;
        readonly modifierFlags: ModifierFlags;
        readonly parentDeclaration: SourceFile | ModuleDeclaration;
    }

    function getInfo(sourceFile: SourceFile, tokenPos: number, checker: TypeChecker, program: Program): Info | undefined {
        // The identifier of the missing property. eg:
        // this.missing = 1;
        //      ^^^^^^^
        const token = getTokenAtPosition(sourceFile, tokenPos);
        if (!isIdentifier(token) && !isPrivateIdentifier(token)) {
            return undefined;
        }

        const { parent } = token;
        if (isIdentifier(token) && isCallExpression(parent)) {
            return { kind: InfoKind.Function, token, call: parent, sourceFile, modifierFlags: ModifierFlags.None, parentDeclaration: sourceFile };
        }

        if (!isPropertyAccessExpression(parent)) {
            return undefined;
        }

        const leftExpressionType = skipConstraint(checker.getTypeAtLocation(parent.expression));
        const { symbol } = leftExpressionType;
        if (!symbol || !symbol.declarations) {
            return undefined;
        }

        if (isIdentifier(token) && isCallExpression(parent.parent)) {
            const moduleDeclaration = find(symbol.declarations, isModuleDeclaration);
            const moduleDeclarationSourceFile = moduleDeclaration?.getSourceFile();
            if (moduleDeclaration && moduleDeclarationSourceFile && !program.isSourceFileFromExternalLibrary(moduleDeclarationSourceFile)) {
                return { kind: InfoKind.Function, token, call: parent.parent, sourceFile, modifierFlags: ModifierFlags.Export, parentDeclaration: moduleDeclaration };
            }

            const moduleSourceFile = find(symbol.declarations, isSourceFile);
            if (sourceFile.commonJsModuleIndicator) {
                return;
            }

            if (moduleSourceFile && !program.isSourceFileFromExternalLibrary(moduleSourceFile)) {
                return { kind: InfoKind.Function, token, call: parent.parent, sourceFile: moduleSourceFile, modifierFlags: ModifierFlags.Export, parentDeclaration: moduleSourceFile };
            }
        }

        const classDeclaration = find(symbol.declarations, isClassLike);
        // Don't suggest adding private identifiers to anything other than a class.
        if (!classDeclaration && isPrivateIdentifier(token)) {
            return undefined;
        }

        // Prefer to change the class instead of the interface if they are merged
        const classOrInterface = classDeclaration || find(symbol.declarations, isInterfaceDeclaration);
        if (classOrInterface && !program.isSourceFileFromExternalLibrary(classOrInterface.getSourceFile())) {
            const makeStatic = ((leftExpressionType as TypeReference).target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol);
            if (makeStatic && (isPrivateIdentifier(token) || isInterfaceDeclaration(classOrInterface))) {
                return undefined;
            }

            const declSourceFile = classOrInterface.getSourceFile();
            const modifierFlags = (makeStatic ? ModifierFlags.Static : 0) | (startsWithUnderscore(token.text) ? ModifierFlags.Private : 0);
            const isJSFile = isSourceFileJS(declSourceFile);
            const call = tryCast(parent.parent, isCallExpression);
            return { kind: InfoKind.ClassOrInterface, token, call, modifierFlags, parentDeclaration: classOrInterface, declSourceFile, isJSFile };
        }

        const enumDeclaration = find(symbol.declarations, isEnumDeclaration);
        if (enumDeclaration && !isPrivateIdentifier(token) && !program.isSourceFileFromExternalLibrary(enumDeclaration.getSourceFile())) {
            return { kind: InfoKind.Enum, token, parentDeclaration: enumDeclaration };
        }
        return undefined;
    }

    function getActionsForMissingMemberDeclaration(context: CodeFixContext, info: ClassOrInterfaceInfo): CodeFixAction[] | undefined {
        return info.isJSFile ? singleElementArray(createActionForAddMissingMemberInJavascriptFile(context, info)) :
            createActionsForAddMissingMemberInTypeScriptFile(context, info);
    }

    function createActionForAddMissingMemberInJavascriptFile(context: CodeFixContext, { parentDeclaration, declSourceFile, modifierFlags, token }: ClassOrInterfaceInfo): CodeFixAction | undefined {
        if (isInterfaceDeclaration(parentDeclaration)) {
            return undefined;
        }

        const changes = textChanges.ChangeTracker.with(context, t => addMissingMemberInJs(t, declSourceFile, parentDeclaration, token, !!(modifierFlags & ModifierFlags.Static)));
        if (changes.length === 0) {
            return undefined;
        }

        const diagnostic = modifierFlags & ModifierFlags.Static ? Diagnostics.Initialize_static_property_0 :
            isPrivateIdentifier(token) ? Diagnostics.Declare_a_private_field_named_0 : Diagnostics.Initialize_property_0_in_the_constructor;

        return createCodeFixAction(fixMissingMember, changes, [diagnostic, token.text], fixMissingMember, Diagnostics.Add_all_missing_members);
    }

    function addMissingMemberInJs(changeTracker: textChanges.ChangeTracker, declSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, token: Identifier | PrivateIdentifier, makeStatic: boolean): void {
        const tokenName = token.text;
        if (makeStatic) {
            if (classDeclaration.kind === SyntaxKind.ClassExpression) {
                return;
            }
            const className = classDeclaration.name!.getText();
            const staticInitialization = initializePropertyToUndefined(factory.createIdentifier(className), tokenName);
            changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization);
        }
        else if (isPrivateIdentifier(token)) {
            const property = factory.createPropertyDeclaration(
                /*decorators*/ undefined,
                /*modifiers*/ undefined,
                tokenName,
                /*questionToken*/ undefined,
                /*type*/ undefined,
                /*initializer*/ undefined);

            const lastProp = getNodeToInsertPropertyAfter(classDeclaration);
            if (lastProp) {
                changeTracker.insertNodeAfter(declSourceFile, lastProp, property);
            }
            else {
                changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property);
            }
        }
        else {
            const classConstructor = getFirstConstructorWithBody(classDeclaration);
            if (!classConstructor) {
                return;
            }
            const propertyInitialization = initializePropertyToUndefined(factory.createThis(), tokenName);
            changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization);
        }
    }

    function initializePropertyToUndefined(obj: Expression, propertyName: string) {
        return factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(obj, propertyName), factory.createIdentifier("undefined")));
    }

    function createActionsForAddMissingMemberInTypeScriptFile(context: CodeFixContext, { parentDeclaration, declSourceFile, modifierFlags, token }: ClassOrInterfaceInfo): CodeFixAction[] | undefined {
        const memberName = token.text;
        const isStatic = modifierFlags & ModifierFlags.Static;
        const typeNode = getTypeNode(context.program.getTypeChecker(), parentDeclaration, token);
        const addPropertyDeclarationChanges = (modifierFlags: ModifierFlags) => textChanges.ChangeTracker.with(context, t => addPropertyDeclaration(t, declSourceFile, parentDeclaration, memberName, typeNode, modifierFlags));

        const actions = [createCodeFixAction(fixMissingMember, addPropertyDeclarationChanges(modifierFlags & ModifierFlags.Static), [isStatic ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0, memberName], fixMissingMember, Diagnostics.Add_all_missing_members)];
        if (isStatic || isPrivateIdentifier(token)) {
            return actions;
        }

        if (modifierFlags & ModifierFlags.Private) {
            actions.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addPropertyDeclarationChanges(ModifierFlags.Private), [Diagnostics.Declare_private_property_0, memberName]));
        }

        actions.push(createAddIndexSignatureAction(context, declSourceFile, parentDeclaration, token.text, typeNode));
        return actions;
    }

    function getTypeNode(checker: TypeChecker, classDeclaration: ClassOrInterface, token: Node) {
        let typeNode: TypeNode | undefined;
        if (token.parent.parent.kind === SyntaxKind.BinaryExpression) {
            const binaryExpression = token.parent.parent as BinaryExpression;
            const otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left;
            const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression)));
            typeNode = checker.typeToTypeNode(widenedType, classDeclaration, NodeBuilderFlags.NoTruncation);
        }
        else {
            const contextualType = checker.getContextualType(token.parent as Expression);
            typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, NodeBuilderFlags.NoTruncation) : undefined;
        }
        return typeNode || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword);
    }

    function addPropertyDeclaration(changeTracker: textChanges.ChangeTracker, declSourceFile: SourceFile, classDeclaration: ClassOrInterface, tokenName: string, typeNode: TypeNode, modifierFlags: ModifierFlags): void {
        const property = factory.createPropertyDeclaration(
            /*decorators*/ undefined,
            /*modifiers*/ modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : undefined,
            tokenName,
            /*questionToken*/ undefined,
            typeNode,
            /*initializer*/ undefined);

        const lastProp = getNodeToInsertPropertyAfter(classDeclaration);
        if (lastProp) {
            changeTracker.insertNodeAfter(declSourceFile, lastProp, property);
        }
        else {
            changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property);
        }
    }

    // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration.
    function getNodeToInsertPropertyAfter(cls: ClassOrInterface): PropertyDeclaration | undefined {
        let res: PropertyDeclaration | undefined;
        for (const member of cls.members) {
            if (!isPropertyDeclaration(member)) break;
            res = member;
        }
        return res;
    }

    function createAddIndexSignatureAction(context: CodeFixContext, declSourceFile: SourceFile, classDeclaration: ClassOrInterface, tokenName: string, typeNode: TypeNode): CodeFixAction {
        // Index signatures cannot have the static modifier.
        const stringTypeNode = factory.createKeywordTypeNode(SyntaxKind.StringKeyword);
        const indexingParameter = factory.createParameterDeclaration(
            /*decorators*/ undefined,
            /*modifiers*/ undefined,
            /*dotDotDotToken*/ undefined,
            "x",
            /*questionToken*/ undefined,
            stringTypeNode,
            /*initializer*/ undefined);
        const indexSignature = factory.createIndexSignature(
            /*decorators*/ undefined,
            /*modifiers*/ undefined,
            [indexingParameter],
            typeNode);

        const changes = textChanges.ChangeTracker.with(context, t => t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature));
        // No fixId here because code-fix-all currently only works on adding individual named properties.
        return createCodeFixActionWithoutFixAll(fixMissingMember, changes, [Diagnostics.Add_index_signature_for_property_0, tokenName]);
    }

    function getActionsForMissingMethodDeclaration(context: CodeFixContext, info: ClassOrInterfaceInfo): CodeFixAction[] | undefined {
        const { parentDeclaration, declSourceFile, modifierFlags, token, call } = info;
        if (call === undefined) {
            return undefined;
        }

        // Private methods are not implemented yet.
        if (isPrivateIdentifier(token)) {
            return undefined;
        }

        const methodName = token.text;
        const addMethodDeclarationChanges = (modifierFlags: ModifierFlags) => textChanges.ChangeTracker.with(context, t => addMethodDeclaration(context, t, call, token, modifierFlags, parentDeclaration, declSourceFile));
        const actions = [createCodeFixAction(fixMissingMember, addMethodDeclarationChanges(modifierFlags & ModifierFlags.Static), [modifierFlags & ModifierFlags.Static ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0, methodName], fixMissingMember, Diagnostics.Add_all_missing_members)];
        if (modifierFlags & ModifierFlags.Private) {
            actions.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addMethodDeclarationChanges(ModifierFlags.Private), [Diagnostics.Declare_private_method_0, methodName]));
        }
        return actions;
    }

    function addMethodDeclaration(
        context: CodeFixContextBase,
        changes: textChanges.ChangeTracker,
        callExpression: CallExpression,
        name: Identifier,
        modifierFlags: ModifierFlags,
        parentDeclaration: ClassOrInterface,
        sourceFile: SourceFile,
    ): void {
        const importAdder = createImportAdder(sourceFile, context.program, context.preferences, context.host);
        const methodDeclaration = createSignatureDeclarationFromCallExpression(SyntaxKind.MethodDeclaration, context, importAdder, callExpression, name, modifierFlags, parentDeclaration) as MethodDeclaration;
        const containingMethodDeclaration = findAncestor(callExpression, n => isMethodDeclaration(n) || isConstructorDeclaration(n));
        if (containingMethodDeclaration && containingMethodDeclaration.parent === parentDeclaration) {
            changes.insertNodeAfter(sourceFile, containingMethodDeclaration, methodDeclaration);
        }
        else {
            changes.insertNodeAtClassStart(sourceFile, parentDeclaration, methodDeclaration);
        }
        importAdder.writeFixes(changes);
    }

    function addEnumMemberDeclaration(changes: textChanges.ChangeTracker, checker: TypeChecker, { token, parentDeclaration }: EnumInfo) {
        /**
         * create initializer only literal enum that has string initializer.
         * value of initializer is a string literal that equal to name of enum member.
         * numeric enum or empty enum will not create initializer.
         */
        const hasStringInitializer = some(parentDeclaration.members, member => {
            const type = checker.getTypeAtLocation(member);
            return !!(type && type.flags & TypeFlags.StringLike);
        });

        const enumMember = factory.createEnumMember(token, hasStringInitializer ? factory.createStringLiteral(token.text) : undefined);
        changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, factory.updateEnumDeclaration(
            parentDeclaration,
            parentDeclaration.decorators,
            parentDeclaration.modifiers,
            parentDeclaration.name,
            concatenate(parentDeclaration.members, singleElementArray(enumMember))
        ), {
            leadingTriviaOption: textChanges.LeadingTriviaOption.IncludeAll,
            trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude
        });
    }

    function addFunctionDeclaration(changes: textChanges.ChangeTracker, context: CodeFixContextBase, info: FunctionInfo) {
        const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host);
        const functionDeclaration = createSignatureDeclarationFromCallExpression(SyntaxKind.FunctionDeclaration, context, importAdder, info.call, idText(info.token), info.modifierFlags, info.parentDeclaration) as FunctionDeclaration;
        changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration);
    }
}