text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Digimezzo.WPFControls
{
    public enum DateFormat
    {
        DayMonthYear = 0,
        MonthDayYear = 1,
        YearMonthDay = 2,
        YearDayMonth = 3
    }

    public class MaterialDateBox : Control, IDisposable
    {
        MaterialComboBox boxDay;
        MaterialComboBox boxMonth;
        MaterialComboBox boxYear;
        private TextBlock errorLabel;
        private StackPanel panel;
        private bool disposedValue = false;

        public bool IsValid
        {
            get { return (bool)GetValue(IsValidProperty); }
            set { SetValue(IsValidProperty, value); }
        }

        public static readonly DependencyProperty IsValidProperty =
            DependencyProperty.Register(nameof(IsValid), typeof(bool), typeof(MaterialDateBox), new PropertyMetadata(true));

        public int Day
        {
            get { return (int)GetValue(DayProperty); }
            set { SetValue(DayProperty, value); }
        }

        public static readonly DependencyProperty DayProperty =
            DependencyProperty.Register(nameof(Day), typeof(int), typeof(MaterialDateBox), new PropertyMetadata(0));

        public int Month
        {
            get { return (int)GetValue(MonthProperty); }
            set { SetValue(MonthProperty, value); }
        }

        public static readonly DependencyProperty MonthProperty =
            DependencyProperty.Register(nameof(Month), typeof(int), typeof(MaterialDateBox), new PropertyMetadata(0));

        public int Year
        {
            get { return (int)GetValue(YearProperty); }
            set { SetValue(YearProperty, value); }
        }

        public static readonly DependencyProperty YearProperty =
            DependencyProperty.Register(nameof(Year), typeof(int), typeof(MaterialDateBox), new PropertyMetadata(0));

        public ValidationMode ValidationMode
        {
            get { return (ValidationMode)GetValue(ValidationModeProperty); }
            set { SetValue(ValidationModeProperty, value); }
        }

        public static readonly DependencyProperty ValidationModeProperty =
            DependencyProperty.Register(nameof(ValidationMode), typeof(ValidationMode), typeof(MaterialDateBox), new PropertyMetadata(ValidationMode.None));

        public DateFormat DateFormat
        {
            get { return (DateFormat)GetValue(DateFormatProperty); }
            set { SetValue(DateFormatProperty, value); }
        }

        public Brush Accent
        {
            get { return (Brush)GetValue(AccentProperty); }
            set { SetValue(AccentProperty, value); }
        }

        public static readonly DependencyProperty AccentProperty =
            DependencyProperty.Register(nameof(Accent), typeof(Brush), typeof(MaterialDateBox), new PropertyMetadata(Brushes.Blue));

        public bool IsFloating
        {
            get { return (bool)GetValue(IsFloatingProperty); }
            set { SetValue(IsFloatingProperty, value); }
        }

        public static readonly DependencyProperty IsFloatingProperty =
            DependencyProperty.Register(nameof(IsFloating), typeof(bool), typeof(MaterialDateBox), new PropertyMetadata(false));

        public string LabelDay
        {
            get { return (string)GetValue(LabelDayProperty); }
            set { SetValue(LabelDayProperty, value); }
        }

        public static readonly DependencyProperty LabelDayProperty =
            DependencyProperty.Register(nameof(LabelDay), typeof(string), typeof(MaterialDateBox), new PropertyMetadata("Day", new PropertyChangedCallback(OnLabelDayPropertyChanged)));

        private static void OnLabelDayPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MaterialDateBox dateBox = d as MaterialDateBox;

            if (dateBox != null && dateBox.boxDay != null && dateBox.boxDay.InputLabel != null)
            {
                dateBox.boxDay.InputLabel.Text = dateBox.boxDay.Label;
            }
        }

        public string LabelMonth
        {
            get { return (string)GetValue(LabelMonthProperty); }
            set { SetValue(LabelMonthProperty, value); }
        }

        public static readonly DependencyProperty LabelMonthProperty =
            DependencyProperty.Register(nameof(LabelMonth), typeof(string), typeof(MaterialDateBox), new PropertyMetadata("Month", new PropertyChangedCallback(OnLabelMonthPropertyChanged)));

        private static void OnLabelMonthPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MaterialDateBox dateBox = d as MaterialDateBox;

            if (dateBox != null && dateBox.boxMonth != null && dateBox.boxMonth.InputLabel != null)
            {
                dateBox.boxMonth.InputLabel.Text = dateBox.boxMonth.Label;
            }
        }

        public string LabelYear
        {
            get { return (string)GetValue(LabelYearProperty); }
            set { SetValue(LabelYearProperty, value); }
        }

        public static readonly DependencyProperty LabelYearProperty =
            DependencyProperty.Register(nameof(LabelYear), typeof(string), typeof(MaterialDateBox), new PropertyMetadata("Year", new PropertyChangedCallback(OnLabelYearPropertyChanged)));

        private static void OnLabelYearPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MaterialDateBox dateBox = d as MaterialDateBox;

            if (dateBox != null && dateBox.boxYear != null && dateBox.boxYear.InputLabel != null)
            {
                dateBox.boxYear.InputLabel.Text = dateBox.boxYear.Label;
            }
        }

        public Brush ErrorForeground
        {
            get { return (Brush)GetValue(ErrorForegroundProperty); }
            set { SetValue(ErrorForegroundProperty, value); }
        }

        public static readonly DependencyProperty ErrorForegroundProperty =
            DependencyProperty.Register(nameof(ErrorForeground), typeof(Brush), typeof(MaterialDateBox), new PropertyMetadata(Brushes.Red));

        public string ErrorText
        {
            get { return (string)GetValue(ErrorTextProperty); }
            set { SetValue(ErrorTextProperty, value); }
        }

        public static readonly DependencyProperty ErrorTextProperty =
            DependencyProperty.Register(nameof(ErrorText), typeof(string), typeof(MaterialDateBox), new PropertyMetadata("Invalid"));

        public static readonly DependencyProperty DateFormatProperty =
            DependencyProperty.Register(nameof(DateFormat), typeof(DateFormat), typeof(MaterialDateBox), new PropertyMetadata(DateFormat.DayMonthYear));

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            this.errorLabel = (TextBlock)GetTemplateChild("PART_ErrorLabel");
            this.panel = (StackPanel)GetTemplateChild("PART_Panel");

            switch (this.DateFormat)
            {
                case DateFormat.DayMonthYear:
                    this.boxDay = (MaterialComboBox)GetTemplateChild("PART_Box1");
                    this.boxMonth = (MaterialComboBox)GetTemplateChild("PART_Box2");
                    this.boxYear = (MaterialComboBox)GetTemplateChild("PART_Box3");
                    break;
                case DateFormat.MonthDayYear:
                    this.boxMonth = (MaterialComboBox)GetTemplateChild("PART_Box1");
                    this.boxDay = (MaterialComboBox)GetTemplateChild("PART_Box2");
                    this.boxYear = (MaterialComboBox)GetTemplateChild("PART_Box3");
                    break;
                case DateFormat.YearMonthDay:
                    this.boxYear = (MaterialComboBox)GetTemplateChild("PART_Box1");
                    this.boxMonth = (MaterialComboBox)GetTemplateChild("PART_Box2");
                    this.boxDay = (MaterialComboBox)GetTemplateChild("PART_Box3");
                    break;
                case DateFormat.YearDayMonth:
                    this.boxYear = (MaterialComboBox)GetTemplateChild("PART_Box1");
                    this.boxDay = (MaterialComboBox)GetTemplateChild("PART_Box2");
                    this.boxMonth = (MaterialComboBox)GetTemplateChild("PART_Box3");
                    break;
                default:
                    break;
            }

            this.errorLabel.FontSize = this.GetSmallFontSize();
            this.errorLabel.Margin = this.ValidationMode.Equals(ValidationMode.None) ? new Thickness(0) : new Thickness(0, this.GetMargin(), 0, 0);
            this.panel.Margin = this.IsFloating ? new Thickness(0, this.GetSmallFontSize() + this.GetMargin(), 0, 0) : new Thickness(0);

            this.boxDay.Label = this.LabelDay;
            this.boxMonth.Label = this.LabelMonth;
            this.boxYear.Label = this.LabelYear;

            this.boxDay.ItemsSource = this.Days();
            this.boxMonth.ItemsSource = this.Months();
            this.boxYear.ItemsSource = this.Years();

            this.boxDay.SelectionChanged += BoxDay_SelectionChanged;
            this.boxMonth.SelectionChanged += BoxMonth_SelectionChanged;
            this.boxYear.SelectionChanged += BoxYear_SelectionChanged;
        }

        private void BoxDay_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is MaterialComboBox)
            {
                MaterialComboBox box = (MaterialComboBox)sender;

                if (box.SelectedItem is int)
                {
                    this.Day = (int)box.SelectedItem;
                    this.Validate();
                }
            }
        }

        private void BoxMonth_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is MaterialComboBox)
            {
                MaterialComboBox box = (MaterialComboBox)sender;

                if(box.SelectedItem is int)
                {
                    this.Month = (int)box.SelectedItem;
                    this.Validate();
                }
            }
        }

        private void BoxYear_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is MaterialComboBox)
            {
                MaterialComboBox box = (MaterialComboBox)sender;

                if (box.SelectedItem is int)
                {
                    this.Year = (int)box.SelectedItem;
                    this.Validate();
                }
            }
        }

        static MaterialDateBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(MaterialDateBox), new FrameworkPropertyMetadata(typeof(MaterialDateBox)));
        }

        private double GetSmallFontSize()
        {
            return this.FontSize > 14 ? this.FontSize * 0.7 : 10;
        }

        private double GetMargin()
        {
            return this.FontSize * 0.3;
        }

        public List<int> Days()
        {
            var days = new List<int>();

            for (int i = 1; i <= 31; i++)
            {
                days.Add(i);
            }

            return days;
        }

        public List<int> Months()
        {
            var days = new List<int>();

            for (int i = 1; i <= 12; i++)
            {
                days.Add(i);
            }

            return days;
        }

        public List<int> Years()
        {
            var years = new List<int>();

            for (int i = 1979; i <= DateTime.Now.Year; i++)
            {
                years.Add(i);
            }

            return years;
        }

        private void Validate()
        {
            if (!this.ValidationMode.Equals(ValidationMode.Date))
            {
                return;
            }

            if (this.Day.Equals(0) || this.Month.Equals(0) || this.Year.Equals(0))
            {
                return;
            }

            DateTime dateValue;

            if (DateTime.TryParseExact($"{this.Year}-{this.Month.ToString("D2")}-{this.Day.ToString("D2")}", "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
            {
                this.errorLabel.Text = String.Empty;
                this.IsValid = true;
            }
            else
            {
                this.errorLabel.Text = this.ErrorText;
                this.IsValid = false;
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    if (this.boxDay != null)
                    {
                        this.boxDay.SelectionChanged -= BoxDay_SelectionChanged;
                    }

                    if (this.boxMonth != null)
                    {
                        this.boxMonth.SelectionChanged -= BoxMonth_SelectionChanged;
                    }

                    if (this.boxYear != null)
                    {
                        this.boxYear.SelectionChanged -= BoxYear_SelectionChanged;
                    }
                }

                disposedValue = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }
    }
}


text:
package org.spongycastle.cms;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import org.spongycastle.asn1.ASN1Encodable;
import org.spongycastle.asn1.ASN1Encoding;
import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.ASN1Sequence;

public class PKCS7ProcessableObject
    implements CMSTypedData
{
    private final ASN1ObjectIdentifier type;
    private final ASN1Encodable structure;

    public PKCS7ProcessableObject(
        ASN1ObjectIdentifier type,
        ASN1Encodable structure)
    {
        this.type = type;
        this.structure = structure;
    }

    public ASN1ObjectIdentifier getContentType()
    {
        return type;
    }

    public void write(OutputStream cOut)
        throws IOException, CMSException
    {
        if (structure instanceof ASN1Sequence)
        {
            ASN1Sequence s = ASN1Sequence.getInstance(structure);

            for (Iterator it = s.iterator(); it.hasNext();)
            {
                ASN1Encodable enc = (ASN1Encodable)it.next();

                cOut.write(enc.toASN1Primitive().getEncoded(ASN1Encoding.DER));
            }
        }
        else
        {
            byte[] encoded = structure.toASN1Primitive().getEncoded(ASN1Encoding.DER);
            int index = 1;

            while ((encoded[index] & 0xff) > 127)
            {
                index++;
            }

            index++;

            cOut.write(encoded, index, encoded.length - index);
        }
    }

    public Object getContent()
    {
        return structure;
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <aws/ram/model/AssociateResourceShareRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::RAM::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

AssociateResourceShareRequest::AssociateResourceShareRequest() :
    m_resourceShareArnHasBeenSet(false),
    m_resourceArnsHasBeenSet(false),
    m_principalsHasBeenSet(false),
    m_clientTokenHasBeenSet(false)
{
}

Aws::String AssociateResourceShareRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_resourceShareArnHasBeenSet)
  {
   payload.WithString("resourceShareArn", m_resourceShareArn);

  }

  if(m_resourceArnsHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> resourceArnsJsonList(m_resourceArns.size());
   for(unsigned resourceArnsIndex = 0; resourceArnsIndex < resourceArnsJsonList.GetLength(); ++resourceArnsIndex)
   {
     resourceArnsJsonList[resourceArnsIndex].AsString(m_resourceArns[resourceArnsIndex]);
   }
   payload.WithArray("resourceArns", std::move(resourceArnsJsonList));

  }

  if(m_principalsHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> principalsJsonList(m_principals.size());
   for(unsigned principalsIndex = 0; principalsIndex < principalsJsonList.GetLength(); ++principalsIndex)
   {
     principalsJsonList[principalsIndex].AsString(m_principals[principalsIndex]);
   }
   payload.WithArray("principals", std::move(principalsJsonList));

  }

  if(m_clientTokenHasBeenSet)
  {
   payload.WithString("clientToken", m_clientToken);

  }

  return payload.View().WriteReadable();
}


text:
class Gathering < ActiveRecord::Base
  has_many :contact_gatherings
  has_many :members, :through => :contact_gatherings, :source => :contact
end


text:
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable MemberCanBePrivate.Global
namespace Apache.Ignite.Core.Cache.Configuration
{
    using System;
    using System.Diagnostics;
    using Apache.Ignite.Core.Impl.Binary;
    using Apache.Ignite.Core.Impl.Common;
    using Apache.Ignite.Core.Log;

    /// <summary>
    /// Represents a queryable field.
    /// </summary>
    public class QueryField
    {
        /** */
        private Type _type;

        /** */
        private string _fieldTypeName;

        /// <summary>
        /// Initializes a new instance of the <see cref="QueryField"/> class.
        /// </summary>
        public QueryField()
        {
            // No-op.
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="QueryField"/> class.
        /// </summary>
        /// <param name="name">Name.</param>
        /// <param name="javaFieldTypeName">Java type name.</param>
        public QueryField(string name, string javaFieldTypeName)
        {
            IgniteArgumentCheck.NotNullOrEmpty(name, "name");
            IgniteArgumentCheck.NotNullOrEmpty(javaFieldTypeName, "typeName");

            Name = name;
            FieldTypeName = javaFieldTypeName;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="QueryField" /> class.
        /// </summary>
        /// <param name="name">Name.</param>
        /// <param name="fieldType">Type.</param>
        public QueryField(string name, Type fieldType)
        {
            IgniteArgumentCheck.NotNullOrEmpty(name, "name");
            IgniteArgumentCheck.NotNull(fieldType, "type");

            Name = name;
            FieldType = fieldType;
        }

        /// <summary>
        /// Gets or sets the field name.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the type of the value.
        /// <para />
        /// This is a shortcut for <see cref="FieldTypeName"/>. Getter will return null for non-primitive types.
        /// </summary>
        public Type FieldType
        {
            get { return _type ?? JavaTypes.GetDotNetType(FieldTypeName); }
            set
            {
                FieldTypeName = value == null
                    ? null
                    : (JavaTypes.GetJavaTypeName(value) ?? BinaryUtils.GetTypeName(value));

                _type = value;
            }
        }

        /// <summary>
        /// Gets the Java type name.
        /// </summary>
        public string FieldTypeName
        {
            get { return _fieldTypeName; }
            set
            {
                _fieldTypeName = value;
                _type = null;
            }
        }

        /// <summary>
        /// Validates this instance and outputs information to the log, if necessary.
        /// </summary>
        internal void Validate(ILogger log, string logInfo)
        {
            Debug.Assert(log != null);
            Debug.Assert(logInfo != null);

            logInfo += string.Format(", QueryField '{0}'", Name);

            JavaTypes.LogIndirectMappingWarning(_type, log, logInfo);
        }
    }
}


text:
package com.sharethis.loopy.sdk.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;

import java.util.List;

/**
 * @author Jason Polites
 */
public class MockAppUtils extends AppUtils {
    public MockAppUtils() {
        super();
    }

    @Override
    public List<ResolveInfo> listAppsForType(Context context, String type) {
        return super.listAppsForType(context, type);
    }

    @Override
    public Intent getSendIntent() {
        return super.getSendIntent();
    }
}


text:
"""Tests for non-core functionality in sandman2."""

from pytest_flask.fixtures import client

read_only = True

def test_pagination(client):
    """Do we return paginated results when a 'page' parameter is provided?"""
    response = client.get('/artist/?page=2')
    assert response.status_code == 200
    assert len(response.json['resources']) == 20
    assert response.json['resources'][0]['ArtistId'] == 21

def test_filtering(client):
    """Do we return filtered results when a URL parameter is provided?"""
    response = client.get('/artist/?Name=AC/DC')
    assert response.status_code == 200
    assert len(response.json['resources']) == 1
    assert response.json['resources'][0]['ArtistId'] == 1

def test_filtering_unkown_field(client):
    """Do we return filtered results when a URL parameter is provided?"""
    response = client.get('/artist/?Foo=AC/DC')
    assert response.status_code == 400

def test_wildcard_filtering(client):
    """Do we return filtered results when a wildcarded URL parameter is provided?"""
    response = client.get('/artist/?Name=%25%25DC')
    assert response.status_code == 200
    assert len(response.json['resources']) == 1
    assert response.json['resources'][0]['ArtistId'] == 1

def test_sorting(client):
    """Do we return sorted results when a 'sort' URL parameter is provided?"""
    response = client.get('/artist/?sort=Name')
    assert response.status_code == 200
    assert len(response.json['resources']) == 276
    assert response.json['resources'][0]['ArtistId'] == 43

def test_sorting_descending(client):
    """Can we sort results in descending order?"""
    response = client.get('/artist/?sort=-Name')
    assert response.status_code == 200
    assert len(response.json['resources']) == 276
    assert response.json['resources'][0]['ArtistId'] == 155

def test_limit(client):
    """Do we return sorted results when a 'limit' URL parameter is provided?"""
    response = client.get('/artist/?limit=5')
    assert response.status_code == 200
    assert len(response.json['resources']) == 5
    assert response.json['resources'][0]['ArtistId'] == 1

def test_sort_limit_and_pagination(client):
    """Can we combine filtering parameters to get targeted results?"""
    response = client.get('/artist/?limit=2&sort=ArtistId&page=2')
    assert response.status_code == 200
    assert len(response.json['resources']) == 2
    assert response.json['resources'][0]['ArtistId'] == 3


text:
using Microsoft.DataTransfer.Basics;
using Microsoft.DataTransfer.Basics.Collections;
using Microsoft.DataTransfer.DocumentDb.Client;
using Microsoft.DataTransfer.DocumentDb.Shared;
using Microsoft.DataTransfer.DocumentDb.Sink.Substitutions;
using Microsoft.DataTransfer.DocumentDb.Sink.Substitutions.Range;
using Microsoft.DataTransfer.DocumentDb.Transformation;
using Microsoft.DataTransfer.DocumentDb.Transformation.Dates;
using Microsoft.DataTransfer.DocumentDb.Transformation.Remap;
using Microsoft.DataTransfer.DocumentDb.Transformation.Stringify;
using Microsoft.DataTransfer.Extensibility;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Microsoft.DataTransfer.DocumentDb.Sink
{
    abstract class DocumentDbSinkAdapterFactoryBase<TConfiguration> : DocumentDbAdapterFactoryBase, IDataSinkAdapterFactory<TConfiguration>
        where TConfiguration : IDocumentDbSinkAdapterConfiguration
    {
        private const string DocumentDbIdField = "id";

        private static readonly ISubstitutionResolver substitutions = new RangeSubstitutionResolver();

        public abstract string Description { get; }

        public Task<IDataSinkAdapter> CreateAsync(TConfiguration configuration, IDataTransferContext context)
        {
            ValidateBaseConfiguration(configuration);

            var collectionNames = ResolveCollectionNames(configuration.Collection);
            if (!collectionNames.Any())
                throw Errors.CollectionNameMissing();

            return CreateAsync(
                CreateClient(configuration, context, collectionNames.Length > 1),
                GetDataItemTransformation(configuration),
                configuration, collectionNames);
        }

        protected abstract Task<IDataSinkAdapter> CreateAsync(DocumentDbClient client, IDataItemTransformation transformation,
            TConfiguration configuration, IEnumerable<string> collectionNames);

        private static IDataItemTransformation GetDataItemTransformation(IDocumentDbSinkAdapterConfiguration configuration)
        {
            Guard.NotNull("configuration", configuration);

            var transformations = new List<IDataItemTransformation>();

            if (configuration.IdField != null && !DocumentDbIdField.Equals(configuration.IdField))
               transformations.Add(new RemapFieldsTransformation(new Map<string, string> { { configuration.IdField, DocumentDbIdField } }));

            transformations.Add(new DateTimeFieldsTransformation(configuration.Dates ?? Defaults.Current.SinkDateTimeHandling));

            transformations.Add(new StringifyFieldsTransformation(new[] { DocumentDbIdField }));

            return new TransformationPipeline(transformations);
        }

        private static string[] ResolveCollectionNames(IEnumerable<string> collectionNamePatterns)
        {
            return collectionNamePatterns.AsParallel().SelectMany(p => substitutions.Resolve(p)).Distinct().ToArray();
        }
    }
}


text:
namespace SmartSchoolManagementSystem
{
    partial class ChangeClass
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnsearch = new System.Windows.Forms.Button();
            this.txtid = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            //
            // btnsearch
            //
            this.btnsearch.Location = new System.Drawing.Point(255, 26);
            this.btnsearch.Name = "btnsearch";
            this.btnsearch.Size = new System.Drawing.Size(75, 23);
            this.btnsearch.TabIndex = 0;
            this.btnsearch.Text = "button1";
            this.btnsearch.UseVisualStyleBackColor = true;
            this.btnsearch.Click += new System.EventHandler(this.btnsearch_Click);
            //
            // txtid
            //
            this.txtid.Location = new System.Drawing.Point(120, 26);
            this.txtid.Name = "txtid";
            this.txtid.Size = new System.Drawing.Size(129, 20);
            this.txtid.TabIndex = 1;
            //
            // ChangeClass
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(607, 346);
            this.Controls.Add(this.txtid);
            this.Controls.Add(this.btnsearch);
            this.Name = "ChangeClass";
            this.Text = "Change Class";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnsearch;
        private System.Windows.Forms.TextBox txtid;
    }
}


text:
namespace ranges
{
    inline namespace v3
    {
        /// \ingroup group-concepts
        template<typename I, typename C, typename P = ident>
        using RemovableIf = meta::strict_and<
            ForwardIterator<I>,
            IndirectPredicate<C, projected<I, P>>,
            Permutable<I>>;

        /// \addtogroup group-algorithms
        /// @{
        struct remove_if_fn
        {
            template<typename I, typename S, typename C, typename P = ident,
                CONCEPT_REQUIRES_(RemovableIf<I, C, P>() && Sentinel<S, I>())>
            I operator()(I begin, S end, C pred, P proj = P{}) const
            {
                begin = find_if(std::move(begin), end, std::ref(pred), std::ref(proj));
                if(begin != end)
                {
                    for(I i = next(begin); i != end; ++i)
                    {
                        if(!(invoke(pred, invoke(proj, *i))))
                        {
                            *begin = iter_move(i);
                            ++begin;
                        }
                    }
                }
                return begin;
            }

            template<typename Rng, typename C, typename P = ident,
                typename I = iterator_t<Rng>,
                CONCEPT_REQUIRES_(RemovableIf<I, C, P>() && ForwardRange<Rng>())>
            safe_iterator_t<Rng> operator()(Rng &&rng, C pred, P proj = P{}) const
            {
                return (*this)(begin(rng), end(rng), std::move(pred), std::move(proj));
            }
        };

        /// \sa `remove_if_fn`
        /// \ingroup group-algorithms
        RANGES_INLINE_VARIABLE(with_braced_init_args<remove_if_fn>, remove_if)
        /// @}
    } // namespace v3
} // namespace ranges

#endif // include guard


text:
'''
Copyright (c) 2015 by Tobias Houska
This file is part of Statistical Parameter Estimation Tool (SPOTPY).

:author: Tobias Houska

:paper: Houska, T., Kraft, P., Chamorro-Chavez, A. and Breuer, L.:
SPOTting Model Parameters Using a Ready-Made Python Package,
PLoS ONE, 10(12), e0145180, doi:10.1371/journal.pone.0145180, 2015.

This package enables the comprehensive use of different Bayesian and Heuristic calibration
techniques in one Framework. It comes along with an algorithms folder for the
sampling and an analyser class for the plotting of results by the sampling.

:dependencies: - Numpy >1.8 (http://www.numpy.org/)
               - Pandas >0.13 (optional) (http://pandas.pydata.org/)
               - Matplotlib >1.4 (optional) (http://matplotlib.org/)
               - CMF (optional) (http://fb09-pasig.umwelt.uni-giessen.de:8000/)
               - mpi4py (optional) (http://mpi4py.scipy.org/)
               - pathos (optional) (https://pypi.python.org/pypi/pathos/)
               - sqlite3 (optional) (https://pypi.python.org/pypi/sqlite3/)

               :help: For specific questions, try to use the documentation website at:
                http://fb09-pasig.umwelt.uni-giessen.de/spotpy/

For general things about parameter optimization techniques have a look at:
https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/tree/master/

Please cite our paper, if you are using SPOTPY.
'''
from . import database            # Writes the results of the sampler in a user defined output file
from . import algorithms          # Contains all the different algorithms implemented in SPOTPY
from . import parameter           # Contains different distributions to describe the prior information for every model parameter
from . import analyser            # Contains some examples to analyse the results of the different algorithms
from . import objectivefunctions  # Quantifies goodness of fit between simulation and evaluation data with objective functions
from . import likelihoods         # Quantifies goodness of fit between simulation and evaluation data with likelihood functions
from . import examples            # Contains tutorials how to use SPOTPY
from . import describe            # Contains some helper functions to describe samplers and set-ups
from .hydrology import signatures # Quantifies goodness of fit between simulation and evaluation data with hydrological signatures

__version__ = '1.5.8'


text:
using System;

class SayHello
{
   static void Main()
   {
      Hello();
   }
   public static void Hello()
   {
      //input
      string name = Console.ReadLine();
      //output
      Console.WriteLine("Hello, {0}!",name);
   }
}


text:
<?php

namespace Binaerpiloten\LigaBundle\Twig;

class UserExtension extends \Twig_Extension {

    protected $em;

    public function __construct($em) {
        $this->em = $em;
    }

    public function getFunctions() {
        return array(new \Twig_SimpleFunction('globalGetUsers', array($this, 'globalGetUsers')));
    }

    public function globalGetToken() {
    		$entities = $em->getRepository('BinaerpilotenLigaBundle:User')->findAll();
        return $entities;
    }

    public function getName()
    {
        return 'user_extension';
    }
}


text:
[![Gem Version](https://badge.fury.io/rb/component_generator.svg)](http://badge.fury.io/rb/component_generator)

## Description
Creates new rails engines in the components directory. New engines use postgres by default

## Usage:
- Require gem `gem "component_generator", "0.1.4"` .
- Install `bundle install`.
- Run `rails generate component_generator:new my_engine`.
- This will create a new engine called `MyEngine` in `components/my_engine`.


text:
package com.amazonaws.services.elasticloadbalancingv2.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum IpAddressType {

    Ipv4("ipv4"),
    Dualstack("dualstack");

    private String value;

    private IpAddressType(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return IpAddressType corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static IpAddressType fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (IpAddressType enumEntry : IpAddressType.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
Directory with recipes used to compile the various applications and libraries
modules in OASIS


text:
This code sample demonstrates techniques for creating a table binding, adding rows to an existing binding, applying table styles and applying cell formatting.

![](http://i.imgur.com/dex6lyr.png)

### Applies to ###
-  Excel 2013
-  Excel Online 2013

### Solution ###
Solution | Author(s)
---------|----------
Excel.TableBindingFormatting.sln | Doug Perkes (**Microsoft**)

### Version history ###
Version  | Date | Comments
---------| -----| --------
1.0  | April 23rd 2015 | Initial release

### Disclaimer ###
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

## Building the Sample ##
1. Open `ExcelFormattingSample.sln` in Visual Studio 2013.
2. Right-click on the `ExcelFormattingSample` project in Solution Explorer and choose Set as startup project.
3. Press the F5 key to build the solution and run it in Excel 2013

## Description ##

This example demonstrates several techniques for working with table bindings in Excel 2013 using the JavaScript API for Office.

To get started, run the solution as described above. Once running, specify a number of rows and click the Create Sample Table button. This will create a sample table with random data containing five columns: Number of Widgets, Order Needed By, Month, Color and Customer. The color column is a hex value and the font color of the cell is set to the value.

- Once the table has been inserted, the additional buttons on the app become available for use. Clicking Add Rows adds the specified number of rows of random data to the table.

![](http://i.imgur.com/2n4kNew.png)

- Select a table style from the Table Options drop down list and click the Table Options button to apply the style.

![](http://i.imgur.com/4tkMndG.png)

- Use the Range Formatting section to apply a border around the cells specified by the start and end row/col input boxes.
![](http://i.imgur.com/dgzD5kp.png)

> Note: The rows and columns are zero based and relative to the start of the table. They are not representative of the row numbers and column letters in Excel.

![](http://i.imgur.com/RT9YLob.png)

- To clear all formatting from the table, click the Clear Format button.

- Clicking Clear Data will remove all the rows from the table, but leave the table headers.

## Cell Formatting ##

The code samples demonstrate a valuable technique for applying cell formatting to a large range of cells. When applying cell formatting in Excel Online, the number of format groups passed to the `cellFormat` parameter cannot exceed 100. To get around this limitation the code demonstrates the use of a queue and a recursive function for applying the formatting in sets of 100.

## Source Code Files ##

The key source code files in this project are the following

- `Excel.TableBindingFormattingWeb\App\Home\Home.html` - contains the html controls and formatting for the UI of the app.
- `Excel.TableBindingFormattingWeb\App\Home\Home.js` - contains the application logic for creating and manipulating the table

## More Information ##

For more information see the [JavaScript API for Office](https://msdn.microsoft.com/en-us/library/office/fp142185.aspx "JavaScript API for Office").


text:
=======================================
 Release notes for PyTables 3.4 series
=======================================

Changes from 3.4.3 to 3.4.4
===========================

Improvements
------------
 - Environment variable to control the use of embedded libraries.
   Thanks to avalentino.
 - Include citation in repository.
   :issue:`690`. Thanks to katrinleinweber.

Bugs fixed
----------
 - Fixed import error with numexpr 2.6.5.dev0
   :issue:`685`. Thanks to cgohlke.
 - Fixed linter warnings.
   Thanks to avalentino.
 - Fixed for re.split() is version detection.
   :issue:`687`. Thanks to mingwandroid.
 - Fixed test failures with Python 2.7 and NumPy 1.14.3
   :issue:`688` & :issue:`689`. Thanks to oleksandr-pavlyk.

Changes from 3.4.2 to 3.4.3
===========================

Improvements
------------
 - On interactive python sessions, group/attribute  `__dir__()` method
   autocompletes children that are named as valid python identifiers.
   :issue:`624` & :issue:`625` thanks to ankostis.
 - Implement `Group.__getitem__()` to have groups act as python-containers,
   so code like this works: ``hfile.root['some child']``.
   :issue:`628` thanks to ankostis.
 - Enable building with Intel compiler (icc/icpc).
   Thanks to rohit-jamuar.
 - PEP 519 support, using new `os.fspath` method.
   Thanks to mruffalo.
 - Optional disable recording of ctime (metadata creation time) when
   creating datasets that makes possible to get bitwise identical output
   from repeated runs.
   Thanks to alex-cobb.
 - Prevent from reading all rows for each coord in a VLArray when
   indexing using a list .
   Thanks to igormq.
 - Internal Blosc version updated to 1.14.3

Bugs fixed
----------
 - Fixed division by zero when using `_convert_time64()` with an empty
   nparr array.
   :issue:`653`. Thanks to alobbs.
 - Fixed deprecation warnings with numpy 1.14.
   Thanks to oleksandr-pavlyk.
 - Skip DLL check when running from a frozen app.
   :issue:`675`. Thanks to jwiggins.
 - Fixed behaviour with slices out of range.
   :issue:`651`. Thanks to jackdbd.

Changes from 3.4.1 to 3.4.2
===========================

Improvements
------------
 - setup.py detects conda env and uses installed conda (hdf5, bzip2, lzo
   and/or blosc) packages when building from source.

Bugs fixed
----------
 - Linux wheels now built against built-in blosc.
 - Fixed windows absolute paths in ptrepack, ptdump, ptree.
   :issue:`616`. Thanks to oscar6echo.

Changes from 3.4.0 to 3.4.1
===========================

Bugs fixed
----------
 - Fixed bug in ptrepack

Changes from 3.3.0 to 3.4.0
===========================

Improvements
------------
 - Support for HDF5 v1.10.x (see :issue:`582`)
 - Fix compatibility with the upcoming Python 2.7.13, 3.5.3 and 3.6 versions.
   See also :issue:`590`. Thanks to Yaroslav Halchenko
 - Internal Blosc version updated to 1.11.3
 - Gracefully handle cpuinfo failure. (PR #578)
   Thanks to Zbigniew Jędrzejewski-Szmek
 - Update internal py-cpuinfo to 3.3.0. Thanks to Gustavo Serra Scalet.

Bugs fixed
----------
 - Fix conversion of python 2 `long` type to `six.integer_types` in atom.py.
   See also :issue:`598`. Thanks to Kyle Keppler for reporting.
 - Fix important bug in bitshuffle filter in internal Blosc on big-endian
   machines. See also :issue:`583`.
 - Fix allow for long type in nextafter. (PR #587) Thanks to Yaroslav Halchenko.
 - Fix unicode bug in group and tables names. :issue:`514`


text:
<?php

namespace Translate\Translator\Engine;

use Translate\Translator\EngineInterface;
use Yandex\Translate\Exception;

class Transltr implements EngineInterface {

	/**
	 * @var string
	 */
	public const URL = 'http://transltr.org/api/translate?text=%s&to=%s&from=%s';

	/**
	 * @param string $text Text
	 * @param string $to Iso2 code (e.g.: de)
	 * @param string $from Iso2 code (e.g.: en)
	 *
	 * @return string|null
	 */
	public function translate($text, $to, $from) {
		$text = urlencode($text);
		$url = sprintf(static::URL, $text, $to, $from);

		try {
			$handler = curl_init();
			curl_setopt($handler, CURLOPT_RETURNTRANSFER, true);

			curl_setopt($handler, CURLOPT_URL, $url);
			curl_setopt($handler, CURLOPT_SSL_VERIFYPEER, false);

			$remoteResult = curl_exec($handler);
			if ($remoteResult === false) {
				throw new Exception(curl_error($handler), curl_errno($handler));
			}

			$response = json_decode($remoteResult, true);

			$result = $response['translationText'];
		} catch (Exception $e) {
			trigger_error($e->getMessage());

			return null;
		}

		if ($result === '') {
			return null;
		}

		return $result;
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
Spring Framework: Class  ParameterizableViewController
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

com.interface21.web.servlet.mvc

Class  ParameterizableViewController

java.lang.Object
  |
  +--com.interface21.context.support.ApplicationObjectSupport
        |
        +--com.interface21.web.servlet.mvc.WebContentGenerator
              |
              +--com.interface21.web.servlet.mvc.AbstractController
                    |
                    +--com.interface21.web.servlet.mvc.ParameterizableViewController

All Implemented Interfaces:
ApplicationContextAware, Controller, InitializingBean

public class ParameterizableViewController
extends AbstractController
implements InitializingBean

Trivial controller that always returns a named view. The view
 can be configured using an exposed configuration property. This
 controller offers an alternative to sending a request straight to a view
 such as a JSP. The advantage here is, that you're decoupling the controller
 and the view, letter the some the configuration determine (instead of
 the controller) the viewtechnology.

An alternative to the ParameterizableViewController is of the
 com.interface21.web.servlet.mvc.multiaction,
 some of which allow the same behavior, but then for more views at in one
 controller.

Workflow
 (and that defined by superclass):

Request is received by the controller

call to handleRequestInternal which
      just returns the view, named by the configuration property
      viewName. Nothing more, nothing less

Exposed configuration properties
 (and those defined by superclass):

      name
      default
      description

      viewName
      null
      the name of the view the viewResolver will use to forward to
          (if this property is not set, an exception will be thrown during
          initialization)

Author:
Rod Johnson

Fields inherited from class com.interface21.context.support.ApplicationObjectSupport

logger

Constructor Summary

ParameterizableViewController()

Method Summary

 void
afterPropertiesSet()

          Ensure at least successView is set!?

 java.lang.String
getViewName()

          Gets the viewName.

protected  ModelAndView
handleRequestInternal(javax.servlet.http.HttpServletRequest request,
                      javax.servlet.http.HttpServletResponse response)

          Template method.

 void
setViewName(java.lang.String viewName)

          Sets the viewName.

Methods inherited from class com.interface21.web.servlet.mvc.AbstractController

handleRequest, setCacheSeconds, setRequireSession, setSupportedMethods

Methods inherited from class com.interface21.web.servlet.mvc.WebContentGenerator

cacheForSeconds, preventCaching, setUseExpiresHeader

Methods inherited from class com.interface21.context.support.ApplicationObjectSupport

getApplicationContext, initApplicationContext, setApplicationContext

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ParameterizableViewController

public ParameterizableViewController()

Method Detail

getViewName

public java.lang.String getViewName()

Gets the viewName.
 Used in this class: other properties are for subclasses only.

Returns:
Returns a String

setViewName

public void setViewName(java.lang.String viewName)

Sets the viewName.

Parameters:
viewName - The viewName to set

handleRequestInternal

protected ModelAndView handleRequestInternal(javax.servlet.http.HttpServletRequest request,
                                             javax.servlet.http.HttpServletResponse response)
                                      throws javax.servlet.ServletException,
                                             java.io.IOException

Description copied from class: AbstractController

Template method. Subclasses must implement this.
 The contract is the same as for handleRequest.

Overrides:
handleRequestInternal in class AbstractController

See Also:
AbstractController.handleRequest(HttpServletRequest, HttpServletResponse)

afterPropertiesSet

public void afterPropertiesSet()
                        throws java.lang.Exception

Ensure at least successView is set!?

Specified by:
afterPropertiesSet in interface InitializingBean

See Also:
InitializingBean.afterPropertiesSet()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Rod Johnson and Spring contributors 2001-2003.


text:
package edas

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// DeleteK8sSecret invokes the edas.DeleteK8sSecret API synchronously
func (client *Client) DeleteK8sSecret(request *DeleteK8sSecretRequest) (response *DeleteK8sSecretResponse, err error) {
	response = CreateDeleteK8sSecretResponse()
	err = client.DoAction(request, response)
	return
}

// DeleteK8sSecretWithChan invokes the edas.DeleteK8sSecret API asynchronously
func (client *Client) DeleteK8sSecretWithChan(request *DeleteK8sSecretRequest) (<-chan *DeleteK8sSecretResponse, <-chan error) {
	responseChan := make(chan *DeleteK8sSecretResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.DeleteK8sSecret(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// DeleteK8sSecretWithCallback invokes the edas.DeleteK8sSecret API asynchronously
func (client *Client) DeleteK8sSecretWithCallback(request *DeleteK8sSecretRequest, callback func(response *DeleteK8sSecretResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *DeleteK8sSecretResponse
		var err error
		defer close(result)
		response, err = client.DeleteK8sSecret(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// DeleteK8sSecretRequest is the request struct for api DeleteK8sSecret
type DeleteK8sSecretRequest struct {
	*requests.RoaRequest
	Name      string `position:"Query" name:"Name"`
	Namespace string `position:"Query" name:"Namespace"`
	ClusterId string `position:"Query" name:"ClusterId"`
}

// DeleteK8sSecretResponse is the response struct for api DeleteK8sSecret
type DeleteK8sSecretResponse struct {
	*responses.BaseResponse
	Code      int    `json:"Code" xml:"Code"`
	Message   string `json:"Message" xml:"Message"`
	RequestId string `json:"RequestId" xml:"RequestId"`
}

// CreateDeleteK8sSecretRequest creates a request to invoke DeleteK8sSecret API
func CreateDeleteK8sSecretRequest() (request *DeleteK8sSecretRequest) {
	request = &DeleteK8sSecretRequest{
		RoaRequest: &requests.RoaRequest{},
	}
	request.InitWithApiInfo("Edas", "2017-08-01", "DeleteK8sSecret", "/pop/v5/k8s/acs/k8s_secret", "Edas", "openAPI")
	request.Method = requests.DELETE
	return
}

// CreateDeleteK8sSecretResponse creates a response to parse from DeleteK8sSecret response
func CreateDeleteK8sSecretResponse() (response *DeleteK8sSecretResponse) {
	response = &DeleteK8sSecretResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
// Copyright (c) 2020 Uber Technologies, Inc.
//
// 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.

'use strict';

var assert = require('assert');
var Buffer = require('buffer').Buffer;
var process = require('process');
var bufrw = require('bufrw');
var extend = require('xtend');
var ReadMachine = require('bufrw/stream/read_machine');
var inherits = require('util').inherits;

var stat = require('./stat-tags.js');
var EventEmitter = require('./lib/event_emitter');
var v2 = require('./v2');
var errors = require('./errors');
var States = require('./reqres_states');
var Operations = require('./operations');

var CONNECTION_BASE_IDENTIFIER = 0;
var MAX_PENDING_SOCKET_WRITE_REQ = 100;

function TChannelConnection(
    channel, socket, direction, socketRemoteAddr, socketInitTimeout
) {
    assert(!channel.destroyed, 'refuse to create connection for destroyed channel');

    EventEmitter.call(this);
    this.errorEvent = this.defineEvent('error');
    this.timedOutEvent = this.defineEvent('timedOut');
    this.pingResponseEvent = this.defineEvent('pingResonse');

    this.draining = false;
    this.drainReason = '';

    this.closing = false;
    this.closeError = null;
    this.closeEvent = this.defineEvent('close');

    this.channel = channel;
    this.options = this.channel.options;
    this.logger = channel.logger;
    this.random = channel.random;
    this.timers = channel.timers;
    this.direction = direction;
    this.socketInitTimeout = socketInitTimeout || this.channel.initTimeout;
    this.socketRemoteAddr = socketRemoteAddr;
    this.remoteName = null; // filled in by identify message

    this.ops = new Operations({
        timers: this.timers,
        logger: this.logger,
        random: this.random,
        initTimeout: this.socketInitTimeout,
        connectionStalePeriod: this.options.connectionStalePeriod,
        maxTombstoneTTL: this.options.maxTombstoneTTL,
        connection: this
    });

    this.guid = ++CONNECTION_BASE_IDENTIFIER + '~';

    this.tracer = this.channel.tracer;
    this.identifiedEvent = this.defineEvent('identified');

    if (direction === 'out') {
        if (this.channel.emitConnectionMetrics) {
            this.channel.emitFastStat(
                'tchannel.connections.initiated',
                'counter',
                1,
                new stat.ConnectionsInitiatedTags(
                    this.channel.hostPort || '0.0.0.0:0',
                    socketRemoteAddr
                ));
        }
    } else if (this.channel.emitConnectionMetrics) {
        this.channel.emitFastStat(
            'tchannel.connections.accepted',
            'counter',
            1,
            new stat.ConnectionsAcceptedTags(
                this.channel.hostPort,
                socketRemoteAddr
            ));
    }

    this.socket = socket;
    this.ephemeral = false;
    this.initHeaders = null;

    var self = this;
    // TODO: prototype this options shape
    var opts = {
        logger: this.channel.logger,
        random: this.channel.random,
        timers: this.channel.timers,
        hostPort: this.channel.hostPort,
        requireAs: this.channel.requireAs,
        requireCn: this.channel.requireCn,
        tracer: this.tracer,
        processName: this.options.processName,
        connection: this,
        handleCallLazily: handleCallLazily
    };

    this.handler = new v2.Handler(opts);

    this.mach = ReadMachine(bufrw.UInt16BE, v2.Frame.RW);

    this.setupSocket();
    this.setupHandler();
    this.start();

    function handleCallLazily(frame) {
        return self.handleCallLazily(frame);
    }
}
inherits(TChannelConnection, EventEmitter);

TChannelConnection.prototype.extendLogInfo = function extendLogInfo(info) {
    var self = this;

    info = self.channel.extendLogInfo(info);

    info.connGUID = self.guid;
    info.connDirection = self.direction;
    info.socketRemoteAddr = self.socketRemoteAddr;
    info.remoteName = self.remoteName;
    info.connClosing = self.closing;

    return info;
};

TChannelConnection.prototype.drain =
function drain(reason, callback) {
    var self = this;

    self._drain(reason);

    if (callback) {
        if (self.ops.hasDrained()) {
            process.nextTick(callback);
        } else {
            self.ops.drainEvent.on(callback);
        }
    }
};

TChannelConnection.prototype._drain =
function _drain(reason, exempt) {
    var self = this;

    self.draining = true;
    self.drainReason = reason;
    self.ops.draining = true;

    if (self.remoteName) {
        sendDrainingFrame();
    } else {
        self.identifiedEvent.on(sendDrainingFrame);
    }

    function sendDrainingFrame() {
        self.handler.sendErrorFrame(
            v2.Frame.NullId, null,
            'Declined',
            'draining: ' + self.drainReason);
    }
};

// create a request
TChannelConnection.prototype.request =
function connBaseRequest(options) {
    var self = this;

    assert(self.remoteName, 'cannot make request unless identified');
    options.remoteAddr = self.remoteName;

    // TODO: use this to protect against >4Mi outstanding messages edge case
    // (e.g. zombie operation bug, incredible throughput, or simply very long
    // timeout
    // assert(!self.requests.out[id], 'duplicate frame id in flight');

    // options.checksumType = options.checksum;

    var req = self.buildOutRequest(options);
    if (self.draining && (
        !self.channel.drainExempt ||
        !self.channel.drainExempt(req)
    )) {
        req.drained = true;
        req.drainReason = self.drainReason;
    }
    self.ops.addOutReq(req);
    req.peer.invalidateScore('conn.request');
    return req;
};

TChannelConnection.prototype.handleCallRequest = function handleCallRequest(req) {
    var self = this;

    req.remoteAddr = self.remoteName;
    self.ops.addInReq(req);

    if (self.draining && (
        !self.channel.drainExempt ||
        !self.channel.drainExempt(req)
    )) {
        var res = self.buildResponse(req, {});
        res.sendError('Declined', 'connection draining: ' + self.drainReason);
        return;
    }

    process.nextTick(runHandler);

    function runHandler() {
        self.runHandler(req);
    }
};

TChannelConnection.prototype.handleCallLazily = function handleCallLazily(frame) {
    var self = this;
    var op = null;

    switch (frame.type) {
        case v2.Types.CallRequest:
            return self.channel.handler.handleLazily &&
                   self.channel.handler.handleLazily(self, frame);
        case v2.Types.CallResponse:
        case v2.Types.CallResponseCont:
        case v2.Types.ErrorResponse:
            op = self.ops.getOutReq(frame.id);
            break;
        case v2.Types.CallRequestCont:
            op = self.ops.getInReq(frame.id);
            break;
        default:
            return false;
    }

    if (!op || !op.handleFrameLazily) {
        return false;
    }
    op.handleFrameLazily(frame);
    return true;
};

TChannelConnection.prototype.runHandler = function runHandler(req) {
    var self = this;

    self.channel.emitFastStat(
        'tchannel.inbound.calls.recvd',
        'counter',
        1,
        new stat.InboundCallsRecvdTags(
            req.callerName,
            req.serviceName,
            req.endpoint
        )
    );

    self.channel.handler.handleRequest(req, buildResponse);
    function buildResponse(options) {
        return self.buildResponse(req, options || {});
    }
};

TChannelConnection.prototype.buildResponse =
function buildResponse(req, options) {
    var self = this;

    if (req.res && req.res.state !== States.Initial) {
        req.errorEvent.emit(req, errors.ResponseAlreadyStarted({
            state: req.res.state,
            reason: 'buildResponse called twice',
            codeString: req.res.codeString,
            responseMessage: req.res.message
        }));
        return req.res;
    }

    return self._buildResponse(req, options);
};

TChannelConnection.prototype._buildResponse =
function _buildResponse(req, options) {
    var self = this;

    options.channel = self.channel;
    options.inreq = req;

    // TODO give this options a well defined type
    req.res = self.buildOutResponse(req, options);

    req.res.errorEvent.on(onError);
    req.res.finishEvent.on(opDone);

    if (!req.forwardTrace) {
        self.captureResponseSpans(req.res);
    }

    return req.res;

    function opDone() {
        self.onReqDone(req);
    }

    function onError(err) {
        self.onResponseError(err, req);
    }
};

TChannelConnection.prototype.captureResponseSpans =
function captureResponseSpans(res) {
    var self = this;

    res.spanEvent.on(handleSpanFromRes);

    function handleSpanFromRes(span) {
        self.handleSpanFromRes(span);
    }
};

function isStringOrBuffer(x) {
    return typeof x === 'string' || Buffer.isBuffer(x);
}

TChannelConnection.prototype.handleSpanFromRes =
function handleSpanFromRes(span) {
    var self = this;

    self.channel.tracer.report(span);
};

TChannelConnection.prototype.onResponseError =
function onResponseError(err, req) {
    var self = this;

    var reqTimedOut = req.err &&
                      errors.classify(req.err) === 'Timeout';

    // don't log if we get further timeout errors for already timed out response
    if (reqTimedOut && errors.classify(err) === 'Timeout') {
        return;
    }

    var loggingOptions = req.extendLogInfo(req.res.extendLogInfo({
        error: err
    }));

    if (req.res.state === States.Done) {
        var arg2 = isStringOrBuffer(req.res.arg2) ?
            req.res.arg2 : 'streaming';
        var arg3 = isStringOrBuffer(req.res.arg3) ?
            req.res.arg3 : 'streaming';

        loggingOptions.bufArg2 = arg2.slice(0, 50);
        loggingOptions.arg2 = String(arg2).slice(0, 50);
        loggingOptions.bufArg3 = arg3.slice(0, 50);
        loggingOptions.arg3 = String(arg3).slice(0, 50);
    }

    if ((err.type === 'tchannel.response-already-started' ||
        err.type === 'tchannel.response-already-done') &&
        reqTimedOut
    ) {
        self.logger.info(
            'error for timed out outgoing response', loggingOptions
        );
    } else {
        self.logger.error(
            'outgoing response has an error', loggingOptions
        );
    }
};

TChannelConnection.prototype.onReqDone = function onReqDone(req) {
    var self = this;

    var inreq = self.ops.popInReq(req.id);

    if (inreq === req) {
        return;
    }

    // incoming req that timed out are already cleaned up
    if (req.err && errors.classify(req.err) === 'Timeout') {
        return;
    }

    if (inreq) {
        // we popped something else
        self.logger.warn('mismatched conn.onReqDone', self.extendLogInfo(req.extendLogInfo({})));
        return;
    }

    // there was nothing to pop
    if (self.closing) {
        // this happens because TChannelConnection#resetAll calls popInReq on
        // all conn.requests.in, and is okay
        return;
    }

    self.logger.warn('orphaned conn.onReqDone', self.extendLogInfo(req.extendLogInfo({})));
};

TChannelConnection.prototype.setLazyHandling = function setLazyHandling(enabled) {
    var self = this;

    // TODO: push down read machine concern into handler entirely;
    // boundary should just be self.handler.handleChunk in
    // onSocketChunk under setupSocket; then the switching logic
    // moves wholly into a `self.handler.setLazyHandling(bool)`
    if (enabled && self.mach.chunkRW !== v2.LazyFrame.RW) {
        self.mach.chunkRW = v2.LazyFrame.RW;
    } else if (!enabled && self.mach.chunkRW !== v2.Frame.RW) {
        self.mach.chunkRW = v2.Frame.RW;
    }
    self.handler.useLazyFrames(enabled);
};

TChannelConnection.prototype.setupSocket = function setupSocket() {
    var self = this;

    self.socket.setNoDelay(true);
    // TODO: stream the data with backpressure
    // when you add data event listener you go into
    // a deoptimized mode and you have lost all
    // backpressure on the stream
    self.socket.on('data', onSocketChunk);
    self.socket.on('close', onSocketClose);
    self.socket.on('error', onSocketError);

    // TODO: move to method for function optimization
    function onSocketChunk(chunk) {
        var err = self.mach.handleChunk(chunk);
        if (err) {
            self.sendProtocolError('read', err);
        }
    }

    // TODO: move to method for function optimization
    function onSocketClose() {
        self.resetAll(errors.SocketClosedError({
            reason: 'remote closed',
            socketRemoteAddr: self.socketRemoteAddr,
            direction: self.direction,
            remoteName: self.remoteName
        }));

        if (self.ephemeral) {
            var peer = self.channel.peers.get(self.socketRemoteAddr);
            if (peer) {
                peer.close(noop);
            }
            self.channel.peers.delete(self.socketRemoteAddr);
        }
    }

    function onSocketError(err) {
        self.onSocketError(err);
    }
};

function noop() {}

TChannelConnection.prototype.setupHandler = function setupHandler() {
    var self = this;

    self.setLazyHandling(self.channel.options.useLazyHandling);

    self.handler.write = function write(buf) {
        self.writeToSocket(buf);
    };

    self.mach.emit = handleReadFrame;

    self.handler.writeErrorEvent.on(onWriteError);
    self.handler.errorEvent.on(onHandlerError);
    self.handler.errorFrameEvent.on(onErrorFrame);
    self.handler.callIncomingRequestEvent.on(onCallRequest);
    self.handler.callIncomingResponseEvent.on(onCallResponse);
    self.handler.pingIncomingResponseEvent.on(onPingResponse);
    self.handler.callIncomingErrorFrameEvent.on(onCallErrorFrame);

    // TODO: restore dumping from old:
    // var stream = self.socket;
    // if (dumpEnabled) {
    //     stream = stream.pipe(Spy(process.stdout, {
    //         prefix: '>>> ' + self.remoteAddr + ' '
    //     }));
    // }
    // stream = stream
    //     .pipe(self.reader)
    //     .pipe(self.handler)
    //     ;
    // if (dumpEnabled) {
    //     stream = stream.pipe(Spy(process.stdout, {
    //         prefix: '<<< ' + self.remoteAddr + ' '
    //     }));
    // }
    // stream = stream
    //     .pipe(self.socket)
    //     ;

    function onWriteError(err) {
        self.onWriteError(err);
    }

    function onHandlerError(err) {
        self.onHandlerError(err);
    }

    function onErrorFrame(errFrame) {
        self.onErrorFrame(errFrame);
    }

    function handleReadFrame(frame) {
        self.handleReadFrame(frame);
    }

    function onCallRequest(req) {
        self.handleCallRequest(req);
    }

    function onCallResponse(res) {
        self.onCallResponse(res);
    }

    function onPingResponse(res) {
        self.handlePingResponse(res);
    }

    function onCallErrorFrame(errFrame) {
        self.onCallErrorFrame(errFrame);
    }
};

function getSocketBuffer(socket) {
    var writableState = socket._writableState;

    // node >=4 has getBuffer()
    if (typeof writableState.getBuffer === 'function') {
        return writableState.getBuffer();
    } else {
        // Node 0.10 has `.buffer`
        return writableState.buffer;
    }
}

TChannelConnection.prototype.writeToSocket =
function writeToSocket(buf) {
    var self = this;

    var buffer = getSocketBuffer(self.socket);

    if (buffer.length > MAX_PENDING_SOCKET_WRITE_REQ) {
        var error = errors.SocketWriteFullError({
            pendingWrites: buffer.length
        });
        self.logger.warn('resetting connection due to write backup',
            self.extendLogInfo({
                pendingWrites: buffer.length,
                totalFastBufferBytes: self.socket._writableState.length,
                lastBufferLength: buf.length,
                error: error
            })
        );

        // NUKE THE SOCKET
        self.resetAll(error);
        return;
    }

    self.socket.write(buf);
};

TChannelConnection.prototype.sendProtocolError =
function sendProtocolError(type, err) {
    var self = this;

    assert(type === 'write' || type === 'read',
        'Got invalid type: ' + type);

    var protocolError;

    if (type === 'read') {
        protocolError = errors.TChannelReadProtocolError(err, {
            remoteName: self.remoteName,
            localName: self.channel.hostPort,
            frameId: err.frameId
        });

        self.channel.emitFastStat(
            'tchannel.inbound.protocol-errors',
            'counter',
            1,
            new stat.InboundProtocolErrorsTags(self.socketRemoteAddr)
        );

        self.handler.sendErrorFrame(
            protocolError.frameId || v2.Frame.NullId, null,
            'ProtocolError', protocolError.message);

        self.resetAll(protocolError);
    } else if (type === 'write') {
        protocolError = errors.TChannelWriteProtocolError(err, {
            remoteName: self.remoteName,
            localName: self.channel.hostPort,
            frameId: err.frameId
        });

        // TODO: what if you have a write error in a call req cont frame
        self.resetAll(protocolError);
    }
};

TChannelConnection.prototype.onWriteError = function onWriteError(err) {
    var self = this;

    self.sendProtocolError('write', err);
};

TChannelConnection.prototype.onErrorFrame = function onErrorFrame(errFrame) {
    var self = this;

    // TODO: too coupled to v2

    switch (errFrame.body.code) {

    case v2.ErrorResponse.Codes.ProtocolError:
        var CodeErrorType = v2.ErrorResponse.CodeErrors[errFrame.body.code];
        self.resetAll(new CodeErrorType({
            originalId: errFrame.id,
            message: String(errFrame.body.message)
        }));
        return;

    case v2.ErrorResponse.Codes.Declined:
        var match = /^draining:\s*(.+)$/.exec(errFrame.body.message);
        if (match) {
            self.draining = true;
            self.drainReason = 'remote draining: ' + match[1];
            // TODO:
            // - info log?
            // - invaliadet peer score?
            return;
        }
        logUnhandled(v2.ErrorResponse.CodeNames[errFrame.body.code]);
        break;

    case v2.ErrorResponse.Codes.BadRequest:
    case v2.ErrorResponse.Codes.Busy:
    case v2.ErrorResponse.Codes.Cancelled:
    case v2.ErrorResponse.Codes.NetworkError:
    case v2.ErrorResponse.Codes.Timeout:
    case v2.ErrorResponse.Codes.UnexpectedError:
    case v2.ErrorResponse.Codes.Unhealthy:
        logUnhandled(v2.ErrorResponse.CodeNames[errFrame.body.code]);
        return;

    default:
        logUnhandled('unknown');
    }

    function logUnhandled(codeName) {
        self.logger.warn('unhandled error frame', self.extendLogInfo({
            id: errFrame.id,
            errorCode: errFrame.body.code,
            errorCodeName: codeName,
            errorTracing: errFrame.body.tracing,
            errorMessage: errFrame.body.message
        }));
    }
};

TChannelConnection.prototype.onHandlerError = function onHandlerError(err) {
    var self = this;

    if (err.isParseError) {
        self.sendProtocolError('read', err);
        return;
    }

    self.resetAll(err);
};

TChannelConnection.prototype.handlePingResponse = function handlePingResponse(resFrame) {
    var self = this;
    // TODO: explicit type
    self.pingResponseEvent.emit(self, {id: resFrame.id});
};

TChannelConnection.prototype.handleReadFrame = function handleReadFrame(frame) {
    var self = this;

    if (!self.closing) {
        self.ops.resetLastTimeoutTime();
    }

    self.handler.handleFrame(frame);
};

TChannelConnection.prototype.onCallResponse = function onCallResponse(res) {
    var self = this;

    var req = self.ops.getOutReq(res.id);
    if (res.state === States.Done || res.state === States.Error) {
        self.ops.popOutReq(res.id, res);
    } else {
        self._deferPopOutReq(res);
    }

    if (!req) {
        self.logUnknownCallResponse(res);
        return;
    }

    if (self.tracer && !req.forwardTrace) {
        // TODO: better annotations
        req.span.annotate('cr');
        self.tracer.report(req.span);
        res.span = req.span;
    }

    req.emitResponse(res);
};

TChannelConnection.prototype.logUnknownCallResponse =
function logUnknownCallResponse(res) {
    var self = this;

    var logger = self.channel.logger;
    var tombstone = self.ops.getOutTombstone(res.id);
    var info = self.extendLogInfo(res.extendLogInfo({
        responseHeaders: res.headers
    }));

    if (tombstone) {
        info = tombstone.extendLogInfo(info);
        logger.info('got call response for timed out call request', info);
    } else {
        logger.warn('got unexpected call response without call request', info);
    }
};

TChannelConnection.prototype._deferPopOutReq = function _deferPopOutReq(res) {
    var self = this;
    var called = false;

    res.errorEvent.on(popOutReq);
    res.finishEvent.on(popOutReq);

    // TODO: move to method
    function popOutReq() {
        if (called) {
            return;
        }

        called = true;
        self.ops.popOutReq(res.id, res);
    }
};

TChannelConnection.prototype.ping = function ping() {
    var self = this;
    return self.handler.sendPingRequest();
};

TChannelConnection.prototype.onCallErrorFrame =
function onCallErrorFrame(errFrame) {
    var self = this;

    var id = errFrame.id;
    var req = self.ops.getOutReq(id);
    // TODO: req could rarely be a lazy req, then maybe call req.handleFrameLazily

    var CodeErrorType = v2.ErrorResponse.CodeErrors[errFrame.body.code];
    var err = new CodeErrorType({
        originalId: id,
        message: String(errFrame.body.message),
        remoteAddr: self.remoteName
    });

    if (req) {
        if (req.res) {
            req.res.errorEvent.emit(req.res, err);
        } else {
            // Only popOutReq if there is no call response object yet
            req = self.ops.popOutReq(id, err);
            req.emitError(err);
        }
    } else {
        self.logUnknownErrorFrame(err, id);
    }
};

TChannelConnection.prototype.logUnknownErrorFrame =
function logUnknownErrorFrame(err, id) {
    var self = this;

    var logger = self.channel.logger;
    var tombstone = self.ops.getOutTombstone(id);
    var level = errors.logLevel(err, err.codeName);

    // Do not log about incoming timeouts for tombstones
    if (err.codeName === 'Timeout' && tombstone) {
        return;
    }

    var info = self.extendLogInfo({
        error: err,
        isErrorFrame: err.isErrorFrame
    });

    if (level === 'error') {
        logger.error('got unexpected errorframe without call request', info);
    } else if (level === 'warn') {
        logger.warn('got errorframe without call request', info);
    } else if (level === 'info') {
        logger.info('got expected errorframe without call request', info);
    }
};

TChannelConnection.prototype.start = function start() {
    var self = this;
    if (self.direction === 'out') {
        self.handler.sendInitRequest();
        self.handler.initResponseEvent.on(onOutIdentified);
    } else {
        self.handler.initRequestEvent.on(onInIdentified);
    }

    var now = self.timers.now();
    var initOp = new InitOperation(self, now, self.socketInitTimeout);
    var initTo = self.channel.timeHeap.update(initOp, now);

    function onOutIdentified(init) {
        initTo.cancel();
        self.onOutIdentified(init);
    }

    function onInIdentified(init) {
        initTo.cancel();
        self.onInIdentified(init);
    }
};

TChannelConnection.prototype.onOutIdentified = function onOutIdentified(init) {
    var self = this;

    if (init.hostPort === '0.0.0.0:0') {
        return self.emit('error', errors.EphemeralInitResponse({
            hostPort: init.hostPort,
            socketRemoteAddr: self.socketRemoteAddr,
            processName: init.processName
        }));
    }

    self.initHeaders = init;
    self.remoteName = init.hostPort;
    self.identifiedEvent.emit(self, {
        hostPort: init.hostPort,
        processName: init.processName
    });
};

TChannelConnection.prototype.onInIdentified = function onInIdentified(init) {
    var self = this;
    if (init.hostPort === '0.0.0.0:0') {
        self.ephemeral = true;
        self.remoteName = '' + self.socket.remoteAddress + ':' + self.socket.remotePort;
        assert(self.remoteName !== self.channel.hostPort,
              'should not be able to receive ephemeral connection from self');
    } else {
        self.remoteName = init.hostPort;
    }

    self.initHeaders = init;
    self.channel.peers.add(self.remoteName).addConnection(self);
    self.identifiedEvent.emit(self, {
        hostPort: self.remoteName,
        processName: init.processName
    });
};

TChannelConnection.prototype.close = function close(callback) {
    var self = this;
    if (self.socket.destroyed) {
        callback();
    } else {
        self.socket.once('close', callback);
        self.resetAll(errors.LocalSocketCloseError());
    }
};

TChannelConnection.prototype.onSocketError = function onSocketError(err) {
    var self = this;
    if (!self.closing) {
        self.resetAll(errors.SocketError(err, {
            hostPort: self.channel.hostPort,
            direction: self.direction,
            socketRemoteAddr: self.socketRemoteAddr
        }));
    }
};

TChannelConnection.prototype.nextFrameId = function nextFrameId() {
    var self = this;
    return self.handler.nextFrameId();
};

TChannelConnection.prototype.buildOutRequest = function buildOutRequest(options) {
    var self = this;
    var req = self.handler.buildOutRequest(options);
    req.errorEvent.on(onReqError);
    return req;

    function onReqError(err) {
        // The timeout path already popped the error
        if (self.ops.getOutReq(req.id)) {
            self.ops.popOutReq(req.id, err);
        }
    }
};

TChannelConnection.prototype.buildOutResponse = function buildOutResponse(req, options) {
    var self = this;

    options = options || {};
    options.inreq = req;
    options.channel = self.channel;
    options.logger = self.logger;
    options.random = self.random;
    options.timers = self.timers;

    options.tracing = req.tracing;
    options.span = req.span;
    options.checksumType = req.checksum && req.checksum.type;

    // TODO: take over popInReq on req/res error?
    return self.handler.buildOutResponse(req, options);
};

// this connection is completely broken, and is going away
// In addition to erroring out all of the pending work, we reset the state
// in case anybody stumbles across this object in a core dump.
TChannelConnection.prototype.resetAll = function resetAll(err) {
    /*eslint complexity: [2, 20], max-statements: [2, 40]*/
    var self = this;

    self.ops.destroy();

    err = err || errors.TChannelConnectionCloseError();

    if (self.closing) {
        return;
    }

    self.closing = true;
    self.closeError = err;
    self.socket.destroy();

    var requests = self.ops.getRequests();
    var pending = self.ops.getPending();

    var inOpKeys = Object.keys(requests.in);
    var outOpKeys = Object.keys(requests.out);

    if (!err) {
        err = errors.UnknownConnectionReset();
    }

    if (!self.remoteName && self.channel.emitConnectionMetrics) {
        if (self.direction === 'out') {
            self.channel.emitFastStat(
                'tchannel.connections.connect-errors',
                'counter',
                1,
                new stat.ConnectionsConnectErrorsTags(
                    self.channel.hostPort || '0.0.0.0:0',
                    self.socketRemoteAddr
                ));
        } else {
            self.channel.emitFastStat(
                'tchannel.connections.accept-errors',
                'counter',
                1,
                new stat.ConnectionsAcceptErrorsTags(self.channel.hostPort));
        }
    } else if (self.channel.emitConnectionMetrics) {
        if (err.type !== 'tchannel.socket-local-closed') {
            self.channel.emitFastStat(
                'tchannel.connections.errors',
                'counter',
                1,
                new stat.ConnectionsErrorsTags(
                    self.remoteName,
                    err.type // TODO unified error type
                )
            );
        }

        self.channel.emitFastStat(
            'tchannel.connections.closed',
            'counter',
            1,
            new stat.ConnectionsClosedTags(
                self.channel.hostPort || '0.0.0.0:0',
                self.remoteName,
                err.type // TODO unified reason type
            )
        );
    }

    var logInfo = self.extendLogInfo({
        error: err,
        numInOps: inOpKeys.length,
        numOutOps: outOpKeys.length,
        inPending: pending.in,
        outPending: pending.out
    });

    // requests that we've received we can delete, but these reqs may have started their
    //   own outgoing work, which is hard to cancel. By setting this.closing, we make sure
    //   that once they do finish that their callback will swallow the response.
    inOpKeys.forEach(function eachInOp(id) {
        self.ops.popInReq(id);
        // TODO: support canceling pending handlers
        // TODO report or handle or log errors or something
    });

    // for all outgoing requests, forward the triggering error to the user callback
    outOpKeys.forEach(function eachOutOp(id) {
        var req = self.ops.popOutReq(id);
        if (!req) {
            return;
        }
        req.emitError(makeReqError(req));
    });

    function makeReqError(req) {
        var reqErr = err;
        if (reqErr.type === 'tchannel.socket-local-closed') {
            reqErr = errors.TChannelLocalResetError(reqErr);
        } else {
            reqErr = errors.TChannelConnectionResetError(reqErr);
        }
        return req.extendLogInfo(self.extendLogInfo(reqErr));
    }

    self.ops.clear();

    var errorCodeName = errors.classify(err);
    if (errorCodeName !== 'NetworkError' &&
        errorCodeName !== 'ProtocolError'
    ) {
        self.logger.warn('resetting connection', logInfo);
        self.errorEvent.emit(self, err);
    } else if (
        err.type !== 'tchannel.socket-local-closed' &&
        err.type !== 'tchannel.socket-closed'
    ) {
        logInfo.error = extend(err);
        logInfo.error.message = err.message;
        self.logger.info('resetting connection', logInfo);
    }

    self.closeEvent.emit(self, err);
};

function InitOperation(connection, time, timeout) {
    var self = this;

    self.connection = connection;
    self.time = time;
    self.timeout = timeout;
}

InitOperation.prototype.onTimeout = function onTimeout(now) {
    var self = this;

    // noop if identify succeeded
    if (self.connection.remoteName || self.connection.closing) {
        return;
    }

    var elapsed = now - self.time;
    var err = errors.ConnectionTimeoutError({
        start: self.time,
        elapsed: elapsed,
        timeout: self.timeout
    });

    self.connection.logger.warn('destroying due to init timeout', self.connection.extendLogInfo({
        error: err
    }));
    self.connection.resetAll(err);
};

TChannelConnection.prototype.sendLazyErrorFrameForReq =
function sendLazyErrorFrameForReq(reqFrame, codeString, message) {
    var self = this;

    var res = reqFrame.bodyRW.lazy.readTracing(reqFrame);
    var tracing = res.err ? v2.Tracing.emptyTracing : res.value;

    self.sendLazyErrorFrame(reqFrame.id, tracing, codeString, message);

    var now = self.channel.timers.now();
    self._observeInboundErrorFrame(reqFrame, now, codeString);
};

TChannelConnection.prototype._observeInboundErrorFrame =
function _observeInboundErrorFrame(reqFrame, now, codeName) {
    var self = this;

    var serviceName = reqFrame.bodyRW.lazy
        .readServiceStr(reqFrame);
    var callerName = reqFrame.bodyRW.lazy
        .readCallerNameStr(reqFrame);
    var endpoint = reqFrame.bodyRW.lazy
        .readArg1Str(reqFrame);

    if (!callerName || !serviceName || endpoint === null) {
        return;
    }

    self.channel.emitFastStat(
        'tchannel.inbound.calls.latency',
        'timing',
        now - reqFrame.start,
        new stat.InboundCallsLatencyTags(
            callerName,
            serviceName,
            endpoint
        )
    );

    self.channel.emitFastStat(
        'tchannel.inbound.calls.system-errors',
        'counter',
        1,
        new stat.InboundCallsSystemErrorsTags(
            callerName,
            serviceName,
            endpoint,
            codeName
        )
    );
};

TChannelConnection.prototype.sendLazyErrorFrame =
function sendLazyErrorFrame(id, tracing, codeString, message) {
    var self = this;

    self.handler.sendErrorFrame(id, tracing, codeString, message);
};

module.exports = TChannelConnection;


text:
/**
 * Module dependencies.
 */
var util = require('util')
  , OAuth2Strategy = require('passport-oauth2')
  , InternalOAuthError = require('passport-oauth2').InternalOAuthError
  , Profile = require('./profile');

/**
 * Create a new Shopify `Strategy`.
 */
function Strategy(options, verify) {
  options = options || {};

  if (!options.myshopifyDomain) { throw new TypeError('Shopify Strategy requires a myshopifyDomain option'); }

  options.authorizationURL = options.authorizationURL || 'https://' + options.myshopifyDomain + '/admin/oauth/authorize';
  options.tokenURL = options.tokenURL || 'https://' + options.myshopifyDomain + '/admin/oauth/access_token';
  options.scopeSeparator = options.scopeSeparator || ',';
  options.customHeaders = options.customHeaders || {};

  OAuth2Strategy.call(this, options, verify);

  this.name = 'shopify';
  this._userProfileURL = options.userProfileURL || 'https://' + options.myshopifyDomain + '/admin/shop.json';
  this._customHeaders = options.customHeaders;
};

util.inherits(Strategy, OAuth2Strategy);

/**
 *
 */
Strategy.prototype.userProfile = function(accessToken, done) {
  this._customHeaders['X-Shopify-Access-Token'] = accessToken;

  this._oauth2.get(this._userProfileURL, null, function (err, body, res) {
    var json
      , profile;

    if (err) {
      return done(new InternalOAuthError('Failed to fetch shop metadata for user profile', err));
    }

    try {
      json = JSON.parse(body);
      profile = Profile.parse(json);
    } catch (e) {
      return done(e);
    }

    profile._raw = body;
    profile._json = json;

    done(null, profile);
  });
};

module.exports = Strategy;


text:
/**
* Main AngularJS Web Application
*/
var app = angular.module('onboardingWebApp', [ 'ngRoute' ]);

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider

  // Home
    .when("/", {templateUrl: "partials/kingsLanding.html", controller: "PageCtrl"})

  // Pages
    .when("/winterfell", {templateUrl: "partials/winterfell.html", controller: "PageCtrl"})
    .when("/essos", {templateUrl: "partials/essos.html", controller: "PageCtrl"})

  // else 404
    .otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
}]);

/**
 * Controls all Category Pages
 */
app.controller('PageCtrl', function (/* $scope, $location, $http */) {
  console.log("Page Controller reporting for duty.");

  // Activates the Carousel
  $('.carousel').carousel({
    interval: 5000
  });

  // Activates Tooltips for Social Links
  $('.tooltip-social').tooltip({
    selector: "a[data-toggle=tooltip]"
  })
});


text:
<?php
namespace Rails\I18n\Exception;

interface ExceptionInterface
{
}


text:
#include BOSS_WEBRTC_U_modules__video_coding__utility__moving_average_h //original-code:"modules/video_coding/utility/moving_average.h"

#include <algorithm>

namespace webrtc {

MovingAverage::MovingAverage(size_t s) : sum_history_(s + 1, 0) {}
MovingAverage::~MovingAverage() = default;

void MovingAverage::AddSample(int sample) {
  count_++;
  sum_ += sample;
  sum_history_[count_ % sum_history_.size()] = sum_;
}

absl::optional<int> MovingAverage::GetAverage() const {
  return GetAverage(size());
}

absl::optional<int> MovingAverage::GetAverage(size_t num_samples) const {
  if (num_samples > size() || num_samples == 0)
    return absl::nullopt;
  int sum = sum_ - sum_history_[(count_ - num_samples) % sum_history_.size()];
  return sum / static_cast<int>(num_samples);
}

void MovingAverage::Reset() {
  count_ = 0;
  sum_ = 0;
  std::fill(sum_history_.begin(), sum_history_.end(), 0);
}

size_t MovingAverage::size() const {
  return std::min(count_, sum_history_.size() - 1);
}

}  // namespace webrtc


text:
package org.sleuthkit.autopsy.modules.pictureanalyzer.impls;

import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;

import java.nio.file.DirectoryIteratorException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;

import org.apache.commons.io.FilenameUtils;

import org.openide.modules.InstalledFileLocator;
import org.openide.util.lookup.ServiceProvider;

import org.sleuthkit.autopsy.modules.pictureanalyzer.spi.PictureProcessor;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.coreutils.ExecUtil;
import org.sleuthkit.autopsy.coreutils.FileUtil;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.PlatformUtil;
import org.sleuthkit.autopsy.ingest.FileIngestModuleProcessTerminator;
import org.sleuthkit.autopsy.ingest.IngestJobContext;
import org.sleuthkit.autopsy.ingest.IngestServices;
import org.sleuthkit.autopsy.ingest.ModuleContentEvent;

import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.DerivedFile;
import org.sleuthkit.datamodel.ReadContentInputStream;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData;

/**
 * Processes HEIC containers by extracting and converting all internal photos to
 * JPEGs, which are then added as derived files of the container.
 *
 * All of this work is serviced by ImageMagick, a third party executable.
 */
@ServiceProvider(service = PictureProcessor.class)
public class HEICProcessor implements PictureProcessor {

    private static final Logger logger = Logger.getLogger(HEICProcessor.class.getName());

    private static final int EXIT_SUCCESS = 0;
    private static final String HEIC_MODULE_FOLDER = "HEIC";
    private static final long TIMEOUT_IN_SEC = TimeUnit.SECONDS.convert(2, TimeUnit.MINUTES);

    // Windows location
    private static final String IMAGE_MAGICK_FOLDER = "ImageMagick-7.0.10-27-portable-Q16-x64";
    private static final String IMAGE_MAGICK_EXE = "magick.exe";
    private static final String IMAGE_MAGICK_ERROR_FILE = "magick_error.txt";

    // Actual path of ImageMagick on the system
    private final Path IMAGE_MAGICK_PATH;

    public HEICProcessor() {
        IMAGE_MAGICK_PATH = findImageMagick();

        if (IMAGE_MAGICK_PATH == null) {
            logger.log(Level.WARNING, "ImageMagick executable not found. "
                    + "HEIC functionality will be automatically disabled.");
        }
    }

    private Path findImageMagick() {
        final Path windowsLocation = Paths.get(IMAGE_MAGICK_FOLDER, IMAGE_MAGICK_EXE);
        final Path macAndLinuxLocation = Paths.get("/usr", "local", "bin", "magick");

        final String osName = PlatformUtil.getOSName().toLowerCase();

        if (PlatformUtil.isWindowsOS() && PlatformUtil.is64BitJVM()) {
            final File locatedExec = InstalledFileLocator.getDefault().locate(
                windowsLocation.toString(), HEICProcessor.class.getPackage().getName(), false);

            return (locatedExec != null) ? locatedExec.toPath() : null;
        } else if ((osName.equals("linux") || osName.startsWith("mac")) &&
                    Files.isExecutable(macAndLinuxLocation) &&
                    !Files.isDirectory(macAndLinuxLocation)) {
            return macAndLinuxLocation;
        } else {
            return null;
        }
    }

    /**
     * Give each file its own folder in module output. This makes scanning for
     * ImageMagick output fast.
     */
    private Path getModuleOutputFolder(AbstractFile file) throws NoCurrentCaseException {
        final String moduleOutputDirectory = Case.getCurrentCaseThrows().getModuleDirectory();

        return Paths.get(moduleOutputDirectory,
                HEIC_MODULE_FOLDER,
                String.valueOf(file.getId()));
    }

    /**
     * Create any sub directories within the module output folder.
     */
    private void createModuleOutputFolder(AbstractFile file) throws IOException, NoCurrentCaseException {
        final Path moduleOutputFolder = getModuleOutputFolder(file);

        if (!Files.exists(moduleOutputFolder)) {
            Files.createDirectories(moduleOutputFolder);
        }
    }

    @Override
    public void process(IngestJobContext context, AbstractFile file) {
        try {
            if (IMAGE_MAGICK_PATH == null) {
                return;
            }
            createModuleOutputFolder(file);

            if (context.fileIngestIsCancelled()) {
                return;
            }

            final Path localDiskCopy = extractToDisk(file);

            convertToJPEG(context, localDiskCopy, file);
        } catch (IOException ex) {
            logger.log(Level.WARNING, "I/O error encountered during HEIC photo processing.", ex);
        } catch (TskCoreException ex) {
            logger.log(Level.SEVERE, "Unable to add pictures as derived files.", ex);
        } catch (NoCurrentCaseException ex) {
            logger.log(Level.WARNING, "No open case!", ex);
        }
    }

    /**
     * Copies the HEIC container to disk in order to run ImageMagick.
     */
    private Path extractToDisk(AbstractFile heicFile) throws IOException, NoCurrentCaseException {
        final String tempDir = Case.getCurrentCaseThrows().getTempDirectory();
        final String heicFileName = FileUtil.escapeFileName(heicFile.getName());

        final Path localDiskCopy = Paths.get(tempDir, heicFileName);

        try (BufferedInputStream heicInputStream = new BufferedInputStream(new ReadContentInputStream(heicFile))) {
            Files.copy(heicInputStream, localDiskCopy, StandardCopyOption.REPLACE_EXISTING);
            return localDiskCopy;
        }
    }

    private void convertToJPEG(IngestJobContext context, Path localDiskCopy,
            AbstractFile heicFile) throws IOException, TskCoreException, NoCurrentCaseException {

        // First step, run ImageMagick against this heic container.
        final Path moduleOutputFolder = getModuleOutputFolder(heicFile);

        final String baseFileName = FilenameUtils.getBaseName(FileUtil.escapeFileName(heicFile.getName()));
        final Path outputFile = moduleOutputFolder.resolve(baseFileName + ".jpg");

        final Path imageMagickErrorOutput = moduleOutputFolder.resolve(IMAGE_MAGICK_ERROR_FILE);
        Files.deleteIfExists(imageMagickErrorOutput);
        Files.createFile(imageMagickErrorOutput);

        // ImageMagick will write the primary image to the output file.
        // Any additional images found within the HEIC container will be
        // formatted as fileName-1.jpg, fileName-2.jpg, etc.
        final ProcessBuilder processBuilder = new ProcessBuilder()
                .command(IMAGE_MAGICK_PATH.toString(),
                        localDiskCopy.toString(),
                        outputFile.toString());

        processBuilder.redirectError(imageMagickErrorOutput.toFile());

        final int exitStatus = ExecUtil.execute(processBuilder, new FileIngestModuleProcessTerminator(context, TIMEOUT_IN_SEC));

        if (context.fileIngestIsCancelled()) {
            return;
        }

        if (exitStatus != EXIT_SUCCESS) {
            logger.log(Level.INFO, "Non-zero exit status for HEIC file [id: {0}]. Skipping...", heicFile.getId());
            return;
        }

        // Second step, visit all the output files and create derived files.
        // Glob for the pattern mentioned above.
        final String glob = String.format("{%1$s.jpg,%1$s-*.jpg}", baseFileName);
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(moduleOutputFolder, glob)) {

            final Path caseDirectory = Paths.get(Case.getCurrentCaseThrows().getCaseDirectory());
            for (Path candidate : stream) {
                if (context.fileIngestIsCancelled()) {
                    return;
                }

                final BasicFileAttributes attrs = Files.readAttributes(candidate, BasicFileAttributes.class);
                final Path localCasePath = caseDirectory.relativize(candidate);

                final DerivedFile jpegFile = Case.getCurrentCaseThrows().getSleuthkitCase()
                        .addDerivedFile(candidate.getFileName().toString(),
                                localCasePath.toString(), attrs.size(), 0L,
                                attrs.creationTime().to(TimeUnit.SECONDS),
                                attrs.lastAccessTime().to(TimeUnit.SECONDS),
                                attrs.lastModifiedTime().to(TimeUnit.SECONDS),
                                attrs.isRegularFile(), heicFile, "",
                                "", "", "", TskData.EncodingType.NONE);

                context.addFilesToJob(Arrays.asList(jpegFile));
                IngestServices.getInstance().fireModuleContentEvent(new ModuleContentEvent(jpegFile));
            }

        } catch (DirectoryIteratorException ex) {
            throw ex.getCause();
        }
    }

    @Override
    public Set<String> mimeTypes() {
        return new HashSet<String>() {
            {
                add("image/heif");
                add("image/heic");
            }
        };
    }
}