text:
'{{groupName}}' /

'{{clientName}}' /

{{'label.anchor.viewloanaccount' | translate}} /

{{'label.anchor.modifyloanapplication' | translate}}

<form name="editloanaccountform" novalidate="" class="well" rc-submit="submit()">
<api-validate></api-validate>

          {{ 'label.input.product' | translate }}*:

          <select id="productId" ng-model="formData.productId" ng-options="product.id as product.name for product in loanaccountinfo.productOptions" value="{{product.id}}" ng-change="loanProductChange(formData.productId)"/>
              <option style="display:none" value="">{{'label.selectloanproduct' | translate}}</option>
            </select>

          {{ 'label.input.loanofficer' | translate }}:

          <select ng-show="formData.productId" id="loanOfficerId" ng-model="formData.loanOfficerId" ng-options="loanOfficer.id as loanOfficer.displayName for loanOfficer in loanaccountinfo.loanOfficerOptions | orderBy:'displayName':reverse" value="{{loanOfficer.id}}">
            <option value="">{{'label.selectloanofficer' | translate}}</option>
          </select>

        {{ 'label.input.loanpurpose' | translate }}:

          <select id="loanPurposeId" ng-model="formData.loanPurposeId" ng-options="loanPurpose.id as loanPurpose.name for loanPurpose in loanaccountinfo.loanPurposeOptions | orderBy:'name':reverse" value="{{loanPurpose.id}}">
            <option value="">{{'label.selectpurpose' | translate}}</option>
          </select>

        {{ 'label.input.fund' | translate }}:

          <select id="fundId" ng-model="formData.fundId" ng-options="fund.id as fund.name for fund in loanaccountinfo.fundOptions" value="{{fund.id}}">
            <option value="">{{'label.selectfund' | translate}}</option>
          </select>

        {{ 'label.input.submittedon' | translate }}*:

          <input id="submittedOnDate" sort type="text" datepicker-pop="dd MMMM yyyy" ng-model="formData.submittedOnDate" is-open="opened" min="'2000-01-01'" max="restrictDate" />

          {{ 'label.input.disbursementon' | translate }}*:

          <input id="expectedDisbursementDate" type="text" datepicker-pop="dd MMMM yyyy" ng-model="formData.expectedDisbursementDate" is-open="opened1" min="minDate" max="'2020-06-22'" date-disabled="disabled(date, mode)" late-Validate />

       {{ 'label.heading.meetingdetails' | translate }}

          {{ 'label.heading.startdate' | translate }}:
          {{calendar.startDate | DateFormat}}
          {{ 'label.heading.repeatson' | translate }}:
          {{calendar.humanReadable}}

          <input type="checkbox" ng-model="formData.syncRepaymentsWithMeeting" ng-change="syncRepaymentsWithMeetingchange()">
          {{ 'label.input.syncrepaymentswithmeeting' | translate }}
          <input type="checkbox" ng-model="formData.syncDisbursementWithMeeting" ng-change="syncDisbursementWithMeetingchange()">
          {{ 'label.input.syncdisbursementdatewithmeeting' | translate }}

      {{ 'label.heading.terms' | translate }}

          {{ 'label.input.principal' | translate }} *:

            <input type="text" class="input-small" id="principal" name="principal" ng-model="formData.principal" required late-Validate/> {{loanaccountinfo.currency.displaySymbol}}<form-validate valattributeform="editloanaccountform" valattribute="principal"/>

          {{ 'label.input.loanterm' | translate }} *:

            <input id="loanTermFrequency" class="input-mini-small" name="loanterm" type="text" ng-model="formData.loanTermFrequency" required late-Validate/>
            <select id="loanTermFrequencyType" class="input-small" ng-model="formData.loanTermFrequencyType" ng-options="termFrequencyType.id as termFrequencyType.value for termFrequencyType in loanaccountinfo.termFrequencyTypeOptions" value="{{termFrequencyType.id}}"/>
            <form-validate valattributeform="editloanaccountform" valattribute="loanterm"/>

          {{ 'label.input.numofrepayments' | translate }} *

            <input id="numberOfRepayments" class="input-mini-small" name="numofrepayments" type="text" ng-model="formData.numberOfRepayments" required late-Validate/> <form-validate valattributeform="editloanaccountform" valattribute="numofrepayments"/>

          {{ 'label.input.repaidevery' | translate }} *

            <input id="repaymentEvery" class="input-mini-small" type="text" name="repaidevery" ng-model="formData.repaymentEvery" required late-Validate/>
            <select id="repaymentFrequencyType" class="input-small" ng-model="formData.repaymentFrequencyType" ng-options="repaymentFrequencyType.id as repaymentFrequencyType.value for repaymentFrequencyType in loanaccountinfo.termFrequencyTypeOptions" value="{{repaymentFrequencyType.id}}"/> <form-validate valattributeform="editloanaccountform" valattribute="repaidevery"/>

            {{ 'label.input.firstrepaymenton' | translate }}

            <input id="repaymentsStartingFromDate" type="text" datepicker-pop="dd MMMM yyyy" ng-model="formData.repaymentsStartingFromDate" is-open="opened3" min="minDate" max="'2020-06-22'"/>

          {{ 'label.input.interestchargedfrom' | translate }}:

            <input id="interestChargedFromDate" type="text" datepicker-pop="dd MMMM yyyy" ng-model="formData.interestChargedFromDate" is-open="opened2" min="minDate" max="'2020-06-22'"/>

          {{ 'label.input.nominalinterestrate' | translate }} *

            <input id="interestRatePerPeriod" class="input-mini-small" type="text" name="nominalinterestrate" ng-model="formData.interestRatePerPeriod" required late-Validate/>  {{loanaccountinfo.interestRateFrequencyType.value}}

          {{ 'label.input.interestmethod' | translate }}

            <select id="interestType" ng-model="formData.interestType" ng-options="interestType.id as interestType.value for interestType in loanaccountinfo.interestTypeOptions" value="{{interestType.id}}" />

          {{ 'label.input.amortization' | translate }} *:

            <select id="amortizationType" ng-model="formData.amortizationType" ng-options="amortizationType.id as amortizationType.value for amortizationType in loanaccountinfo.amortizationTypeOptions" value="{{amortizationType.id}}" />

          {{ 'label.input.interestcalculationperiod' | translate }} *

            <select id="interestCalculationPeriodType" ng-model="formData.interestCalculationPeriodType" ng-options="interestCalculationPeriodType.id as interestCalculationPeriodType.value for interestCalculationPeriodType in loanaccountinfo.interestCalculationPeriodTypeOptions" value="{{interestCalculationPeriodType.id}}"/>

          {{ 'label.input.arearstolerance' | translate }}

            <input id="inArrearsTolerance" type="text" ng-model="formData.inArrearsTolerance"> {{loanaccountinfo.currency.displaySymbol}}

          {{ 'label.input.interestfreeperiod' | translate }}

            <input id="graceOnInterestCharged" type="text" ng-model="formData.graceOnInterestCharged">

          {{ 'label.input.repaymentstrategy' | translate }} *

            <select id="transactionProcessingStrategyId" ng-model="formData.transactionProcessingStrategyId" ng-options="transactionProcessingStrategy.id as transactionProcessingStrategy.name for transactionProcessingStrategy in loanaccountinfo.transactionProcessingStrategyOptions" value="{{transactionProcessingStrategy.id}}"/>

            {{ 'label.input.grace' | translate }} {{'label.input.onprincipalpayment' | translate}} <input id="graceOnPrincipalPayment" class="input-mini-small" type="text" ng-model="formData.graceOnPrincipalPayment"> {{'label.input.oninterestpayment' | translate}} <input id="graceOnInterestPayment" type="text" class="input-mini-small" ng-model="formData.graceOnInterestPayment">

            {{ 'label.input.linksavings' | translate }}

            <select id="linkAccountId" ng-model="formData.linkAccountId"
                      ng-options="savingaccount.id as savingaccount.productName for savingaccount in loanaccountinfo.accountLinkingOptions"
                      value="{{savingaccount.id}}">
              <option value="">{{'label.menu.selectone' | translate}}</option>
            </select>

          {{ 'label.heading.tranchedetails' | translate }}

              {{ 'label.input.fixedemiamount' | translate }}:

                <input id="fixedEmiAmount" type="text" ng-model="formData.fixedEmiAmount">

              {{'label.input.outstandingloanbalance' | translate}}:

                <input id="maxOutstandingLoanBalance" type="text" ng-model="formData.maxOutstandingLoanBalance">

0">

                {{'label.input.expecteddisbursementon' | translate}}
                {{'label.input.principal' | translate}}

                  <input id="disbursementDetail[{{$index}}].expectedDisbursementDate" type="text" datepicker-pop="dd MMMM yyyy" placeholder="{{'label.input.expecteddisbursementon' | translate}}" ng-model="disbursementDetail.expectedDisbursementDate" is-open="'openedtranche'+$index" min="minDate" max="'2020-06-22'"/>

                  <input id="{{disbursementDetail[$index].principal}}" class="input-small" type="text" ng-model="disbursementDetail.principal"  placeholder="{{'label.input.principal' | translate}}">

        {{ 'label.heading.charges' | translate }}
        <select ng-model="chargeFormData.chargeId" ng-options="charge.id as (charge.name + ',' + charge.currency.displaySymbol) for charge in loanaccountinfo.chargeOptions" value="{{charge.id}}">
           <option value="">{{'label.selectcharge' | translate}}</option>
        </select>

0">

              {{'label.heading.name' | translate}}
              {{'label.heading.type' | translate}}
              {{'label.heading.amount' | translate}}
              {{'label.heading.collectedon' | translate}}
              {{'label.heading.date' | translate}}
              {{'label.heading.actions' | translate}}

            {{charge.name}},{{charge.currency.displaySymbol}}
            {{charge.chargeCalculationType.value}}
            <input id="{{charges[$index].amount}}" class="input-small" type="text" ng-model="charge.amount"  placeholder="{{'label.input.amount' | translate}}">
            {{charge.chargeTimeType.value}}

              <input id="charges[{{$index}}].duedate" type="text" datepicker-pop="dd MMMM yyyy" placeholder="{{'label.input.duedate' | translate}}" ng-model="charge.dueDate" is-open="'openedch'+$index" min="minDate" max="'2020-06-22'"/>

        {{ 'label.heading.collaterals' | translate }}
        <select ng-model="collateralFormData.collateralIdTemplate" ng-options="collateralTemplate.name for collateralTemplate in collateralOptions" value="{{collateralTemplate.id}}">
                      </select>
                      <input class="input-small" type="text" ng-model="collateralFormData.collateralValueTemplate"  placeholder="{{'label.input.value' | translate}}">
                      <input type="text" ng-model="collateralFormData.collateralDescriptionTemplate" placeholder="{{'label.input.description' | translate}}">

0">

                    {{'label.heading.name' | translate}}
                    {{'label.heading.value' | translate}}
                    {{'label.heading.description' | translate}}
                    {{'label.heading.actions' | translate}}

                  <input type="text" class="input-small"  ng-model="collateral.name" readonly>
                  <input id="{{collaterals[$index].value}}" type="text" class="input-small"  ng-model="collateral.value">
                  <input id="{{collaterals[$index].description}}" type="text" ng-model="collateral.description" placeholder="{{'label.input.description' | translate}}">

        {{'label.anchor.repaymentinfo' | translate}}
        {{'label.anchor.backtoloaninfo' | translate}}

            {{'label.heading.loanamountandbalance' | translate}}
            {{'label.heading.totalcostofloan' | translate}}

              #
                {{'label.heading.date' | translate}}
                {{'label.heading.days' | translate}}
                {{'label.heading.disbursement' | translate}}
                {{'label.heading.principaldue' | translate}}
                {{'label.heading.principalbalance' | translate}}
                {{'label.heading.interestdue' | translate}}
                {{'label.heading.fees' | translate}}
                {{'label.heading.due' | translate}}

              {{period.period}}
              {{period.dueDate | DateFormat}}
              {{period.daysInPeriod}}
              {{period.principalDisbursed}}
              {{period.principalDue}}
              {{period.principalLoanBalanceOutstanding}}
              {{period.interestDue}}
              {{period.feeChargesDue}}
              {{period.totalDueForPeriod}}

                {{'label.heading.total' | translate}}
                {{repaymentscheduleinfo.loanTermInDays}}
                {{repaymentscheduleinfo.totalPrincipalDisbursed}}
                {{repaymentscheduleinfo.totalPrincipalExpected}}

                {{repaymentscheduleinfo.totalInterestCharged}}
                {{repaymentscheduleinfo.totalFeeChargesCharged}}
                {{repaymentscheduleinfo.totalRepaymentExpected}}

    <button id="cancel" type="reset" class="btn" ng-click="cancel()">{{'label.button.cancel' | translate}}</button>
    <button id="save" type="submit" class="btn btn-primary" ng-show="loanaccountinfo">{{'label.button.save' | translate}}</button>

</form>


text:
package common;

import java.util.ArrayDeque;
import java.util.Date;
import java.util.Deque;

import common.Util.Deferrable;

/**
 * A general purpose file-operation (or any operation who's progress and completion can be measured by a single number) progress tracker.
 * It can be used to calculate transfer speeds, monitor progress of a file copy etc.
 *
 * the defaults (sample lifetime and sample-clumping interval) are only sensible for file transfers order of 1000mbits/sec.
 * For slower transfers (such as people filling a hall) reduce the parameters accordingly.
 *
 * Samples are clumped together and recorded only every 100ms by default at most.
 * Samples are only kept for 10 seconds at most, implying a maximum of 100 samples.
 *
 * Trackers may also be formed into a hierarchy with progress propagated to a tracker's parent.
 *
 * @author gary
 */
public class ProgressTracker {

	private final class Sample {
		final long value;
		final long at;
		public Sample(long value, long when) {
			this.value = value;
			this.at = when;
		}
	}

	Deque<Sample> samples = new ArrayDeque<Sample>();
	long accumulator = 0; //the sum of all bytes transfered in the samples.

	long position = 0; //the current position in the transfer.
	volatile long expectedMaximum = 0; //the expected end of the file/transfer

	//Sensible defaults?:
	long sampleClumpInterval = 100; //milliseconds to clump samples.
	long maxSampleAge = 10*1000; //number of milliseconds to keep samples.

	ProgressTracker parent;

	public long getMaxSampleAge() {
		return maxSampleAge;
	}

	public void setMaxSampleAge(long maxSampleAge) {
		this.maxSampleAge = maxSampleAge;
	}

	public long getSampleClumpInterval() {
		return sampleClumpInterval;
	}

	/**
	 * ProgressTrackers may have parents that also recieve all the progress that this tracker recieves.
	 * In this way multiple simultanious chunks of a task may be aggregated into the whole task,
	 * likewise many tasks may be aggregated into a group/collection.
	 * @param parent
	 */
	public void setParent(ProgressTracker parent) {
		this.parent = parent;
	}

	public ProgressTracker getParent() {
		return parent;
	}

	/**
	 * Constructs and returns a new progress tracker that is a child of this one.
	 * @return
	 */
	public ProgressTracker getNewChild() {
		return new ProgressTracker(this);
	}

	/**
	 * Construct a progress tracker with no parent.
	 */
	public ProgressTracker() {
		//No-arg constructor is fine.
	}

	/**
	 * Constructs a new progress tracker with the specified parent.
	 * @param parent
	 */
	public ProgressTracker(ProgressTracker parent) {
		this.parent = parent;
	}

	/**
	 * Sets the minimum interval in milliseconds between contributions the samples list.
	 * Calls to progress() or progressTo() more quickly than this interval will be clumped together.
	 * @param sampleClumpInterval
	 */
	public void setSampleClumpInterval(long sampleClumpInterval) {
		this.sampleClumpInterval = sampleClumpInterval;
	}

	/**
	 * notify this tracker that some quantity of thing has occured.
	 *
	 * @param amount the quantity of thing that has progressed.
	 */
	public synchronized void progress(long amount) {
		addSample(amount);
		if (parent!=null) parent.progress(amount);
	}

	/**
	 * Set the position of this task to the value of newPosition, the difference between the current and newPosision will count as progress.
	 * This is equivalent to: progress(newPosition-getPosition());
	 * @param newPosition
	 */
	public synchronized void progressTo(long newPosition) {
		progress(newPosition-position);
	}

	/**
	 * Gets the total amount of progress that has happened since the start
	 * @return
	 */
	public synchronized long getPosition() {
		return position;
	}

	/**
	 * Atomically returns the position of this tracker and zeros the position.
	 * @return
	 */
	public synchronized long getAndZeroPosition() {
		long ret = position;
		position = 0;
		return ret;
	}

	/**
	 * Sets the current absolute position towards completion.
	 * This does not count as task progress, so will not count as speed or change the estimated time to completion.
	 * See progressTo() to change the absolute position and count as speed.
	 * @param pos the new position of the task.
	 * @return
	 */
	public synchronized void setPosition(long pos) {
		this.position = pos;
	}

	/**
	 * Returns a running average number of units of progress occurring per second.
	 *
	 * @return the number of units per second currently occurring.
	 */
	public synchronized double getSpeed() {
		addSample(0); //record that no units were added now, so that if this is polled when no progress is occurring it will decrease over time.

		long dur = getDuration();
		if (dur==0l) {
			return 0;  //speed is meaningless over an interval of zero time.
		} else {
			return (((double)accumulator)/(double)dur)*1000f;
		}
	}

	/**
	 * Gets the estimated time in seconds until the position is at least expectedMaximum.
	 * Returns zero if the position is already>=expectedMaximum
	 *
	 * Returns MAX_VALUE if the speed is zero.
	 *
	 * @return
	 */
	public synchronized long getEstimatedTimeRemaining() {
		if (position>=expectedMaximum) return 0;
		double speed = getSpeed();
		if (speed==0) {
			return Long.MAX_VALUE;
		} else {
			return (long) (((double)(expectedMaximum-position))/(speed)+0.5);
		}
	}

	/**
	 * Gets the estimated time of completion.
	 * @return
	 */
	public synchronized Date getETA() {
		return new Date(getEstimatedTimeRemaining()+System.currentTimeMillis());
	}

	/**
	 * Returns a string describing the time remaining. This very basic!
	 *
	 * @return
	 */
	public synchronized String describeTimeRemaining() {
		return Util.describeInterval(getEstimatedTimeRemaining());

	}

	/**
	 * Returns either the expectedMaximum or the position, whichever is larger.
	 * @return
	 */
	public long getMaximum() {
		return (position>expectedMaximum ? position : expectedMaximum);
	}

	/**
	 * Describes the percent of this progress, or zero if there is no known expected maximum.
	 * This is never more than 100%
	 *
	 * @return
	 */
	public synchronized float percentComplete() {
		if (expectedMaximum==0) return 0;
		return ((float)position/(float)getMaximum())*100;
	}

	/**
	 * Returns a string expressing the percentage this task is complete.
	 * @return
	 */
	public synchronized String percentCompleteString() {
		return Util.oneDecimalPlace(percentComplete())+"%";
	}

	/**
	 * Describes this object as it it were a file transfer, including an ETA if the expected maximum size is known.
	 *
	 * If the expected maximum is known: 55.5MiB of 100MiB, 10m 2s remaining (55.5% at 10MiB/s)
	 * otherwise:						 55.5MiB of unknown at 10MiB/s
	 *
	 */
	public synchronized String describe() {
		if (expectedMaximum==0) {
			return Util.niceSize(position)+" of unknown at "+Util.niceSize((long)(getSpeed()))+"/s";
		} else {
			String ret = Util.niceSize(position)+" of "+Util.niceSize(expectedMaximum)+", "+describeTimeRemaining()+" remaining ("+percentCompleteString()+" at "+Util.niceSize((long)(getSpeed()))+"/s)";
			return ret;
		}
	}

	/**
	 * Set the value that it is expected this progress will finish at.
	 * @param expectedMaximum
	 */
	public void setExpectedMaximum(long expectedMaximum) {
		this.expectedMaximum = expectedMaximum;
	}

	/**
	 * Sets the expectedMaximum of the task that this tracker follows to be larger by 'size' bytes.
	 * @param size
	 */
	public void expandTask(long size) {
		this.expectedMaximum+=size;
	}

	/**
	 * Returns the amount remaining to complete. This is maximum-progress or zero, whichever is larger.
	 * @return
	 */
	public long getRemaining() {
		return Math.max(0, expectedMaximum-position);
	}

	//Helpers:

	//Gets the duration between the oldest and newest sample in milliseconds.
	private long getDuration() {
		if (samples.isEmpty()) {
			return 0;
		} else {
			long ret = samples.getFirst().at - samples.getLast().at;
			return ret;
		}
	}

	private long clumpCount = 0;
	private void addSample(long amount) {
		clumpCount += amount;
		position += amount;
		Util.executeNeverFasterThan(sampleClumpInterval, adder);
	}

	private SampleAdder adder = new SampleAdder();
	private class SampleAdder implements Deferrable {
		@Override
		public void run() {
			long now = System.currentTimeMillis();
			accumulator += clumpCount;
			samples.addFirst(new Sample(clumpCount, now));
			clumpCount = 0;
			dropSamples();
		}

	}

	private void dropSamples() {
		//Remove elements from the samples if:
		//  the oldest is older than the maximum age.
		while (samples.getLast().at+maxSampleAge<System.currentTimeMillis()) {
			Sample s = samples.removeLast();
			accumulator -= s.value;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.mcxiao.ipmsg;

/**
 */
public interface ConnectCreationListener {

    void connectionCreated(AbstractConnection connection);

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using emu_pi2.Data.Objects;

namespace emu_pi2.Data.Services
{
    public class ConsoleRepository : IConsoleRepository
    {
        public IEnumerable<Console> GetAll()
        {
            throw new NotImplementedException();
        }
    }
}


text:
namespace ZendeskXamarinAndroid.Core.Services
{
	public interface IFileSystem
	{
		byte[] ReadAllByteS(string path);
	}
}


text:
namespace gl {

class VertexArray {
 public:
  VertexArray() {
    glGenVertexArrays(1, &handle);
    glBindVertexArray(handle);
  }
  GLuint Handle() const { return handle; }

 private:
  GLuint handle;
};

template <typename T>
class Buffer {
 public:
  explicit Buffer(GLenum t = GL_ARRAY_BUFFER) : type{t} {
    if (va == nullptr) {
      va = new VertexArray{};
    }
    glGenBuffers(1, &handle);
  }
  explicit Buffer(std::vector<T> values, GLenum t = GL_ARRAY_BUFFER)
      : Buffer(t) {
    Write(values);
  }
  Buffer(const Buffer &) = delete;
  ~Buffer() { glDeleteBuffers(1, &handle); }

  size_t Size() const { return size; }
  GLuint Handle() const { return handle; }

  void Write(std::vector<T> vec) {
    Bind();
    size = vec.size();
    glBufferData(type, sizeof(T) * size, vec.data(), GL_STATIC_DRAW);
  }
  void Bind() { glBindBuffer(type, handle); }

 private:
  static thread_local VertexArray *va;
  size_t size = {0};
  GLenum type;
  GLuint handle;
};

template <typename T>
thread_local VertexArray *Buffer<T>::va = nullptr;

}  // namespace gl

template <typename T>
std::ostream &operator<<(std::ostream &os, const gl::Buffer<T> &buf) {
  os << "{";
  for (auto i = 0; i < buf.Size(); i++) {
    os << buf[i];

    if (i + 1 != buf.Size()) {
      os << ", ";
    }
  }
  os << "}";
  return os;
}

#endif  // SRC_RENDERER_RENDERERS_GL_BUFFER_H_


text:
/**
 * @typedef {import('../types.js').Handle} Handle
 * @typedef {import('../types.js').Element} Element
 * @typedef {import('../types.js').MdastNode} MdastNode
 */

import {all} from '../all.js'

/**
 * @type {Handle}
 * @param {Element} node
 */
export function heading(h, node) {
  // `else` shouldn't happen, of course…
  /* c8 ignore next */
  const depth = Number(node.tagName.charAt(1)) || 1
  const wrap = h.wrapText

  h.wrapText = false
  const result = h(node, 'heading', {depth}, all(h, node))
  h.wrapText = wrap

  return result
}


text:
namespace file_system_access_ui_helper {

std::unique_ptr<views::View> CreateOriginLabel(int message_id,
                                               const url::Origin& origin,
                                               int text_context,
                                               bool show_emphasis) {
  std::u16string formatted_origin =
      url_formatter::FormatOriginForSecurityDisplay(
          origin, url_formatter::SchemeDisplay::OMIT_CRYPTOGRAPHIC);
  size_t offset;
  auto label = std::make_unique<views::StyledLabel>();
  label->SetText(
      l10n_util::GetStringFUTF16(message_id, formatted_origin, &offset));
  label->SetTextContext(text_context);
  label->SetDefaultTextStyle(show_emphasis ? views::style::STYLE_SECONDARY
                                           : views::style::STYLE_PRIMARY);
  label->SetHorizontalAlignment(gfx::ALIGN_LEFT);

  if (show_emphasis) {
    views::StyledLabel::RangeStyleInfo origin_style;
    origin_style.text_style = views::style::STYLE_EMPHASIZED_SECONDARY;
    label->AddStyleRange(gfx::Range(offset, offset + formatted_origin.length()),
                         origin_style);
  }
  return label;
}

std::unique_ptr<views::View> CreateOriginPathLabel(int message_id,
                                                   const url::Origin& origin,
                                                   const base::FilePath& path,
                                                   int text_context,
                                                   bool show_emphasis) {
  std::u16string formatted_origin =
      url_formatter::FormatOriginForSecurityDisplay(
          origin, url_formatter::SchemeDisplay::OMIT_CRYPTOGRAPHIC);
  std::u16string formatted_path = GetPathForDisplay(path);
  std::vector<size_t> offsets;
  auto label = std::make_unique<views::StyledLabel>();
  label->SetText(l10n_util::GetStringFUTF16(message_id, formatted_origin,
                                            formatted_path, &offsets));
  DCHECK_GE(offsets.size(), 2u);

  label->SetTextContext(text_context);
  label->SetDefaultTextStyle(show_emphasis ? views::style::STYLE_SECONDARY
                                           : views::style::STYLE_PRIMARY);
  label->SetHorizontalAlignment(gfx::ALIGN_LEFT);

  if (show_emphasis) {
    views::StyledLabel::RangeStyleInfo origin_style;
    origin_style.text_style = views::style::STYLE_EMPHASIZED_SECONDARY;
    // All but the last offset should be the origin.
    for (size_t i = 0; i < offsets.size() - 1; ++i) {
      label->AddStyleRange(
          gfx::Range(offsets[i], offsets[i] + formatted_origin.length()),
          origin_style);
    }
  }

  views::StyledLabel::RangeStyleInfo path_style;
  if (show_emphasis)
    path_style.text_style = views::style::STYLE_EMPHASIZED_SECONDARY;
  path_style.tooltip = path.LossyDisplayName();
  label->AddStyleRange(
      gfx::Range(offsets.back(), offsets.back() + formatted_path.length()),
      path_style);

  return label;
}

std::u16string GetPathForDisplay(const base::FilePath& path) {
  // Display the drive letter if the path is the root of the filesystem.
  auto dir_name = path.DirName();
  if (!path.empty() && (dir_name.empty() || path == dir_name))
    return path.LossyDisplayName();

  return path.BaseName().LossyDisplayName();
}

}  // namespace file_system_access_ui_helper


text:
/**
* @module Canvas
*/

var dependencies = [
	'helpers/RGB',
	'helpers/Canvas',
	'helpers/EventManager',
	'scenes/SceneManager'
];

define(dependencies, function(RGB, Canvas, EventManager, SceneManager){

	var canvas = new Canvas();
	var EventManager = new EventManager();
	var sceneManager = new SceneManager(canvas);

	var Game = function(){

	};

	Game.prototype.init = function(){

		canvas.resize();
		this.startupEvents();

		requestAnimationFrame(this.update);

	};

	Game.prototype.update = function(){

		//TODO: fix this...it is weird
		var updateClosure = function(){
			sceneManager.updateCurrentScene();
			requestAnimationFrame(updateClosure);
		};

		requestAnimationFrame(updateClosure);
	};

	Game.prototype.startupEvents = function(){

		EventManager.createEvent('WindowResizeEvent', 'resize', window, canvas.resize);
		EventManager.createEvent('ControllerInputEvent', 'keydown', window, sceneManager.getCurrentScene().userInput);

	};

	return Game;

});


text:
define(
	[
		'./request-anim-frame'
	],
	function(
		frame
	){

		var API
			,lastTime = 0
			,active = false
			,listeners = []
			;

		function each( arr, fn ){

			for(var i = 0, l = arr.length; i < l; ++i){

				if ( fn( arr[i], i ) === false ){

					return false;
				}

			}

			return true;
		}

		function step( time ){

			if (!active){
				return;
			}

			frame.requestAnimationFrame( step );

			each( listeners, function( l ){

				l( time, time - lastTime );
			});

			lastTime = time;
		}

		function start(){

			lastTime = new Date().getTime();
			active = true;
			step();

			return API;
		}

		function stop(){

			active = false;

			return API;
		}

		function subscribe( listener ){

			function cb( l ){

				if ( l === listener )
					return false;
			}

			// if function and not already in listeners...
			if ( typeof listener === 'function' && each( listeners, cb ) ){

				// add it
				listeners.push( listener );

			}

			return API;

		}

		function unsubscribe( listener ){

			each( listeners, function( l, i ){

				if ( l === listener ){

					// remove it
					listeners.splice( i, 1 );
					return false;

				}

			});

			return API;
		}

		function isActive(){

			return !!active;
		}

		// API
		return API = {
			start: start,
			stop: stop,
			subscribe: subscribe,
			unsubscribe: unsubscribe,
			isActive: isActive
		};
	}
);


text:
package gov.va.cpe.feed.atom.xml;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import gov.va.hmp.feed.atom.Content;

import javax.xml.bind.annotation.XmlRootElement;

/**
 * Created with IntelliJ IDEA. User: sblaz Date: 7/12/13 Time: 12:17 PM To change this template use File | Settings |
 * File Templates.
 */
@JacksonXmlRootElement(localName = "baz")
@XmlRootElement(name = "baz")
public class Baz {
    public Content getContent() {
        return content;
    }

    public void setContent(Content content) {
        this.content = content;
    }

    private Content content;
}


text:
package bin

import (
	"io"

	mc "gx/ipfs/QmP6H1kAKEHohE2U4GE4PiiRtXp37L5Bxfwi4EvxV7Jn5K/go-multicodec"
	base "gx/ipfs/QmP6H1kAKEHohE2U4GE4PiiRtXp37L5Bxfwi4EvxV7Jn5K/go-multicodec/base"
)

var (
	HeaderPath = "/bin/"
	Header     = mc.Header([]byte(HeaderPath))
	multic     = mc.NewMulticodecFromCodec(Codec(), Header)
)

type codec struct{}

func (codec) Header() []byte {
	return Header
}

type decoder struct {
	r io.Reader
}

func (d decoder) Decode(v interface{}) error {
	slice, ok := v.([]byte)
	if !ok {
		return base.ErrExpectedByteSlice
	}

	_, err := d.r.Read(slice)
	return err
}

func (codec) Decoder(r io.Reader) mc.Decoder {
	return decoder{r}
}

type encoder struct {
	w io.Writer
}

func (e encoder) Encode(v interface{}) error {
	slice, ok := v.([]byte)
	if !ok {
		return base.ErrExpectedByteSlice
	}

	_, err := e.w.Write(slice)
	return err
}

func (codec) Encoder(w io.Writer) mc.Encoder {
	return encoder{w}
}

func Codec() mc.Codec {
	return codec{}
}

func Multicodec() mc.Multicodec {
	return multic
}


text:
<?php

namespace Symfony\Component\Lock\Tests\Store;

use Symfony\Component\Lock\Key;
use Symfony\Component\Lock\PersistingStoreInterface;
use Symfony\Component\Lock\Store\StoreFactory;
use Symfony\Component\Lock\Store\ZookeeperStore;

/**
 * @author Ganesh Chandrasekaran <gchandrasekaran@wayfair.com>
 *
 * @requires extension zookeeper
 * @group integration
 */
class ZookeeperStoreTest extends AbstractStoreTest
{
    use UnserializableTestTrait;

    /**
     * @return ZookeeperStore
     */
    public function getStore(): PersistingStoreInterface
    {
        $zookeeper_server = getenv('ZOOKEEPER_HOST').':2181';

        $zookeeper = new \Zookeeper($zookeeper_server);

        return StoreFactory::createStore($zookeeper);
    }

    /**
     * @dataProvider provideValidConnectionString
     */
    public function testCreateConnection(string $connectionString)
    {
        $this->assertInstanceOf(\Zookeeper::class, ZookeeperStore::createConnection($connectionString));
    }

    public function provideValidConnectionString(): iterable
    {
        yield 'single host' => ['zookeeper://localhost:2181'];
        yield 'single multiple host' => ['zookeeper://localhost:2181,localhost:2181'];
        yield 'with extra attributes' => ['zookeeper://localhost:2181/path?option=value'];
    }

    public function testSaveSucceedsWhenPathContainsMoreThanOneNode()
    {
        $store = $this->getStore();
        $resource = '/baseNode/lockNode';
        $key = new Key($resource);

        $store->save($key);
        $this->assertTrue($store->exists($key));

        $store->delete($key);
        $this->assertFalse($store->exists($key));
    }

    public function testSaveSucceedsWhenPathContainsOneNode()
    {
        $store = $this->getStore();
        $resource = '/baseNode';
        $key = new Key($resource);

        $store->save($key);
        $this->assertTrue($store->exists($key));

        $store->delete($key);
        $this->assertFalse($store->exists($key));
    }

    public function testSaveSucceedsWhenPathsContainSameFirstNode()
    {
        $store = $this->getStore();
        $resource = 'foo/bar';
        $key = new Key($resource);

        $store->save($key);
        $this->assertTrue($store->exists($key));

        $resource2 = 'foo';
        $key2 = new Key($resource2);

        $this->assertFalse($store->exists($key2));
        $store->save($key2);
        $this->assertTrue($store->exists($key2));

        $store->delete($key2);
        $this->assertFalse($store->exists($key2));

        $store->delete($key);
        $this->assertFalse($store->exists($key));
    }

    public function testRootPathIsLockable()
    {
        $store = $this->getStore();
        $resource = '/';
        $key = new Key($resource);

        $store->save($key);
        $this->assertTrue($store->exists($key));

        $store->delete($key);
        $this->assertFalse($store->exists($key));
    }

    public function testEmptyStringIsLockable()
    {
        $store = $this->getStore();
        $resource = '';
        $key = new Key($resource);

        $store->save($key);
        $this->assertTrue($store->exists($key));

        $store->delete($key);
        $this->assertFalse($store->exists($key));
    }
}


text:
  Damerey est
       un village
       situé dans le département de Saône-et-Loire en Bourgogne. Elle totalisait 526 habitants en 2008.

À Damerey, le prix moyen à l'achat d'un appartement se situe à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 347 € du m². À la location le prix moyen se situe à 0 € du m² par mois.

Si vous pensez emmenager à Damerey, vous pourrez aisément trouver une maison à vendre.

À proximité de Damerey sont positionnées géographiquement les villes de
Ciel localisée à 6 km, 662 habitants,
Saint-Martin-en-Bresse située à 5 km, 1 826 habitants,
Saint-Maurice-en-Rivière à 1 km, 527 habitants,
Sassenay à 5 km, 1 476 habitants,
Bey à 2 km, 749 habitants,
Montcoy localisée à 3 km, 268 habitants,
 entre autres. De plus, Damerey est située à seulement onze km de Chalon-sur-Saône.

Le nombre d'habitations, à Damerey, était réparti en 2011 en neuf appartements et 243 maisons soit
 un marché relativement équilibré.

La commune propose quelques  aménagements, elle propose entre autres un terrain de sport.


text:
<?php

namespace Liuggio\Concurrent\Process;

use Liuggio\Concurrent\CommandLine;
use Liuggio\Concurrent\Process\Channel\Channel;
use Symfony\Component\Process\PhpProcess;

class ClosureProcess extends PhpProcess
{
    /** @var ProcessEnvironment */
    private $processEnvironment;

    public function __construct(
        CommandLine $script,
        ProcessEnvironment $processEnvironment,
        $timeout = null,
        $cwd = null
    ) {
        $this->processEnvironment = $processEnvironment;
        parent::__construct((string) $script, null, $this->processEnvironment->exportToEnvsArray());
        if (!$timeout) {
            $this->setTimeout($timeout);
            // compatibility to SF 2.2
            if (method_exists($this, 'setIdleTimeout')) {
                $this->setIdleTimeout($timeout);
            }
        }
    }

    /**
     * @return mixed
     */
    public function getInputLine()
    {
        return $this->processEnvironment->getArguments();
    }

    /**
     * Waits for the process to terminate.
     *
     * The callback receives the type of output (out or err) and some bytes
     * from the output in real-time while writing the standard input to the process.
     * It allows to have feedback from the independent process during execution.
     *
     * @param callable|null $callback A valid PHP callback
     *
     * @return int The returnValue of the Closure
     *
     * @throws RuntimeException When process timed out
     * @throws RuntimeException When process stopped after receiving signal
     * @throws LogicException   When process is not yet started
     */
    public function wait($callback = null)
    {
        parent::wait($callback);

        return $this->getReturnValue();
    }

    /**
     * @return CommandLine
     */
    public function getCommandLine()
    {
        return new CommandLine(parent::getCommandLine());
    }

    /**
     * The current Id of the processes.
     *
     * @return int
     */
    public function getIncrementalNumber()
    {
        return $this->processEnvironment->getIncrementalNumber();
    }

    /**
     * The channel where the processes is executed.
     *
     * @return Channel
     */
    public function getChannel()
    {
        return $this->processEnvironment->getChannel();
    }

    /**
     * The output of the callable.
     *
     * @return string
     */
    public function getOutput()
    {
        $value = ClosureReturnValue::unserialize(parent::getOutput());

        return $value->getOutput();
    }

    /**
     * The return value of the callable.
     *
     * @return mixed
     */
    public function getReturnValue()
    {
        $value = ClosureReturnValue::unserialize(parent::getOutput());

        return $value->getReturnValue();
    }
}


text:
from tvtk.tools import tvtk_doc
tvtk_doc.main()


text:
$(document).ready(function(){
    $(function() {
		var cache = {},
			lastXhr;
		$( "#player_search" ).autocomplete({
			minLength: 1,
			source: function( request, response ) {
				var term = request.term;
				if ( term in cache ) {
					response( cache[ term ] );
					return;
				}

				lastXhr = $.getJSON( "/player_search/", request, function( data, status, xhr ) {
					cache[ term ] = data;
					if ( xhr === lastXhr ) {
						response( data );
					}
				});
			},
                        select: function(event, ui){
                            $("#player_search_id").val(ui.item.id);
                        }
		});
	});
});


text:
using System.Collections.Generic;
using System.Linq;
using SugarRest.Extensions;

namespace SugarRest
{
    public class SugarList
    {
        /// <summary>
        /// Represents SugarCRM dropdown list key (system key) value (display label)
        /// </summary>
        protected Dictionary<string, string> list;

        /// <summary>
        /// Create new SugarList
        /// </summary>
        /// <param name="list">Key Value dropdown list dictionary</param>
        public SugarList(Dictionary<string, string> list)
        {
            this.list = list;
        }

        /// <summary>
        /// Retrieve list of system keys for a Sugar dropdown list
        /// </summary>
        /// <returns>Array of system keys</returns>
        public List<string> GetSystemKeys()
        {
            return list.Keys.ToList();
        }

        /// <summary>
        /// Retrieve list of display values for a dropdown
        /// </summary>
        /// <returns></returns>
        public List<string> GetDisplayValues()
        {
            return list.Values.ToList();
        }

        /// <summary>
        /// Check if a value is valid list option
        /// </summary>
        /// <param name="value">String</param>
        /// <returns>bool</returns>
        public bool KeyExists(string value)
        {
            return list.ContainsKey(value);
        }

        /// <summary>
        /// Create a SugarCRM formatted multi-select string
        /// </summary>
        /// <param name="values">List of Values</param>
        /// <returns>Formatted String</returns>
        public static string CreateMultiSelect(IList<string> values)
        {
            return values.ToSugarMultiSelect();
        }

    }
}


text:
import React from 'react'
import ReactDom from 'react-dom'
import testUtils from 'react/lib/ReactTestUtils'
import Footer from '../../../../src/js/components/frame/footer'
var expect = require('expect');
var findDOMNode = ReactDom.findDOMNode;

describe('Footer functional component', function () {
    it('has child elements', function () {
        // for stateless components, ReactDOM.render and TestUtils.renderIntoDocument will return null.
        var wrappedComp = testUtils.renderIntoDocument(

);
        var comp = findDOMNode(wrappedComp).children[0];
        expect(comp).toExist();
        expect(comp.childNodes.length).toEqual(3);
    });
});


text:
package untouchedwagons.minecraft.plasmacraft.blocks;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;

import untouchedwagons.minecraft.plasmacraft.PlasmaCraft;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public class BlockAcidBarrier extends Block
{
	public BlockAcidBarrier()
	{
		super(Material.glass);
		setHardness(3F);
		setResistance(5F);
		setLightOpacity(2);
		setLightLevel(1.0F);
		setStepSound(Block.soundTypeGlass);
		setCreativeTab(PlasmaCraft.plasmaTab);
	}

	@Override
	public int getRenderBlockPass()
	{
		return 1;
	}

	@Override
	public boolean isOpaqueCube()
	{
		return false;
	}

	@Override
	public void onEntityWalking(World world, int x, int y, int z, Entity entity)
	{
		entity.attackEntityFrom(DamageSource.magic, 2);
	}

	@Override
	public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity)
	{
		entity.attackEntityFrom(DamageSource.magic, 2);
	}

	@Override
	public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z)
	{
		float shrinkAmount = 0.125F;
		return AxisAlignedBB.getBoundingBox(x + shrinkAmount, y + shrinkAmount, z + shrinkAmount,
				x + 1 - shrinkAmount, y + 1 - shrinkAmount, z + 1 - shrinkAmount);
	}

	@Override
	@SideOnly(Side.CLIENT)
	public void registerBlockIcons(IIconRegister par1IconRegister)
	{
		this.blockIcon = par1IconRegister.registerIcon(PlasmaCraft.MOD_ID + ":acidBarrier");
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--L
  Copyright Oracle Inc

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details.
L-->

<cgMDR:Data_Element xmlns:cgMDR="http://www.cancergrid.org/schema/cgMDR" item_registration_authority_identifier="US-NCICB-CACORE" data_identifier="2183617" version="1">
    <cgMDR:administered_item_administration_record>
        <cgMDR:administrative_status>noPendingChanges</cgMDR:administrative_status>
        <cgMDR:creation_date>2007-04-17</cgMDR:creation_date>
        <cgMDR:effective_date>2007-04-17</cgMDR:effective_date>
        <cgMDR:explanatory_comment>Transformed from NCICB caDSR</cgMDR:explanatory_comment>
        <cgMDR:last_change_date>2007-04-17</cgMDR:last_change_date>
        <cgMDR:registration_status>Qualified</cgMDR:registration_status>
    </cgMDR:administered_item_administration_record>
    <cgMDR:administered_by>US-NCICB-CCR-STEWARD</cgMDR:administered_by>
    <cgMDR:classified_by>http://www.cancergrid.org/ontologies/data-element-classification#US-NCICB-CACORE-D1E57229-1</cgMDR:classified_by>
    <cgMDR:registered_by>US-NCICB-CACORE-REGISTRAR</cgMDR:registered_by>
    <cgMDR:submitted_by>US-NCICB-CCR-SUMBMITTER</cgMDR:submitted_by>
    <cgMDR:described_by>US-NCICB-CACORE-D1E57184-1</cgMDR:described_by>
    <cgMDR:having>
        <cgMDR:context_identifier>US-NCICB-CCR-1</cgMDR:context_identifier>
        <cgMDR:containing>
            <cgMDR:language_section_language_identifier>
                <cgMDR:country_identifier>US</cgMDR:country_identifier>
                <cgMDR:language_identifier>eng</cgMDR:language_identifier>
            </cgMDR:language_section_language_identifier>
            <cgMDR:name>Common Toxicity Criteria Version Number</cgMDR:name>
            <cgMDR:definition_text>Version of the Common Toxicity Criteria as referenced by the protocol.</cgMDR:definition_text>
            <cgMDR:preferred_designation>true</cgMDR:preferred_designation>
            <cgMDR:definition_source_reference/>
        </cgMDR:containing>
        <cgMDR:containing>
            <cgMDR:language_section_language_identifier>
                <cgMDR:country_identifier>US</cgMDR:country_identifier>
                <cgMDR:language_identifier>eng</cgMDR:language_identifier>
            </cgMDR:language_section_language_identifier>
            <cgMDR:name>CTC_VER_NUM</cgMDR:name>
            <cgMDR:definition_text/>
            <cgMDR:preferred_designation>false</cgMDR:preferred_designation>
            <cgMDR:definition_source_reference/>
        </cgMDR:containing>
        <cgMDR:containing>
            <cgMDR:language_section_language_identifier>
                <cgMDR:country_identifier>US</cgMDR:country_identifier>
                <cgMDR:language_identifier>eng</cgMDR:language_identifier>
            </cgMDR:language_section_language_identifier>
            <cgMDR:name>ENGLISH</cgMDR:name>
            <cgMDR:definition_text>CONTEXT NAME</cgMDR:definition_text>
            <cgMDR:preferred_designation>false</cgMDR:preferred_designation>
            <cgMDR:definition_source_reference/>
        </cgMDR:containing>
    </cgMDR:having>
    <cgMDR:data_element_precision>0</cgMDR:data_element_precision>
    <cgMDR:representation_class_qualifier/>
    <cgMDR:representing>US-NCICB-CACORE-2183615-1</cgMDR:representing>
    <cgMDR:typed_by>GB-CANCERGRID-000019-1</cgMDR:typed_by>
    <cgMDR:expressing>US-NCICB-CACORE-2183614-1</cgMDR:expressing>
    <cgMDR:field_name preferred=""/>
    <cgMDR:question_text preferred=""/>
</cgMDR:Data_Element>


text:
package org.apache.cassandra.schema;

import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Future;

import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Futures;
import org.junit.Assert;
import org.junit.Test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.Mutation;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.utils.concurrent.WaitQueue;

import static com.google.common.util.concurrent.Futures.getUnchecked;

public class MigrationCoordinatorTest
{
    private static final Logger logger = LoggerFactory.getLogger(MigrationCoordinatorTest.class);

    private static final InetAddressAndPort EP1;
    private static final InetAddressAndPort EP2;
    private static final InetAddressAndPort EP3;

    private static final UUID LOCAL_VERSION = UUID.randomUUID();
    private static final UUID V1 = UUID.randomUUID();
    private static final UUID V2 = UUID.randomUUID();
    private static final UUID V3 = UUID.randomUUID();

    static
    {
        try
        {
            EP1 = InetAddressAndPort.getByName("10.0.0.1");
            EP2 = InetAddressAndPort.getByName("10.0.0.2");
            EP3 = InetAddressAndPort.getByName("10.0.0.3");
        }
        catch (UnknownHostException e)
        {
            throw new AssertionError(e);
        }

        DatabaseDescriptor.daemonInitialization();
    }

    private static class InstrumentedCoordinator extends MigrationCoordinator
    {

        Queue<Callback> requests = new LinkedList<>();
        @Override
        protected void sendMigrationMessage(MigrationCoordinator.Callback callback)
        {
            requests.add(callback);
        }

        boolean shouldPullSchema = true;
        @Override
        protected boolean shouldPullSchema(UUID version)
        {
            return shouldPullSchema;
        }

        boolean shouldPullFromEndpoint = true;
        @Override
        protected boolean shouldPullFromEndpoint(InetAddressAndPort endpoint)
        {
            return shouldPullFromEndpoint;
        }

        boolean shouldPullImmediately = true;
        @Override
        protected boolean shouldPullImmediately(InetAddressAndPort endpoint, UUID version)
        {
            return shouldPullImmediately;
        }

        Set<InetAddressAndPort> deadNodes = new HashSet<>();
        protected boolean isAlive(InetAddressAndPort endpoint)
        {
            return !deadNodes.contains(endpoint);
        }

        UUID localVersion = LOCAL_VERSION;
        @Override
        protected boolean isLocalVersion(UUID version)
        {
            return localVersion.equals(version);
        }

        int maxOutstandingRequests = 3;
        @Override
        protected int getMaxOutstandingVersionRequests()
        {
            return maxOutstandingRequests;
        }

        Set<InetAddressAndPort> mergedSchemasFrom = new HashSet<>();
        @Override
        protected void mergeSchemaFrom(InetAddressAndPort endpoint, Collection<Mutation> mutations)
        {
            mergedSchemasFrom.add(endpoint);
        }
    }

    @Test
    public void requestResponseCycle() throws InterruptedException
    {
        InstrumentedCoordinator coordinator = new InstrumentedCoordinator();
        coordinator.maxOutstandingRequests = 1;

        Assert.assertTrue(coordinator.requests.isEmpty());

        // first schema report should send a migration request
        getUnchecked(coordinator.reportEndpointVersion(EP1, V1));
        Assert.assertEquals(1, coordinator.requests.size());
        Assert.assertFalse(coordinator.awaitSchemaRequests(1));

        // second should not
        getUnchecked(coordinator.reportEndpointVersion(EP2, V1));
        Assert.assertEquals(1, coordinator.requests.size());
        Assert.assertFalse(coordinator.awaitSchemaRequests(1));

        // until the first request fails, then the second endpoint should be contacted
        MigrationCoordinator.Callback request1 = coordinator.requests.poll();
        Assert.assertEquals(EP1, request1.endpoint);
        getUnchecked(request1.fail());
        Assert.assertTrue(coordinator.mergedSchemasFrom.isEmpty());
        Assert.assertFalse(coordinator.awaitSchemaRequests(1));

        // ... then the second endpoint should be contacted
        Assert.assertEquals(1, coordinator.requests.size());
        MigrationCoordinator.Callback request2 = coordinator.requests.poll();
        Assert.assertEquals(EP2, request2.endpoint);
        Assert.assertFalse(coordinator.awaitSchemaRequests(1));
        getUnchecked(request2.response(Collections.emptyList()));
        Assert.assertEquals(EP2, Iterables.getOnlyElement(coordinator.mergedSchemasFrom));
        Assert.assertTrue(coordinator.awaitSchemaRequests(1));

        // and migration tasks should not be sent out for subsequent version reports
        getUnchecked(coordinator.reportEndpointVersion(EP3, V1));
        Assert.assertTrue(coordinator.requests.isEmpty());

    }

    /**
     * If we don't send a request for a version, and endpoints associated with
     * it all change versions, we should signal anyone waiting on that version
     */
    @Test
    public void versionsAreSignaledWhenDeleted()
    {
        InstrumentedCoordinator coordinator = new InstrumentedCoordinator();

        coordinator.reportEndpointVersion(EP1, V1);
        WaitQueue.Signal signal = coordinator.getVersionInfoUnsafe(V1).register();
        Assert.assertFalse(signal.isSignalled());

        coordinator.reportEndpointVersion(EP1, V2);
        Assert.assertNull(coordinator.getVersionInfoUnsafe(V1));

        Assert.assertTrue(signal.isSignalled());
    }

    private static void assertNoContact(InstrumentedCoordinator coordinator, InetAddressAndPort endpoint, UUID version, boolean startupShouldBeUnblocked)
    {
        Assert.assertTrue(coordinator.requests.isEmpty());
        Future<Void> future = coordinator.reportEndpointVersion(EP1, V1);
        if (future != null)
            getUnchecked(future);
        Assert.assertTrue(coordinator.requests.isEmpty());

        Assert.assertEquals(startupShouldBeUnblocked, coordinator.awaitSchemaRequests(1));
    }

    private static void assertNoContact(InstrumentedCoordinator coordinator, boolean startupShouldBeUnblocked)
    {
        assertNoContact(coordinator, EP1, V1, startupShouldBeUnblocked);
    }

    @Test
    public void dontContactNodesWithSameSchema()
    {
        InstrumentedCoordinator coordinator = new InstrumentedCoordinator();

        coordinator.localVersion = V1;
        assertNoContact(coordinator, true);
    }

    @Test
    public void dontContactIncompatibleNodes()
    {
        InstrumentedCoordinator coordinator = new InstrumentedCoordinator();

        coordinator.shouldPullFromEndpoint = false;
        assertNoContact(coordinator, false);
    }

    @Test
    public void dontContactDeadNodes()
    {
        InstrumentedCoordinator coordinator = new InstrumentedCoordinator();

        coordinator.deadNodes.add(EP1);
        assertNoContact(coordinator, EP1, V1, false);
    }

    /**
     * If a node has become incompativle between when the task was scheduled and when it
     * was run, we should detect that and fail the task
     */
    @Test
    public void testGossipRace()
    {
        InstrumentedCoordinator coordinator = new InstrumentedCoordinator() {
            protected boolean shouldPullImmediately(InetAddressAndPort endpoint, UUID version)
            {
                // this is the last thing that gets called before scheduling the pull, so set this flag here
                shouldPullFromEndpoint = false;
                return super.shouldPullImmediately(endpoint, version);
            }
        };

        Assert.assertTrue(coordinator.shouldPullFromEndpoint(EP1));
        assertNoContact(coordinator, EP1, V1, false);
    }

    @Test
    public void testWeKeepSendingRequests()
    {
        InstrumentedCoordinator coordinator = new InstrumentedCoordinator();

        getUnchecked(coordinator.reportEndpointVersion(EP3, V2));
        coordinator.requests.remove().response(Collections.emptyList());

        getUnchecked(coordinator.reportEndpointVersion(EP1, V1));
        getUnchecked(coordinator.reportEndpointVersion(EP2, V1));

        MigrationCoordinator.Callback prev = null;
        Set<InetAddressAndPort> EPs = Sets.newHashSet(EP1, EP2);
        int ep1requests = 0;
        int ep2requests = 0;

        for (int i=0; i<10; i++)
        {
            Assert.assertEquals(String.format("%s", i), 2, coordinator.requests.size());

            MigrationCoordinator.Callback next = coordinator.requests.remove();

            // we should be contacting endpoints in a round robin fashion
            Assert.assertTrue(EPs.contains(next.endpoint));
            if (prev != null && prev.endpoint.equals(next.endpoint))
                Assert.fail(String.format("Not expecting prev %s to be equal to next %s", prev.endpoint, next.endpoint));

            // should send a new request
            next.fail();
            prev = next;
            Assert.assertFalse(coordinator.awaitSchemaRequests(1));

            Assert.assertEquals(2, coordinator.requests.size());
        }
        logger.info("{} -> {}", EP1, ep1requests);
        logger.info("{} -> {}", EP2, ep2requests);

        // a single success should unblock startup though
        coordinator.requests.remove().response(Collections.emptyList());
        Assert.assertTrue(coordinator.awaitSchemaRequests(1));

    }

    /**
     * Pull unreceived schemas should detect and send requests out for any
     * schemas that are marked unreceived and have no outstanding requests
     */
    @Test
    public void pullUnreceived()
    {
        InstrumentedCoordinator coordinator = new InstrumentedCoordinator();

        coordinator.shouldPullFromEndpoint = false;
        assertNoContact(coordinator, false);

        coordinator.shouldPullFromEndpoint = true;
        Assert.assertEquals(0, coordinator.requests.size());
        List<Future<Void>> futures = coordinator.pullUnreceivedSchemaVersions();
        futures.forEach(Futures::getUnchecked);
        Assert.assertEquals(1, coordinator.requests.size());
    }
}


text:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

def get_weights(n_features, n_labels):
    """
    Return TensorFlow weights
    :param n_features: Number of features
    :param n_labels: Number of labels
    :return: TensorFlow weights
    """
    return tf.Variable(tf.truncated_normal((n_features, n_labels)))

def get_biases(n_labels):
    """
    Return TensorFlow bias
    :param n_labels: Number of labels
    :return: TensorFlow bias
    """
    return tf.Variable(tf.zeros(n_labels))

def linear(input, w, b):
    """
    Return linear function in TensorFlow
    :param input: TensorFlow input
    :param w: TensorFlow weights
    :param b: TensorFlow biases
    :return: TensorFlow linear function
    """
    return tf.add(tf.matmul(input, w), b)

def mnist_features_labels(n_labels):
    """
    Gets the first <n> labels from the MNIST dataset
    :param n_labels: Number of labels to use
    :return: Tuple of feature list and label list
    """
    mnist_features = []
    mnist_labels = []

    mnist = input_data.read_data_sets('mnist/', one_hot=True)

    # In order to make quizzes run faster, we're only looking at 10000 images
    for mnist_feature, mnist_label in zip(*mnist.train.next_batch(10000)):

        # Add features and labels if it's for the first <n>th labels
        if mnist_label[:n_labels].any():
            mnist_features.append(mnist_feature)
            mnist_labels.append(mnist_label[:n_labels])

    return mnist_features, mnist_labels

# Number of features (28*28 image is 784 features)
n_features = 784
# Number of labels
n_labels = 3

# Features and Labels
features = tf.placeholder(tf.float32)
labels = tf.placeholder(tf.float32)

# Weights and Biases
w = get_weights(n_features, n_labels)
b = get_biases(n_labels)

# Linear Function xW + b
logits = linear(features, w, b)

# Training data
train_features, train_labels = mnist_features_labels(n_labels)

with tf.Session() as session:
    session.run(tf.global_variables_initializer())

    # Softmax
    prediction = tf.nn.softmax(logits)

    # Cross entropy
    # This quantifies how far off the predictions were.
    # You'll learn more about this in future lessons.
    cross_entropy = -tf.reduce_sum(labels * tf.log(prediction), reduction_indices=1)

    # Training loss
    # You'll learn more about this in future lessons.
    loss = tf.reduce_mean(cross_entropy)

    # Rate at which the weights are changed
    # You'll learn more about this in future lessons.
    learning_rate = 0.05

    # Gradient Descent
    # This is the method used to train the model
    # You'll learn more about this in future lessons.
    optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

    # Run optimizer and get loss
    _, l = session.run(
        [optimizer, loss],
        feed_dict={features: train_features, labels: train_labels})

# Print loss
print('Loss: {}'.format(l))


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
    /// <summary>
    /// Implementations of EnvDTE.FileCodeModel for both languages.
    /// </summary>
    public sealed partial class FileCodeModel : AbstractCodeModelObject, EnvDTE.FileCodeModel, EnvDTE80.FileCodeModel2, ICodeElementContainer<AbstractCodeElement>, IVBFileCodeModelEvents, ICSCodeModelRefactoring
    {
        internal static ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> Create(
            CodeModelState state,
            object? parent,
            DocumentId documentId,
            bool isSourceGeneratorOutput,
            ITextManagerAdapter textManagerAdapter)
        {
            // Keep track that code model was accessed.  We want to get a sense of how widespread usage of it still is.
            Logger.Log(FunctionId.CodeModel_FileCodeModel_Create);
            return new FileCodeModel(state, parent, documentId, isSourceGeneratorOutput, textManagerAdapter).GetComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>();
        }

        private readonly ComHandle<object?, object?> _parentHandle;

        /// <summary>
        /// Don't use directly. Instead, call <see cref="GetDocumentId()"/>.
        /// </summary>
        private DocumentId? _documentId;
        private readonly bool _isSourceGeneratedOutput;

        // Note: these are only valid when the underlying file is being renamed. Do not use.
        private ProjectId? _incomingProjectId;
        private string? _incomingFilePath;
        private Document? _previousDocument;

        private readonly CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement> _codeElementTable;

        // These are used during batching.
        private bool _batchMode;
        private List<AbstractKeyedCodeElement>? _batchElements;
        private Document? _batchDocument;

        // track state to make sure we open editor only once
        private int _editCount;
        private IInvisibleEditor? _invisibleEditor;

        private SyntaxTree _lastSyntaxTree;

        private FileCodeModel(
            CodeModelState state,
            object? parent,
            DocumentId documentId,
            bool isSourceGeneratedOutput,
            ITextManagerAdapter textManagerAdapter)
            : base(state)
        {
            RoslynDebug.AssertNotNull(documentId);
            RoslynDebug.AssertNotNull(textManagerAdapter);

            _parentHandle = new ComHandle<object?, object?>(parent);
            _documentId = documentId;
            _isSourceGeneratedOutput = isSourceGeneratedOutput;
            TextManagerAdapter = textManagerAdapter;

            _codeElementTable = new CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement>(state.ThreadingContext);

            _batchMode = false;
            _batchDocument = null;
            _lastSyntaxTree = GetSyntaxTree();
        }

        internal ITextManagerAdapter TextManagerAdapter
        {
            get; set;
        }

        /// <summary>
        /// Internally, we store the DocumentId for the document that the FileCodeModel represents. If the underlying file
        /// is renamed, the DocumentId will become invalid because the Roslyn VS workspace treats file renames as a remove/add pair.
        /// To work around this, the FileCodeModel is notified when a file rename is about to occur. At that point, the
        /// <see cref="_documentId"/> field is null'd out and <see cref="_incomingFilePath"/> is set to the name of the new file.
        /// The next time that a FileCodeModel operation occurs that requires the DocumentId, it will be retrieved from the workspace
        /// using the <see cref="_incomingFilePath"/>.
        /// </summary>
        internal void OnRename(string newFilePath)
        {
            Debug.Assert(_editCount == 0, "FileCodeModel have an open edit and the underlying file is being renamed. This is a bug.");

            RoslynDebug.AssertNotNull(_documentId);

            _previousDocument = Workspace.CurrentSolution.GetDocument(_documentId);
            _incomingFilePath = newFilePath;
            _incomingProjectId = _documentId.ProjectId;

            _documentId = null;
        }

        internal override void Shutdown()
        {
            if (_invisibleEditor != null)
            {
                // we are shutting down, so do not worry about editCount. We will detach our format tracking from the text
                // buffer now; if anybody else had an invisible editor open to this file, we wouldn't want our format tracking
                // to trigger. We can safely do that on a background thread since it's just disconnecting a few event handlers.
                // We have to defer the shutdown of the invisible editor though as that requires talking to the UI thread.
                // We don't want to block up file removal on the UI thread since we want that path to stay asynchronous.
                CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer);

                State.ProjectCodeModelFactory.ScheduleDeferredCleanupTask(
                    cancellationToken =>
                    {
                        // Ignore cancellationToken: we always need to call Dispose since it triggers the file save.
                        _ = cancellationToken;

                        _invisibleEditor.Dispose();
                    });
            }

            base.Shutdown();
        }

        private bool TryGetDocumentId([NotNullWhen(true)] out DocumentId? documentId)
        {
            if (_documentId != null)
            {
                documentId = _documentId;
                return true;
            }

            documentId = null;

            // We don't have DocumentId, so try to retrieve it from the workspace.
            if (_incomingProjectId == null || _incomingFilePath == null)
            {
                return false;
            }

            var project = this.State.Workspace.CurrentSolution.GetProject(_incomingProjectId);
            if (project == null)
            {
                return false;
            }

            documentId = project.Solution.GetDocumentIdsWithFilePath(_incomingFilePath).FirstOrDefault(d => d.ProjectId == project.Id);
            if (documentId == null)
            {
                return false;
            }

            _documentId = documentId;
            _incomingProjectId = null;
            _incomingFilePath = null;
            _previousDocument = null;

            return true;
        }

        internal DocumentId GetDocumentId()
        {
            if (_documentId != null)
            {
                return _documentId;
            }

            if (TryGetDocumentId(out var documentId))
            {
                return documentId;
            }

            throw Exceptions.ThrowEUnexpected();
        }

        internal void UpdateCodeElementNodeKey(AbstractKeyedCodeElement keyedElement, SyntaxNodeKey oldNodeKey, SyntaxNodeKey newNodeKey)
        {
            if (!_codeElementTable.TryGetValue(oldNodeKey, out var codeElement))
            {
                throw new InvalidOperationException($"Could not find {oldNodeKey} in Code Model element table.");
            }

            _codeElementTable.Remove(oldNodeKey);

            var managedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(codeElement);
            if (!object.Equals(managedElement, keyedElement))
            {
                throw new InvalidOperationException($"Unexpected failure in Code Model while updating node keys {oldNodeKey} -> {newNodeKey}");
            }

            // If we're updating this element with the same node key as an element that's already in the table,
            // just remove the old element. The old element will continue to function (through its node key), but
            // the new element will replace it in the cache.
            if (_codeElementTable.ContainsKey(newNodeKey))
            {
                _codeElementTable.Remove(newNodeKey);
            }

            _codeElementTable.Add(newNodeKey, codeElement);
        }

        internal void OnCodeElementCreated(SyntaxNodeKey nodeKey, EnvDTE.CodeElement element)
        {
            // If we're updating this element with the same node key as an element that's already in the table,
            // just remove the old element. The old element will continue to function (through its node key), but
            // the new element will replace it in the cache.
            if (_codeElementTable.ContainsKey(nodeKey))
            {
                _codeElementTable.Remove(nodeKey);
            }

            _codeElementTable.Add(nodeKey, element);
        }

        internal void OnCodeElementDeleted(SyntaxNodeKey nodeKey)
            => _codeElementTable.Remove(nodeKey);

        internal T GetOrCreateCodeElement<T>(SyntaxNode node)
        {
            var nodeKey = CodeModelService.TryGetNodeKey(node);

            if (!nodeKey.IsEmpty)
            {
                // Since the node already has a key, check to see if a code element already
                // exists for it. If so, return that element it it's still valid; otherwise,
                // remove it from the table.
                if (_codeElementTable.TryGetValue(nodeKey, out var codeElement))
                {
                    if (codeElement != null)
                    {
                        var element = ComAggregate.GetManagedObject<AbstractCodeElement>(codeElement);
                        if (element.IsValidNode())
                        {
                            if (codeElement is T tcodeElement)
                            {
                                return tcodeElement;
                            }

                            throw new InvalidOperationException($"Found a valid code element for {nodeKey}, but it is not of type, {typeof(T).ToString()}");
                        }
                    }
                }

                // Go ahead and remove the nodeKey from the table. At this point, we'll be creating a new one.
                _codeElementTable.Remove(nodeKey);
            }

            return (T)CodeModelService.CreateInternalCodeElement(this.State, this, node);
        }

        private void InitializeEditor()
        {
            // If this is a source generated file, we can't edit it, so just block this at the very start.
            // E_FAIL is probably as a good as anything else, is and is also what we use files that go missing
            // so it's consistent for "this file isn't something you can use."
            if (_isSourceGeneratedOutput)
            {
                throw Exceptions.ThrowEFail();
            }

            _editCount++;

            if (_editCount == 1)
            {
                Debug.Assert(_invisibleEditor == null);

                _invisibleEditor = Workspace.OpenInvisibleEditor(GetDocumentId());
                CodeModelService.AttachFormatTrackingToBuffer(_invisibleEditor.TextBuffer);
            }
        }

        private void ReleaseEditor()
        {
            Debug.Assert(_editCount >= 1);

            _editCount--;
            if (_editCount == 0)
            {
                RoslynDebug.AssertNotNull(_invisibleEditor);
                CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer);

                _invisibleEditor.Dispose();
                _invisibleEditor = null;
            }
        }

        internal void EnsureEditor(Action action)
        {
            InitializeEditor();
            try
            {
                action();
            }
            finally
            {
                ReleaseEditor();
            }
        }

        internal T EnsureEditor<T>(Func<T> action)
        {
            InitializeEditor();
            try
            {
                return action();
            }
            finally
            {
                ReleaseEditor();
            }
        }

        internal void PerformEdit(Func<Document, Document> action)
        {
            EnsureEditor(() =>
            {
                Debug.Assert(_invisibleEditor != null);

                var document = GetDocument();
                var workspace = document.Project.Solution.Workspace;

                var result = action(document);

                var formatted = State.ThreadingContext.JoinableTaskFactory.Run(async () =>
                {
                    var formatted = await Formatter.FormatAsync(result, Formatter.Annotation).ConfigureAwait(true);
                    formatted = await Formatter.FormatAsync(formatted, SyntaxAnnotation.ElasticAnnotation).ConfigureAwait(true);

                    return formatted;
                });

                ApplyChanges(workspace, formatted);
            });
        }

        internal T PerformEdit<T>(Func<Document, Tuple<T, Document>> action) where T : SyntaxNode
        {
            return EnsureEditor(() =>
            {
                Debug.Assert(_invisibleEditor != null);

                var document = GetDocument();
                var workspace = document.Project.Solution.Workspace;

                var result = action(document);

                ApplyChanges(workspace, result.Item2);

                return result.Item1;
            });
        }

        private void ApplyChanges(Workspace workspace, Document document)
        {
            if (IsBatchOpen)
            {
                _batchDocument = document;
            }
            else
            {
                var applied = workspace.TryApplyChanges(document.Project.Solution);
                if (!applied)
                {
                    FatalError.ReportAndPropagate(new Exception("Failed to apply the workspace changes."), ErrorSeverity.Critical);
                }
            }
        }

        internal Document GetDocument()
        {
            if (!TryGetDocument(out var document))
            {
                throw Exceptions.ThrowEFail();
            }

            return document;
        }

        internal bool TryGetDocument([NotNullWhen(true)] out Document? document)
        {
            if (IsBatchOpen && _batchDocument != null)
            {
                document = _batchDocument;
                return true;
            }

            if (!TryGetDocumentId(out _) && _previousDocument != null)
            {
                document = _previousDocument;
            }
            else if (_isSourceGeneratedOutput)
            {
                document = State.ThreadingContext.JoinableTaskFactory.Run(
                    () => Workspace.CurrentSolution.GetSourceGeneratedDocumentAsync(GetDocumentId(), CancellationToken.None).AsTask());
            }
            else
            {
                // HACK HACK HACK: Ensure we've processed all files being opened before we let designers work further.
                // In https://devdiv.visualstudio.com/DevDiv/_workitems/edit/728035, a file is opened in an invisible editor and contents are written
                // to it. The file isn't saved, but it's added to the workspace; we won't have yet hooked up to the open file since that work was deferred.
                // Since we're on the UI thread here, we can ensure those are all wired up since the analysis of this document may depend on that other file.
                // We choose to do this here rather than in the project system code when it's added because we don't want to pay the penalty of checking the RDT for
                // all files being opened on the UI thread if we really don't need it. This uses an 'as' cast, because in unit tests the workspace is a different
                // derived form of VisualStudioWorkspace, and there we aren't dealing with open files at all so it doesn't matter.
                (State.Workspace as VisualStudioWorkspaceImpl)?.ProcessQueuedWorkOnUIThread();

                document = Workspace.CurrentSolution.GetDocument(GetDocumentId());
            }

            return document != null;
        }

        internal SyntaxTree GetSyntaxTree()
        {
            return GetDocument().GetRequiredSyntaxTreeSynchronously(CancellationToken.None);
        }

        internal SyntaxNode GetSyntaxRoot()
        {
            return GetDocument().GetRequiredSyntaxRootSynchronously(CancellationToken.None);
        }

        internal SemanticModel GetSemanticModel()
            => State.ThreadingContext.JoinableTaskFactory.Run(() =>
            {
                return GetDocument()
                    .GetRequiredSemanticModelAsync(CancellationToken.None).AsTask();
            });

        internal Compilation GetCompilation()
            => State.ThreadingContext.JoinableTaskFactory.Run(() =>
            {
                return GetDocument().Project
                    .GetRequiredCompilationAsync(CancellationToken.None);
            });

        internal ProjectId GetProjectId()
            => GetDocumentId().ProjectId;

        internal SyntaxNode LookupNode(SyntaxNodeKey nodeKey)
            => CodeModelService.LookupNode(nodeKey, GetSyntaxTree());

        public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position)
        {
            return EnsureEditor(() =>
            {
                return AddAttribute(GetSyntaxRoot(), name, value, position, target: CodeModelService.AssemblyAttributeString);
            });
        }

        public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access)
        {
            return EnsureEditor(() =>
            {
                return AddClass(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access);
            });
        }

        public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access)
        {
            return EnsureEditor(() =>
            {
                return AddDelegate(GetSyntaxRoot(), name, type, position, access);
            });
        }

        public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access)
        {
            return EnsureEditor(() =>
            {
                return AddEnum(GetSyntaxRoot(), name, position, bases, access);
            });
        }

        public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access)
            => throw Exceptions.ThrowEFail();

        public EnvDTE80.CodeImport AddImport(string name, object position, string alias)
        {
            return EnsureEditor(() =>
            {
                return AddImport(GetSyntaxRoot(), name, position, alias);
            });
        }

        public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access)
        {
            return EnsureEditor(() =>
            {
                return AddInterface(GetSyntaxRoot(), name, position, bases, access);
            });
        }

        public EnvDTE.CodeNamespace AddNamespace(string name, object position)
        {
            return EnsureEditor(() =>
            {
                return AddNamespace(GetSyntaxRoot(), name, position);
            });
        }

        public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access)
        {
            return EnsureEditor(() =>
            {
                return AddStruct(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access);
            });
        }

        public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access)
            => throw Exceptions.ThrowEFail();

        public EnvDTE.CodeElement CodeElementFromPoint(EnvDTE.TextPoint point, EnvDTE.vsCMElement scope)
        {
            // Can't use point.AbsoluteCharOffset because it's calculated by the native
            // implementation in GetAbsoluteOffset (in env\msenv\textmgr\autoutil.cpp)
            // to only count each newline as a single character. We need to ask for line and
            // column and calculate the right offset ourselves. See DevDiv2 530496 for details.
            var position = GetPositionFromTextPoint(point);

            var result = CodeElementFromPosition(position, scope);
            if (result == null)
            {
                throw Exceptions.ThrowEFail();
            }

            return result;
        }

        private int GetPositionFromTextPoint(EnvDTE.TextPoint point)
        {
            var lineNumber = point.Line - 1;
            var column = point.LineCharOffset - 1;
            var line = GetDocument().GetTextSynchronously(CancellationToken.None).Lines[lineNumber];
            var position = line.Start + column;

            return position;
        }

        internal EnvDTE.CodeElement? CodeElementFromPosition(int position, EnvDTE.vsCMElement scope)
        {
            var root = GetSyntaxRoot();
            var leftToken = root.FindTokenOnLeftOfPosition(position);
            var rightToken = root.FindTokenOnRightOfPosition(position);

            // We apply a set of heuristics to determine which member we pick to start searching.
            var token = leftToken;
            if (leftToken != rightToken)
            {
                if (leftToken.Span.End == position && rightToken.SpanStart == position)
                {
                    // If both tokens are touching, we prefer identifiers and keywords to
                    // separators. Note that the language doesn't allow both tokens to be a
                    // keyword or identifier.
                    if (SyntaxFactsService.IsReservedOrContextualKeyword(rightToken) ||
                        SyntaxFactsService.IsIdentifier(rightToken))
                    {
                        token = rightToken;
                    }
                }
                else if (leftToken.Span.End < position && rightToken.SpanStart <= position)
                {
                    // If only the right token is touching, we have to use it.
                    token = rightToken;
                }
            }

            // If we ended up using the left token but the position is after that token,
            // walk up to the first node who's last token is not the leftToken. By doing this, we
            // ensure that we don't find members when the position is actually between them.
            // In that case, we should find the enclosing type or namespace.
            var parent = token.Parent;
            if (token == leftToken && position > token.Span.End)
            {
                while (parent != null)
                {
                    if (parent.GetLastToken() == token)
                    {
                        parent = parent.Parent;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            var node = parent?.AncestorsAndSelf().FirstOrDefault(n => CodeModelService.MatchesScope(n, scope));

            if (node == null)
            {
                return null;
            }

            if (scope == EnvDTE.vsCMElement.vsCMElementAttribute ||
                scope == EnvDTE.vsCMElement.vsCMElementImportStmt ||
                scope == EnvDTE.vsCMElement.vsCMElementParameter ||
                scope == EnvDTE.vsCMElement.vsCMElementOptionStmt ||
                scope == EnvDTE.vsCMElement.vsCMElementInheritsStmt ||
                scope == EnvDTE.vsCMElement.vsCMElementImplementsStmt ||
                (scope == EnvDTE.vsCMElement.vsCMElementFunction && CodeModelService.IsAccessorNode(node)))
            {
                // Attributes, imports, parameters, Option, Inherits and Implements
                // don't have node keys of their own and won't be included in our
                // collection of elements. Delegate to the service to create these.
                return CodeModelService.CreateInternalCodeElement(State, this, node);
            }

            return GetOrCreateCodeElement<EnvDTE.CodeElement>(node);
        }

        public EnvDTE.CodeElements CodeElements
        {
            get { return NamespaceCollection.Create(this.State, this, this, SyntaxNodeKey.Empty); }
        }

        public EnvDTE.ProjectItem? Parent
        {
            get { return _parentHandle.Object as EnvDTE.ProjectItem; }
        }

        public void Remove(object element)
        {
            var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element);

            if (codeElement == null)
            {
                codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.CodeElements.Item(element));
            }

            if (codeElement == null)
            {
                throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element));
            }

            codeElement.Delete();
        }

        int IVBFileCodeModelEvents.StartEdit()
        {
            try
            {
                InitializeEditor();

                if (_editCount == 1)
                {
                    _batchMode = true;
                    _batchElements = new List<AbstractKeyedCodeElement>();
                }

                return VSConstants.S_OK;
            }
            catch (Exception ex)
            {
                return Marshal.GetHRForException(ex);
            }
        }

        int IVBFileCodeModelEvents.EndEdit()
        {
            try
            {
                if (_editCount == 1)
                {
                    RoslynDebug.AssertNotNull(_batchElements);
                    RoslynDebug.AssertNotNull(_invisibleEditor);

                    List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>>? elementAndPaths = null;
                    if (_batchElements.Count > 0)
                    {
                        foreach (var element in _batchElements)
                        {
                            var node = element.LookupNode();
                            if (node != null)
                            {
                                elementAndPaths ??= new List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>>();
                                elementAndPaths.Add(ValueTuple.Create(element, new SyntaxPath(node)));
                            }
                        }
                    }

                    if (_batchDocument != null)
                    {
                        // perform expensive operations at once
                        var newDocument = State.ThreadingContext.JoinableTaskFactory.Run(() =>
                            Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None));

                        _batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution);

                        // done using batch document
                        _batchDocument = null;
                    }

                    // Ensure the file is prettylisted, even if we didn't make any edits
                    CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer);

                    if (elementAndPaths != null)
                    {
                        foreach (var elementAndPath in elementAndPaths)
                        {
                            // make sure the element is there.
                            if (_codeElementTable.TryGetValue(elementAndPath.Item1.NodeKey, out var existingElement))
                            {
                                elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None);
                            }

                            // make sure existing element doesn't go away (weak reference) in the middle of
                            // updating the node key
                            GC.KeepAlive(existingElement);
                        }
                    }

                    _batchMode = false;
                    _batchElements = null;
                }

                return VSConstants.S_OK;
            }
            catch (Exception ex)
            {
                return Marshal.GetHRForException(ex);
            }
            finally
            {
                ReleaseEditor();
            }
        }

        public void BeginBatch()
        {
            IVBFileCodeModelEvents temp = this;
            ErrorHandler.ThrowOnFailure(temp.StartEdit());
        }

        public void EndBatch()
        {
            IVBFileCodeModelEvents temp = this;
            ErrorHandler.ThrowOnFailure(temp.EndEdit());
        }

        [MemberNotNullWhen(true, nameof(_batchElements))]
        public bool IsBatchOpen
        {
            get
            {
                return _batchMode && _editCount > 0;
            }
        }

        public EnvDTE.CodeElement ElementFromID(string id)
            => throw new NotImplementedException();

        public EnvDTE80.vsCMParseStatus ParseStatus
        {
            get
            {
                var syntaxTree = GetSyntaxTree();
                return syntaxTree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)
                    ? EnvDTE80.vsCMParseStatus.vsCMParseStatusError
                    : EnvDTE80.vsCMParseStatus.vsCMParseStatusComplete;
            }
        }

        public void Synchronize()
            => FireEvents();

        EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection()
            => CodeElements;

        internal List<GlobalNodeKey> GetCurrentNodeKeys()
        {
            var currentNodeKeys = new List<GlobalNodeKey>();

            foreach (var element in _codeElementTable.Values)
            {
                var keyedElement = ComAggregate.TryGetManagedObject<AbstractKeyedCodeElement>(element);
                if (keyedElement == null)
                {
                    continue;
                }

                if (keyedElement.TryLookupNode(out var node))
                {
                    var nodeKey = keyedElement.NodeKey;
                    currentNodeKeys.Add(new GlobalNodeKey(nodeKey, new SyntaxPath(node)));
                }
            }

            return currentNodeKeys;
        }

        internal void ResetElementKeys(List<GlobalNodeKey> globalNodeKeys)
        {
            foreach (var globalNodeKey in globalNodeKeys)
            {
                ResetElementKey(globalNodeKey);
            }
        }

        private void ResetElementKey(GlobalNodeKey globalNodeKey)
        {
            // Failure to find the element is not an error -- it just means the code
            // element didn't exist...
            if (_codeElementTable.TryGetValue(globalNodeKey.NodeKey, out var element))
            {
                var keyedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(element);
                if (keyedElement != null)
                {
                    keyedElement.ReacquireNodeKey(globalNodeKey.Path, default);
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace CommandLineArgumentsParser.Parsers
{
    public class SByteParser : ICommandLineTokenParser
    {
        #region ICommandLineTokenParser Members

        public object Parse(string[] values)
        {
            return SByte.Parse(values[0]);
        }

        public int TokensRequired
        {
            get { return 1; }
        }

        #endregion
    }
}


text:
class Api::DashboardController < Api::ApiController
  before_action :require_user

  def counts
    @user = current_user
    @properties = @user.properties
    @contracts = @user.all_contracts

    @current_year = Date.today.strftime('%Y').to_i
    @current_month = Date.today.strftime('%m').to_i
    @monthly_paid = Date::ABBR_MONTHNAMES[1..12].map {|m| [m, 0]}

    @all_payments = if @user.user_type == User::LANDLORD
                      Payment.year(@current_year)
                      .joins(:contract)
                      .where('contracts.landlord_id = ?', @user.id)
                      .order(:contract_id, :due_date)
                    else
                      Payment.year(@current_year)
                      .joins(:contract)
                      .where('contracts.tenant_id = ?', @user.id)
                      .order(:contract_id, :due_date)
                    end
    @paid_payments = @all_payments.paid.all
    @paid_payments = @paid_payments.group_by { |p| p.date_paid.beginning_of_month }
    @outstanding_payments = @all_payments.outstanding.all + @all_payments.refunded.all
    @outstanding_payments = @outstanding_payments.group_by { |p| p.due_date.beginning_of_month }

    # @year_paid_total = 0
    @paid_payments.sort.map do |month, p|
      index = @monthly_paid.index {|e| e[0] == month.strftime('%b')}
      total = p.map(&:amount).reduce(&:+).to_f
      @monthly_paid[index][1] = total
      # @year_paid_total += total
      @monthly_paid[index][2] = "Amount: #{decimal_amount(total)}"
      @monthly_paid[index][3] = p.count
    end

    render json: {
        properties_count: @properties.count,
        contracts_count: @contracts.count,
        monthly_paid: @monthly_paid[@current_month - 1][3] || 0,
        outstanding_count: @outstanding_payments.count
    }
  end

end


text:
@implementation GotoRiskCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code

    [self.questionBtn setUserInteractionEnabled:YES];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setModel:(QuestionModel *)model{
    _model = model;
}

@end


text:
name             'kubernetes-install'
maintainer       'Flexiant Ltd.'
maintainer_email 'contact@flexiant.com'
license          'Apache v2.0'
description      'Installs/Configures kubernetes'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          IO.read(File.join(File.dirname(__FILE__), 'VERSION')).chomp

source_url       'https://github.com/flexiant/kubernetes-install'
issues_url       'https://github.com/flexiant/kubernetes-install/issues'

supports 'ubuntu', '>= 15.04'

depends "tar"
depends "docker", '= 1.1.49'
depends "etcd", '= 2.2.4'

recipe "kubernetes-install::default", "Install and configure Kubernetes"
recipe "kubernetes-install::load_balancer", "Install and configure Load Balancer for Kubernetes"
recipe "kubernetes-install::master", "Install and Configures Kubernetes Master"
recipe "kubernetes-install::node", "Install and Configure Kuberntes Node"
recipe "kubernetes-install::service_discovery", "Install and configure Kubernetes Service Discovery"

# Flexiant Concerto Defaults
attribute "kubernetes/package",
  :display_name => "Url of Kubernetes Package"

attribute "kubernetes/nodes",
  :display_name => "Array of Nodes of Kubernetes",
  :default => []

attribute "kubernetes/cloud-provider",
  :display_name => "Cloud provider. Empty if no provider is used"

attribute "kubernetes/cloud-config",
  :display_name => "Cloud provider configuration file"

attribute 'kubernetes/kubelet/params/cluster_dns',
  :display_name => "Service Discovery Ip Address",
  :default => "172.30.3.1"

attribute "kubernetes/apiserver/params/service-cluster-ip-range",
  :display_name => "Service Cluster Ip Range",
  :default => "172.30.0.0/16"

attribute "kubernetes/kubelet/params/cluster-domain",
  :display_name => "Cluster domain",
  :default => "cluster.local"


text:
namespace Azure.ResourceManager.CognitiveServices.Models
{
    /// <summary> Cognitive Services account commitment cost. </summary>
    public partial class CommitmentCost
    {
        /// <summary> Initializes a new instance of CommitmentCost. </summary>
        internal CommitmentCost()
        {
        }

        /// <summary> Initializes a new instance of CommitmentCost. </summary>
        /// <param name="commitmentMeterId"> Commitment meter Id. </param>
        /// <param name="overageMeterId"> Overage meter Id. </param>
        internal CommitmentCost(string commitmentMeterId, string overageMeterId)
        {
            CommitmentMeterId = commitmentMeterId;
            OverageMeterId = overageMeterId;
        }

        /// <summary> Commitment meter Id. </summary>
        public string CommitmentMeterId { get; }
        /// <summary> Overage meter Id. </summary>
        public string OverageMeterId { get; }
    }
}