text:
#include <stdlib.h> /* malloc, free, EXIT_X, ...*/
#include <stdio.h> /* printf, fprintf, recvfrom */
#include <unistd.h> /* getopt */
#include <netinet/in.h> /* sockaddr_in6 */
#include <sys/types.h> /* in6_addr */
#include <sys/socket.h> /* socket, bind, connect */
#include <sys/select.h> /* fd_set, select */
#ifdef __APPLE__
	#include <sys/time.h> /* gettimeofday */
#endif
#include <time.h> /* clock_gettime, time */
#include <string.h> /* memcpy, memcmp */
#include <errno.h> /* errno, EAGAIN, ... */
#include <fcntl.h> /* fcntl */
#include <arpa/inet.h> /* inet_ntop */
#include <limits.h> /* INT_MAX, SHRT_MAX */
#include <stdint.h> /* uint8_t */

#include "min_queue.h" /* minq_x */

/* Min packet length in the protocol */
#define MIN_PKT_LEN 10
/* Min packet length of a data packet in the protocol */
#define MIN_PKT_PDATA_LEN 12
/* Position of the length bit in the header */
#define LENGTH_FIELD_LENGTH_BIT_POS 8

/*
 * Max packet length in the protocol (packet with max header size +
 * max payload size + CRC2 size
 */
#define MAX_PKT_LEN (MIN_PKT_LEN + 2 + 512 + 4)
/* Random number between 0 and 100 */
#define RAND_PERCENT ((unsigned int)(rand() % 101))

/* Link directions*/
#define LINK_FORWARD 1
#define LINK_REVERSE 2
#define LINK_BOTH_WAYS (LINK_FORWARD | LINK_REVERSE)
#define SAME_DIRECTION(x, y) (x & y)
static inline const char* get_link_direction(int x)
{
	switch (x) {
		case LINK_FORWARD: return "Forward";
		case LINK_REVERSE: return "Reverse";
		case LINK_BOTH_WAYS: return "Both ways";
		default: return "Unknown";
	}
}

int forward_port = 12345;
int port = 1341;
unsigned int delay = 0;
unsigned int jitter = 0;
unsigned int err_rate = 0;
unsigned int cut_rate = 0;
unsigned int loss_rate = 0;
int link_direction = LINK_FORWARD;
int sfd = -1; /* socket file des. */
minqueue_t *pkt_queue = NULL; /* Queue for delayed packet */
struct timeval last_clock; /* Cache current timestamp */
struct sockaddr_in6 dest_addr, src_addr; /* The addresses of the 2 parties */
int has_source_addr = 0; /* Have we seen the other party yet */

struct pkt_slot { /* One entry in the packet queue */
	struct timeval ts; /* Expiration date */
	int direction; /* The direction of the packet */
	int size; /* How many bytes are used in buf */
	char buf[MAX_PKT_LEN]; /* The packet data */
};

/* Get the human-readable representation of an IPv6 */
static inline const char *sockaddr6_to_human(const struct in6_addr *a)
{
	static char b[INET6_ADDRSTRLEN];
	/* Can safely ignore return value as we control all parameters */
	inet_ntop(AF_INET6, a, b, sizeof(*a));
	return b;
}

/* @return: left > right */
static inline int timeval_cmp(const struct timeval *left,
							const struct timeval *right)
{
	return left->tv_sec == right->tv_sec ?
		left->tv_usec > right->tv_usec :
		left->tv_sec > right->tv_sec;
}

/* @return: c = a - b */
static void timeval_diff(const struct timeval *a,
					const struct timeval *b,
					struct timeval *c)
{
	c->tv_sec = a->tv_sec - b->tv_sec;
	c->tv_usec = a->tv_usec - b->tv_usec;
	/* Underflow in usec, compensate through secs */
	if (c->tv_usec < 0) {
		if (--c->tv_sec)
			c->tv_usec += 1000000;
	}
}

/* Log an action on a processed packet */
#define LOG_PKT_FMT(buf, fmt, ...) \
	fprintf(stderr,"[%s %3hhu] " fmt, ((uint8_t)buf[0] & 0xC0) == 0x00 ? "FEC" : "SEQ" , (((uint8_t)buf[0] & 0xC0) <= 0x40) ? buf[3] : buf[1], ##__VA_ARGS__)
#define LOG_PKT(buf, msg) LOG_PKT_FMT(buf, msg "\n")

/* Send a packet to the host we're proxying */
static int write_out(const char *buf, int len, int direction)
{
	struct sockaddr_in6 *addr;
	switch (direction) {
		case LINK_FORWARD: addr = &dest_addr;
						   break;
		case LINK_REVERSE: addr = &src_addr;
						   break;
		default: addr = NULL;
				 break;
	};
	LOG_PKT_FMT(buf, "Sent packet (%s).\n", get_link_direction(direction));
	return sendto(sfd, buf, len, 0, (struct sockaddr*)addr,
			sizeof(*addr)) == len ? EXIT_SUCCESS : EXIT_FAILURE;
}

/* Deliver all queued packets whose timestamps have expired */
static int deliver_delayed_pkt()
{
	struct pkt_slot *p = (struct pkt_slot*)minq_peek(pkt_queue);
	/* We have a packet and its timestamp is < current time */
	while (p && timeval_cmp(&last_clock, &p->ts)) {
		/* Send it */
		if (write_out(p->buf, p->size, p->direction)) {
			/* We can try again later for these errors
			 * (send bunf is full, or ...) */
			if (errno == EWOULDBLOCK || errno == EINTR || errno == EAGAIN)
				return EXIT_SUCCESS;
			/* Otherwise propagate error */
			perror("Failed to write all delayed bytes");
			return EXIT_FAILURE;
		}
		minq_pop(pkt_queue);
		free(p);
		p = (struct pkt_slot*)minq_peek(pkt_queue);
	}
	return EXIT_SUCCESS;
}

/* @return: 1 iff a != b, else 0 */
static inline int sockaddr_cmp(const struct sockaddr_in6 *a,
						const struct sockaddr_in6 *b)
{
	return memcmp(&a->sin6_addr, &b->sin6_addr, sizeof(a->sin6_addr)) ||
		a->sin6_port != b->sin6_port;
}

/* Simulate the effect of a lossy link on a received packet */
static inline int simulate_link(char *buf, int len, int direction)
{
	/* Do we drop it? */
	if (loss_rate && RAND_PERCENT < loss_rate) {
		LOG_PKT(buf, "Dropping packet");
		return EXIT_SUCCESS;
	}
	/* Do we cut it after the header? (only if packet is elligible) */
	if (cut_rate && RAND_PERCENT < cut_rate && len > MIN_PKT_PDATA_LEN &&  ((uint8_t) buf[0])>>6 == 1) {
		LOG_PKT(buf, "Truncating packet");
		len = MIN_PKT_PDATA_LEN;
		/* ... and don't forget to mark it as truncated */
		buf[0] |= 0x20;
	/* or do we corrupt it? */
	} else if (err_rate && RAND_PERCENT < err_rate) {
		int idx = rand() % len;
		LOG_PKT_FMT(buf, "Corrupting packet: inverted byte #%d\n", idx);
		buf[idx] = ~buf[idx];
	}
	/* Do we want to simulate delay? */
	if (delay) {
		/* Random delay to add is capped to 10s */
		unsigned int applied_delay;
		if (jitter) {
			if (jitter > delay) {
				applied_delay = rand() % (delay + jitter);
			} else {
				applied_delay = (delay + rand() % (2 * jitter)) - jitter;
			}
		} else {
			applied_delay = delay;
		}
		applied_delay %= 10000;
		LOG_PKT_FMT(buf, "Delayed packet by %u ms\n", applied_delay);
		/* Create a slot for the packet queue */
		struct pkt_slot *slot;
		if (!(slot = malloc(sizeof(*slot)))) {
			fprintf(stderr,
					"Failed to allocate memory for a delayed packet!\n");
			return EXIT_FAILURE;
		}
		slot->direction = direction;
		/* Copy the packet in the slot */
		memcpy(slot->buf, buf, len);
		slot->size = len;
		/* Register expiration date: current date + delay */
		slot->ts.tv_sec = last_clock.tv_sec + applied_delay / 1000;
		/* delay is in ms not us! */
		slot->ts.tv_usec = last_clock.tv_usec + (applied_delay % 1000) * 1000;
		/* Enqueue the new slot */
		if (minq_push(pkt_queue, slot)) {
			perror("Failed to enqueue a packet!");
			return EXIT_FAILURE;
		}
	} else {
		/* Forward it to the host we're proxying */
		if (write_out(buf, len, direction)) {
			perror("Failed to write all bytes");
			return EXIT_FAILURE;
		}
	}
	return EXIT_SUCCESS;
}

/* sfd has been marked for reading, handle the read and process the packet */
static int process_incoming_pkt()
{
	struct sockaddr_in6 from; /* Whois the one sending us data? */
	socklen_t len_from = sizeof(from);
	char buf[MAX_PKT_LEN]; /* Max allowed packet size for the protocol */
	int len; /* Actual received packet size */
	if ((len = recvfrom(sfd, buf, MAX_PKT_LEN, 0,
					(struct sockaddr *)&from, &len_from)) < 0) {
		/* Ignore if we have been interrupted by a signal,
		 * or if select marked sfd as ready for reading
		 * without any no data available. */
		if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
			return EXIT_SUCCESS;
		/* Real error, abort mission */
		perror("recv failed");
		return EXIT_FAILURE;
	}
	/* Check packet consistency */
	if (len < MIN_PKT_LEN) {
		fprintf(stderr,"Received malformed data, dropping. "
				"(len < %d)\n", MIN_PKT_LEN);
		return EXIT_SUCCESS;
	}
	/* We need to track who is sending us data, so that we can send him the
	 * reverse traffic coming from the host we're proxying
	 */
	if (!has_source_addr) {
		memcpy(&src_addr, &from, sizeof(src_addr));
		fprintf(stderr, "@@ Remote host is %s [%d]\n",
				sockaddr6_to_human(&from.sin6_addr), ntohs(from.sin6_port));
		has_source_addr = 1; /* We're logically connected to that guy */
	}
	int direction = 0;
	if (!sockaddr_cmp(&from, &dest_addr))
		direction = LINK_REVERSE;
	if (!sockaddr_cmp(&from, &src_addr))
		direction = LINK_FORWARD;
	if (!direction) {
		/* We do not know the guy that sent us this data, ignore him */
		fprintf(stderr, "@@ Received %d bytes from %s [%d], "
			"which is an alien to the connection. Dropping it!\n",
			len, sockaddr6_to_human(&from.sin6_addr), ntohs(from.sin6_port));
		return EXIT_SUCCESS;
	}
	/* Simply relay packets from the host we're proxying */
	if (!SAME_DIRECTION(direction, link_direction)) {
		if (write_out(buf, len, direction)) {
			perror("Failed to relay a message without altering it.");
			return EXIT_FAILURE;
		}
		return EXIT_SUCCESS;
	}
	/* We have valid data, simulate the behavior of a lossy link
	 * before delivery
	 */
	return simulate_link(buf, len, direction);
}

/* Update last_lock to the current time */
static int update_time()
{
#ifdef __APPLE__
	if (gettimeofday(&last_clock, NULL)) {
		perror("Cannot get internal clock");
		return EXIT_FAILURE;
	}
#else /* gettimeofday is deprecated */
	struct timespec ts;
	if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
		perror("Cannot internal clock");
		return EXIT_FAILURE;
	}
	last_clock.tv_sec = ts.tv_sec;
	last_clock.tv_usec = ts.tv_nsec/1000;
#endif /* __APPLE__ */
	return EXIT_SUCCESS;
}

/* If a packet is queue, return how long until it should be delivered,
 * otherwise return NULL
 */
static struct timeval* get_queue_timeout()
{
	static struct timeval timeout;
	/* No queued packet */
	if (minq_empty(pkt_queue))
		return NULL;
	/* Get closest expiration date for the queued packet */
	struct timeval *ts = &((struct pkt_slot*)minq_peek(pkt_queue))->ts;
	/* timeout = expiration_date - current date */
	timeval_diff(ts, &last_clock, &timeout);
	/* If we queued the packet for too long, set a 1ms timeout. We cannot set
	 * 0 as packet queued for too long can be due to the send buffer
	 * being full, thus packet not being dequeued.
	 */
	if (timeout.tv_sec < 0 || (!timeout.tv_sec && timeout.tv_usec <= 0)) {
		timeout.tv_sec = 0;
		timeout.tv_usec = 1000; /* 1ms */
	}
	return &timeout;
}

/* Loop forever, waiting on packet to process */
static int proxy_loop()
{
	fd_set rfds;
	FD_ZERO(&rfds);
	if (update_time()) return EXIT_FAILURE;
	while (1) {
		/* Reset sfd in fdset, as timeout expiration would have removed it. */
		FD_SET(sfd, &rfds);
		/* Wait for incoming data, or end of a delay on a previously received
		 * packet */
		if (select(sfd+1, &rfds, NULL, NULL, get_queue_timeout()) < 0) {
			/* Ignore if interruption is due to a signal */
			if (errno == EINTR) continue;
			else {
				/* Bad things do happen ... */
				perror("Select failed");
				break;
			}
		}
		if (update_time() || /* Update time cache */
			deliver_delayed_pkt() || /* Deliver delayed packets */
			/* Process incoming packets, applying drop rates etc */
			(FD_ISSET(sfd, &rfds) && process_incoming_pkt()))
			break;
	}
	/* Reached only on error */
	return EXIT_FAILURE;
}

/* Get a socket,
 * bind to all interfaces on specified port,
 * connect to localhost on forward_port,
 * set as non-blocking,
 * @return: -1 on error or a valid file descriptor.
 */
static int get_socket()
{

	const char *err_str;
	/* Socket creation (IPv6, UDP) */
	if ((sfd = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
		err_str = "Cannot create socket";
		goto fail;
	}
	/* Force the socket to use IPv6,
	 * enable address sharing: multiple processes can consume data for this
	 * IP/port port combination*/
	int enable = 1;
	if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable))) {
		err_str = "Couldn't enable the re-use of the address ...";
		goto fail_socket;
	}
	if (setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable))) {
		err_str = "Cannot force the socket to IPv6";
		goto fail_socket;
	}
	/* Bind the socket to listen on all interfaces (::), on port */
	struct sockaddr_in6 addr;
	/* Implicitly set address to ::,
	 * as well as flowinfo-scope  as they are unwanted here */
	memset(&addr, 0, sizeof(addr));
	addr.sin6_family = AF_INET6;
	addr.sin6_port = htons(port);
	if (bind(sfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
		err_str = "Cannot bind socket";
		goto fail_socket;
	}
	/* Initialize the dest_addr struct (loopback, forward_port).
	 * Cannot connect as we will receive/send data from/to multiple hosts */
	memset(&dest_addr, 0, sizeof(dest_addr));
	dest_addr.sin6_family = AF_INET6;
	dest_addr.sin6_port = htons(forward_port);
	memcpy(&dest_addr.sin6_addr, &in6addr_loopback,
			sizeof(dest_addr.sin6_addr));
	/* Set the socket to non-blocking,
	 * as select() indicates that a socket is ready to be read, but not that it
	 * will not block. */
	if (fcntl(sfd, F_SETFL, fcntl(sfd, F_GETFL, 0) | O_NONBLOCK) < 0) {
		err_str = "Cannot set the socket to non-blocking mode";
		goto fail_socket;
	}
	return sfd;

fail_socket:
	close(sfd);
fail:
	perror(err_str);
	return -1;
}

 /* ? a > b */
static int pkt_slot_cmp(const void *a, const void *b)
{
	struct timeval *left = &((struct pkt_slot*)a)->ts;
	struct timeval *right = &((struct pkt_slot*)b)->ts;
	/* We compare the slots based on their (future) expiration date */
	return timeval_cmp(left, right);
}

static int proxy_traffic()
{
#define _DIE(label, msg, ...) do { \
	fprintf(stderr, msg, ##__VA_ARGS__); \
	rval = EXIT_FAILURE; \
	goto label; \
} while (0)

	int rval = EXIT_SUCCESS;

	if (get_socket() < 0)
		_DIE(exit, "Socket initialization failure!\n");

	if (!(pkt_queue = minq_new(pkt_slot_cmp)))
		_DIE(sfd, "Cannot create priority queue!\n");

	/* Process incoming traffic until error (or forever) */
	if ((rval = proxy_loop()))
		_DIE(queue, "The proxy loop crashed, "
			"had %zu element(s) left in pkt_queue\n", minq_size(pkt_queue));

queue:
	minq_del(pkt_queue);
sfd:
	close(sfd);
exit:
	return rval;

#undef _DIE
}

static void usage(const char *prog_name)
{
	fprintf(stderr,
"Link sim: A simple lossy link simulator.\n"
"This program will relay all incoming UDP traffic on port `port` to\n"
"the loopback address [::1], on port `forward_port`, simulating \n"
"random losses, transmission errors, ...\n"
"\n"
"Usage: %s [-p port] [-P forward_port] [-d delay] [-j jitter]\n"
"       %*s [-e err_rate] [-c cut_rate] [-l loss_rate] [-s seed] [-h]\n"
"-p port          The UDP port on which the link simulator operates.\n"
"                 Defaults to: 1341\n"
"-P forward_port  The UDP port on localhost on which the incoming traffic\n"
"                 should be forwarded.\n"
"                 Defaults to: 12345\n"
"-d delay         The delay (in ms) that should be applied to the traffic.\n"
"                 Defaults to: 0\n"
"-j jitter        The jitter (in ms) that should be applied to the traffic.\n"
"                 The total delay applied to one packet will be:\n"
"                 delay + rand[-jitter, jitter].\n"
"                 Defaults to: 0\n"
"                 Unused if delay == 0.\n"
"-e err_rate      The rate of packet corruption occurrence (in packet/100).\n"
"                 Defaults to: 0\n"
"                 A packet that has been corrupted will NOT be cut.\n"
"-c cut_rate      The rate of packet being cut after the header to simulate\n"
"                 router truncation due to high network load (in packet/100).\n"
"                 Defaults to: 0\n"
"                 A packet that has been cut will NOT be corrupted.\n"
"-l loss_rate     The rate of packets loss (in packet/100).\n"
"                 Defaults to 0\n"
"-s seed          The seed for the random generator, to replay a previous\n"
"                 session.\n"
"                 Defaults to: time() casted to int\n"
"-r               Simulate the link on the reverse path.\n"
"-R               Simulate the link in both ways.\n"
"-h               Prints this message and exit.\n",
			prog_name,
			(int)strlen(prog_name),
			"");
}

static long parse_number(const char *val)
{
	char *c;
	long parsed = strtol(val, &c, 0);
	if (*c != '\0')
		fprintf(stderr, "!! Parsed %s as %ld\n", val, parsed);
	return parsed;
}

int main(int argc, char **argv)
{
	int opt;
	long seed = -1L;
	/* parse option values */
	while ((opt = getopt(argc, argv, "p:P:d:j:e:c:s:l:hrR")) != -1) {
		switch (opt) {
			case 'p':
				port = parse_number(optarg) & ((1 << 16) - 1);
				break;
			case 'P':
				forward_port = parse_number(optarg) & ((1 << 16) - 1);
				break;
			case 'd':
				delay = parse_number(optarg);
				break;
			case 'j':
				jitter = parse_number(optarg);
				break;
			case 'e':
				err_rate = parse_number(optarg) % 101;
				break;
			case 'c':
				cut_rate = parse_number(optarg) % 101;
				break;
			case 'l':
				loss_rate = parse_number(optarg) % 101;
				break;
			case 's':
				seed = parse_number(optarg);
				break;
			case 'r':
				link_direction = LINK_REVERSE;
				break;
			case 'R':
				link_direction = LINK_BOTH_WAYS;
				break;
			case 'h':
				/* Fall-through */
			default:
				usage(argv[0]);
				return EXIT_FAILURE;
		}
	}
	if (optind != argc) {
		fprintf(stderr, "!! Ignoring positional arguments: ");
		for (; optind < argc-1; ++optind)
			fprintf(stderr, "%s, ", argv[optind]);
		fprintf(stderr, "%s\n", argv[optind]);
	}
	/* Setup RNG */
	if (seed == -1L) {
		seed = (int)time(NULL);
		fprintf(stderr, "@@ Using random seed: %d\n", (int)seed);
	}
	srand((int)seed);
	fprintf(stderr, "@@ Using parameters:\n"
					".. port: %d\n"
					".. forward_port: %d\n"
					".. delay: %u\n"
					".. jitter: %u\n"
					".. err_rate: %u\n"
					".. cut_rate: %u\n"
					".. loss_rate: %u\n"
					".. seed: %d\n"
					".. link_direction: %s\n",
					port, forward_port, delay, jitter, err_rate, cut_rate,
					loss_rate, (int)seed, get_link_direction(link_direction));
	/* Start proxying UDP traffic according to the specified options */
	return proxy_traffic();
}


text:
if (process.env.NODE_ENV !== 'production') {
    require('babel-register');
    require('babel-polyfill');
}

/* eslint-disable vars-on-top, no-var */
var startServer = require('./server').default;

// Starting server
var server = startServer(function doneCb(err) {
    if (err) {
        throw err;
    }
});
/* eslint-enable vars-on-top, no-var */

// We need this when working with multiple node instances
process.on('message', message => {
    if (message === 'shutdown') {
        server.stop();
        process.exit(0);
    }
});

redpajama_set_name: RedPajamaGithub


text:
from tethys_apps.utilities import link_service_to_app_setting
from tethys_cli.cli_colors import pretty_output, FG_RED

def add_link_parser(subparsers):
    # LINK COMMANDS
    link_parser = subparsers.add_parser(
        "link", help="Link a Service to a Tethys app Setting."
    )

    # tethys link
    link_parser.add_argument(
        "service",
        help="Service to link to a target app. Of the form "
        '"<spatial|persistent>:<service_id|service_name>" '
        '(i.e. "persistent_connection:super_conn")',
    )
    link_parser.add_argument(
        "setting",
        help="Setting of an app with which to link the specified service."
        'Of the form "<app_package>:'
        "<setting_type (ps_database|ps_connection|ds_spatial)>:"
        '<setting_id|setting_name>" (i.e. "epanet:database:epanet_2")',
    )
    link_parser.set_defaults(func=link_command)

def link_command(args):
    """
    Interact with Tethys Services (Spatial/Persistent Stores) to create them and/or link them to existing apps
    """
    try:
        service = args.service
        setting = args.setting

        service_parts = service.split(":")
        setting_parts = setting.split(":")
        service_type = None
        service_uid = None
        setting_app_package = None
        setting_type = None
        setting_uid = None

        try:
            service_type = service_parts[0]
            service_uid = service_parts[1]

            setting_app_package = setting_parts[0]
            setting_type = setting_parts[1]
            setting_uid = setting_parts[2]
        except IndexError:
            with pretty_output(FG_RED) as p:
                p.write(
                    'Incorrect argument format. \nUsage: "tethys link <spatial|persistent>:<service_id|service_name> '
                    '<app_package>:<setting_type (ps_database|ps_connection|ds_spatial)><setting_id|setting_name>"'
                    "\nCommand aborted."
                )
            exit(1)

        success = link_service_to_app_setting(
            service_type, service_uid, setting_app_package, setting_type, setting_uid
        )

        if not success:
            exit(1)

        exit(0)

    except Exception as e:
        with pretty_output(FG_RED) as p:
            p.write(e)
            p.write("An unexpected error occurred. Please try again.")
        exit(1)


text:
require 'spec_helper'

RSpec.describe AmiManager do
  let(:access_key) { 'access-key' }
  let(:secret_key) { 'secret-key' }
  let(:ami_id) { 'ami-deadbeef' }
  let(:ami_file_path) { Tempfile.new('ami-id-file').tap { |f| f.write("#{ami_id}\n"); f.close }.path }
  let(:ec2) { double('AWS.ec2') }

  let(:aws_options) do
    {
      aws_access_key: 'aws-access-key',
      aws_secret_key: 'aws-secret-key',
      ssh_key_name: 'ssh-key-name',
      security_group_id: 'security-group-id',
      public_subnet_id: 'public-subnet-id',
      private_subnet_id: 'private-subnet-id',
      elastic_ip_id: 'elastic-ip-id',
      vm_name: 'Ops Manager: clean_install_spec'
    }
  end

  subject(:ami_manager) { AmiManager.new(aws_options) }

  before do
    expect(AWS).to receive(:config).with(
        access_key_id: aws_options.fetch(:aws_access_key),
        secret_access_key: aws_options.fetch(:aws_secret_key),
        region: 'us-east-1',
      )

    allow(AWS).to receive(:ec2).and_return(ec2)
  end

  describe '#deploy' do
    let(:instance) { instance_double(AWS::EC2::Instance, status: :running, associate_elastic_ip: nil, add_tag: nil) }
    let(:instances) { instance_double(AWS::EC2::InstanceCollection, create: instance) }

    before do
      allow(ec2).to receive(:instances).and_return(instances)
      allow(ami_manager).to receive(:sleep) # speed up retry logic
    end

    it 'creates an instance using AWS SDK v1' do
      expect(ec2).to receive_message_chain(:instances, :create).with(
          image_id: ami_id,
          key_name: 'ssh-key-name',
          security_group_ids: ['security-group-id'],
          subnet: aws_options.fetch(:public_subnet_id),
          private_ip_address: AmiManager::OPS_MANAGER_PRIVATE_IP,
          instance_type: 'm3.medium').and_return(instance)

      ami_manager.deploy(ami_file_path)
    end

    context 'when the ip address is in use' do
      it 'retries until the IP address is available' do
        expect(instances).to receive(:create).and_raise(AWS::EC2::Errors::InvalidIPAddress::InUse).once
        expect(instances).to receive(:create).and_return(instance).once

        ami_manager.deploy(ami_file_path)
      end

      it 'stops retrying after 60 times' do
        expect(instances).to receive(:create).and_raise(AWS::EC2::Errors::InvalidIPAddress::InUse).
            exactly(AmiManager::RETRY_LIMIT).times

        expect { ami_manager.deploy(ami_file_path) }.to raise_error(AmiManager::RetryLimitExceeded)
      end
    end

    it 'does not return until the instance is running' do
      expect(instance).to receive(:status).and_return(:pending, :pending, :pending, :running)

      ami_manager.deploy(ami_file_path)
    end

    it 'handles API endpoints not knowing (right away) about the instance created' do
      expect(instance).to receive(:status).and_raise(AWS::EC2::Errors::InvalidInstanceID::NotFound).
          exactly(AmiManager::RETRY_LIMIT - 1).times
      expect(instance).to receive(:status).and_return(:running).once

      ami_manager.deploy(ami_file_path)
    end

    it 'stops retrying after 60 times' do
      expect(instance).to receive(:status).and_return(:pending).
          exactly(AmiManager::RETRY_LIMIT).times

      expect { ami_manager.deploy(ami_file_path) }.to raise_error(AmiManager::RetryLimitExceeded)
    end

    it 'attaches the elastic IP' do
      expect(instance).to receive(:associate_elastic_ip).with(aws_options.fetch(:elastic_ip_id))

      ami_manager.deploy(ami_file_path)
    end

    it 'tags the instance with a name' do
      expect(instance).to receive(:add_tag).with('Name', value: aws_options.fetch(:vm_name))

      ami_manager.deploy(ami_file_path)
    end
  end

  describe '#destroy' do
    let(:subnets) { instance_double(AWS::EC2::SubnetCollection) }
    let(:subnet1) { instance_double(AWS::EC2::Subnet, instances: subnet1_instances) }
    let(:subnet2) { instance_double(AWS::EC2::Subnet, instances: subnet2_instances) }
    let(:instance1) { instance_double(AWS::EC2::Instance, tags: {}) }
    let(:instance2) { instance_double(AWS::EC2::Instance, tags: {}) }
    let(:subnet1_instances) { [instance1] }
    let(:subnet2_instances) { [instance2] }

    before do
      allow(ec2).to receive(:subnets).and_return(subnets)
      allow(subnets).to receive(:[]).with('public-subnet-id').and_return(subnet1)
      allow(subnets).to receive(:[]).with('private-subnet-id').and_return(subnet2)
    end

    it 'terminates all VMs in the subnet' do
      expect(instance1).to receive(:terminate)
      expect(instance2).to receive(:terminate)

      ami_manager.destroy
    end

    context 'when an instance has the magical tag' do
      let(:persistent_instance) { instance_double(AWS::EC2::Instance, tags: persist_tag) }
      let(:instances) { [instance1, instance2, persistent_instance] }

      context 'when the do not terminate tag is present' do
        let(:persist_tag) { { AmiManager::DO_NOT_TERMINATE_TAG_KEY => 'any value' } }
        it 'does not attempt to terminate this instance' do
          expect(instance1).to receive(:terminate)
          expect(instance2).to receive(:terminate)
          expect(persistent_instance).not_to receive(:terminate)

          ami_manager.destroy
        end
      end
    end
  end
end


text:
<?xml version="1.0"?>

<registration>
	<tool
			id="sakai.podcasts"
			title="Podcasts"
			description="For managing individual podcast and podcast feed information.">
			<!-- Note: Tool titles and descriptions are now internationalized and managed in the tools.properties file in the config project and will override the above values -->

		<category name="course" />
		<category name="project" />

		<configuration name="functions.require" value="content.read" />
		<configuration name="help.id" value="sakai.podcasts" />
	</tool>
</registration>


text:
<?php

namespace Magento\Tax\Model\ResourceModel\Calculation;

/**
 * Tax Calculation Collection
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * Resource initialization
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('Magento\Tax\Model\Calculation', 'Magento\Tax\Model\ResourceModel\Calculation');
    }
}


text:
namespace MahApps.Metro.Controls
{
    using System.Windows.Controls.Primitives;

    public enum MouseWheelChange
    {
        /// <summary>
        /// Change the value of the slider if the user rotates the mouse wheel by the value defined for <see cref="RangeBase.SmallChange"/>
        /// </summary>
        SmallChange,
        /// <summary>
        /// Change the value of the slider if the user rotates the mouse wheel by the value defined for <see cref="RangeBase.LargeChange"/>
        /// </summary>
        LargeChange
    }
}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

namespace Microsoft.Azure.Commands.Intune
{
    using Management.Intune;
    using Management.Intune.Models;
    using Microsoft.Azure.Commands.Intune.Properties;
    using System;
    using System.Globalization;
    using System.Management.Automation;

    /// <summary>
    /// A cmdlet that creates a new iOS Intune MAM policy azure resource.
    /// </summary>
    [Cmdlet(VerbsCommon.New, "AzureRmIntuneiOSMAMPolicy"), OutputType(typeof(IOSMAMPolicy))]
    public sealed class NewIntuneiOSMAMPolicyCmdlet : IntuneBaseCmdlet
    {
        /// <summary>
        /// Gets or sets the kind.
        /// </summary>
        [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy friendly name.")]
        [ValidateNotNullOrEmpty]
        public string FriendlyName { get; set; }

        /// <summary>
        /// The description of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy description.")]
        [ValidateNotNullOrEmpty]
        public string Description { get; set; }

        /// <summary>
        /// The AppSharingFromLevel of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether the application is allowed to receive information shared by other applications. Information can be restricted to no applications, only managed applications, or be allowed from all applications.")]
        [ValidateNotNullOrEmpty, ValidateSet("none", "policyManagedApps","allApps"), PSDefaultValue(Value = AppSharingType.none)]
        public AppSharingType AppSharingFromLevel { get; set; }

        /// <summary>
        /// The AppSharingToLevel of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether the application is allowed to share information with other applications. Information can be shared with no applications, only managed applications, or shared to all applications.")]
        [ValidateNotNullOrEmpty, ValidateSet("none", "policyManagedApps", "allApps"), PSDefaultValue(Value = AppSharingType.none)]
        public AppSharingType AppSharingToLevel{ get; set; }

        /// <summary>
        /// The Authentication of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether corporate credentials are required to access the application.")]
        [ValidateNotNullOrEmpty, ValidateSet("required","notRequired"), PSDefaultValue(Value = ChoiceType.required)]
        public ChoiceType Authentication { get; set; }

        /// <summary>
        /// The ClipboardSharingLevel of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether to restrict cut, copy and paste with other applications.")]
        [ValidateNotNullOrEmpty, ValidateSet("blocked", "policyManagedApps", "policyManagedAppsWithPasteIn", "allApps"), PSDefaultValue(Value = ClipboardSharingLevelType.blocked)]
        public ClipboardSharingLevelType ClipboardSharingLevel{ get; set; }

        /// <summary>
        /// The DataBackup of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether to prevent iTunes and iCloud backups.")]
        [ValidateNotNullOrEmpty, ValidateSet("allow", "block"), PSDefaultValue(Value = FilterType.allow)]
        public FilterType DataBackup { get; set; }

        /// <summary>
        /// The FileSharingSaveAs of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether to prevent 'Save As' from the application.")]
        [ValidateNotNullOrEmpty, ValidateSet("allow", "block"), PSDefaultValue(Value = FilterType.allow)]
        public FilterType FileSharingSaveAs { get; set; }

        /// <summary>
        /// The Pin of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether simple PIN is required to access the application.")]
        [ValidateNotNullOrEmpty, ValidateSet("required", "notRequired"), PSDefaultValue(Value = ChoiceType.required)]
        public ChoiceType Pin { get; set;}

        /// <summary>
        /// The PinNumRetry  of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "When a simple PIN is required to access the application, this indicates the number of attempts before a PIN reset.")]
        [ValidateNotNullOrEmpty, ValidateRange(0, 200)]
        public int? PinNumRetry { get; set; }

        /// <summary>
        /// The DeviceCompliance  of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether managed applications are blocked from running on rooted or jailbroken devices.")]
        [ValidateNotNullOrEmpty, ValidateSet("enable","disable"), PSDefaultValue(Value = OptionType.enable)]
        public OptionType DeviceCompliance { get; set; }

        /// <summary>
        /// The ManagedBrowser of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether web content from the application is forced to run in the managed browser.")]
        [ValidateNotNullOrEmpty, ValidateSet("required", "notRequired"), PSDefaultValue(Value = ChoiceType.required)]
        public ChoiceType ManagedBrowser { get; set; }

        /// <summary>
        /// The AccessRecheckOfflineTimeout of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates how long to wait in minutes before re-checking access requirements on the device if the device is offline.")]
        [ValidateNotNullOrEmpty]
        public int? AccessRecheckOfflineTimeout { get; set; }

        /// <summary>
        /// The AccessRecheckOnlineTimeout of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates how long to wait in minutes before re-checking access requirements on the device.")]
        public int? AccessRecheckOnlineTimeout { get; set; }

        /// <summary>
        /// The OfflineWipeTimeout of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates the number of days a device must be offline before application data is automatically wiped.")]
        public int? OfflineWipeTimeout { get; set; }

        /// <summary>
        /// The FileEncryptionLevel of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates the level of encryption for application data.")]
        [ValidateNotNullOrEmpty, PSDefaultValue(Value = DeviceLockType.deviceLocked)]
        public DeviceLockType FileEncryptionLevel { get; set; }

        /// <summary>
        /// The TouchId of the policy
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether fingerprints are allowed instead of PIN to access the application.")]
        [ValidateNotNullOrEmpty, PSDefaultValue(Value = OptionType.enable, Help ="Defaults to 'enable'")]
        public OptionType TouchId { get; set; }

        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            InitializeDefaultValuesForParams();

            var policyId = (IntuneBaseCmdlet.iOSPolicyIdsQueue.Count == 0 ? Guid.NewGuid() : IntuneBaseCmdlet.iOSPolicyIdsQueue.Dequeue()).ToString();

            ValidateNumericParameters();
            var policyObj = this.IntuneClient.Ios.CreateOrUpdateMAMPolicy(this.AsuHostName, policyId, this.PrepareIOSPolicyBody());
            this.WriteObject(policyObj);
        }

        /// <summary>
        /// Initialize the number & string parameters if the value is not provided as part of commandlet execution..
        /// Looks like Parameter PSDefaultValue() does not initialize integers & string params
        /// </summary>
        private void InitializeDefaultValuesForParams()
        {
            this.PinNumRetry = this.PinNumRetry ?? IntuneConstants.DefaultPinNumRetry;
            this.AccessRecheckOfflineTimeout = this.AccessRecheckOfflineTimeout ?? IntuneConstants.DefaultAccessRecheckOfflineTimeout;
            this.AccessRecheckOnlineTimeout = this.AccessRecheckOnlineTimeout ?? IntuneConstants.DefaultAccessRecheckOnlineTimeout;
            this.OfflineWipeTimeout = this.OfflineWipeTimeout ?? IntuneConstants.DefaultOfflineWipeTimeout;
            this.Description = this.Description ?? string.Format(CultureInfo.CurrentCulture, Resources.NewResource, Resources.IosPolicy);
        }

        /// <summary>
        /// Verify that numeric parameters are non negative
        /// </summary>
        private void ValidateNumericParameters()
        {
            NumericParameterValueChecker.CheckIfNegativeAndThrowException(
                new System.Collections.Generic.Dictionary<string, int>
                {
                    {IntuneConstants.PinNumRetryProperty, PinNumRetry.Value},
                    {IntuneConstants.AccessRecheckOfflineTimeoutProperty, this.AccessRecheckOfflineTimeout.Value},
                    {IntuneConstants.AccessRecheckOnlineTimeoutProperty, this.AccessRecheckOnlineTimeout.Value},
                    {IntuneConstants.OfflineWipeTimeoutProperty, this.OfflineWipeTimeout.Value }
                });
        }

        /// <summary>
        /// Prepares iOS Policy body for the new policy request
        /// </summary>
        /// <returns>policy request body</returns>
        private IOSMAMPolicy PrepareIOSPolicyBody()
        {
            var policyBody = new IOSMAMPolicy() {
                FriendlyName = this.FriendlyName,
                Description = this.Description,
                AppSharingFromLevel = this.AppSharingFromLevel.ToString(),
                AppSharingToLevel = this.AppSharingToLevel.ToString(),
                Authentication = this.Authentication.ToString(),
                ClipboardSharingLevel = this.ClipboardSharingLevel.ToString(),
                DataBackup = this.DataBackup.ToString(),
                FileSharingSaveAs = this.FileSharingSaveAs.ToString(),
                Pin = this.Pin.ToString(),
                PinNumRetry = this.PinNumRetry,
                DeviceCompliance = this.DeviceCompliance.ToString(),
                ManagedBrowser = this.ManagedBrowser.ToString(),
                AccessRecheckOfflineTimeout = TimeSpan.FromMinutes(this.AccessRecheckOfflineTimeout.Value),
                AccessRecheckOnlineTimeout = TimeSpan.FromMinutes(this.AccessRecheckOnlineTimeout.Value),
                OfflineWipeTimeout = TimeSpan.FromDays(this.OfflineWipeTimeout.Value),
                FileEncryptionLevel = this.FileEncryptionLevel.ToString(),
                TouchId = this.TouchId.ToString()
            };

            return policyBody;
        }
    }
}


text:
skrollr-wormholes
=================

Autoscroll through some content using skrollr


text:
#ifndef PORTMACRO_H
#define PORTMACRO_H

/*-----------------------------------------------------------
 * Port specific definitions.
 *
 * The settings in this file configure FreeRTOS correctly for the
 * given hardware and compiler.
 *
 * These settings should not be altered.
 *-----------------------------------------------------------
 */

/* Type definitions. */
#define portCHAR		char
#define portFLOAT		float
#define portDOUBLE		double
#define portLONG		long
#define portSHORT		int
#define portSTACK_TYPE	uint8_t
#define portBASE_TYPE	char

typedef portSTACK_TYPE StackType_t;
typedef signed char BaseType_t;
typedef unsigned char UBaseType_t;

#if( configUSE_16_BIT_TICKS == 1 )
	typedef uint16_t TickType_t;
	#define portMAX_DELAY ( TickType_t ) 0xffff
#else
	typedef uint32_t TickType_t;
	#define portMAX_DELAY ( TickType_t ) 0xffffffffUL
#endif
/*-----------------------------------------------------------*/

/* Hardware specifics. */
#define portBYTE_ALIGNMENT			1
#define portGLOBAL_INT_ENABLE_BIT	0x80
#define portSTACK_GROWTH			1
#define portTICK_PERIOD_MS			( ( TickType_t ) 1000 / configTICK_RATE_HZ )
/*-----------------------------------------------------------*/

/* Critical section management. */
#define portDISABLE_INTERRUPTS()	INTCONbits.GIEH = 0;
#define portENABLE_INTERRUPTS()		INTCONbits.GIEH = 1;

/* Push the INTCON register onto the stack, then disable interrupts. */
#define portENTER_CRITICAL()		POSTINC1 = INTCON;				\
									INTCONbits.GIEH = 0;

/* Retrieve the INTCON register from the stack, and enable interrupts
if they were saved as being enabled.  Don't modify any other bits
within the INTCON register as these may have lagitimately have been
modified within the critical region. */
#define portEXIT_CRITICAL()			_asm									\
										MOVF	POSTDEC1, 1, 0				\
									_endasm									\
									if( INDF1 & portGLOBAL_INT_ENABLE_BIT )	\
									{										\
										portENABLE_INTERRUPTS();			\
									}
/*-----------------------------------------------------------*/

/* Task utilities. */
extern void vPortYield( void );
#define portYIELD()				vPortYield()
/*-----------------------------------------------------------*/

/* Task function macros as described on the FreeRTOS.org WEB site. */
#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters )
#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters )
/*-----------------------------------------------------------*/

/* Required by the kernel aware debugger. */
#ifdef __DEBUG
	#define portREMOVE_STATIC_QUALIFIER
#endif

#define portNOP()				_asm	\
									NOP \
								_endasm

#endif /* PORTMACRO_H */


text:
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import CircularProgress from '@material-ui/core/CircularProgress';

const styles = theme => ({
  progress: {
    margin: theme.spacing.unit * 2,
  },
});

function CircularIndeterminate(props) {
  const { classes } = props;
  return (
    <div>
      <CircularProgress className={classes.progress} />
      <CircularProgress className={classes.progress} color="secondary" />
    </div>
  );
}

CircularIndeterminate.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(CircularIndeterminate);


text:
![Powered by Gophers](http://i.imgur.com/SwkPj.png "Powered by Gophers")

This repo contains code that connects via SSH and does stuff. Ideally this would turn into a
[Fabric](http://docs.fabfile.org/en/1.6/)-like library for Go.

## Resources

Some files that help during implementation.

* [client\_auth.go](https://code.google.com/p/go/source/browse/ssh/client_auth.go?repo=crypto)
* [client\_auth\_test.go](https://code.google.com/p/go/source/browse/ssh/client_auth_test.go?repo=crypto)
* [openpgp](https://code.google.com/p/go/source/browse?repo=crypto#hg%2Fopenpgp)
* [openpgp/packet/encrypted\_key.go](https://code.google.com/p/go/source/browse/openpgp/packet/encrypted_key.go?repo=crypto)
* [openpgp/packet/encrypted\_key\_test.go](https://code.google.com/p/go/source/browse/openpgp/packet/encrypted_key_test.go?repo=crypto)

## License

This code is released under the MIT license. See `LICENSE.md` for details.


text:
class ApplicationController < ActionController::Base
  include Learnery::ViewPathHelper

  before_filter :prepend_dummy_path
end

module Learnery
  class ApplicationController < ActionController::Base

    include Learnery::ApplicationHelper
    include Learnery::AuthenticationHelper
    include Learnery::RsvpHelper
    include Learnery::ViewPathHelper
    # Prevent CSRF attacks by raising an exception.
    # For APIs, you may want to use :null_session instead.
    protect_from_forgery with: :exception

    before_filter :prepend_dummy_path
  end
end


text:
package me.j360.rpc.client;

import com.google.common.collect.Lists;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;
import me.j360.rpc.client.handler.RPCClientHandler;
import me.j360.rpc.codec.protostuff.RpcDecoder;
import me.j360.rpc.codec.protostuff.RpcEncoder;
import me.j360.rpc.codec.protostuff.RpcRequest;
import me.j360.rpc.codec.protostuff.RpcResponse;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * Package: me.j360.rpc.client
 * User: min_xu
 * Date: 2017/5/23 下午1:25
 * 说明:单例类
 */

@Slf4j
public class RPCConnectManager {

    private RPCClientOption rpcClientOption;

    /**
     * 因为该rpc只使用单个协议作为传输,所以只需要定义一个Client实例
     * 服务集合内存表,根据依赖的多个服务,一个服务有多个实例
     */
    private static ConcurrentHashMap<String,List<InetSocketAddress>> providerMap = new ConcurrentHashMap<>();
    private static ConcurrentHashMap<InetSocketAddress,Channel> channelMap = new ConcurrentHashMap<>();

    private volatile static RPCConnectManager rpcConnectManager;

    private CountDownLatch latch = new CountDownLatch(1);
    private RPCConnectManager(RPCClientOption rpcClientOption) {
        this.rpcClientOption = rpcClientOption;
    }

    public static RPCConnectManager getInstance(RPCClientOption rpcClientOption) {
        if (rpcConnectManager == null) {
            synchronized (RPCConnectManager.class) {
                if (rpcConnectManager == null) {
                    rpcConnectManager = new RPCConnectManager(rpcClientOption);
                }
            }
        }

        return rpcConnectManager;
    }

    /**
     * 调用入口
     * @return
     */
    public Channel selectChannel(String interfaceName) {

        //选择,增加判断是否有已经注册并连接上的channel
        List<InetSocketAddress> list = providerMap.get(interfaceName);

        if (null == list) {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        InetSocketAddress address = select(list);

        return channelMap.get(address);
    }

    /**
     * 入口,添加服务远程连接
     */
    public void addNewConnection(String interfaceName, InetSocketAddress remoteAddress) {

        //需要去重判断
        if (!channelMap.containsKey(remoteAddress)) {
            Bootstrap bootstrap = newBootstrap();
            connect(bootstrap, remoteAddress, interfaceName);
        } else {
            Channel channel = channelMap.get(remoteAddress);
            if (!channel.isActive()) {

            }
        }
    }

    /**
     * 入口,删除服务远程连接
     */
    public void removeConnection(String interfaceName, InetSocketAddress remoteAddress) {

        //删除channel,删除服务列表
        Channel channel = channelMap.get(remoteAddress);
        if (null != channel) {
            close(channel);
        }

    }

    private void close(Channel channel) {
        channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    protected Bootstrap newBootstrap() {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, rpcClientOption.getConnectTimeoutMillis());
        bootstrap.option(ChannelOption.SO_KEEPALIVE, rpcClientOption.isKeepAlive());
        bootstrap.option(ChannelOption.SO_REUSEADDR, rpcClientOption.isReuseAddr());
        bootstrap.option(ChannelOption.TCP_NODELAY, rpcClientOption.isTcpNoDelay());
        bootstrap.option(ChannelOption.SO_RCVBUF, rpcClientOption.getReceiveBufferSize());
        bootstrap.option(ChannelOption.SO_SNDBUF, rpcClientOption.getSendBufferSize());

        ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
                channel.pipeline()
                        .addLast(new RpcEncoder(RpcRequest.class))
                        .addLast(new LengthFieldBasedFrameDecoder(65536,0,4,0,0))
                        .addLast(new RpcDecoder(RpcResponse.class))
                        .addLast(new RPCClientHandler());
            }
        };
        bootstrap.group(new NioEventLoopGroup()).handler(initializer);
        return bootstrap;
    }

    /**
     * 重连
     * @param channel
     * @param remoteAddress
     */
    private void reconnect(Channel channel, InetSocketAddress remoteAddress) {
        try {
            final ChannelFuture future = channel.connect(remoteAddress);
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {

                        //需要去重判断
                        channelMap.put(remoteAddress,channelFuture.channel());

                        log.debug("Connection {} is established", channelFuture.channel());
                    } else {
                        log.warn(String.format("Connection get failed on {} due to {}",
                                channelFuture.cause().getMessage(), channelFuture.cause()));
                    }
                }
            });
            future.awaitUninterruptibly();
            if (future.isSuccess()) {
                log.debug("connect {} success", remoteAddress.toString());

            } else {
                log.warn("connect {} failed", remoteAddress.toString());

            }
        } catch (Exception e) {
            log.error("failed to connect to {} due to {}", remoteAddress.toString(), e.getMessage());
        }
    }

    private Channel connect(Bootstrap bootstrap,InetSocketAddress remoteAddress, String interfaceName) {
        try {
            final ChannelFuture future = bootstrap.connect(remoteAddress);
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {

                        //需要去重判断
                        channelMap.put(remoteAddress,channelFuture.channel());

                        if (providerMap.containsKey(interfaceName)) {
                            providerMap.get(interfaceName).add(remoteAddress);
                        } else {
                            List<InetSocketAddress> list = Lists.newArrayList();
                            list.add(remoteAddress);
                            providerMap.put(interfaceName,list);
                        }

                        latch.countDown();
                        log.debug("Connection {} is established", channelFuture.channel());
                    } else {
                        log.warn(String.format("Connection get failed on {} due to {}",
                                channelFuture.cause().getMessage(), channelFuture.cause()));
                    }
                }
            });
            future.awaitUninterruptibly();
            if (future.isSuccess()) {
                log.debug("connect {} success", remoteAddress.toString());
                return future.channel();
            } else {
                log.warn("connect {} failed", remoteAddress.toString());
                return null;
            }
        } catch (Exception e) {
            log.error("failed to connect to {} due to {}", remoteAddress.toString(), e.getMessage(),e);
            return null;
        }
    }

    /**
     * 选择算法模拟方法
     * 轮训
     * 哈希
     * @return
     */
    private InetSocketAddress select(List<InetSocketAddress> list){
        return list.get(0);
    }
}


text:
* [A. Initial Bet][]
* [B. Random Teams][]

[A. Initial Bet]:  http://codeforces.com/contest/478/problem/A
[B. Random Teams]: http://codeforces.com/contest/478/problem/B


text:
import { Component, ChangeDetectionStrategy, Input } from '@angular/core';

import { Column } from '../../shared';

@Component({
    selector: 'adg-simple-renderer',
    templateUrl: './simple-renderer.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class SimpleRenderer {
    @Input() column: Column;
}


text:
<?php

return array(
	'hello' => 'Hello there :name!'
);


text:
<?php /** @noinspection PhpFullyQualifiedNameUsageInspection */
/** @noinspection SpellCheckingInspection */

/** @noinspection PhpUnused */

namespace ePHP\Http;

/**
 * Make a Http Request using swoole
 *
 * 修改至 https://github.com/dsyph3r/curl-php/blob/master/lib/Network/Curl/Curl.php
 */
class HttpclientSwoole extends Httpclient
{
    /**
     * Create the cURL resource.
     * @noinspection PhpMissingParentConstructorInspection
     */
    public function __construct()
    {
    }

    /**
     * Clean up the cURL handle.
     */
    public function __destruct()
    {
    }

    /**
     * Make a HTTP request.
     *
     * @param string $url
     * @param string $method
     * @param mixed  $params
     * @param array  $options
     *
     * @return HttpclientResponse
     */
    protected function request($url, $method = self::GET, $params = array(), $options = array())
    {
        $paths = parse_url($url);

        $host = $paths['host'];
        $is_ssl = isset($paths['scheme']) && $paths['scheme'] == 'https';
        $port = isset($paths['port']) ? $paths['port'] : ($is_ssl ? 443 : 80);

        $ip = \Swoole\Coroutine::gethostbyname($host);
        if ( !$ip ) {
            \throw_error('Coroutine::gethostbyname("'. $host .'") host is empty', 19220);
        }

        $cli = new \Swoole\Coroutine\Http\Client($ip, $port, $is_ssl);

        // 兼容httpclient的header头
        $headers = ['Host' => $host];
        if (isset($options['headers']) && count($options['headers'])) {
            foreach ($options['headers'] as $value) {
                $tmp = explode(':', $value);
                if (\count($tmp) > 1) {
                    $headers[ $tmp[0] ] = implode(':', array_slice($tmp, 1));
                }
            }
        }

        $uri = (isset($paths['path']) ? $paths['path'] : '/') . '?' . (isset($paths['query']) ? $paths['query'] : '');

        // Set request timeout
        $cli->set(['timeout' => isset($options['timeout']) ? $options['timeout'] * 1000 : 10e3 ]);

        // Support get, post
        if ( $method === self::GET ) {
            $uri .= '&' . http_build_query($params);
            $cli->setHeaders($headers);
            $cli->get( $uri );
        } else if ( $method === self::POST ) {
            if ( !empty($options['json']) ) {
                $params = json_encode($params, JSON_UNESCAPED_UNICODE);
                $headers['Content-type'] = 'application/json';
            }

            // Check for files
            if (isset($options['files']) && count($options['files'])) {
                foreach ($options['files'] as $index => $file) {
                    $cli->addFile($file, $index);
                }
            }

            $cli->setHeaders($headers);
            $cli->post( $uri, $params );
        } else {
            \throw_error('Unsupported method, only GET/POST', 18201);
        }

        // Close
        $cli->close();

        return new HttpclientResponse($cli->body, $cli->statusCode, $cli->getHeaders());
    }
}


text:
/****************************************************************************
 * include/tinyara/analog/adc.h
 *
 *   Copyright (C) 2016-2017 Gregory Nutt. All rights reserved.
 *   Copyright (C) 2011 Li Zhuoyi. All rights reserved.
 *   Author: Li Zhuoyi <lzyy.cn@gmail.com>
 *           Gregory Nutt <gnutt@nuttx.org>
 *
 * Derived from include/nuttx/drivers/can.h
 *
 *   Copyright (C) 2008, 2009 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#ifndef __INCLUDE_TINYARA_ANALOG_ADC_H
#define __INCLUDE_TINYARA_ANALOG_ADC_H

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <tinyara/config.h>
#include <tinyara/compiler.h>

#include <poll.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <semaphore.h>
#include <tinyara/fs/fs.h>
#include <tinyara/spi/spi.h>

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/*
 * Default configuration settings that may be overridden in the TinyARA
 * configuration file. The configured size is limited to 255 to fit into
 * a uint8_t.
 */

#if !defined(CONFIG_ADC_FIFOSIZE)
#define CONFIG_ADC_FIFOSIZE 8
#elif CONFIG_ADC_FIFOSIZE > 255
#undef  CONFIG_ADC_FIFOSIZE
#define CONFIG_ADC_FIFOSIZE 255
#endif

#if !defined(CONFIG_ADC_NPOLLWAITERS)
#define CONFIG_ADC_NPOLLWAITERS 2
#endif

#define ADC_RESET(dev)         ((dev)->ad_ops->ao_reset((dev)))
#define ADC_SETUP(dev)         ((dev)->ad_ops->ao_setup((dev)))
#define ADC_SHUTDOWN(dev)      ((dev)->ad_ops->ao_shutdown((dev)))
#define ADC_RXINT(dev)         ((dev)->ad_ops->ao_rxint((dev)))
#define ADC_IOCTL(dev, cmd, arg) ((dev)->ad_ops->ao_ioctl((dev), (cmd), (arg)))

/****************************************************************************
 * Public Types
 ****************************************************************************/
/* These are callbacks to notify the upper-half driver of ADC events */

struct adc_dev_s;
struct adc_callback_s {
	/*
	 * This method is called from the lower half, platform-specific ADC
	 * logic when new ADC sample data is available.
	 *
	 * Input Parameters:
	 *   dev  - The ADC device structure that was previously registered
	 *          by adc_register()
	 *   ch   - And ID for the ADC channel number that generated the data
	 *   data - The actual converted data from the channel.
	 *
	 * Returned Value:
	 *   Zero on success; a negated errno value on failure.
	 */

	CODE int (*au_receive)(FAR struct adc_dev_s *dev, uint8_t ch,
			       int32_t data);
};

/* This describes on ADC message */

struct adc_msg_s {
	uint8_t am_channel;	/* The 8-bit ADC Channel */
	int32_t am_data;	/* ADC convert result (4 bytes) */
} packed_struct;

/* This describes a FIFO of ADC messages */

struct adc_fifo_s {
	sem_t   af_sem;		/* Counting semaphore */
	uint8_t af_head;	/* Index to the head [IN] index in the circular buffer */
	uint8_t af_tail;	/* Index to the tail [OUT] index in the circular buffer */
	/* Circular buffer of CAN messages */
	struct  adc_msg_s af_buffer[CONFIG_ADC_FIFOSIZE];
};

/*
 * This structure defines all of the operations providd by the architecture
 * specific logic. All fields must be provided with non-NULL function pointers
 * by the caller of can_register().
 */

struct adc_dev_s;
struct adc_ops_s {
	/*
	 * Bind the upper-half driver callbacks to the lower-half
	 * implementation. This must be called early in order to receive ADC
	 * event notifications.
	 */

	CODE int (*ao_bind)(FAR struct adc_dev_s *dev,
			FAR const struct adc_callback_s *callback);

	/*
	 * Reset the ADC device.  Called early to initialize the hardware.
	 * This is called, before ao_setup() and on error conditions.
	 */

	CODE void (*ao_reset)(FAR struct adc_dev_s *dev);

	/*
	 * Configure the ADC. This method is called the first time that the
	 * ADC device is opened.  This will occur when the port is first
	 * opened. This setup includes configuring and attaching ADC
	 * interrupts. Interrupts are all disabled upon return.
	 */

	CODE int (*ao_setup)(FAR struct adc_dev_s *dev);

	/*
	 * Disable the ADC. This method is called when the ADC device is
	 * closed. This method reverses the operation the setup method.
	 */

	CODE void (*ao_shutdown)(FAR struct adc_dev_s *dev);

	/* Call to enable or disable RX interrupts */

	CODE void (*ao_rxint)(FAR struct adc_dev_s *dev, bool enable);

	/* All ioctl calls will be routed through this method */

	CODE int (*ao_ioctl)(FAR struct adc_dev_s *dev, int cmd, unsigned long arg);
};

/*
 * This is the device structure used by the driver.  The caller of
 * adc_register() must allocate and initialize this structure.  The calling
 * logic need only set all fields to zero except:
 *
 *   The elements of 'ad_ops', and 'ad_priv'
 *
 * The common logic will initialize all semaphores.
 */

struct adc_dev_s {
#ifdef CONFIG_ADC
	/* Fields managed by common upper half ADC logic */

	uint8_t           ad_ocount;     /* The number of times the device has been opened */
	uint8_t           ad_nrxwaiters; /* Number of threads waiting to enqueue a message */
	sem_t             ad_closesem;   /* Locks out new opens while close is in progress */
	sem_t             ad_recvsem;    /* Used to wakeup user waiting for space in ad_recv.buffer */
	struct adc_fifo_s ad_recv;       /* Describes receive FIFO */
  /* The following is a list of poll structures of threads waiting for
   * driver events. The 'struct pollfd' reference for each open is also
   * retained in the f_priv field of the 'struct file'.
   */

#if !defined(CONFIG_DISABLE_POLL)
	struct pollfd *fds[CONFIG_ADC_NPOLLWAITERS];
#endif

#endif /* CONFIG_ADC */

	/* Fields provided by lower half ADC logic */

	FAR const struct adc_ops_s *ad_ops;  /* Arch-specific operations */
	FAR void                   *ad_priv; /* Used by the arch-specific logic */
};

/****************************************************************************
 * Public Function Prototypes
 ****************************************************************************/

#if defined(__cplusplus)
extern "C"
{
#endif

/****************************************************************************
 * "Upper-Half" ADC Driver Interfaces
 ****************************************************************************/

/****************************************************************************
 * Name: adc_register
 *
 * Description:
 *   Register a ADC driver. This function binds an instance of a "lower half"
 *   ADC driver with the "upper half" ADC device and registers that device so
 *   that can be used by application code.
 *
 * Input parameters:
 *   path - The full path to the driver to be registers in the TinyARA
 *     pseudo-filesystem. The recommended convention is to name all PWM
 *     drivers as "/dev/adc", "/dev/adc1", etc.  where the driver path differs
 *     only in the "minor" number at the end of the device name.
 *   dev - A pointer to an instance of lower half ADC driver.  This instance
 *     is bound to the upper half ADC driver and must persists as long as the
 *     upper half driver driver persists.
 *
 * Returned Value:
 *   Zero on success; a negated errno value on failure.
 *
 ****************************************************************************/

int adc_register(FAR const char *path, FAR struct adc_dev_s *dev);

/****************************************************************************
 * Platform-Independent "Lower Half" ADC Driver Interfaces
 ****************************************************************************/

/****************************************************************************
 * Name: up_ads1255initialize
 *
 * Description:
 *   Initialize the TI ADS 125X lower half driver
 *
 ****************************************************************************/

FAR struct adc_dev_s *up_ads1255initialize(FAR struct spi_dev_s *spi,
		unsigned int devno);

#if defined(__cplusplus)
}
#endif

#endif /* __INCLUDE_TINYARA_ANALOG_ADC_H */


text:
<!DOCTYPE HTML>

<title>Uses of Class com.google.ortools.linearsolver.MPSolverCommonParameters.Builder (com.google.ortools:ortools-java 9.4.1874 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Uses of Class
com.google.ortools.linearsolver.MPSolverCommonParameters.Builder

Packages that use MPSolverCommonParameters.Builder

Package
Description

com.google.ortools.linearsolver

Uses of MPSolverCommonParameters.Builder in com.google.ortools.linearsolver

Methods in com.google.ortools.linearsolver that return MPSolverCommonParameters.Builder

Modifier and Type
Method
Description

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,
                java.lang.Object value)

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.clear()

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.clearDualTolerance()

 Tolerance for dual feasibility.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.clearField(com.google.protobuf.Descriptors.FieldDescriptor field)

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.clearLpAlgorithm()

 Algorithm to solve linear programs.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof)

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.clearPresolve()

 Gurobi and SCIP enable presolve by default.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.clearPrimalTolerance()

 Tolerance for primal feasibility of basic solutions: this is the maximum
 allowed error in constraint satisfiability.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.clearRelativeMipGap()

 The solver stops if the relative MIP gap reaches this value or below.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.clearScaling()

 Enable automatic scaling of matrix coefficients and objective.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.clone()

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.mergeDualTolerance(OptionalDouble value)

 Tolerance for dual feasibility.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.mergeFrom(MPSolverCommonParameters other)

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.mergeFrom(com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.mergeFrom(com.google.protobuf.Message other)

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.mergePrimalTolerance(OptionalDouble value)

 Tolerance for primal feasibility of basic solutions: this is the maximum
 allowed error in constraint satisfiability.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.mergeRelativeMipGap(OptionalDouble value)

 The solver stops if the relative MIP gap reaches this value or below.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.mergeUnknownFields(com.google.protobuf.UnknownFieldSet unknownFields)

static MPSolverCommonParameters.Builder
MPSolverCommonParameters.newBuilder()

static MPSolverCommonParameters.Builder
MPSolverCommonParameters.newBuilder(MPSolverCommonParameters prototype)

MPSolverCommonParameters.Builder
MPSolverCommonParameters.newBuilderForType()

protected MPSolverCommonParameters.Builder
MPSolverCommonParameters.newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent)

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.setDualTolerance(OptionalDouble value)

 Tolerance for dual feasibility.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.setDualTolerance(OptionalDouble.Builder builderForValue)

 Tolerance for dual feasibility.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.setField(com.google.protobuf.Descriptors.FieldDescriptor field,
        java.lang.Object value)

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.setLpAlgorithm(MPSolverCommonParameters.LPAlgorithmValues value)

 Algorithm to solve linear programs.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.setPresolve(OptionalBoolean value)

 Gurobi and SCIP enable presolve by default.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.setPrimalTolerance(OptionalDouble value)

 Tolerance for primal feasibility of basic solutions: this is the maximum
 allowed error in constraint satisfiability.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.setPrimalTolerance(OptionalDouble.Builder builderForValue)

 Tolerance for primal feasibility of basic solutions: this is the maximum
 allowed error in constraint satisfiability.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.setRelativeMipGap(OptionalDouble value)

 The solver stops if the relative MIP gap reaches this value or below.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.setRelativeMipGap(OptionalDouble.Builder builderForValue)

 The solver stops if the relative MIP gap reaches this value or below.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,
                int index,
                java.lang.Object value)

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.setScaling(OptionalBoolean value)

 Enable automatic scaling of matrix coefficients and objective.

MPSolverCommonParameters.Builder
MPSolverCommonParameters.Builder.setUnknownFields(com.google.protobuf.UnknownFieldSet unknownFields)

MPSolverCommonParameters.Builder
MPSolverCommonParameters.toBuilder()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Copyright © 2022. All rights reserved.


text:
(function() {

var instance = openerp;
openerp.web.formats = {};

var _t = instance.web._t;

/**
 * Intersperses ``separator`` in ``str`` at the positions indicated by
 * ``indices``.
 *
 * ``indices`` is an array of relative offsets (from the previous insertion
 * position, starting from the end of the string) at which to insert
 * ``separator``.
 *
 * There are two special values:
 *
 * ``-1``
 *   indicates the insertion should end now
 * ``0``
 *   indicates that the previous section pattern should be repeated (until all
 *   of ``str`` is consumed)
 *
 * @param {String} str
 * @param {Array<Number>} indices
 * @param {String} separator
 * @returns {String}
 */
instance.web.intersperse = function (str, indices, separator) {
    separator = separator || '';
    var result = [], last = str.length;

    for(var i=0; i<indices.length; ++i) {
        var section = indices[i];
        if (section === -1 || last <= 0) {
            // Done with string, or -1 (stops formatting string)
            break;
        } else if(section === 0 && i === 0) {
            // repeats previous section, which there is none => stop
            break;
        } else if (section === 0) {
            // repeat previous section forever
            //noinspection AssignmentToForLoopParameterJS
            section = indices[--i];
        }
        result.push(str.substring(last-section, last));
        last -= section;
    }

    var s = str.substring(0, last);
    if (s) { result.push(s); }
    return result.reverse().join(separator);
};
/**
 * Insert "thousands" separators in the provided number (which is actually
 * a string)
 *
 * @param {String} num
 * @returns {String}
 */
instance.web.insert_thousand_seps = function (num) {
    var negative = num[0] === '-';
    num = (negative ? num.slice(1) : num);
    return (negative ? '-' : '') + instance.web.intersperse(
        num, _t.database.parameters.grouping, _t.database.parameters.thousands_sep);
};

/**
 * removes literal (non-format) text from a date or time pattern, as datejs can
 * not deal with literal text in format strings (whatever the format), whereas
 * strftime allows for literal characters
 *
 * @param {String} value original format
 */
instance.web.strip_raw_chars = function (value) {
    var isletter = /[a-zA-Z]/, output = [];
    for(var index=0; index < value.length; ++index) {
        var character = value[index];
        if(isletter.test(character) && (index === 0 || value[index-1] !== '%')) {
            continue;
        }
        output.push(character);
    }
    return output.join('');
};
var normalize_format = function (format) {
    return Date.normalizeFormat(instance.web.strip_raw_chars(format));
};

/**
 * Check with a scary heuristic if the value is a bin_size or not.
 * If not, compute an approximate size out of the base64 encoded string.
 *
 * @param {String} value original format
 */
instance.web.binary_to_binsize = function (value) {
    if (!value) {
        return instance.web.human_size(0);
    }
    if (value.substr(0, 10).indexOf(' ') == -1) {
        // Computing approximate size out of base64 encoded string
        // http://en.wikipedia.org/wiki/Base64#MIME
        return instance.web.human_size(value.length / 1.37);
    } else {
        // already bin_size
        return value;
    }
};

/**
 * Returns a human readable size
 *
 * @param {Number} numner of bytes
 */
instance.web.human_size = function(size) {
    var units = _t("Bytes,Kb,Mb,Gb,Tb,Pb,Eb,Zb,Yb").split(',');
    var i = 0;
    while (size >= 1024) {
        size /= 1024;
        ++i;
    }
    return size.toFixed(2) + ' ' + units[i];
};

/**
 * Formats a single atomic value based on a field descriptor
 *
 * @param {Object} value read from OpenERP
 * @param {Object} descriptor union of orm field and view field
 * @param {Object} [descriptor.widget] widget to use to display the value
 * @param {Object} descriptor.type fallback if no widget is provided, or if the provided widget is unknown
 * @param {Object} [descriptor.digits] used for the formatting of floats
 * @param {String} [value_if_empty=''] returned if the ``value`` argument is considered empty
 */
instance.web.format_value = function (value, descriptor, value_if_empty) {
    // If NaN value, display as with a `false` (empty cell)
    if (typeof value === 'number' && isNaN(value)) {
        value = false;
    }
    //noinspection FallthroughInSwitchStatementJS
    switch (value) {
        case '':
            if (descriptor.type === 'char' || descriptor.type === 'text') {
                return '';
            }
            console.warn('Field', descriptor, 'had an empty string as value, treating as false...');
            return value_if_empty === undefined ?  '' : value_if_empty;
        case false:
        case undefined:
        case Infinity:
        case -Infinity:
            return value_if_empty === undefined ?  '' : value_if_empty;
    }
    var l10n = _t.database.parameters;
    switch (descriptor.widget || descriptor.type || (descriptor.field && descriptor.field.type)) {
        case 'id':
            return value.toString();
        case 'integer':
            return instance.web.insert_thousand_seps(
                _.str.sprintf('%d', value));
        case 'float':
            var digits = descriptor.digits ? descriptor.digits : [69,2];
            digits = typeof digits === "string" ? py.eval(digits) : digits;
            var precision = digits[1];
            var formatted = _.str.sprintf('%.' + precision + 'f', value).split('.');
            formatted[0] = instance.web.insert_thousand_seps(formatted[0]);
            return formatted.join(l10n.decimal_point);
        case 'float_time':
            var pattern = '%02d:%02d';
            if (value < 0) {
                value = Math.abs(value);
                pattern = '-' + pattern;
            }
            var hour = Math.floor(value);
            var min = Math.round((value % 1) * 60);
            if (min == 60){
                min = 0;
                hour = hour + 1;
            }
            return _.str.sprintf(pattern, hour, min);
        case 'many2one':
            // name_get value format
            return value[1] ? value[1].split("\n")[0] : value[1];
        case 'one2many':
        case 'many2many':
            if (typeof value === 'string') {
                return value;
            }
            return _.str.sprintf(_t("(%d records)"), value.length);
        case 'datetime':
            if (typeof(value) == "string")
                value = instance.web.auto_str_to_date(value);

            return value.toString(normalize_format(l10n.date_format)
                        + ' ' + normalize_format(l10n.time_format));
        case 'date':
            if (typeof(value) == "string")
                value = instance.web.auto_str_to_date(value);
            return value.toString(normalize_format(l10n.date_format));
        case 'time':
            if (typeof(value) == "string")
                value = instance.web.auto_str_to_date(value);
            return value.toString(normalize_format(l10n.time_format));
        case 'selection': case 'statusbar':
            // Each choice is [value, label]
            if(_.isArray(value)) {
                 return value[1];
            }
            var result = _(descriptor.selection).detect(function (choice) {
                return choice[0] === value;
            });
            if (result) { return result[1]; }
            return;
        default:
            return value;
    }
};

instance.web.parse_value = function (value, descriptor, value_if_empty) {
    var date_pattern = normalize_format(_t.database.parameters.date_format),
        time_pattern = normalize_format(_t.database.parameters.time_format);
    switch (value) {
        case false:
        case "":
            return value_if_empty === undefined ?  false : value_if_empty;
    }
    var tmp;
    switch (descriptor.widget || descriptor.type || (descriptor.field && descriptor.field.type)) {
        case 'integer':
            do {
                tmp = value;
                value = value.replace(instance.web._t.database.parameters.thousands_sep, "");
            } while(tmp !== value);
            tmp = Number(value);
            // do not accept not numbers or float values
            if (isNaN(tmp) || tmp % 1)
                throw new Error(_.str.sprintf(_t("'%s' is not a correct integer"), value));
            return tmp;
        case 'float':
            var tmp2 = value;
            do {
                tmp = tmp2;
                tmp2 = tmp.replace(instance.web._t.database.parameters.thousands_sep, "");
            } while(tmp !== tmp2);
            var reformatted_value = tmp.replace(instance.web._t.database.parameters.decimal_point, ".");
            var parsed = Number(reformatted_value);
            if (isNaN(parsed))
                throw new Error(_.str.sprintf(_t("'%s' is not a correct float"), value));
            return parsed;
        case 'float_time':
            var factor = 1;
            if (value[0] === '-') {
                value = value.slice(1);
                factor = -1;
            }
            var float_time_pair = value.split(":");
            if (float_time_pair.length != 2)
                return factor * instance.web.parse_value(value, {type: "float"});
            var hours = instance.web.parse_value(float_time_pair[0], {type: "integer"});
            var minutes = instance.web.parse_value(float_time_pair[1], {type: "integer"});
            return factor * (hours + (minutes / 60));
        case 'progressbar':
            return instance.web.parse_value(value, {type: "float"});
        case 'datetime':
            var datetime = Date.parseExact(
                    value, (date_pattern + ' ' + time_pattern));
            if (datetime !== null)
                return instance.web.datetime_to_str(datetime);
            datetime = Date.parseExact(value, (date_pattern));
            if (datetime !== null)
                return instance.web.datetime_to_str(datetime);
            var leading_zero_value = value.toString().replace(/\d+/g, function(m){
                return m.length === 1 ? "0" + m : m ;
            });
            datetime = Date.parseExact(leading_zero_value, (date_pattern + ' ' + time_pattern));
            if (datetime !== null)
                return instance.web.datetime_to_str(datetime);
            datetime = Date.parseExact(leading_zero_value, (date_pattern));
            if (datetime !== null)
                return instance.web.datetime_to_str(datetime);
            datetime = Date.parse(value);
            if (datetime !== null)
                return instance.web.datetime_to_str(datetime);
            throw new Error(_.str.sprintf(_t("'%s' is not a correct datetime"), value));
        case 'date':
            var date = Date.parseExact(value, date_pattern);
            if (date !== null)
                return instance.web.date_to_str(date);
            date = Date.parseExact(value.toString().replace(/\d+/g, function(m){
                return m.length === 1 ? "0" + m : m ;
            }), date_pattern);
            if (date !== null)
                return instance.web.date_to_str(date);
            date = Date.parse(value);
            if (date !== null)
                return instance.web.date_to_str(date);
            throw new Error(_.str.sprintf(_t("'%s' is not a correct date"), value));
        case 'time':
            var time = Date.parseExact(value, time_pattern);
            if (time !== null)
                return instance.web.time_to_str(time);
            time = Date.parse(value);
            if (time !== null)
                return instance.web.time_to_str(time);
            throw new Error(_.str.sprintf(_t("'%s' is not a correct time"), value));
    }
    return value;
};

instance.web.auto_str_to_date = function(value, type) {
    try {
        return instance.web.str_to_datetime(value);
    } catch(e) {}
    try {
        return instance.web.str_to_date(value);
    } catch(e) {}
    try {
        return instance.web.str_to_time(value);
    } catch(e) {}
    throw new Error(_.str.sprintf(_t("'%s' is not a correct date, datetime nor time"), value));
};

instance.web.auto_date_to_str = function(value, type) {
    switch(type) {
        case 'datetime':
            return instance.web.datetime_to_str(value);
        case 'date':
            return instance.web.date_to_str(value);
        case 'time':
            return instance.web.time_to_str(value);
        default:
            throw new Error(_.str.sprintf(_t("'%s' is not convertible to date, datetime nor time"), type));
    }
};

/**
 * performs a half up rounding with arbitrary precision, correcting for float loss of precision
 * See the corresponding float_round() in server/tools/float_utils.py for more info
 * @param {Number} the value to be rounded
 * @param {Number} a precision parameter. eg: 0.01 rounds to two digits.
 */
instance.web.round_precision = function(value, precision){
    if (!value) {
        return 0;
    } else if (!precision || precision < 0) {
        precision = 1;
    }
    var normalized_value = value / precision;
    var epsilon_magnitude = Math.log(Math.abs(normalized_value))/Math.log(2);
    var epsilon = Math.pow(2, epsilon_magnitude - 53);
    normalized_value += normalized_value >= 0 ? epsilon : -epsilon;

    /**
     * Javascript performs strictly the round half up method, which is asymmetric. However, in
     * Python, the method is symmetric. For example:
     * - In JS, Math.round(-0.5) is equal to -0.
     * - In Python, round(-0.5) is equal to -1.
     * We want to keep the Python behavior for consistency.
     */
    var sign = normalized_value < 0 ? -1.0 : 1.0;
    var rounded_value = sign * Math.round(Math.abs(normalized_value));
    return rounded_value * precision;
};

/**
 * performs a half up rounding with a fixed amount of decimals, correcting for float loss of precision
 * See the corresponding float_round() in server/tools/float_utils.py for more info
 * @param {Number} the value to be rounded
 * @param {Number} the number of decimals. eg: round_decimals(3.141592,2) -> 3.14
 */
instance.web.round_decimals = function(value, decimals){
    return instance.web.round_precision(value, Math.pow(10,-decimals));
};

instance.web.float_is_zero = function(value, decimals){
    epsilon = Math.pow(10, -decimals);
    return Math.abs(instance.web.round_precision(value, epsilon)) < epsilon;
};

})();


text:
package ee.telekom.workflow.web.console;

import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import ee.telekom.workflow.core.common.WorkflowEngineConfiguration;
import ee.telekom.workflow.facade.WorkflowEngineFacade;
import ee.telekom.workflow.facade.model.CreateWorkflowInstance;
import ee.telekom.workflow.util.JsonUtil;
import ee.telekom.workflow.web.console.form.BatchCreateWorkflowInstancesForm;
import ee.telekom.workflow.web.console.form.CreateWorkflowInstanceForm;

/**
 * Web controller for starting one or multiple workflow instances based on the user input data.
 */
@Controller
@RequestMapping("/console")
public class WorkflowInstanceCreateController{

    private static final Logger log = LoggerFactory.getLogger( MethodHandles.lookup().lookupClass() );

    @Autowired
    private WorkflowEngineConfiguration configuration;
    @Autowired
    private WorkflowEngineFacade facade;

    @RequestMapping(method = RequestMethod.GET, value = "/workflow/create")
    public String viewStart( Model model ){
        model.addAttribute( "workflowNames", facade.getDeployedWorkflowNames() );
        return "console/workflow/create";
    }

    @PreAuthorize("hasRole('ROLE_TWE_ADMIN')")
    @RequestMapping(method = RequestMethod.POST, value = "/workflow/create")
    public String create( RedirectAttributes model, @ModelAttribute("form") CreateWorkflowInstanceForm form, Errors result ){
        model.addFlashAttribute( "form", form );
        // XXX Errors object was never intended to be put into flash/session for POST-REDIRECT-GET: https://jira.spring.io/browse/SPR-8282
        model.addFlashAttribute( "org.springframework.validation.BindingResult.form", result );

        Integer version = null;
        Map<String, Object> arguments = null;
        if( StringUtils.isBlank( form.getWorkflowName() ) ){
            result.rejectValue( "workflowName", "workflow.create.single.error.workflowname" );
        }
        if( !StringUtils.isBlank( form.getWorkflowVersion() ) && !NumberUtils.isNumber( form.getWorkflowVersion() ) ){
            result.rejectValue( "workflowVersion", "workflow.create.single.error.workflowversion" );
        }
        else{
            version = StringUtils.isBlank( form.getWorkflowVersion() ) ? null : Integer.valueOf( form.getWorkflowVersion() );
        }
        try{
            arguments = JsonUtil.deserializeHashMap( form.getArguments(), String.class, Object.class );
        }
        catch( Exception e ){
            log.info( e.getMessage(), e );
            result.rejectValue( "arguments", "workflow.create.single.error.arguments" );
        }

        if( !result.hasErrors() ){
            try{
                CreateWorkflowInstance request = new CreateWorkflowInstance();
                request.setWorkflowName( form.getWorkflowName() );
                request.setWorkflowVersion( version );
                request.setLabel1( form.getLabel1() );
                request.setLabel2( form.getLabel2() );
                request.setArguments( arguments );
                facade.createWorkflowInstance( request );
                form.setRefNum( request.getRefNum() );
            }
            catch( Exception e ){
                model.addFlashAttribute( "error", e.getMessage() );
                log.error( e.getMessage(), e );
            }
        }
        return "redirect:" + configuration.getConsoleMappingPrefix() + "/console/workflow/create";
    }

    @PreAuthorize("hasRole('ROLE_TWE_ADMIN')")
    @RequestMapping(method = RequestMethod.POST, value = "/workflow/batchCreate")
    public String batchCreate( RedirectAttributes model, @ModelAttribute("batchForm") BatchCreateWorkflowInstancesForm batchForm, Errors result ){
        model.addFlashAttribute( "batchForm", batchForm );
        // XXX Errors object was never intended to be put into flash/session for POST-REDIRECT-GET: https://jira.spring.io/browse/SPR-8282
        model.addFlashAttribute( "org.springframework.validation.BindingResult.batchForm", result );

        List<CreateWorkflowInstance> requests = null;

        try{
            if( StringUtils.isNotBlank( batchForm.getBatchRequest() ) ){
                requests = (List<CreateWorkflowInstance>)JsonUtil.deserializeCollection( batchForm.getBatchRequest(), ArrayList.class, CreateWorkflowInstance.class );
            }
            if( requests == null || requests.isEmpty() ){
                result.rejectValue( "batchRequest", "workflow.create.batch.error.empty" );
            }
        }
        catch( Exception e ){
            log.info( e.getMessage(), e );
            result.rejectValue( "batchRequest", "workflow.create.batch.error.syntax" );
        }

        if( !result.hasErrors() ){
            Set<String> deployedWorkflowNames = facade.getDeployedWorkflowNames();
            for( CreateWorkflowInstance element : requests ){
                if( StringUtils.isBlank( element.getWorkflowName() ) || !deployedWorkflowNames.contains( element.getWorkflowName() ) ){
                    result.rejectValue( "batchRequest", "workflow.create.batch.error.workflowname" );
                    break;
                }
            }
        }

        if( !result.hasErrors() ){
            try{
                facade.createWorkflowInstances( requests );
                batchForm.setRefNums( getRefNums( requests ) );

            }
            catch( Exception e ){
                model.addFlashAttribute( "error", e.getMessage() );
                log.error( e.getMessage(), e );
            }
        }

        return "redirect:" + configuration.getConsoleMappingPrefix() + "/console/workflow/create";
    }

    private List<Long> getRefNums( List<CreateWorkflowInstance> requests ){
        List<Long> result = new ArrayList<>( requests.size() );
        for( CreateWorkflowInstance request : requests ){
            result.add( request.getRefNum() );
        }
        return result;
    }

    @ModelAttribute("form")
    public CreateWorkflowInstanceForm createSingleModel(){
        return new CreateWorkflowInstanceForm();
    }

    @ModelAttribute("batchForm")
    public BatchCreateWorkflowInstancesForm createBatchModel(){
        return new BatchCreateWorkflowInstancesForm();
    }

}


text:
package commands

import "github.com/if1live/kanae/kanaelib"

type Dev struct {
	settings kanaelib.Settings
}

func NewDev(s kanaelib.Settings) *Dev {
	return &Dev{
		settings: s,
	}
}

func (cmd *Dev) Execute() error {
	/*
		db, err := histories.NewDatabase(cmd.settings.DatabaseFileName)
		if err != nil {
			return nil
		}

		view := db.MakeTradeView()
		assets := view.UsedAssets("BTC")
		fmt.Println("used assets :", assets)
	*/

	//rows := db.GetLendings("BTC")
	//fmt.Println(rows)

	/*
		exchange := s.PoloniexExchange()
		db, err := histories.NewDatabase("histories.db", exchange)

		// get all
		rows := db.AllTrades("DOGE", "BTC")
		fmt.Println(rows)
	*/

	//if len(rows) == 0 {
	//rowcount, err := db.LoadFromExchange("all")
	//if err != nil {
	//	check(err)
	//}
	//fmt.Printf("%d row added\n", rowcount)
	//}
	return nil
}


text:
import React from 'react';
import { List } from 'immutable';
import { Link } from 'react-router';

import moment from 'moment';

import PropTypes from 'prop-types';

import Tooltip from 'rc-tooltip';
import 'rc-tooltip/assets/bootstrap.css';

import ReadMoreMarkdown from 'components/markdown/read-more';
import TagList from 'components/taglist';

import { paperPropType } from 'utils/constants';

import './row.scss';

const extractAbstract = (text) => {
  const stops = ['#', '\n'];
  let end = text.length;
  stops.forEach((stop) => {
    const i = text.indexOf(stop);
    if (i > 0 && i < end) {
      end = i;
    }
  });

  return text.substring(0, end);
};

const ImportButtonOrLink = ({ paperID, onImport }) => {
  if (paperID !== 0) {
    return (
      <Link
        className="btn btn-sm btn-outline-primary"
        to={`papers/${paperID}`}
      >
        See on Papernet
      </Link>
    );
  }

  return (
    <button className="btn btn-sm btn-primary" onClick={onImport}>
      Import in Papernet
    </button>
  );
};

ImportButtonOrLink.propTypes = {
  paperID: PropTypes.number.isRequired,
  onImport: PropTypes.func.isRequired,
};

const ImportRow = ({ onImport, paper }) => {
  const abstract = extractAbstract(paper.get('summary'));

  const tags = paper.get('tags') || List();

  return (

{paper.get('title')}

        <ReadMoreMarkdown text={abstract} />

          <ImportButtonOrLink paperID={paper.get('id')} onImport={onImport} />

            See on arXiv

            PDF

            <Tooltip
              placement="bottom"
              mouseEnterDelay={0.3}
              overlay={{moment(paper.get('updatedAt')).format('LLL')}}
            >
              Modified {moment(paper.get('updatedAt')).fromNow()}
            </Tooltip>

          <TagList tags={tags} max={5} />

  );
};

ImportRow.propTypes = {
  onImport: PropTypes.func.isRequired,
  paper: paperPropType.isRequired,
};

export default ImportRow;