text:
[![MEAN.JS Logo](http://meanjs.org/img/logo-small.png)](http://meanjs.org/)

## AACC Web Application

redpajama_set_name: RedPajamaGithub


text:
#import <UIKit/UIKit.h>

#import "BeaconData.h"
#import "Beacons.h"

@interface ConfigTableViewController : UITableViewController
@property (weak, nonatomic) IBOutlet UITextField *nameText;
@property (weak, nonatomic) IBOutlet UILabel *uuidLabel;
@property (weak, nonatomic) IBOutlet UITextField *majorText;
@property (weak, nonatomic) IBOutlet UITextField *minorText;
@property (weak, nonatomic) IBOutlet UILabel *eventLabel;
@property (weak, nonatomic) IBOutlet UILabel *actionLabel;
@property (weak, nonatomic) IBOutlet UISwitch *enableSwitch;

@property(strong, nonatomic) Beacons *selectedBeacon;
@property(strong, nonatomic) BeaconData *existingBeacon;
@property(nonatomic) BOOL isAddView;

- (IBAction)enableSwitchChanged:(UISwitch *)sender;

@end


text: <img src="img/splatter.png" alt="Apple sauce all over Rick's glasses" width="50%">


text:
typedef struct WindowPropsPacket WindowPropsPacket;

struct __attribute__((__packed__)) WindowPropsPacket {
  Packet packet;
  uint32_t id;
  GColor8 background_color;
  bool fullscreen;
  bool scrollable;
};

typedef struct WindowButtonConfigPacket WindowButtonConfigPacket;

struct __attribute__((__packed__)) WindowButtonConfigPacket {
  Packet packet;
  uint8_t button_mask;
};

typedef struct WindowActionBarPacket WindowActionBarPacket;

struct __attribute__((__packed__)) WindowActionBarPacket {
  Packet packet;
  uint32_t image[3];
  bool action;
  GColor8 background_color;
};

typedef struct ClickPacket ClickPacket;

struct __attribute__((__packed__)) ClickPacket {
  Packet packet;
  ButtonId button:8;
};

typedef ClickPacket LongClickPacket;

static GColor8 s_button_palette[] = { { GColorWhiteARGB8 }, { GColorClearARGB8 } };

static void click_config_provider(void *data);

static bool send_click(SimplyMsg *self, Command type, ButtonId button) {
  ClickPacket packet = {
    .packet.type = type,
    .packet.length = sizeof(packet),
    .button = button,
  };
  return simply_msg_send_packet(&packet.packet);
}

static bool send_single_click(SimplyMsg *self, ButtonId button) {
  return send_click(self, CommandClick, button);
}

static bool send_long_click(SimplyMsg *self, ButtonId button) {
  return send_click(self, CommandLongClick, button);
}

static void set_scroll_layer_click_config(SimplyWindow *self) {
  if (!self->scroll_layer) {
    return;
  }

  scroll_layer_set_click_config_provider_onto_window(
      self->scroll_layer, click_config_provider, self->window, self);
}

void simply_window_set_scrollable(SimplyWindow *self, bool is_scrollable) {
  if (self->is_scrollable == is_scrollable) {
    return;
  }

  self->is_scrollable = is_scrollable;

  set_scroll_layer_click_config(self);

  if (!self->layer) {
    return;
  }

  if (!is_scrollable) {
    GRect bounds = { GPointZero, layer_get_bounds(window_get_root_layer(self->window)).size };
    layer_set_bounds(self->layer, bounds);
    // TODO: change back to animated when a closing animated scroll doesn't cause a crash
    const bool animated = false;
    scroll_layer_set_content_offset(self->scroll_layer, GPointZero, animated);
    scroll_layer_set_content_size(self->scroll_layer, bounds.size);
  }

  layer_mark_dirty(self->layer);
}

void simply_window_set_fullscreen(SimplyWindow *self, bool is_fullscreen) {
  bool changed = false;
  if (is_fullscreen && self->is_status_bar) {
    status_bar_layer_remove_from_window(self->window, self->status_bar_layer);
    self->is_status_bar = false;
    changed = true;
  } else if (!is_fullscreen && !self->is_status_bar) {
    status_bar_layer_add_to_window(self->window, self->status_bar_layer);
    self->is_status_bar = true;
    changed = true;
  }

  if (!changed || !self->layer) {
    return;
  }

  GRect frame = { GPointZero, layer_get_frame(window_get_root_layer(self->window)).size };
  scroll_layer_set_frame(self->scroll_layer, frame);
  layer_set_frame(self->layer, frame);

#ifdef PBL_SDK_2
  if (!window_stack_contains_window(self->window)) {
    return;
  }

  // HACK: Refresh app chrome state
  uint32_t id = self->id;
  self->id = 0;
  Window *window = window_create();
  window_stack_push(window, false);
  window_stack_remove(window, false);
  window_destroy(window);
  self->id = id;
#endif
}

void simply_window_set_background_color(SimplyWindow *self, GColor8 background_color) {
  self->background_color = background_color;
}

void simply_window_set_action_bar(SimplyWindow *self, bool is_action_bar) {
  self->is_action_bar = is_action_bar;

  if (!self->action_bar_layer) {
    return;
  }

  action_bar_layer_remove_from_window(self->action_bar_layer);

  set_scroll_layer_click_config(self);

  if (!is_action_bar) {
    return;
  }

  action_bar_layer_set_context(self->action_bar_layer, self);
  action_bar_layer_set_click_config_provider(self->action_bar_layer, click_config_provider);
  action_bar_layer_add_to_window(self->action_bar_layer, self->window);
}

void simply_window_set_action_bar_icon(SimplyWindow *self, ButtonId button, uint32_t id) {
  if (!self->action_bar_layer) {
    return;
  }

  SimplyImage *icon = simply_res_auto_image(self->simply->res, id, true);

  if (!icon) {
    action_bar_layer_clear_icon(self->action_bar_layer, button);
    return;
  }

  if (icon->is_palette_black_and_white) {
    gbitmap_set_palette(icon->bitmap, s_button_palette, false);
  }

  action_bar_layer_set_icon(self->action_bar_layer, button, icon->bitmap);
  simply_window_set_action_bar(self, true);
}

void simply_window_set_action_bar_background_color(SimplyWindow *self, GColor8 background_color) {
  if (!self->action_bar_layer) {
    return;
  }

  s_button_palette[0] = gcolor8_equal(background_color, GColor8White) ? GColor8Black : GColor8White;

  action_bar_layer_set_background_color(self->action_bar_layer, gcolor8_get(background_color));
  simply_window_set_action_bar(self, true);
}

void simply_window_action_bar_clear(SimplyWindow *self) {
  simply_window_set_action_bar(self, false);

  for (ButtonId button = BUTTON_ID_UP; button <= BUTTON_ID_DOWN; ++button) {
    action_bar_layer_clear_icon(self->action_bar_layer, button);
  }
}

void simply_window_set_button(SimplyWindow *self, ButtonId button, bool enable) {
  if (enable) {
    self->button_mask |= 1 << button;
  } else {
    self->button_mask &= ~(1 << button);
  }
}

void simply_window_single_click_handler(ClickRecognizerRef recognizer, void *context) {
  SimplyWindow *self = context;
  ButtonId button = click_recognizer_get_button_id(recognizer);
  bool is_enabled = (self->button_mask & (1 << button));
  if (button == BUTTON_ID_BACK) {
    if (!simply_msg_has_communicated()) {
      bool animated = true;
      window_stack_pop(animated);
    } else if (!is_enabled) {
      simply_window_stack_back(self->simply->window_stack, self);
    }
  }
  if (is_enabled) {
    send_single_click(self->simply->msg, button);
  }
}

static void long_click_handler(ClickRecognizerRef recognizer, void *context) {
  SimplyWindow *self = context;
  ButtonId button = click_recognizer_get_button_id(recognizer);
  bool is_enabled = (self->button_mask & (1 << button));
  if (is_enabled) {
    send_long_click(self->simply->msg, button);
  }
}

static void click_config_provider(void *context) {
  SimplyWindow *self = context;
  for (int i = 0; i < NUM_BUTTONS; ++i) {
    if (!self->is_scrollable || (i != BUTTON_ID_UP && i != BUTTON_ID_DOWN)) {
      window_set_click_context(i, context);
      window_single_click_subscribe(i, simply_window_single_click_handler);
      window_long_click_subscribe(i, 500, (ClickHandler) long_click_handler, NULL);
    }
  }
  if (self->is_scrollable) {
    scroll_layer_click_config(self->scroll_layer);
  }
}

void simply_window_load(SimplyWindow *self) {
  Window *window = self->window;

  Layer *window_layer = window_get_root_layer(window);
  GRect frame = layer_get_frame(window_layer);
  frame.origin = GPointZero;

  ScrollLayer *scroll_layer = self->scroll_layer = scroll_layer_create(frame);
  Layer *scroll_base_layer = scroll_layer_get_layer(scroll_layer);
  layer_add_child(window_layer, scroll_base_layer);

  scroll_layer_set_context(scroll_layer, self);
  scroll_layer_set_shadow_hidden(scroll_layer, true);

  simply_window_set_action_bar(self, self->is_action_bar);
}

bool simply_window_appear(SimplyWindow *self) {
  if (!self->id) {
    return false;
  }
  if (simply_msg_has_communicated()) {
    simply_window_stack_send_show(self->simply->window_stack, self);
  }
  return true;
}

bool simply_window_disappear(SimplyWindow *self) {
  if (!self->id) {
    return false;
  }
  if (simply_msg_has_communicated()) {
    simply_window_stack_send_hide(self->simply->window_stack, self);
  }

#ifdef PBL_PLATFORM_BASALT
  simply_window_set_fullscreen(self, true);
#endif

  return true;
}

void simply_window_unload(SimplyWindow *self) {
  scroll_layer_destroy(self->scroll_layer);
  self->scroll_layer = NULL;
}

static void handle_window_props_packet(Simply *simply, Packet *data) {
  WindowPropsPacket *packet = (WindowPropsPacket*) data;
  SimplyWindow *window = simply_window_stack_get_top_window(simply);
  if (!window) {
    return;
  }
  window->id = packet->id;
  simply_window_set_background_color(window, packet->background_color);
  simply_window_set_fullscreen(window, packet->fullscreen);
  simply_window_set_scrollable(window, packet->scrollable);
}

static void handle_window_button_config_packet(Simply *simply, Packet *data) {
  WindowButtonConfigPacket *packet = (WindowButtonConfigPacket*) data;
  SimplyWindow *window = simply_window_stack_get_top_window(simply);
  if (!window) {
    return;
  }
  window->button_mask = packet->button_mask;
}

static void handle_window_action_bar_packet(Simply *simply, Packet *data) {
  WindowActionBarPacket *packet = (WindowActionBarPacket*) data;
  SimplyWindow *window = simply_window_stack_get_top_window(simply);
  if (!window) {
    return;
  }
  simply_window_set_action_bar_background_color(window, packet->background_color);
  for (unsigned int i = 0; i < ARRAY_LENGTH(packet->image); ++i) {
    simply_window_set_action_bar_icon(window, i + 1, packet->image[i]);
  }
  simply_window_set_action_bar(window, packet->action);
}

bool simply_window_handle_packet(Simply *simply, Packet *packet) {
  switch (packet->type) {
    case CommandWindowProps:
      handle_window_props_packet(simply, packet);
      return true;
    case CommandWindowButtonConfig:
      handle_window_button_config_packet(simply, packet);
      return true;
    case CommandWindowActionBar:
      handle_window_action_bar_packet(simply, packet);
      return true;
  }
  return false;
}

SimplyWindow *simply_window_init(SimplyWindow *self, Simply *simply) {
  self->simply = simply;

  for (int i = 0; i < NUM_BUTTONS; ++i) {
    if (i != BUTTON_ID_BACK) {
      self->button_mask |= 1 << i;
    }
  }

  Window *window = self->window = window_create();
  window_set_background_color(window, GColorClear);
  window_set_click_config_provider_with_context(window, click_config_provider, self);

  self->status_bar_layer = status_bar_layer_create();
  status_bar_layer_remove_from_window(window, self->status_bar_layer);
  self->is_status_bar = false;
  self->is_fullscreen = true;

  ActionBarLayer *action_bar_layer = self->action_bar_layer = action_bar_layer_create();
  action_bar_layer_set_context(action_bar_layer, self);

  return self;
}

void simply_window_deinit(SimplyWindow *self) {
  if (!self) {
    return;
  }

  action_bar_layer_destroy(self->action_bar_layer);
  self->action_bar_layer = NULL;

  status_bar_layer_destroy(self->status_bar_layer);
  self->status_bar_layer = NULL;

  window_destroy(self->window);
  self->window = NULL;
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/css/main.css">
<link rel="stylesheet" href="/font-awesome/css/font-awesome.min.css">

<title>Benjamin T. Skinner | University of Florida</title>

Benjamin T. Skinner

Assistant Professor of Higher Education and Policy | University of Florida

	Publications
        Presentations
        Working
	Media
        Teaching
        Code
	Data
        Visualizations
        CV

Batch download IPEDS survey files

Purpose

Use this script to batch download Integrated Postsecondary Education
Data System (IPEDS) files. The downloaded
files are not unzipped or processed in any way. This script simply
saves you the trouble of having to point and click your way through
the data center.

(You can also download database files
here, but you
need MS Access to open them and they only go back to 2004-2005.)

Only those files listed in ipeds_file_list.txt will be
downloaded. The default behavior is to download each of the following
files into their own subdirectories:

Data file

Dictionary file

You can also choose to download other data versions and/or program files:

Data file (STATA version)

STATA program file (default if you ask for STATA version data)

SPSS program file

SAS program file

IMPORTANT NOTE

The default behavior is to download ALL OF IPEDS. If you don't
want everything, modify ipeds_file_list.txt to include only those
files that you want. Simply erase those you don't want, keeping one
file name per row or comment them out using a hash symbol (#). Since
the downloading script ignores lines starting with hashes, you can add
notes or better section headers to the file if you want.

I try to keep ipeds_file_list.txt updated, but if I've missed a file
or haven't updated in a while, just add the name of the file or files,
one to a line. If you notice missing files, feel free to submit a pull
request with an updated version of ipeds_file_list.txt.

You also have the option of whether you wish to overwrite existing
files.  If you do, change the overwrite option to TRUE. The
default behavior is to only download files listed in
ipeds_file_list.txt that have not already been downloaded. Keep in
mind that NCES revises old files from time to time, so it may be best
to overwrite old files unless you have a reason to prefer the old
version.

To Run

For the default options, run the script downloadipeds.R as is. It
will create subdirectories as needed to store data and program
files. You may wish to place the folder in its own directory. Just
make sure that ipeds_file_list.txt is in the same directory. For
example, let's say you place both files in a directory called ipeds:

./ipeds
|__ downloadipeds.R
|__ ipeds_file_list.txt

If you run it with the default options, two new subdirectories will be
created, one for the data files and one for the dictionary
files. Using the above example, your directory will look like this
after it is finished:

./ipeds
|__ downloadipeds.R
|__ ipeds_file_list.txt
|__ /data
|   |__ HD2015.zip
|   |__ IC2015.zip
|   |__ <...>
|
|__ /dictionary
    |__ HD2015_Dict.zip
    |__ IC2015_Dict.zip
    |__ <...>

To download other program scripts or Stata versions of the data,
change the following commands in downloadipeds.R from FALSE to
TRUE:

## -----------------------------------------------------------------------------
## CHOOSE WHAT YOU WANT (TRUE == Yes, FALSE == No)
## -----------------------------------------------------------------------------

## default
primary_data = TRUE
dictionary = TRUE

## STATA version
## (NB: downloading Stata version of data will also get Stata program files)
stata_data = FALSE

## other program files
prog_spss = FALSE
prog_sas  = FALSE

## overwrite already downloaded files
overwrite = FALSE

To change output directory, modify out_dir (default is the current directory):

## -----------------------------------------------------------------------------
## CHOOSE OUTPUT DIRECTORY (DEFAULT == '.', which is current directory)
## -----------------------------------------------------------------------------

out_dir = '.'

Data size

As of 15 October 2020, downloading all IPEDS files (setting all
options to TRUE) requires approximately 2.25 GB of disk
space. Granted, you probably don't need both regular and Stata
versions of the data files (which are the bulk of the directory
size). Here are the approximate subdirectory file sizes if you
download all data files from all years:

      Subdirectory
      Approximate Size

      ./data
      1.08 GB

      ./dictionary
      31.6 MB

      ./sas_prog
      6.3 MB

      ./spss_prog
      19.7 MB

      ./stata_data
      1.1 GB

      ./stata_prog
      6.7 MB

Combine

To combine multiple IPEDS data files into a single dataset, you may
find the following script useful: Combine
IPEDS

© 2022. This site powered by Jekyll + vida + GitHub.


text:
package metrics

import (
	"time"

	"golang.org/x/exp/constraints"
)

// Thresholds encapsulates a set of bucket thresholds used in Summary[T].
type Thresholds[T constraints.Float | constraints.Integer] struct {
	values           []T
	promScale        float64
	prometheusSuffix string
}

// ISOBytesThresholds is a set of thresholds for sizes.
//
//nolint:gochecknoglobals
var ISOBytesThresholds = &Thresholds[int64]{
	[]int64{
		100,
		250,
		500,
		1_000,
		2_500,
		5_000,
		10_000,
		25_000,
		50_000,
		100_000,
		250_000,
		500_000,
		1_000_000,
		2_500_000,
		5_000_000,
		10_000_000,
		25_000_000,
		50_000_000,
		100_000_000,
		250_000_000,
		500_000_000,
	},
	1,
	"",
}

// IOLatencyThresholds is a set of thresholds that can represent IO latencies from 500us to 50s.
//
//nolint:gochecknoglobals
var IOLatencyThresholds = &Thresholds[time.Duration]{
	[]time.Duration{
		500 * time.Microsecond,

		1000 * time.Microsecond,
		2500 * time.Microsecond,
		5000 * time.Microsecond,

		10 * time.Millisecond,
		25 * time.Millisecond,
		50 * time.Millisecond,

		100 * time.Millisecond,
		250 * time.Millisecond,
		500 * time.Millisecond,

		1000 * time.Millisecond,
		2500 * time.Millisecond,
		5000 * time.Millisecond,

		10 * time.Second,
		25 * time.Second,
		50 * time.Second,
	},
	1e6, // store as milliseconds
	"_ms",
}

// CPULatencyThresholds is a set of thresholds that can represent CPU latencies from 10us to 5s.
//
//nolint:gochecknoglobals
var CPULatencyThresholds = &Thresholds[time.Duration]{
	[]time.Duration{
		10 * time.Microsecond,
		25 * time.Microsecond,
		50 * time.Microsecond,

		100 * time.Microsecond,
		250 * time.Microsecond,
		500 * time.Microsecond,

		1000 * time.Microsecond,
		2500 * time.Microsecond,
		5000 * time.Microsecond,

		10 * time.Millisecond,
		25 * time.Millisecond,
		50 * time.Millisecond,

		100 * time.Millisecond,
		250 * time.Millisecond,
		500 * time.Millisecond,

		1000 * time.Millisecond,
		2500 * time.Millisecond,
		5000 * time.Millisecond,
	},
	1, // export to Prometheus as nanoseconds
	"_ns",
}

func bucketForThresholds[T constraints.Integer | constraints.Float](thresholds []T, d T) int {
	l, r := 0, len(thresholds)-1

	for l <= r {
		m := (l + r) >> 1
		mid := thresholds[m]

		switch {
		case mid < d:
			l = m + 1
		case mid > d:
			r = m - 1
		default:
			return m
		}
	}

	return l
}


text:
package org.knowm.xchange.yobit.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.marketdata.Trade;
import org.knowm.xchange.dto.marketdata.Trades;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.exceptions.NotAvailableFromExchangeException;
import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException;
import org.knowm.xchange.service.marketdata.MarketDataService;
import org.knowm.xchange.yobit.YoBitAdapters;
import org.knowm.xchange.yobit.dto.DefaultOrderBookRequestParams;
import org.knowm.xchange.yobit.dto.DefaultPublicTradesDataRequestParams;
import org.knowm.xchange.yobit.dto.DefaultTickerRequestParams;
import org.knowm.xchange.yobit.dto.MultiCurrencyOrderBooksRequestParams;
import org.knowm.xchange.yobit.dto.MultiCurrencyPairTickersRequestParams;
import org.knowm.xchange.yobit.dto.MultiCurrencyPublicTradesDataRequestParams;
import org.knowm.xchange.yobit.dto.OrderBooksRequestParam;
import org.knowm.xchange.yobit.dto.PublicTradesRequestParams;
import org.knowm.xchange.yobit.dto.TickersRequestParams;
import org.knowm.xchange.yobit.dto.marketdata.YoBitOrderBooksReturn;
import org.knowm.xchange.yobit.dto.marketdata.YoBitTickersReturn;
import org.knowm.xchange.yobit.dto.marketdata.YoBitTrade;
import org.knowm.xchange.yobit.dto.marketdata.YoBitTrades;

public class YoBitMarketDataService extends YoBitMarketDataServiceRaw implements MarketDataService {

  public YoBitMarketDataService(Exchange exchange) {
    super(exchange);
  }

  @Override
  public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException {
    return getTickers(new DefaultTickerRequestParams(currencyPair)).iterator().next();
  }

  public Iterable<Ticker> getTickers(TickersRequestParams params) throws IOException {
    if (params instanceof MultiCurrencyPairTickersRequestParams) {
      MultiCurrencyPairTickersRequestParams request = (MultiCurrencyPairTickersRequestParams) params;

      YoBitTickersReturn yoBitTickers = getYoBitTickers(request.currencyPairs);

      List<Ticker> res = new ArrayList<>();
      for (String ccyPair : yoBitTickers.tickers.keySet()) {
        CurrencyPair currencyPair = YoBitAdapters.adaptCurrencyPair(ccyPair);
        Ticker ticker = YoBitAdapters.adaptTicker(yoBitTickers.tickers.get(ccyPair), currencyPair);
        res.add(ticker);
      }

      return res;
    }

    throw new IllegalStateException("Do not understand " + params);
  }

  @Override
  public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException {
    int level = 50;
    if (args != null && args.length > 0) {
      if (args[0] instanceof Number) {
        level = ((Number) args[0]).intValue();
      }
    }

    return getOrderBooks(new DefaultOrderBookRequestParams(level, currencyPair)).iterator().next();
  }

  public Iterable<OrderBook> getOrderBooks(OrderBooksRequestParam params) throws IOException {
    if (params instanceof MultiCurrencyOrderBooksRequestParams) {
      MultiCurrencyOrderBooksRequestParams booksRequestParam = (MultiCurrencyOrderBooksRequestParams) params;

      List<OrderBook> res = new ArrayList<>();

      YoBitOrderBooksReturn orderBooks = getOrderBooks(booksRequestParam.currencyPairs, booksRequestParam.desiredDepth);

      for (String ccyPair : orderBooks.orderBooks.keySet()) {
        CurrencyPair currencyPair = YoBitAdapters.adaptCurrencyPair(ccyPair);
        OrderBook orderBook = YoBitAdapters.adaptOrderBook(orderBooks.orderBooks.get(ccyPair), currencyPair);
        res.add(orderBook);
      }

      return res;
    }

    throw new IllegalStateException("Don't understand " + params);
  }

  @Override
  public Trades getTrades(CurrencyPair currencyPair, Object... args) throws IOException {
    return getTrades(new DefaultPublicTradesDataRequestParams(currencyPair));
  }

  public Trades getTrades(PublicTradesRequestParams params) throws IOException {
    if (params instanceof MultiCurrencyPublicTradesDataRequestParams) {
      MultiCurrencyPublicTradesDataRequestParams multiCurrencyPublicTradesDataRequestParams = (MultiCurrencyPublicTradesDataRequestParams) params;
      YoBitTrades publicTrades = getPublicTrades(multiCurrencyPublicTradesDataRequestParams.currencyPairs);

      List<Trade> all = new ArrayList<>();
      Map<String, List<YoBitTrade>> tradesByCcyPair = publicTrades.getTrades();
      for (String ccyPair : tradesByCcyPair.keySet()) {
        CurrencyPair currencyPair = YoBitAdapters.adaptCurrencyPair(ccyPair);
        List<Trade> trades = YoBitAdapters.adaptTrades(tradesByCcyPair.get(ccyPair), currencyPair).getTrades();
        all.addAll(trades);
      }

      Collections.sort(all, new Comparator<Trade>() {
        @Override
        public int compare(Trade a, Trade b) {
          return a.getTimestamp().compareTo(b.getTimestamp());
        }
      });

      return new Trades(all, Trades.TradeSortType.SortByID);
    }

    throw new IllegalStateException("Don't understand " + params);
  }
}


text:
#define GLOBAL_ERROR_BASE                 25501

#define msierrSecureObjectsFailedCreateSD    25520
#define msierrSecureObjectsFailedSet         25521
#define msierrSecureObjectsUnknownType       25522

#define msierrXmlFileFailedRead         25530
#define msierrXmlFileFailedOpen         25531
#define msierrXmlFileFailedSelect       25532
#define msierrXmlFileFailedSave         25533

#define msierrXmlConfigFailedRead         25540
#define msierrXmlConfigFailedOpen         25541
#define msierrXmlConfigFailedSelect       25542
#define msierrXmlConfigFailedSave         25543

#define msierrFirewallCannotConnect       25580

//---------------------------------------------------------------------------
// Server CustomAction Errors
// SERVER range: 26001-26100
#define SERVER_ERROR_BASE                      26000

#define msierrIISCannotConnect                 26001
#define msierrIISFailedReadWebSite             26002
#define msierrIISFailedReadWebDirs             26003
#define msierrIISFailedReadVDirs               26004
#define msierrIISFailedReadFilters             26005
#define msierrIISFailedReadAppPool             26006
#define msierrIISFailedReadMimeMap             26007
#define msierrIISFailedReadProp                26008
#define msierrIISFailedReadWebSvcExt           26009
#define msierrIISFailedReadWebError            26010
#define msierrIISFailedReadHttpHeader          26011

#define msierrIISFailedSchedTransaction        26031
#define msierrIISFailedSchedInstallWebs        26032
#define msierrIISFailedSchedInstallWebDirs     26033
#define msierrIISFailedSchedInstallVDirs       26034
#define msierrIISFailedSchedInstallFilters     26035
#define msierrIISFailedSchedInstallAppPool     26036
#define msierrIISFailedSchedInstallProp        26037
#define msierrIISFailedSchedInstallWebSvcExt   26038

#define msierrIISFailedSchedUninstallWebs      26051
#define msierrIISFailedSchedUninstallWebDirs   26052
#define msierrIISFailedSchedUninstallVDirs     26053
#define msierrIISFailedSchedUninstallFilters   26054
#define msierrIISFailedSchedUninstallAppPool   26055
#define msierrIISFailedSchedUninstallProp      26056
#define msierrIISFailedSchedUninstallWebSvcExt 26057

#define msierrIISFailedStartTransaction        26101
#define msierrIISFailedOpenKey                 26102
#define msierrIISFailedCreateKey               26103
#define msierrIISFailedWriteData               26104
#define msierrIISFailedCreateApp               26105
#define msierrIISFailedDeleteKey               26106
#define msierrIISFailedDeleteApp               26107
#define msierrIISFailedDeleteValue             26108
#define msierrIISFailedCommitInUse             26109

#define msierrSQLFailedCreateDatabase          26201
#define msierrSQLFailedDropDatabase            26202
#define msierrSQLFailedConnectDatabase         26203
#define msierrSQLFailedExecString              26204
#define msierrSQLDatabaseAlreadyExists         26205

#define msierrPERFMONFailedRegisterDLL         26251
#define msierrPERFMONFailedUnregisterDLL       26252
#define msierrInstallPerfCounterData           26253
#define msierrUninstallPerfCounterData         26254

#define msierrSMBFailedCreate                  26301
#define msierrSMBFailedDrop                    26302

#define msierrCERTFailedOpen                   26351
#define msierrCERTFailedAdd                    26352

#define msierrUSRFailedUserCreate              26401
#define msierrUSRFailedUserCreatePswd          26402
#define msierrUSRFailedUserGroupAdd            26403
#define msierrUSRFailedUserCreateExists        26404
#define msierrUSRFailedGrantLogonAsService     26405

#define msierrDependencyMissingDependencies    26451
#define msierrDependencyHasDependents          26452

//--------------------------------------------------------------------------
// Managed code CustomAction Errors
// MANAGED range: 27000-27100
#define MANAGED_ERROR_BASE                     27000

#define msierrDotNetRuntimeRequired            27000
//---------------------------------------------------------------------------
// Public CustomAction Errors
// PUBLIC range: 28001-28100
#define PUBLIC_ERROR_BASE                            28000

#define msierrComPlusCannotConnect                   28001
#define msierrComPlusPartitionReadFailed             28002
#define msierrComPlusPartitionRoleReadFailed         28003
#define msierrComPlusUserInPartitionRoleReadFailed   28004
#define msierrComPlusPartitionUserReadFailed         28005
#define msierrComPlusApplicationReadFailed           28006
#define msierrComPlusApplicationRoleReadFailed       28007
#define msierrComPlusUserInApplicationRoleReadFailed 28008
#define msierrComPlusAssembliesReadFailed            28009
#define msierrComPlusSubscriptionReadFailed          28010
#define msierrComPlusPartitionDependency             28011
#define msierrComPlusPartitionNotFound               28012
#define msierrComPlusPartitionIdConflict             28013
#define msierrComPlusPartitionNameConflict           28014
#define msierrComPlusApplicationDependency           28015
#define msierrComPlusApplicationNotFound             28016
#define msierrComPlusApplicationIdConflict           28017
#define msierrComPlusApplicationNameConflict         28018
#define msierrComPlusApplicationRoleDependency       28019
#define msierrComPlusApplicationRoleNotFound         28020
#define msierrComPlusApplicationRoleConflict         28021
#define msierrComPlusAssemblyDependency              28022
#define msierrComPlusSubscriptionIdConflict          28023
#define msierrComPlusSubscriptionNameConflict        28024
#define msierrComPlusFailedLookupNames               28025

#define msierrMsmqCannotConnect                      28101


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Log_model extends MX_Controller
{

    function Calendar_model()
    {
        parent:: __construct();
    }

    /*
     * Query the database for all dates for tblSession and return them.
     *
     */
    function get_all_dates()
    {
        $this->db->select('SessionDate');
        $this->db->from('tblSession');

        $query = $this->db->get();
        $result = $query->result();

        return $result;
    }

    /*
    * Query the database for all sessions.
    *
    */
    function get_all_data()
    {
        // SELECT SessionDate, ExerciseName, Weight, Reps FROM tblSession, tblExercise WHERE tblSession.ExerciseID = tblExercise.ExerciseID
        $this->db->select('SessionDate, ExerciseName, Weight, Reps');
        $this->db->from('tblSession, tblExercise');
        $this->db->where('tblSession.ExerciseID = tblExercise.ExerciseID');

        $query = $this->db->get();
        return $result = $query->result();
    }

}


text:
package uk.nhs.ciao.transport.spine;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.Route;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultMessage;
import org.apache.camel.impl.DefaultProducerTemplate;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import uk.nhs.ciao.camel.CamelApplicationRunner;
import uk.nhs.ciao.camel.CamelUtils;
import uk.nhs.ciao.camel.CamelApplicationRunner.AsyncExecution;
import uk.nhs.ciao.configuration.CIAOConfig;
import uk.nhs.ciao.configuration.impl.MemoryCipProperties;
import uk.nhs.ciao.docs.parser.Document;
import uk.nhs.ciao.docs.parser.ParsedDocument;
import uk.nhs.ciao.transport.spine.ebxml.EbxmlEnvelope;
import uk.nhs.ciao.transport.spine.multipart.MultipartBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;

/**
 * Tests for the cda-builder-parser CIP application
 */
public class SpineTransportApplicationTest {
	private static final Logger LOGGER = LoggerFactory.getLogger(SpineTransportApplicationTest.class);
	private static final String CIP_NAME = "ciao-transport-spine";

	@Rule
	public Timeout globalTimeout = Timeout.seconds(30);

	private ExecutorService executorService;
	private SpineTransportApplication application;
	private AsyncExecution execution;
	private ObjectMapper objectMapper;
	private ProducerTemplate producerTemplate;

	@Before
	public void setup() throws Exception {
		final CIAOConfig ciaoConfig = setupCiaoConfig();
		application = new SpineTransportApplication(ciaoConfig);

		executorService = Executors.newSingleThreadExecutor();
		objectMapper = new ObjectMapper();
	}

	private CIAOConfig setupCiaoConfig() throws IOException {
		final MemoryCipProperties cipProperties = new MemoryCipProperties(CIP_NAME, "tests");
		addProperties(cipProperties, CIP_NAME + ".properties");
		addProperties(cipProperties, CIP_NAME + "-test.properties");

		return new CIAOConfig(cipProperties);
	}

	private void addProperties(final MemoryCipProperties cipProperties, final String resourcePath) throws IOException {
		final Resource resource = new ClassPathResource(resourcePath);
		final Properties properties = PropertiesLoaderUtils.loadProperties(resource);
		cipProperties.addConfigValues(properties);
	}

	private void runApplication() throws Exception {
		LOGGER.info("About to start camel application");

		execution = CamelApplicationRunner.runApplication(application, executorService);

		LOGGER.info("Camel application has started");
	}

	@After
	public void tearDown() {
		try {
			stopApplication();
		} finally {
			// Always stop the executor service
			executorService.shutdownNow();
		}
	}

	private void stopApplication() {
		if (execution == null) {
			return;
		}

		CamelUtils.stopQuietly(producerTemplate);

		final CamelContext context = getCamelContext();
		try {
			LOGGER.info("About to stop camel application");
			execution.getRunner().stop();
			execution.getFuture().get(); // wait for task to complete
			LOGGER.info("Camel application has stopped");
		} catch (Exception e) {
			LOGGER.warn("Exception while trying to stop camel application", e);
		} finally {
			if (context != null) {
				MockEndpoint.resetMocks(context);
			}
		}
	}

	private CamelContext getCamelContext() {
		if (execution == null) {
			return null;
		}

		final List<CamelContext> camelContexts = execution.getRunner().getCamelContexts();
		return camelContexts.isEmpty() ? null : camelContexts.get(0);
	}

	private ProducerTemplate getProducerTemplate() throws Exception {
		if (producerTemplate == null) {
			producerTemplate = new DefaultProducerTemplate(getCamelContext());
			producerTemplate.start();
		}

		return producerTemplate;
	}

	@Test
	public void testApplicationStartsUsingSpringConfig() throws Exception {
		LOGGER.info("Checking the application starts via spring config");

		runApplication();

		assertNotNull(execution);
		assertFalse(execution.getRunner().getCamelContexts().isEmpty());
		assertNotNull(getCamelContext());
	}

	@Test
	public void testApplicationProcessesAJsonDocument() throws Exception {
		LOGGER.info("Checking a parsable document");

		runApplication();

		// Using latch to wait for response - using a mock with assertions does not seem to work as expected
		final CountDownLatch latch = new CountDownLatch(1);

		final CamelContext camelContext = getCamelContext();
		sendRouteTo("trunk-request-sender", "direct:trunk-responses");

		camelContext.addRoutes(new RouteBuilder() {
			@Override
			public void configure() throws Exception {
				// Send an ack whenever a request is received
				from("seda:trunk-request")
					// async response
					.convertBodyTo(MultipartBody.class)
					.setBody().spel("#{body.parts[0].body}")
					.convertBodyTo(EbxmlEnvelope.class)
					.setBody().spel("#{body.generateAcknowledgment()}")
					.setHeader("JMSCorrelationID").simple("${body.messageData.refToMessageId}", String.class)
					.convertBodyTo(String.class)
					.setHeader("SOAPAction", constant("urn:oasis:names:tc:ebxml-msg:service/Acknowledgment"))
					.to("direct:trunk-reply")

					// request-response body
					.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(202))
					.setBody().constant("")
				.end();

				// Monitor the responses and unlock the latch
				from("direct:trunk-responses")
					.log("Got an ack response message: ${body}")
					.process(new Processor() {
						@Override
						public void process(final Exchange exchange) throws Exception {
							latch.countDown();
						}
					});
			}
		});

		// Send the initial document to JMS (returns before main processing begins)
		sendMessage("jms:queue:cda-documents", getExampleJson());

		// Wait for ACK response to be processed by the main route
		Assert.assertTrue("Expected one response message", latch.await(10, TimeUnit.SECONDS));
	}

	/**
	 * Sends the end of the route to a further endpoint for testing (e.g. direct:...)
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	private void sendRouteTo(final String routeId, final String toUri) throws Exception {
		// A little 'hacky' -
		// This version of camel does not support the failIfNoConsumers option on the direct component
		// otherwise a NOOP route could have been added in the main route
		// without the option the route would pass unit tests - but fail when running normally!
		final CamelContext camelContext = getCamelContext();

		final Route route = camelContext.getRoute(routeId);
		Assert.assertNotNull(route);

		camelContext.stopRoute(routeId);
		camelContext.removeRoute(routeId);
		camelContext.addRouteDefinition(route.getRouteContext().getRoute().to(toUri));
		camelContext.startRoute(routeId);
	}

	private Exchange sendMessage(final String uri, final Message message) throws Exception {
		final Exchange exchange = getCamelContext().getEndpoint(uri).createExchange();
		exchange.getIn().copyFrom(message);

		return getProducerTemplate().send(uri, exchange);
	}

	private Message getExampleJson() throws IOException {
		final Map<String, Object> properties = Maps.newLinkedHashMap();
		properties.put("somekey", "somevalue");
		properties.put("itkCorrelationId", "12345");
		properties.put("ebxmlCorrelationId", "89EEFD54-7C9E-4B6F-93A8-835CFE6EFC95");

		properties.put("receiverPartyId", "BBB-654321");
		properties.put("receiverAsid", "000000000000");
		properties.put("receiverODSCode", "BBB");
		properties.put("receiverCPAId", "S3024519A3110234");
		properties.put("itkProfileId", "urn:nhs-en:profile:eDischargeInpatientDischargeSummary-v1-0");
		properties.put("itkHandlingSpec", "urn:nhs-itk:interaction:copyRecipientAmbulanceServicePatientReport-v1-0");

		final Document originalDocument = new Document("myfile.xml", "<root>content</root>".getBytes(), "text/xml");
		final ParsedDocument parsedDocument = new ParsedDocument(originalDocument, properties);

		final Message message = new DefaultMessage();
		message.setBody(objectMapper.writeValueAsString(parsedDocument));
		message.setHeader(Exchange.CORRELATION_ID, "12345");

		return message;
	}
}


text:
using InterSystems.Globals;
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Collections;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;

using CacheEXTREME2.WDirectGlobal;
using CacheEXTREME2.WMetaGlobal;
using CacheEXTREME2.WProxyGlobal;

//using EXTREMEAccessTESTS.Generated;
using Generated;

namespace EXTREMEAccessTESTS
{
    public partial class EXTREMEcomparator : Form
    {
        private string _namespace = "USER";
        private string _user = "mihand";
        private string _password = "19735";
        private bool isValidate = false;
        public Connection conn;
        WowsTestContext trueWowsTestContext;
        //
        public EXTREMEcomparator()
        {
            InitializeComponent();
        }
        //
        private void EXTREMEcomparator_Load(object sender, EventArgs e)
        {
            try
            {
                if (conn == null)
                {
                    conn = ConnectionContext.GetConnection();
                    conn.Connect(_namespace, _user, _password);
                }
                initWowsTestMetaGlobal(true);
                trueWowsTestContext = new WowsTestContext(conn);
                trueWowsTestContext.classinfoManager.Validate = isValidate;
                trueWowsTestContext.ShipInfoManager.Validate = isValidate;
                trueWowsTestContext.stuffManager.Validate = isValidate;
                //
                TestEntityProxy test = new TestEntityProxy();
                test.shipclass = "class";
                test.Classification = new Classification("class1", 1);
                test.SubClassification = new Classification("subClass1", 11);
                trueWowsTestContext.TestEntityManager.Save(test);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void initWowsTestMetaGlobal(bool regenerateGlobal = false)
        {
            if (regenerateGlobal)
            {
                GlobalMeta gm = new GlobalMeta("wowsTest", "wowsTestMeta");
                gm.GlobalSemantic = "Navies";
                //structs zone
                //
                StructDefinition contactInfoStruct = new StructDefinition();
                contactInfoStruct.StructTypeName = "Contact";
                contactInfoStruct.elementsMeta = new List<ValueMeta>()
                {
                    new StringValMeta(new ArrayList(){"Name","String",0,255,"Name"})
                    ,new IntValMeta(new ArrayList(){"Phone","Integer",111111,99999999,111111})
                };

                StructDefinition classificationStruct = new StructDefinition();
                classificationStruct.StructTypeName = "Classification";
                classificationStruct.elementsMeta = new List<ValueMeta>()
                {
                    new StringValMeta(new ArrayList(){"ClassType","String",0,255,"ClassType"})
                    ,new IntValMeta(new ArrayList(){"Rank","Integer",0,1005000,0})
                };
                //
                gm.AddStruct(classificationStruct);
                gm.AddStruct(contactInfoStruct);

                //
                //
                //subscripts zone
                gm.AddKeyMeta(new StringValMeta(new ArrayList { "shipclass", "String", 0, 255, "" }), "classinfo");
                gm.AddKeyMeta(new IntValMeta(new ArrayList { "shiprank", "Integer", 0, 1005000, 5 }), "stuff");
                gm.AddKeyMeta(new StructValMeta("Classification", classificationStruct), "");
                gm.AddKeyMeta(new StringValMeta(new ArrayList() { "Name", "String", 0, 255, "ShipName" }), "ShipInfo");
                gm.AddKeyMeta(new StructValMeta("SubClassification", classificationStruct), "TestEntity");
                //
                //
                //values zone
                gm.AddValuesMeta(1, new List<ValueMeta>{
                    new IntValMeta(new ArrayList{"shipsCount","integer",0,1000,0})
                });
                gm.AddValuesMeta(2, new List<ValueMeta>{
                    new ListValMeta(new ArrayList{"workers","List",0,100}, new StringValMeta(new ArrayList{"","String",0,255,0}))
                    ,new ListValMeta(new ArrayList{"officers","List",0,100} ,new StringValMeta(new ArrayList{"","String",0,255,0}))
                    ,new IntValMeta(new ArrayList{"workerSalary","integer",1,2000,0})
                    ,new BytesValMeta(new ArrayList{"photo","bytes", 0, 200000})
                });
                gm.AddValuesMeta(3, new List<ValueMeta>());
                gm.AddValuesMeta(4, new List<ValueMeta>{
                    new ListValMeta(new ArrayList{"captains","list",0,100},new StructValMeta("captainContact",contactInfoStruct))
                    ,new ListValMeta(new ArrayList{"workers","List",0,100}, new StringValMeta(new ArrayList{"","String",0,255,0}))
                    ,new ListValMeta(new ArrayList{"officers","List",0,100} ,new StringValMeta(new ArrayList{"","String",0,255,0}))
                    ,new IntValMeta(new ArrayList{"workerSalary","integer",1,2000,0})
                    ,new BytesValMeta(new ArrayList{"photo","bytes", 0, 200000})
                });
                gm.AddValueMeta(4,new IntValMeta(new ArrayList { "TestIntVal", "Integer", 0, 1005000, 5 }));
                //
                //saving meta
                MetaReaderWriter mr = new MetaReaderWriter(conn);
                NodeReference nr = conn.CreateNodeReference(gm.GlobalMetaName);
                string appPath = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\") + 1);
                ContextGenerator cg = new ContextGenerator(gm, "wowsTest", "Generated", appPath + "WowsTestContext.cs");
                cg.GenerateCSharpCode();
                nr.Kill();
                //
                mr.SaveMeta(gm);
            }
        }
        //
        private void compareSaveSpeed(int count)
        {
            trueWowsTestContext.classinfoManager.Validate = isValidate;
            trueWowsTestContext.ShipInfoManager.Validate = isValidate;
            trueWowsTestContext.stuffManager.Validate = isValidate;

            native_VS_true_VS_object(count);
            GC.Collect();
            //testObjectSave(count);
        }
        private void native_VS_true_VS_object(int count,bool invoke = true)
        {
            txtInfo.Text = ""; txtInfo.Refresh();
            dataGridView.Enabled = false;
            progressNative.Value = 0;
            progressTrue.Value = 0;
            progressObject.Value = 0;
            killOld(new KillParam(count));
            progressClear.Value = 0;

            long Osumm = 0;
            double Oavrg = 0;
            long OFastsumm =  0;
            double OFastavrg = 0;
            try
            {

                //object faster
                List<TimeSpan> objFastSpans = this.testWithStructsObjectFasterSave(count);
                OFastsumm = objFastSpans.Sum(e => e.Ticks);
                OFastavrg = objFastSpans.Average(e => e.TotalMilliseconds);
                TimeSpan oFastTotal = new TimeSpan(OFastsumm);
                txtInfo.Text += " _ ObjectFaster: " + oFastTotal.ToString() + "sec (" + OFastavrg + "msec) _"; txtInfo.Refresh();
                Thread.Sleep(100);
                killOld(new KillParam(count));

                //object
                /*List<TimeSpan> objSpans = this.testWithStructsObjectSave(count);
                Osumm = objSpans.Sum(e => e.Ticks);
                Oavrg = objSpans.Average(e => e.TotalMilliseconds);
                TimeSpan oTotal = new TimeSpan(Osumm);
                txtInfo.Text += " _ Object: " + oTotal.ToString() + "sec (" + Oavrg + "msec) _"; txtInfo.Refresh();
                Thread.Sleep(100);
                killOld(new KillParam(count));*/

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //native
            List<TimeSpan> nativeSpans = testWithStructsNativeSave(count);
            long Nsumm = nativeSpans.Sum(e => e.Ticks);
            double Navrg = nativeSpans.Average(e => e.TotalMilliseconds);
            TimeSpan nTotal = new TimeSpan(Nsumm);
            txtInfo.Text += " _ Native: " + nTotal.ToString() + "sec (" + Navrg + "msec) _ "; txtInfo.Refresh();
            Thread.Sleep(100);
            killOld(new KillParam(count));
            Thread.Sleep(100);

            //true
            /*List<TimeSpan> trueSpans = testTrueSave(count);
            long Tsumm = trueSpans.Sum(e => e.Ticks);
            double Tmax = trueSpans.Max(e => e.TotalMilliseconds);
            TimeSpan tTotal = new TimeSpan(Tsumm);
            txtInfo.Text += " _ True: " + tTotal.ToString() + "(" + Tmax + ") _ "; txtInfo.Refresh();
            Thread.Sleep(100);
            killOld(new KillParam(count));
            Thread.Sleep(100);*/

            //
            dataGridView.Rows.Clear();
            int div = 100;
            if (count >= 10000) { div = 100; }
            if (count >= 50000) { div = 50; }
            if (count >= 100000) { div = 100; }
            if (count >= 200000) {div = 200;}
            int step = count / div;

            /*for (int i = 0, j = 0; i < count; i += step, j++)
            {
                dataGridView.Rows.Add();
                dataGridView["probeCol", j].Value = i;
                dataGridView["nativeCol", j].Value = nativeSpans[0].TotalMilliseconds;
                //dataGridView["trueCol", j].Value = trueSpans[0].TotalMilliseconds;
                dataGridView["objectCol", j].Value = objSpans[0].TotalMilliseconds;
                objSpans.RemoveAt(0);
                //trueSpans.RemoveAt(0);
                nativeSpans.RemoveAt(0);
            }*/
            //txtInfo.Text += " _ obj/nat= " + ((double)Osumm / (double)Nsumm).ToString(); txtInfo.Refresh();
            txtInfo.Text += " _ obj/native= " + ((double)OFastsumm / (double)Nsumm).ToString(); txtInfo.Refresh();
            dataGridView.Enabled = true;
        }

        //without Structs
        private List<TimeSpan> testNativeSave(int count = 100)
        {
            List<TimeSpan> spans = new List<TimeSpan>();
            NodeReference wtr = conn.CreateNodeReference("wowsTest");
            Stopwatch nWatch = new Stopwatch();
            progressNative.Value = 0;
            //
            //Dataholders
            string shipClass = "kruis";
            object[] keys = new object[] { shipClass, 0 };
            object[] oficersNames = new object[] { "", "", "" };
            object[] workersNames = new object[] { "", "", "" };
            StringBuilder name1 = new StringBuilder(20);
            StringBuilder name2 = new StringBuilder(20);
            StringBuilder name3 = new StringBuilder(20);
            int s = 1000;
            byte[] byteValue = new byte[] { 6, 6, 6 };
            //
            for (int i = 0; i < count; i++)
            {
                name1.Remove(0, name1.Length);
                name2.Remove(0, name2.Length);
                name3.Remove(0, name3.Length);
                name1.Insert(0, i + 1);
                name2.Insert(0, i + 2);
                name3.Insert(0, i + 3);

                //отсюда
                keys[0] = shipClass;
                keys[1] = i;
                oficersNames[0] = name1.ToString();
                oficersNames[1] = name2.ToString();
                oficersNames[2] = name3.ToString();
                workersNames[0] = name3.ToString();
                workersNames[1] = name2.ToString();
                workersNames[2] = name1.ToString();
                //s = s;
                //byteValue = byteValue;
                //досюда
                {
                    nWatch.Reset();
                    nWatch.Start();

                    ValueList oficersVL = conn.CreateList();
                    oficersVL.Append(oficersNames);
                    ValueList workersVL = conn.CreateList();
                    workersVL.Append(workersNames);
                    ValueList vlist = conn.CreateList();
                    vlist.Append(oficersVL);
                    vlist.Append(workersVL);
                    vlist.Append(s);
                    vlist.Append(byteValue);
                    wtr.Set(vlist, keys);

                    nWatch.Stop();
                }

                TimeSpan nTS = nWatch.Elapsed;
                spans.Add(nTS);
                progressNative.Value = i * 100 / count;
            }
            progressNative.Value = 100;
            return spans;
        }
        private List<TimeSpan> testTrueSave(int count = 100)
        {
            List<TimeSpan> spans = new List<TimeSpan>();
            TrueNodeReference WTr = new TrueNodeReference(conn, "wowsTest");
            Stopwatch tWatch = new Stopwatch();
            progressTrue.Value = 0;
            for (int i = 0; i < count; i++)
            {
                string i1 = (i + 1).ToString(), i2 = (i + 2).ToString(), i3 = (i + 3).ToString();
                int s = 1000;
                //ОТСЮДА
                ArrayList akeys = new ArrayList() { "kruis", i };
                ArrayList asublist1 = new ArrayList() { i1, i2, i3 };
                ArrayList asublist2 = new ArrayList() { i3, i2, i1 };
                byte[] bytes = new byte[] { 6, 6, 6 };
                ArrayList alist = new ArrayList() { asublist1, asublist2, s, bytes };
                ArrayList values = new ArrayList() {
                    new ArrayList() { i1, i2, i3 }
                    , new ArrayList() { i3, i2, i1 }
                    , 1000
                    , new byte[] { 6, 6, 6 } };
                //Досюда
                {
                    tWatch.Reset();
                    tWatch.Start();

                    WTr.SetValues(akeys, alist);

                    tWatch.Stop();
                }
                TimeSpan tTS = tWatch.Elapsed;
                spans.Add(tTS);
                progressTrue.Value = i * 100 / count;
            }
            progressTrue.Value = 100;
            return spans;
        }
        private List<TimeSpan> testObjectSave(int count = 100)
        {
            List<TimeSpan> spans = new List<TimeSpan>();
            TrueNodeReference WTr = new TrueNodeReference(conn, "wowsTest");
            Stopwatch oWatch = new Stopwatch();
            progressObject.Value = 0;
            //
            trueWowsTestContext.stuffManager.Validate = false;
            Random rand = new Random();
            //
            //Data holders
            string shipClass = "kruis";
            int s = 1000;
            List<string> oficersNames = new List<string> { "", "", "" };
            List<string> workersNames = new List<string> { "", "", "" };
            StringBuilder name1 = new StringBuilder(20);
            StringBuilder name2 = new StringBuilder(20);
            StringBuilder name3 = new StringBuilder(20);
            byte[] byteValue = new byte[] { 6, 6, 6 };
            stuffProxy entity = new stuffProxy();
            //
            for (int i = 0; i < count; i++)
            {
                name1.Remove(0, name1.Length);
                name2.Remove(0, name2.Length);
                name3.Remove(0, name3.Length);
                name1.Insert(0, i + 1);
                name2.Insert(0, i + 2);
                name3.Insert(0, i + 3);
                oficersNames[0] = name1.ToString();
                oficersNames[1] = name2.ToString();
                oficersNames[2] = name3.ToString();
                workersNames[0] = name3.ToString();
                workersNames[1] = name2.ToString();
                workersNames[2] = name1.ToString();
                //ОТСЮДА
                entity.shipclass = shipClass;
                entity.shiprank = i;
                entity.officers = oficersNames;
                entity.workers = workersNames;
                entity.workerSalary = s;
                entity.photo = byteValue;
                //Досюда
                {
                    oWatch.Reset();
                    oWatch.Start();

                    trueWowsTestContext.stuffManager.Save(entity);

                    oWatch.Stop();
                }
                TimeSpan tTS = oWatch.Elapsed;
                spans.Add(tTS);
                progressObject.Value = i * 100 / count;
            }
            progressObject.Value = 100;
            return spans;
        }
        //

        //with Structs
        private List<TimeSpan> testWithStructsNativeSave(int count = 100)
        {
            List<TimeSpan> spans = new List<TimeSpan>();
            NodeReference wtr = conn.CreateNodeReference("wowsTest");
            Stopwatch nWatch = new Stopwatch();
            progressNative.Value = 0;
            //
            //Dataholders
            string shipClass = "kruis";
            string classificationClass = "";
            int classificationRank = 1;
            string shipName = "";
            object[] keys = new object[] { shipClass, 0, classificationClass, classificationRank, shipName};
            object[] oficersNames = new object[] { "", "", "" };
            object[] workersNames = new object[] { "", "", "" };
            object[] captain1 = new object[] { "", 11111111 };
            object[] captain2 = new object[] { "", 11111111 };
            object[] captainsList = new object[] { captain1, captain2 };
            object[] classification = new object[] { "", 1 };
            StringBuilder name1 = new StringBuilder(20);
            StringBuilder name2 = new StringBuilder(20);
            StringBuilder name3 = new StringBuilder(20);
            int s = 1000;
            byte[] byteValue = new byte[] { 6, 6, 6 };
            //

            ValueList oficersVL = conn.CreateList();
            ValueList workersVL = conn.CreateList();
            ValueList captainsContactsVL = conn.CreateList();
            ValueList captain1VL = conn.CreateList(2);
            ValueList captain2VL = conn.CreateList(2);
            ValueList vlist = conn.CreateList();
            //
            bool variantClear = true;
            for (int i = 0; i < count; i++)
            {
                name1.Remove(0, name1.Length);
                name2.Remove(0, name2.Length);
                name3.Remove(0, name3.Length);
                name1.Insert(0, i + 1);
                name2.Insert(0, i + 2);
                name3.Insert(0, i + 3);

                //отсюда
                keys[0] = shipClass;
                keys[1] = i;
                keys[2] = name3.ToString();
                keys[3] = i;
                keys[4] = name1.ToString();
                captain1[0] = name1.ToString();
                captain1[1] = (int)captain1[1]+i;
                captain2[0] = name2.ToString();
                captain2[1] = (int)captain1[1] + i;
                captainsList[0] = captain1;
                captainsList[1] = captain2;
                oficersNames[0] = name1.ToString();
                oficersNames[1] = name2.ToString();
                oficersNames[2] = name3.ToString();
                workersNames[0] = name3.ToString();
                workersNames[1] = name2.ToString();
                workersNames[2] = name1.ToString();
                //

                //
                //s = s;
                //byteValue = byteValue;
                //досюда
                //
                if (variantClear)
                {
                    nWatch.Reset();
                    nWatch.Start();

                    oficersVL.Append(oficersNames);
                    workersVL.Append(workersNames);
                    captain1VL.Append(captain1);
                    captain2VL.Append(captain2);
                    captainsContactsVL.Append(captain1VL);
                    captainsContactsVL.Append(captain2VL);
                    vlist.Append(captainsContactsVL);
                    vlist.Append(oficersVL);
                    vlist.Append(workersVL);
                    vlist.Append(s);
                    vlist.Append(byteValue);
                    //
                    wtr.Set(vlist, keys);
                    //
                    oficersVL.Clear();
                    workersVL.Clear();
                    captain1VL.Clear();
                    captain2VL.Clear();
                    captainsContactsVL.Clear();
                    vlist.Clear();

                    nWatch.Stop();
                }
                else
                {
                    nWatch.Reset();
                    nWatch.Start();

                    ValueList oficersVLc = conn.CreateList();
                    ValueList workersVLc = conn.CreateList();
                    ValueList captainsContactsVLc = conn.CreateList();
                    ValueList captain1VLc = conn.CreateList(2);
                    ValueList captain2VLc = conn.CreateList(2);
                    ValueList vlistc = conn.CreateList();

                    oficersVLc.Append(oficersNames);
                    workersVLc.Append(workersNames);
                    captain1VLc.Append(captain1);
                    captain2VLc.Append(captain2);
                    captainsContactsVLc.Append(captain1VLc);
                    captainsContactsVLc.Append(captain2VLc);
                    vlistc.Append(captainsContactsVLc);
                    vlistc.Append(oficersVLc);
                    vlistc.Append(workersVLc);
                    vlistc.Append(s);
                    vlistc.Append(byteValue);
                    //
                    wtr.Set(vlistc, keys);

                    //variant close
                    oficersVLc.Close();
                    workersVLc.Close();
                    captain1VLc.Close();
                    captain2VLc.Close();
                    captainsContactsVLc.Close();
                    vlistc.Close();

                    nWatch.Stop();
                }

                TimeSpan nTS = nWatch.Elapsed;
                spans.Add(nTS);
                progressNative.Value = i * 100 / count;
            }
            progressNative.Value = 100;
            return spans;
        }
        private List<TimeSpan> testWithStructsTrueSave(int count = 100)
        {
            List<TimeSpan> spans = new List<TimeSpan>();
            TrueNodeReference WTr = new TrueNodeReference(conn, "wowsTest");
            Stopwatch tWatch = new Stopwatch();
            progressTrue.Value = 0;
            for (int i = 0; i < count; i++)
            {
                string i1 = (i + 1).ToString(), i2 = (i + 2).ToString(), i3 = (i + 3).ToString();
                int s = 1000;
                //ОТСЮДА
                ArrayList akeys = new ArrayList() { "kruis", i };
                ArrayList asublist1 = new ArrayList() { i1, i2, i3 };
                ArrayList asublist2 = new ArrayList() { i3, i2, i1 };
                byte[] bytes = new byte[] { 6, 6, 6 };
                ArrayList alist = new ArrayList() { asublist1, asublist2, s, bytes };
                ArrayList values = new ArrayList() {
                    new ArrayList() { i1, i2, i3 }
                    , new ArrayList() { i3, i2, i1 }
                    , 1000
                    , new byte[] { 6, 6, 6 } };
                //Досюда
                {
                    tWatch.Reset();
                    tWatch.Start();

                    WTr.SetValues(akeys, alist);

                    tWatch.Stop();
                }
                TimeSpan tTS = tWatch.Elapsed;
                spans.Add(tTS);
                progressTrue.Value = i * 100 / count;
            }
            progressTrue.Value = 100;
            return spans;
        }
        private List<TimeSpan> testWithStructsObjectSave(int count = 100)
        {
            List<TimeSpan> spans = new List<TimeSpan>();
            TrueNodeReference WTr = new TrueNodeReference(conn, "wowsTest");
            Stopwatch oWatch = new Stopwatch();
            progressObject.Value = 0;
            //
            trueWowsTestContext.stuffManager.Validate = false;
            Random rand = new Random();
            //
            //Data holders
            string shipClass = "kruis";
            int s = 1000;
            Classification classification = new Classification(ClassType: "", Rank: 1);
            List<string> oficersNames = new List<string> { "", "", "" };
            List<string> workersNames = new List<string> { "", "", "" };
            StringBuilder name1 = new StringBuilder(20);
            StringBuilder name2 = new StringBuilder(20);
            StringBuilder name3 = new StringBuilder(20);
            byte[] byteValue = new byte[] { 6, 6, 6 };
            List<Contact> captainsList = new List<Contact>{
                 new Contact ( Name:"", Phone:111111)
                ,new Contact( Name:"", Phone:111111)
            };

            //stuffProxy entity = new stuffProxy();
            ShipInfoProxy entity = new ShipInfoProxy();
            //
            for (int i = 0; i < count; i++)
            {
                name1.Remove(0, name1.Length);
                name2.Remove(0, name2.Length);
                name3.Remove(0, name3.Length);
                captainsList[0].Phone = 111111;
                captainsList[1].Phone = 111111;
                name1.Insert(0, i + 1);
                name2.Insert(0, i + 2);
                name3.Insert(0, i + 3);
                oficersNames[0] = name1.ToString();
                oficersNames[1] = name2.ToString();
                oficersNames[2] = name3.ToString();
                workersNames[0] = name3.ToString();
                workersNames[1] = name2.ToString();
                workersNames[2] = name1.ToString();
                //
                classification.ClassType = name3.ToString();
                classification.Rank = i;
                //
                captainsList[0].Name = name1.ToString();
                captainsList[0].Phone += i;
                captainsList[1].Name = name2.ToString();
                captainsList[1].Phone += i;
                //ОТСЮДА keys
                entity.shipclass = shipClass;
                entity.shiprank = i;
                entity.Classification = classification;
                entity.Name = name1.ToString();
                // values
                entity.officers = oficersNames;
                entity.workers = workersNames;
                entity.workerSalary = s;
                entity.photo = byteValue;
                entity.captains = captainsList;
                //Досюда
                {
                    oWatch.Reset();
                    oWatch.Start();

                    trueWowsTestContext.ShipInfoManager.Save(entity);

                    oWatch.Stop();
                }
                TimeSpan tTS = oWatch.Elapsed;
                spans.Add(tTS);
                progressObject.Value = i * 100 / count;
            }
            progressObject.Value = 100;
            return spans;
        }
        private List<TimeSpan> testWithStructsObjectFasterSave(int count = 100)
        {
            List<TimeSpan> spans = new List<TimeSpan>();
            TrueNodeReference WTr = new TrueNodeReference(conn, "wowsTest");
            Stopwatch oWatch = new Stopwatch();
            progressObject.Value = 0;
            //
            trueWowsTestContext.stuffManager.Validate = false;
            Random rand = new Random();
            //
            //Data holders
            string shipClass = "kruis";
            int s = 1000;
            Classification classification = new Classification(ClassType: "", Rank: 1);
            List<string> oficersNames = new List<string> { "", "", "" };
            List<string> workersNames = new List<string> { "", "", "" };
            StringBuilder name1 = new StringBuilder(20);
            StringBuilder name2 = new StringBuilder(20);
            StringBuilder name3 = new StringBuilder(20);
            byte[] byteValue = new byte[] { 6, 6, 6 };
            List<Contact> captainsList = new List<Contact>{
                 new Contact ( Name:"", Phone:111111)
                ,new Contact( Name:"", Phone:111111)
            };

            //stuffProxy entity = new stuffProxy();
            ShipInfoProxy entity = new ShipInfoProxy();
            //
            for (int i = 0; i < count; i++)
            {
                name1.Remove(0, name1.Length);
                name2.Remove(0, name2.Length);
                name3.Remove(0, name3.Length);
                captainsList[0].Phone = 111111;
                captainsList[1].Phone = 111111;
                name1.Insert(0, i + 1);
                name2.Insert(0, i + 2);
                name3.Insert(0, i + 3);
                oficersNames[0] = name1.ToString();
                oficersNames[1] = name2.ToString();
                oficersNames[2] = name3.ToString();
                workersNames[0] = name3.ToString();
                workersNames[1] = name2.ToString();
                workersNames[2] = name1.ToString();
                //
                classification.ClassType = name3.ToString();
                classification.Rank = i;
                //
                captainsList[0].Name = name1.ToString();
                captainsList[0].Phone += i;
                captainsList[1].Name = name2.ToString();
                captainsList[1].Phone += i;
                //ОТСЮДА keys
                entity.shipclass = shipClass;
                entity.shiprank = i;
                entity.Classification = classification;
                entity.Name = name1.ToString();
                // values
                entity.officers = oficersNames;
                entity.workers = workersNames;
                entity.workerSalary = s;
                entity.photo = byteValue;
                entity.captains = captainsList;
                //Досюда
                {
                    oWatch.Reset();
                    oWatch.Start();

                    trueWowsTestContext.ShipInfoManager.SaveFaster(entity);

                    oWatch.Stop();
                }
                TimeSpan tTS = oWatch.Elapsed;
                spans.Add(tTS);
                progressObject.Value = i * 100 / count;
            }
            progressObject.Value = 100;
            return spans;
        }
        //

        class KillParam
        {
            public int param;
            public KillParam(int param) { this.param = param; }
        }
        void killOld(object param)
        {
            int count = ((KillParam)param).param;
            progressClear.Value = 0;

            NodeReference wtr = conn.CreateNodeReference("wowsTest");

            //withoutstructcheck
            /*object[] akeys = new object[2]{"kruis",0};
            for (int i = 0; i < count; i++)
            {
                akeys[1] = i;
                wtr.Kill(akeys);
                progressClear.Value = i * 100 / count;
            }*/

            //with struct
            string shipClass = "kruis";
            string classificationClass = "";
            int classificationRank = 1;
            string shipName = "";
            object[] keys = new object[] { shipClass, 0, classificationClass, classificationRank, shipName };
            StringBuilder name1 = new StringBuilder(20);
            StringBuilder name3 = new StringBuilder(20);
            for (int i = 0; i < count; i++)
            {
                name1.Remove(0, name1.Length);
                name3.Remove(0, name3.Length);
                name1.Insert(0, i + 1);
                name3.Insert(0, i + 3);
                keys[0] = shipClass;
                keys[1] = i;
                keys[2] = name3.ToString();
                keys[3] = i;
                keys[4] = name1.ToString();
                wtr.Kill(keys);
                progressClear.Value = i * 100 / count;
            }

            //
            progressClear.Value = 100;
        }
        //
        private void btnTest_Click(object sender, EventArgs e)
        {
            int count = (int)numericUpDown1.Value;
            //DialogResult result = MessageBox.Show("At the moment this test may force a lot of RAM, it may temporarily slow your system. For example, saving 300000 units takes approximately 2Gb of RAM.\n\n Do you want to continue?", "WARNING!!!", MessageBoxButtons.OKCancel);
            //if (result == DialogResult.OK)
            //{
                compareSaveSpeed(count);
            //}
            /*Thread tr = new Thread(new ParameterizedThreadStart(killOld));
            tr.Start(new KillParam(count));*/
        }

        private void btnValidation_Click(object sender, EventArgs e)
        {
            if(btnValidation.Text.Equals("OFF validation"))
            {
                btnValidation.Text = "ON validation";
                btnValidation.BackColor = Color.Green;
                isValidate = true;
                return;
            }
            if (btnValidation.Text.Equals("ON validation"))
            {
                btnValidation.Text = "OFF validation";
                btnValidation.BackColor = Color.Pink;
                isValidate = false;
            }
        }
    }
}


text:
package org.apache.ignite.ml.math.functions;

import org.apache.ignite.ml.math.Vector;

/**
 * Interface for differentiable functions from vector to double.
 */
public interface IgniteDifferentiableVectorToDoubleFunction extends IgniteFunction<Vector, Double> {
    /**
     * Get function differential at a given point.
     *
     * @param pnt Point to calculate differential at.
     * @return Function differential at a given point.
     */
    Vector differential(Vector pnt);
}


text:
from django import forms

from corpus.models import EvidenceLabel

DEFAULT_LABEL = EvidenceLabel._meta.get_field('label').default

class EvidenceForm(forms.ModelForm):
    class Meta:
        model = EvidenceLabel
        fields = ["label"]
        widgets = {
            'label': forms.RadioSelect
        }

    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance', None)
        restore_None = False
        if instance and instance.label is None:
            # When created, EvidenceLabel get None as label.
            # For such cases, on forms, we'll suggest the model.default
            instance.label = DEFAULT_LABEL
            restore_None = True
        super().__init__(*args, **kwargs)
        if restore_None:
            self.instance.label = None
        self.fields['label'].label = ''

    def has_changed(self, *args, **kwargs):
        changed = super().has_changed(*args, **kwargs)
        if not changed and self.instance.label == DEFAULT_LABEL:
            # On init we "hacked" the instance so the form was created showing our
            # desired default value. Because of that, we may not be seeing that change.
            if EvidenceLabel.objects.get(pk=self.instance.pk).label is None:
                changed = True
        return changed

class EvidenceOnDocumentForm(EvidenceForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        f_lbl = self.fields['label']
        f_lbl.widget = forms.HiddenInput()
        # "forms" is the name of some Angular context object on the frontend.
        f_lbl.widget.attrs['ng-value'] = 'forms["%s"]' % self.prefix
        f_lbl.required = False

class EvidenceToolboxForm(EvidenceForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        f_lbl = self.fields['label']
        prev_widget = f_lbl
        f_lbl.widget = forms.RadioSelect(choices=prev_widget.choices)
        f_lbl.widget.attrs['ng-model'] = 'current_tool'


text:
package org.kie.workbench.common.forms.dynamic.client.rendering.formGroups.impl.def;

import javax.enterprise.context.Dependent;
import javax.inject.Inject;

import com.google.gwt.user.client.ui.Widget;
import org.kie.workbench.common.forms.dynamic.client.rendering.formGroups.impl.AbstractFormGroup;
import org.kie.workbench.common.forms.model.FieldDefinition;

@Dependent
public class DefaultFormGroup extends AbstractFormGroup<DefaultFormGroupView> {

    @Inject
    public DefaultFormGroup(DefaultFormGroupView view) {
        super(view);
    }

    public void render(String inputId,
                       Widget widget,
                       FieldDefinition fieldDefinition) {
        this.bindable = widget;

        view.render(inputId,
                    widget,
                    fieldDefinition);
    }
}


text:
Packages in rez can contain different *variants*. Think of these as different
flavors of the same package version. Each variant has one or more package
dependencies that differ to the other variants in the same package.

Use of variants is best illustrated with an example. Consider a maya plugin,
*my_maya_plugin*. Let us assume that there are two active versions of maya
currently in use at your studio - *2016.sp2* and *2017*. If your plugin is compiled,
you may need to build it separately for each maya version, even though the source
is no different.

You would use *variants* to create a version of your plugin that will work with
both maya versions. Consider the following package definition for our plugin:

    name = "my_maya_plugin"

    version = "1.0.0"

    requires = [
        "openexr-2.2"
    ]

    variants = [
        ["maya-2016.sp2"],
        ["maya-2017"]
    ]

When you build and install this package, two separate builds will occur - one
using *maya-2016.sp2*, and the other *maya-2017*. When an environment is resolved
that includes *my_maya_plugin*, the correct variant will be selected depending on
the version of maya present. Only one variant of a package is ever used in a
given configured environment.

Each variant entry is a list of dependencies, no different to the packages listed
in the *requires* field. These dependencies are appended to the *requires* list
for each variant. Thus the first variant requires *openexr-2.2* and *maya-2016.sp1*,
and the second variant requires *openexr-2.2* and *maya-2017*.

## Disk Structure

Package variants are stored within the package, under subdirectories that match
the variant requirements. For example, continuing on with our *my_maya_plugin*
package, the installation of that package would look like so:

    /rez/packages/my_maya_plugin/1.0.0/maya-2016.sp2/<PAYLOAD>
                                      /maya-2017/<PAYLOAD>

The anatomy of a package with variants is illustrated in the following diagram:

The *root* of a package is the root directory of its current variant (the one
the current environment is configured to use); the *base* of a package is the
directory containing its variants. In a package that does not have variants,
*base* and *root* are the same.

## Hashed Variants

There are two problems with the variant subpath as illustrated above:
* The variant install path can become long if there are many requirements;
* If some variant requirements contain characters such as `!` and `<`, they
  can cause escaping problems that affect build systems; and, depending on the
  platform, may not be a valid filesystem path.

You can avoid these issues by using _hashed variants_. This sets the variant
subpath to a hash of its requirements, rather than the requirements themselves.
The resulting subdirectly is somewhat unwieldy (example:
`83e0c415db1b602f9d59cee028da6ac785e9bacc`). However, another feature -
_variant shortlinks_ - deals with this. A shortlink is a symlink to each variant,
created in a separate subdirectory (default `_v`).

Here is an example hashed variant path:

    /rez/packages/my_maya_plugin/1.0.0/83e0c415db1b602f9d59cee028da6ac785e9bacc

Here is the matching _shortlink_, which is what will be used in a resolved
environment:

    /rez/packages/my_maya_plugin/1.0.0/_v/a

Hashed variants must be enabled explicitly for a package. To do this, simply set
this in your package definition:

    hashed_variants = True

## Platform As Variant

It is not uncommon to see the platform, architecture and/or operating system
packages in package variants (recall that rez represents these as packages). For
example, you might see variants like this:

    # in package.py
    variants = [
        ["platform-linux", "arch-x86_64", "os-Ubuntu-12.04"],
        ["platform-linux", "arch-x86_64", "os-Ubuntu-16.04"]
    ]

This indicates that the package has been built for multiple platforms. The correct
variant will be selected for you, because you probably have the relevant
[implicit packages](Basic-Concepts#implicit-packages) set to limit packages to
the current platform.

## Single Variants

You may often see packages with just one variant. There are two reasons for this:

* *Future proofing*. Let's say you have a compiled package that links against python.
  It may currently support *python-2.7*, however it's conceivable that support for
  newer python versions may be added later. It is not possible to add new variants
  to a package that does not have any; so by adding the *python-2.7* variant now,
  you can add variants later without needing to move to a newer version.
* *Installation path*. People often expect to see platform, architecture and/or
  operating system information in the installation path of a piece of software (and
  may also expect the same of python version, or other core packages). By putting
  these dependencies into a variant, we ensure that they appear in the installation
  path of the package.

## Variant Selection

As mentioned, rez will automatically select the correct variant of a package
depending on the environment being resolved. For example, consider:

    ]$ rez-env my_maya_plugin maya-2017 -- echo '$REZ_MY_MAYA_PLUGIN_ROOT'
    /rez/packages/my_maya_plugin/1.0.0/maya-2017
    ]$ rez-env my_maya_plugin maya-2016 -- echo '$REZ_MY_MAYA_PLUGIN_ROOT'
    /rez/packages/my_maya_plugin/1.0.0/maya-2016.sp2

You can see how the correct variant (ie the one that does not conflict with other
packages in the request) has been selected. But what if both variants are valid
for the given request? Consider:

    ]$ rez-env my_maya_plugin -- echo '$REZ_MY_MAYA_PLUGIN_ROOT'
    /rez/packages/my_maya_plugin/1.0.0/maya-2017

Here *maya* was not in the request. Either variant of *my_maya_plugin* would have
satisfied the request, since we have not specified which version of maya we actually
want.

By default, rez will prefer the variant with the higher-versioned packages, which
is why the *maya-2017* variant was selected in this example. If there are
multiple packages in the variant, priority is given to those that were in the request
list, if any; following that, priority is given to packages listed earlier in the
variant. For example, consider:

    name = "foo"

    variants = [
        ["python-2.6", "maya-2017"],
        ["python-2.7", "maya-2016"]
    ]

If I run "rez-env foo", which variant will I get? The answer is not clear. In this
case it will be the second variant, since *python* is given priority (it is the
first listed package in the variant), and the second variant has the higher version
of python. However, if I ran "rez-env foo maya", I would get the *first* variant -
because priority is now given to *maya*, because it's listed in my request, and the
first variant has the higher version of maya.

The rez setting
[variant_select_mode](Configuring-Rez#variant_select_mode) affects this selection behavior.
The default mode just described is *version_priority*, but there is another mode -
*intersection_priority*. In this mode, variants are preferred that have *the most
number of packages present in the request*; version priority is secondary.

### Mutual Exclusivity

In all the examples we've seen so far, a package's variants have been mutually
exclusive. For example, you cannot have both *python-2.6* and *python-2.7* in the
same environment, so when we request "foo python-2.6" we can be sure of which
variant we will get.

Variants, however, do not need to be mutually exclusive. In fact, you may use
variants in order to provide support for different DCCs for your package. Consider
a package with the following variants:

    name = "geocache"

    variants = [
        ["maya-2016"],
        ["houdini-14"]
    ]

Which variant will I get if I run "rez-env geocache"? Behavior in this case is
undefined - rez gives no guarantees as to which variant will be selected. We cannot
meaningfully compare version numbers across packages, so maya will not have preference
simply because 2016 > 14. However, *version_priority* mode does give priority to
packages listed in the request. So if we ran "rez-env geocache maya", we will get
the first variant... probably.

#### Probably?

The operative word here is *preference*. Because the variants are not mutually
exclusive, we can't make guarantees. A resolve is still deterministic - you aren't
going to get differing results when requesting the same environment - but predicting
which variant you'll get can be tricky.

Consider the following request:

    ]$ rez-env geocache maya animtools-1.4

We would expect to get the *maya-2016* variant of *geocache*. However, what if
*animtools* requires *maya-2017*? This makes the first *geocache* variant impossible
to select, since a conflict would occur, and so the *houdini* variant of *geocache*
will be selected - quite possibly not what you expected.

> [[media/icons/under_construction.png]] I plan on adding a new package request
> syntax, that is able to explicitly select package variants. This will avoid the
> ambiguity in cases like the one described here.

## Why Use Variants?

Variants are a powerful mechanism in rez. They avoid the need to maintain separate
branches of a package in order to support varying dependencies. You may have had
problems in the past where a common library depends on, say, boost, and is used in
various DCCs (maya, nuke etc), and depended on by many other packages in your
pipeline. When a DCC moves to a new version of boost (or python, or OIIO, etc)
you now have to branch this library, which potentially affects many other packages.
The problem gets worse if you have multiple dependencies with varying versions.
Variants solve that problem - you simply add another boost variant to your library,
and other dependent packages are not affected. Rez will correctly select the
package variant that does not conflict with the resolved environment.


text:
package org.bdgenomics.avocado.algorithms.hmm

import org.scalatest.FunSuite

class HMMAlignerSuite extends FunSuite {

  test("test perfect match alignment") {
    val hmm = new HMMAligner
    val refSequence = "TCGATCGA"
    val testSequence = "TCGATCGA"
    val qualities = "FFFFFFFF"

    val alignment = hmm.alignSequences(refSequence, testSequence, qualities)

    assert(alignment.hasVariants === false)
    assert(alignment.alignmentStateSequence === "========")
    assert(alignment.alignedReference === "TCGATCGA")
    assert(alignment.alignedSequence === "TCGATCGA")

  }

  test("test single-snp alignment") {
    val hmm = new HMMAligner
    val refSequence = "TCGATCGA"
    val testSequence = "TCGTTCGA"
    val qualities = "FFFFFFFF"

    val alignment = hmm.alignSequences(refSequence, testSequence, qualities)

    assert(alignment.hasVariants === true)
    assert(alignment.alignmentStateSequence === "===X====")
    assert(alignment.alignedReference === "TCGATCGA")
    assert(alignment.alignedSequence === "TCGTTCGA")
  }

  test("test multi-snp alignment") {
    val hmm = new HMMAligner
    val refSequence = "TCGATCGA"
    val testSequence = "TGGATGGA"
    val qualities = "FFFFFFFF"

    val alignment = hmm.alignSequences(refSequence, testSequence, qualities)

    assert(alignment.hasVariants === true)
    assert(alignment.alignmentStateSequence === "=X===X==")
    assert(alignment.alignedReference === "TCGATCGA")
    assert(alignment.alignedSequence === "TGGATGGA")
  }

  test("test single insertion alignment") {
    val hmm = new HMMAligner
    val refSequence = "TCGATCGA"
    val testSequence = "TCGAATCGA"
    val qualities = "FFFFFFFFF"

    val alignment = hmm.alignSequences(refSequence, testSequence, qualities)

    assert(alignment.hasVariants === true)
    assert(alignment.alignmentStateSequence === "===I=====")
    assert(alignment.alignedReference === "TCG_ATCGA")
    assert(alignment.alignedSequence === "TCGAATCGA")
  }

  test("test homopolymer single insertion alignment") {
    val hmm = new HMMAligner
    val refSequence = "TACCAATGTAA"
    val testSequence = "TACCCAATGTAA"
    val qualities = "FFFFFFFFF"

    val alignment = hmm.alignSequences(refSequence, testSequence, qualities)

    assert(alignment.hasVariants === true)
    assert(alignment.alignmentStateSequence === "==I=========")
    assert(alignment.alignedReference === "TA_CCAATGTAA")
    assert(alignment.alignedSequence === "TACCCAATGTAA")
  }

  test("test long insertion alignment") {
    val hmm = new HMMAligner
    val refSequence = "TCGATCGA"
    val testSequence = "TCGACCCCTCGA"
    val qualities = "FFFFFFFFFFFF"

    val alignment = hmm.alignSequences(refSequence, testSequence, qualities)

    assert(alignment.hasVariants === true)
    assert(alignment.alignmentStateSequence === "====IIII====")
    assert(alignment.alignedReference === "TCGA____TCGA")
    assert(alignment.alignedSequence === "TCGACCCCTCGA")
  }

  test("test single deletion alignment") {
    val hmm = new HMMAligner
    val refSequence = "TCGATCGA"
    val testSequence = "TCGATGA"
    val qualities = "FFFFFFFF"

    val alignment = hmm.alignSequences(refSequence, testSequence, qualities)

    assert(alignment.hasVariants === true)
    assert(alignment.alignmentStateSequence === "=====D==")
    assert(alignment.alignedReference === "TCGATCGA")
    assert(alignment.alignedSequence === "TCGAT_GA")
  }

  test("test mixed insertion and deletion alignment") {
    val hmm = new HMMAligner
    val refSequence = "TCGATCAGGAAGC"
    val testSequence = "TCGAGGTCAGAAGC"
    val qualities = "FFFFFFFFFFFFFF"

    val alignment = hmm.alignSequences(refSequence, testSequence, qualities)

    assert(alignment.hasVariants === true)
    assert(alignment.alignmentStateSequence === "====II===D=====")
    assert(alignment.alignedReference === "TCGA__TCAGGAAGC")
    assert(alignment.alignedSequence === "TCGAGGTCA_GAAGC")
  }

  test("test padded alignment") {
    val hmm = new HMMAligner
    val refSequence = "ACCATAGGACATACCGGACAT"
    val testSequence = "GGACATACCG"
    val qualities = "FFFFFFFFFF"

    val alignment = hmm.alignSequences(refSequence, testSequence, qualities)

    assert(alignment.hasVariants === false)
    assert(alignment.alignmentStateSequence === "PPPPPP==========PPPPP")
    assert(alignment.alignedReference === "accataGGACATACCGgacat")
    assert(alignment.alignedSequence === "______GGACATACCG_____")
  }
}


text:
<?php

namespace app\modules\api\v1\controllers;

use app\components\base\APIController;
use app\components\base\interfaсes\RestFullAPIControllerMethods;

/**
 * Контролер сутності Оцінка
 * Class ClientController
 * @package app\modules\api\v1\controllers
 */
class MoodController extends APIController implements RestFullAPIControllerMethods
{
    /**
     * Ініціалізує контроллер
     * @param string $id
     * @param \yii\base\Module $module
     * @param array $config
     */
    public function __construct($id, $module, $config = [])
    {
        $this->selfModel = new \app\modelsMap\MoodMap();

        return parent::__construct($id, $module, $config = []);
    }

    /**
     * Повертає список Оцінок
     * @return mixed
     */
    public function actionList()
    {
        $list = $this->selfModel->getList();

        $this->dataContainerResponse->setData($list);

        return $this->dataContainerResponse->getData();
    }

    /**
     * Створити Оцінку
     * @return mixed|string
     */
    public function actionCreate()
    {
        $this->selfModel->setScenario('create');
        $this->selfModel->setAttributes($this->requestData->getAttributes()->getData());
        $this->selfModel->create();

        $this->dataContainerResponse->setData($this->selfModel);

        return $this->dataContainerResponse->getData();
    }

    /**
     * Повернути оцінку по ідентифікатору
     * @param null $id - ідентифікатор оцінки
     * @return mixed|string
     */
    public function actionRead($id = null)
    {
        $this->selfModel->setScenario('read');

        $this->selfModel->id = $id;

        $result = $this->selfModel->read();

        $this->dataContainerResponse->setData($result);

        return $this->dataContainerResponse->getData();
    }

    /**
     * Оновити дані оцінки
     * @param null $id - ідентифікатор оцінки
     * @return mixed|string
     */
    public function actionUpdate($id = null)
    {
        $this->selfModel->setScenario('update');
        $this->selfModel->id = $id;
        $this->selfModel->setAttributes($this->requestData->getAttributes()->getData());
        $this->selfModel->update();

        $this->dataContainerResponse->setData($this->selfModel);

        return $this->dataContainerResponse->getData();
    }

    /**
     * Видалити оцінку по ідентифікатору
     * @param null $id -  - ідентифікатор оцінки
     * @return mixed|string
     */
    public function actionDelete($id = null)
    {
        $this->selfModel->setScenario('delete');

        $this->selfModel->id = $id;

        $this->selfModel->delete();

        $this->dataContainerResponse->setData($this->selfModel);

        return $this->dataContainerResponse->getData();
    }

    /**
     * Видалити всі оцінки
     * @return mixed|string
     */
    public function actionDelete_all()
    {
        $message = $this->selfModel->delete_all();

        $this->dataContainerResponse->setData($message);

        return $this->dataContainerResponse->getData();
    }
}


text:
layout: landing
title: "Monetization"
description: "Learn how to maximize your revenue on any device. Improve user experience and get paid."
introduction: "Learn how to maximize your revenue on any device. Improve user experience and get paid."
snippet: "Maximize your revenue potential on any device."
article:
  written_on: 2014-05-29
  updated_on: 2014-05-29
  order: 5
priority: 0
id: monetization
collection: home
---

{% comment %}
Page content will be output by the section layout based on the article collection matching page.id
{% endcomment %}