text:
def init(env=ENV['RACK_ENV']); end
Encoding.default_internal = 'UTF-8'
require 'rubygems'
require 'bundler/setup'
require 'yaml'
require './lib/base58'
require './lib/notify'
require './lib/photosync'
require 'exifr/jpeg'
Bundler.require

SyncConfig = YAML.load_file('config.yml')

FlickRaw.api_key = SyncConfig['flickr_consumer_key']
FlickRaw.shared_secret = SyncConfig['flickr_consumer_secret']

@flickr = FlickRaw::Flickr.new
@flickr.access_token = SyncConfig['flickr_access_token']
@flickr.access_secret = SyncConfig['flickr_access_token_secret']

PhotoSync.flickr = @flickr


text:
{% if paginator.total_pages > 1 %}

    {% assign url = site.baseurl | append: "/blog/" %}
    {% if paginator.previous_page %}
      {% if paginator.previous_page > 1 %}
        {% assign prev = 'page/' | append: paginator.previous_page %}
      {% endif %}

« Prev

    {% else %}

« Prev

    {% endif %}

Page {{paginator.page}} of {{paginator.total_pages}}

    {% if paginator.next_page %}

Next »

    {% else %}

Next »

    {% endif %}

{% endif %}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Do not modify this file. This file is generated from the email-2010-12-01.normal.json service model.
 */

using System;

namespace Amazon.SimpleEmail.Model
{
    /// <summary>
    /// Configuration for accessing Amazon VerifyDomainIdentity service
    /// </summary>
    public partial class VerifyDomainIdentityResponse : VerifyDomainIdentityResult
    {
        /// <summary>
        /// Gets and sets the VerifyDomainIdentityResult property.
        /// Represents the output of a VerifyDomainIdentity operation.
        /// </summary>
        [Obsolete(@"This property has been deprecated. All properties of the VerifyDomainIdentityResult class are now available on the VerifyDomainIdentityResponse class. You should use the properties on VerifyDomainIdentityResponse instead of accessing them through VerifyDomainIdentityResult.")]
        public VerifyDomainIdentityResult VerifyDomainIdentityResult
        {
            get
            {
                return this;
            }
        }
    }
}


text:
using UnityEngine;
using System.Collections;

public class SpawnPrefabController : MonoBehaviour {
	public GameObject prefab;
	public int numberOfObjects=10;
	public float rndFactor=1.2f;
	public float timeout=0.5f;
	public int atalasRandomIndexMax=10;

	private GameObject parentGO;

	// Use this for initialization
	void Start () {
		StartCoroutine("startSpawning");
	}

	IEnumerator startSpawning ()
	{
		if (parentGO==null){
			parentGO=new GameObject("GeneratedObjects");
		}

		for (int i=0;i<numberOfObjects;i++){
			Vector3 spawnPosition=transform.position;
			float rnd=Random.Range(-rndFactor,rndFactor);
			spawnPosition.z+=rnd;
			spawnPosition.x+=rnd;

			GameObject go=Instantiate(prefab,spawnPosition,Quaternion.identity) as GameObject;
			go.transform.position=spawnPosition;
			CubeAtlasUVManager cm=go.GetComponent<CubeAtlasUVManager>();
			if (cm==null){
				throw new System.Exception("Prefab must have CubeAtlasUVManager on it");
			}
			cm.randomizeFaces(10);
			go.transform.parent=parentGO.transform;
			yield return new WaitForSeconds(timeout);
		}
	}

	// Update is called once per frame
	void Update () {

	}
}


text:
package org.criteria4jpa.order;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;

import java.util.List;

import org.criteria4jpa.AbstractIntegrationTest;
import org.criteria4jpa.Criteria;
import org.criteria4jpa.CriteriaUtils;
import org.criteria4jpa.model.Person;
import org.testng.annotations.Test;

public class MultipleOrderByTest extends AbstractIntegrationTest {

  public MultipleOrderByTest() {
    super("order/MultipleOrderByTest.xml");
  }

  @Test
  public void testMultiLevelOrderBy() {

    // build criteria
    Criteria criteria = CriteriaUtils.createCriteria(entityManager, Person.class);
    criteria.addOrder( Order.asc("age") );
    criteria.addOrder( Order.asc("firstname") );

    // perform query
    List<Person> result = criteria.getResultList();

    // assert correct result
    assertNotNull( result );
    assertEquals( result.size(), 4 );
    assertEquals( result.get(0).getAge(),       Integer.valueOf( 21 ) );
    assertEquals( result.get(0).getFirstname(), "Xavian" );
    assertEquals( result.get(1).getAge(),       Integer.valueOf( 28 ) );
    assertEquals( result.get(1).getFirstname(), "Christian" );
    assertEquals( result.get(2).getAge(),       Integer.valueOf( 28 ) );
    assertEquals( result.get(2).getFirstname(), "Hans" );
    assertEquals( result.get(3).getAge(),       Integer.valueOf( 28 ) );
    assertEquals( result.get(3).getFirstname(), "Peter" );

  }

}


text:
  <loader></loader>

    <list-trigger-history loading="loading"></list-trigger-history>


text:
Welcome to your practical assessment for Module 4 of MIT Big Data and Social Analytics.

Engage with the mentor team and fellow students in the forums to get help, and share your insights and learning experiences.

We hope that you enjoy this course, and that you will acquire and refine skills that are of use to you in your personal journey.

## Objective
This module will explore the fundamentals and structure of peer networks, and introduce you to the concepts of network theory and graph clustering.

# Notebook 1: Introduction to NetworkX
> **Notebook goal**: Identify how to represent and manipulate data as a graph object, using NetworkX.

In this notebook, you will be introduced to NetworkX, a Python module for working with graph objects. Using simple examples, you will be shown how to create and visualize graphs.

**List of exercises:**
- **Exercise 1:**
 Create and manipulate NetworkX graphs.

# Notebook 2: Network analysis using NetworkX
> **Notebook goal:** Execute graph analysis with NetworkX, using the "Friends and Family" data set.

You will use the graph objects generated from the data set to evaluate and compare structural properties that can reveal the relationships between the nodes. These properties include the following:
- **Degree centrality:** Identify nodes with most interactions.
- **Closeness and betweenness centrality:** Identify important nodes within a graph, with respect to a specified measure.
- **Eigenvector centrality:** Identify important nodes using a measure of a node that is estimated through transference of that measure from other connected nodes.

You will also start exploring indications of subgraph relationships
by evaluating the tendency of nodes within a graph to form tight-knit groups. In addition, the notebook also engages with the concept of small-world networks, which is used to characterise social networks, power grids, and other networks with unique properties of regional specialization with efficient information transfer. These networks exhibit high clustering coefficients, but have small characteristic path lengths, like random graphs.

**List of exercises:**
- **Exercise 1:** Compute number of call interactions between a pair of nodes.
- **Exercise 2:** Evaluate structure qualitatively in a graph based on visualization.
- **Exercise 3:** Create a graph object using the SMS data set.
- **Exercise [Advanced] 4:** Compare the centrality structural properties evaluated on a graph.
- **Exercise 5:** Describe the effect on the average clustering coefficient when nodes of lower degree are removed.
- **Exercise 6:** List the two criteria of a small-world network.
- **Exercise 7:** Identify small-world networks, given the values for the characteristic path length and clustering coefficient.

# Notebook 3: Finding connected components using  clustering
> **Notebook goal**: Use hierarchical clustering, modularity maximization, and spectral graph partitioning to find connected components.

Community detection is an important task in social network analysis. The idea behind it is to identify groups of people who share a common interest, based on the assumption that these people tend to link to each other more than to the rest of the network. Specifically, real-world networks exhibit clustering behavior that can be observed in the graph representation of these networks by the formation of clusters or partitions. These groups of nodes on a graph (clusters) correspond to communities that share common properties, or have a common role in the system under study.

**List of exercises:**
- **Exercise 1**: Understanding hierarchical clustering.

- **Exercise 2 [Advanced]**: Interpreting the results of hierarchical clustering.

- **Exercise 3 [Advanced]**: Summarizing clustering results based on modularity maximization and spectral graph partitioning.

# Notebook 4: Graph signal processing
> **Notebook goal:** Evaluate graph signal processing.

Graphs not only capture relationship between nodes, but also information about the nodes. The data on these graphs can be visualized as a finite collection of samples, with one sample at each vertex in the graph, and each such sample described by a scalar value. The collection of these scalar samples, defined on each vertex of a graph, is referred to as a graph signal. Graph signal processing is a generalization of the classical signal processing framework in the graph spectral domain.

You will be introduced to this emerging field by reviewing a simple example demonstrating a network of temperature sensors. As such, you will not be required to complete any exercises in this notebook.

**Notebook Contributors**:
**Andre Voges**, Mieszko Manijak, **Gorden Jemwa**, Arek Stopczynski, **Xiaowen Dong**, and Yves-Alexandre de Montjoye.


text:
package org.elasticsearch.index.mapper;

import java.util.Objects;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.DelegatingAnalyzerWrapper;
import org.elasticsearch.index.analysis.FieldNameAnalyzer;

/** Hacky analyzer to dispatch per-thread based on the type of the current document being indexed, to look up the per-field Analyzer.  Once
 *  mappings are moved to the index level we can remove this. */
public class MapperAnalyzer extends DelegatingAnalyzerWrapper {

    private final MapperService mapperService;

    /** Which type this thread is currently indexing. */
    private final ThreadLocal<String> threadTypes = new ThreadLocal<>();

    public MapperAnalyzer(MapperService mapperService) {
        super(Analyzer.PER_FIELD_REUSE_STRATEGY);
        this.mapperService = mapperService;
    }

    /** Any thread that is about to use this analyzer for indexing must first set the type by calling this. */
    public void setType(String type) {
        threadTypes.set(type);
    }

    @Override
    protected Analyzer getWrappedAnalyzer(String fieldName) {
        // First get the FieldNameAnalyzer from the type, then ask it for the right analyzer for this field, or the default index analyzer:
        return ((FieldNameAnalyzer) mapperService.documentMapper(threadTypes.get()).mappers().indexAnalyzer()).getWrappedAnalyzer(fieldName);
    }
}


text:
package com.liveramp.kafka_service.integration_tests;

import java.util.Properties;

import com.google.gson.Gson;

import com.liveramp.kafka_service.producer.StringProducer;
import com.liveramp.kafka_service.producer.config.ProducerConfigBuilder;

public class ProducerStressTest {

  private final StringProducer producer;

  public ProducerStressTest(Properties properties) {
    this.producer = new StringProducer(properties);
  }

  public static void main(String[] args) {
    ProducerConfigBuilder builder = new ProducerConfigBuilder("integration-producer");
    builder.addBroker("s2s-data-syncer00", 9092);
    builder.addBroker("s2s-data-syncer01", 9092);
    builder.addBroker("s2s-data-syncer02", 9092);
    builder.addBroker("s2s-data-syncer03", 9092);
    builder.addBroker("s2s-data-syncer04", 9092);

    Gson gson = new Gson();
    gson.
  }

}


text:
from neutron_lib.api import converters
from neutron_lib import constants
from neutron_lib import exceptions as nexception

from neutron._i18n import _
from neutron.api import extensions
from neutron.api.v2 import attributes as attr

# Extra Routes Exceptions
class InvalidRoutes(nexception.InvalidInput):
    message = _("Invalid format for routes: %(routes)s, %(reason)s")

class RouterInterfaceInUseByRoute(nexception.InUse):
    message = _("Router interface for subnet %(subnet_id)s on router "
                "%(router_id)s cannot be deleted, as it is required "
                "by one or more routes.")

class RoutesExhausted(nexception.BadRequest):
    message = _("Unable to complete operation for %(router_id)s. "
                "The number of routes exceeds the maximum %(quota)s.")

# Attribute Map
EXTENDED_ATTRIBUTES_2_0 = {
    'routers': {
        'routes': {'allow_post': False, 'allow_put': True,
                   'validate': {'type:hostroutes': None},
                   'convert_to': converters.convert_none_to_empty_list,
                   'is_visible': True,
                   'default': constants.ATTR_NOT_SPECIFIED},
    }
}

class Extraroute(extensions.ExtensionDescriptor):

    @classmethod
    def get_name(cls):
        return "Neutron Extra Route"

    @classmethod
    def get_alias(cls):
        return "extraroute"

    @classmethod
    def get_description(cls):
        return "Extra routes configuration for L3 router"

    @classmethod
    def get_updated(cls):
        return "2013-02-01T10:00:00-00:00"

    def get_extended_resources(self, version):
        if version == "2.0":
            attr.PLURALS.update({'routes': 'route'})
            return EXTENDED_ATTRIBUTES_2_0
        else:
            return {}


text:
// General info: http://doc.winnowtag.org/open-source
// Source code repository: http://github.com/winnowtag
// Questions and feedback: contact@winnowtag.org
//
// Copyright (c) 2007-2011 The Kaphan Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

// contact@winnowtag.org

#include <pthread.h>
#include <config.h>
#include <stdlib.h>
#include <getopt.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <json/json.h>
#include "logging.h"
#include "classification_engine.h"
#include "httpd.h"
#include "misc.h"
#include "fetch_url.h"
#include "xml_error_functions.h"

#define DEFAULT_LOG_FILE "classifier.log"
#define DEFAULT_PID_FILE "classifier.pid"
#define DEFAULT_DB_FILE "classifier.db"
#define DEFAULT_CACHE_UPDATE_WAIT_TIME 60
#define DEFAULT_LOAD_ITEMS_SINCE 30
#define DEFAULT_MIN_TOKENS 50

#define PID_VAL 512
#define DB_VAL  513
#define CREATE_DB_VAL 514
#define CACHE_UPDATE_WAIT_TIME_VAL 515
#define LOAD_ITEMS_SINCE_VAL 516
#define MIN_TOKENS_VAL 517
#define PERFORMANCE_LOG_FILE_VAL 519
#define TAG_INDEX_VAL 520

#define SHORT_OPTS "hvdo:t:n:p:a:c:"
#define USAGE "Usage: classifier [-dvh] [-o LOGFILE] [--db DATABASE_FILE] [--pid PIDFILE]  [--create-db]\n"

static ItemCacheOptions item_cache_options;
static ItemCache *item_cache;
static Credentials classifier_credentials = {NULL, NULL};
static Credentials item_cache_credentials = {NULL, NULL};
static Credentials classification_credentials = {NULL, NULL};
static TaggerCacheOptions tagger_cache_options = {NULL, &classifier_credentials};
static TaggerCache *tagger_cache;
static ClassificationEngineOptions ce_options = {1, 0.0, NULL, &classifier_credentials};
static ClassificationEngine *engine;
static Httpd *httpd;
static HttpConfig http_config = {8080, NULL, &item_cache_credentials, &classification_credentials};

static void parse_credential(struct json_object * credentials, Credentials * target, const char * role) {
  struct json_object *role_credentials = NULL;

  if ((role_credentials = json_object_object_get(credentials, role))) {
    struct json_object * access_id_json = json_object_object_get(role_credentials, "access_id");
    struct json_object * secret_json = json_object_object_get(role_credentials, "secret_key");

    if (access_id_json && secret_json &&
            json_object_is_type(access_id_json, json_type_string) &&
            json_object_is_type(secret_json, json_type_string)) {
      target->access_id = strdup(json_object_get_string(access_id_json));
      target->secret_key = strdup(json_object_get_string(secret_json));
      info("Credentials '%s:XXXX' supplied for role %s", target->access_id, role);
    } else {
      fprintf(stderr, "Bad credentials format for %s. 'access_id' and 'secret_key' properties required\n");
      exit(1);
    }
  } else {
    info("No credentials supplied for role '%s'.", role);
  }
}

static void parse_credentials(const char * credentials_file) {
  struct json_object *credentials_json = json_object_from_file(credentials_file);

  if (is_error(credentials_json)) {
    fprintf(stderr, "Error parsing json credentials in %s", credentials_file);
    exit(1);
  } else {
    parse_credential(credentials_json, &item_cache_credentials, "item_cache");
    parse_credential(credentials_json, &classification_credentials, "classification");
    parse_credential(credentials_json, &classifier_credentials, "classifier");
    json_object_put(credentials_json);
  }
}

static void printHelp(void) {
  printf("This is the Peerwork classifier.\n\n");
  printf("Usage: classifier [OPTIONS]\n\n");
  printf(" General Options\n");
  printf("    -d               runs as a daemon\n");
  printf("    -v, --version    prints version information\n");
  printf("    -h, --help       prints this help text\n");
  printf("    -o, --log-file FILE\n");
  printf("                     location of the file to write log messages to\n");
  printf("                     Default: %s\n", DEFAULT_LOG_FILE);
  printf("        --pid FILE   location to write the pid to when running as a daemon\n");
  printf("                     Default: %s\n\n", DEFAULT_PID_FILE);

  printf(" Classification Options:\n");
  printf("    -n, --worker-threads N\n");
  printf("                     number of threads for processing jobs\n");
  printf("                     Default: 1\n");
  printf("    -t, --positive-threshold N\n");
  printf("                     probability threshold for considering a tag to be\n");
  printf("                     applied to and item\n");
  printf("                     Default: 0\n");
  printf("        --performance-log FILE\n");
  printf("                     location of the file in which to write job timings\n\n");
  printf("        --tag-index URL\n");
  printf("                     URL which provides an index of the tags to classify\n\n");

  printf(" Item Cache Options:\n");
  printf("        --db FILE    location of the item cache database file\n");
  printf("        --create     if provide the classifier with create the database at\n");
  printf("                     --db and exit\n");
  printf("        --cache-update-wait-time N\n");
  printf("                     number of seconds to wait after a cache update\n");
  printf("                     before spawning classification jobs\n");
  printf("                     Default: %i seconds\n", DEFAULT_CACHE_UPDATE_WAIT_TIME);
  printf("        --load-items-since N\n");
  printf("                     how many days back to load items from the item cache\n");
  printf("                     Default: %i days\n", DEFAULT_LOAD_ITEMS_SINCE);
  printf("        --min-tokens N\n");
  printf("                     the minimum number of tokens an item requires to be\n");
  printf("                     classified\n\n");

  printf(" HTTP Options:\n");
  printf("    -p, --port N     the port to run the HTTP server on\n");
  printf("    -a, --allowed_ip IP_ADDRESS\n");
  printf("                     An IP address to allow to make HTTP requests\n");
  printf("                     Default: any\n\n");
}

volatile sig_atomic_t termination_in_progress = 0;

void termination_handler(int sig) {
  if (termination_in_progress) {
    raise(sig);
  } else {
    termination_in_progress = 1;
    fprintf(stderr, "Terminating classifier...\n");

    if (httpd) {
      fprintf(stderr, "\tShutting down httpd.\n");
      httpd_stop(httpd);
    }

    if (engine) {
      fprintf(stderr, "\tShutting down engine.\n");
      ce_stop(engine);
      free_classification_engine(engine);
    }

    if (tagger_cache) {
      fprintf(stderr, "\tClosing tagger cache\n");
      free_tagger_cache(tagger_cache);
    }

    if (item_cache) {
      fprintf(stderr, "\tClosing database.\n");
      free_item_cache(item_cache);
    }

    fprintf(stderr, "Complete.\n");
    exit(sig);
  }
}

static void _daemonize(const char * pid_file) {
  int pid, sid;
  pid = fork();

  if (pid < 0) {
    exit(EXIT_FAILURE);
  } else if (pid > 0) {
    if (pid_file) {
      FILE *pidout = fopen(pid_file, "w");
      if (pidout) {
        fprintf(pidout, "%i", pid);
        fclose(pidout);
      } else {
        fprintf(stderr, "Could not open pid file %s: %s", pid_file, strerror(errno));
      }
    }
    // exit the foreground process
    exit(EXIT_SUCCESS);
  }

  umask(0);

  sid = setsid();
  if (sid < 0) {
    fprintf(stderr, "setsid failed: %s", strerror(errno));
    exit(EXIT_FAILURE);
  }

  if (chdir("/") < 0) {
    fprintf(stderr, "chdir(\"/\") failed: %s", strerror(errno));
    exit(EXIT_FAILURE);
  }
}

static int start_classifier(const char * db_file) {
  SET_XML_ERROR_HANDLERS;

  if (CLASSIFIER_OK != item_cache_create(&item_cache, db_file, &item_cache_options)) {
    fprintf(stderr, "Error opening classifier database file at %s: %s\n", db_file, item_cache_errmsg(item_cache));
    free_item_cache(item_cache);
    return EXIT_FAILURE;
  } else {
    item_cache_load(item_cache);
    item_cache_start_cache_updater(item_cache);
    item_cache_start_purger(item_cache, 60 * 60 * 24);

    tagger_cache = create_tagger_cache(item_cache, &tagger_cache_options);
    tagger_cache->tag_retriever = &fetch_url;
    tagger_cache->tag_index_retriever = &fetch_url;

    info("Fetching tag index for the first time...");
    Array *tags = NULL;
    char *errmsg = NULL;
    int rc = fetch_tags(tagger_cache, &tags, &errmsg);
    if (TAG_INDEX_OK == rc) {
      info("Fetched %i tags from %s", tags->size, tagger_cache_options.tag_index_url);
    } else {
      error("Error fetching tag index: %s", errmsg);
      free(errmsg);
    }

    engine = create_classification_engine(item_cache, tagger_cache, &ce_options);
    httpd = httpd_start(&http_config, engine, item_cache, tagger_cache);
    ce_run(engine);
    return EXIT_SUCCESS;
  }
}

int main(int argc, char **argv) {
  int create_database = false;
  int daemonize = false;
  char *log_file = DEFAULT_LOG_FILE;
  char *pid_file = DEFAULT_PID_FILE;
  char *db_file = DEFAULT_DB_FILE;
  char *credentials_file = NULL;
  char real_log_file[MAXPATHLEN];
  char real_db_file[MAXPATHLEN];
  char real_credentials_file[MAXPATHLEN];
  item_cache_options.cache_update_wait_time = DEFAULT_CACHE_UPDATE_WAIT_TIME;
  item_cache_options.load_items_since = DEFAULT_LOAD_ITEMS_SINCE;
  item_cache_options.min_tokens = DEFAULT_MIN_TOKENS;

  int longindex;
  int opt;
  static struct option long_options[] = {
      {"version", no_argument, 0, 'v'},
      {"help", no_argument, 0, 'h'},

      {"log-file", required_argument, 0, 'o'},
      {"pid", required_argument, 0, PID_VAL},
      {"db", required_argument, 0, DB_VAL},
      {"create-db", no_argument, 0, CREATE_DB_VAL},

      {"cache-update-wait-time", required_argument, 0, CACHE_UPDATE_WAIT_TIME_VAL},
      {"load-items-since", required_argument, 0, LOAD_ITEMS_SINCE_VAL},
      {"min-tokens", required_argument, 0, MIN_TOKENS_VAL},

      {"worker-threads", required_argument, 0, 'n'},
      {"positive-threshold", required_argument, 0, 't'},
      {"performance-log", required_argument, 0, PERFORMANCE_LOG_FILE_VAL},

      {"port", required_argument, 0, 'p'},
      {"allowed_ip", required_argument, 0, 'a'},

      {"credentials", required_argument, 0, 'c'},

      {"tag-index", required_argument, 0, TAG_INDEX_VAL},

      {0, 0, 0, 0}
  };

  while (-1 != (opt = getopt_long(argc, argv, SHORT_OPTS, long_options, &longindex))) {
    switch (opt) {
      case 'o':
        log_file = optarg;
        break;
      case PID_VAL:
        pid_file = optarg;
        break;
      case DB_VAL:
        db_file = optarg;
        break;
      case CREATE_DB_VAL:
        create_database = true;
        break;
      case 'd':
        daemonize = true;
        break;

      /* Item Cache Options */
      case CACHE_UPDATE_WAIT_TIME_VAL:
        item_cache_options.cache_update_wait_time = strtol(optarg, NULL, 10);
        break;
      case LOAD_ITEMS_SINCE_VAL:
        item_cache_options.load_items_since = strtol(optarg, NULL, 10);
        break;
      case MIN_TOKENS_VAL:
        item_cache_options.min_tokens = strtol(optarg, NULL, 10);
        break;

      /* Classification Engine Options */
      case 'n': /* Number of worker threads */
        ce_options.worker_threads = strtol(optarg, NULL, 10);
        break;
      case 't': /* Positive threshold for classification */
        ce_options.positive_threshold = strtod(optarg, NULL);
        break;
      case PERFORMANCE_LOG_FILE_VAL:
        ce_options.performance_log = optarg;
        break;

      /* HTTP options */
      case 'p':
        http_config.port = strtol(optarg, NULL, 10);
        break;
      case 'a':
        http_config.allowed_ip = optarg;
        break;

      case 'c':
        credentials_file = optarg;
        break;

      /* Tagger Cache options */
      case TAG_INDEX_VAL:
        tagger_cache_options.tag_index_url = optarg;
        break;

      /* Common Options */
      case 'h':
        // TODO Add help
        printHelp();
        exit(0);
      case 'v':
        printf("%s\n", PACKAGE_STRING);
        exit(EXIT_SUCCESS);
        break;
      default:
        fprintf(stderr, USAGE);
        exit(EXIT_FAILURE);
      break;
    }
  }

  int rc = EXIT_SUCCESS;

  if (create_database) {
    char error[512];
    if (CLASSIFIER_OK != item_cache_initialize(db_file, error)) {
      fprintf(stderr, "%s\n", error);
      rc = EXIT_FAILURE;
    } else {
      fprintf(stderr, "Database successfully initialized at '%s'\n", db_file);
    }
  } else {
    if (create_file(log_file)) {
      fprintf(stderr, "Could not create %s: %s\n", log_file, strerror(errno));
      exit(EXIT_FAILURE);
    }

    if (NULL == realpath(log_file, real_log_file)) {
      fprintf(stderr, "Could not find %s: %s\n", real_log_file, strerror(errno));
      exit(EXIT_FAILURE);
    }

    if (NULL == realpath(db_file, real_db_file)) {
      fprintf(stderr, "Could not find %s: %s\n", real_db_file, strerror(errno));
      exit(EXIT_FAILURE);
    }

    if (credentials_file && NULL == realpath(credentials_file, real_credentials_file)) {
      fprintf(stderr, "Could not find %s: %s\n", real_credentials_file, strerror(errno));
      exit(EXIT_FAILURE);
    }

    if (daemonize) {
      _daemonize(pid_file);
    }

    if (signal(SIGINT, termination_handler) == SIG_IGN)  signal(SIGINT, SIG_IGN);
    if (signal(SIGHUP, termination_handler) == SIG_IGN)  signal(SIGHUP, SIG_IGN);
    if (signal(SIGTERM, termination_handler) == SIG_IGN) signal(SIGTERM, SIG_IGN);

    initialize_logging(real_log_file);

    if (credentials_file) {
      parse_credentials(real_credentials_file);
    }

    rc = start_classifier(real_db_file);
  }

  return rc;
}


text:
ACCEPTED

#### According to
IRMNG Homonym List

#### Published in
Ann. Mo. bot. Gdn 23: 562 (1936)

#### Original name
Arborella Zebrowski, 1936

### Remarks
null


text:
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def __unicode__(self):
        return u'val:%s'%(self.val,)
    def __str__(self):
        return self.__unicode__().encode('utf-8')
    @staticmethod
    def array2list(a):
        head, tail = None, None
        for i in a:
            if not head:
                head = ListNode(i)
                tail = head
            else:
                node = ListNode(i)
                tail.next = node
                tail = node
        return head

    def trace(self):
        node = self
        while node:
            print node.val,'->',
            node = node.next
        print 'end'


text:
namespace {
bool IsSingleShotRig(const map::RigInstance* rig_instance,
                     const map::RigCamera* rig_camera) {
  const bool has_identity_rig_camera = rig_camera->pose.IsIdentity();
  const bool is_single_shot_instance = rig_instance->NumberOfShots() == 1;
  return has_identity_rig_camera && is_single_shot_instance;
}
}  // namespace

namespace map {

Shot::Shot(const ShotId& shot_id, const geometry::Camera* const shot_camera,
           RigInstance* rig_instance, RigCamera* rig_camera,
           const geometry::Pose& pose)
    : id_(shot_id),
      pose_(std::make_unique<geometry::Pose>(pose)),
      rig_instance_(rig_instance),
      rig_camera_(rig_camera),
      shot_camera_(shot_camera) {
  rig_instance_->AddShot(rig_camera_, this);
  rig_instance_->UpdateInstancePoseWithShot(shot_id, pose);
}

Shot::Shot(const ShotId& shot_id, const geometry::Camera* const shot_camera,
           RigInstance* rig_instance, RigCamera* rig_camera)
    : id_(shot_id),
      pose_(std::make_unique<geometry::Pose>(geometry::Pose())),
      rig_instance_(rig_instance),
      rig_camera_(rig_camera),
      shot_camera_(shot_camera) {
  rig_instance_->AddShot(rig_camera_, this);
}

Shot::Shot(const ShotId& shot_id, const geometry::Camera& shot_camera,
           const geometry::Pose& pose)
    : id_(shot_id),
      pose_(std::make_unique<geometry::Pose>(pose)),
      own_rig_instance_(map::RigInstance(shot_id)),
      own_rig_camera_(map::RigCamera(geometry::Pose(), shot_id)),
      rig_instance_(&own_rig_instance_.Value()),
      rig_camera_(&own_rig_camera_.Value()),
      own_camera_(shot_camera),
      shot_camera_(&own_camera_.Value()) {
  rig_instance_->AddShot(rig_camera_, this);
  rig_instance_->SetPose(pose);
}

bool Shot::IsInRig() const { return true; }

void Shot::SetRig(RigInstance* rig_instance, RigCamera* rig_camera) {
  rig_instance_ = rig_instance;
  rig_camera_ = rig_camera;
  pose_ = std::make_unique<geometry::PoseImmutable>(*pose_);
}

const RigInstanceId& Shot::GetRigInstanceId() const {
  return rig_instance_->id;
}

const RigCameraId& Shot::GetRigCameraId() const { return rig_camera_->id; }

void ShotMeasurements::Set(const ShotMeasurements& other) {
  if (other.capture_time_.HasValue()) {
    capture_time_.SetValue(other.capture_time_.Value());
  } else {
    capture_time_.Reset();
  }
  if (other.gps_position_.HasValue()) {
    gps_position_.SetValue(other.gps_position_.Value());
  } else {
    gps_position_.Reset();
  }
  if (other.gps_accuracy_.HasValue()) {
    gps_accuracy_.SetValue(other.gps_accuracy_.Value());
  } else {
    gps_accuracy_.Reset();
  }
  if (other.opk_angles_.HasValue()) {
    opk_angles_.SetValue(other.opk_angles_.Value());
  } else {
    opk_angles_.Reset();
  }
  if (other.opk_accuracy_.HasValue()) {
    opk_accuracy_.SetValue(other.opk_accuracy_.Value());
  } else {
    opk_accuracy_.Reset();
  }
  if (other.compass_accuracy_.HasValue()) {
    compass_accuracy_.SetValue(other.compass_accuracy_.Value());
  } else {
    compass_accuracy_.Reset();
  }

  if (other.compass_angle_.HasValue()) {
    compass_angle_.SetValue(other.compass_angle_.Value());
  } else {
    compass_angle_.Reset();
  }
  if (other.gravity_down_.HasValue()) {
    gravity_down_.SetValue(other.gravity_down_.Value());
  } else {
    gravity_down_.Reset();
  }
  if (other.orientation_.HasValue()) {
    orientation_.SetValue(other.orientation_.Value());
  } else {
    orientation_.Reset();
  }
  if (other.sequence_key_.HasValue()) {
    sequence_key_.SetValue(other.sequence_key_.Value());
  } else {
    sequence_key_.Reset();
  }

  // Copy the attributes
  attributes_ = other.GetAttributes();
}

void Shot::RemoveLandmarkObservation(const FeatureId id) {
  const auto find_feature = landmark_id_.find(id);
  if (find_feature == landmark_id_.end()) {
    throw std::runtime_error("Can't find Feature ID " + std::to_string(id) +
                             " in Shot " + this->id_);
  }
  auto* lm = find_feature->second;
  landmark_id_.erase(id);
  landmark_observations_.erase(lm);
}

void Shot::SetPose(const geometry::Pose& pose) {
  if (!IsSingleShotRig(rig_instance_, rig_camera_)) {
    throw std::runtime_error(
        "Can't set the pose of Shot belonging to a RigInstance");
  } else {
    rig_instance_->SetPose(pose);
  }
  *pose_ = pose;
}

geometry::Pose Shot::GetPoseInRig() const {
  // pose(shot) = pose(rig_camera)*pose(instance)
  const auto& pose_instance = rig_instance_->GetPose();
  const auto& rig_camera_pose = rig_camera_->pose;
  return rig_camera_pose.Compose(pose_instance);
}

const geometry::Pose* const Shot::GetPose() const {
  *pose_ = GetPoseInRig();
  if (IsSingleShotRig(rig_instance_, rig_camera_)) {
    return &rig_instance_->GetPose();
  }
  return pose_.get();
}

geometry::Pose* const Shot::GetPose() {
  *pose_ = GetPoseInRig();
  if (IsSingleShotRig(rig_instance_, rig_camera_)) {
    return &rig_instance_->GetPose();
  }
  return pose_.get();
}

Vec2d Shot::Project(const Vec3d& global_pos) const {
  return shot_camera_->Project(GetPose()->RotationWorldToCamera() * global_pos +
                               GetPose()->TranslationWorldToCamera());
}

MatX2d Shot::ProjectMany(const MatX3d& points) const {
  MatX2d projected(points.rows(), 2);
  for (int i = 0; i < points.rows(); ++i) {
    projected.row(i) = Project(points.row(i));
  }
  return projected;
}

Vec3d Shot::Bearing(const Vec2d& point) const {
  return GetPose()->RotationCameraToWorld() * shot_camera_->Bearing(point);
}

MatX3d Shot::BearingMany(const MatX2d& points) const {
  MatX3d bearings(points.rows(), 3);
  for (int i = 0; i < points.rows(); ++i) {
    bearings.row(i) = Bearing(points.row(i));
  }
  return bearings;
}
}  // namespace map


text:
[![Stories in Ready](https://badge.waffle.io/ko2ic/xcode-singleton-templates.png?label=ready&title=Ready)](https://waffle.io/ko2ic/xcode-singleton-templates)
Xcode-Singleton-Templates
===============
These are templates of Singleton class and the TestCase.
Code shown below is a part of testcase template which will pass.
```
    KO2Abc* a = [KO2Abc sharedInstance];
    KO2Abc* b = [[KO2Abc alloc] init];
    KO2Abc* c = [KO2Abc allocWithZone:nil];
    KO2Abc* d = [KO2Abc new];
    KO2Abc* e = [[KO2Abc alloc] copy];
    KO2Abc* f = [[KO2Abc alloc] mutableCopy];

    XCTAssertEqualObjects(a, b);
    XCTAssertEqualObjects(a, c);
    XCTAssertEqualObjects(a, d);
    XCTAssertEqualObjects(a, e);
    XCTAssertEqualObjects(a, f);
```

# install #

If you are using Alcatraz, it will be able to use in there.
https://github.com/supermarin/Alcatraz

If you aren't using Alcatraz, it is as follows.
* ```git clone https://github.com/ko2ic/Xcode-Singleton-Templates.git```
* ```cd Xcode-Singleton-Templates ```
* ```./install-templates.sh```

# uninstall #
* ```./uninstall-templates.sh```

# Usage #
* When you create a new file, you can select singleton as follows..
![ScreenShot](https://raw.github.com/ko2ic/ImageRepository/master/Xcode-Singleton-Templates/screenshot1.png)

* In case of the testcase template, you can select Test Library, which Kiwi or XCTest or SenTest.
![ScreenShot](https://raw.github.com/ko2ic/ImageRepository/master/Xcode-Singleton-Templates/screenshot2.png)


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Reflection;
using AbstractFactory;

namespace Main
{
    class Program
    {
        // Main処理
        static void Main(string[] args)
        {

            if (args.Length != 2)
            {
                //第1引数:アセンブリ名 第2引数:名前空間.クラス名
                Console.WriteLine("Example 1: C# AbstractFactory ListFactory ListFactory.ListFactory");
                Console.WriteLine("Example 2: C# AbstractFactory ListFactory.TableFactory");
                Environment.Exit(0);
            }

            Factory AbstractFactory = Factory.GetFactory(args[0], args[1]);
            Link asahi = AbstractFactory.CreateLink("朝日新聞", "http://www.asashi.com/");
            Link yomiuri = AbstractFactory.CreateLink("読売新聞", "http://www.yomiuri.co.jp/");

            Link usYahoo = AbstractFactory.CreateLink("Yahoo!", "http://www.yahoo.com/");
            Link jpYahoo = AbstractFactory.CreateLink("Yahoo!Japan", "http://www.yahoo.co.jp/");
            Link excite = AbstractFactory.CreateLink("Excite", "http://www.excite.co.jp/");
            Link google = AbstractFactory.CreateLink("Google", "http://www.google.com/");

            Tray traynews = AbstractFactory.CreateTray("新聞");
            traynews.Add(asahi);
            traynews.Add(yomiuri);

            Tray trayyahoo = AbstractFactory.CreateTray("Yahoo!");
            trayyahoo.Add(usYahoo);
            trayyahoo.Add(jpYahoo);

            Tray traysearch = AbstractFactory.CreateTray("サーチエンジン");
            traysearch.Add(trayyahoo);
            traysearch.Add(excite);
            traysearch.Add(google);

            Page page = AbstractFactory.CreatePage("LinkPage", "AbstractFactory Sample");
            page.Add(traynews);
            page.Add(traysearch);
            page.Output(args[1]);

            // 実行が一瞬で終わって確認ため、キーの入力を待ちます
            Console.ReadLine();
        }
    }
}


text:
ActiveAdmin.setup do |config|
  config.authentication_method = nil #:authenticate_admin_user!
  config.current_user_method = nil #:current_admin_user
  config.logout_link_path = :destroy_admin_user_session_path
  config.batch_actions = true
end


text:
function [bits_array, next_seed] = ...
    prop_rng_new(the_seed, Nbits, Nsweeps, lfsr_mask)
    % the_seed  The seed you gave the propeller
    % Nbits     The number of bits per modulation you requestion
    % Nsweeps   The number of DIFFERENT sweeps you wanted
    % lfsr_mask The LFSR_mask you supplied
    %
    % This code is supposed to emulate the random number generator in the
    % propeller to reduce talking the amount of communication between the
    % propeller and the computer (sending the huge matrix takes a really long
    % time
    %
    %
    % The code makes no attempt at being fast but literally writes each line of
    % assembly as a few lines of matlab

    % Proeller source code
    % :rnd                    min     x,#1                    '?var/var?
    %                         mov     y,#32
    %                         mov     a,#%10111
    %         if_nz           ror     a,#1
    % :rndlp                  test    x,a             wc
    %         if_z            rcr     x,#1
    %         if_nz           rcl     x,#1
    %                         djnz    y,#:rndlp       wc      'c=0
    %                         jmp     #:stack

    if nargin < 1; the_seed = 1; end
    if nargin < 2; Nbits = 32; end
    if nargin < 3 ; Nsweeps = 1; end
    if nargin < 4; lfsr_mask = '8000000B'; end

    lfsr_mask_bin = hex2dec(lfsr_mask);

    the_seed = uint32(the_seed);

    bits_array = zeros(32 + (Nbits*Nsweeps), 1);

    bits_array(1:32) = (dec2bin(the_seed, 32) == '1');

    locations_look = find(dec2bin(lfsr_mask_bin) == '1');
    for i = 1:(Nbits*Nsweeps)
      bits_array(i+32) = ...
        mod(sum(bits_array(locations_look+i-1)), 2);
    end

    bits_array(1:32) = [];

    next_seed = char(bits_array(end-31:end) + '0')';
    next_seed = bin2dec(next_seed);
    bits_array = reshape(bits_array, Nbits, []);

    %{
    a = dec2bin(lfsr_mask);
    a(:) = '0';
    a(bits_array(1:32, 1) == 1) = '1';
    disp(['First 32 bits are = 0x', dec2hex(bin2dec(a))])
    %}
end

%{
Copyright (c) 2016, Mark Harfouche
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Mark Harfouche nor the
      names of his/her 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 Mark Harfouche 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.
%}


text:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
using System;
using System.Linq;
using LitJson;

//Stores all the world information -- This is what is going to get loaded from online
public class WorldInformation : MonoBehaviour {
    public static string CurrentArea { get; set; }
    public static string UserID { get; set; }

    public static System.Random rnd = new System.Random();
    //paths
    //public static int[,] Edges = new int[10, 5] { { 2, 9, 0, 0, 0 }, { 1, 4, 0, 0, 0 }, { 4, 0, 0, 0, 0 }, { 2, 3, 5, 9, 0 }, { 4, 6, 7, 8, 0 }, { 5, 7, 0, 0, 0 }, { 5, 6, 0, 0, 0 }, { 5, 10, 0, 0, 0 }, { 1, 4, 10, 0, 0 }, { 8, 9, 0, 0, 0 } };
    public static int[,] Edges = new int[34, 5] { { 2, 3, 24, 34, 0 }, { 1, 3, 0, 0, 0 }, { 1, 2, 4, 0, 0 }, { 3, 5, 27, 0, 0 }, { 4, 6, 7, 0, 0 }, { 5, 7, 32, 33, 0 }, { 5, 6, 9, 10, 0 }, { 9, 11, 26, 0, 0 }, { 7, 8, 10, 11, 0 }, { 7, 9, 12, 13, 14 }, { 8, 9, 12, 29, 0 }, { 10, 11, 13, 0, 0 }, { 10, 12, 14, 0, 0 }, { 10, 13, 15, 0, 0 }, { 14, 16, 30, 0, 0 }, { 15, 17, 30, 31, 0 }, { 16, 18, 31, 0, 0 }, { 17, 19, 31, 0, 0 }, { 18, 20, 33, 0, 0 }, { 19, 21, 0, 0, 0 }, { 20, 22, 23, 0, 0 }, { 21, 23, 32, 33, 0 }, { 21, 22, 24, 25, 0 }, { 1, 23, 25, 34, 0 }, { 23, 24, 34, 0, 0 }, { 8, 27, 28, 0, 0 }, { 4, 26, 28, 0, 0 }, { 26, 27, 0, 0, 0 }, { 11, 0, 0, 0, 0 }, { 15, 16, 0, 0, 0 }, { 16, 17, 18, 0, 0 }, { 6, 22, 33, 0, 0 }, { 6, 19, 22, 32, 0 }, { 1, 24, 25, 0, 0 } };
    //total of 34 Areas

    private static string[] AreaNames = new string[34] { "Alnerwick", "Bardford", "Holden", "Ashborne", "Aramore", "Gilramore", "Tarmsworth", "Lancaster", "Shadowfen", "Jueht Fields", "Kiahs Grassland", "Cloud Prairie", "Strotyl Plateau", "Boa Valley", "Giant's Expanse", "Grasshopper Plains", "Mutolm Meadow", "Kicalt Fields", "Great Meadow", "Great Plains", "Sacred Grasslands", "Abandoned Fields", "Ruehn's Expanse", "Lazy Foot Gardens", "Gilivore Prairie", "Knife Range", "The Parched Fields", "The Angry Wilds", "The Red Sea", "Desert of Akrid", "Unresting Barrens", "Desolated Savanna", "The Sea of Fire", "The Wasteland" };
    //0-8 are cities, 9-25 are plains, 26-33 are deserts
    private static string[] AreaIDs = new string[34] { "000001", "000032", "000019", "000029", "000014", "000016", "000023", "000007", "000028", "000002", "000003", "000004", "000005", "000011", "000012", "000015", "000017", "000018", "000020", "000022", "000024", "000027", "000030", "000031", "000033", "000034", "000021", "000006", "000008", "000009", "000010", "000013", "000025", "000026" };
    // private static string[] KingNames = new string[9] {}

    private static string[] KingNames = new string[10] { "None", "Tonius Pisarvius", "Jer Kimothy III", "Wolfgang Tom", "Alexander Hero", "Vybihal the Tyrant", "Queen Narges", "King Trottier", "General 11:59 Submissions", "Prince Full Credit" };
    private string url = "http://tomaswolfgang.com/hansa361/GetWorldInformation.php";
    public static JsonData AreaData;

    public static List<Area> Areas { get; set; }
    public static Inventory shopInv = new Inventory();
    public static List<Quest> AvailableQuests { get; set; }
    public static string currentWorldID { get; set; }
    public static List<Kingdom> Kingdoms { get; set; }
    public static Quest CurrentQuest{ get; set; }
    public static int attacker { get; set; }
    public static Quest Control { get; set; }

    public static int DayCounter { get; set; }

    private static CreateNewWeapon WeaponCreator = new CreateNewWeapon();
    private static CreateNewEquipment EquipmentCreator = new CreateNewEquipment();
    private static CreateNewPotion PotionCreator = new CreateNewPotion();
    private static CreateNewQuest questCreator = new CreateNewQuest();
    private int areaNamer = 0;

    void Awake()
    {
        DontDestroyOnLoad(transform.gameObject);
    }

    public void initAreas()
    {
        Areas = new List<Area>();
        for (int i = 0; i < 34; i++)
        {
            Areas.Add(initArea());
        }

    }

    private void initKingdoms()
    {
        Kingdoms = new List<Kingdom>();
        for(int i = 0; i < 10; i++)
        {
            Kingdoms.Add(initKingdom(i));
        }
    }

    private Kingdom initKingdom(int i)
    {
        Kingdom newKingdom = new Kingdom();
        newKingdom.KingdomID = "00000"+(i);
        newKingdom.KingName = KingNames[i];
        return newKingdom;
    }

    private Area initArea()
    {
        //Gets this info from db
        //if it's a city then give it a name
        Area newArea = new Area();
        newArea.AreaID = AreaIDs[areaNamer];
        newArea.AreaName = AreaNames[areaNamer];
        if (areaNamer <= 8)
        {
            newArea.AreaType = Area.AreaTypes.City;
        }
        else if (areaNamer <= 25) newArea.AreaType = Area.AreaTypes.Plains;
        else newArea.AreaType = Area.AreaTypes.Desert;
        newArea.IconNumber = Int32.Parse(AreaIDs[areaNamer]);
        areaNamer++;
        return newArea;
    }

    private void printAreaInfo(Area a)
    {
        Debug.Log(a.AreaID + ". ------ . " + a.AreaName + ".---------." + a.AreaType.ToString()+".-------.Owned By:" + a.OwnedBy.KingdomID + "    -------   Enemy:" + a.BeingTakenOverBy.KingdomID);

    }

    private void printKingdomInfo(Kingdom a)
    {
        Debug.Log(a.KingdomID + " king id ----------- " + a.KingName + "King name");
    }

    public void StartWorld()
    {

        BaseCharacter test = CreateEnemy.returnEnemy(5);
        Debug.Log("Name: " + test.PlayerName + " --- str: " + test.Strength + " ---- int: " + test.Intellect + " --- agi: " + test.Agility + " --- def: " + test.Defense);
        Debug.Log(test.PlayerName);

        //currentWorldID = "000001";

        LoadInformation.LoadAllInformation();

        initKingdoms();
        initAreas();
        CurrentArea = "1";
        WWWForm form = new WWWForm();
        form.AddField("World", currentWorldID);
        WWW www = new WWW(url, form);
        StartCoroutine(goDoIt(www));
    }

    IEnumerator goDoIt(WWW www)
    {
        yield return www;
        //Debug.Log(www.text);
        AreaData = JsonMapper.ToObject(www.text);
        for (int i = 0; i < 34; i++)
        {
            //Debug.Log("area "+AreaData[i]["area_ID"].ToString()+" is owned by:"+AreaData[i]["owner_kingdom_ID"].ToString());
            Area holder = Areas.Find(x => String.Compare(x.AreaID, AreaData[i]["area_ID"].ToString()) == 0);
            //Debug.Log("Loading areaname: " + holder.AreaName);
            //Debug.Log("Owned by this kingdom!  " + Kingdoms.Find(x => String.Compare(x.KingdomID, AreaData[i]["owner_kingdom_ID"].ToString()) == 0).KingName);
            holder.OwnedBy = Kingdoms.Find(x => String.Compare(x.KingdomID, AreaData[i]["owner_kingdom_ID"].ToString()) == 0);
            holder.BeingTakenOverBy = Kingdoms.Find(x => String.Compare(x.KingdomID, AreaData[i]["enemy_kingdom_ID"].ToString()) == 0);
            holder.TakeOverCount = Int32.Parse(AreaData[i]["takeOverCount"].ToString());
            holder.DefendCount = Int32.Parse(AreaData[i]["DefendCount"].ToString());

        }
        //Areas.ForEach(printAreaInfo);
        initShopsAndQuests();
        SceneManager.LoadScene("test");
    }

    private void initShopsAndQuests()
    {
       AvailableQuests = new List<Quest>();
       LoadNewQuests();
       RenewShopInv();

    }

    //Day counter!

    public static void LoadNewQuests()
    {
        //Loads new quests for the quest keep

        for (int i = 0; i<3; i++)
        {
            //Debug.Log("Initiating quests in world info!");
            //Debug.Log("Is there a problem with this? " + questCreator.returnQuest().QuestName);
            AvailableQuests.Add(questCreator.returnQuest());
        }
    }

    // Use this for initialization
    public static void RenewShopInv()
    {

        //add to database!!!!!! -------------------------------------------------->>>>>>>>>>>>>>

        List<BaseWeapon> WArr = new List<BaseWeapon>();
        List<BasePotion> PArr = new List<BasePotion>();
        List<BaseEquipment> EArr = new List<BaseEquipment>();

        for(int i = 0; i<5; i++)
        {
            WArr.Add( WeaponCreator.returnWeapon());
            PArr.Add(PotionCreator.returnPotion());
            EArr.Add(EquipmentCreator.returnEquipment());
        }

        shopInv.Equipment = EArr;
        shopInv.Potions = PArr;
        shopInv.Weapons = WArr;

    }

    // Update is called once per frame
    void Update () {

	}
}


text:
var should = require("should")

describe("Test section 1", function() {
  it("Test 2", function() {
    should.exist({})
  })

})


text:
/**
 *
 */
package com.gemstone.gemfire.internal.cache;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.logging.log4j.Logger;

import com.gemstone.gemfire.CancelException;
import com.gemstone.gemfire.DataSerializer;
import com.gemstone.gemfire.cache.CommitIncompleteException;
import com.gemstone.gemfire.cache.RegionDestroyedException;
import com.gemstone.gemfire.cache.UnsupportedOperationInTransactionException;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.internal.DM;
import com.gemstone.gemfire.distributed.internal.DistributionManager;
import com.gemstone.gemfire.distributed.internal.DistributionMessage;
import com.gemstone.gemfire.distributed.internal.ReplyException;
import com.gemstone.gemfire.distributed.internal.ReplyMessage;
import com.gemstone.gemfire.distributed.internal.ReplyProcessor21;
import com.gemstone.gemfire.distributed.internal.ReplySender;
import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
import com.gemstone.gemfire.internal.Assert;
import com.gemstone.gemfire.internal.cache.TXEntryState.DistTxThinEntryState;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import com.gemstone.gemfire.internal.logging.LogService;
import com.gemstone.gemfire.internal.logging.log4j.LogMarker;

/**
 * @author vivekb
 *
 */
public class DistTXCommitMessage extends TXMessage {

  private static final Logger logger = LogService.getLogger();
  protected ArrayList<ArrayList<DistTxThinEntryState>> entryStateList = null;

  /** for deserialization */
  public DistTXCommitMessage() {
  }

  public DistTXCommitMessage(TXId txUniqId,
      InternalDistributedMember onBehalfOfClientMember,
      ReplyProcessor21 processor) {
    super(txUniqId.getUniqId(), onBehalfOfClientMember, processor);
  }

  @Override
  public int getDSFID() {
    return DISTTX_COMMIT_MESSAGE;
  }

  @Override
  protected boolean operateOnTx(TXId txId, DistributionManager dm)
      throws RemoteOperationException {
    if (logger.isDebugEnabled()) {
      logger.debug("DistTXCommitMessage.operateOnTx: Tx {}", txId);
    }

    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
    TXManagerImpl txMgr = cache.getTXMgr();
    final TXStateProxy txStateProxy = txMgr.getTXState();
    TXCommitMessage cmsg = null;
    try {
      // do the actual commit, only if it was not done before
      if (txMgr.isHostedTxRecentlyCompleted(txId)) {
        if (logger.isDebugEnabled()) {
          logger
              .debug(
                  "DistTXCommitMessage.operateOnTx: found a previously committed transaction:{}",
                  txId);
        }
        cmsg = txMgr.getRecentlyCompletedMessage(txId);
        if (txMgr.isExceptionToken(cmsg)) {
          throw txMgr.getExceptionForToken(cmsg, txId);
        }
      } else {
        // [DISTTX] TODO - Handle scenarios of no txState
        // if no TXState was created (e.g. due to only getEntry/size operations
        // that don't start remote TX) then ignore
        if (txStateProxy != null) {
          /*
           * [DISTTX] TODO See how other exceptions are caught and send on wire,
           * than throwing?
           *
           * This can be spared since it will be programming bug
           */
          if (!txStateProxy.isDistTx()
              || txStateProxy.isCreatedOnDistTxCoordinator()) {
            throw new UnsupportedOperationInTransactionException(
                LocalizedStrings.DISTTX_TX_EXPECTED.toLocalizedString(
                    "DistTXStateProxyImplOnDatanode", txStateProxy.getClass()
                        .getSimpleName()));
          }
          if (logger.isDebugEnabled()) {
            logger.debug("DistTXCommitMessage.operateOnTx Commiting {} "
                + " incoming entryEventList:{} coming from {} ", txId,
                DistTXStateProxyImplOnCoordinator
                    .printEntryEventList(this.entryStateList), this.getSender()
                    .getId());
          }

          // Set Member's ID to all entry states
          String memberID = this.getSender().getId();
          for (ArrayList<DistTxThinEntryState> esList : this.entryStateList) {
            for (DistTxThinEntryState es : esList) {
              es.setMemberID(memberID);
            }
          }

          ((DistTXStateProxyImplOnDatanode) txStateProxy)
              .populateDistTxEntryStates(this.entryStateList);
          txStateProxy.setCommitOnBehalfOfRemoteStub(true);

          txMgr.commit();

          cmsg = txStateProxy.getCommitMessage();
        }
      }
    } finally {
        txMgr.removeHostedTXState(txId);
    }
    DistTXCommitReplyMessage.send(getSender(), getProcessorId(), cmsg,
        getReplySender(dm));

    /*
     * return false so there isn't another reply
     */
    return false;
  }

  @Override
  public void fromData(DataInput in) throws IOException, ClassNotFoundException {
    super.fromData(in);
    this.entryStateList = DataSerializer.readArrayList(in);
  }

  @Override
  public void toData(DataOutput out) throws IOException {
    super.toData(out);
    DataSerializer.writeArrayList(entryStateList, out);
  }

  @Override
  public boolean isTransactionDistributed() {
    return true;
  }

  @Override
  public boolean canStartRemoteTransaction() {
    return true;
  }

  public void setEntryStateList(
      ArrayList<ArrayList<DistTxThinEntryState>> entryStateList) {
    this.entryStateList = entryStateList;
  }

  /**
   * This message is used for the reply to a Dist Tx Phase Two commit operation:
   * a commit from a stub to the tx host. This is the reply to a
   * {@link DistTXCommitMessage}.
   *
   */
  public static final class DistTXCommitReplyMessage extends
      ReplyMessage {
    private transient TXCommitMessage commitMessage;

    /**
     * Empty constructor to conform to DataSerializable interface
     */
    public DistTXCommitReplyMessage() {
    }

    public DistTXCommitReplyMessage(DataInput in) throws IOException,
        ClassNotFoundException {
      fromData(in);
    }

    private DistTXCommitReplyMessage(int processorId,
        TXCommitMessage val) {
      setProcessorId(processorId);
      this.commitMessage = val;
    }

    /** GetReplyMessages are always processed in-line */
    @Override
    public boolean getInlineProcess() {
      return true;
    }

    /**
     * Return the value from the get operation, serialize it bytes as late as
     * possible to avoid making un-neccesary byte[] copies. De-serialize those
     * same bytes as late as possible to avoid using precious threads (aka P2P
     * readers).
     *
     * @param recipient
     *          the origin VM that performed the get
     * @param processorId
     *          the processor on which the origin thread is waiting
     * @param val
     *          the raw value that will eventually be serialized
     * @param replySender
     *          distribution manager used to send the reply
     */
    public static void send(InternalDistributedMember recipient,
        int processorId, TXCommitMessage val, ReplySender replySender)
        throws RemoteOperationException {
      Assert.assertTrue(recipient != null,
          "DistTXCommitPhaseTwoReplyMessage NULL reply message");
      DistTXCommitReplyMessage m = new DistTXCommitReplyMessage(
          processorId, val);
      m.setRecipient(recipient);
      replySender.putOutgoing(m);
    }

    /**
     * Processes this message. This method is invoked by the receiver of the
     * message.
     *
     * @param dm
     *          the distribution manager that is processing the message.
     */
    @Override
    public void process(final DM dm, ReplyProcessor21 processor) {
      final long startTime = getTimestamp();
      if (logger.isTraceEnabled(LogMarker.DM)) {
        logger
            .trace(
                LogMarker.DM,
                "DistTXCommitPhaseTwoReplyMessage process invoking reply processor with processorId:{}",
                this.processorId);
      }

      if (processor == null) {
        if (logger.isTraceEnabled(LogMarker.DM)) {
          logger.trace(LogMarker.DM,
              "DistTXCommitPhaseTwoReplyMessage processor not found");
        }
        return;
      }
      processor.process(this);
    }

    @Override
    public int getDSFID() {
      return DISTTX_COMMIT_REPLY_MESSAGE;
    }

    @Override
    public void toData(DataOutput out) throws IOException {
      super.toData(out);
      DataSerializer.writeObject(commitMessage, out);
    }

    @Override
    public void fromData(DataInput in) throws IOException,
        ClassNotFoundException {
      super.fromData(in);
      this.commitMessage = (TXCommitMessage) DataSerializer.readObject(in);
    }

    @Override
    public String toString() {
      StringBuffer sb = new StringBuffer();
      sb.append("DistTXCommitPhaseTwoReplyMessage ").append("processorid=")
          .append(this.processorId).append(" reply to sender ")
          .append(this.getSender());
      return sb.toString();
    }

    public TXCommitMessage getCommitMessage() {
      // TODO Auto-generated method stub
      return commitMessage;
    }
  }

  /**
   * Reply processor which collects all CommitReplyExceptions for Dist Tx and emits
   * a detailed failure exception if problems occur
   *
   * @see TXCommitMessage.CommitReplyProcessor
   *
   * [DISTTX] TODO see if need ReliableReplyProcessor21? departed members?
   */
  public static final class DistTxCommitReplyProcessor extends ReplyProcessor21 {
    private HashMap<DistributedMember, DistTXCoordinatorInterface> msgMap;
    private Map<DistributedMember, TXCommitMessage> commitResponseMap;
    private transient TXId txIdent = null;

    public DistTxCommitReplyProcessor(TXId txUniqId, DM dm, Set initMembers,
        HashMap<DistributedMember, DistTXCoordinatorInterface> msgMap) {
      super(dm, initMembers);
      this.msgMap = msgMap;
      // [DISTTX] TODO Do we need synchronised map?
      this.commitResponseMap = Collections
          .synchronizedMap(new HashMap<DistributedMember, TXCommitMessage>());
      this.txIdent = txUniqId;
    }

    @Override
    public void process(DistributionMessage msg) {
      if (msg instanceof DistTXCommitReplyMessage) {
        DistTXCommitReplyMessage reply = (DistTXCommitReplyMessage) msg;
        this.commitResponseMap.put(reply.getSender(), reply.getCommitMessage());
      }
      super.process(msg);
    }

    public void waitForPrecommitCompletion() {
      try {
        waitForRepliesUninterruptibly();
      }
      catch (DistTxCommitExceptionCollectingException e) {
        e.handlePotentialCommitFailure(msgMap);
      }
    }

    @Override
    protected void processException(DistributionMessage msg,
        ReplyException ex) {
      if (msg instanceof ReplyMessage) {
        synchronized(this) {
          if (this.exception == null) {
            // Exception Container
            this.exception = new DistTxCommitExceptionCollectingException(txIdent);
          }
          DistTxCommitExceptionCollectingException cce = (DistTxCommitExceptionCollectingException) this.exception;
          if (ex instanceof CommitReplyException) {
            CommitReplyException cre = (CommitReplyException) ex;
            cce.addExceptionsFromMember(msg.getSender(), cre.getExceptions());
          } else {
            cce.addExceptionsFromMember(msg.getSender(), Collections.singleton(ex));
          }
        }
      }
    }

    @Override
    protected boolean stopBecauseOfExceptions() {
      return false;
    }

    public Set getCacheClosedMembers() {
      if (this.exception != null) {
        DistTxCommitExceptionCollectingException cce = (DistTxCommitExceptionCollectingException) this.exception;
        return cce.getCacheClosedMembers();
      } else {
        return Collections.EMPTY_SET;
      }
    }
    public Set getRegionDestroyedMembers(String regionFullPath) {
      if (this.exception != null) {
        DistTxCommitExceptionCollectingException cce = (DistTxCommitExceptionCollectingException) this.exception;
        return cce.getRegionDestroyedMembers(regionFullPath);
      } else {
        return Collections.EMPTY_SET;
      }
    }

    public Map<DistributedMember, TXCommitMessage> getCommitResponseMap() {
      return commitResponseMap;
    }
  }

  /**
   * An Exception that collects many remote CommitExceptions
   *
   * @see TXCommitMessage.CommitExceptionCollectingException
   */
  public static class DistTxCommitExceptionCollectingException extends
      ReplyException {
    private static final long serialVersionUID = -2681117727592137893L;
    /** Set of members that threw CacheClosedExceptions */
    private final Set<InternalDistributedMember> cacheExceptions;
    /** key=region path, value=Set of members */
    private final Map<String, Set<InternalDistributedMember>> regionExceptions;
    /** List of exceptions that were unexpected and caused the tx to fail */
    private final Map fatalExceptions;

    private final TXId id;

    /*
     * [DISTTX] TODO Actually handle exceptions like commit conflict, primary bucket moved, etc
     */
    public DistTxCommitExceptionCollectingException(TXId txIdent) {
      this.cacheExceptions = new HashSet<InternalDistributedMember>();
      this.regionExceptions = new HashMap<String, Set<InternalDistributedMember>>();
      this.fatalExceptions = new HashMap();
      this.id = txIdent;
    }

    /**
     * Determine if the commit processing was incomplete, if so throw a detailed
     * exception indicating the source of the problem
     *
     * @param msgMap
     */
    public void handlePotentialCommitFailure(
        HashMap<DistributedMember, DistTXCoordinatorInterface> msgMap) {
      if (fatalExceptions.size() > 0) {
        StringBuffer errorMessage = new StringBuffer(
            "Incomplete commit of transaction ").append(id).append(
            ".  Caused by the following exceptions: ");
        for (Iterator i = fatalExceptions.entrySet().iterator(); i.hasNext();) {
          Map.Entry me = (Map.Entry) i.next();
          DistributedMember mem = (DistributedMember) me.getKey();
          errorMessage.append(" From member: ").append(mem).append(" ");
          List exceptions = (List) me.getValue();
          for (Iterator ei = exceptions.iterator(); ei.hasNext();) {
            Exception e = (Exception) ei.next();
            errorMessage.append(e);
            for (StackTraceElement ste : e.getStackTrace()) {
              errorMessage.append("\n\tat ").append(ste);
            }
            if (ei.hasNext()) {
              errorMessage.append("\nAND\n");
            }
          }
          errorMessage.append(".");
        }
        throw new CommitIncompleteException(errorMessage.toString());
      }

      /* [DISTTX] TODO Not Sure if required */
      // Mark any persistent members as offline
      // handleClosedMembers(msgMap);
      // handleRegionDestroyed(msgMap);
    }

    public Set<InternalDistributedMember> getCacheClosedMembers() {
      return this.cacheExceptions;
    }

    public Set getRegionDestroyedMembers(String regionFullPath) {
      Set members = (Set) this.regionExceptions.get(regionFullPath);
      if (members == null) {
        members = Collections.EMPTY_SET;
      }
      return members;
    }

    /**
     * Protected by (this)
     *
     * @param member
     * @param exceptions
     */
    public void addExceptionsFromMember(InternalDistributedMember member,
        Set exceptions) {
      for (Iterator iter = exceptions.iterator(); iter.hasNext();) {
        Exception ex = (Exception) iter.next();
        if (ex instanceof CancelException) {
          cacheExceptions.add(member);
        } else if (ex instanceof RegionDestroyedException) {
          String r = ((RegionDestroyedException) ex).getRegionFullPath();
          Set<InternalDistributedMember> members = regionExceptions.get(r);
          if (members == null) {
            members = new HashSet<InternalDistributedMember>();
            regionExceptions.put(r, members);
          }
          members.add(member);
        } else {
          List el = (List) this.fatalExceptions.get(member);
          if (el == null) {
            el = new ArrayList(2);
            this.fatalExceptions.put(member, el);
          }
          el.add(ex);
        }
      }
    }
  }
}


text:
require 'securerandom'

Synvert::Rewriter.new 'rails', 'upgrade_4_0_to_4_1' do
  description <<-EOF
It upgrades rails from 4.0 to 4.1.

1. config/secrets.yml
    Create a secrets.yml file in your config folder
    Copy the existing secret_key_base from the secret_token.rb initializer to secrets.yml under the production section.
    Remove the secret_token.rb initializer

2. remove ActiveRecord::Migration.check_pending! in test/test_helper.rb
    add `require 'test_help'`

3. add config/initializers/cookies_serializer.rb

4. replace MultiJson.dump with obj.to_json
    MultiJson.load with JSON.parse(str)

5. warn return within inline callback blocks
    before_save { return false }
  EOF

  secrets_content = <<-EOF
development:
  secret_key_base: #{SecureRandom.hex(64)}

test:
  secret_key_base: #{SecureRandom.hex(64)}

# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
  EOF
  add_file 'config/secrets.yml', secrets_content.strip

  remove_file 'config/initializers/secret_token.rb'

  within_file 'test/test_helper.rb' do
    # ActiveRecord::Migration.check_pending! => require 'test_help'
    with_node type: 'send', receiver: 'ActiveRecord::Migration', message: 'check_pending!' do
      replace_with "require 'test_help'"
    end
  end

  add_file 'config/initializers/cookies_serializer.rb', 'Rails.application.config.action_dispatch.cookies_serializer = :json'

  within_files '**/*.rb' do
    # MultiJson.dump(obj) => obj.to_json
    with_node type: 'send', receiver: 'MultiJson', message: 'dump' do
      replace_with "{{arguments}}.to_json"
    end

    # MultiJson.load(str) => JSON.parse(str)
    with_node type: 'send', receiver: 'MultiJson', message: 'load' do
      replace_with "JSON.parse {{arguments}}"
    end
  end

  within_files '**/*.rb' do
    [/before_/, /after_/].each do |message_regex|
      # Warn if finding return in before_* or after_* callbacks
      within_node type: 'block', caller: {type: 'send', message: message_regex} do
        with_node type: 'return' do
          warn 'Using a return statement in an inline callback block causes a LocalJumpError to be raised when the callback is executed.'
        end
      end
    end
  end
end


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__strdup_delete_char_54e.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__strdup_delete.label.xml
Template File: sources-sinks-54e.tmpl.cpp
*/
/*
 * @description
 * CWE: 762 Mismatched Memory Management Routines
 * BadSource:  Allocate data using strdup()
 * GoodSource: Allocate data using new
 * Sinks:
 *    GoodSink: Deallocate data using free()
 *    BadSink : Deallocate data using delete
 * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

namespace CWE762_Mismatched_Memory_Management_Routines__strdup_delete_char_54
{

#ifndef OMITBAD

void badSink_e(char * data)
{
    /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may
     * require a call to free() to deallocate the memory */
    delete data;
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_e(char * data)
{
    /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may
     * require a call to free() to deallocate the memory */
    delete data;
}

/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink_e(char * data)
{
    /* FIX: Deallocate the memory using free() */
    free(data);
}

#endif /* OMITGOOD */

} /* close namespace */


text:
namespace {

int64_t AmountOfMemory(DWORDLONG MEMORYSTATUSEX::*memory_field) {
  MEMORYSTATUSEX memory_info;
  memory_info.dwLength = sizeof(memory_info);
  if (!GlobalMemoryStatusEx(&memory_info)) {
    NOTREACHED();
    return 0;
  }

  int64_t rv = static_cast<int64_t>(memory_info.*memory_field);
  return rv < 0 ? std::numeric_limits<int64_t>::max() : rv;
}

bool GetDiskSpaceInfo(const base::FilePath& path,
                      int64_t* available_bytes,
                      int64_t* total_bytes) {
  ULARGE_INTEGER available;
  ULARGE_INTEGER total;
  ULARGE_INTEGER free;
  if (!GetDiskFreeSpaceExW(path.value().c_str(), &available, &total, &free))
    return false;

  if (available_bytes) {
    *available_bytes = static_cast<int64_t>(available.QuadPart);
    if (*available_bytes < 0)
      *available_bytes = std::numeric_limits<int64_t>::max();
  }
  if (total_bytes) {
    *total_bytes = static_cast<int64_t>(total.QuadPart);
    if (*total_bytes < 0)
      *total_bytes = std::numeric_limits<int64_t>::max();
  }
  return true;
}

}  // namespace

namespace base {

// static
int SysInfo::NumberOfProcessors() {
  return win::OSInfo::GetInstance()->processors();
}

// static
int64_t SysInfo::AmountOfPhysicalMemoryImpl() {
  return AmountOfMemory(&MEMORYSTATUSEX::ullTotalPhys);
}

// static
int64_t SysInfo::AmountOfAvailablePhysicalMemoryImpl() {
  SystemMemoryInfoKB info;
  if (!GetSystemMemoryInfo(&info))
    return 0;
  return static_cast<int64_t>(info.avail_phys) * 1024;
}

// static
int64_t SysInfo::AmountOfVirtualMemory() {
  return AmountOfMemory(&MEMORYSTATUSEX::ullTotalVirtual);
}

// static
int64_t SysInfo::AmountOfFreeDiskSpace(const FilePath& path) {
  base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
                                                base::BlockingType::MAY_BLOCK);

  int64_t available;
  if (!GetDiskSpaceInfo(path, &available, nullptr))
    return -1;
  return available;
}

// static
int64_t SysInfo::AmountOfTotalDiskSpace(const FilePath& path) {
  base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
                                                base::BlockingType::MAY_BLOCK);

  int64_t total;
  if (!GetDiskSpaceInfo(path, nullptr, &total))
    return -1;
  return total;
}

std::string SysInfo::OperatingSystemName() {
  return "Windows NT";
}

// static
std::string SysInfo::OperatingSystemVersion() {
  win::OSInfo* os_info = win::OSInfo::GetInstance();
  win::OSInfo::VersionNumber version_number = os_info->version_number();
  std::string version(StringPrintf("%d.%d.%d", version_number.major,
                                   version_number.minor, version_number.build));
  win::OSInfo::ServicePack service_pack = os_info->service_pack();
  if (service_pack.major != 0) {
    version += StringPrintf(" SP%d", service_pack.major);
    if (service_pack.minor != 0)
      version += StringPrintf(".%d", service_pack.minor);
  }
  return version;
}

// TODO: Implement OperatingSystemVersionComplete, which would include
// patchlevel/service pack number.
// See chrome/browser/feedback/feedback_util.h, FeedbackUtil::SetOSVersion.

// static
std::string SysInfo::OperatingSystemArchitecture() {
  win::OSInfo::WindowsArchitecture arch = win::OSInfo::GetArchitecture();
  switch (arch) {
    case win::OSInfo::X86_ARCHITECTURE:
      return "x86";
    case win::OSInfo::X64_ARCHITECTURE:
      return "x86_64";
    case win::OSInfo::IA64_ARCHITECTURE:
      return "ia64";
    case win::OSInfo::ARM64_ARCHITECTURE:
      return "arm64";
    default:
      return "";
  }
}

// static
std::string SysInfo::CPUModelName() {
  return win::OSInfo::GetInstance()->processor_model_name();
}

// static
size_t SysInfo::VMAllocationGranularity() {
  return win::OSInfo::GetInstance()->allocation_granularity();
}

// static
void SysInfo::OperatingSystemVersionNumbers(int32_t* major_version,
                                            int32_t* minor_version,
                                            int32_t* bugfix_version) {
  win::OSInfo* os_info = win::OSInfo::GetInstance();
  *major_version = os_info->version_number().major;
  *minor_version = os_info->version_number().minor;
  *bugfix_version = 0;
}

// static
std::string ReadHardwareInfoFromRegistry(const wchar_t* reg_value_name) {
  // On some systems or VMs, the system information and some of the below
  // locations may be missing info. Attempt to find the info from the below
  // registry keys in the order provided.
  static const wchar_t* const kSystemInfoRegKeyPaths[] = {
      L"HARDWARE\\DESCRIPTION\\System\\BIOS",
      L"SYSTEM\\CurrentControlSet\\Control\\SystemInformation",
      L"SYSTEM\\HardwareConfig\\Current",
  };

  std::wstring value;
  for (const wchar_t* system_info_reg_key_path : kSystemInfoRegKeyPaths) {
    base::win::RegKey system_information_key;
    if (system_information_key.Open(HKEY_LOCAL_MACHINE,
                                    system_info_reg_key_path,
                                    KEY_READ) == ERROR_SUCCESS) {
      if ((system_information_key.ReadValue(reg_value_name, &value) ==
           ERROR_SUCCESS) &&
          !value.empty()) {
        break;
      }
    }
  }

  return base::SysWideToUTF8(value);
}

// static
SysInfo::HardwareInfo SysInfo::GetHardwareInfoSync() {
  HardwareInfo info = {ReadHardwareInfoFromRegistry(L"SystemManufacturer"),
                       SysInfo::HardwareModelName()};
  return info;
}

// static
std::string SysInfo::HardwareModelName() {
  return ReadHardwareInfoFromRegistry(L"SystemProductName");
}

}  // namespace base


text:
package gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;

import javax.swing.*;

public class OptionMenu extends JPanel {
	/**
	 *
	 */
	private static final long serialVersionUID = 134527328306666687L;
	private Set<Reservation> allReservations;
	private List<Integer> availableTimes = new ArrayList<Integer>();
	private List<Integer> availableTables = new ArrayList<Integer>();
	private TableMap tableMap;
	private JComboBox timeList, tableList;
	private JButton reserve;
	private JLabel overviewLabel1, overviewLabel2;

	OptionMenu(TableMap tableMap, JButton reserve) {
		this.reserve = reserve;
		reserve.addActionListener(new ButtonListener());
		this.tableMap = tableMap;
		allReservations = tableMap.getReservationList();
		for(Reservation r : allReservations) {
			if(!availableTimes.contains(r.time()))
				availableTimes.add(r.time());
			if(!availableTables.contains(r.table().numberOfPlates()))
				availableTables.add(r.table().numberOfPlates());
		}
		Collections.sort(availableTimes);
		Collections.sort(availableTables);

		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

		JComboBox<String> dateList = new JComboBox<String>();
		dateList.addItem("Today");
		dateList.setSelectedIndex(0);
		JLabel dateLabel = new JLabel("Date:");
		dateLabel.setAlignmentX(CENTER_ALIGNMENT);
		add(dateLabel);
		add(dateList);

		timeList = new JComboBox(availableTimes.toArray());
		timeList.setSelectedIndex(0);
		timeList.addActionListener(new TimeListlistener());
		JLabel timeLabel = new JLabel("Time:");
		timeLabel.setAlignmentX(CENTER_ALIGNMENT);
		add(timeLabel);
		add(timeList);

		tableList = new JComboBox(availableTables.toArray());
		tableList.setSelectedIndex(0);
		tableList.addActionListener(new TableListlistener());
		JLabel tableLabel = new JLabel("Guests:");
		tableLabel.setAlignmentX(CENTER_ALIGNMENT);
		add(tableLabel);
		add(tableList);

		int time = (int)timeList.getSelectedItem();
        int numberOfPlates = (int)tableList.getSelectedItem();
        tableMap.selectTables(numberOfPlates, time);

        int tableCounter = tableCounter(numberOfPlates);

        overviewLabel1 = new JLabel(numberOfPlates + "-seats tables left:");
        overviewLabel2 = new JLabel("" + tableCounter);
        overviewLabel1.setAlignmentX(CENTER_ALIGNMENT);
        overviewLabel2.setAlignmentX(CENTER_ALIGNMENT);
		add(overviewLabel1);
		add(overviewLabel2);

        add(Box.createRigidArea(new Dimension(0, 50)));

		reserve.setEnabled(false);
		reserve.setAlignmentX(CENTER_ALIGNMENT);
		add(reserve);

		add(Box.createRigidArea(new Dimension(0, 450)));

	}
	private int tableCounter(int numberOfPlates){
		int tableCounter = 0;
        for(Reservation r : allReservations)
        	if(!r.isItReserved() && r.table().numberOfPlates() == numberOfPlates)
        		tableCounter++;
        return tableCounter;
	}
	private class TableListlistener implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {
	        JComboBox cb = (JComboBox)e.getSource();
	        int time = (int)timeList.getSelectedItem();
	        int numberOfPlates = (int)cb.getSelectedItem();
	        tableMap.selectTables(numberOfPlates, time);

	        int tableCounter = tableCounter(numberOfPlates);
	        overviewLabel1.setText(numberOfPlates + "-seats tables left:");
	        overviewLabel2.setText("" + tableCounter);
	    }
	}
	private class TimeListlistener implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {
	        JComboBox cb = (JComboBox)e.getSource();
	        int time = (int)cb.getSelectedItem();
	        int numberOfPlates = (int)tableList.getSelectedItem();
	        tableMap.selectTables(numberOfPlates, time);

	        int tableCounter = tableCounter(numberOfPlates);
	        overviewLabel1.setText(numberOfPlates + "-seats tables left:");
	        overviewLabel2.setText("" + tableCounter);
	    }
	}
	private class ButtonListener implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			int tableCounter = tableCounter((int)tableList.getSelectedItem())-1;
	        overviewLabel1.setText((int)tableList.getSelectedItem() + "-seats tables left:");
	        overviewLabel2.setText("" + tableCounter);
		}
	}
}


text:
const resolve = require('rollup-plugin-node-resolve');
const sourcemaps = require('rollup-plugin-sourcemaps');

const globals = {
  '@angular/core': 'ng.core',
  '@angular/common': 'ng.common',
  '@angular/router': 'ng.router',
  '@angular/upgrade/static': 'ng.upgrade.static'
};

module.exports = {
  entry: '../../../dist/packages-dist/router/esm5/upgrade.js',
  dest: '../../../dist/packages-dist/router/bundles/router-upgrade.umd.js',
  format: 'umd',
  exports: 'named',
  amd: {id: '@angular/router/upgrade'},
  moduleName: 'ng.router.upgrade',
  plugins: [resolve(), sourcemaps()],
  external: Object.keys(globals),
  globals: globals
};


text:
namespace System.Html.WebComponents {
	public delegate void LifecycleDetachedCallback();
}


text:
void	signalWarning()
{
	object rstrt;

	fprintf(stderr, "Before gSignal(<SimpleWarning>)\n");
	rstrt = gSignal(vNew(SimpleWarning, Dynace, "You have been warned!"));
	if (gIsKindOf(rstrt, Abort))
		gSignal(rstrt);
	else
		gDeepDispose(rstrt);
	fprintf(stderr, "After gSignal(<SimpleWarning>)\n");
}

void	unwindMePlease()
{
	withUnwindProtect
		signalWarning();
	onUnwind
		fprintf(stderr, "It's good just to unwind sometimes.\n");
	endUnwind;
}

int feeling_cranky = 0;

object	maybeAbort(object cond)
{
	object result;

	if (feeling_cranky)
		result = vNew(Abort, cond);
	else
		result = vNew(SimpleRestart, cond);
	return result;
}

void	driver()
{
	withRestartHandling(maybeAbort) {
		fprintf(stderr, "Here we go...\n");
		signalWarning();
		fprintf(stderr, "Ignored first warning...\n");
		unwindMePlease();
		fprintf(stderr, "Ignored second warning...\n");
		feeling_cranky = 1;
		unwindMePlease();
		fprintf(stderr, "This should not print!\n");
	}
	onError {
		object cond;

		if (cond = catchKind(Abort)) {
			fprintf(stderr, "driver caught Abort-- declining to handle!\n");
			declineHandling(cond);
		}
	}
	endHandling;
}

#if 0

int	main(int argc, char **argv)
{
	InitDynace(&argc);
	withHandling
		driver();
	onError {
		object cond;

		if (cond = catchKind(Error)) {
			fprintf(stderr, "main caught Abort!\n");
			gDeepDispose(cond);
		}
	}
	endHandling;
	return 0;
}

#endif

int	main(int argc, char **argv)
{
	char	*p = NULL;

	InitDynace(&argc);
	printf("Line start\n");
	withHandling {
		printf("Regular code\n");
		*p = '\f';
	}
	onError {
		printf("Error handling code\n");
	}
	endHandling;

	printf("End code\n");
	return 0;
}


text:
<?php

/**
 * The "operations" collection of methods.
 * Typical usage is:
 *  <code>
 *   $dlpService = new Google_Service_DLP(...);
 *   $operations = $dlpService->operations;
 *  </code>
 */
class Google_Service_DLP_Resource_RiskAnalysisOperations extends Google_Service_Resource
{
  /**
   * Cancels an operation. Use the `inspect.operations.get` to check whether the
   * cancellation succeeded or the operation completed despite cancellation.
   * (operations.cancel)
   *
   * @param string $name The name of the operation resource to be cancelled.
   * @param Google_Service_DLP_GoogleLongrunningCancelOperationRequest $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_DLP_GoogleProtobufEmpty
   */
  public function cancel($name, Google_Service_DLP_GoogleLongrunningCancelOperationRequest $postBody, $optParams = array())
  {
    $params = array('name' => $name, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('cancel', array($params), "Google_Service_DLP_GoogleProtobufEmpty");
  }
  /**
   * This method is not supported and the server returns `UNIMPLEMENTED`.
   * (operations.delete)
   *
   * @param string $name The name of the operation resource to be deleted.
   * @param array $optParams Optional parameters.
   * @return Google_Service_DLP_GoogleProtobufEmpty
   */
  public function delete($name, $optParams = array())
  {
    $params = array('name' => $name);
    $params = array_merge($params, $optParams);
    return $this->call('delete', array($params), "Google_Service_DLP_GoogleProtobufEmpty");
  }
  /**
   * Gets the latest state of a long-running operation.  Clients can use this
   * method to poll the operation result at intervals as recommended by the API
   * service. (operations.get)
   *
   * @param string $name The name of the operation resource.
   * @param array $optParams Optional parameters.
   * @return Google_Service_DLP_GoogleLongrunningOperation
   */
  public function get($name, $optParams = array())
  {
    $params = array('name' => $name);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_DLP_GoogleLongrunningOperation");
  }
  /**
   * Fetches the list of long running operations.
   * (operations.listRiskAnalysisOperations)
   *
   * @param string $name The name of the operation's parent resource.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string pageToken The standard list page token.
   * @opt_param int pageSize The list page size. The maximum allowed value is 256
   * and the default is 100.
   * @opt_param string filter Filters by `done`. That is, `done=true` or
   * `done=false`.
   * @return Google_Service_DLP_GoogleLongrunningListOperationsResponse
   */
  public function listRiskAnalysisOperations($name, $optParams = array())
  {
    $params = array('name' => $name);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_DLP_GoogleLongrunningListOperationsResponse");
  }
}


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

/**
 * Print Google Analytics script.
 *
 * This helper function should be used in view files in order to output the Google Analytics
 * script. It will check whether the code is set in the database and print it, otherwise nothing
 * will be outputted. This eliminates the need for extra checking before outputting.
 */
function google_analytics_script() {
    $ci =& get_instance();

    $ci->load->model('settings_model');

    $google_analytics_code = $ci->settings_model->get_setting('google_analytics_code');

    if ($google_analytics_code !== '') {
        echo '
            <script>
                (function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                })(window,document,"script","//www.google-analytics.com/analytics.js","ga");
                ga("create", "' . $google_analytics_code . '", "auto");
                ga("send", "pageview");
            </script>
        ';
    }
}

/* End of file google_analytics.php */
/* Location: ./application/helpers/google_analytics.php */


text:
package simpleframework;

import battlecode.common.GameActionException;
import battlecode.common.RobotController;

public class TrainingFieldHandler extends RobotHandler {

	protected TrainingFieldHandler(RobotController rc) {
		super(rc);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void doTheThing() throws GameActionException {
		// TODO Auto-generated method stub

	}

}