text:
/*
 * Argument decode
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */
#include <am_defs.h>
#include <amd.h>

/* include auto-generated version file */
#include <build_version.h>

char *amu_conf_file = "/etc/amd.conf"; /* default amd configuration file */
char *conf_tag = NULL;		/* default conf file tags to use */
int usage = 0;
int use_conf_file = 0;		/* default don't use amd.conf file */
char *mnttab_file_name = NULL;	/* symbol must be available always */

/*
 * Return the version string (dynamic buffer)
 */
char *
get_version_string(void)
{
  char *vers = NULL;
  char tmpbuf[1024];
  char *wire_buf;
  int wire_buf_len = 0;
  size_t len;		  /* max allocated length (to avoid buf overflow) */

  /*
   * First get dynamic string listing all known networks.
   * This could be a long list, if host has lots of interfaces.
   */
  wire_buf = print_wires();
  if (wire_buf)
    wire_buf_len = strlen(wire_buf);

  len = 2048 + wire_buf_len;
  vers = xmalloc(len);
  xsnprintf(vers, len, "%s\n%s\n%s\n%s\n",
	    "Copyright (c) 1997-2006 Erez Zadok",
	    "Copyright (c) 1990 Jan-Simon Pendry",
	    "Copyright (c) 1990 Imperial College of Science, Technology & Medicine",
	    "Copyright (c) 1990 The Regents of the University of California.");
  xsnprintf(tmpbuf, sizeof(tmpbuf), "%s version %s (build %d).\n",
	    PACKAGE_NAME, PACKAGE_VERSION, AMU_BUILD_VERSION);
  strlcat(vers, tmpbuf, len);
  xsnprintf(tmpbuf, sizeof(tmpbuf), "Report bugs to %s.\n", PACKAGE_BUGREPORT);
  strlcat(vers, tmpbuf, len);
  xsnprintf(tmpbuf, sizeof(tmpbuf), "Configured by %s@%s on date %s.\n",
	    USER_NAME, HOST_NAME, CONFIG_DATE);
  strlcat(vers, tmpbuf, len);
  xsnprintf(tmpbuf, sizeof(tmpbuf), "Built by %s@%s.\n",
	    BUILD_USER, BUILD_HOST);
  strlcat(vers, tmpbuf, len);
  xsnprintf(tmpbuf, sizeof(tmpbuf), "cpu=%s (%s-endian), arch=%s, karch=%s.\n",
	    cpu, endian, gopt.arch, gopt.karch);
  strlcat(vers, tmpbuf, len);
  xsnprintf(tmpbuf, sizeof(tmpbuf), "full_os=%s, os=%s, osver=%s, vendor=%s, distro=%s.\n",
	    gopt.op_sys_full, gopt.op_sys, gopt.op_sys_ver, gopt.op_sys_vendor, DISTRO_NAME);
  strlcat(vers, tmpbuf, len);
  xsnprintf(tmpbuf, sizeof(tmpbuf), "domain=%s, host=%s, hostd=%s.\n",
	    hostdomain, am_get_hostname(), hostd);
  strlcat(vers, tmpbuf, len);

  strlcat(vers, "Map support for: ", len);
  mapc_showtypes(tmpbuf, sizeof(tmpbuf));
  strlcat(vers, tmpbuf, len);
  strlcat(vers, ".\nAMFS: ", len);
  ops_showamfstypes(tmpbuf, sizeof(tmpbuf));
  strlcat(vers, tmpbuf, len);
  strlcat(vers, ", inherit.\nFS: ", len); /* hack: "show" that we support type:=inherit */
  ops_showfstypes(tmpbuf, sizeof(tmpbuf));
  strlcat(vers, tmpbuf, len);

  /* append list of networks if available */
  if (wire_buf) {
    strlcat(vers, wire_buf, len);
    XFREE(wire_buf);
  }

  return vers;
}

static void
show_usage(void)
{
  fprintf(stderr,
	  "Usage: %s [-nprvHS] [-a mount_point] [-c cache_time] [-d domain]\n\
\t[-k kernel_arch] [-l logfile%s\n\
\t[-t timeout.retrans] [-w wait_timeout] [-A arch] [-C cluster_name]\n\
\t[-o op_sys_ver] [-O op_sys_name]\n\
\t[-F conf_file] [-T conf_tag]", am_get_progname(),
#ifdef HAVE_SYSLOG
# ifdef LOG_DAEMON
	  "|\"syslog[:facility]\"]"
# else /* not LOG_DAEMON */
	  "|\"syslog\"]"
# endif /* not LOG_DAEMON */
#else /* not HAVE_SYSLOG */
	  "]"
#endif /* not HAVE_SYSLOG */
	  );

#ifdef HAVE_MAP_NIS
  fputs(" [-y nis-domain]\n", stderr);
#else /* not HAVE_MAP_NIS */
  fputc('\n', stderr);
#endif /* HAVE_MAP_NIS */

  show_opts('x', xlog_opt);
#ifdef DEBUG
  show_opts('D', dbg_opt);
#endif /* DEBUG */
  fprintf(stderr, "\t[directory mapname [-map_options]] ...\n");
}

void
get_args(int argc, char *argv[])
{
  int opt_ch, i;
  FILE *fp = stdin;
  char getopt_arguments[] = "+nprvSa:c:d:k:l:o:t:w:x:y:C:D:F:T:O:HA:";
  char *getopt_args;
  int print_version = 0;	/* 1 means we should print version info */

#ifdef HAVE_GNU_GETOPT
  getopt_args = getopt_arguments;
#else /* ! HAVE_GNU_GETOPT */
  getopt_args = &getopt_arguments[1];
#endif /* HAVE_GNU_GETOPT */

  /* if no arguments were passed, try to use /etc/amd.conf file */
  if (argc <= 1)
    use_conf_file = 1;

  while ((opt_ch = getopt(argc, argv, getopt_args)) != -1)
    switch (opt_ch) {

    case 'a':
      if (*optarg != '/') {
	fprintf(stderr, "%s: -a option must begin with a '/'\n",
		am_get_progname());
	exit(1);
      }
      gopt.auto_dir = optarg;
      break;

    case 'c':
      gopt.am_timeo = atoi(optarg);
      if (gopt.am_timeo <= 0)
	gopt.am_timeo = AM_TTL;
      break;

    case 'd':
      gopt.sub_domain = optarg;
      break;

    case 'k':
      gopt.karch = optarg;
      break;

    case 'l':
      gopt.logfile = optarg;
      break;

    case 'n':
      gopt.flags |= CFM_NORMALIZE_HOSTNAMES;
      break;

    case 'o':
      gopt.op_sys_ver = optarg;
      break;

    case 'p':
     gopt.flags |= CFM_PRINT_PID;
      break;

    case 'r':
      gopt.flags |= CFM_RESTART_EXISTING_MOUNTS;
      break;

    case 't':
      /* timeo.retrans (also affects toplvl mounts) */
      {
	char *dot = strchr(optarg, '.');
	int i;
	if (dot)
	  *dot = '\0';
	if (*optarg) {
	  for (i=0; i<AMU_TYPE_MAX; ++i)
	    gopt.amfs_auto_timeo[i] = atoi(optarg);
	}
	if (dot) {
	  for (i=0; i<AMU_TYPE_MAX; ++i)
	    gopt.amfs_auto_retrans[i] = atoi(dot + 1);
	  *dot = '.';
	}
      }
      break;

    case 'v':
      /*
       * defer to print version info after every variable had been
       * initialized.
       */
      print_version++;
      break;

    case 'w':
      gopt.am_timeo_w = atoi(optarg);
      if (gopt.am_timeo_w <= 0)
	gopt.am_timeo_w = AM_TTL_W;
      break;

    case 'x':
      usage += switch_option(optarg);
      break;

    case 'y':
#ifdef HAVE_MAP_NIS
      gopt.nis_domain = optarg;
#else /* not HAVE_MAP_NIS */
      plog(XLOG_USER, "-y: option ignored.  No NIS support available.");
#endif /* not HAVE_MAP_NIS */
      break;

    case 'A':
      gopt.arch = optarg;
      break;

    case 'C':
      gopt.cluster = optarg;
      break;

    case 'D':
#ifdef DEBUG
      usage += debug_option(optarg);
#else /* not DEBUG */
      fprintf(stderr, "%s: not compiled with DEBUG option -- sorry.\n",
	      am_get_progname());
#endif /* not DEBUG */
      break;

    case 'F':
      amu_conf_file = optarg;
      use_conf_file = 1;
      break;

    case 'H':
      show_usage();
      exit(1);
      break;

    case 'O':
      gopt.op_sys = optarg;
      break;

    case 'S':
      gopt.flags &= ~CFM_PROCESS_LOCK; /* turn process locking off */
      break;

    case 'T':
      conf_tag = optarg;
      break;

    default:
      usage = 1;
      break;
    }

  /*
   * amd.conf file: if not command-line arguments were used, or if -F was
   * specified, then use that amd.conf file.  If the file cannot be opened,
   * abort amd.  If it can be found, open it, parse it, and then close it.
   */
  if (use_conf_file && amu_conf_file) {
    fp = fopen(amu_conf_file, "r");
    if (!fp) {
      char buf[128];
      xsnprintf(buf, sizeof(buf), "Amd configuration file (%s)",
		amu_conf_file);
      perror(buf);
      exit(1);
    }
    yyin = fp;
    yyparse();
    fclose(fp);
    if (process_all_regular_maps() != 0)
      exit(1);
  }

  /* make sure there are some default options defined */
  if (xlog_level_init == ~0) {
    switch_option("");
  }
#ifdef DEBUG
  usage += switch_option("debug");
#endif /* DEBUG */

  /* log information regarding amd.conf file */
  if (use_conf_file && amu_conf_file)
    plog(XLOG_INFO, "using configuration file %s", amu_conf_file);

#ifdef HAVE_MAP_LDAP
  /* ensure that if ldap_base is specified, that also ldap_hostports is */
  if (gopt.ldap_hostports && !gopt.ldap_base) {
    fprintf(stderr, "must specify both ldap_hostports and ldap_base\n");
    exit(1);
  }
#endif /* HAVE_MAP_LDAP */

  if (usage) {
    show_usage();
    exit(1);
  }

  while (optind <= argc - 2) {
    char *dir = argv[optind++];
    char *map = argv[optind++];
    char *opts = "";
    if (argv[optind] && *argv[optind] == '-')
      opts = &argv[optind++][1];

    root_newmap(dir, opts, map, NULL);
  }

  if (optind == argc) {
    /*
     * Append domain name to hostname.
     * sub_domain overrides hostdomain
     * if given.
     */
    if (gopt.sub_domain)
      hostdomain = gopt.sub_domain;
    if (*hostdomain == '.')
      hostdomain++;
    xstrlcat(hostd, ".", sizeof(hostd));
    xstrlcat(hostd, hostdomain, sizeof(hostd));

#ifdef MOUNT_TABLE_ON_FILE
    if (amuDebug(D_MTAB))
      if (gopt.debug_mtab_file)
        mnttab_file_name = gopt.debug_mtab_file; /* user supplied debug mtab path */
      else
	mnttab_file_name = DEBUG_MNTTAB_FILE; /* default debug mtab path */
    else
      mnttab_file_name = MNTTAB_FILE_NAME;
#else /* not MOUNT_TABLE_ON_FILE */
    if (amuDebug(D_MTAB))
      dlog("-D mtab option ignored");
# ifdef MNTTAB_FILE_NAME
    mnttab_file_name = MNTTAB_FILE_NAME;
# endif /* MNTTAB_FILE_NAME */
#endif /* not MOUNT_TABLE_ON_FILE */

    /*
     * If the kernel architecture was not specified
     * then use the machine architecture.
     */
    if (gopt.karch == NULL)
      gopt.karch = gopt.arch;

    if (gopt.cluster == NULL)
      gopt.cluster = hostdomain;

    /* sanity checking, normalize values just in case (toplvl too) */
    for (i=0; i<AMU_TYPE_MAX; ++i) {
      if (gopt.amfs_auto_timeo[i] == 0)
	gopt.amfs_auto_timeo[i] = AMFS_AUTO_TIMEO;
      if (gopt.amfs_auto_retrans[i] == 0)
	gopt.amfs_auto_retrans[i] = AMFS_AUTO_RETRANS(i);
      if (gopt.amfs_auto_retrans[i] == 0)
	gopt.amfs_auto_retrans[i] = 3;	/* under very unusual circumstances, could be zero */
    }
  }

  /* finally print version string and exit, if asked for */
  if (print_version) {
    fputs(get_version_string(), stderr);
    exit(0);
  }

  if (switch_to_logfile(gopt.logfile, orig_umask,
			(gopt.flags & CFM_TRUNCATE_LOG)) != 0)
    plog(XLOG_USER, "Cannot switch logfile");

  return;
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef __COMPONENT_CAMERA_H__
#define __COMPONENT_CAMERA_H__

#include "BaseComponent.h"
#include <MathGeoLib/include/Geometry/Frustum.h>

class CameraComponent :
	public BaseComponent
{
	DEFAULT_COMPONENT_IMPLEMENTATION;
public:
	CameraComponent();
	~CameraComponent();

	void Update(float dt) override;

	void SetFOV(float fov);
	void SetAspectRatio(float ratio);
	void SetPlaneDistances(float near, float far);
	float3 Position() const;
	float3 Orientation() const;
	void LookAt(float x, float y, float z);
	float* GetProjectionMatrix() const;
	float* GetViewMatrix() const;
	void SetFront(const vec &front);
	void SetUp(const vec &up);
	void SetPos(const vec &pos);
	const vec& GetUp() const;
	vec GetWorldRight() const;
	AABB GetFrustumAABB();

private:
	math::Frustum _frustum;

};

#endif


text:
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */

import Page = require('../../../../base/Page');
import Response = require('../../../../http/response');
import V1 = require('../../V1');
import { SerializableClass } from '../../../../interfaces';

/**
 * Initialize the UsAppToPersonList
 *
 * PLEASE NOTE that this class contains beta products that are subject to change.
 * Use them with caution.
 *
 * @param version - Version of the resource
 * @param messagingServiceSid - The SID of the Messaging Service the resource is associated with
 */
declare function UsAppToPersonList(version: V1, messagingServiceSid: string): UsAppToPersonListInstance;

interface UsAppToPersonListInstance {
  /**
   * @param sid - sid of instance
   */
  (sid: string): UsAppToPersonContext;
  /**
   * create a UsAppToPersonInstance
   *
   * @param opts - Options for request
   * @param callback - Callback to handle processed record
   */
  create(opts: UsAppToPersonListInstanceCreateOptions, callback?: (error: Error | null, item: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance>;
  /**
   * Streams UsAppToPersonInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory
   * efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Function to process each record
   */
  each(callback?: (item: UsAppToPersonInstance, done: (err?: Error) => void) => void): void;
  /**
   * Streams UsAppToPersonInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory
   * efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param opts - Options for request
   * @param callback - Function to process each record
   */
  each(opts?: UsAppToPersonListInstanceEachOptions, callback?: (item: UsAppToPersonInstance, done: (err?: Error) => void) => void): void;
  /**
   * Constructs a us_app_to_person
   *
   * @param sid - The SID that identifies the US A2P Compliance resource to fetch
   */
  get(sid: string): UsAppToPersonContext;
  /**
   * Retrieve a single target page of UsAppToPersonInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Callback to handle list of records
   */
  getPage(callback?: (error: Error | null, items: UsAppToPersonPage) => any): Promise<UsAppToPersonPage>;
  /**
   * Retrieve a single target page of UsAppToPersonInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param targetUrl - API-generated URL for the requested results page
   * @param callback - Callback to handle list of records
   */
  getPage(targetUrl?: string, callback?: (error: Error | null, items: UsAppToPersonPage) => any): Promise<UsAppToPersonPage>;
  /**
   * Lists UsAppToPersonInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Callback to handle list of records
   */
  list(callback?: (error: Error | null, items: UsAppToPersonInstance[]) => any): Promise<UsAppToPersonInstance[]>;
  /**
   * Lists UsAppToPersonInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  list(opts?: UsAppToPersonListInstanceOptions, callback?: (error: Error | null, items: UsAppToPersonInstance[]) => any): Promise<UsAppToPersonInstance[]>;
  /**
   * Retrieve a single page of UsAppToPersonInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Callback to handle list of records
   */
  page(callback?: (error: Error | null, items: UsAppToPersonPage) => any): Promise<UsAppToPersonPage>;
  /**
   * Retrieve a single page of UsAppToPersonInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  page(opts?: UsAppToPersonListInstancePageOptions, callback?: (error: Error | null, items: UsAppToPersonPage) => any): Promise<UsAppToPersonPage>;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

/**
 * Options to pass to create
 *
 * @property brandRegistrationSid - A2P Brand Registration SID
 * @property description - A short description of what this SMS campaign does
 * @property hasEmbeddedLinks - Indicates that this SMS campaign will send messages that contain links
 * @property hasEmbeddedPhone - Indicates that this SMS campaign will send messages that contain phone numbers
 * @property helpKeywords - Help Keywords
 * @property helpMessage - Help Message
 * @property messageFlow - The message flow of the campaign
 * @property messageSamples - Message samples
 * @property optInKeywords - Opt In Keywords
 * @property optInMessage - Opt In Message
 * @property optOutKeywords - Opt Out Keywords
 * @property optOutMessage - Opt Out Message
 * @property usAppToPersonUsecase - A2P Campaign Use Case.
 */
interface UsAppToPersonListInstanceCreateOptions {
  brandRegistrationSid: string;
  description: string;
  hasEmbeddedLinks: boolean;
  hasEmbeddedPhone: boolean;
  helpKeywords?: string | string[];
  helpMessage?: string;
  messageFlow?: string;
  messageSamples: string | string[];
  optInKeywords?: string | string[];
  optInMessage?: string;
  optOutKeywords?: string | string[];
  optOutMessage?: string;
  usAppToPersonUsecase: string;
}

/**
 * Options to pass to each
 *
 * @property callback -
 *                         Function to process each record. If this and a positional
 *                         callback are passed, this one will be used
 * @property done - Function to be called upon completion of streaming
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         each() guarantees never to return more than limit.
 *                         Default is no limit
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no pageSize is defined but a limit is defined,
 *                         each() will attempt to read the limit with the most efficient
 *                         page size, i.e. min(limit, 1000)
 */
interface UsAppToPersonListInstanceEachOptions {
  callback?: (item: UsAppToPersonInstance, done: (err?: Error) => void) => void;
  done?: Function;
  limit?: number;
  pageSize?: number;
}

/**
 * Options to pass to list
 *
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         list() guarantees never to return more than limit.
 *                         Default is no limit
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no page_size is defined but a limit is defined,
 *                         list() will attempt to read the limit with the most
 *                         efficient page size, i.e. min(limit, 1000)
 */
interface UsAppToPersonListInstanceOptions {
  limit?: number;
  pageSize?: number;
}

/**
 * Options to pass to page
 *
 * @property pageNumber - Page Number, this value is simply for client state
 * @property pageSize - Number of records to return, defaults to 50
 * @property pageToken - PageToken provided by the API
 */
interface UsAppToPersonListInstancePageOptions {
  pageNumber?: number;
  pageSize?: number;
  pageToken?: string;
}

interface UsAppToPersonPayload extends UsAppToPersonResource, Page.TwilioResponsePayload {
}

interface UsAppToPersonResource {
  account_sid: string;
  brand_registration_sid: string;
  campaign_id: string;
  campaign_status: string;
  date_created: Date;
  date_updated: Date;
  description: string;
  has_embedded_links: boolean;
  has_embedded_phone: boolean;
  help_keywords: string[];
  help_message: string;
  is_externally_registered: boolean;
  message_flow: string;
  message_samples: string[];
  messaging_service_sid: string;
  mock: boolean;
  opt_in_keywords: string[];
  opt_in_message: string;
  opt_out_keywords: string[];
  opt_out_message: string;
  rate_limits: object;
  sid: string;
  url: string;
  us_app_to_person_usecase: string;
}

interface UsAppToPersonSolution {
  messagingServiceSid?: string;
}

declare class UsAppToPersonContext {
  /**
   * Initialize the UsAppToPersonContext
   *
   * PLEASE NOTE that this class contains beta products that are subject to change.
   * Use them with caution.
   *
   * @param version - Version of the resource
   * @param messagingServiceSid - The SID of the Messaging Service to fetch the resource from
   * @param sid - The SID that identifies the US A2P Compliance resource to fetch
   */
  constructor(version: V1, messagingServiceSid: string, sid: string);

  /**
   * fetch a UsAppToPersonInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance>;
  /**
   * remove a UsAppToPersonInstance
   *
   * @param callback - Callback to handle processed record
   */
  remove(callback?: (error: Error | null, items: UsAppToPersonInstance) => any): Promise<boolean>;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

declare class UsAppToPersonInstance extends SerializableClass {
  /**
   * Initialize the UsAppToPersonContext
   *
   * PLEASE NOTE that this class contains beta products that are subject to change.
   * Use them with caution.
   *
   * @param version - Version of the resource
   * @param payload - The instance payload
   * @param messagingServiceSid - The SID of the Messaging Service the resource is associated with
   * @param sid - The SID that identifies the US A2P Compliance resource to fetch
   */
  constructor(version: V1, payload: UsAppToPersonPayload, messagingServiceSid: string, sid: string);

  private _proxy: UsAppToPersonContext;
  accountSid: string;
  brandRegistrationSid: string;
  campaignId: string;
  campaignStatus: string;
  dateCreated: Date;
  dateUpdated: Date;
  description: string;
  /**
   * fetch a UsAppToPersonInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: UsAppToPersonInstance) => any): Promise<UsAppToPersonInstance>;
  hasEmbeddedLinks: boolean;
  hasEmbeddedPhone: boolean;
  helpKeywords: string[];
  helpMessage: string;
  isExternallyRegistered: boolean;
  messageFlow: string;
  messageSamples: string[];
  messagingServiceSid: string;
  mock: boolean;
  optInKeywords: string[];
  optInMessage: string;
  optOutKeywords: string[];
  optOutMessage: string;
  rateLimits: any;
  /**
   * remove a UsAppToPersonInstance
   *
   * @param callback - Callback to handle processed record
   */
  remove(callback?: (error: Error | null, items: UsAppToPersonInstance) => any): Promise<boolean>;
  sid: string;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
  url: string;
  usAppToPersonUsecase: string;
}

declare class UsAppToPersonPage extends Page<V1, UsAppToPersonPayload, UsAppToPersonResource, UsAppToPersonInstance> {
  /**
   * Initialize the UsAppToPersonPage
   *
   * PLEASE NOTE that this class contains beta products that are subject to change.
   * Use them with caution.
   *
   * @param version - Version of the resource
   * @param response - Response from the API
   * @param solution - Path solution
   */
  constructor(version: V1, response: Response<string>, solution: UsAppToPersonSolution);

  /**
   * Build an instance of UsAppToPersonInstance
   *
   * @param payload - Payload response from the API
   */
  getInstance(payload: UsAppToPersonPayload): UsAppToPersonInstance;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

export { UsAppToPersonContext, UsAppToPersonInstance, UsAppToPersonList, UsAppToPersonListInstance, UsAppToPersonListInstanceCreateOptions, UsAppToPersonListInstanceEachOptions, UsAppToPersonListInstanceOptions, UsAppToPersonListInstancePageOptions, UsAppToPersonPage, UsAppToPersonPayload, UsAppToPersonResource, UsAppToPersonSolution }


text:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/hints_indicator_right"
    android:fromDegrees="180"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="180" />


text:
#pragma once

#include "mcrouter/lib/network/McParser.h"
#include "mcrouter/lib/network/McAsciiParser.h"

namespace facebook { namespace memcache {

template <class Callback>
class ClientMcParser : private McParser::ParserCallback {
 public:
  ClientMcParser(Callback& cb,
                 size_t requestsPerRead,
                 size_t minBufferSize,
                 size_t maxBufferSize,
                 bool useNewAsciiParser);

  ~ClientMcParser() override;

  /**
   * TAsyncTransport-style getReadBuffer().
   *
   * @return  a buffer pointer and its size that should be safe to read into.
   *
   * The caller might use less than the whole buffer, and will call
   * readDataAvailable(n) giving the actual number of bytes used from
   * the beginning of this buffer.
   */
  std::pair<void*, size_t> getReadBuffer();

  /**
   * Feeds the new data into the parser.
   *
   * @return false  On any parse error.
   */
  bool readDataAvailable(size_t len);

  /**
   * Next reply type specifier.
   *
   * This method should be called by client when it received nextAvailable(id)
   * callback. It explicitly tells parser what type of message is expected.
   */
  template <class Operation, class Request>
  void expectNext();
 private:
  McParser parser_;
  McAsciiParser asciiParser_;
  mc_parser_t mcParser_;
  void (ClientMcParser<Callback>::*replyForwarder_)(){nullptr};
  bool useNewParser_{false};

  Callback& callback_;

  void replyReadyHelper(McReply&& reply, uint64_t reqid);

  template <class Operation, class Request>
  void forwardAsciiReply();

  /* McParser callbacks */
  bool umMessageReady(const UmbrellaMessageInfo& info,
                      const uint8_t* header,
                      const uint8_t* body,
                      const folly::IOBuf& bodyBuffer) override;
  void handleAscii(folly::IOBuf& readBuffer) override;
  void parseError(mc_res_t result, folly::StringPiece reason) override;

  /* mc_parser_t callbacks */
  static void parserMsgReady(void* context, uint64_t reqid, mc_msg_t* req);
  static void parserParseError(void* context, parser_error_t error);
};

}}  // facebook::memcache

#include "ClientMcParser-inl.h"


text:
Test
This is the new changes in readme file by tejinder.


text:
import setuptools
import sys

tests_require = ['nose', 'mock']
if sys.version_info < (2, 7, 0):
    tests_require.append('unittest2')

dnspython = 'dnspython' if sys.version_info < (3, 0, 0) else 'dnspython3'

setuptools.setup(name='srvlookup',
                 version='0.1.0',
                 description='Service lookup using DNS SRV records',
                 long_description=open('README.rst').read(),
                 author='Gavin M. Roy',
                 author_email='gavinr@aweber.com',
                 url='http://github.com/AWeber/srvlookup',
                 py_modules=['srvlookup'],
                 package_data={'': ['LICENSE', 'README.rst']},
                 include_package_data=True,
                 install_requires=[dnspython],
                 tests_require=tests_require,
                 test_suite='nose.collector',
                 license=open('LICENSE').read(),
                 classifiers=['Development Status :: 4 - Beta',
                              'Intended Audience :: Developers',
                              'License :: OSI Approved :: BSD License',
                              'Operating System :: OS Independent',
                              'Programming Language :: Python :: 2',
                              'Programming Language :: Python :: 2.6',
                              'Programming Language :: Python :: 2.7',
                              'Programming Language :: Python :: 3',
                              'Programming Language :: Python :: 3.2',
                              'Programming Language :: Python :: 3.3',
                              'Programming Language :: Python :: Implementation :: CPython',
                              'Programming Language :: Python :: Implementation :: PyPy',
                              'Topic :: Communications',
                              'Topic :: Internet',
                              'Topic :: Software Development :: Libraries'],
                 zip_safe=True)


text:
namespace dawn_native { namespace metal {

    class MapRequestTracker;
    class ResourceUploader;

    class Device : public DeviceBase {
      public:
        Device(id<MTLDevice> mtlDevice);
        ~Device();

        BindGroupBase* CreateBindGroup(BindGroupBuilder* builder) override;
        BlendStateBase* CreateBlendState(BlendStateBuilder* builder) override;
        BufferViewBase* CreateBufferView(BufferViewBuilder* builder) override;
        CommandBufferBase* CreateCommandBuffer(CommandBufferBuilder* builder) override;
        DepthStencilStateBase* CreateDepthStencilState(DepthStencilStateBuilder* builder) override;
        InputStateBase* CreateInputState(InputStateBuilder* builder) override;
        RenderPassDescriptorBase* CreateRenderPassDescriptor(
            RenderPassDescriptorBuilder* builder) override;
        RenderPipelineBase* CreateRenderPipeline(RenderPipelineBuilder* builder) override;
        SwapChainBase* CreateSwapChain(SwapChainBuilder* builder) override;
        TextureViewBase* CreateTextureView(TextureViewBuilder* builder) override;

        void TickImpl() override;

        id<MTLDevice> GetMTLDevice();

        id<MTLCommandBuffer> GetPendingCommandBuffer();
        void SubmitPendingCommandBuffer();
        Serial GetPendingCommandSerial();

        MapRequestTracker* GetMapTracker() const;
        ResourceUploader* GetResourceUploader() const;

      private:
        ResultOrError<BindGroupLayoutBase*> CreateBindGroupLayoutImpl(
            const BindGroupLayoutDescriptor* descriptor) override;
        ResultOrError<BufferBase*> CreateBufferImpl(const BufferDescriptor* descriptor) override;
        ResultOrError<ComputePipelineBase*> CreateComputePipelineImpl(
            const ComputePipelineDescriptor* descriptor) override;
        ResultOrError<PipelineLayoutBase*> CreatePipelineLayoutImpl(
            const PipelineLayoutDescriptor* descriptor) override;
        ResultOrError<QueueBase*> CreateQueueImpl() override;
        ResultOrError<SamplerBase*> CreateSamplerImpl(const SamplerDescriptor* descriptor) override;
        ResultOrError<ShaderModuleBase*> CreateShaderModuleImpl(
            const ShaderModuleDescriptor* descriptor) override;
        ResultOrError<TextureBase*> CreateTextureImpl(const TextureDescriptor* descriptor) override;

        void OnCompletedHandler();

        id<MTLDevice> mMtlDevice = nil;
        id<MTLCommandQueue> mCommandQueue = nil;
        std::unique_ptr<MapRequestTracker> mMapTracker;
        std::unique_ptr<ResourceUploader> mResourceUploader;

        Serial mFinishedCommandSerial = 0;
        Serial mPendingCommandSerial = 1;
        id<MTLCommandBuffer> mPendingCommands = nil;
    };

}}  // namespace dawn_native::metal

#endif  // DAWNNATIVE_METAL_DEVICEMTL_H_


text:
/*
 * OANDA v20 REST API
 *
 * The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more.
 *
 * OpenAPI spec version: 3.0.15
 * Contact: api@oanda.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 */

using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;

namespace Oanda.RestV20.Model
{
    /// <summary>
    /// The dynamic state of an Order. This is only relevant to TrailingStopLoss Orders, as no other Order type has dynamic state.
    /// </summary>
    [DataContract]
    public partial class DynamicOrderState :  IEquatable<DynamicOrderState>, IValidatableObject
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DynamicOrderState" /> class.
        /// </summary>
        /// <param name="Id">The Order's ID..</param>
        /// <param name="TrailingStopValue">The Order's calculated trailing stop value..</param>
        /// <param name="TriggerDistance">The distance between the Trailing Stop Loss Order's trailingStopValue and the current Market Price. This represents the distance (in price units) of the Order from a triggering price. If the distance could not be determined, this value will not be set..</param>
        /// <param name="IsTriggerDistanceExact">True if an exact trigger distance could be calculated. If false, it means the provided trigger distance is a best estimate. If the distance could not be determined, this value will not be set..</param>
        public DynamicOrderState(string Id = default(string), string TrailingStopValue = default(string), string TriggerDistance = default(string), bool? IsTriggerDistanceExact = default(bool?))
        {
            this.Id = Id;
            this.TrailingStopValue = TrailingStopValue;
            this.TriggerDistance = TriggerDistance;
            this.IsTriggerDistanceExact = IsTriggerDistanceExact;
        }

        /// <summary>
        /// The Order's ID.
        /// </summary>
        /// <value>The Order's ID.</value>
        [DataMember(Name="id", EmitDefaultValue=false)]
        public string Id { get; set; }
        /// <summary>
        /// The Order's calculated trailing stop value.
        /// </summary>
        /// <value>The Order's calculated trailing stop value.</value>
        [DataMember(Name="trailingStopValue", EmitDefaultValue=false)]
        public string TrailingStopValue { get; set; }
        /// <summary>
        /// The distance between the Trailing Stop Loss Order's trailingStopValue and the current Market Price. This represents the distance (in price units) of the Order from a triggering price. If the distance could not be determined, this value will not be set.
        /// </summary>
        /// <value>The distance between the Trailing Stop Loss Order's trailingStopValue and the current Market Price. This represents the distance (in price units) of the Order from a triggering price. If the distance could not be determined, this value will not be set.</value>
        [DataMember(Name="triggerDistance", EmitDefaultValue=false)]
        public string TriggerDistance { get; set; }
        /// <summary>
        /// True if an exact trigger distance could be calculated. If false, it means the provided trigger distance is a best estimate. If the distance could not be determined, this value will not be set.
        /// </summary>
        /// <value>True if an exact trigger distance could be calculated. If false, it means the provided trigger distance is a best estimate. If the distance could not be determined, this value will not be set.</value>
        [DataMember(Name="isTriggerDistanceExact", EmitDefaultValue=false)]
        public bool? IsTriggerDistanceExact { get; set; }
        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class DynamicOrderState {\n");
            sb.Append("  Id: ").Append(Id).Append("\n");
            sb.Append("  TrailingStopValue: ").Append(TrailingStopValue).Append("\n");
            sb.Append("  TriggerDistance: ").Append(TriggerDistance).Append("\n");
            sb.Append("  IsTriggerDistanceExact: ").Append(IsTriggerDistanceExact).Append("\n");
            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="obj">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object obj)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            return this.Equals(obj as DynamicOrderState);
        }

        /// <summary>
        /// Returns true if DynamicOrderState instances are equal
        /// </summary>
        /// <param name="other">Instance of DynamicOrderState to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(DynamicOrderState other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return
                (
                    this.Id == other.Id ||
                    this.Id != null &&
                    this.Id.Equals(other.Id)
                ) &&
                (
                    this.TrailingStopValue == other.TrailingStopValue ||
                    this.TrailingStopValue != null &&
                    this.TrailingStopValue.Equals(other.TrailingStopValue)
                ) &&
                (
                    this.TriggerDistance == other.TriggerDistance ||
                    this.TriggerDistance != null &&
                    this.TriggerDistance.Equals(other.TriggerDistance)
                ) &&
                (
                    this.IsTriggerDistanceExact == other.IsTriggerDistanceExact ||
                    this.IsTriggerDistanceExact != null &&
                    this.IsTriggerDistanceExact.Equals(other.IsTriggerDistanceExact)
                );
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;
                // Suitable nullity checks etc, of course :)
                if (this.Id != null)
                    hash = hash * 59 + this.Id.GetHashCode();
                if (this.TrailingStopValue != null)
                    hash = hash * 59 + this.TrailingStopValue.GetHashCode();
                if (this.TriggerDistance != null)
                    hash = hash * 59 + this.TriggerDistance.GetHashCode();
                if (this.IsTriggerDistanceExact != null)
                    hash = hash * 59 + this.IsTriggerDistanceExact.GetHashCode();
                return hash;
            }
        }

        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            yield break;
        }
    }

}


text:
taskName = "Problem 10. Find palindromes";
function Main(bufferElement) {

    var test = 'Write a program that extracts from a given text all palindromes "ABBA", "lamal", "exe".',
        print;

    function findPalindromes(text) {
        var i,
            result = [],
            arrOfWords = text.split(' ').map(function(item) {
                return item.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"");
            }),
            len = arrOfWords.length;

        for (i = 0; i < len; i += 1) {
            if (arrOfWords[i].length > 1 &&
                arrOfWords[i].toLowerCase() === reverseWord(arrOfWords[i].toLowerCase())) {
                result.push(arrOfWords[i]);
            }
        }
        return result;
    }

    function reverseWord(word) {
        return word.split('').reverse().join('');
    }

    print = findPalindromes(test);
    print.forEach(function(item) {
        WriteLine(item);
    })
}


text:
"use strict";

import {assert, assertIsGenerator, assertIsNumber, size} from './utils';

/**
 * @class LazyStack
 * @classdesc
 *    A lazy stack has an Array-like API. It only does as much work
 *    as needed to return the values requested by all(), take(), or
 *    toArray, toJSON, toString
 * @static from
 * @static fromArray
 * @constructor constructor
 * @method map
 * @method filter
 * @method fold
 * @method take
 * @method all
 * @method toArray
 * @method toJSON
 * @method toString
 */
export default class LazyStack {

  /**
   * Create a LazyStack from an arbitrary amount of values.
   *
   * @param {*} values
   * @returns {LazyStack}
   */
  static from(...values) {
    assert(size(values) > 0, 'LazyStack.from requires at least 1 value.');

    return new LazyStack(function * (toArray = false) {
      if (toArray) {
        // A way to get the raw array without iterator.
        return values;
      }

      const len = size(values);
      for (let i = 0; i < len; i++) {
        yield values[i];
      }
    })
  }

  /**
   * Create a LazyStack from one or more JavaScript Arrays.
   *
   * @param {Array} array
   * @param {Array} [arrays]
   *     Any additional arrays with values to add into LazyStack
   * @returns {*}
   */
  static fromArray(array, ...arrays) {
    return LazyStack.from([].concat(array, ...arrays));
  }

  /**
   * Create a LazyStream
   * @param {Function} generatorFn (* -> Iterator)
   * @param {LazyStack} [parent]
   *     The LazyStack to pull values from
   */
  constructor(generatorFn, parent) {
    assertIsGenerator(
      generatorFn,
      'First argument to LazyStream constructor must be a generator'
    );
    this.generatorFn = generatorFn;
    this.parent      = parent;
  }

  /**
   * Transform values from the LazyStream Collection one at
   * a time by passing them through a transformer function.
   *
   * @param {Function} transformerFunction (α -> β)
   * @returns {LazyStack}
   */
  map(transformerFunction) {
    return new LazyStack(function * () {

      const iterator = this.parent.generatorFn();
      let value;

      while ((value = iterator.next()) && !value.done) {
        yield transformerFunction(value.value);
      }

    }, this);
  }

  /**
   * Filter the values in the LazyStream Collection
   * by testing them with a predicate function. This is a
   * lazy-op
   *
   * @param {Function} predicateFunction (α -> Bool)
   * @returns {LazyStack}
   */
  filter(predicateFunction) {
    return new LazyStack(function * () {
      let value;
      const iterator = this.parent.generatorFn();

      while ((value = iterator.next()) && !value.done) {
        if (predicateFunction(value.value)) {
          yield value.value;
        }
      }

    }, this);
  }

  fold(foldingFn, defaultValue) {

    return new LazyStack(function * () {
      const iterator = this.parent.generatorFn();
      let accumulation = defaultValue,
            value;

      while ((value = iterator.next()) && !value.done) {
        accumulation = foldingFn(accumulation, value.value);
        yield accumulation;
      }

      return accumulation;
    }, this);
  }

  /**
   * Take `n` values from the Stream, this is a lazy-op so
   * it will only do as much work as is required.
   *
   * @param n
   * @returns {*}
   */
  take(n) {
    assertIsNumber(n, "LazyStream.take expects a number");
    let value, index = 0;
    const taken = [],
        iterator = this.generatorFn();

    value = iterator.next();
    while (!value.done && index < n) {
      taken.push(value.value);
      index = size(taken);
      if (index >= n) {
        break;
      }
      value = iterator.next();
    }

    return LazyStack.from(...taken);
  }

  /**
   * Take from stream until there are no more values.
   * @returns {Lazy}
   */
  all() {
    return this.take(Infinity);
  }

  /**
   * Return a regular JavaScript Array from the current values in the
   * LazyStream.
   *
   */
  toArray() {
    const iterator = this.generatorFn(true);
    return iterator.next().value;
  }

  /**
   * Return a JSON representation of the LazyStack values.
   */
  toJSON() {
    const asArray = this.toArray();
    return JSON.stringify(asArray);
  }

  /**
   * Return a String to identify object in text.
   * @returns {string}
   */
  toString() {
    return `Lazy( ${this.toArray()} )`;
  }
}


text:
#include "log.h"

string Trace::filename   = "trace.log";
int    Trace::tracelevel = 1;


text:
""" Test foglamp/services/core/scheduler/exceptions.py """

import uuid
import pytest
from foglamp.services.core.scheduler.exceptions import *

__author__ = "Amarendra K Sinha"
__copyright__ = "Copyright (c) 2018 OSIsoft, LLC"
__license__ = "Apache 2.0"
__version__ = "${VERSION}"

@pytest.allure.feature("unit")
@pytest.allure.story("services", "core", "scheduler")
class TestSchedulerExceptions:
    def test_NotReadyError(self):
        with pytest.raises(NotReadyError) as excinfo:
            raise NotReadyError()
        assert excinfo.type is NotReadyError
        assert issubclass(excinfo.type, RuntimeError)

    def test_DuplicateRequestError(self):
        with pytest.raises(DuplicateRequestError) as excinfo:
            raise DuplicateRequestError()
        assert excinfo.type is DuplicateRequestError
        assert issubclass(excinfo.type, RuntimeError)

    def test_TaskNotRunningError(self):
        task_id = uuid.uuid4()
        with pytest.raises(TaskNotRunningError) as excinfo:
            raise TaskNotRunningError(task_id)
        assert excinfo.type is TaskNotRunningError
        assert issubclass(excinfo.type, RuntimeError)
        assert str(excinfo).endswith("Task is not running: {}".format(str(task_id)))

    def test_TaskNotFoundError(self):
        task_id = uuid.uuid4()
        with pytest.raises(TaskNotFoundError) as excinfo:
            raise TaskNotFoundError(task_id)
        assert excinfo.type is TaskNotFoundError
        assert issubclass(excinfo.type, ValueError)
        assert str(excinfo).endswith("Task not found: {}".format(task_id))

    def test_ScheduleNotFoundError(self):
        schedule_id = uuid.uuid4()
        with pytest.raises(ScheduleNotFoundError) as excinfo:
            raise ScheduleNotFoundError(schedule_id)
        assert excinfo.type is ScheduleNotFoundError
        assert issubclass(excinfo.type, ValueError)
        assert str(excinfo).endswith("Schedule not found: {}".format(schedule_id))

    def test_ScheduleProcessNameNotFound(self):
        with pytest.raises(ScheduleProcessNameNotFoundError) as excinfo:
            raise ScheduleProcessNameNotFoundError()
        assert excinfo.type is ScheduleProcessNameNotFoundError
        assert issubclass(excinfo.type, ValueError)


text:
package upload

import (
	"testing"
)

func TestUploadMarathon(t *testing.T) {
	runAllMultiCmdTests(t,
		map[string]processorTestCase{
			"simple": {
				in: `---
unstable-url: "http://unstable.test.ru"
stable-url: "http://stable.test.ru"`,
				expect: map[string]interface{}{
					"cmdline": []string{"curl -vsSf -o marathon.tar.gz http://unstable.test.ru",
						"curl -vsSf -XPUT -T marathon.tar.gz http://stable.test.ru"},
				},
			},
		},
		UploadMarathon{})
}


text:
#ifndef MITKANNOTATIONPROPERTY_H_HEADER_INCLUDED
#define MITKANNOTATIONPROPERTY_H_HEADER_INCLUDED

#include <MitkExports.h>
#include "mitkBaseProperty.h"
#include "mitkVector.h"

#include <itkConfigure.h>

#include <string>

namespace mitk {

/**
 * \brief Property for annotations
 * \ingroup DataManagement
 */
class MITK_CORE_EXPORT AnnotationProperty : public BaseProperty
{
public:
  mitkClassMacro(AnnotationProperty, BaseProperty);

  typedef std::string ValueType;

  itkNewMacro( AnnotationProperty );
  mitkNewMacro2Param( AnnotationProperty,
    const char *, const Point3D & );
  mitkNewMacro2Param( AnnotationProperty,
    const std::string &, const Point3D & );
  mitkNewMacro4Param( AnnotationProperty,
    const char *, ScalarType, ScalarType, ScalarType );
  mitkNewMacro4Param( AnnotationProperty,
    const std::string &, ScalarType, ScalarType, ScalarType );

  itkGetStringMacro( Label );
  itkSetStringMacro( Label );

  const Point3D &GetPosition() const;
  void SetPosition( const Point3D &position );

  virtual std::string GetValueAsString() const;
  virtual BaseProperty& operator=(const BaseProperty& other) { return Superclass::operator=(other); } \

  using BaseProperty::operator =;

protected:

  std::string m_Label;
  Point3D m_Position;

  AnnotationProperty();
  AnnotationProperty( const char *label, const Point3D &position );
  AnnotationProperty( const std::string &label, const Point3D &position );
  AnnotationProperty( const char *label, ScalarType x, ScalarType y, ScalarType z );
  AnnotationProperty( const std::string &label, ScalarType x, ScalarType y, ScalarType z );

  AnnotationProperty(const AnnotationProperty& other);

private:

  // purposely not implemented
  AnnotationProperty& operator=(const AnnotationProperty&);

  itk::LightObject::Pointer InternalClone() const;

  virtual bool IsEqual(const BaseProperty& property) const;
  virtual bool Assign(const BaseProperty & property);

};

} // namespace mitk

#endif /* MITKANNOTATIONPROPERTY_H_HEADER_INCLUDED */


text:
package com.github.simy4.xpath.jdom.navigator;

import com.github.simy4.xpath.XmlBuilderException;
import com.github.simy4.xpath.jdom.navigator.node.JDomNode;
import com.github.simy4.xpath.navigator.Navigator;
import org.jdom2.Attribute;
import org.jdom2.Element;
import org.jdom2.Namespace;

import javax.xml.XMLConstants;
import javax.xml.namespace.QName;

public final class JDomNavigator implements Navigator<JDomNode> {

  private final JDomNode xml;

  public JDomNavigator(JDomNode xml) {
    this.xml = xml;
  }

  @Override
  public JDomNode root() {
    return xml;
  }

  @Override
  public JDomNode parentOf(JDomNode node) {
    return node.getParent();
  }

  @Override
  public Iterable<? extends JDomNode> elementsOf(final JDomNode parent) {
    return parent.elements();
  }

  @Override
  public Iterable<? extends JDomNode> attributesOf(final JDomNode parent) {
    return parent.attributes();
  }

  @Override
  public JDomNode createAttribute(JDomNode parent, QName attribute) throws XmlBuilderException {
    final Attribute attr = new Attribute(attribute.getLocalPart(), "");
    if (!XMLConstants.NULL_NS_URI.equals(attribute.getNamespaceURI())) {
      attr.setNamespace(Namespace.getNamespace(attribute.getPrefix(), attribute.getNamespaceURI()));
    }
    return parent.appendAttribute(attr);
  }

  @Override
  public JDomNode createElement(JDomNode parent, QName element) throws XmlBuilderException {
    final Element elem = new Element(element.getLocalPart());
    if (!XMLConstants.NULL_NS_URI.equals(element.getNamespaceURI())) {
      elem.setNamespace(Namespace.getNamespace(element.getPrefix(), element.getNamespaceURI()));
    }
    return parent.appendElement(elem);
  }

  @Override
  public void setText(JDomNode node, String text) throws XmlBuilderException {
    node.setText(text);
  }

  @Override
  public void prependCopy(JDomNode node) throws XmlBuilderException {
    node.prependCopy();
  }

  @Override
  public void remove(JDomNode node) throws XmlBuilderException {
    node.remove();
  }
}


text:
package org.apache.druid.java.util.common.granularity;

import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.joda.time.format.DateTimeFormatter;

/**
 * NoneGranularity does not bucket data
 */
public class NoneGranularity extends Granularity
{
  /**
   * This constructor is public b/c it is serialized and deserialized
   * based on type in GranularityModule
   */
  public NoneGranularity()
  {
  }

  @Override
  public DateTimeFormatter getFormatter(Formatter type)
  {
    throw new UnsupportedOperationException("This method should not be invoked for this granularity type");
  }

  @Override
  public DateTime increment(DateTime time)
  {
    return time.plus(1);
  }

  @Override
  public DateTime bucketStart(DateTime time)
  {
    return time;
  }

  @Override
  public DateTime toDate(String filePath, Formatter formatter)
  {
    throw new UnsupportedOperationException("This method should not be invoked for this granularity type");
  }

  /**
   * Any interval is aligned with none granularity since it's effectively millisecond granularity.
   */
  @Override
  public boolean isAligned(Interval interval)
  {
    return true;
  }

  @Override
  public byte[] getCacheKey()
  {
    return new byte[]{0x0};
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    return true;
  }

  @Override
  public int hashCode()
  {
    return -1;
  }

  @Override
  public String toString()
  {
    return "NoneGranularity";
  }
}


text:
<?php

/**
 * Auto generated by MySQL Workbench Schema Exporter.
 * Version 2.1.6-dev (doctrine2-annotation) on 2015-04-21 02:33:04.
 * Goto https://github.com/johmue/mysql-workbench-schema-exporter for more
 * information.
 */

namespace Url\ApiveBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Url\ApiveBundle\Entity\Cuotum
 *
 * @ORM\Entity(repositoryClass="Url\ApiveBundle\Entity\CuotumRepository")
 * @ORM\Table(name="Cuota", indexes={@ORM\Index(name="fk_Cuota_Faena1_idx", columns={"Faena_id"})})
 */
class Cuotum
{
    /**
     * @ORM\Id
     * @ORM\Column(type="bigint")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="date", nullable=true)
     */
    protected $Fecha;

    /**
     * @ORM\Column(type="float", nullable=true)
     */
    protected $Monto;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    protected $Motivo;

    /**
     * @ORM\Column(type="boolean", nullable=true)
     */
    protected $Activa;

    /**
     * @ORM\Column(type="boolean", nullable=true)
     */
    protected $Extraordinaria;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    protected $Observaciones;

    /**
     * @ORM\Column(type="boolean", nullable=true)
     */
    protected $Obligatoria;

    /**
     * @ORM\Column(type="bigint", nullable=true)
     */
    protected $Faena_id;

    /**
     * @ORM\OneToMany(targetEntity="Pago", mappedBy="cuotum")
     * @ORM\JoinColumn(name="id", referencedColumnName="Cuota_id")
     */
    protected $pagos;

    /**
     * @ORM\OneToMany(targetEntity="RegistroCambio", mappedBy="cuotum")
     * @ORM\JoinColumn(name="id", referencedColumnName="Cuota_id")
     */
    protected $registroCambios;

    /**
     * @ORM\ManyToOne(targetEntity="Faena", inversedBy="cuota")
     * @ORM\JoinColumn(name="Faena_id", referencedColumnName="id", nullable=true)
     */
    protected $faena;

    public function __construct()
    {
        $this->pagos = new ArrayCollection();
        $this->registroCambios = new ArrayCollection();
    }

    /**
     * Set the value of id.
     *
     * @param integer $id
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Get the value of id.
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set the value of Fecha.
     *
     * @param datetime $Fecha
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function setFecha($Fecha)
    {
        $this->Fecha = $Fecha;

        return $this;
    }

    /**
     * Get the value of Fecha.
     *
     * @return datetime
     */
    public function getFecha()
    {
        return $this->Fecha;
    }

    /**
     * Set the value of Monto.
     *
     * @param float $Monto
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function setMonto($Monto)
    {
        $this->Monto = $Monto;

        return $this;
    }

    /**
     * Get the value of Monto.
     *
     * @return float
     */
    public function getMonto()
    {
        return $this->Monto;
    }

    /**
     * Set the value of Motivo.
     *
     * @param string $Motivo
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function setMotivo($Motivo)
    {
        $this->Motivo = $Motivo;

        return $this;
    }

    /**
     * Get the value of Motivo.
     *
     * @return string
     */
    public function getMotivo()
    {
        return $this->Motivo;
    }

    /**
     * Set the value of Activa.
     *
     * @param boolean $Activa
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function setActiva($Activa)
    {
        $this->Activa = $Activa;

        return $this;
    }

    /**
     * Get the value of Activa.
     *
     * @return boolean
     */
    public function getActiva()
    {
        return $this->Activa;
    }

    /**
     * Set the value of Extraordinaria.
     *
     * @param boolean $Extraordinaria
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function setExtraordinaria($Extraordinaria)
    {
        $this->Extraordinaria = $Extraordinaria;

        return $this;
    }

    /**
     * Get the value of Extraordinaria.
     *
     * @return boolean
     */
    public function getExtraordinaria()
    {
        return $this->Extraordinaria;
    }

    /**
     * Set the value of Observaciones.
     *
     * @param string $Observaciones
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function setObservaciones($Observaciones)
    {
        $this->Observaciones = $Observaciones;

        return $this;
    }

    /**
     * Get the value of Observaciones.
     *
     * @return string
     */
    public function getObservaciones()
    {
        return $this->Observaciones;
    }

    /**
     * Set the value of Faena_id.
     *
     * @param integer $Faena_id
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function setFaenaId($Faena_id)
    {
        $this->Faena_id = $Faena_id;

        return $this;
    }

    /**
     * Get the value of Faena_id.
     *
     * @return integer
     */
    public function getFaenaId()
    {
        return $this->Faena_id;
    }

    /**
     * Set the value of Obligatoria.
     *
     * @param boolean $Obligatoria
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function setObligatoria($Obligatoria)
    {
        $this->Obligatoria = $Obligatoria;

        return $this;
    }

    /**
     * Get the value of Obligatoria.
     *
     * @return boolean
     */
    public function getObligatoria()
    {
        return $this->Obligatoria;
    }

    /**
     * Add Pago entity to collection (one to many).
     *
     * @param \Url\ApiveBundle\Entity\Pago $pago
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function addPago(Pago $pago)
    {
        $this->pagos[] = $pago;

        return $this;
    }

    /**
     * Remove Pago entity from collection (one to many).
     *
     * @param \Url\ApiveBundle\Entity\Pago $pago
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function removePago(Pago $pago)
    {
        $this->pagos->removeElement($pago);

        return $this;
    }

    /**
     * Get Pago entity collection (one to many).
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPagos()
    {
        return $this->pagos;
    }

    /**
     * Add RegistroCambio entity to collection (one to many).
     *
     * @param \Url\ApiveBundle\Entity\RegistroCambio $registroCambio
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function addRegistroCambio(RegistroCambio $registroCambio)
    {
        $this->registroCambios[] = $registroCambio;

        return $this;
    }

    /**
     * Remove RegistroCambio entity from collection (one to many).
     *
     * @param \Url\ApiveBundle\Entity\RegistroCambio $registroCambio
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function removeRegistroCambio(RegistroCambio $registroCambio)
    {
        $this->registroCambios->removeElement($registroCambio);

        return $this;
    }

    /**
     * Get RegistroCambio entity collection (one to many).
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getRegistroCambios()
    {
        return $this->registroCambios;
    }

    /**
     * Set Faena entity (many to one).
     *
     * @param \Url\ApiveBundle\Entity\Faena $faena
     * @return \Url\ApiveBundle\Entity\Cuotum
     */
    public function setFaena(Faena $faena = null)
    {
        $this->faena = $faena;

        return $this;
    }

    /**
     * Get Faena entity (many to one).
     *
     * @return \Url\ApiveBundle\Entity\Faena
     */
    public function getFaena()
    {
        return $this->faena;
    }

    public function __sleep()
    {
        return array('id', 'Fecha', 'Monto', 'Motivo', 'Activa', 'Extraordinaria', 'Observaciones', 'Faena_id', 'Obligatoria');
    }

    public function __toString()
    {
        return $this->Motivo;
    }
}


text:
You can use this command to generate your app.yaml and appengine_config.py files already configurated
to work with Ray.

```bash
ray new_gae_project # this will create the app.yaml and appengine_config files and a dir called libs
cd libs/
pip install ray -t . # this will download the ray library in this dir
pip install ray-appengine -t . # this will download the ray-appengine library in this dir
cd ..
```

Run the dev_server:
```bash
# in the same dir that has the app.yaml file
dev_appserver.py .
```

### How to run the tests

```bash
# at the ray-core directory
pip install --editable .

cd ../ray-appengine/
pip install --editable

cd tests/
./run_tests.sh
```


text:
{-# LANGUAGE TemplateHaskell, TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
--------------------------------------------------------------------------------
-- |
-- Module      :  Examples.Common
-- Copyright   :  (c) 2011 Patrick Bahr, Tom Hvitved
-- License     :  BSD3
-- Maintainer  :  Tom Hvitved <hvitved@diku.dk>
-- Stability   :  experimental
-- Portability :  non-portable (GHC Extensions)
--
-- Common definitions used in examples.
--
--------------------------------------------------------------------------------

module Examples.Common where

import Data.Comp
import Data.Comp.Derive
import Data.Comp.Show ()
import Data.Comp.Equality ()

-- Signature for values and operators
data Value a = Const Int | Pair a a
data Op a    = Add a a | Mult a a | Fst a | Snd a

-- Signature for the simple expression language
type Sig = Op :+: Value

-- Derive boilerplate code using Template Haskell
$(derive [makeFunctor, makeTraversable, makeFoldable,
          makeEqF, makeShowF, smartConstructors, smartAConstructors]
         [''Value, ''Op])


text:
This inspection reports any inspection suppression comments or annotations.

  Powered by InspectionGadgets


text:
from tkinter import *

class WindowTemplate:

    def __init__(self, programWindow):
        self.programWindow = programWindow
        self._thisWindow = Frame(programWindow)
        self.loadUI()
        self._thisWindow.pack()

    def loadUI(self):
        print("Not ready yet")

    def stop(self):
        self._thisWindow.destroy()


text:
/*
Let S(A) represent the sum of elements in set A of size n. We shall call it a
special sum set if for any two non-empty disjoint subsets, B and C, the
following properties are true:

    1. S(B) ≠ S(C); that is, sums of subsets cannot be equal.
    2. If B contains more elements than C then S(B) > S(C).

For example, {81, 88, 75, 42, 87, 84, 86, 65} is not a special sum set because
65 + 87 + 88 = 75 + 81 + 84, whereas {157, 150, 164, 119, 79, 159, 161, 139,
158} satisfies both rules for all possible subset pair combinations and S(A) =
1286.

Using sets.txt (right click and "Save Link/Target As..."), a 4K text file with
one-hundred sets containing seven to twelve elements (the two examples given
above are the first two sets in the file), identify all the special sum sets,
A1, A2, ..., Ak, and find the value of S(A1) + S(A2) + ... + S(Ak).

NOTE: This problem is related to Problem 103 and Problem 106.

Solution comment: ~15 ms. Purely reuse of code from 103. Only thing of note
                  was to remember to sort the set before testing, as
                  the code from 103 assumed to set to be in ascending
                  order for some efficient checks.
 */
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cmath>
#include <chrono>
#include <vector>
#include <numeric>
#include <algorithm>

/*
 * Return a vector of sums, where sum[i] is the sum of the set
 * containing A[k] where k is the index of all the set bits in i.
 *
 * Example:
 *   A = {1, 2, 3}
 *   sum[3] = sum[0b011] = A[0] + A[1]
 *   sum[4] = sum[0b100] = A[3]
 */
template<typename Container>
auto all_subset_sums(const Container &A) {
    const auto n = std::distance(A.begin(), A.end());
    std::vector<int> subset_sums((std::size_t) std::pow(2, n));
    for (std::size_t i = 1; i < subset_sums.size(); i++) {
        auto selector = i;
        for (int element : A) {
            if (selector & 1) {
                subset_sums[i] += element;
            }
            selector >>= 1;
        }
    }
    return subset_sums;
}

template<typename Container>
bool is_special(const Container &A) {
    // Computing size of A. Workaround for cppitertools classes
    // which don't have a .size() method.
    const auto n = std::distance(A.begin(), A.end());

    // Rule 1: Smaller subsets have smaller sums.
    // Shortcut, since A is sorted: a1 + a2 > an, a1+a2+a3 > a(n-1) + an etc.
    // is a sufficient condition to check.
    // We check this first, as this is _much_ easier to do.
    int left_sum = A[0];
    int right_sum = 0;
    for (int i = 0; i < n / 2; i++) {
        left_sum += A[i + 1];
        right_sum += A[n - 1 - i];

        if (left_sum <= right_sum)
            return false;
    }

    // Rule 2: No duplicate subset sums.
    // If two duplicate sums are found, we check if
    // the corresponding sets are disjoint (meaning
    // set i and set k have no common set bits). If
    // both conditions are met, no special sum for you.
    const auto sums = all_subset_sums(A);
    auto n_sums = std::distance(sums.begin(), sums.end());
    for (int i = 0; i < n_sums; ++i) {
        auto k = std::distance(sums.begin(),
                               std::find(sums.begin() + i + 1,
                                         sums.end(),
                                         sums[i])
        );
        if (k != n_sums and not (i & k))
            return false;
    }
    return true;
}

int main() {
    auto start = std::chrono::high_resolution_clock::now();

    long total = 0;

    std::ifstream input("../../105/p105_sets.txt");
    std::string line;
    while (std::getline(input, line)) {
        std::stringstream linestream(line);
        std::vector<int> A;
        std::string number;
        while (std::getline(linestream, number, ',')) {
            A.push_back(std::stoi(number));
        }

        // Important! Needs to be sorted!
        std::sort(A.begin(), A.end());
        if (is_special(A)) {
            total = std::accumulate(A.begin(), A.end(), total);
        }
    }
    printf("Answer: %ld\n", total);

    auto end = std::chrono::high_resolution_clock::now();
    auto time = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() / (double) 1e6;
    printf("Found in time: %g ms\n", time);
}


text:
namespace multiverso {

template <typename Key, typename Val>
struct KVTableOption;

// A distributed shared std::unordered_map<Key, Val> table
// Key, Val should be the basic type
template <typename Key, typename Val>
class KVWorkerTable : public WorkerTable {
public:
  explicit KVWorkerTable(const KVTableOption<Key, Val>&) {}

  void Get(Key key) { WorkerTable::Get(Blob(&key, sizeof(Key))); }

  void Get(std::vector<Key>& keys) {
    WorkerTable::Get(Blob(&keys[0], sizeof(Key) * keys.size()));
  }

  void Add(Key key, Val value) {
    WorkerTable::Add(Blob(&key, sizeof(Key)), Blob(&value, sizeof(Val)));
  }

  void Add(std::vector<Key>& keys, std::vector<Val>& vals) {
    CHECK(keys.size() == vals.size());
    Blob keys_blob(&keys[0], sizeof(Key) * keys.size());
    Blob vals_blob(&vals[0], sizeof(Val) * vals.size());
    WorkerTable::Add(keys_blob, vals_blob);
  }

  std::unordered_map<Key, Val>& raw() { return table_; }

  int Partition(const std::vector<Blob>& kv,
    MsgType, std::unordered_map<int, std::vector<Blob> >* out) override {
    CHECK(kv.size() == 1 || kv.size() == 2);
    CHECK_NOTNULL(out);
    std::unordered_map<int, int> counts;
    Blob keys = kv[0];
    for (int i = 0; i < keys.size<Key>(); ++i) { // iterate as type Key
      int dst = static_cast<int>(keys.As<Key>(i) % MV_NumServers());
      ++counts[dst];
    }
    for (auto& it : counts) { // Allocate memory
      std::vector<Blob>& vec = (*out)[it.first];
      vec.push_back(Blob(it.second * sizeof(Key)));
      if (kv.size() == 2) vec.push_back(Blob(it.second * sizeof(Val)));
    }
    counts.clear();
    for (int i = 0; i < keys.size<Key>(); ++i) {
      int dst = static_cast<int>(keys.As<Key>(i) % MV_NumServers());
      (*out)[dst][0].As<Key>(counts[dst]) = keys.As<Key>(i);
      if (kv.size() == 2)
        (*out)[dst][1].As<Val>(counts[dst]) = kv[1].As<Val>(i);
      ++counts[dst];
    }
    return static_cast<int>(out->size());
  }

  void ProcessReplyGet(std::vector<Blob>& data) override {
    CHECK(data.size() == 2);
    Blob keys = data[0], vals = data[1];
    CHECK(keys.size<Key>() == vals.size<Val>());
    for (int i = 0; i < keys.size<Key>(); ++i) {
      table_[keys.As<Key>(i)] = vals.As<Val>(i);
    }
  }

private:
  std::unordered_map<Key, Val> table_;
};

template <typename Key, typename Val>
class KVServerTable : public ServerTable {
public:
  explicit KVServerTable(const KVTableOption<Key, Val>&) {}

  void ProcessGet(const std::vector<Blob>& data,
                  std::vector<Blob>* result) override {
    CHECK(data.size() == 1);
    CHECK_NOTNULL(result);
    Blob keys = data[0];
    result->push_back(keys); // also push the key
    result->push_back(Blob(keys.size<Key>() * sizeof(Val)));
    Blob& vals = (*result)[1];
    for (int i = 0; i < keys.size<Key>(); ++i) {
      vals.As<Val>(i) = table_[keys.As<Key>(i)];
    }
  }

  void ProcessAdd(const std::vector<Blob>& data) override {
    CHECK(data.size() == 2);
    Blob keys = data[0], vals = data[1];
    CHECK(keys.size<Key>() == vals.size<Val>());
    for (int i = 0; i < keys.size<Key>(); ++i) {
      table_[keys.As<Key>(i)] += vals.As<Val>(i);
    }
  }

  void Store(Stream*) override {
    Log::Fatal("Not implemented yet\n");
  }

  void Load(Stream*) override {
    Log::Fatal("Not implemented yet\n");
  }

private:
  std::unordered_map<Key, Val> table_;
};

template <typename Key, typename Val>
struct KVTableOption {
  typedef KVWorkerTable<Key, Val> WorkerTableType;
  typedef KVServerTable<Key, Val> ServerTableType;
};

}  // namespace multiverso

#endif // MULTIVERSO_KV_TABLE_H_


text:
<?php

namespace Click\GalleryBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * GalleryRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class GalleryRepository extends EntityRepository
{

    public function getGalleries()
    {
    	$qb = $this->createQueryBuilder('g')
                   ->select('g')
                   ->addOrderBy('g.name');

    	return $qb->getQuery()->getResult();
    }

    public function getCoverPhoto(Gallery $gallery)
    {

        $qb = $this->createQueryBuilder('p')
                    ->select('p')
                    ->innerJoin('p.gallery', 'g')
                    ->innerJoin('p.gallery','g','WITH','g = :gallery')
                    ->setParameter('gallery', $gallery)
                    ->addOrderBy('p.updatedAt', 'DESC')
                    ->setMaxResults(1);

        return $qb->getQuery()->getResult();
    }

}


text:
//  Copyright (c) 2013 Couchbase, Inc.
//  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.

/*

Package mock provides a fake, mock 100%-in-memory implementation of
the catalog package, which can be useful for testing.  Because it is
memory-oriented, performance testing of higher layers may be easier
with this mock catalog.

*/
package mock

import (
	"fmt"
	"sort"
	"strconv"
	"strings"

	"github.com/couchbaselabs/dparval"
	"github.com/couchbaselabs/tuqtng/catalog"
	"github.com/couchbaselabs/tuqtng/query"
)

const (
	DEFAULT_NUM_POOLS   = 1
	DEFAULT_NUM_BUCKETS = 1
	DEFAULT_NUM_ITEMS   = 100000
)

// NewSite creates a new mock site for the given "path".  The path has
// prefix "mock:", with the rest of the path treated as a
// comma-separated key=value params.  For example:
//     mock:pools=2,buckets=5,items=50000
// The above means 2 pools.
// And, each pool has 5 buckets.
// And, each bucket with 50000 items.
// By default, you get...
//     mock:pools=1,buckets=1,items=100000
// Which is what you'd get by specifying a path of just...
//     mock:
func NewSite(path string) (catalog.Site, query.Error) {
	if strings.HasPrefix(path, "mock:") {
		path = path[5:]
	}
	params := map[string]int{}
	for _, kv := range strings.Split(path, ",") {
		if kv == "" {
			continue
		}
		pair := strings.Split(kv, "=")
		v, err := strconv.Atoi(pair[1])
		if err != nil {
			return nil, query.NewError(err,
				fmt.Sprintf("could not parse mock param key: %s, val: %s",
					pair[0], pair[1]))
		}
		params[pair[0]] = v
	}
	npools := paramVal(params, "pools", DEFAULT_NUM_POOLS)
	nbuckets := paramVal(params, "buckets", DEFAULT_NUM_BUCKETS)
	nitems := paramVal(params, "items", DEFAULT_NUM_ITEMS)
	s := &site{path: path, params: params, pools: map[string]*pool{}}
	for i := 0; i < npools; i++ {
		p := &pool{site: s, name: "p" + strconv.Itoa(i), buckets: map[string]*bucket{}}
		for j := 0; j < nbuckets; j++ {
			b := &bucket{pool: p, name: "b" + strconv.Itoa(j), nitems: nitems,
				indexes: map[string]catalog.Index{}}
			pi := &primaryIndex{site: s, name: "all_docs", bucket: b}
			b.primary = pi
			b.indexes["all_docs"] = pi
			p.buckets[b.name] = b
		}
		s.pools[p.name] = p
	}
	return s, nil
}

func paramVal(params map[string]int, key string, defaultVal int) int {
	v, ok := params[key]
	if ok {
		return v
	}
	return defaultVal
}

type site struct {
	path   string
	params map[string]int
	pools  map[string]*pool
}

type pool struct {
	site    *site
	name    string
	buckets map[string]*bucket
}

type bucket struct {
	pool    *pool
	name    string
	nitems  int
	indexes map[string]catalog.Index
	primary catalog.PrimaryIndex
}

func (s *site) Id() string {
	return s.URL()
}

func (s *site) URL() string {
	return "mock:" + s.path
}

func (s *site) PoolIds() ([]string, query.Error) {
	return s.PoolNames()
}

func (s *site) PoolNames() ([]string, query.Error) {
	names := make([]string, 0, len(s.pools))
	for name, _ := range s.pools {
		names = append(names, name)
	}
	sort.Strings(names)
	return names, nil
}

func (s *site) PoolById(id string) (p catalog.Pool, e query.Error) {
	return s.PoolByName(id)
}

func (s *site) PoolByName(name string) (p catalog.Pool, e query.Error) {
	p, ok := s.pools[name]
	if !ok {
		return nil, query.NewError(nil, "Pool "+name+" not found.")
	}
	return p, nil
}

func (p *pool) SiteId() string {
	return p.site.Id()
}

func (p *pool) Id() string {
	return p.Name()
}

func (p *pool) Name() string {
	return p.name
}

func (p *pool) BucketIds() ([]string, query.Error) {
	return p.BucketNames()
}

func (p *pool) BucketNames() ([]string, query.Error) {
	names := make([]string, 0, len(p.buckets))
	for name, _ := range p.buckets {
		names = append(names, name)
	}
	sort.Strings(names)
	return names, nil
}

func (p *pool) BucketById(id string) (b catalog.Bucket, e query.Error) {
	return p.BucketByName(id)
}

func (p *pool) BucketByName(name string) (b catalog.Bucket, e query.Error) {
	b, ok := p.buckets[name]
	if !ok {
		return nil, query.NewError(nil, "Bucket "+name+" not found.")
	}
	return b, nil
}

func (b *bucket) Release() {
}

func (b *bucket) PoolId() string {
	return b.pool.Id()
}

func (b *bucket) Id() string {
	return b.Name()
}

func (b *bucket) Name() string {
	return b.name
}

func (b *bucket) Count() (int64, query.Error) {
	return int64(b.nitems), nil
}

func (b *bucket) IndexIds() ([]string, query.Error) {
	return b.IndexNames()
}

func (b *bucket) IndexNames() ([]string, query.Error) {
	rv := make([]string, 0, len(b.indexes))
	for name, _ := range b.indexes {
		rv = append(rv, name)
	}
	return rv, nil
}

func (b *bucket) IndexById(id string) (catalog.Index, query.Error) {
	return b.IndexByName(id)
}

func (b *bucket) IndexByName(name string) (catalog.Index, query.Error) {
	index, ok := b.indexes[name]
	if !ok {
		return nil, query.NewError(nil, fmt.Sprintf("Index %v not found.", name))
	}
	return index, nil
}

func (b *bucket) IndexByPrimary() (catalog.PrimaryIndex, query.Error) {
	return b.primary, nil
}

func (b *bucket) IndexesByPrimary() ([]catalog.PrimaryIndex, query.Error) {
	return []catalog.PrimaryIndex{b.primary}, nil
}

func (b *bucket) Indexes() ([]catalog.Index, query.Error) {
	rv := make([]catalog.Index, 0, len(b.indexes))
	for _, index := range b.indexes {
		rv = append(rv, index)
	}
	return rv, nil
}

func (b *bucket) BulkFetch(ids []string) (map[string]*dparval.Value, query.Error) {
	rv := make(map[string]*dparval.Value, 0)
	for _, id := range ids {
		item, e := b.Fetch(id)
		if e != nil {
			return nil, e
		}
		rv[id] = item
	}
	return rv, nil
}

func (b *bucket) Fetch(id string) (item *dparval.Value, e query.Error) {
	i, err := strconv.Atoi(id)
	if err != nil {
		return nil, query.NewError(err,
			fmt.Sprintf("no mock item: %v", id))
	}
	return genItem(i, b.nitems)
}

func (b *bucket) CreatePrimaryIndex() (catalog.PrimaryIndex, query.Error) {
	if b.primary != nil {
		return b.primary, nil
	}

	return nil, query.NewError(nil, "Not supported.")
}

func (b *bucket) CreateIndex(name string, key catalog.IndexKey, using catalog.IndexType) (catalog.Index, query.Error) {
	return nil, query.NewError(nil, "Not supported.")
}

type primaryIndex struct {
	site   *site
	name   string
	bucket *bucket
}

func (pi *primaryIndex) BucketId() string {
	return pi.bucket.Id()
}

func (pi *primaryIndex) Id() string {
	return pi.Name()
}

func (pi *primaryIndex) Name() string {
	return pi.name
}

func (pi *primaryIndex) Type() catalog.IndexType {
	return catalog.UNSPECIFIED
}

func (pi *primaryIndex) IsPrimary() bool {
	return true
}

func (pi *primaryIndex) Key() catalog.IndexKey {
	// FIXME
	return nil
}

func (pi *primaryIndex) Drop() query.Error {
	return query.NewError(nil, "Primary index cannot be dropped.")
}

func (pi *primaryIndex) ScanBucket(limit int64, ch catalog.EntryChannel, warnch, errch query.ErrorChannel) {
	pi.ScanEntries(limit, ch, warnch, errch)
}

func (pi *primaryIndex) ScanEntries(limit int64, ch catalog.EntryChannel, warnch, errch query.ErrorChannel) {
	go pi.scanEntries(limit, ch, warnch, errch)
}

func (pi *primaryIndex) scanEntries(limit int64, ch catalog.EntryChannel, warnch, errch query.ErrorChannel) {
	defer close(ch)
	defer close(warnch)
	defer close(errch)

	if limit == 0 {
		limit = int64(pi.bucket.nitems)
	}

	for i := 0; i < pi.bucket.nitems && int64(i) < limit; i++ {
		entry := catalog.IndexEntry{PrimaryKey: strconv.Itoa(i)}
		ch <- &entry
	}
}

func (pi *primaryIndex) Lookup(value catalog.LookupValue, ch catalog.EntryChannel, warnch, errch query.ErrorChannel) {
	defer close(ch)
	defer close(warnch)
	defer close(errch)

	if value == nil || len(value) != 1 || value[0].Type() != dparval.STRING {
		errch <- query.NewError(nil, "Invalid lookup value: string required.")
		return
	}

	val, ok := value[0].Value().(string)
	if !ok {
		errch <- query.NewError(nil, "Invalid lookup value: string required.")
		return
	}

	ival, err := strconv.Atoi(val)
	if err == nil && ival < pi.bucket.nitems {
		entry := catalog.IndexEntry{PrimaryKey: val}
		ch <- &entry
	}
}

func genItem(i int, nitems int) (*dparval.Value, query.Error) {
	if i < 0 || i >= nitems {
		return nil, query.NewError(nil,
			fmt.Sprintf("item out of mock range: %v [0,%v)", i, nitems))
	}
	id := strconv.Itoa(i)
	doc := dparval.NewValue(map[string]interface{}{"id": id, "i": float64(i)})
	doc.SetAttachment("meta", map[string]interface{}{"id": id})
	return doc, nil
}


text:
package org.apache.jackrabbit.oak.jcr;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.jackrabbit.oak.plugins.atomic.AtomicCounterEditor.PROP_COUNTER;
import static org.apache.jackrabbit.oak.plugins.atomic.AtomicCounterEditor.PROP_INCREMENT;
import static org.apache.jackrabbit.oak.spi.nodetype.NodeTypeConstants.MIX_ATOMIC_COUNTER;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import javax.annotation.Nonnull;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;

import org.apache.jackrabbit.oak.fixture.NodeStoreFixture;
import org.junit.Test;

public class AtomicCounterTest extends AbstractRepositoryTest {
    public AtomicCounterTest(NodeStoreFixture fixture) {
        super(fixture);
    }

    @Test
    public void incrementRootNode() throws RepositoryException {

        Session session = getAdminSession();

        try {
            Node root = session.getRootNode();
            Node node = root.addNode("normal node");
            session.save();

            node.setProperty(PROP_INCREMENT, 1L);
            session.save();

            assertTrue("for normal nodes we expect the increment property to be treated as normal",
                node.hasProperty(PROP_INCREMENT));

            node = root.addNode("counterNode");
            node.addMixin(MIX_ATOMIC_COUNTER);
            session.save();

            assertCounter(node, 0);

            node.setProperty(PROP_INCREMENT, 1L);
            session.save();
            assertCounter(node, 1);

            // increment again the same node
            node.setProperty(PROP_INCREMENT, 1L);
            session.save();
            assertCounter(node, 2);

            // decrease the counter by 2
            node.setProperty(PROP_INCREMENT, -2L);
            session.save();
            assertCounter(node, 0);

            // increase by 5
            node.setProperty(PROP_INCREMENT, 5L);
            session.save();
            assertCounter(node, 5);
        } finally {
            session.logout();
        }
    }

    private static void assertCounter(@Nonnull final Node counter, final long expectedCount)
                                    throws RepositoryException {
        checkNotNull(counter);

        assertTrue(counter.hasProperty(PROP_COUNTER));
        assertEquals(expectedCount, counter.getProperty(PROP_COUNTER).getLong());
        assertFalse(counter.hasProperty(PROP_INCREMENT));
    }

    @Test
    public void incrementNonRootNode() throws RepositoryException {
        Session session = getAdminSession();

        try {
            Node counter = session.getRootNode().addNode("foo").addNode("bar").addNode("counter");
            counter.addMixin(MIX_ATOMIC_COUNTER);
            session.save();

            assertCounter(counter, 0);

            counter.setProperty(PROP_INCREMENT, 1L);
            session.save();
            assertCounter(counter, 1);

            // increment again the same node
            counter.setProperty(PROP_INCREMENT, 1L);
            session.save();
            assertCounter(counter, 2);

            // decrease the counter by 2
            counter.setProperty(PROP_INCREMENT, -2L);
            session.save();
            assertCounter(counter, 0);

            // increase by 5
            counter.setProperty(PROP_INCREMENT, 5L);
            session.save();
            assertCounter(counter, 5);
        } finally {
            session.logout();
        }
    }

    @Override
    protected Jcr initJcr(Jcr jcr) {
        return super.initJcr(jcr).withAtomicCounter();
    }
}


text:
package gov.nih.nci.eagle.enumeration;

public enum SpecimenType {
    BLOOD(1, "Blood"),
    TISSUE_NORMAL(2, "Tissue - Normal"),
    TISSUE_CANCER(3, "Tissue - Cancer");

    private final int value;
    private final String name;

    SpecimenType(int key, String name) {
        this.value = key;
    	this.name = name;
    }

    public String getName() {
        return name;
    }

    public int getValue()	{
    	return value;
    }

}


text:
layout: post
date:	2009-06-30 09:34:00
title:  What she was actually thinking...
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---


text:
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body><GetLastClosingPriceResponse xmlns="http://www.xignite.com/services/">
<GetLastClosingPriceResult>
    <Outcome>Success</Outcome>
    <Identity>IP</Identity>
    <Delay>0</Delay>
    <Security>
        <Outcome>Success</Outcome>
        <Delay>0</Delay>
        <CIK>0000858877</CIK>
        <Cusip>17275R102</Cusip>
        <Symbol>CSCO</Symbol>
        <ISIN>US17275R1023</ISIN>
        <Name>Cisco Systems, Inc.</Name>
        <Market>NASDAQGS</Market>
        <CategoryOrIndustry>TECHNOLOGY</CategoryOrIndustry>
    </Security>
<Date>6/29/2007</Date>
<Last>27.85</Last>
<Open>27.98</Open>
<LastClose>27.85</LastClose>
<High>28.06</High>
<Low>27.65</Low>
<ChangeFromOpen>-0.13</ChangeFromOpen>
<PercentChangeFromOpen>-0.465</PercentChangeFromOpen>
<ChangeFromLastClose>0</ChangeFromLastClose>
<PercentChangeFromLastClose>0</PercentChangeFromLastClose>
<Volume>44983400</Volume>
<SplitRatio>1</SplitRatio>
<LastAdjusted>27.85</LastAdjusted>
<OpenAdjusted>27.98</OpenAdjusted><LastCloseAdjusted>27.85</LastCloseAdjusted>
<HighAdjusted>28.06</HighAdjusted><LowAdjusted>27.65</LowAdjusted>
<ChangeFromOpenAdjusted>-0.13</ChangeFromOpenAdjusted>
<ChangeFromLastCloseAdjusted>0</ChangeFromLastCloseAdjusted>
<VolumeAdjusted>44983400</VolumeAdjusted>
<NotTraded>false</NotTraded>
</GetLastClosingPriceResult>
</GetLastClosingPriceResponse>
</soap:Body></soap:Envelope>