text:
/*
 * Camunda BPM REST API
 * OpenApi Spec for Camunda BPM REST API.
 *
 * The version of the OpenAPI document: 7.13.0
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package com.camunda.consulting.openapi.client.model;

import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * FetchExternalTaskTopicDto
 */
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-14T01:59:23.608853+02:00[Europe/Berlin]")
public class FetchExternalTaskTopicDto {
  public static final String SERIALIZED_NAME_TOPIC_NAME = "topicName";
  @SerializedName(SERIALIZED_NAME_TOPIC_NAME)
  private String topicName;

  public static final String SERIALIZED_NAME_LOCK_DURATION = "lockDuration";
  @SerializedName(SERIALIZED_NAME_LOCK_DURATION)
  private Long lockDuration;

  public static final String SERIALIZED_NAME_VARIABLES = "variables";
  @SerializedName(SERIALIZED_NAME_VARIABLES)
  private List<String> variables = null;

  public static final String SERIALIZED_NAME_LOCAL_VARIABLES = "localVariables";
  @SerializedName(SERIALIZED_NAME_LOCAL_VARIABLES)
  private Boolean localVariables = false;

  public static final String SERIALIZED_NAME_BUSINESS_KEY = "businessKey";
  @SerializedName(SERIALIZED_NAME_BUSINESS_KEY)
  private String businessKey;

  public static final String SERIALIZED_NAME_PROCESS_DEFINITION_ID = "processDefinitionId";
  @SerializedName(SERIALIZED_NAME_PROCESS_DEFINITION_ID)
  private String processDefinitionId;

  public static final String SERIALIZED_NAME_PROCESS_DEFINITION_ID_IN = "processDefinitionIdIn";
  @SerializedName(SERIALIZED_NAME_PROCESS_DEFINITION_ID_IN)
  private List<String> processDefinitionIdIn = null;

  public static final String SERIALIZED_NAME_PROCESS_DEFINITION_KEY = "processDefinitionKey";
  @SerializedName(SERIALIZED_NAME_PROCESS_DEFINITION_KEY)
  private String processDefinitionKey;

  public static final String SERIALIZED_NAME_PROCESS_DEFINITION_KEY_IN = "processDefinitionKeyIn";
  @SerializedName(SERIALIZED_NAME_PROCESS_DEFINITION_KEY_IN)
  private List<String> processDefinitionKeyIn = null;

  public static final String SERIALIZED_NAME_PROCESS_DEFINITION_VERSION_TAG = "processDefinitionVersionTag";
  @SerializedName(SERIALIZED_NAME_PROCESS_DEFINITION_VERSION_TAG)
  private String processDefinitionVersionTag;

  public static final String SERIALIZED_NAME_WITHOUT_TENANT_ID = "withoutTenantId";
  @SerializedName(SERIALIZED_NAME_WITHOUT_TENANT_ID)
  private Boolean withoutTenantId = false;

  public static final String SERIALIZED_NAME_TENANT_ID_IN = "tenantIdIn";
  @SerializedName(SERIALIZED_NAME_TENANT_ID_IN)
  private List<String> tenantIdIn = null;

  public static final String SERIALIZED_NAME_PROCESS_VARIABLES = "processVariables";
  @SerializedName(SERIALIZED_NAME_PROCESS_VARIABLES)
  private Map<String, Object> processVariables = null;

  public static final String SERIALIZED_NAME_DESERIALIZE_VALUES = "deserializeValues";
  @SerializedName(SERIALIZED_NAME_DESERIALIZE_VALUES)
  private Boolean deserializeValues = false;

  public FetchExternalTaskTopicDto topicName(String topicName) {

    this.topicName = topicName;
    return this;
  }

   /**
   * **Mandatory.** The topic's name.
   * @return topicName
  **/
  @ApiModelProperty(required = true, value = "**Mandatory.** The topic's name.")

  public String getTopicName() {
    return topicName;
  }

  public void setTopicName(String topicName) {
    this.topicName = topicName;
  }

  public FetchExternalTaskTopicDto lockDuration(Long lockDuration) {

    this.lockDuration = lockDuration;
    return this;
  }

   /**
   * **Mandatory.** The duration to lock the external tasks for in milliseconds.
   * @return lockDuration
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(required = true, value = "**Mandatory.** The duration to lock the external tasks for in milliseconds.")

  public Long getLockDuration() {
    return lockDuration;
  }

  public void setLockDuration(Long lockDuration) {
    this.lockDuration = lockDuration;
  }

  public FetchExternalTaskTopicDto variables(List<String> variables) {

    this.variables = variables;
    return this;
  }

  public FetchExternalTaskTopicDto addVariablesItem(String variablesItem) {
    if (this.variables == null) {
      this.variables = new ArrayList<String>();
    }
    this.variables.add(variablesItem);
    return this;
  }

   /**
   * A JSON array of `String` values that represent variable names. For each result task belonging to this topic, the given variables are returned as well if they are accessible from the external task's execution. If not provided - all variables will be fetched.
   * @return variables
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "A JSON array of `String` values that represent variable names. For each result task belonging to this topic, the given variables are returned as well if they are accessible from the external task's execution. If not provided - all variables will be fetched.")

  public List<String> getVariables() {
    return variables;
  }

  public void setVariables(List<String> variables) {
    this.variables = variables;
  }

  public FetchExternalTaskTopicDto localVariables(Boolean localVariables) {

    this.localVariables = localVariables;
    return this;
  }

   /**
   * If `true` only local variables will be fetched.
   * @return localVariables
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "If `true` only local variables will be fetched.")

  public Boolean getLocalVariables() {
    return localVariables;
  }

  public void setLocalVariables(Boolean localVariables) {
    this.localVariables = localVariables;
  }

  public FetchExternalTaskTopicDto businessKey(String businessKey) {

    this.businessKey = businessKey;
    return this;
  }

   /**
   * A `String` value which enables the filtering of tasks based on process instance business key.
   * @return businessKey
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "A `String` value which enables the filtering of tasks based on process instance business key.")

  public String getBusinessKey() {
    return businessKey;
  }

  public void setBusinessKey(String businessKey) {
    this.businessKey = businessKey;
  }

  public FetchExternalTaskTopicDto processDefinitionId(String processDefinitionId) {

    this.processDefinitionId = processDefinitionId;
    return this;
  }

   /**
   * Filter tasks based on process definition id.
   * @return processDefinitionId
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "Filter tasks based on process definition id.")

  public String getProcessDefinitionId() {
    return processDefinitionId;
  }

  public void setProcessDefinitionId(String processDefinitionId) {
    this.processDefinitionId = processDefinitionId;
  }

  public FetchExternalTaskTopicDto processDefinitionIdIn(List<String> processDefinitionIdIn) {

    this.processDefinitionIdIn = processDefinitionIdIn;
    return this;
  }

  public FetchExternalTaskTopicDto addProcessDefinitionIdInItem(String processDefinitionIdInItem) {
    if (this.processDefinitionIdIn == null) {
      this.processDefinitionIdIn = new ArrayList<String>();
    }
    this.processDefinitionIdIn.add(processDefinitionIdInItem);
    return this;
  }

   /**
   * Filter tasks based on process definition ids.
   * @return processDefinitionIdIn
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "Filter tasks based on process definition ids.")

  public List<String> getProcessDefinitionIdIn() {
    return processDefinitionIdIn;
  }

  public void setProcessDefinitionIdIn(List<String> processDefinitionIdIn) {
    this.processDefinitionIdIn = processDefinitionIdIn;
  }

  public FetchExternalTaskTopicDto processDefinitionKey(String processDefinitionKey) {

    this.processDefinitionKey = processDefinitionKey;
    return this;
  }

   /**
   * Filter tasks based on process definition key.
   * @return processDefinitionKey
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "Filter tasks based on process definition key.")

  public String getProcessDefinitionKey() {
    return processDefinitionKey;
  }

  public void setProcessDefinitionKey(String processDefinitionKey) {
    this.processDefinitionKey = processDefinitionKey;
  }

  public FetchExternalTaskTopicDto processDefinitionKeyIn(List<String> processDefinitionKeyIn) {

    this.processDefinitionKeyIn = processDefinitionKeyIn;
    return this;
  }

  public FetchExternalTaskTopicDto addProcessDefinitionKeyInItem(String processDefinitionKeyInItem) {
    if (this.processDefinitionKeyIn == null) {
      this.processDefinitionKeyIn = new ArrayList<String>();
    }
    this.processDefinitionKeyIn.add(processDefinitionKeyInItem);
    return this;
  }

   /**
   * Filter tasks based on process definition keys.
   * @return processDefinitionKeyIn
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "Filter tasks based on process definition keys.")

  public List<String> getProcessDefinitionKeyIn() {
    return processDefinitionKeyIn;
  }

  public void setProcessDefinitionKeyIn(List<String> processDefinitionKeyIn) {
    this.processDefinitionKeyIn = processDefinitionKeyIn;
  }

  public FetchExternalTaskTopicDto processDefinitionVersionTag(String processDefinitionVersionTag) {

    this.processDefinitionVersionTag = processDefinitionVersionTag;
    return this;
  }

   /**
   * Filter tasks based on process definition version tag.
   * @return processDefinitionVersionTag
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "Filter tasks based on process definition version tag.")

  public String getProcessDefinitionVersionTag() {
    return processDefinitionVersionTag;
  }

  public void setProcessDefinitionVersionTag(String processDefinitionVersionTag) {
    this.processDefinitionVersionTag = processDefinitionVersionTag;
  }

  public FetchExternalTaskTopicDto withoutTenantId(Boolean withoutTenantId) {

    this.withoutTenantId = withoutTenantId;
    return this;
  }

   /**
   * Filter tasks without tenant id.
   * @return withoutTenantId
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "Filter tasks without tenant id.")

  public Boolean getWithoutTenantId() {
    return withoutTenantId;
  }

  public void setWithoutTenantId(Boolean withoutTenantId) {
    this.withoutTenantId = withoutTenantId;
  }

  public FetchExternalTaskTopicDto tenantIdIn(List<String> tenantIdIn) {

    this.tenantIdIn = tenantIdIn;
    return this;
  }

  public FetchExternalTaskTopicDto addTenantIdInItem(String tenantIdInItem) {
    if (this.tenantIdIn == null) {
      this.tenantIdIn = new ArrayList<String>();
    }
    this.tenantIdIn.add(tenantIdInItem);
    return this;
  }

   /**
   * Filter tasks based on tenant ids.
   * @return tenantIdIn
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "Filter tasks based on tenant ids.")

  public List<String> getTenantIdIn() {
    return tenantIdIn;
  }

  public void setTenantIdIn(List<String> tenantIdIn) {
    this.tenantIdIn = tenantIdIn;
  }

  public FetchExternalTaskTopicDto processVariables(Map<String, Object> processVariables) {

    this.processVariables = processVariables;
    return this;
  }

  public FetchExternalTaskTopicDto putProcessVariablesItem(String key, Object processVariablesItem) {
    if (this.processVariables == null) {
      this.processVariables = new HashMap<String, Object>();
    }
    this.processVariables.put(key, processVariablesItem);
    return this;
  }

   /**
   * A `JSON` object used for filtering tasks based on process instance variable values. A property name of the object represents a process variable name, while the property value represents the process variable value to filter tasks by.
   * @return processVariables
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "A `JSON` object used for filtering tasks based on process instance variable values. A property name of the object represents a process variable name, while the property value represents the process variable value to filter tasks by.")

  public Map<String, Object> getProcessVariables() {
    return processVariables;
  }

  public void setProcessVariables(Map<String, Object> processVariables) {
    this.processVariables = processVariables;
  }

  public FetchExternalTaskTopicDto deserializeValues(Boolean deserializeValues) {

    this.deserializeValues = deserializeValues;
    return this;
  }

   /**
   * Determines whether serializable variable values (typically variables that store custom Java objects) should be deserialized on server side (default `false`).  If set to `true`, a serializable variable will be deserialized on server side and transformed to JSON using [Jackson's](https://github.com/FasterXML/jackson) POJO/bean property introspection feature. Note that this requires the Java classes of the variable value to be on the REST API's classpath.  If set to `false`, a serializable variable will be returned in its serialized format. For example, a variable that is serialized as XML will be returned as a JSON string containing XML.
   * @return deserializeValues
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "Determines whether serializable variable values (typically variables that store custom Java objects) should be deserialized on server side (default `false`).  If set to `true`, a serializable variable will be deserialized on server side and transformed to JSON using [Jackson's](https://github.com/FasterXML/jackson) POJO/bean property introspection feature. Note that this requires the Java classes of the variable value to be on the REST API's classpath.  If set to `false`, a serializable variable will be returned in its serialized format. For example, a variable that is serialized as XML will be returned as a JSON string containing XML.")

  public Boolean getDeserializeValues() {
    return deserializeValues;
  }

  public void setDeserializeValues(Boolean deserializeValues) {
    this.deserializeValues = deserializeValues;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    FetchExternalTaskTopicDto fetchExternalTaskTopicDto = (FetchExternalTaskTopicDto) o;
    return Objects.equals(this.topicName, fetchExternalTaskTopicDto.topicName) &&
        Objects.equals(this.lockDuration, fetchExternalTaskTopicDto.lockDuration) &&
        Objects.equals(this.variables, fetchExternalTaskTopicDto.variables) &&
        Objects.equals(this.localVariables, fetchExternalTaskTopicDto.localVariables) &&
        Objects.equals(this.businessKey, fetchExternalTaskTopicDto.businessKey) &&
        Objects.equals(this.processDefinitionId, fetchExternalTaskTopicDto.processDefinitionId) &&
        Objects.equals(this.processDefinitionIdIn, fetchExternalTaskTopicDto.processDefinitionIdIn) &&
        Objects.equals(this.processDefinitionKey, fetchExternalTaskTopicDto.processDefinitionKey) &&
        Objects.equals(this.processDefinitionKeyIn, fetchExternalTaskTopicDto.processDefinitionKeyIn) &&
        Objects.equals(this.processDefinitionVersionTag, fetchExternalTaskTopicDto.processDefinitionVersionTag) &&
        Objects.equals(this.withoutTenantId, fetchExternalTaskTopicDto.withoutTenantId) &&
        Objects.equals(this.tenantIdIn, fetchExternalTaskTopicDto.tenantIdIn) &&
        Objects.equals(this.processVariables, fetchExternalTaskTopicDto.processVariables) &&
        Objects.equals(this.deserializeValues, fetchExternalTaskTopicDto.deserializeValues);
  }

  @Override
  public int hashCode() {
    return Objects.hash(topicName, lockDuration, variables, localVariables, businessKey, processDefinitionId, processDefinitionIdIn, processDefinitionKey, processDefinitionKeyIn, processDefinitionVersionTag, withoutTenantId, tenantIdIn, processVariables, deserializeValues);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class FetchExternalTaskTopicDto {\n");
    sb.append("    topicName: ").append(toIndentedString(topicName)).append("\n");
    sb.append("    lockDuration: ").append(toIndentedString(lockDuration)).append("\n");
    sb.append("    variables: ").append(toIndentedString(variables)).append("\n");
    sb.append("    localVariables: ").append(toIndentedString(localVariables)).append("\n");
    sb.append("    businessKey: ").append(toIndentedString(businessKey)).append("\n");
    sb.append("    processDefinitionId: ").append(toIndentedString(processDefinitionId)).append("\n");
    sb.append("    processDefinitionIdIn: ").append(toIndentedString(processDefinitionIdIn)).append("\n");
    sb.append("    processDefinitionKey: ").append(toIndentedString(processDefinitionKey)).append("\n");
    sb.append("    processDefinitionKeyIn: ").append(toIndentedString(processDefinitionKeyIn)).append("\n");
    sb.append("    processDefinitionVersionTag: ").append(toIndentedString(processDefinitionVersionTag)).append("\n");
    sb.append("    withoutTenantId: ").append(toIndentedString(withoutTenantId)).append("\n");
    sb.append("    tenantIdIn: ").append(toIndentedString(tenantIdIn)).append("\n");
    sb.append("    processVariables: ").append(toIndentedString(processVariables)).append("\n");
    sb.append("    deserializeValues: ").append(toIndentedString(deserializeValues)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }

}


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

namespace TravelService.Model.ServiceModel
{
    public class UserLoginResponse
    {
        public long userId { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "singa/server.h"

#include <thread>
#include <chrono>
#include "mshadow/tensor.h"
#include "singa/proto/common.pb.h"
#include "singa/utils/param.h"
#include "singa/utils/singleton.h"
#include "singa/utils/factory.h"
#include "singa/utils/cluster.h"

namespace singa {

using namespace mshadow;
using std::vector;

Server::Server(int group_id, int server_id,
    const JobProto& job_conf,
    const vector<int>& slice2group,
    const vector<int>& slice2server) {
  grp_id_ = group_id;
  id_ = server_id;
  updater_ = Updater::Create(job_conf.updater());
  slice2group_ = slice2group;
  slice2server_ = slice2server;
}

Server::~Server() {
  delete updater_;
  // free Params (i.e., slices) in server shard
  for (auto entry : shard_)
    for (auto param : entry.second->shares)
      delete param;
}

void Stop(void* running) {
  *static_cast<bool *>(running) = false;
}

void Server::Run() {
  LOG(ERROR) << "Server (group = " << grp_id_ <<", id = " << id_ << ") start";
  auto cluster = Cluster::Get();
  if (cluster->nserver_groups()) {
    CHECK_GT(slice2group_.size(), 0);
    if (cluster->nservers_per_group()) {
      CHECK_GT(slice2server_.size(), 0);
    }
  }
  n_updates_.resize(slice2group_.size(), 0);
  n_pending_sync_.resize(slice2group_.size(), 0);
  last_sync_.resize(slice2group_.size());

  // TODO(wangsh): give each dealer a unique id
  auto dealer = new Dealer(0);
  CHECK(dealer->Connect(kInprocRouterEndpoint));
  Msg* ping = new Msg(Addr(grp_id_, id_, kServer), Addr(-1, -1, kStub));
  ping->set_type(kConnect);
  dealer->Send(&ping);

  bool running = true;
  CHECK(cluster->runtime()->WatchSGroup(grp_id_, id_, Stop, &running));
  Poller poll(dealer);
  // start recv loop and process requests
  while (running) {
    // must use poller here; otherwise Receive() gets stuck after workers stop.
    auto* sock = poll.Wait(cluster->poll_time());
    if (poll.Terminated()) {
      LOG(ERROR) << "Connection broken!";
      exit(0);
    } else if (sock == nullptr) {
      continue;
    }
    Msg* msg = dealer->Receive();
    if (msg == nullptr) break;  // interrupted
    Msg* response = nullptr;
    int type = msg->type();
    int slice_id = SliceID(msg->trgt_val());
    if (type == kPut) {
      response = HandlePut(&msg);
    } else if (shard_.find(slice_id) == shard_.end()) {
      // TODO(wangsh): buffer the msg instead, and process it after the
      //               corresponding put request is done
      // delay the processing by re-queue the msg. May sleep for a while?
      response = msg;
    } else {
      switch (type) {
        case kGet:
          response = HandleGet(&msg);
          break;
        case kUpdate:
          for (auto reply : HandleUpdate(&msg))
            dealer->Send(&reply);
          break;
        case kSyncRequest:
          response = HandleSyncRequest(&msg);
          break;
        case kSyncResponse:
          HandleSyncResponse(&msg);
          break;
        default:
          LOG(ERROR) << "Unknown message type: " << type;
          break;
      }
    }
    if (response != nullptr)
      dealer->Send(&response);
  }

  // send stop msg to stub
  Msg* msg = new Msg(Addr(grp_id_, id_, kServer), Addr(-1, -1, kStub));
  msg->set_type(kStop);
  dealer->Send(&msg);
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  LOG(ERROR) << "Server (group = " << grp_id_ << ", id = " << id_ << ") stops";
  delete dealer;
}

Msg* Server::HandlePut(Msg **msg) {
  int version = (*msg)->trgt_version();
  int slice_id = SliceID((*msg)->trgt_val());
  if (shard_.find(slice_id) != shard_.end())
    LOG(FATAL) << "Param (" << slice_id << ") is put more than once";

  // TODO(wangwei) replace hard coded param type 0
  auto  param = Singleton<Factory<Param>>::Instance()->Create(0);
  auto response = param->HandlePutMsg(msg, true);
  // parse num of shares of this param from a worker group
  int num_shares = 1;
  if ((*msg)->NextFrame())
    (*msg)->ParseFormatFrame("i", &num_shares);
  DeleteMsg(msg);
  shard_[slice_id] = new ParamEntry(num_shares, param);
  // must set version after HandlePutMsg which allocates the memory
  param->set_version(version);
  param->set_last_version(version);
  param->set_id(slice_id);
  // allocate blob for param sync between groups.
  if (slice2group_[slice_id] != grp_id_) {
    last_sync_[slice_id].ReshapeLike(param->data());
    last_sync_[slice_id].CopyFrom(param->data());
  }
  LOG(INFO) << "server (group = " << grp_id_ << ", id = " << id_
            <<") put slice=" << slice_id << " size=" << param->size();
  return response;
}

Msg* Server::HandleGet(Msg **msg) {
  int val = (*msg)->trgt_val();
  auto param = shard_.at(SliceID(val))->shares.at(0);
  // re-queue the request if the param is not updated to the required version
  if (param->version() < (*msg)->trgt_version()) {
    return *msg;
  } else {
    // LOG(ERROR) << "get " << slice << " from "<<(*msg)->src_first();
    auto reply = param->HandleGetMsg(msg, false);
    reply->set_trgt(val, param->version());
    return reply;
  }
}

const vector<Msg*> Server::HandleUpdate(Msg **msg) {
  vector<Msg*> ret;
  int sliceid = SliceID((*msg)->trgt_val());
  auto entry = shard_.at(sliceid);
  buffer_requests_[sliceid].push_back(*msg);
  int num_update;
  (*msg)->LastFrame();
  (*msg)->ParseFormatFrame("i", &num_update);
  (*msg)->FirstFrame();
  entry->num_update += num_update;
  // LOG(ERROR) << "update "<< sliceid << " from " << AddrGrp((*msg)->src())
  //            << ", " << num_update << " total " << entry->num_total;
  // do update until recv gradients from all shares of this param/slice
  if (entry->num_update >= entry->num_total) {
    CHECK_EQ(entry->num_update, entry->num_total);
    auto& request = buffer_requests_.at(sliceid);
    int step = (*msg)->trgt_version();
    int trgt_val = (*msg)->trgt_val();
    auto param = entry->shares.at(0);
    // extract and aggregate gradients
    param->ParseUpdateMsgs(request);
    // DLOG(ERROR) << "update param " << param->id() << " @ step " << step;
    updater_->Update(step, param, 1.0f / entry->num_total);
    param->set_version(param->version() + 1);
    // response to all shares of this param
    for (auto response : param->GenUpdateResponseMsgs(&request, false)) {
      response->set_trgt(trgt_val, param->version());
      ret.push_back(response);
    }
    entry->num_update = 0;
    n_updates_[sliceid]++;
    // sync with master group after at least sync_freq local updates
    // the last check is to avoid sending msg to stopped servers
    // may send the update steps on this server since last sync, i.e.,
    // version-last_version
    if (slice2group_[sliceid] != grp_id_
        && n_updates_[sliceid] >= Cluster::Get()->sync_freq()
        && n_pending_sync_[sliceid] <= Cluster::Get()->sync_freq()) {
      auto shape = Shape1(param->size());
      Tensor<cpu, 1> tmp(last_sync_[sliceid].mutable_cpu_data(), shape);
      Tensor<cpu, 1> cur(param->mutable_cpu_data(), shape);
      tmp = cur - tmp;
      int addr = Addr(slice2group_[sliceid], slice2server_[sliceid], kServer);
      Msg* sync = new Msg(Addr(grp_id_, id_, kServer), addr);
      sync->set_type(kSyncRequest);
      sync->set_trgt(trgt_val, param->version());
      sync->AddFrame(tmp.dptr, param->size() * sizeof(float));
      Copy(tmp, cur);
      ret.push_back(sync);
      n_updates_[sliceid] = 0;
      n_pending_sync_[sliceid]++;
    }
  }
  // message already pushed to buffer, just need to reset the pointer
  *msg = nullptr;
  return ret;
}

Msg* Server::HandleSyncRequest(Msg **msg) {
  Msg* msgg = *msg;
  int slice = SliceID(msgg->trgt_val());
  auto param = shard_.at(slice)->shares.at(0);
  auto shape = Shape1(param->size());
  CHECK_EQ(msgg->FrameSize(), param->size()*sizeof(float));
  Tensor<cpu, 1> inc(static_cast<float*>(msgg->FrameData()), shape);
  Tensor<cpu, 1> cur(param->mutable_cpu_data(), shape);
  // recv sync msg on the slice I am maintaining
  cur += inc;
  msgg->SwapAddr();
  msgg->set_type(kSyncResponse);
  // copy the fresh param value into the response msg
  Copy(inc, cur);
  return msgg;
}

// recv sync msg on slice mastered by others
void Server::HandleSyncResponse(Msg **msg) {
  Msg* msgg = *msg;
  int slice = SliceID(msgg->trgt_val());
  auto param = shard_.at(slice)->shares.at(0);
  auto shape = Shape1(param->size());
  Tensor<cpu, 1> prev(last_sync_[param->id()].mutable_cpu_data(), shape);
  Tensor<cpu, 1> cur(param->mutable_cpu_data(), shape);
  Tensor<cpu, 1> master(static_cast<float*>(msgg->FrameData()), shape);
  cur += master - prev;  // cur = master + (cur - prev);
  Copy(prev, cur);
  DeleteMsg(msg);
  n_pending_sync_[slice]--;
}

}  // namespace singa


text:
#pragma strict

function Start () {

}

function Update () {

}

function ResetLevel(){
	Application.LoadLevel(Application.loadedLevel);
}


text:
package colossus

import testkit._

import akka.actor._
import akka.testkit.TestProbe
import akka.util.ByteString

import scala.concurrent.duration._
import scala.concurrent.Await

import protocols.telnet._
import service._
import Callback.Implicits._

import RawProtocol.{RawCodec, Raw}

class ErrorTestDSL(probe: ActorRef) extends CodecProvider[Raw] {

    def provideCodec() = RawCodec

    def errorResponse(request: ByteString, reason: Throwable) = {
      probe ! reason
      ByteString(s"Error (${reason.getClass.getName}): ${reason.getMessage}")
    }

}

class ServiceDSLSpec extends ColossusSpec {

  "Service DSL" must {
    "receive delegator messages" in {
      withIOSystem{implicit system =>
        val probe = TestProbe()
        val server = Service.serve[Telnet]("test", 12345){context =>
          context.receive{
            case "PING" => probe.ref ! "PONG"
          }
          context.handle{_.become{
            case _ => TelnetReply("meeh")
          }}
        }
        server.delegatorBroadcast("PING")
        probe.expectMsg(250.milliseconds, "PONG")
        probe.expectMsg(250.milliseconds, "PONG")
      }
    }

    "throw UnhandledRequestException on unhandled request" in {
      val probe = TestProbe()
      implicit val provider = new ErrorTestDSL(probe.ref)
      withIOSystem{ implicit system =>
        val server = Service.become[Raw]("test", TEST_PORT) {
          case any if (false) => ByteString("WAT")
        }
        withServer(server) {
          val client = TestClient(system, TEST_PORT)
          client.send(ByteString("hello"))
          probe.expectMsgType[UnhandledRequestException]
        }
      }
    }

    "receive connection messages" in {
      val probe = TestProbe()
      withIOSystem{ implicit system =>
        val server = Service.serve[Raw]("test", TEST_PORT) { context =>
          context.handle{ connection =>
            connection.receive{
              case "PING" => {
                probe.ref ! "PONG"
              }
            }
            connection.become{
              case x if (x == ByteString("PING")) => {
                context.worker.worker ! core.WorkerCommand.Message(connection.connectionInfo.get.id, "PING")
                Callback.successful(ByteString("WHATEVER"))
              }
            }
          }
        }
        withServer(server) {
          val client = TestClient(system, TEST_PORT)
          client.send(ByteString("PING"))
          probe.expectMsg(250.milliseconds, "PONG")
        }
      }
    }

    "override error handler" in {
      withIOSystem{ implicit system =>
        val server = Service.serve[Raw]("test", TEST_PORT) { context =>
          context.handle{ connection =>
            connection.onError{
              case (request, c: UnhandledRequestException) => ByteString("OVERRIDE")
            }
            connection.become{
              case x if (false) => ByteString("NOPE")
            }
          }
        }
        withServer(server) {
          val client = TestClient(system, TEST_PORT)
          Await.result(client.send(ByteString("TEST")), 1.second).utf8String must equal("OVERRIDE")
        }
      }
    }

  }
}


text:
package com.google.common.collect;

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

import javax.annotation.Nullable;

/**
 * GWT emulated version of {@link ImmutableList}.
 * TODO(cpovirk): more doc
 *
 * @author Hayward Chan
 */
abstract class ForwardingImmutableList<E> extends ImmutableList<E> {

  ForwardingImmutableList() {
  }

  abstract List<E> delegateList();

  public int indexOf(@Nullable Object object) {
    return delegateList().indexOf(object);
  }

  public int lastIndexOf(@Nullable Object object) {
    return delegateList().lastIndexOf(object);
  }

  public E get(int index) {
    return delegateList().get(index);
  }

  public ImmutableList<E> subList(int fromIndex, int toIndex) {
    return unsafeDelegateList(delegateList().subList(fromIndex, toIndex));
  }

  public UnmodifiableListIterator<E> listIterator() {
    return Iterators.unmodifiableListIterator(delegateList().listIterator());
  }

  public UnmodifiableListIterator<E> listIterator(int index) {
    return Iterators.unmodifiableListIterator(delegateList().listIterator(index));
  }

  @Override public Object[] toArray() {
    // Note that ArrayList.toArray() doesn't work here because it returns E[]
    // instead of Object[].
    return delegateList().toArray(new Object[size()]);
  }

  @Override public boolean equals(Object obj) {
    return delegateList().equals(obj);
  }

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

  @Override public UnmodifiableIterator<E> iterator() {
    return Iterators.unmodifiableIterator(delegateList().iterator());
  }

  @Override public boolean contains(@Nullable Object object) {
    return object != null && delegateList().contains(object);
  }

  @Override public boolean containsAll(Collection<?> targets) {
    return delegateList().containsAll(targets);
  }

  public int size() {
    return delegateList().size();
  }

  @Override public boolean isEmpty() {
    return delegateList().isEmpty();
  }

  @Override public <T> T[] toArray(T[] other) {
    return delegateList().toArray(other);
  }

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


text:
"""Generate ML model inputs from images."""
import argparse
import os
import struct
import urllib.request

import numpy as np
from PIL import Image

parser = argparse.ArgumentParser(
    description='Generate inputs for ML models.')
parser.add_argument('--i', dest='input_name',
                    help='Model input image name', required=True)
parser.add_argument('--o', dest='output_file',
                    help='Output binary name', required=True)
parser.add_argument('--s', dest='input_shape',
                    help='Model input shape (example: "1, 224, 224, 3")', required=True)
parser.add_argument('--q', dest='is_quant', action='store_true',
                    help='Indicate it is quant model (default: False)')
parser.add_argument('--r', dest='float_input_range', default="-1.0, 1.0",
                    help='Float model input range (default: "-1.0, 1.0")')
args = parser.parse_args()

def write_binary_file(file_path, input, is_quant):
    with open(file_path, "wb+") as file:
        for d in input:
            if is_quant:
                file.write(struct.pack("<B", d))
            else:
                file.write(struct.pack("<f", d))

def gen_mlmodel_input(input_name, output_file, input_shape, is_quant):
    if not os.path.exists(input_name):
        raise RuntimeError("Input file %s doesn't exist" % {input_name})
    if len(input_shape) < 3:
        raise ValueError("Input shape < 3 dimensions")
    input_ext = os.path.splitext(input_name)[1]
    if (not input_ext) or (input_ext == '.bin'):
        with open(input_name, mode='rb') as f:
            input = np.fromfile(f, dtype=np.uint8 if is_quant else np.float32).reshape(
                np.prod(input_shape))
    else:
        resized_img = Image.open(input_name).resize(
            (input_shape[2], input_shape[1]))
        input = np.array(resized_img).reshape(np.prod(input_shape))
        if not is_quant:
            low = np.min(float_input_range)
            high = np.max(float_input_range)
            input = (high - low) * input / 255.0 + low
    write_binary_file(output_file, input, is_quant)

if __name__ == '__main__':
    # convert input shape to a list
    input_shape = [int(x) for x in args.input_shape.split(',')]
    float_input_range = [float(x) for x in args.float_input_range.split(',')]
    gen_mlmodel_input(args.input_name, args.output_file,
                      input_shape, args.is_quant)


text:
/*
 * bootup setup stuff..
 */

#undef DEBUG

#include <linux/config.h>
#include <linux/cpu.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/slab.h>
#include <linux/user.h>
#include <linux/a.out.h>
#include <linux/tty.h>
#include <linux/major.h>
#include <linux/interrupt.h>
#include <linux/reboot.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/console.h>
#include <linux/pci.h>
#include <linux/utsname.h>
#include <linux/adb.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/seq_file.h>
#include <linux/root_dev.h>

#include <asm/mmu.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#include <asm/prom.h>
#include <asm/rtas.h>
#include <asm/pci-bridge.h>
#include <asm/iommu.h>
#include <asm/dma.h>
#include <asm/machdep.h>
#include <asm/irq.h>
#include <asm/kexec.h>
#include <asm/time.h>
#include <asm/nvram.h>
#include "xics.h"
#include <asm/firmware.h>
#include <asm/pmc.h>
#include <asm/mpic.h>
#include <asm/ppc-pci.h>
#include <asm/i8259.h>
#include <asm/udbg.h>
#include <asm/smp.h>

#include "plpar_wrappers.h"
#include "ras.h"

#ifdef DEBUG
#define DBG(fmt...) udbg_printf(fmt)
#else
#define DBG(fmt...)
#endif

extern void find_udbg_vterm(void);

int fwnmi_active;  /* TRUE if an FWNMI handler is present */

static void pseries_shared_idle(void);
static void pseries_dedicated_idle(void);

struct mpic *pSeries_mpic;

static void pSeries_show_cpuinfo(struct seq_file *m)
{
	struct device_node *root;
	const char *model = "";

	root = of_find_node_by_path("/");
	if (root)
		model = get_property(root, "model", NULL);
	seq_printf(m, "machine\t\t: CHRP %s\n", model);
	of_node_put(root);
}

/* Initialize firmware assisted non-maskable interrupts if
 * the firmware supports this feature.
 */
static void __init fwnmi_init(void)
{
	unsigned long system_reset_addr, machine_check_addr;

	int ibm_nmi_register = rtas_token("ibm,nmi-register");
	if (ibm_nmi_register == RTAS_UNKNOWN_SERVICE)
		return;

	/* If the kernel's not linked at zero we point the firmware at low
	 * addresses anyway, and use a trampoline to get to the real code. */
	system_reset_addr  = __pa(system_reset_fwnmi) - PHYSICAL_START;
	machine_check_addr = __pa(machine_check_fwnmi) - PHYSICAL_START;

	if (0 == rtas_call(ibm_nmi_register, 2, 1, NULL, system_reset_addr,
				machine_check_addr))
		fwnmi_active = 1;
}

static void __init pSeries_init_mpic(void)
{
        unsigned int *addrp;
	struct device_node *np;
	unsigned long intack = 0;

	/* All ISUs are setup, complete initialization */
	mpic_init(pSeries_mpic);

	/* Check what kind of cascade ACK we have */
        if (!(np = of_find_node_by_name(NULL, "pci"))
            || !(addrp = (unsigned int *)
                 get_property(np, "8259-interrupt-acknowledge", NULL)))
                printk(KERN_ERR "Cannot find pci to get ack address\n");
        else
		intack = addrp[prom_n_addr_cells(np)-1];
	of_node_put(np);

	/* Setup the legacy interrupts & controller */
	i8259_init(intack, 0);

	/* Hook cascade to mpic */
	mpic_setup_cascade(NUM_ISA_INTERRUPTS, i8259_irq_cascade, NULL);
}

static void __init pSeries_setup_mpic(void)
{
	unsigned int *opprop;
	unsigned long openpic_addr = 0;
        unsigned char senses[NR_IRQS - NUM_ISA_INTERRUPTS];
        struct device_node *root;
	int irq_count;

	/* Find the Open PIC if present */
	root = of_find_node_by_path("/");
	opprop = (unsigned int *) get_property(root, "platform-open-pic", NULL);
	if (opprop != 0) {
		int n = prom_n_addr_cells(root);

		for (openpic_addr = 0; n > 0; --n)
			openpic_addr = (openpic_addr << 32) + *opprop++;
		printk(KERN_DEBUG "OpenPIC addr: %lx\n", openpic_addr);
	}
	of_node_put(root);

	BUG_ON(openpic_addr == 0);

	/* Get the sense values from OF */
	prom_get_irq_senses(senses, NUM_ISA_INTERRUPTS, NR_IRQS);

	/* Setup the openpic driver */
	irq_count = NR_IRQS - NUM_ISA_INTERRUPTS - 4; /* leave room for IPIs */
	pSeries_mpic = mpic_alloc(openpic_addr, MPIC_PRIMARY,
				  16, 16, irq_count, /* isu size, irq offset, irq count */
				  NR_IRQS - 4, /* ipi offset */
				  senses, irq_count, /* sense & sense size */
				  " MPIC     ");
}

static void pseries_lpar_enable_pmcs(void)
{
	unsigned long set, reset;

	power4_enable_pmcs();

	set = 1UL << 63;
	reset = 0;
	plpar_hcall_norets(H_PERFMON, set, reset);

	/* instruct hypervisor to maintain PMCs */
	if (firmware_has_feature(FW_FEATURE_SPLPAR))
		get_lppaca()->pmcregs_in_use = 1;
}

static void __init pSeries_setup_arch(void)
{
	/* Fixup ppc_md depending on the type of interrupt controller */
	if (ppc64_interrupt_controller == IC_OPEN_PIC) {
		ppc_md.init_IRQ       = pSeries_init_mpic;
		ppc_md.get_irq        = mpic_get_irq;
		/* Allocate the mpic now, so that find_and_init_phbs() can
		 * fill the ISUs */
		pSeries_setup_mpic();
	} else {
		ppc_md.init_IRQ       = xics_init_IRQ;
		ppc_md.get_irq        = xics_get_irq;
	}

#ifdef CONFIG_SMP
	smp_init_pSeries();
#endif
	/* openpic global configuration register (64-bit format). */
	/* openpic Interrupt Source Unit pointer (64-bit format). */
	/* python0 facility area (mmio) (64-bit format) REAL address. */

	/* init to some ~sane value until calibrate_delay() runs */
	loops_per_jiffy = 50000000;

	if (ROOT_DEV == 0) {
		printk("No ramdisk, default root is /dev/sda2\n");
		ROOT_DEV = Root_SDA2;
	}

	fwnmi_init();

	/* Find and initialize PCI host bridges */
	init_pci_config_tokens();
	find_and_init_phbs();
	eeh_init();

	pSeries_nvram_init();

	/* Choose an idle loop */
	if (firmware_has_feature(FW_FEATURE_SPLPAR)) {
		vpa_init(boot_cpuid);
		if (get_lppaca()->shared_proc) {
			printk(KERN_INFO "Using shared processor idle loop\n");
			ppc_md.idle_loop = pseries_shared_idle;
		} else {
			printk(KERN_INFO "Using dedicated idle loop\n");
			ppc_md.idle_loop = pseries_dedicated_idle;
		}
	} else {
		printk(KERN_INFO "Using default idle loop\n");
		ppc_md.idle_loop = default_idle;
	}

	if (platform_is_lpar())
		ppc_md.enable_pmcs = pseries_lpar_enable_pmcs;
	else
		ppc_md.enable_pmcs = power4_enable_pmcs;
}

static int __init pSeries_init_panel(void)
{
	/* Manually leave the kernel version on the panel. */
	ppc_md.progress("Linux ppc64\n", 0);
	ppc_md.progress(system_utsname.version, 0);

	return 0;
}
arch_initcall(pSeries_init_panel);

/* Build up the ppc64_firmware_features bitmask field
 * using contents of device-tree/ibm,hypertas-functions.
 * Ultimately this functionality may be moved into prom.c prom_init().
 */
static void __init fw_feature_init(void)
{
	struct device_node * dn;
	char * hypertas;
	unsigned int len;

	DBG(" -> fw_feature_init()\n");

	ppc64_firmware_features = 0;
	dn = of_find_node_by_path("/rtas");
	if (dn == NULL) {
		printk(KERN_ERR "WARNING ! Cannot find RTAS in device-tree !\n");
		goto no_rtas;
	}

	hypertas = get_property(dn, "ibm,hypertas-functions", &len);
	if (hypertas) {
		while (len > 0){
			int i, hypertas_len;
			/* check value against table of strings */
			for(i=0; i < FIRMWARE_MAX_FEATURES ;i++) {
				if ((firmware_features_table[i].name) &&
				    (strcmp(firmware_features_table[i].name,hypertas))==0) {
					/* we have a match */
					ppc64_firmware_features |=
						(firmware_features_table[i].val);
					break;
				}
			}
			hypertas_len = strlen(hypertas);
			len -= hypertas_len +1;
			hypertas+= hypertas_len +1;
		}
	}

	of_node_put(dn);
no_rtas:

	DBG(" <- fw_feature_init()\n");
}

static  void __init pSeries_discover_pic(void)
{
	struct device_node *np;
	char *typep;

	/*
	 * Setup interrupt mapping options that are needed for finish_device_tree
	 * to properly parse the OF interrupt tree & do the virtual irq mapping
	 */
	__irq_offset_value = NUM_ISA_INTERRUPTS;
	ppc64_interrupt_controller = IC_INVALID;
	for (np = NULL; (np = of_find_node_by_name(np, "interrupt-controller"));) {
		typep = (char *)get_property(np, "compatible", NULL);
		if (strstr(typep, "open-pic")) {
			ppc64_interrupt_controller = IC_OPEN_PIC;
			break;
		} else if (strstr(typep, "ppc-xicp")) {
			ppc64_interrupt_controller = IC_PPC_XIC;
			break;
		}
	}
	if (ppc64_interrupt_controller == IC_INVALID)
		printk("pSeries_discover_pic: failed to recognize"
			" interrupt-controller\n");

}

static void pSeries_mach_cpu_die(void)
{
	local_irq_disable();
	idle_task_exit();
	/* Some hardware requires clearing the CPPR, while other hardware does not
	 * it is safe either way
	 */
	pSeriesLP_cppr_info(0, 0);
	rtas_stop_self();
	/* Should never get here... */
	BUG();
	for(;;);
}

static int pseries_set_dabr(unsigned long dabr)
{
	return plpar_hcall_norets(H_SET_DABR, dabr);
}

static int pseries_set_xdabr(unsigned long dabr)
{
	/* We want to catch accesses from kernel and userspace */
	return plpar_hcall_norets(H_SET_XDABR, dabr,
			H_DABRX_KERNEL | H_DABRX_USER);
}

/*
 * Early initialization.  Relocation is on but do not reference unbolted pages
 */
static void __init pSeries_init_early(void)
{
	int iommu_off = 0;

	DBG(" -> pSeries_init_early()\n");

	fw_feature_init();

	if (platform_is_lpar())
		hpte_init_lpar();
	else {
		hpte_init_native();
		iommu_off = (of_chosen &&
			     get_property(of_chosen, "linux,iommu-off", NULL));
	}

	if (platform_is_lpar())
		find_udbg_vterm();

	if (firmware_has_feature(FW_FEATURE_DABR))
		ppc_md.set_dabr = pseries_set_dabr;
	else if (firmware_has_feature(FW_FEATURE_XDABR))
		ppc_md.set_dabr = pseries_set_xdabr;

	iommu_init_early_pSeries();

	pSeries_discover_pic();

	DBG(" <- pSeries_init_early()\n");
}

static int pSeries_check_legacy_ioport(unsigned int baseport)
{
	struct device_node *np;

#define I8042_DATA_REG	0x60
#define FDC_BASE	0x3f0

	switch(baseport) {
	case I8042_DATA_REG:
		np = of_find_node_by_type(NULL, "8042");
		if (np == NULL)
			return -ENODEV;
		of_node_put(np);
		break;
	case FDC_BASE:
		np = of_find_node_by_type(NULL, "fdc");
		if (np == NULL)
			return -ENODEV;
		of_node_put(np);
		break;
	}
	return 0;
}

/*
 * Called very early, MMU is off, device-tree isn't unflattened
 */
extern struct machdep_calls pSeries_md;

static int __init pSeries_probe(int platform)
{
	if (platform != PLATFORM_PSERIES &&
	    platform != PLATFORM_PSERIES_LPAR)
		return 0;

	/* if we have some ppc_md fixups for LPAR to do, do
	 * it here ...
	 */

	return 1;
}

DECLARE_PER_CPU(unsigned long, smt_snooze_delay);

static inline void dedicated_idle_sleep(unsigned int cpu)
{
	struct lppaca *plppaca = &lppaca[cpu ^ 1];

	/* Only sleep if the other thread is not idle */
	if (!(plppaca->idle)) {
		local_irq_disable();

		/*
		 * We are about to sleep the thread and so wont be polling any
		 * more.
		 */
		clear_thread_flag(TIF_POLLING_NRFLAG);
		smp_mb__after_clear_bit();

		/*
		 * SMT dynamic mode. Cede will result in this thread going
		 * dormant, if the partner thread is still doing work.  Thread
		 * wakes up if partner goes idle, an interrupt is presented, or
		 * a prod occurs.  Returning from the cede enables external
		 * interrupts.
		 */
		if (!need_resched())
			cede_processor();
		else
			local_irq_enable();
		set_thread_flag(TIF_POLLING_NRFLAG);
	} else {
		/*
		 * Give the HV an opportunity at the processor, since we are
		 * not doing any work.
		 */
		poll_pending();
	}
}

static void pseries_dedicated_idle(void)
{
	unsigned int cpu = smp_processor_id();
	unsigned long start_snooze;
	unsigned long *smt_snooze_delay = &__get_cpu_var(smt_snooze_delay);
	set_thread_flag(TIF_POLLING_NRFLAG);

	while (1) {
		/*
		 * Indicate to the HV that we are idle. Now would be
		 * a good time to find other work to dispatch.
		 */
		get_lppaca()->idle = 1;

		if (!need_resched()) {
			start_snooze = get_tb() +
				*smt_snooze_delay * tb_ticks_per_usec;

			while (!need_resched() && !cpu_is_offline(cpu)) {
				ppc64_runlatch_off();

				/*
				 * Go into low thread priority and possibly
				 * low power mode.
				 */
				HMT_low();
				HMT_very_low();

				if (*smt_snooze_delay != 0 &&
				    get_tb() > start_snooze) {
					HMT_medium();
					dedicated_idle_sleep(cpu);
				}

			}

			HMT_medium();
		}

		get_lppaca()->idle = 0;
		ppc64_runlatch_on();

		preempt_enable_no_resched();
		schedule();
		preempt_disable();

		if (cpu_is_offline(cpu) && system_state == SYSTEM_RUNNING)
			cpu_die();
	}
}

static void pseries_shared_idle(void)
{
	unsigned int cpu = smp_processor_id();

	while (1) {
		/*
		 * Indicate to the HV that we are idle. Now would be
		 * a good time to find other work to dispatch.
		 */
		get_lppaca()->idle = 1;

		while (!need_resched() && !cpu_is_offline(cpu)) {
			local_irq_disable();
			ppc64_runlatch_off();

			/*
			 * Yield the processor to the hypervisor.  We return if
			 * an external interrupt occurs (which are driven prior
			 * to returning here) or if a prod occurs from another
			 * processor. When returning here, external interrupts
			 * are enabled.
			 *
			 * Check need_resched() again with interrupts disabled
			 * to avoid a race.
			 */
			if (!need_resched())
				cede_processor();
			else
				local_irq_enable();

			HMT_medium();
		}

		get_lppaca()->idle = 0;
		ppc64_runlatch_on();

		preempt_enable_no_resched();
		schedule();
		preempt_disable();

		if (cpu_is_offline(cpu) && system_state == SYSTEM_RUNNING)
			cpu_die();
	}
}

static int pSeries_pci_probe_mode(struct pci_bus *bus)
{
	if (platform_is_lpar())
		return PCI_PROBE_DEVTREE;
	return PCI_PROBE_NORMAL;
}

#ifdef CONFIG_KEXEC
static void pseries_kexec_cpu_down(int crash_shutdown, int secondary)
{
	/* Don't risk a hypervisor call if we're crashing */
	if (firmware_has_feature(FW_FEATURE_SPLPAR) && !crash_shutdown) {
		unsigned long vpa = __pa(get_lppaca());

		if (unregister_vpa(hard_smp_processor_id(), vpa)) {
			printk("VPA deregistration of cpu %u (hw_cpu_id %d) "
					"failed\n", smp_processor_id(),
					hard_smp_processor_id());
		}
	}

	if (ppc64_interrupt_controller == IC_OPEN_PIC)
		mpic_teardown_this_cpu(secondary);
	else
		xics_teardown_cpu(secondary);
}
#endif

struct machdep_calls __initdata pSeries_md = {
	.probe			= pSeries_probe,
	.setup_arch		= pSeries_setup_arch,
	.init_early		= pSeries_init_early,
	.show_cpuinfo		= pSeries_show_cpuinfo,
	.log_error		= pSeries_log_error,
	.pcibios_fixup		= pSeries_final_fixup,
	.pci_probe_mode		= pSeries_pci_probe_mode,
	.irq_bus_setup		= pSeries_irq_bus_setup,
	.restart		= rtas_restart,
	.power_off		= rtas_power_off,
	.halt			= rtas_halt,
	.panic			= rtas_os_term,
	.cpu_die		= pSeries_mach_cpu_die,
	.get_boot_time		= rtas_get_boot_time,
	.get_rtc_time		= rtas_get_rtc_time,
	.set_rtc_time		= rtas_set_rtc_time,
	.calibrate_decr		= generic_calibrate_decr,
	.progress		= rtas_progress,
	.check_legacy_ioport	= pSeries_check_legacy_ioport,
	.system_reset_exception = pSeries_system_reset_exception,
	.machine_check_exception = pSeries_machine_check_exception,
#ifdef CONFIG_KEXEC
	.kexec_cpu_down		= pseries_kexec_cpu_down,
	.machine_kexec		= default_machine_kexec,
	.machine_kexec_prepare	= default_machine_kexec_prepare,
	.machine_crash_shutdown	= default_machine_crash_shutdown,
#endif
};


text:
package priorities

import (
	"fmt"

	"github.com/golang/glog"
	"k8s.io/kubernetes/pkg/api/v1"
	v1helper "k8s.io/kubernetes/pkg/api/v1/helper"
	schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api"
	"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache"
)

// CountIntolerableTaintsPreferNoSchedule gives the count of intolerable taints of a pod with effect PreferNoSchedule
func countIntolerableTaintsPreferNoSchedule(taints []v1.Taint, tolerations []v1.Toleration) (intolerableTaints int) {
	for _, taint := range taints {
		// check only on taints that have effect PreferNoSchedule
		if taint.Effect != v1.TaintEffectPreferNoSchedule {
			continue
		}

		if !v1helper.TolerationsTolerateTaint(tolerations, &taint) {
			intolerableTaints++
		}
	}
	return
}

// getAllTolerationEffectPreferNoSchedule gets the list of all Tolerations with Effect PreferNoSchedule or with no effect.
func getAllTolerationPreferNoSchedule(tolerations []v1.Toleration) (tolerationList []v1.Toleration) {
	for _, toleration := range tolerations {
		// Empty effect means all effects which includes PreferNoSchedule, so we need to collect it as well.
		if len(toleration.Effect) == 0 || toleration.Effect == v1.TaintEffectPreferNoSchedule {
			tolerationList = append(tolerationList, toleration)
		}
	}
	return
}

// ComputeTaintTolerationPriorityMap prepares the priority list for all the nodes based on the number of intolerable taints on the node
func ComputeTaintTolerationPriorityMap(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) {
	node := nodeInfo.Node()
	if node == nil {
		return schedulerapi.HostPriority{}, fmt.Errorf("node not found")
	}
	// To hold all the tolerations with Effect PreferNoSchedule
	var tolerationsPreferNoSchedule []v1.Toleration
	if priorityMeta, ok := meta.(*priorityMetadata); ok {
		tolerationsPreferNoSchedule = priorityMeta.podTolerations

	} else {
		tolerationsPreferNoSchedule = getAllTolerationPreferNoSchedule(pod.Spec.Tolerations)
	}

	return schedulerapi.HostPriority{
		Host:  node.Name,
		Score: countIntolerableTaintsPreferNoSchedule(node.Spec.Taints, tolerationsPreferNoSchedule),
	}, nil
}

// ComputeTaintTolerationPriorityReduce calculates the source of each node based on the number of intolerable taints on the node
func ComputeTaintTolerationPriorityReduce(pod *v1.Pod, meta interface{}, nodeNameToInfo map[string]*schedulercache.NodeInfo, result schedulerapi.HostPriorityList) error {
	var maxCount int
	for i := range result {
		if result[i].Score > maxCount {
			maxCount = result[i].Score
		}
	}
	maxCountFloat := float64(maxCount)

	// The maximum priority value to give to a node
	// Priority values range from 0 - maxPriority
	const maxPriority = float64(10)
	for i := range result {
		fScore := maxPriority
		if maxCountFloat > 0 {
			fScore = (1.0 - float64(result[i].Score)/maxCountFloat) * 10
		}
		if glog.V(10) {
			// We explicitly don't do glog.V(10).Infof() to avoid computing all the parameters if this is
			// not logged. There is visible performance gain from it.
			glog.Infof("%v -> %v: Taint Toleration Priority, Score: (%d)", pod.Name, result[i].Host, int(fScore))
		}
		result[i].Score = int(fScore)
	}
	return nil
}


text:
'use strict';

var _ = require('lodash');

var utils = require('./utils');

// todo: TBD add options: isTabsVisible on default page
module.exports = function (schema) {
  var paths = utils.getPaths(schema, {});
  var _schema = utils.toUiFormsSchema(paths);
  var tabs = _(paths).map(function (p) {
    if (!p.tabName) {
      return false;
    }

    return {name: p.tabName, order: p.tabOrder};
  })
    .compact()
    .unique('name')
    .sortBy('order')
    .value();

  function toUiFormsSchema() {
    return _schema;
  }

  function getUiFormsProjection() {
    return _.pluck(_schema, 'field').join(' ');
  }

  Object.defineProperties(schema.statics, {
    UiFormsTabs: {value: tabs, enumerable: true},
    UiFormsSchema: {value: _schema, enumerable: true}
  });

  schema.statics.getUiFormsProjection = getUiFormsProjection;
  schema.statics.getUiFormsSchema = toUiFormsSchema;
};


text:
package dk.itu.noxdroid.ioio;

public interface IOIOEventListener {
	public void notify(int msg);
}


text:
"""
[1/2/2013] Challenge #115 [Difficult] Pack-o-Tron 5000

https://www.reddit.com/r/dailyprogrammer/comments/15uohz/122013_challenge_115_difficult_packotron_5000/

**Description:**
Overdrive Mega-Corporation is coming out with a new and brilliant commercial electronic device that packs your bags for
you! It is named "Pack-o-Tron 5000": an automated box-packing solution. Moving to a new home? Traveling overseas? Going
on a business trip? No matter what, this device will help you pack your boxes optimally, reducing empty space and
fitting more objects in less area!
As the lead engineer, you are tasked with designing the code that generates the "optimal placement" of items in a given
area. Fortunately for you, the "Pack-o-Tron 5000" only works with very specific definitions of "items" and "areas".
(Shh, don't tell the customers that, marketing is still working on it).
An "area" is an empty 2D grid, where the length and width are integers representing inches. As an example, a suitcase
could be defined as a 36-inch by 48-inch grid. An "item" is a 2D object, whose length and width are integers
representing inches. As an example, a tooth-brush item can be 1-inch in width, and 3-inches long.
Your goal is to place all given items in a given area as optimally as possible. "Optimally" is defined as having the
smallest minimum-rectangle that spans your set of items.
Note that the "area" is defined as a grid where the origin is in the top-left and X+ grows to the right, with Y+
growing to the bottom. An item's origin is in the top-left, with X+ growing to the right, and Y+ growing to the bottom.
A minimum-rectangle that spans your set of items is a rectangle on the grid that includes all items placed, and is
either equal to or smaller than the given area. Your goal is to make this minimum-span as small as possible. You are
allowed to place your objects in any position, as long as it is in the grid. You are also allowed to rotate your
objects by 90 degrees.
[Here is an album of several examples of how objects are placed, and how they can be moved and rotated to minimized the
minimum-span rectangle.](http://imgur.com/a/M3MNk)
**Formal Inputs & Outputs:**
*Input Description:*
You will first be given two integers: the width and height of your starting (empty) grid. After, you will be given
another integer representing the number of following items you are to place in this grid. For each item, you will be
given two integers: the width and height of the object. All of this is done through standard input. (i.e. console).
*Output Description:*
Once you have optimally placed the given items in the given grid such that it as the smallest minimum-span possible,
you must print each item's x and y coordinate (as an integer), and the object's size (to show us if there has been any
rotations).
**Sample Inputs & Outputs:**
[Take a look at the example images here.](http://imgur.com/a/M3MNk) For all images that have the two 1x3 items, you
would be given the following sample input:
    8 8
    2
    1 3
    1 3
The most optimal result (the last image) is a 2x3 minimum-span, which can be described in the following:
    0 0 1 3
    1 0 1 3
For those who are keen observers, an equivalent solution is the same pair of objects, but mirrored on the diagonal axis:
    0 0 3 1
    0 1 3 1
*Note:*
This is essentially a clean version of the [Packing Problem](http://en.wikipedia.org/wiki/Packing_problem). Since the
packing problem is in the computational complexity class of NP-hard, there is no known algorithm to run in P-time
(...yet! Maybe there is! But that's the whole P-NP relationship problem, isn't it? :P). Instead, look into heuristic
algorithm designs, and try to avoid brute-force solutions.
Us mods are putting together an achievement system - those who give us a good solution will get some sort of cool title
in their user-flare, since this challenge is frankly very *very* difficult.
"""

def main():
    pass

if __name__ == "__main__":
    main()


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
/**
 * The "continue" token can not be used as identifier
 *
 * @path ch07/7.6/7.6.1/7.6.1.1/S7.6.1.1_A1.4.js
 * @description Checking if execution of "contunue=1" fails
 * @negative
 */

continue = 1;


text:
//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-2015, Egret Technology Inc.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

module egret.gui {
    /**
     * @class egret.gui.EaseInOutBase
     * @classdesc
     * EaseInOutBase 类是提供缓动功能的基类。
     * @implements egret.gui.IEaser
     */
    export class EaseInOutBase implements IEaser{
        /**
         * @param easeInFraction 缓入过程所占动画播放时间的百分比。剩余即为缓出的时间。
         * 默认值为 EasingFraction.IN_OUT,它会缓入前一半时间,并缓出剩余的一半时间。
         * @method egret.gui.EaseInOutBase#constructor
         */
        public constructor(easeInFraction:number = 0.5){
            this.easeInFraction = easeInFraction;
        }

        private _easeInFraction:number = .5;
        /**
         * 缓入过程所占动画播放时间的百分比。剩余即为缓出的时间。
         * 有效值为 0.0 到 1.0。
         */
        public get easeInFraction():number{
            return this._easeInFraction;
        }

        public set easeInFraction(value:number){
            this._easeInFraction = value;
        }

        public ease(fraction:number):number{
            var easeOutFraction:number = 1 - this._easeInFraction;

            if (fraction <= this._easeInFraction && this._easeInFraction > 0)
                return this._easeInFraction * this._easeIn(fraction/this._easeInFraction);
            else
                return this._easeInFraction + easeOutFraction *
                    this._easeOut((fraction - this._easeInFraction)/easeOutFraction);
        }
        /**
         * 在动画的缓入阶段期间计算已经缓动部分要映射到的值。
         */
        public _easeIn(fraction:number):number{
            return fraction;
        }

        /**
         * 在动画的缓出阶段期间计算已经缓动部分要映射到的值。
         */
        public _easeOut(fraction:number):number{
            return fraction;
        }

    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Intérprete de BASIC: C:/Users/figura4/Dropbox/común/Curso/PruebaGui/src/operadores/OperadorNEQ.h Source File</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />

<link href="search/search.css" rel="stylesheet" type="text/css"/>

Intérprete de BASIC

Main Page

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

 All Classes Namespaces Files Functions Variables Friends

C:/Users/figura4/Dropbox/común/Curso/PruebaGui/src/operadores/OperadorNEQ.h

Go to the documentation of this file.

00001 #ifndef OPERADORNEQ_H
00002 #define OPERADORNEQ_H
00003
00004 #include "..\Operador.h"
00005
00007 class OperadorNEQ : public Operador
00008 {
00009     public:
00010         OperadorNEQ();
00011         virtual ~OperadorNEQ();
00016         std::string ejecuta(Operando* opA, Operando* opB);
00019         std::string getSimbolo();
00020     protected:
00021     private:
00023         static const std::string SIMBOLO;
00024 };
00025
00026 #endif // OPERADORNEQ_H

<address class="footer">
Generated on Mon Jun 4 2012 01:01:33 for Intérprete de BASIC by

 1.8.0
</address>


text:
require 'rails_helper'

describe OpmlExportJobState, type: :model do

  before :each do
    @user = FactoryBot.create :user
    @filename = 'some_filename.opml'
  end

  context 'validations' do

    it 'always belongs to a user' do
      opml_export_job_state = FactoryBot.build :opml_export_job_state, user_id: nil
      expect(opml_export_job_state).not_to be_valid
    end

    it 'has filename if it has state SUCCESS' do
      opml_export_job_state = FactoryBot.build :opml_export_job_state, user_id: @user.id,
                                                state: OpmlExportJobState::SUCCESS,
                                                filename: nil,
                                                export_date: Time.zone.now
      expect(opml_export_job_state).not_to be_valid

      opml_export_job_state = FactoryBot.build :opml_export_job_state, user_id: @user.id,
                                                state: OpmlExportJobState::SUCCESS,
                                                filename: @filename,
                                                export_date: Time.zone.now
      expect(opml_export_job_state).to be_valid
    end

    it 'does not have a filename if it has state NONE' do
      opml_export_job_state = FactoryBot.build :opml_export_job_state, user_id: @user.id,
                                                state: OpmlExportJobState::NONE,
                                                filename: @filename
      opml_export_job_state.save!
      expect(opml_export_job_state.filename).to be_nil
    end

    it 'does not have a filename if it has state RUNNING' do
      opml_export_job_state = FactoryBot.build :opml_export_job_state, user_id: @user.id,
                                                state: OpmlExportJobState::RUNNING,
                                                filename: @filename
      opml_export_job_state.save!
      expect(opml_export_job_state.filename).to be_nil
    end

    it 'does not have a filename if it has state ERROR' do
      opml_export_job_state = FactoryBot.build :opml_export_job_state, user_id: @user.id,
                                                state: OpmlExportJobState::ERROR,
                                                filename: @filename
      opml_export_job_state.save!
      expect(opml_export_job_state.filename).to be_nil
    end

    it 'has export_date if it has state SUCCESS' do
      opml_export_job_state = FactoryBot.build :opml_export_job_state, user_id: @user.id,
                                                state: OpmlExportJobState::SUCCESS,
                                                export_date: nil
      expect(opml_export_job_state).not_to be_valid

      opml_export_job_state = FactoryBot.build :opml_export_job_state, user_id: @user.id,
                                                state: OpmlExportJobState::SUCCESS,
                                                export_date: Time.zone.now
      expect(opml_export_job_state).to be_valid
    end

    it 'does not have an export_date if it has state NONE' do
      opml_export_job_state = FactoryBot.build :opml_export_job_state, user_id: @user.id,
                                                state: OpmlExportJobState::NONE,
                                                export_date: Time.zone.now
      opml_export_job_state.save!
      expect(opml_export_job_state.export_date).to be_nil
    end

    it 'does not have an export_date if it has state RUNNING' do
      opml_export_job_state = FactoryBot.build :opml_export_job_state, user_id: @user.id,
                                                state: OpmlExportJobState::RUNNING,
                                                export_date: Time.zone.now
      opml_export_job_state.save!
      expect(opml_export_job_state.export_date).to be_nil
    end

    it 'does not have an export_date if it has state ERROR' do
      opml_export_job_state = FactoryBot.build :opml_export_job_state, user_id: @user.id,
                                                state: OpmlExportJobState::ERROR,
                                                export_date: Time.zone.now
      opml_export_job_state.save!
      expect(opml_export_job_state.export_date).to be_nil
    end
  end

  context 'default values' do

    it 'defaults to state NONE when created' do
      @user.create_opml_export_job_state
      expect(@user.opml_export_job_state.state).to eq OpmlExportJobState::NONE
    end

    it 'defaults show_alert to true' do
      opml_export_job_state = FactoryBot.build :opml_export_job_state, show_alert: nil
      opml_export_job_state.save!
      expect(opml_export_job_state.show_alert).to be true
    end
  end

  it 'deletes OPML file when deleting a opml_export_job_state' do
    filename = 'some_filename.opml'
    @user.create_opml_export_job_state
    @user.opml_export_job_state.update state: OpmlExportJobState::SUCCESS,
                                       filename: filename,
                                       export_date: Time.zone.now
    allow(Feedbunch::Application.config.uploads_manager).to receive(:exists?).and_return true
    expect(Feedbunch::Application.config.uploads_manager).to receive(:delete).once do |user_id, folder, file|
      expect(user_id).to eq @user.id
      expect(folder).to eq OpmlExporter::FOLDER
      expect(file).to eq filename
    end

    @user.opml_export_job_state.destroy
  end

end


text:
package yy.tidialogs;

import java.util.Calendar;
import java.util.Date;

import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.util.TiUIHelper;
import org.appcelerator.titanium.view.TiUIView;

import android.R;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.text.format.DateFormat;
import android.widget.TimePicker;

@Kroll.proxy(creatableInModule = TidialogsModule.class)
public class TimePickerProxy extends TiViewProxy {
	private class BasicDatePicker extends TiUIView {

		private int hour;
		private int minute;

		private String okButtonTitle;
		private String cancelButtonTitle;

		public BasicDatePicker(TiViewProxy proxy) {
			super(proxy);

		}

		private TimePickerDialog getDialog() {
			TimePickerDialog picker = new TimePickerDialog(this.proxy.getActivity(),
						new TimePickerDialog.OnTimeSetListener() {

							@Override
							public void onTimeSet(TimePicker selectedTime,
									int selectedHour, int selectedMinute) {
								// TODO Auto-generated method stub

								hour = selectedHour;
								minute = selectedMinute;

								KrollDict data = new KrollDict();

									Calendar calendar = Calendar.getInstance();
									calendar.set(Calendar.HOUR_OF_DAY, hour);
									calendar.set(Calendar.MINUTE, minute);
									Date value = calendar.getTime();

									data.put("value", value);
									data.put("hour", hour);
									data.put("minute", minute);
                                    fireEvent("click", data);

							}
						}, hour, minute, DateFormat.is24HourFormat(this.proxy
								.getActivity()));

			picker.setCanceledOnTouchOutside(false);

			picker.setButton(DialogInterface.BUTTON_POSITIVE, okButtonTitle, picker);

			picker.setButton(DialogInterface.BUTTON_NEGATIVE, cancelButtonTitle,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						fireEvent("cancel", new KrollDict());
					}
				});

			return picker;
		}

		@Override
		public void processProperties(KrollDict d) {
			super.processProperties(d);

			Calendar c = Calendar.getInstance();
			if (d.containsKey("value")) {
				c.setTime((Date) d.get("value"));
				hour = c.get(Calendar.HOUR_OF_DAY);
				minute = c.get(Calendar.MINUTE);
			} else {
				if (d.containsKey("hour")) {
					hour = d.getInt("hour");
				} else {
					hour = c.get(Calendar.HOUR_OF_DAY);
				}
				if (d.containsKey("minute")) {
					minute = d.getInt("minute");
				} else {
					minute = c.get(Calendar.MINUTE);
				}
			}

			if (d.containsKey("okButtonTitle")) {
				okButtonTitle = d.getString("okButtonTitle");
			} else {
				okButtonTitle =  this.proxy.getActivity().getApplication().getResources().getString(R.string.ok);
			}
			if (d.containsKey("cancelButtonTitle")) {
				cancelButtonTitle = d.getString("cancelButtonTitle");
			} else {
				cancelButtonTitle = this.proxy.getActivity().getApplication().getResources().getString(R.string.cancel);
			}
		}

		public void show() {
			getDialog().show();
		}

	}

	public TimePickerProxy() {
		super();
	}

	@Override
	public TiUIView createView(Activity activity) {
		return new BasicDatePicker(this);
	}

	@Override
	public void handleCreationDict(KrollDict options) {
		super.handleCreationDict(options);
	}

	@Override
	protected void handleShow(KrollDict options) {
		super.handleShow(options);
		TiUIHelper.runUiDelayedIfBlock(new Runnable() {
			@Override
			public void run() {
				BasicDatePicker d = (BasicDatePicker) getOrCreateView();
				d.show();
			}
		});
	}
}


text:
/*
 * File.h
 *
 *  Created on: Jun 1, 2017
 *      Author: kolban
 */

#ifndef COMPONENTS_CPP_UTILS_FILE_H_
#define COMPONENTS_CPP_UTILS_FILE_H_
#include <string>
#include <dirent.h>

/**
 * @brief A logical representation of a file.
 */
class File {
public:
	File(std::string name, uint8_t type = DT_UNKNOWN);

	std::string getContent(bool base64Encode = false);
	std::string getContent(uint32_t offset, uint32_t size);
	std::string getName();
	std::string getPath();
	uint8_t     getType();
	bool        isDirectory();
	uint32_t    length();

private:
	std::string m_path;
	uint8_t     m_type;
};

#endif /* COMPONENTS_CPP_UTILS_FILE_H_ */


text:
#region

using System;
using System.Collections.Generic;
using System.IdentityModel.Services;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Web;
using Sitecore;
using Sitecore.Configuration;
using Sitecore.Diagnostics;
using Sitecore.Security.Accounts;
using Sitecore.Security.Authentication;
using Sitecore.Web;

#endregion

namespace ADFS.Authenticator.Pipelines.HttpRequest
{
    public class LoginHelper
    {
        /// <summary>
        /// Logins the specified user.
        /// </summary>
        /// <param name="user">The user.</param>
        public void Login(IPrincipal user)
        {
            var identity = user.Identity;

#if DEBUG
            WriteClaimsInfo(user.Identity as ClaimsIdentity);
#endif
            if (!identity.IsAuthenticated)
                return;
            var userName = string.Format("{0}\\{1}", Context.Domain.Name, identity.Name);
            try
            {
                var virtualUser = AuthenticationManager.BuildVirtualUser(userName, true);
                var roles = Context.Domain.GetRoles();
                if (roles != null)
                {
                    var groups = GetGroups(user.Identity as ClaimsIdentity);
                    foreach (var role in from role in roles
                                         let roleName = GetRoleName(role.Name)
                                         where groups.Contains(roleName.ToLower()) && !virtualUser.Roles.Contains(role)
                                         select role)
                    {
                        virtualUser.Roles.Add(role);
                    }
                    foreach (
                        var role2 in
                            virtualUser.Roles.SelectMany(
                                role1 =>
                                    RolesInRolesManager.GetRolesForRole(role1, true)
                                        .Where(role2 => !virtualUser.Roles.Contains(role2))))
                    {
                        virtualUser.Roles.Add(role2);
                    }

                    // Setting the user to be an admin.
                    virtualUser.RuntimeSettings.IsAdministrator =
                        groups.Contains(Settings.GetSetting("ADFS.Authenticator.AdminUserRole", "Admins"));
                }

                AuthenticationManager.Login(virtualUser);
            }
            catch (ArgumentException ex)
            {
                Log.Error("ADFS::Login Failed!", ex, this);
            }
        }

        /// <summary>
        /// Gets the group names.
        /// </summary>
        /// <param name="claimsIdentity">The claims identity.</param>
        /// <returns></returns>
        private static IEnumerable<string> GetGroups(ClaimsIdentity claimsIdentity)
        {
            var enumerable =
                claimsIdentity.Claims.Where(
                    c => c.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").ToList();
            var list = new List<string>();
            foreach (
                var str in
                    enumerable.Select(claim => claim.Value.ToLower().Replace('-', '_'))
                        .Where(str => !list.Contains(str)))
            {
                list.Add(str);
            }
            return list.ToArray();
        }

        /// <summary>
        /// Gets the name of the role.
        /// </summary>
        /// <param name="roleName">Name of the role.</param>
        /// <returns></returns>
        private static string GetRoleName(string roleName)
        {
            if (!roleName.Contains('\\'))
                return roleName;
            return roleName.Split(new[]
            {
                '\\'
            })[1];
        }

        /// <summary>
        /// Requests the token.
        /// </summary>
        public static void RequestToken()
        {
            var url =
                FederatedAuthentication.WSFederationAuthenticationModule.CreateSignInRequest(Guid.NewGuid().ToString(),
                    HttpContext.Current.Request.RawUrl, false).WriteQueryString();
            if (string.IsNullOrWhiteSpace(url))
                return;

            WebUtil.Redirect(url);
        }

        /// <summary>
        /// Writes the claims information.
        /// </summary>
        /// <param name="claimsIdentity">The claims identity.</param>
        private void WriteClaimsInfo(ClaimsIdentity claimsIdentity)
        {
            Log.Info("Writing Claims Info", this);
            foreach (var claim in claimsIdentity.Claims)
                Log.Info(string.Format("Claim : {0} , {1}", claim.Type, claim.Value), this);
        }

        /// <summary>
        /// Adds the claims information.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="claimsIdentity">The claims identity.</param>
        public void AddClaimsInfo(User user, ClaimsIdentity claimsIdentity)
        {
        }
    }
}


text:
<!DOCTYPE HTML>

        <meta charset="UTF-8">
<meta name="generator" content="Jekyll v3.1.6">
<link type="application/atom+xml" rel="alternate" href="http://localhost:4000/feed.xml" title="JekyllTemplate by ~Manuel Thalmann" />
<link rel="icon" type="image/x-icon" href="../favicon.ico">
<link rel="stylesheet" type="text/css" href="../assets/css/styles.css" />
<link rel="stylesheet" type="text/css" href="../assets/css/markdown.css" />
<link href="../dist/css/bootstrap.min.css" rel="stylesheet">
<link href="../dist/css/bootstrap-theme.min.css" rel="stylesheet">

<title>Documents - JekyllTemplate by ~Manuel Thalmann</title>
<meta property="og:title" content="Documents" />
<meta name="description" content="  Docs Main-Entry 1          A Sub-Entry      Some Thingies      Another Thingy        Docs Main-Entry 2          Some Thingies      Another Thingy      A Sub-Entry      " />
<meta property="og:description" content="  Docs Main-Entry 1          A Sub-Entry      Some Thingies      Another Thingy        Docs Main-Entry 2          Some Thingies      Another Thingy      A Sub-Entry      " />
<link rel="canonical" href="http://localhost:4000/docs/" />
<meta property="og:url" content="http://localhost:4000/docs/" />
<meta property="og:site_name" content="JekyllTemplate by ~Manuel Thalmann" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2016-12-15T23:20:55+01:00" />

    JekyllTemplate

A nice template for a github-page

            Home

            Documents

            Presentations

Documents

Docs Main-Entry 1

A Sub-Entry

Some Thingies

Another Thingy

Docs Main-Entry 2

Some Thingies

Another Thingy

A Sub-Entry

        Manuel Thalmann

    maintains
    JekyllTemplate

                This page generated using GitHub Pages

                Theme by Manuel Thalmann

                Last Build:
15.
Dezember

2016
23:20:55


text:
<?php

namespace App\Model\Table;

use App\Model\Entity\Banco;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\ORM\Entity;
use Cake\Event\Event;
use Search\Manager;

/**
 * Bancos Model
 *
 * @property \Cake\ORM\Association\HasMany $ContasPagar
 * @property \Cake\ORM\Association\HasMany $ContasReceber
 */
class BancosTable extends Table {

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config) {
        parent::initialize($config);

        $this->table('bancos');
        $this->displayField('nome');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->hasMany('ContasPagar', [
            'foreignKey' => 'banco_id'
        ]);
        $this->hasMany('ContasReceber', [
            'foreignKey' => 'banco_id'
        ]);
        $this->addBehavior('Search.Search');
    }

    public function searchConfiguration() {
        return $this->searchConfigurationDynamic();
    }

    private function searchConfigurationDynamic() {
        $search = new Manager($this);
        $c = $this->schema()->columns();
        foreach ($c as $key => $value) {
            $t = $this->schema()->columnType($value);
            if ($t != 'string' AND $t != 'text') {
                $search->value($value, ['field' => $this->aliasField($value)]);
            } else {
                $search->like($value, ['before' => true, 'after' => true, 'field' => $this->aliasField($value)]);
            }
        }

        return $search;
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator) {
        $validator->provider('extra', new \App\Model\Validation\ExtraValidator());
        $validator
                ->add('id', 'valid', ['rule' => 'numeric'])
                ->allowEmpty('id', 'create');

        $validator
                ->add('codigo_banco', 'valid', ['rule' => 'numeric'])
                ->allowEmpty('codigo_banco');

        $validator
                ->allowEmpty('nome');

        $validator
                ->allowEmpty('agencia');

        $validator
                ->allowEmpty('conta_corrente');

        $validator
                ->add('sequencial_arquivo', 'valid', ['rule' => 'numeric'])
                ->allowEmpty('sequencial_arquivo');

        $validator
                ->allowEmpty('caminho_arquivo');

        $validator
                ->allowEmpty('sacador_avalista');

        $validator
                ->add('cnpj_sacador', 'valid', ['provider' => 'extra', 'rule' => 'moeda', 'message' => __('CNPJ Informado esta invalido')])
                ->allowEmpty('cnpj_sacador');

        $validator
                ->allowEmpty('contrato');

        $validator
                ->allowEmpty('carteira');

        $validator
                ->allowEmpty('convenio');

        return $validator;
    }

    public function beforeSave(Event $event, Entity $entity) {
        $entity->cnpj_sacador = str_replace(['.', '-', '/'], '', $entity->cnpj_sacador);
        $entity->caminho_arquivo = ROOT . DS . 'webroot' . DS . 'Banco' . DS . '{id}-{nome}' . DS;
    }

}


text:
package org.apache.drill.exec.compile;

import org.apache.drill.exec.compile.sig.RuntimeOverridden;

public abstract class ExampleTemplateWithInner implements ExampleInner{
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ExampleTemplateWithInner.class);

  public abstract void doOutside();
  public class TheInnerClass{

    @RuntimeOverridden
    public void doInside(){};

    public void doDouble(){
      DoubleInner di = new DoubleInner();
      di.doDouble();
    }

    public class DoubleInner{
      @RuntimeOverridden
      public void doDouble(){};
    }

  }

  public void doInsideOutside(){
    TheInnerClass inner = new TheInnerClass();
    inner.doInside();
    inner.doDouble();
  }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.core.preference;

import java.io.Serializable;
import java.util.Objects;

/**
 *
 * @author Gonza
 */
public class Address implements Serializable{

    private String zip_code;
    private String street_name;
    private String street_number;

    public Address() {
    }

    public Address(String zip_code, String street_name, String street_number) {
        this.zip_code = zip_code;
        this.street_name = street_name;
        this.street_number = street_number;
    }

    public String getZip_code() {
        return zip_code;
    }

    public void setZip_code(String zip_code) {
        this.zip_code = zip_code;
    }

    public String getStreet_name() {
        return street_name;
    }

    public void setStreet_name(String street_name) {
        this.street_name = street_name;
    }

    public String getStreet_number() {
        return street_number;
    }

    public void setStreet_number(String street_number) {
        this.street_number = street_number;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 67 * hash + Objects.hashCode(this.zip_code);
        hash = 67 * hash + Objects.hashCode(this.street_name);
        hash = 67 * hash + Objects.hashCode(this.street_number);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Address other = (Address) obj;
        if (!Objects.equals(this.zip_code, other.zip_code)) {
            return false;
        }
        if (!Objects.equals(this.street_name, other.street_name)) {
            return false;
        }
        if (!Objects.equals(this.street_number, other.street_number)) {
            return false;
        }
        return true;
    }

}


text:
package kembe.transform;

import fj.P;
import fj.P2;
import fj.data.Either;
import fj.data.List;
import fj.data.Option;
import kembe.Mealy;
public class LeftJoin<A,B> extends Mealy<Either<A,B>, Option<P2<A,List<B>>>> {

    final List<B> bs;

    public LeftJoin( List<B> bs) {
        this.bs = bs;
    }

    @Override public Transition<Either<A,B>, Option<P2<A,List<B>>>> apply(Either<A, B> value) {
        if (value.isLeft()) {
            return Mealy.transition( Option.some( P.p( value.left().value(), bs ) ), new LeftJoin<A, B>( List.<B>nil() ) );
        }else
            return Mealy.transition( Option.<P2<A, List<B>>>none(), new LeftJoin<A, B>( bs.cons( value.right().value() ) ) );
    }

}


text:
<!DOCTYPE html>
<html>
<head>
	<title>Circles</title>
	<link rel="stylesheet" type="text/css" href="lib/css/circles.css">
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.0.0/howler.core.min.js"></script>
	<script type="text/javascript" src="lib/paper-full.js"></script>
	<script type="text/paperscript" canvas="myCanvas">
	var circles = [];

	var sound = new Howl({
		src: ['sounds/bubbles.mp3']
	});

	function onKeyDown(event) {
	sound.play();

	var maxPoint = new Point(view.size.width, view.size.height);
	var randomPoint = Point.random();
	var point = maxPoint * randomPoint;
	var newCircle = new Path.Circle(point, 100);
		newCircle.fillColor = "orange";
		circles.push(newCircle);
	}

	function onFrame(event){
		for(var i=0; i<circles.length; i++)
		{
			circles[i].fillColor.hue += 1;
			circles[i].scale(.9);
		}
	}

	</script>
</head>
<body>
<canvas id="myCanvas" resize></canvas>

<script type="text/javascript" src="lib/js/circles.js"></script>
</body>
</html>


text:
TensorBuilder's DSL enables you to express the computation do desire to do into a single flexible structure. The DSL preserves all features of given to you by the `Builder` class:

* Composing operations
* Branching
* Scoping

The `Applicative` was built to create elements that are accepted/play well will this language. It also two very import methods

* `compile`: generates a function out a given valid **ast**/structure (compiles it)
* `pipe`: given `Builder` or `Tensor` and an **ast**, compile it to a function and apply it to the Tensor/Builder.

## Rules

* All final elements in the "AST" must be functions, non final elements are compiled to a function.
* A Tuple `()` denotes a sequential operation. Results in the composition of all elements within it.
* A List `[]` denotes a branching operation. Results in the creation of a function that applies the `.branch` method to its argument, and each element in the list results in a branch. It compiles to a function of type `Builder -> BuilderTree`.
* A Dict `{}` denotes a scoping operation. It only accepts a single key-value pair, its key must me a [Disposable](https://www.python.org/dev/peps/pep-0343/) and its value can be any element of the language. It results in the creation of a function that takes a `Builder` as its argument, applies the `with` statemente to the `key` and applies the function of the `value` to its argument inside the `with` block.

## Example

Its easier to see the actual DSL with an example, especially because you can see a direct mapping of the concepts brought by the `Builder` class into the DSL:

    import tensorflow as tf
    from phi import tb

    x = placeholder(tf.float32, shape=[None, 10])
    y = placeholder(tf.float32, shape=[None, 5])

    [h, trainer] = tb.pipe(
        x,
        [
            { tf.device("/gpu:0"):
                tb.relu_layer(20)
            }
        ,
            { tf.device("/gpu:1"):
                tb.sigmoid_layer(20)
            }
        ,
            { tf.device("/cpu:0"):
                tb.tanh_layer(20)
            }
        ],
        tb.relu_layer(10)
        .linear_layer(5),
        [
            tb.softmax() # h
        ,
            tb.softmax_cross_entropy_with_logits(y)
            .reduce_mean()
            .map(tf.trainer.AdamOptimizer(0.01).minimize) # trainer
        ],
        tb.tensors()
    )

Lets go step by step to what is happening here:

1. The Tensor `x` pluged inside a `Builder` and *piped* through the computational structured defined. All the arguments of `pipe` after `x` are grouped as if they were in a tuple `()` and the whole expression is compiled to a single function with is then applied to the `Buider` containing `x`.
1. **final** elements you see here like `tb.softmax()` are `Applicative`s which as you've been told are functions. As you see, *almost* all methods from the `Builder` class are also methods from the `Applicative` class, the diference is that the methods of the `Builder` class actually perform the computation they intend (construct a new Tensor), but the methods from the `Applicative` class rather *compose/define* the computation to be done later.
1. There is an implicit Tuple `()` element that is performing a sequential composition of all the other elements. As a result, the visual/spatial ordering of the code corresponds to the intended behavior.
1. Lists very naturally express branches. Notice how indentation and an intentional positioning of the `,` comma help to diferentiate each branch.
1. Expresions like `tb.relu_layer(10)` are polymorphic and work for `Builder`s or `BuilderTree`s regardless.
1. Scoping is very clean with the `{}` notation. In constrast to using `then_with` from the `Builder` class, here you can actually use the original functions from `tensorflow` unchanged in the `key` of the dict.


text:
Casts to a ServiceResult with a value.

```csharp
public ServiceResult<T> Cast<T>()
```

## Remarks

A failed ServiceResult can be cast to a ServiceResult of any type. A successful ServiceResult can only be cast to a ServiceResult of another type if its value can be successfully cast through object.

## See Also

* class [ServiceResult<T>](../ServiceResult-1.md)
* class [ServiceResult](../ServiceResult.md)
* namespace [Facility.Core](../../Facility.Core.md)

<!-- DO NOT EDIT: generated by xmldocmd for Facility.Core.dll -->


text:
namespace MetaMorpheusGUI
{
    public class GuiGlobalParams
    {
        public bool AskAboutUpdating { get; internal set; } = true;
        public bool AskBeforeExitingMetaMorpheus { get; internal set; } = true;

        //Ask about protease-specific parameter recommendations
        public bool AskAboutTopDownParams { get; internal set; } = true;
        public bool AskAboutChymotrypsinParams { get; internal set; } = true;
        public bool AskAboutElastaseParams { get; internal set; } = true;
        public bool AskAboutNonSpecificParams { get; internal set; } = true;
        public bool AskAboutSemiTrypsinParams { get; internal set; } = true;
        public bool AskAboutArgCParams { get; internal set; } = true;

        //Use protease-specific parameter recommendations
        public bool UseTopDownParams { get; internal set; } = true;
        public bool UseChymotrypsinParams { get; internal set; } = true;
        public bool UseElastaseParams { get; internal set; } = true;
        public bool UseNonSpecificParams { get; internal set; } = true;
        public bool UseSemiTrypsinParams { get; internal set; } = true;
        public bool UseArgCParams { get; internal set; } = true;
    }
}