text:
package com.ibasco.agql.protocols.valve.dota2.webapi.pojos;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.ArrayList;
import java.util.List;

/**
 *
Dota2TeamDetails class.

 *
 * @author Rafael Luis Ibasco
 */
public class Dota2TeamDetails {

    @SerializedName("members")
    @Expose
    private List<Dota2TeamMemberDetails> members = new ArrayList<>();

    @SerializedName("team_id")
    @Expose
    private int teamId;

    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("tag")
    @Expose
    private String tag;

    @SerializedName("time_created")
    @Expose
    private int timeCreated;

    @SerializedName("pro")
    @Expose
    private boolean pro;

    @SerializedName("locked")
    @Expose
    private boolean locked;

    @SerializedName("ugc_logo")
    @Expose
    private String ugcLogo;

    @SerializedName("ugc_base_logo")
    @Expose
    private String ugcBaseLogo;

    @SerializedName("ugc_banner_logo")
    @Expose
    private String ugcBannerLogo;

    @SerializedName("ugc_sponsor_logo")
    @Expose
    private String ugcSponsorLogo;

    @SerializedName("country_code")
    @Expose
    private String countryCode;

    @SerializedName("url")
    @Expose
    private String url;

    @SerializedName("wins")
    @Expose
    private int wins;

    @SerializedName("losses")
    @Expose
    private int losses;

    @SerializedName("rank")
    @Expose
    private int rank;

    @SerializedName("calibration_games_remaining")
    @Expose
    private int calibrationGamesRemaining;

    @SerializedName("games_played_total")
    @Expose
    private int gamesPlayedTotal;

    @SerializedName("games_played_matchmaking")
    @Expose
    private int gamesPlayedMatchmaking;

    @SerializedName("leagues_participated")
    @Expose
    private List<Integer> leaguesParticipated = new ArrayList<>();

    @SerializedName("top_match_ids")
    @Expose
    private List<String> topMatchIds = new ArrayList<>();

    @SerializedName("recent_match_ids")
    @Expose
    private List<String> recentMatchIds = new ArrayList<>();

    /**
     *
Getter for the field members.

     *
     * @return The members
     */
    public List<Dota2TeamMemberDetails> getMembers() {
        return members;
    }

    /**
     *
Setter for the field members.

     *
     * @param members
     *         The members
     */
    public void setMembers(List<Dota2TeamMemberDetails> members) {
        this.members = members;
    }

    /**
     *
Getter for the field teamId.

     *
     * @return The teamId
     */
    public int getTeamId() {
        return teamId;
    }

    /**
     *
Setter for the field teamId.

     *
     * @param teamId
     *         The team_id
     */
    public void setTeamId(int teamId) {
        this.teamId = teamId;
    }

    /**
     *
Getter for the field name.

     *
     * @return The name
     */
    public String getName() {
        return name;
    }

    /**
     *
Setter for the field name.

     *
     * @param name
     *         The name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *
Getter for the field tag.

     *
     * @return The tag
     */
    public String getTag() {
        return tag;
    }

    /**
     *
Setter for the field tag.

     *
     * @param tag
     *         The tag
     */
    public void setTag(String tag) {
        this.tag = tag;
    }

    /**
     *
Getter for the field timeCreated.

     *
     * @return The timeCreated
     */
    public int getTimeCreated() {
        return timeCreated;
    }

    /**
     *
Setter for the field timeCreated.

     *
     * @param timeCreated
     *         The time_created
     */
    public void setTimeCreated(int timeCreated) {
        this.timeCreated = timeCreated;
    }

    /**
     *
isPro.

     *
     * @return The pro
     */
    public boolean isPro() {
        return pro;
    }

    /**
     *
Setter for the field pro.

     *
     * @param pro
     *         The pro
     */
    public void setPro(boolean pro) {
        this.pro = pro;
    }

    /**
     *
isLocked.

     *
     * @return The locked
     */
    public boolean isLocked() {
        return locked;
    }

    /**
     *
Setter for the field locked.

     *
     * @param locked
     *         The locked
     */
    public void setLocked(boolean locked) {
        this.locked = locked;
    }

    /**
     *
Getter for the field ugcLogo.

     *
     * @return The ugcLogo
     */
    public String getUgcLogo() {
        return ugcLogo;
    }

    /**
     *
Setter for the field ugcLogo.

     *
     * @param ugcLogo
     *         The ugc_logo
     */
    public void setUgcLogo(String ugcLogo) {
        this.ugcLogo = ugcLogo;
    }

    /**
     *
Getter for the field ugcBaseLogo.

     *
     * @return The ugcBaseLogo
     */
    public String getUgcBaseLogo() {
        return ugcBaseLogo;
    }

    /**
     *
Setter for the field ugcBaseLogo.

     *
     * @param ugcBaseLogo
     *         The ugc_base_logo
     */
    public void setUgcBaseLogo(String ugcBaseLogo) {
        this.ugcBaseLogo = ugcBaseLogo;
    }

    /**
     *
Getter for the field ugcBannerLogo.

     *
     * @return The ugcBannerLogo
     */
    public String getUgcBannerLogo() {
        return ugcBannerLogo;
    }

    /**
     *
Setter for the field ugcBannerLogo.

     *
     * @param ugcBannerLogo
     *         The ugc_banner_logo
     */
    public void setUgcBannerLogo(String ugcBannerLogo) {
        this.ugcBannerLogo = ugcBannerLogo;
    }

    /**
     *
Getter for the field ugcSponsorLogo.

     *
     * @return The ugcSponsorLogo
     */
    public String getUgcSponsorLogo() {
        return ugcSponsorLogo;
    }

    /**
     *
Setter for the field ugcSponsorLogo.

     *
     * @param ugcSponsorLogo
     *         The ugc_sponsor_logo
     */
    public void setUgcSponsorLogo(String ugcSponsorLogo) {
        this.ugcSponsorLogo = ugcSponsorLogo;
    }

    /**
     *
Getter for the field countryCode.

     *
     * @return The countryCode
     */
    public String getCountryCode() {
        return countryCode;
    }

    /**
     *
Setter for the field countryCode.

     *
     * @param countryCode
     *         The country_code
     */
    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }

    /**
     *
Getter for the field url.

     *
     * @return The url
     */
    public String getUrl() {
        return url;
    }

    /**
     *
Setter for the field url.

     *
     * @param url
     *         The url
     */
    public void setUrl(String url) {
        this.url = url;
    }

    /**
     *
Getter for the field wins.

     *
     * @return The wins
     */
    public int getWins() {
        return wins;
    }

    /**
     *
Setter for the field wins.

     *
     * @param wins
     *         The wins
     */
    public void setWins(int wins) {
        this.wins = wins;
    }

    /**
     *
Getter for the field losses.

     *
     * @return The losses
     */
    public int getLosses() {
        return losses;
    }

    /**
     *
Setter for the field losses.

     *
     * @param losses
     *         The losses
     */
    public void setLosses(int losses) {
        this.losses = losses;
    }

    /**
     *
Getter for the field rank.

     *
     * @return The rank
     */
    public int getRank() {
        return rank;
    }

    /**
     *
Setter for the field rank.

     *
     * @param rank
     *         The rank
     */
    public void setRank(int rank) {
        this.rank = rank;
    }

    /**
     *
Getter for the field calibrationGamesRemaining.

     *
     * @return The calibrationGamesRemaining
     */
    public int getCalibrationGamesRemaining() {
        return calibrationGamesRemaining;
    }

    /**
     *
Setter for the field calibrationGamesRemaining.

     *
     * @param calibrationGamesRemaining
     *         The calibration_games_remaining
     */
    public void setCalibrationGamesRemaining(int calibrationGamesRemaining) {
        this.calibrationGamesRemaining = calibrationGamesRemaining;
    }

    /**
     *
Getter for the field gamesPlayedTotal.

     *
     * @return The gamesPlayedTotal
     */
    public int getGamesPlayedTotal() {
        return gamesPlayedTotal;
    }

    /**
     *
Setter for the field gamesPlayedTotal.

     *
     * @param gamesPlayedTotal
     *         The games_played_total
     */
    public void setGamesPlayedTotal(int gamesPlayedTotal) {
        this.gamesPlayedTotal = gamesPlayedTotal;
    }

    /**
     *
Getter for the field gamesPlayedMatchmaking.

     *
     * @return The gamesPlayedMatchmaking
     */
    public int getGamesPlayedMatchmaking() {
        return gamesPlayedMatchmaking;
    }

    /**
     *
Setter for the field gamesPlayedMatchmaking.

     *
     * @param gamesPlayedMatchmaking
     *         The games_played_matchmaking
     */
    public void setGamesPlayedMatchmaking(int gamesPlayedMatchmaking) {
        this.gamesPlayedMatchmaking = gamesPlayedMatchmaking;
    }

    /**
     *
Getter for the field leaguesParticipated.

     *
     * @return The leaguesParticipated
     */
    public List<Integer> getLeaguesParticipated() {
        return leaguesParticipated;
    }

    /**
     *
Setter for the field leaguesParticipated.

     *
     * @param leaguesParticipated
     *         The leagues_participated
     */
    public void setLeaguesParticipated(List<Integer> leaguesParticipated) {
        this.leaguesParticipated = leaguesParticipated;
    }

    /**
     *
Getter for the field topMatchIds.

     *
     * @return The topMatchIds
     */
    public List<String> getTopMatchIds() {
        return topMatchIds;
    }

    /**
     *
Setter for the field topMatchIds.

     *
     * @param topMatchIds
     *         The top_match_ids
     */
    public void setTopMatchIds(List<String> topMatchIds) {
        this.topMatchIds = topMatchIds;
    }

    /**
     *
Getter for the field recentMatchIds.

     *
     * @return The recentMatchIds
     */
    public List<String> getRecentMatchIds() {
        return recentMatchIds;
    }

    /**
     *
Setter for the field recentMatchIds.

     *
     * @param recentMatchIds
     *         The recent_match_ids
     */
    public void setRecentMatchIds(List<String> recentMatchIds) {
        this.recentMatchIds = recentMatchIds;
    }

    /** {@inheritDoc} */
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.NO_CLASS_NAME_STYLE);
    }

}


text: DLSU Thesis Coordinator System

redpajama_set_name: RedPajamaGithub


text:
(function(angular, HttpStatus) {
  'use strict';

  angular
    .module('pm')
    .factory('httpErrorInterceptador', httpErrorInterceptador);

  httpErrorInterceptador.$inject = ['$location', '$q', '$rootScope'];

  function httpErrorInterceptador($location, $q, $rootScope) {
    var service = {
      responseError: responseError
    };

    return service;

    function responseError(response) {
      switch (response.status) {
        case HttpStatus.INTERNAL_SERVER_ERROR:
          $location.path('/500');
          break;
        case HttpStatus.NOT_FOUND:
          $location.path('/404');
          break;
        case HttpStatus.PRECONDITION_FAILED:
          $rootScope.$broadcast('uiFbViolacoes', response.data);
          break;
        default:
          break;
      }

      return $q.reject(response);
    }
  }
})(angular, httpStatusCode);


text:
<!DOCTYPE html>

		<meta charset="utf-8">
			<title>HOME</title>
			<link rel="stylesheet" href="">

HOME

This page was generated by the home controller and the method index.

The view does exists at app/views/home/index.php


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Geastrum lloydii Bres. & Pat.

### Remarks
null


text:
namespace courgette {

LabelManager::SimpleIndexAssigner::SimpleIndexAssigner(LabelVector* labels)
    : labels_(labels) {
  // Initialize |num_index_| and |available_|.
  num_index_ = std::max(base::checked_cast<int>(labels_->size()),
                        GetLabelIndexBound(*labels_));
  available_.resize(num_index_, true);
  size_t used = 0;
  for (const Label& label : *labels_) {
    if (label.index_ != Label::kNoIndex) {
      available_.at(label.index_) = false;
      ++used;
    }
  }
  VLOG(1) << used << " of " << labels_->size() << " labels pre-assigned.";
}

LabelManager::SimpleIndexAssigner::~SimpleIndexAssigner() = default;

void LabelManager::SimpleIndexAssigner::DoForwardFill() {
  size_t count = 0;
  // Inside the loop, if |prev_index| == |kNoIndex| then we try to assign 0.
  // This allows 0 (if unused) to be assigned in middle of |labels_|.
  int prev_index = Label::kNoIndex;
  for (auto p = labels_->begin(); p != labels_->end(); ++p) {
    if (p->index_ == Label::kNoIndex) {
      int index = (prev_index == Label::kNoIndex) ? 0 : prev_index + 1;
      if (index < num_index_ && available_.at(index)) {
        p->index_ = index;
        available_.at(index) = false;
        ++count;
      }
    }
    prev_index = p->index_;
  }
  VLOG(1) << "  fill forward " << count;
}

void LabelManager::SimpleIndexAssigner::DoBackwardFill() {
  size_t count = 0;
  // This is asymmetric from DoForwardFill(), to preserve old behavior.
  // Inside the loop, if |prev_index| == |kNoIndex| then we skip assignment.
  // But we initilaize |prev_index| = |num_index_|, so if the last element in
  // |labels_| has no index, then can use |num_index_| - 1 (if unused). We don't
  // try this assignment elsewhere.
  int prev_index = num_index_;
  for (auto p = labels_->rbegin(); p != labels_->rend(); ++p) {
    if (p->index_ == Label::kNoIndex && prev_index != Label::kNoIndex) {
      int index = prev_index - 1;
      if (index >= 0 && available_.at(index)) {
        p->index_ = index;
        available_.at(index) = false;
        ++count;
      }
    }
    prev_index = p->index_;
  }
  VLOG(1) << "  fill backward " << count;
}

void LabelManager::SimpleIndexAssigner::DoInFill() {
  size_t count = 0;
  int index = 0;
  for (Label& label : *labels_) {
    if (label.index_ == Label::kNoIndex) {
      while (!available_.at(index))
        ++index;
      label.index_ = index;
      available_.at(index) = false;
      ++index;
      ++count;
    }
  }
  VLOG(1) << "  infill " << count;
}

LabelManager::LabelManager() = default;

LabelManager::~LabelManager() = default;

// static
int LabelManager::GetLabelIndexBound(const LabelVector& labels) {
  int max_index = -1;
  for (const Label& label : labels) {
    if (label.index_ != Label::kNoIndex)
      max_index = std::max(max_index, label.index_);
  }
  return max_index + 1;
}

// Uses binary search to find |rva|.
Label* LabelManager::Find(RVA rva) {
  auto it = std::lower_bound(
      labels_.begin(), labels_.end(), Label(rva),
      [](const Label& l1, const Label& l2) { return l1.rva_ < l2.rva_; });
  return it == labels_.end() || it->rva_ != rva ? nullptr : &(*it);
}

void LabelManager::UnassignIndexes() {
  for (Label& label : labels_)
    label.index_ = Label::kNoIndex;
}

void LabelManager::DefaultAssignIndexes() {
  int cur_index = 0;
  for (Label& label : labels_) {
    CHECK_EQ(Label::kNoIndex, label.index_);
    label.index_ = cur_index++;
  }
}

void LabelManager::AssignRemainingIndexes() {
  // This adds some memory overhead, about 1 bit per Label (more if indexes >=
  // |labels_.size()| get used).
  SimpleIndexAssigner assigner(&labels_);
  assigner.DoForwardFill();
  assigner.DoBackwardFill();
  assigner.DoInFill();
}

// We wish to minimize peak memory usage here. Analysis: Let
//   m = number of (RVA) elements in |rva_visitor|,
//   n = number of distinct (RVA) elements in |rva_visitor|.
// The final storage is n * sizeof(Label) bytes. During computation we uniquify
// m RVAs, and count repeats. Taking sizeof(RVA) = 4, an implementation using
// std::map or std::unordered_map would consume additionally 32 * n bytes.
// Meanwhile, our std::vector implementation consumes additionally 4 * m bytes
// For our typical usage (i.e. Chrome) we see m = ~4n, so we use 16 * n bytes of
// extra contiguous memory during computation. Assuming memory fragmentation
// would not be an issue, this is much better than using std::map.
void LabelManager::Read(RvaVisitor* rva_visitor) {
  // Write all values in |rva_visitor| to |rvas|.
  size_t num_rva = rva_visitor->Remaining();
  std::vector<RVA> rvas(num_rva);
  for (size_t i = 0; i < num_rva; ++i, rva_visitor->Next())
    rvas[i] = rva_visitor->Get();

  // Sort |rvas|, then count the number of distinct values.
  using CRV = ConsecutiveRangeVisitor<std::vector<RVA>::iterator>;
  std::sort(rvas.begin(), rvas.end());
  DCHECK(rvas.empty() || rvas.back() != kUnassignedRVA);

  size_t num_distinct_rva = 0;
  for (CRV it(rvas.begin(), rvas.end()); it.has_more(); it.advance())
    ++num_distinct_rva;

  // Reserve space for |labels_|, populate with sorted RVA and repeats.
  DCHECK(labels_.empty());
  labels_.reserve(num_distinct_rva);
  for (CRV it(rvas.begin(), rvas.end()); it.has_more(); it.advance()) {
    labels_.push_back(Label(*it.cur()));
    labels_.back().count_ =
        base::checked_cast<decltype(labels_.back().count_)>(it.repeat());
  }
}

}  // namespace courgette


text:
package com.epam.training.taskmanager.service;

import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.os.ResultReceiver;
import android.util.Log;

import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by IstiN on 19.12.2014.
 */
public class MyCoolService extends IntentService {

    public static final String TAG = "MyCoolService";

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     */
    public MyCoolService() {
        super("my service");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            if (ServiceResult.ACTION_EXECUTE_WITH_RESULT_RECEIVER.equals(intent.getAction())) {
                Log.d(TAG, "ACTION_EXECUTE_WITH_RESULT_RECEIVER");
                ResultReceiver resultReceiver = intent.getParcelableExtra(ServiceResult.KEY_RESULT_RECEIVER);
                Log.d(TAG, "send 0 start");
                resultReceiver.send(0, null);
                Log.d(TAG, "send 0 end");
                Bundle resultData = new Bundle();
                resultData.putString("test_key", "test_string");
                Log.d(TAG, "send 1 start");
                resultReceiver.send(1, resultData);
                Log.d(TAG, "send 1 end");
            } else if (ServiceResult.ACTION_EXECUTE_WITH_SERVICE_CONNECTION.equals(intent.getAction())) {
                Log.d(TAG, "ACTION_EXECUTE_WITH_SERVICE_CONNECTION");
                int i = 0;
                for (Runnable runnable : event) {
                    Log.d(TAG, "send "+i+" start");
                    runnable.run();
                    i++;
                }
            }
        }
    }

    private Set<Runnable> event = new HashSet<>();

    public void addRunnable(Runnable runnable) {
        event.add(runnable);
    }

    public void removeRunnable(Runnable runnable) {
        event.remove(runnable);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new ServiceBinder<>(this);
    }

    public class ServiceBinder<S> extends Binder {

        private final WeakReference<S> mService;

        public ServiceBinder(S service){
            mService = new WeakReference<S>(service);
        }

        public S getService() {
            return mService.get();
        }

    }

}


text:
module BigQuery
  module Attribute
    class Date < Base
      def parse
        return nil if @value.nil?
        ::Date.parse(@value)
      end
    end
  end
end


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var doc_1 = require("./doc");
var environment_1 = require("./environment");
var ops = require("./ops/ops");
var util = require("./util");
var TensorBuffer = (function () {
    function TensorBuffer(shape, dtype, values) {
        this.shape = shape;
        this.dtype = dtype;
        this.values = values;
        if (values != null) {
            var n = values.length;
            var size = util.sizeFromShape(shape);
            util.assert(n === size, "Length of values '" + n + "' does not match the size " +
                ("inferred by the shape '" + size + "'"));
        }
        this.values =
            values || util.getTypedArrayFromDType(dtype, util.sizeFromShape(shape));
        this.strides = computeStrides(shape);
    }
    TensorBuffer.prototype.set = function (value) {
        var locs = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            locs[_i - 1] = arguments[_i];
        }
        if (locs.length === 0) {
            locs = [0];
        }
        util.assert(locs.length === this.rank, "The number of provided coordinates (" + locs.length + ") must " +
            ("match the rank (" + this.rank + ")"));
        var index = this.locToIndex(locs);
        this.values[index] = value;
    };
    TensorBuffer.prototype.get = function () {
        var locs = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            locs[_i] = arguments[_i];
        }
        if (locs.length === 0) {
            locs = [0];
        }
        var index = locs[locs.length - 1];
        for (var i = 0; i < locs.length - 1; ++i) {
            index += this.strides[i] * locs[i];
        }
        return this.values[index];
    };
    TensorBuffer.prototype.locToIndex = function (locs) {
        if (this.rank === 0) {
            return 0;
        }
        else if (this.rank === 1) {
            return locs[0];
        }
        var index = locs[locs.length - 1];
        for (var i = 0; i < locs.length - 1; ++i) {
            index += this.strides[i] * locs[i];
        }
        return index;
    };
    TensorBuffer.prototype.indexToLoc = function (index) {
        if (this.rank === 0) {
            return [];
        }
        else if (this.rank === 1) {
            return [index];
        }
        var locs = new Array(this.shape.length);
        for (var i = 0; i < locs.length - 1; ++i) {
            locs[i] = Math.floor(index / this.strides[i]);
            index -= locs[i] * this.strides[i];
        }
        locs[locs.length - 1] = index;
        return locs;
    };
    Object.defineProperty(TensorBuffer.prototype, "rank", {
        get: function () {
            return this.shape.length;
        },
        enumerable: true,
        configurable: true
    });
    TensorBuffer.prototype.toTensor = function () {
        return Tensor.make(this.shape, { values: this.values }, this.dtype);
    };
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
    ], TensorBuffer.prototype, "set", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
    ], TensorBuffer.prototype, "get", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
    ], TensorBuffer.prototype, "toTensor", null);
    TensorBuffer = __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], TensorBuffer);
    return TensorBuffer;
}());
exports.TensorBuffer = TensorBuffer;
var Tensor = (function () {
    function Tensor(shape, dtype, values, dataId) {
        this.isDisposed = false;
        this.size = util.sizeFromShape(shape);
        if (values != null) {
            util.assert(this.size === values.length, "Constructing tensor of shape (" + this.size + ") should match the " +
                ("length of values (" + values.length + ")"));
        }
        this.shape = shape;
        this.dtype = dtype || 'float32';
        this.strides = computeStrides(shape);
        this.dataId = dataId != null ? dataId : {};
        this.id = Tensor_1.nextId++;
        this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher');
        environment_1.ENV.engine.registerTensor(this);
        if (values != null) {
            environment_1.ENV.engine.write(this.dataId, values);
        }
    }
    Tensor_1 = Tensor;
    Tensor.ones = function (shape, dtype) {
        return ops.ones(shape, dtype);
    };
    Tensor.zeros = function (shape, dtype) {
        return ops.zeros(shape, dtype);
    };
    Tensor.onesLike = function (x) {
        return ops.onesLike(x);
    };
    Tensor.zerosLike = function (x) {
        return ops.zerosLike(x);
    };
    Tensor.like = function (x) {
        return ops.clone(x);
    };
    Tensor.make = function (shape, data, dtype) {
        return new Tensor_1(shape, dtype, data.values, data.dataId);
    };
    Tensor.fromPixels = function (pixels, numChannels) {
        if (numChannels === void 0) { numChannels = 3; }
        return ops.fromPixels(pixels, numChannels);
    };
    Tensor.rand = function (shape, randFunction, dtype) {
        return ops.rand(shape, randFunction, dtype);
    };
    Tensor.randNormal = function (shape, mean, stdDev, dtype, seed) {
        if (mean === void 0) { mean = 0; }
        if (stdDev === void 0) { stdDev = 1; }
        return ops.randomNormal(shape, mean, stdDev, dtype, seed);
    };
    Tensor.randTruncatedNormal = function (shape, mean, stdDev, dtype, seed) {
        if (mean === void 0) { mean = 0; }
        if (stdDev === void 0) { stdDev = 1; }
        return ops.truncatedNormal(shape, mean, stdDev, dtype, seed);
    };
    Tensor.randUniform = function (shape, a, b, dtype) {
        return ops.randomUniform(shape, a, b, dtype);
    };
    Tensor.prototype.flatten = function () {
        this.throwIfDisposed();
        return this.as1D();
    };
    Tensor.prototype.asScalar = function () {
        this.throwIfDisposed();
        util.assert(this.size === 1, 'The array must have only 1 element.');
        return this.reshape([]);
    };
    Tensor.prototype.as1D = function () {
        this.throwIfDisposed();
        return this.reshape([this.size]);
    };
    Tensor.prototype.as2D = function (rows, columns) {
        this.throwIfDisposed();
        return this.reshape([rows, columns]);
    };
    Tensor.prototype.as3D = function (rows, columns, depth) {
        this.throwIfDisposed();
        return this.reshape([rows, columns, depth]);
    };
    Tensor.prototype.as4D = function (rows, columns, depth, depth2) {
        this.throwIfDisposed();
        return this.reshape([rows, columns, depth, depth2]);
    };
    Tensor.prototype.asType = function (dtype) {
        this.throwIfDisposed();
        return ops.cast(this, dtype);
    };
    Object.defineProperty(Tensor.prototype, "rank", {
        get: function () {
            return this.shape.length;
        },
        enumerable: true,
        configurable: true
    });
    Tensor.prototype.get = function () {
        var locs = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            locs[_i] = arguments[_i];
        }
        this.throwIfDisposed();
        if (locs.length === 0) {
            locs = [0];
        }
        var index = locs[locs.length - 1];
        for (var i = 0; i < locs.length - 1; ++i) {
            index += this.strides[i] * locs[i];
        }
        return this.dataSync()[index];
    };
    Tensor.prototype.val = function () {
        var locs = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            locs[_i] = arguments[_i];
        }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (locs.length === 0) {
                            locs = [0];
                        }
                        this.throwIfDisposed();
                        return [4, this.data()];
                    case 1:
                        _a.sent();
                        return [2, this.get.apply(this, locs)];
                }
            });
        });
    };
    Tensor.prototype.locToIndex = function (locs) {
        this.throwIfDisposed();
        if (this.rank === 0) {
            return 0;
        }
        else if (this.rank === 1) {
            return locs[0];
        }
        var index = locs[locs.length - 1];
        for (var i = 0; i < locs.length - 1; ++i) {
            index += this.strides[i] * locs[i];
        }
        return index;
    };
    Tensor.prototype.indexToLoc = function (index) {
        this.throwIfDisposed();
        if (this.rank === 0) {
            return [];
        }
        else if (this.rank === 1) {
            return [index];
        }
        var locs = new Array(this.shape.length);
        for (var i = 0; i < locs.length - 1; ++i) {
            locs[i] = Math.floor(index / this.strides[i]);
            index -= locs[i] * this.strides[i];
        }
        locs[locs.length - 1] = index;
        return locs;
    };
    Tensor.prototype.getValues = function () {
        return this.dataSync();
    };
    Tensor.prototype.getValuesAsync = function () {
        return this.data();
    };
    Tensor.prototype.buffer = function () {
        return ops.buffer(this.shape, this.dtype, this.dataSync());
    };
    Tensor.prototype.data = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.throwIfDisposed();
                return [2, environment_1.ENV.engine.read(this.dataId)];
            });
        });
    };
    Tensor.prototype.dataSync = function () {
        this.throwIfDisposed();
        return environment_1.ENV.engine.readSync(this.dataId);
    };
    Tensor.prototype.dispose = function () {
        if (this.isDisposed) {
            return;
        }
        this.isDisposed = true;
        environment_1.ENV.engine.disposeTensor(this);
    };
    Tensor.prototype.throwIfDisposed = function () {
        if (this.isDisposed) {
            throw new Error("Tensor is disposed.");
        }
    };
    Tensor.prototype.toFloat = function () {
        return this.asType('float32');
    };
    Tensor.prototype.toInt = function () {
        return this.asType('int32');
    };
    Tensor.prototype.toBool = function () {
        return this.asType('bool');
    };
    Tensor.prototype.print = function (verbose) {
        if (verbose === void 0) { verbose = false; }
        return ops.print(this, verbose);
    };
    Tensor.prototype.reshape = function (newShape) {
        this.throwIfDisposed();
        return ops.reshape(this, newShape);
    };
    Tensor.prototype.reshapeAs = function (x) {
        this.throwIfDisposed();
        return this.reshape(x.shape);
    };
    Tensor.prototype.expandDims = function (axis) {
        if (axis === void 0) { axis = 0; }
        return ops.expandDims(this, axis);
    };
    Tensor.prototype.squeeze = function (axis) {
        this.throwIfDisposed();
        return ops.squeeze(this, axis);
    };
    Tensor.prototype.clone = function () {
        this.throwIfDisposed();
        return ops.clone(this);
    };
    Tensor.prototype.tile = function (reps) {
        this.throwIfDisposed();
        return ops.tile(this, reps);
    };
    Tensor.prototype.gather = function (indices, axis) {
        if (axis === void 0) { axis = 0; }
        this.throwIfDisposed();
        return ops.gather(this, indices);
    };
    Tensor.prototype.matMul = function (b, transposeA, transposeB) {
        if (transposeA === void 0) { transposeA = false; }
        if (transposeB === void 0) { transposeB = false; }
        this.throwIfDisposed();
        return ops.matMul(this, b, transposeA, transposeB);
    };
    Tensor.prototype.norm = function (ord, axis, keepDims) {
        if (ord === void 0) { ord = 'euclidean'; }
        if (axis === void 0) { axis = null; }
        if (keepDims === void 0) { keepDims = false; }
        this.throwIfDisposed();
        return ops.norm(this, ord, axis, keepDims);
    };
    Tensor.prototype.slice = function (begin, size) {
        this.throwIfDisposed();
        return ops.slice(this, begin, size);
    };
    Tensor.prototype.reverse = function (axis) {
        this.throwIfDisposed();
        return ops.reverse(this, axis);
    };
    Tensor.prototype.concat = function (x, axis) {
        if (axis === void 0) { axis = 0; }
        this.throwIfDisposed();
        return ops.concat([this, x], axis);
    };
    Tensor.prototype.stack = function (x, axis) {
        if (axis === void 0) { axis = 0; }
        return ops.stack([this, x], axis);
    };
    Tensor.prototype.pad = function (paddings, constantValue) {
        if (constantValue === void 0) { constantValue = 0; }
        return ops.pad(this, paddings, constantValue);
    };
    Tensor.prototype.batchNormalization = function (mean, variance, varianceEpsilon, scale, offset) {
        if (varianceEpsilon === void 0) { varianceEpsilon = .001; }
        this.throwIfDisposed();
        return ops.batchNormalization(this, mean, variance, varianceEpsilon, scale, offset);
    };
    Tensor.prototype.logSumExp = function (axis, keepDims) {
        if (axis === void 0) { axis = null; }
        if (keepDims === void 0) { keepDims = false; }
        this.throwIfDisposed();
        return ops.logSumExp(this, axis, keepDims);
    };
    Tensor.prototype.sum = function (axis, keepDims) {
        if (axis === void 0) { axis = null; }
        if (keepDims === void 0) { keepDims = false; }
        this.throwIfDisposed();
        return ops.sum(this, axis, keepDims);
    };
    Tensor.prototype.mean = function (axis, keepDims) {
        if (axis === void 0) { axis = null; }
        if (keepDims === void 0) { keepDims = false; }
        this.throwIfDisposed();
        return ops.mean(this, axis, keepDims);
    };
    Tensor.prototype.min = function (axis, keepDims) {
        if (axis === void 0) { axis = null; }
        if (keepDims === void 0) { keepDims = false; }
        this.throwIfDisposed();
        return ops.min(this, axis, keepDims);
    };
    Tensor.prototype.max = function (axis, keepDims) {
        if (axis === void 0) { axis = null; }
        if (keepDims === void 0) { keepDims = false; }
        this.throwIfDisposed();
        return ops.max(this, axis, keepDims);
    };
    Tensor.prototype.argMin = function (axis) {
        if (axis === void 0) { axis = null; }
        this.throwIfDisposed();
        return ops.argMin(this, axis);
    };
    Tensor.prototype.argMax = function (axis) {
        if (axis === void 0) { axis = null; }
        this.throwIfDisposed();
        return ops.argMax(this, axis);
    };
    Tensor.prototype.add = function (x) {
        this.throwIfDisposed();
        return ops.add(this, x);
    };
    Tensor.prototype.addStrict = function (x) {
        this.throwIfDisposed();
        return ops.addStrict(this, x);
    };
    Tensor.prototype.sub = function (x) {
        this.throwIfDisposed();
        return ops.sub(this, x);
    };
    Tensor.prototype.subStrict = function (x) {
        this.throwIfDisposed();
        return ops.subStrict(this, x);
    };
    Tensor.prototype.pow = function (exp) {
        this.throwIfDisposed();
        return ops.pow(this, exp);
    };
    Tensor.prototype.powStrict = function (exp) {
        this.throwIfDisposed();
        return ops.powStrict(this, exp);
    };
    Tensor.prototype.mul = function (x) {
        this.throwIfDisposed();
        return ops.mul(this, x);
    };
    Tensor.prototype.mulStrict = function (x) {
        this.throwIfDisposed();
        return ops.mulStrict(this, x);
    };
    Tensor.prototype.div = function (x) {
        this.throwIfDisposed();
        return ops.div(this, x);
    };
    Tensor.prototype.divStrict = function (x) {
        this.throwIfDisposed();
        return ops.divStrict(this, x);
    };
    Tensor.prototype.minimum = function (x) {
        this.throwIfDisposed();
        return ops.minimum(this, x);
    };
    Tensor.prototype.minimumStrict = function (x) {
        this.throwIfDisposed();
        return ops.minimumStrict(this, x);
    };
    Tensor.prototype.maximum = function (x) {
        this.throwIfDisposed();
        return ops.maximum(this, x);
    };
    Tensor.prototype.maximumStrict = function (x) {
        this.throwIfDisposed();
        return ops.maximumStrict(this, x);
    };
    Tensor.prototype.transpose = function (perm) {
        this.throwIfDisposed();
        return ops.transpose(this, perm);
    };
    Tensor.prototype.notEqual = function (x) {
        this.throwIfDisposed();
        return ops.notEqual(this, x);
    };
    Tensor.prototype.notEqualStrict = function (x) {
        this.throwIfDisposed();
        return ops.notEqualStrict(this, x);
    };
    Tensor.prototype.less = function (x) {
        this.throwIfDisposed();
        return ops.less(this, x);
    };
    Tensor.prototype.lessStrict = function (x) {
        this.throwIfDisposed();
        return ops.lessStrict(this, x);
    };
    Tensor.prototype.equal = function (x) {
        this.throwIfDisposed();
        return ops.equal(this, x);
    };
    Tensor.prototype.equalStrict = function (x) {
        this.throwIfDisposed();
        return ops.equalStrict(this, x);
    };
    Tensor.prototype.lessEqual = function (x) {
        this.throwIfDisposed();
        return ops.lessEqual(this, x);
    };
    Tensor.prototype.lessEqualStrict = function (x) {
        this.throwIfDisposed();
        return ops.lessEqualStrict(this, x);
    };
    Tensor.prototype.greater = function (x) {
        this.throwIfDisposed();
        return ops.greater(this, x);
    };
    Tensor.prototype.greaterStrict = function (x) {
        this.throwIfDisposed();
        return ops.greaterStrict(this, x);
    };
    Tensor.prototype.greaterEqual = function (x) {
        this.throwIfDisposed();
        return ops.greaterEqual(this, x);
    };
    Tensor.prototype.greaterEqualStrict = function (x) {
        this.throwIfDisposed();
        return ops.greaterEqualStrict(this, x);
    };
    Tensor.prototype.logicalAnd = function (x) {
        this.throwIfDisposed();
        return ops.logicalAnd(this, x);
    };
    Tensor.prototype.logicalOr = function (x) {
        this.throwIfDisposed();
        return ops.logicalOr(this, x);
    };
    Tensor.prototype.logicalXor = function (x) {
        this.throwIfDisposed();
        return ops.logicalXor(this, x);
    };
    Tensor.prototype.where = function (condition, x) {
        this.throwIfDisposed();
        return ops.where(condition, this, x);
    };
    Tensor.prototype.neg = function () {
        this.throwIfDisposed();
        return ops.neg(this);
    };
    Tensor.prototype.ceil = function () {
        this.throwIfDisposed();
        return ops.ceil(this);
    };
    Tensor.prototype.floor = function () {
        this.throwIfDisposed();
        return ops.floor(this);
    };
    Tensor.prototype.exp = function () {
        this.throwIfDisposed();
        return ops.exp(this);
    };
    Tensor.prototype.log = function () {
        this.throwIfDisposed();
        return ops.log(this);
    };
    Tensor.prototype.sqrt = function () {
        this.throwIfDisposed();
        return ops.sqrt(this);
    };
    Tensor.prototype.square = function () {
        this.throwIfDisposed();
        return ops.square(this);
    };
    Tensor.prototype.abs = function () {
        this.throwIfDisposed();
        return ops.abs(this);
    };
    Tensor.prototype.clipByValue = function (min, max) {
        this.throwIfDisposed();
        return ops.clipByValue(this, min, max);
    };
    Tensor.prototype.relu = function () {
        this.throwIfDisposed();
        return ops.relu(this);
    };
    Tensor.prototype.elu = function () {
        this.throwIfDisposed();
        return ops.elu(this);
    };
    Tensor.prototype.selu = function () {
        this.throwIfDisposed();
        return ops.selu(this);
    };
    Tensor.prototype.leakyRelu = function (alpha) {
        if (alpha === void 0) { alpha = 0.2; }
        this.throwIfDisposed();
        return ops.leakyRelu(this, alpha);
    };
    Tensor.prototype.prelu = function (alpha) {
        this.throwIfDisposed();
        return ops.prelu(this, alpha);
    };
    Tensor.prototype.sigmoid = function () {
        this.throwIfDisposed();
        return ops.sigmoid(this);
    };
    Tensor.prototype.sin = function () {
        this.throwIfDisposed();
        return ops.sin(this);
    };
    Tensor.prototype.cos = function () {
        this.throwIfDisposed();
        return ops.cos(this);
    };
    Tensor.prototype.tan = function () {
        this.throwIfDisposed();
        return ops.tan(this);
    };
    Tensor.prototype.asin = function () {
        this.throwIfDisposed();
        return ops.asin(this);
    };
    Tensor.prototype.acos = function () {
        this.throwIfDisposed();
        return ops.acos(this);
    };
    Tensor.prototype.atan = function () {
        this.throwIfDisposed();
        return ops.atan(this);
    };
    Tensor.prototype.sinh = function () {
        this.throwIfDisposed();
        return ops.sinh(this);
    };
    Tensor.prototype.cosh = function () {
        this.throwIfDisposed();
        return ops.cosh(this);
    };
    Tensor.prototype.tanh = function () {
        this.throwIfDisposed();
        return ops.tanh(this);
    };
    Tensor.prototype.step = function (alpha) {
        if (alpha === void 0) { alpha = 0.0; }
        this.throwIfDisposed();
        return ops.step(this, alpha);
    };
    Tensor.prototype.softmax = function (dim) {
        if (dim === void 0) { dim = -1; }
        this.throwIfDisposed();
        return ops.softmax(this, dim);
    };
    Tensor.prototype.resizeBilinear = function (newShape2D, alignCorners) {
        if (alignCorners === void 0) { alignCorners = false; }
        this.throwIfDisposed();
        return ops.image.resizeBilinear(this, newShape2D, alignCorners);
    };
    Tensor.prototype.conv1d = function (filter, stride, pad, dimRoundingMode) {
        this.throwIfDisposed();
        return ops.conv1d(this, filter, stride, pad, dimRoundingMode);
    };
    Tensor.prototype.conv2d = function (filter, strides, pad, dimRoundingMode) {
        this.throwIfDisposed();
        return ops.conv2d(this, filter, strides, pad, dimRoundingMode);
    };
    Tensor.prototype.conv2dTranspose = function (filter, outputShape, strides, pad, dimRoundingMode) {
        this.throwIfDisposed();
        return ops.conv2dTranspose(this, filter, outputShape, strides, pad, dimRoundingMode);
    };
    Tensor.prototype.depthwiseConv2D = function (filter, strides, pad, rates, dimRoundingMode) {
        if (rates === void 0) { rates = [1, 1]; }
        this.throwIfDisposed();
        return ops.depthwiseConv2d(this, filter, strides, pad, rates, dimRoundingMode);
    };
    Tensor.prototype.avgPool = function (filterSize, strides, pad, dimRoundingMode) {
        this.throwIfDisposed();
        return ops.avgPool(this, filterSize, strides, pad, dimRoundingMode);
    };
    Tensor.prototype.maxPool = function (filterSize, strides, pad, dimRoundingMode) {
        this.throwIfDisposed();
        return ops.maxPool(this, filterSize, strides, pad, dimRoundingMode);
    };
    Tensor.prototype.minPool = function (filterSize, strides, pad, dimRoundingMode) {
        this.throwIfDisposed();
        return ops.minPool(this, filterSize, strides, pad, dimRoundingMode);
    };
    Tensor.prototype.localResponseNormalization = function (radius, bias, alpha, beta, normRegion) {
        if (radius === void 0) { radius = 5; }
        if (bias === void 0) { bias = 1; }
        if (alpha === void 0) { alpha = 1; }
        if (beta === void 0) { beta = 0.5; }
        if (normRegion === void 0) { normRegion = 'acrossChannels'; }
        return ops.localResponseNormalization(this, radius, bias, alpha, beta, normRegion);
    };
    Tensor.prototype.variable = function (trainable, name, dtype) {
        if (trainable === void 0) { trainable = true; }
        this.throwIfDisposed();
        return Variable.variable(this, trainable, name, dtype);
    };
    Tensor.nextId = 0;
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "flatten", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "asScalar", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "as1D", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "as2D", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "as3D", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "as4D", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "asType", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "buffer", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "data", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "dataSync", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "dispose", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "toFloat", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "toInt", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "toBool", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "print", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "reshape", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "reshapeAs", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "expandDims", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "squeeze", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor.prototype, "clone", null);
    Tensor = Tensor_1 = __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Tensor);
    return Tensor;
    var Tensor_1;
}());
exports.Tensor = Tensor;
exports.NDArray = Tensor;
var Scalar = (function (_super) {
    __extends(Scalar, _super);
    function Scalar() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Scalar.new = function (value, dtype) {
        return ops.scalar(value, dtype);
    };
    return Scalar;
}(Tensor));
exports.Scalar = Scalar;
var Tensor1D = (function (_super) {
    __extends(Tensor1D, _super);
    function Tensor1D() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Tensor1D.new = function (values, dtype) {
        return ops.tensor1d(values, dtype);
    };
    return Tensor1D;
}(Tensor));
exports.Tensor1D = Tensor1D;
exports.Array1D = Tensor1D;
var Tensor2D = (function (_super) {
    __extends(Tensor2D, _super);
    function Tensor2D() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Tensor2D.new = function (shape, values, dtype) {
        return ops.tensor2d(values, shape, dtype);
    };
    return Tensor2D;
}(Tensor));
exports.Tensor2D = Tensor2D;
exports.Array2D = Tensor2D;
var Tensor3D = (function (_super) {
    __extends(Tensor3D, _super);
    function Tensor3D() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Tensor3D.new = function (shape, values, dtype) {
        return ops.tensor3d(values, shape, dtype);
    };
    return Tensor3D;
}(Tensor));
exports.Tensor3D = Tensor3D;
exports.Array3D = Tensor3D;
var Tensor4D = (function (_super) {
    __extends(Tensor4D, _super);
    function Tensor4D() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Tensor4D.new = function (shape, values, dtype) {
        return ops.tensor4d(values, shape, dtype);
    };
    return Tensor4D;
}(Tensor));
exports.Tensor4D = Tensor4D;
exports.Array4D = Tensor4D;
var Variable = (function (_super) {
    __extends(Variable, _super);
    function Variable(initialValue, trainable, name) {
        if (trainable === void 0) { trainable = true; }
        var _this = _super.call(this, initialValue.shape, initialValue.dtype, null, initialValue.dataId) || this;
        _this.trainable = trainable;
        _this.name = name;
        if (_this.name == null) {
            _this.name = Variable_1.nextVarId.toString();
            Variable_1.nextVarId++;
        }
        environment_1.ENV.engine.registerVariable(_this);
        return _this;
    }
    Variable_1 = Variable;
    Variable.variable = function (initialValue, trainable, name, dtype) {
        if (trainable === void 0) { trainable = true; }
        if (dtype != null && dtype !== initialValue.dtype) {
            initialValue = initialValue.asType(dtype);
        }
        return new Variable_1(initialValue, trainable, name);
    };
    Variable.prototype.assign = function (newValue) {
        if (newValue.dtype !== this.dtype) {
            throw new Error("dtype of the new value (" + newValue.dtype + ") and " +
                ("previous value (" + this.dtype + ") must match"));
        }
        if (!util.arraysEqual(newValue.shape, this.shape)) {
            throw new Error("shape of the new value (" + newValue.shape + ") and " +
                ("previous value (" + this.shape + ") must match"));
        }
        environment_1.ENV.engine.disposeTensor(this);
        this.dataId = newValue.dataId;
        environment_1.ENV.engine.registerTensor(this);
    };
    Variable.nextVarId = 0;
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Variable.prototype, "assign", null);
    __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
    ], Variable, "variable", null);
    Variable = Variable_1 = __decorate([
        doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
    ], Variable);
    return Variable;
    var Variable_1;
}(Tensor));
exports.Variable = Variable;
var variable = Variable.variable;
exports.variable = variable;
function computeStrides(shape) {
    var rank = shape.length;
    if (rank < 2) {
        return [];
    }
    var strides = new Array(rank - 1);
    strides[rank - 2] = shape[rank - 1];
    for (var i = rank - 3; i >= 0; --i) {
        strides[i] = strides[i + 1] * shape[i + 1];
    }
    return strides;
}


text:
namespace Machete.Values.Converters
{
    using System.Diagnostics;
    using System.Globalization;

    public class DecimalValueConverter :
        IValueConverter<decimal>
    {
        public DecimalValueConverter()
        {
            Styles = NumberStyles.Any;
        }

        public NumberStyles Styles { get; set; }

        public bool TryConvert(TextSlice slice, out Value<decimal> convertedValue)
        {
            Debug.Assert(slice != null);

            if (decimal.TryParse(slice.Text.ToString(), Styles, CultureInfo.InvariantCulture, out var value))
            {
                convertedValue = new ConvertedValue<decimal>(slice.SourceText, slice.SourceSpan, value);
                return true;
            }

            convertedValue = null;
            return false;
        }
    }
}


text:
package com.jess.arms.integration;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jess.arms.integration.cache.Cache;
import com.jess.arms.integration.cache.CacheType;
import com.jess.arms.mvp.IModel;
import com.jess.arms.utils.Preconditions;

import java.lang.reflect.Proxy;

import javax.inject.Inject;
import javax.inject.Singleton;

import dagger.Lazy;
import io.rx_cache2.internal.RxCache;
import retrofit2.Retrofit;

/**
 * ================================================
 * 用来管理网络请求层,以及数据缓存层,以后可能添加数据库请求层
 * 提供给 {@link IModel} 层必要的 Api 做数据处理
 *
 * @see RepositoryManager wiki 官方文档
 * Created by JessYan on 13/04/2017 09:52
 * Contact me
 * Follow me
 * ================================================
 */
@SuppressWarnings("unchecked")
@Singleton
public class RepositoryManager implements IRepositoryManager {

    @Inject
    Lazy<Retrofit> mRetrofit;
    @Inject
    Lazy<RxCache> mRxCache;
    @Inject
    Application mApplication;
    @Inject
    Cache.Factory mCacheFactory;
    @Inject
    @Nullable
    ObtainServiceDelegate mObtainServiceDelegate;
    private Cache<String, Object> mRetrofitServiceCache;
    private Cache<String, Object> mCacheServiceCache;

    @Inject
    public RepositoryManager() {
    }

    /**
     * 根据传入的 Class 获取对应的 Retrofit service
     *
     * @param serviceClass ApiService class
     * @param <T>          ApiService class
     * @return ApiService
     */
    @NonNull
    @Override
    public synchronized <T> T obtainRetrofitService(@NonNull Class<T> serviceClass) {
        if (mRetrofitServiceCache == null) {
            mRetrofitServiceCache = mCacheFactory.build(CacheType.RETROFIT_SERVICE_CACHE);
        }
        Preconditions.checkNotNull(mRetrofitServiceCache,
                "Cannot return null from a Cache.Factory#build(int) method");
        T retrofitService = (T) mRetrofitServiceCache.get(serviceClass.getCanonicalName());
        if (retrofitService == null) {
            if (mObtainServiceDelegate != null) {
                retrofitService = mObtainServiceDelegate.createRetrofitService(
                        mRetrofit.get(), serviceClass);
            }
            if (retrofitService == null) {
                retrofitService = (T) Proxy.newProxyInstance(
                        serviceClass.getClassLoader(),
                        new Class[]{serviceClass},
                        new RetrofitServiceProxyHandler(mRetrofit.get(), serviceClass));
            }
            mRetrofitServiceCache.put(serviceClass.getCanonicalName(), retrofitService);
        }
        return retrofitService;
    }

    /**
     * 根据传入的 Class 获取对应的 RxCache service
     *
     * @param cacheClass Cache class
     * @param <T>        Cache class
     * @return Cache
     */
    @NonNull
    @Override
    public synchronized <T> T obtainCacheService(@NonNull Class<T> cacheClass) {
        Preconditions.checkNotNull(cacheClass, "cacheClass == null");
        if (mCacheServiceCache == null) {
            mCacheServiceCache = mCacheFactory.build(CacheType.CACHE_SERVICE_CACHE);
        }
        Preconditions.checkNotNull(mCacheServiceCache,
                "Cannot return null from a Cache.Factory#build(int) method");
        T cacheService = (T) mCacheServiceCache.get(cacheClass.getCanonicalName());
        if (cacheService == null) {
            cacheService = mRxCache.get().using(cacheClass);
            mCacheServiceCache.put(cacheClass.getCanonicalName(), cacheService);
        }
        return cacheService;
    }

    /**
     * 清理所有缓存
     */
    @Override
    public void clearAllCache() {
        mRxCache.get().evictAll().subscribe();
    }

    @NonNull
    @Override
    public Context getContext() {
        return mApplication;
    }
}


text:
package javassist.bytecode.stackmap;

import javassist.bytecode.StackMapTable;

public interface TypeTag {
    TypeData TOP = null;
    TypeData INTEGER = new TypeData.BasicType("int", StackMapTable.INTEGER);
    TypeData FLOAT = new TypeData.BasicType("float", StackMapTable.FLOAT);
    TypeData DOUBLE = new TypeData.BasicType("double", StackMapTable.DOUBLE);
    TypeData LONG = new TypeData.BasicType("long", StackMapTable.LONG);

    // and NULL, THIS, OBJECT, UNINIT
}


text:
import React from 'react'
import DuckImage from '../assets/Duck.jpg'
import classes from './HomeView.scss'

export const HomeView = () => (

Welcome!

)

export default HomeView


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mono.Cecil;
using Mono.Cecil.Rocks;

namespace CodeContracts.Fody.Internal
{
    /// <summary>
    /// Contains extension methods for <see cref="MethodReference"/> and <see cref="MethodDefinition"/>
    /// </summary>
    internal static class MethodReferenceExtensions
    {
        /// <summary>
        /// Method that answer does specified <paramref name="method"/> overrides <paramref name="overridden"/>
        /// </summary>
        /// <param name="method">Method that overrides another method</param>
        /// <param name="overridden">Method that overriden by another method</param>
        /// <returns>Does method <paramref name="method"/> overrides method <paramref name="overridden"/></returns>
        public static bool IsOverride(this MethodDefinition method, MethodReference overridden)
        {
            Contract.Requires(method != null);
            Contract.Requires(overridden != null);

            return method.Overrides.Contains(overridden) ||
                   method.GetOriginalBaseMethod().Equals(overridden) ||
                   method.Name.Equals(overridden.Name) &&
                   overridden.DeclaringType.Resolve().IsInterface &&
                   method.DeclaringType.Interfaces.Contains(overridden.DeclaringType) &&
                   !method.DeclaringType.Methods.SelectMany(m => m.Overrides).Contains(overridden) &&
                   method.Parameters.Select(p => p.ParameterType).SequenceEqual(overridden.Parameters.Select(p => p.ParameterType));
        }

        /// <summary>
        /// Creates new closed generic method that maked from open generic method with specified types
        /// </summary>
        /// <param name="methodReference">Open generic method</param>
        /// <param name="genericTypeReferences">Types for closes open generic method</param>
        /// <returns>Closed generic method</returns>
        public static MethodReference MakeGeneric(this MethodReference methodReference, params TypeReference[] genericTypeReferences)
        {
            Contract.Requires(methodReference != null);
            Contract.Requires(genericTypeReferences != null);
            Contract.Ensures(Contract.Result<MethodReference>() != null);

            var genericMethodReference = new GenericInstanceMethod(methodReference);
            genericMethodReference.GenericArguments.AddRange(genericTypeReferences);

            return genericMethodReference;
        }
    }
}


text:
function toParser(p) {
    return p == "string" ? token() : p;
}
function sequence() {
    toParser(arguments[0]);
}
function choice() {
    return function () {
        {
            var parser = toParser();
            var result = parser();
        }
    };
}
function butnot() {
    return function () {
        var p2 = toParser();
        var br = p2();
    };
}
function optional() {
    var p = toParser();
    return function () {
        var r = p();
    };
}
function assertParseFailed(parser) {
    try {
        var result = parser();
    } catch (e) {
    }
}
sequence();
assertParseFailed(toParser(choice()));
assertParseFailed(sequence(optional()));
sequence(optional());
assertParseFailed(butnot());


text:
package pl.com.agora.kornaja.repository;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import pl.com.agora.kornaja.domain.User;
import pl.com.agora.kornaja.domain.UserGroup;

import java.util.List;

/**
 * Created by P on 2015-11-23.
 */
@Repository
public interface UserCrudRepository extends CrudRepository<User,Long> {

    User findUserByLogin(String login);

    List<User> findUsersByUserGroups(UserGroup userGroup);

    @Query("select user from User user inner join user.userGroups groups where groups.id = :id")
    List<User> findUsersByUserGroups(@Param("id") Long id);

}


text:
<?php

namespace Wps\Contracts;

interface Brand
{

}


text:
These settings apply only when `--go` is specified on the command line.

``` yaml $(go) && !$(track2)
go:
  license-header: MICROSOFT_MIT_NO_VERSION
  namespace: datadog
  clear-output-folder: true
```

``` yaml $(go) && $(track2)
license-header: MICROSOFT_MIT_NO_VERSION
module-name: sdk/resourcemanager/datadog/armdatadog
module: github.com/Azure/azure-sdk-for-go/$(module-name)
output-folder: $(go-sdk-folder)/$(module-name)
azure-arm: true
```

### Go multi-api

``` yaml $(go) && $(multiapi)
batch:
  - tag: package-2021-03
  - tag: package-2020-02-preview
```

### Tag: package-2021-03 and go

These settings apply only when `--tag=package-2021-03 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2021-03' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2021-03-01/$(namespace)
```

### Tag: package-2020-02-preview and go

These settings apply only when `--tag=package-2020-02-preview --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2020-02-preview' && $(go)
output-folder: $(go-sdk-folder)/services/preview/$(namespace)/mgmt/2020-02-01-preview/$(namespace)
```


text:
package Paws::OpsWorks::CreateUserProfile;
  use Moose;
  has AllowSelfManagement => (is => 'ro', isa => 'Bool');
  has IamUserArn => (is => 'ro', isa => 'Str', required => 1);
  has SshPublicKey => (is => 'ro', isa => 'Str');
  has SshUsername => (is => 'ro', isa => 'Str');

  use MooseX::ClassAttribute;

  class_has _api_call => (isa => 'Str', is => 'ro', default => 'CreateUserProfile');
  class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::OpsWorks::CreateUserProfileResult');
  class_has _result_key => (isa => 'Str', is => 'ro');
1;

### main pod documentation begin ###

=head1 NAME

Paws::OpsWorks::CreateUserProfile - Arguments for method CreateUserProfile on Paws::OpsWorks

=head1 DESCRIPTION

This class represents the parameters used for calling the method CreateUserProfile on the
AWS OpsWorks service. Use the attributes of this class
as arguments to method CreateUserProfile.

You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to CreateUserProfile.

As an example:

  $service_obj->CreateUserProfile(Att1 => $value1, Att2 => $value2, ...);

Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.

=head1 ATTRIBUTES

=head2 AllowSelfManagement => Bool

Whether users can specify their own SSH public key through the My
Settings page. For more information, see Setting an IAM User's Public
SSH Key.

=head2 B<REQUIRED> IamUserArn => Str

The user's IAM ARN; this can also be a federated user's ARN.

=head2 SshPublicKey => Str

The user's public SSH key.

=head2 SshUsername => Str

The user's SSH user name. The allowable characters are [a-z], [A-Z],
[0-9], '-', and '_'. If the specified name includes other punctuation
marks, AWS OpsWorks Stacks removes them. For example, C<my.name> will
be changed to C<myname>. If you do not specify an SSH user name, AWS
OpsWorks Stacks generates one from the IAM user name.

=head1 SEE ALSO

This class forms part of L<Paws>, documenting arguments for method CreateUserProfile in L<Paws::OpsWorks>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
<?php

namespace LinkORB\Component\FileList\Driver;

use LinkORB\Component\FileList\File;
use LinkORB\Component\FileList\FileList;

class FileSystemDriver implements DriverInterface
{
    protected $path;

    public function __construct($path)
    {

        $path =rtrim($path, '/');
        $this->path = $path;
    }

    protected function getFullPath($key)
    {
        $fullpath = $this->path . '/' . str_replace('.', '/', $key);
        //exit("key:$key so fullpath=[$fullpath]");
        return $fullpath;
    }

    private function ensurePath($path)
    {
        if (file_exists($path)) {
            return true;
        }
        mkdir($path, 0777, true);
    }

    public function getFilesInList($filelist)
    {
        $fullpath = $this->getFullPath($filelist->getKey());
        $dirfiles = glob($fullpath . '/*');

        if (!file_exists($fullpath)) {
            return array();
        }

        foreach ($dirfiles as $filename) {
            $file = new File($filelist, basename($filename));
            $files[] = $file;
        }
        return $files;
    }

    public function set($filelist, $filename, $data)
    {
        $fullpath = $this->getFullPath($filelist->getKey());
        $this->ensurePath($fullpath);
        file_put_contents($fullpath . '/' . $filename, $data);
    }

    public function get($filelist, $filename)
    {
        $fullpath = $this->getFullPath($filelist->getKey());
        $data = file_get_contents($fullpath . '/' . $filename);
        return $data;
    }

    public function delete($filelist, $filename)
    {
        $fullpath = $this->getFullPath($filelist->getKey());
        unlink($fullpath . '/' . $filename);
    }

    public function getFileListByKey($key)
    {
        return new FileList($key, $this);
    }

}


text:
package org.apache.hadoop.yarn.factories;

import java.net.InetSocketAddress;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.YarnException;

public interface RpcClientFactory {

  public Object getClient(Class<?> protocol, long clientVersion,
      InetSocketAddress addr, Configuration conf) throws YarnException;

  public void stopClient(Object proxy);

}


text:
package org.radargun.stages;

import org.radargun.StageResult;
import org.radargun.config.Property;
import org.radargun.config.Stage;

@Stage(doc = "Allows to system out messages for more readable logs.")
public class EchoStage extends AbstractMainStage {
   @Property(optional = false, doc = "Message to be printed.")
   private String message;

   @Override
   public StageResult execute() {
      log.info(message);

      return StageResult.SUCCESS;
   }
}


text:
<?php

namespace Benmag\Rancher\Factories\Api;

use \Benmag\Rancher\Factories\Entity\Project as ProjectEntity;

/**
 * Rancher API wrapper for Laravel
 *
 * @package  Rancher
 * @author   @benmagg
 */
class Project extends AbstractApi implements \Benmag\Rancher\Contracts\Api\Project
{

    /**
     * The class of the entity we are working with
     *
     * @var Container
     */
    protected $class = ProjectEntity::class;

    /**
     * The Rancher API endpoint of the resource type.
     *
     * @var string
     */
    protected $endpoint = "projects";

    /**
     * {@inheritdoc}
     */
    public function create(ProjectEntity $project)
    {

        // Data
        $data = $project->toArray();

        // Send "create" project request
        $project = $this->client->post($this->getEndpoint(), $data);

        // Parse response
        $project = json_decode($project);

        // Create ContainerEntity from response
        return new ProjectEntity($project);

    }

    /**
     * {@inheritdoc}
     */
    public function delete($id)
    {

        // Send "stop" container request
        $project = $this->client->delete($this->getEndpoint()."/".$id);

        // Parse response
        $project = json_decode($project);

        // Create ContainerEntity from response
        return new ProjectEntity($project);

    }

    /**
     * {@inheritdoc}
     */
    public function remove($id)
    {

        // Send "remove" container request
        $project = $this->client->post($this->getEndpoint()."/".$id, ['action' => 'remove']);

        // Parse response
        $project = json_decode($project);

        // Create ContainerEntity from response
        return new ProjectEntity($project);

    }

    /**
     * {@inheritdoc}
     */
    public function activate($id)
    {

        // Send "stop" container request
        $project = $this->client->post($this->getEndpoint()."/".$id, ['action' => 'activate']);

        // Parse response
        $project = json_decode($project);

        // Create ContainerEntity from response
        return new ProjectEntity($project);

    }

    /**
     * {@inheritdoc}
     */
    public function deactivate($id)
    {

        // Send "stop" container request
        $project = $this->client->post($this->getEndpoint()."/".$id, ['action' => 'deactivate']);

        // Parse response
        $project = json_decode($project);

        // Create ContainerEntity from response
        return new ProjectEntity($project);

    }

    /**
     * {@inheritdoc}
     */
    public function setMembers($id, array $members)
    {
        // TODO
        // I can't figure this out just yet. I think it has something to do
        // with different access permissions for different environments/entities.
        //
        // This is confusing as hell because for some endpoints you need to unauthorise
        // and with this you might need to potentially authorise with a specific key...
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.codepoetics</groupId>
    <artifactId>centipede</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <properties>
        <kotlin.version>1.1.0-beta-17</kotlin.version>
        <main.class>com.codepoetics.centipede.CentipedeKt</main.class>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib</artifactId>
            <version>${kotlin.version}</version>
        </dependency>

        <dependency>
            <groupId>io.kotlintest</groupId>
            <artifactId>kotlintest</artifactId>
            <version>1.3.6</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>test-compile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals> <goal>single</goal> </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>${main.class}</mainClass>
                                </manifest>
                            </archive>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>bintray</id>
            <url>http://dl.bintray.com/kotlin/kotlin-eap-1.1/</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>bintray</id>
            <url>http://dl.bintray.com/kotlin/kotlin-eap-1.1/</url>
        </pluginRepository>
    </pluginRepositories>

</project>


text:
require 'gulp/pipeline/rails/assets'

module Gulp
  module Pipeline
    module Rails
      module Patches
        module MetaRequestMiddlewaresHeaders
          def asset?(path)
            @app_config.respond_to?(:assets) && Assets.path_starts_with?(path)
          end
        end
      end
    end
  end
end


text:
<?php

namespace Tm\TeambuilderBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;

class RegleType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nombre',                'integer')
            ->add('typeRegle', 'choice', array(
                'choices' => array(
                    'caracteristique' => 'Caractéristique',
                    'typeAttaque' => 'Type d\'attaque'
                ),
                'required'    => true,
                'empty_value' => 'Choisissez une option',
                'empty_data'  => null,
                'mapped'     => false
            ))
            ->add('caracteristique', 'entity', array(
                'class' => 'TmTeambuilderBundle:Caracteristique',
                'property' => 'libelle',
                'multiple' => false,
                'expanded' => false,
                'required' => false,
                'empty_value' => 'Choisissez une option',
            ))
            ->add('typeAttaque', 'entity', array(
                'class' => 'TmTeambuilderBundle:TypeAttaque',
                'property' => 'libelle',
                'multiple' => false,
                'expanded' => false,
                'required' => false,
                'empty_value' => 'Choisissez une option',
            ))
            ->add('operation', 'entity', array(
                'class' => 'TmTeambuilderBundle:Operation',
                'property' => 'libelle',
                'multiple' => false,
                'expanded' => false,
                'required' => true,
            ));
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Tm\TeambuilderBundle\Entity\Regle'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'tm_teambuilderbundle_regle';
    }
}


text:
package cloudade.server.auth.mongo.oauth.repositories;

import static org.springframework.data.mongodb.core.query.Criteria.where;

import java.util.Collection;
import java.util.List;

import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import cloudade.server.auth.mongo.oauth.domain.MongoApproval;

import com.mongodb.WriteResult;

@Component
public class MongoApprovalRepositoryImpl implements MongoApprovalRepositoryBase {

	private final MongoTemplate mongoTemplate;

	@Autowired
	public MongoApprovalRepositoryImpl(final MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}

	@Override
	public boolean updateOrCreate(final Collection<MongoApproval> mongoApprovals) {
		boolean result = true;
		for (MongoApproval mongoApproval : mongoApprovals) {
			final Update update = Update
					.update("expiresAt", mongoApproval.getExpiresAt())
					.addToSet("status", mongoApproval.getStatus())
					.addToSet("lastModifiedAt",
							mongoApproval.getLastUpdatedAt());

			final WriteResult writeResult = mongoTemplate.upsert(
					byUserIdAndClientIdAndScope(mongoApproval), update,
					MongoApproval.class);

			if (writeResult.getN() != 1) {
				result = false;
			}
		}
		return result;
	}

	@Override
	public boolean updateExpiresAt(final LocalDate expiresAt,
			final MongoApproval mongoApproval) {
		final Update update = Update.update("expiresAt", expiresAt);

		final WriteResult writeResult = mongoTemplate.updateFirst(
				byUserIdAndClientIdAndScope(mongoApproval), update,
				MongoApproval.class);

		return writeResult.getN() == 1;
	}

	@Override
	public boolean deleteByUserIdAndClientIdAndScope(
			final MongoApproval mongoApproval) {
		final WriteResult writeResult = mongoTemplate
				.remove(byUserIdAndClientIdAndScope(mongoApproval),
						MongoApproval.class);

		return writeResult.getN() == 1;
	}

	@Override
	public List<MongoApproval> findByUserIdAndClientId(final String userId,
			final String clientId) {
		final Query query = Query.query(where("userId").is(userId).andOperator(
				where("clientId").is(clientId)));
		return mongoTemplate.find(query, MongoApproval.class);
	}

	private Query byUserIdAndClientIdAndScope(final MongoApproval mongoApproval) {
		return Query.query(where("userId").is(mongoApproval.getUserId())
				.andOperator(
						where("clientId").is(mongoApproval.getClientId())
								.andOperator(
										where("scope").is(
												mongoApproval.getScope()))));
	}
}


text:
@interface SMScrollView ()
@property (nonatomic, assign) CGSize prevBoundsSize;
@property (nonatomic, assign) CGPoint prevContentOffset;
@property (nonatomic, strong, readwrite) UIView *viewForZooming;
@property (nonatomic, strong, readwrite) UITapGestureRecognizer *doubleTapGestureRecognizer;
@end

@implementation SMScrollView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self performInitialisation];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self performInitialisation];
    }
    return self;
}

- (void)performInitialisation {
    // Set the prevBoundsSize to the initial bounds, so the first time layoutSubviews
    // is called we won't do any contentOffset adjustments
    self.prevBoundsSize = self.bounds.size;
    self.prevContentOffset = self.contentOffset;
    self.fitOnSizeChange = NO;
    self.upscaleToFitOnSizeChange = YES;
    self.stickToBounds = NO;
    self.centerZoomingView = YES;

    // Add double-tap-gesture-recognizer to zoom in and out when user double taps.
    self.doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_doubleTapped:)];
    self.doubleTapGestureRecognizer.numberOfTapsRequired = 2;
    [self addGestureRecognizer:self.doubleTapGestureRecognizer];
}

- (void)setContentSize:(CGSize)contentSize {
    [super setContentSize:contentSize];
    [self _centerScrollViewContent];
}

- (void)setZoomScale:(CGFloat)zoomScale {
    [super setZoomScale:zoomScale];
    // On iPhone 6+ iOS8, after setting zoomScale content, the contentSize becomes slightly bigger than bounds (e.g. 0.00001)
    self.contentSize = CGSizeMake(floorf(self.contentSize.width), floorf(self.contentSize.height));
}

- (void)scaleToFit {
    if (![self.delegate respondsToSelector:@selector(viewForZoomingInScrollView:)]) return;
    [self _setMinimumZoomScaleToFit];
    self.zoomScale = self.minimumZoomScale;
}

- (void)addViewForZooming:(UIView *)view {
    if (self.viewForZooming) {
        [self.viewForZooming removeFromSuperview];
    }
    self.viewForZooming = view;
    [self addSubview:self.viewForZooming];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    if (!CGSizeEqualToSize(self.prevBoundsSize, self.bounds.size)) {
        if (self.fitOnSizeChange) {
            [self scaleToFit];
        } else {
            [self _adjustContentOffset];
        }
        self.prevBoundsSize = self.bounds.size;
    }
    self.prevContentOffset = self.contentOffset;

    [self _centerScrollViewContent];
}

- (void)_centerScrollViewContent {
    if (self.centerZoomingView && [self.delegate respondsToSelector:@selector(viewForZoomingInScrollView:)]) {
        UIView *zoomView = [self.delegate viewForZoomingInScrollView:self];

        CGRect frame = zoomView.frame;
        if (self.contentSize.width < self.bounds.size.width) {
            frame.origin.x = roundf((self.bounds.size.width - self.contentSize.width) / 2);
        } else {
            frame.origin.x = 0;
        }
        if (self.contentSize.height < self.bounds.size.height) {
            frame.origin.y = roundf((self.bounds.size.height - self.contentSize.height) / 2);
        } else {
            frame.origin.y = 0;
        }
        zoomView.frame = frame;
    }
}

- (void)_adjustContentOffset {
    if ([self.delegate respondsToSelector:@selector(viewForZoomingInScrollView:)]) {
        UIView *zoomView = [self.delegate viewForZoomingInScrollView:self];

        // Using contentOffset and bounds values before the bounds were changed (e.g.: interface orientation change),
        // find the visible center point in the unscaled coordinate space of the zooming view.
        CGPoint prevCenterPoint = (CGPoint){
            .x = (self.prevContentOffset.x + roundf(self.prevBoundsSize.width / 2) - zoomView.frame.origin.x) / self.zoomScale,
            .y = (self.prevContentOffset.y + roundf(self.prevBoundsSize.height / 2) - zoomView.frame.origin.y) / self.zoomScale,
        };

        if (self.stickToBounds) {
            if (self.contentSize.width > self.prevBoundsSize.width) {
                if (self.prevContentOffset.x == 0) {
                    prevCenterPoint.x = 0;
                } else if (self.prevContentOffset.x + self.prevBoundsSize.width == roundf(self.contentSize.width)) {
                    prevCenterPoint.x = zoomView.bounds.size.width;
                }
            }
            if (self.contentSize.height > self.prevBoundsSize.height) {
                if (self.prevContentOffset.y == 0) {
                    prevCenterPoint.y = 0;
                } else if (self.prevContentOffset.y + self.prevBoundsSize.height == roundf(self.contentSize.height)) {
                    prevCenterPoint.y = zoomView.bounds.size.height;
                }
            }
        }

        // If the size of the scrollView was changed such that the minimumZoomScale is increased
        if (self.upscaleToFitOnSizeChange) {
            [self _increaseScaleIfNeeded];
        }

        // Calculate new contentOffset using the previously calculated center point and the new contentOffset and bounds values.
        CGPoint contentOffset = CGPointMake(0.0, 0.0);
        CGRect frame = zoomView.frame;
        if (self.contentSize.width > self.bounds.size.width) {
            frame.origin.x = 0;
            contentOffset.x = prevCenterPoint.x * self.zoomScale - roundf(self.bounds.size.width / 2);
            if (contentOffset.x < 0) {
                contentOffset.x = 0;
            } else if (contentOffset.x > self.contentSize.width - self.bounds.size.width) {
                contentOffset.x = self.contentSize.width - self.bounds.size.width;
            }
        }
        if (self.contentSize.height > self.bounds.size.height) {
            frame.origin.y = 0;
            contentOffset.y = prevCenterPoint.y * self.zoomScale - roundf(self.bounds.size.height / 2);
            if (contentOffset.y < 0) {
                contentOffset.y = 0;
            } else if (contentOffset.y > self.contentSize.height - self.bounds.size.height) {
                contentOffset.y = self.contentSize.height - self.bounds.size.height;
            }
        }
        zoomView.frame = frame;
        self.contentOffset = contentOffset;
    }
}

- (void)_increaseScaleIfNeeded {
    [self _setMinimumZoomScaleToFit];
    if (self.zoomScale < self.minimumZoomScale) {
        self.zoomScale = self.minimumZoomScale;
    }
}

- (void)_setMinimumZoomScaleToFit {
    UIView *zoomView = [self.delegate viewForZoomingInScrollView:self];
    CGSize scrollViewSize = self.bounds.size;
    CGSize zoomViewSize = zoomView.bounds.size;

    CGFloat scaleToFit = fminf(scrollViewSize.width / zoomViewSize.width, scrollViewSize.height / zoomViewSize.height);
    if (scaleToFit > 1.0) {
        scaleToFit = 1.0;
    }
    self.minimumZoomScale = scaleToFit;
}

- (void)_doubleTapped:(UIGestureRecognizer *)gestureRecognizer {
    if ([self.delegate respondsToSelector:@selector(viewForZoomingInScrollView:)]) {
        UIView *zoomView = [self.delegate viewForZoomingInScrollView:self];

        if (self.zoomScale == self.minimumZoomScale) {
            // When user double-taps on the scrollView while it is zoomed out, zoom-in
            CGFloat newScale = self.maximumZoomScale;
            CGPoint centerPoint = [gestureRecognizer locationInView:zoomView];
            CGRect zoomRect = [self _zoomRectInView:self forScale:newScale withCenter:centerPoint];
            [self zoomToRect:zoomRect animated:YES];
        } else {
            // When user double-taps on the scrollView while it is zoomed, zoom-out
            [self setZoomScale:self.minimumZoomScale animated:YES];
        }
    }
}

- (CGRect)_zoomRectInView:(UIView *)view forScale:(CGFloat)scale withCenter:(CGPoint)center {

    CGRect zoomRect;

    // The zoom rect is in the content view's coordinates.
    // At a zoom scale of 1.0, it would be the size of the scrollView's bounds.
    // As the zoom scale decreases, so more content is visible, the size of the rect grows.
    zoomRect.size.height = view.bounds.size.height / scale;
    zoomRect.size.width = view.bounds.size.width / scale;

    // choose an origin so as to get the right center.
    zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);

    return zoomRect;
}

@end


text:
from nose2.tools import such

with such.A('test scenario with errors') as it:

    @it.has_teardown
    def teardown_fail():
        raise RuntimeError('Bad Error in such tearDown!')

    @it.should('check that value == 1')
    def test_passes(case):
        pass

it.createTests(globals())


text:
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

'''
This is an example showing how to create an export file from
an existing chat bot that can then be used to train other bots.
'''

chatbot = ChatBot('Export Example Bot')

# First, lets train our bot with some data
trainer = ChatterBotCorpusTrainer(chatbot)

trainer.train('chatterbot.corpus.english')

# Now we can export the data to a file
trainer.export_for_training('./my_export.json')


text:
<?php
/*
 *  Required object values:
 *  data -
 */

class mailSetDomainMailboxLimits extends openSRS_mail {
	private $_dataObject;
	private $_formatHolder = "";
	private $_osrsm;

	public $resultRaw;
	public $resultFormatted;
	public $resultSuccess;

	public function __construct ($formatString, $dataObject) {
		parent::__construct();

		$this->_dataObject = $dataObject;
		$this->_formatHolder = $formatString;
		$this->_validateObject ();
	}

	public function __destruct () {
		parent::__destruct();
	}

	// Validate the object
	private function _validateObject (){
		$allPassed = true;
		$compile = "";

		// Command required values - authentication
		if (!isSet($this->_dataObject->data->admin_username) || $this->_dataObject->data->admin_username == "") {
			if (APP_MAIL_USERNAME == ""){
				trigger_error ("oSRS-eMail Error - username is not defined.", E_USER_WARNING);
				$allPassed = false;
			} else {
				$this->_dataObject->data->admin_username = APP_MAIL_USERNAME;
			}
		}
		if (!isSet($this->_dataObject->data->admin_password) || $this->_dataObject->data->admin_password == "") {
			if (APP_MAIL_PASSWORD == ""){
				trigger_error ("oSRS-eMail Error - password is not defined.", E_USER_WARNING);
				$allPassed = false;
			} else {
				$this->_dataObject->data->admin_password = APP_MAIL_PASSWORD;
			}
		}
		if (!isSet($this->_dataObject->data->admin_domain) || $this->_dataObject->data->admin_domain == "") {
			if (APP_MAIL_DOMAIN == ""){
				trigger_error ("oSRS-eMail Error - authentication domain is not defined.", E_USER_WARNING);
				$allPassed = false;
			} else {
				$this->_dataObject->data->admin_domain = APP_MAIL_DOMAIN;
			}
		}

		// Command required values
		if (!isSet($this->_dataObject->data->domain) || $this->_dataObject->data->domain == "") {
			trigger_error ("oSRS-eMail Error - domain is not defined.", E_USER_WARNING);
			$allPassed = false;
		} else {
			$compile .= " domain=\"". $this->_dataObject->data->domain ."\"";
		}

		// Command optional values
		if (isSet($this->_dataObject->data->mailbox) || $this->_dataObject->data->mailbox != "") $compile .= " mailbox=\"". $this->_dataObject->data->mailbox ."\"";
		if (isSet($this->_dataObject->data->filter_only) || $this->_dataObject->data->filter_only != "") $compile .= " filter_only=\"". $this->_dataObject->data->filter_only ."\"";
		if (isSet($this->_dataObject->data->alias) || $this->_dataObject->data->alias != "") $compile .= " alias=\"". $this->_dataObject->data->alias ."\"";
		if (isSet($this->_dataObject->data->forward_only) || $this->_dataObject->data->forward_only != "") $compile .= " forward_only=\"". $this->_dataObject->data->forward_only ."\"";
		if (isSet($this->_dataObject->data->mailing_list) || $this->_dataObject->data->mailing_list != "") $compile .= " mailing_list=\"". $this->_dataObject->data->mailing_list ."\"";

		// Run the command
		if ($allPassed) {
			// Execute the command
			$this->_processRequest ($compile);
		} else {
			trigger_error ("oSRS-eMail Error - Missing data.", E_USER_WARNING);
		}
	}

	// Post validation functions
	private function _processRequest ($command = ""){
		$sequence = array (
			0 => "ver ver=\"3.4\"",
			1 => "login user=\"". $this->_dataObject->data->admin_username ."\" domain=\"". $this->_dataObject->data->admin_domain ."\" password=\"". $this->_dataObject->data->admin_password ."\"",
			2 => "set_domain_mailbox_limits". $command,
			3 => "quit"
		);
		$tucRes = $this->makeCall($sequence);
		$arrayResult = $this->parseResults($tucRes);

		// Results
		$this->resultFullRaw = $arrayResult;
		$this->resultRaw = $arrayResult;
		$this->resultFullFormatted = convertArray2Formatted ($this->_formatHolder, $this->resultFullRaw);
		$this->resultFormatted = convertArray2Formatted ($this->_formatHolder, $this->resultRaw);
	}
}


text:
package metricapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * This class is the boot class used with Spring, put this as target to build
 *
 *
 */
@SpringBootApplication
public class BootApplication {

	public static void main(String[] args) {
		SpringApplication.run(BootApplication.class, args);
	}

}


text:
package org.jetbrains.idea.svn;

import com.intellij.openapi.util.Factory;
import com.intellij.util.Consumer;

public class FragmentsMerger<U, T extends Consumer<U>> {
  private T myData;
  private final Object myLock;
  private final Factory<T> myFactory;

  public FragmentsMerger(final Factory<T> factory) {
    myFactory = factory;
    myLock = new Object();
    myData = myFactory.create();
  }

  public void add(final U data) {
    synchronized (myLock) {
      // only T decides what to do with input, not the external code
      myData.consume(data);
    }
  }

  public T receive() {
    synchronized (myLock) {
      final T copy = myData;
      myData = myFactory.create();
      return copy;
    }
  }
}


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

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

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VersionForm));
            this.webBrowser1 = new System.Windows.Forms.WebBrowser();
            this.SuspendLayout();
            //
            // webBrowser1
            //
            resources.ApplyResources(this.webBrowser1, "webBrowser1");
            this.webBrowser1.AllowNavigation = false;
            this.webBrowser1.AllowWebBrowserDrop = false;
            this.webBrowser1.IsWebBrowserContextMenuEnabled = false;
            this.webBrowser1.Name = "webBrowser1";
            this.webBrowser1.Url = new System.Uri("", System.UriKind.Relative);
            this.webBrowser1.WebBrowserShortcutsEnabled = false;
            this.webBrowser1.NewWindow += new System.ComponentModel.CancelEventHandler(this.webBrowser1_NewWindow);
            //
            // Version_Info
            //
            resources.ApplyResources(this, "$this");
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.SystemColors.ButtonFace;
            this.Controls.Add(this.webBrowser1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "Version_Info";
            this.Load += new System.EventHandler(this.Version_Info_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.WebBrowser webBrowser1;
    }
}