text:
package org.apache.spark.api.python

import scala.collection.JavaConverters._
import scala.util.{Failure, Success, Try}

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.io._

import org.apache.spark.SparkException
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.internal.Logging
import org.apache.spark.rdd.RDD
import org.apache.spark.util.{SerializableConfiguration, Utils}

/**
 * A trait for use with reading custom classes in PySpark. Implement this trait and add custom
 * transformation code by overriding the convert method.
 */
trait Converter[-T, +U] extends Serializable {
  def convert(obj: T): U
}

private[python] object Converter extends Logging {

  def getInstance[T, U](converterClass: Option[String],
                        defaultConverter: Converter[_ >: T, _ <: U]): Converter[T, U] = {
    converterClass.map { cc =>
      Try {
        val c = Utils.classForName[Converter[T, U]](cc).getConstructor().newInstance()
        logInfo(s"Loaded converter: $cc")
        c
      } match {
        case Success(c) => c
        case Failure(err) =>
          logError(s"Failed to load converter: $cc")
          throw err
      }
    }.getOrElse { defaultConverter }
  }
}

/**
 * A converter that handles conversion of common [[org.apache.hadoop.io.Writable]] objects.
 * Other objects are passed through without conversion.
 */
private[python] class WritableToJavaConverter(
    conf: Broadcast[SerializableConfiguration]) extends Converter[Any, Any] {

  /**
   * Converts a [[org.apache.hadoop.io.Writable]] to the underlying primitive, String or
   * object representation
   */
  private def convertWritable(writable: Writable): Any = {
    writable match {
      case iw: IntWritable => iw.get()
      case dw: DoubleWritable => dw.get()
      case lw: LongWritable => lw.get()
      case fw: FloatWritable => fw.get()
      case t: Text => t.toString
      case bw: BooleanWritable => bw.get()
      case byw: BytesWritable =>
        val bytes = new Array[Byte](byw.getLength)
        System.arraycopy(byw.getBytes(), 0, bytes, 0, byw.getLength)
        bytes
      case n: NullWritable => null
      case aw: ArrayWritable =>
        // Due to erasure, all arrays appear as Object[] and they get pickled to Python tuples.
        // Since we can't determine element types for empty arrays, we will not attempt to
        // convert to primitive arrays (which get pickled to Python arrays). Users may want
        // write custom converters for arrays if they know the element types a priori.
        aw.get().map(convertWritable(_))
      case mw: MapWritable =>
        val map = new java.util.HashMap[Any, Any]()
        mw.asScala.foreach { case (k, v) => map.put(convertWritable(k), convertWritable(v)) }
        map
      case w: Writable => WritableUtils.clone(w, conf.value.value)
      case other => other
    }
  }

  override def convert(obj: Any): Any = {
    obj match {
      case writable: Writable =>
        convertWritable(writable)
      case _ =>
        obj
    }
  }
}

/**
 * A converter that converts common types to [[org.apache.hadoop.io.Writable]]. Note that array
 * types are not supported since the user needs to subclass [[org.apache.hadoop.io.ArrayWritable]]
 * to set the type properly. See [[org.apache.spark.api.python.DoubleArrayWritable]] and
 * [[org.apache.spark.api.python.DoubleArrayToWritableConverter]] for an example. They are used in
 * PySpark RDD `saveAsNewAPIHadoopFile` doctest.
 */
private[python] class JavaToWritableConverter extends Converter[Any, Writable] {

  /**
   * Converts common data types to [[org.apache.hadoop.io.Writable]]. Note that array types are not
   * supported out-of-the-box.
   */
  private def convertToWritable(obj: Any): Writable = {
    obj match {
      case i: java.lang.Integer => new IntWritable(i)
      case d: java.lang.Double => new DoubleWritable(d)
      case l: java.lang.Long => new LongWritable(l)
      case f: java.lang.Float => new FloatWritable(f)
      case s: java.lang.String => new Text(s)
      case b: java.lang.Boolean => new BooleanWritable(b)
      case aob: Array[Byte] => new BytesWritable(aob)
      case null => NullWritable.get()
      case map: java.util.Map[_, _] =>
        val mapWritable = new MapWritable()
        map.asScala.foreach { case (k, v) =>
          mapWritable.put(convertToWritable(k), convertToWritable(v))
        }
        mapWritable
      case array: Array[Any] =>
        val arrayWriteable = new ArrayWritable(classOf[Writable])
        arrayWriteable.set(array.map(convertToWritable(_)))
        arrayWriteable
      case other => throw new SparkException(
        s"Data of type ${other.getClass.getName} cannot be used")
    }
  }

  override def convert(obj: Any): Writable = obj match {
    case writable: Writable => writable
    case other => convertToWritable(other)
  }
}

/** Utilities for working with Python objects <-> Hadoop-related objects */
private[python] object PythonHadoopUtil {

  /**
   * Convert a [[java.util.Map]] of properties to a [[org.apache.hadoop.conf.Configuration]]
   */
  def mapToConf(map: java.util.Map[String, String]): Configuration = {
    val conf = new Configuration()
    map.asScala.foreach { case (k, v) => conf.set(k, v) }
    conf
  }

  /**
   * Merges two configurations, returns a copy of left with keys from right overwriting
   * any matching keys in left
   */
  def mergeConfs(left: Configuration, right: Configuration): Configuration = {
    val copy = new Configuration(left)
    right.asScala.foreach(entry => copy.set(entry.getKey, entry.getValue))
    copy
  }

  /**
   * Converts an RDD of key-value pairs, where key and/or value could be instances of
   * [[org.apache.hadoop.io.Writable]], into an RDD of base types, or vice versa.
   */
  def convertRDD[K, V](rdd: RDD[(K, V)],
                       keyConverter: Converter[K, Any],
                       valueConverter: Converter[V, Any]): RDD[(Any, Any)] = {
    rdd.map { case (k, v) => (keyConverter.convert(k), valueConverter.convert(v)) }
  }

}


text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: cloudformation_facts
short_description: Obtain facts about an AWS CloudFormation stack
description:
  - Gets information about an AWS CloudFormation stack
requirements:
  - boto3 >= 1.0.0
  - python >= 2.6
version_added: "2.2"
author: Justin Menga (@jmenga)
options:
    stack_name:
        description:
          - The name or id of the CloudFormation stack. Gathers facts for all stacks by default.
        required: false
        default: null
    all_facts:
        description:
            - Get all stack information for the stack
        required: false
        default: false
    stack_events:
        description:
            - Get stack events for the stack
        required: false
        default: false
    stack_template:
        description:
            - Get stack template body for the stack
        required: false
        default: false
    stack_resources:
        description:
            - Get stack resources for the stack
        required: false
        default: false
    stack_policy:
        description:
            - Get stack policy for the stack
        required: false
        default: false
extends_documentation_fragment:
    - aws
    - ec2
'''

EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.

# Get summary information about a stack
- cloudformation_facts:
    stack_name: my-cloudformation-stack

# Facts are published in ansible_facts['cloudformation'][<stack_name>]
- debug:
    msg: "{{ ansible_facts['cloudformation']['my-cloudformation-stack'] }}"

# Get all stack information about a stack
- cloudformation_facts:
    stack_name: my-cloudformation-stack
    all_facts: true

# Get stack resource and stack policy information about a stack
- cloudformation_facts:
    stack_name: my-cloudformation-stack
    stack_resources: true
    stack_policy: true

# Example dictionary outputs for stack_outputs, stack_parameters and stack_resources:
# "stack_outputs": {
#     "ApplicationDatabaseName": "dazvlpr01xj55a.ap-southeast-2.rds.amazonaws.com",
#     ...
# },
# "stack_parameters": {
#     "DatabaseEngine": "mysql",
#     "DatabasePassword": "****",
#     ...
# },
# "stack_resources": {
#     "AutoscalingGroup": "dev-someapp-AutoscalingGroup-1SKEXXBCAN0S7",
#     "AutoscalingSecurityGroup": "sg-abcd1234",
#     "ApplicationDatabase": "dazvlpr01xj55a",
#     "EcsTaskDefinition": "arn:aws:ecs:ap-southeast-2:123456789:task-definition/dev-someapp-EcsTaskDefinition-1F2VM9QB0I7K9:1"
#     ...
# }
'''

RETURN = '''
stack_description:
    description: Summary facts about the stack
    returned: always
    type: dict
stack_outputs:
    description: Dictionary of stack outputs keyed by the value of each output 'OutputKey' parameter and corresponding value of each
                 output 'OutputValue' parameter
    returned: always
    type: dict
stack_parameters:
    description: Dictionary of stack parameters keyed by the value of each parameter 'ParameterKey' parameter and corresponding value of
                 each parameter 'ParameterValue' parameter
    returned: always
    type: dict
stack_events:
    description: All stack events for the stack
    returned: only if all_facts or stack_events is true
    type: list
stack_policy:
    description: Describes the stack policy for the stack
    returned: only if all_facts or stack_policy is true
    type: dict
stack_template:
    description: Describes the stack template for the stack
    returned: only if all_facts or stack_template is true
    type: dict
stack_resource_list:
    description: Describes stack resources for the stack
    returned: only if all_facts or stack_resourses is true
    type: list
stack_resources:
    description: Dictionary of stack resources keyed by the value of each resource 'LogicalResourceId' parameter and corresponding value of each
                 resource 'PhysicalResourceId' parameter
    returned: only if all_facts or stack_resourses is true
    type: dict
'''

import json
import traceback
from functools import partial

try:
    import boto3
    import botocore
    HAS_BOTO3 = True
except ImportError:
    HAS_BOTO3 = False

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import (get_aws_connection_info, ec2_argument_spec, boto3_conn,
                                      camel_dict_to_snake_dict, AWSRetry, boto3_tag_list_to_ansible_dict)

class CloudFormationServiceManager:
    """Handles CloudFormation Services"""

    def __init__(self, module):
        self.module = module

        try:
            region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
            self.client = boto3_conn(module, conn_type='client',
                                     resource='cloudformation', region=region,
                                     endpoint=ec2_url, **aws_connect_kwargs)
            backoff_wrapper = AWSRetry.jittered_backoff(retries=10, delay=3, max_delay=30)
            self.client.describe_stacks = backoff_wrapper(self.client.describe_stacks)
            self.client.list_stack_resources = backoff_wrapper(self.client.list_stack_resources)
            self.client.describe_stack_events = backoff_wrapper(self.client.describe_stack_events)
            self.client.get_stack_policy = backoff_wrapper(self.client.get_stack_policy)
            self.client.get_template = backoff_wrapper(self.client.get_template)
        except botocore.exceptions.NoRegionError:
            self.module.fail_json(msg="Region must be specified as a parameter, in AWS_DEFAULT_REGION environment variable or in boto configuration file")
        except Exception as e:
            self.module.fail_json(msg="Can't establish connection - " + str(e), exception=traceback.format_exc())

    def describe_stacks(self, stack_name=None):
        try:
            kwargs = {'StackName': stack_name} if stack_name else {}
            func = partial(self.client.describe_stacks, **kwargs)
            response = self.paginated_response(func, 'Stacks')
            if response:
                return response
            self.module.fail_json(msg="Error describing stack(s) - an empty response was returned")
        except Exception as e:
            self.module.fail_json(msg="Error describing stack(s) - " + str(e), exception=traceback.format_exc())

    def list_stack_resources(self, stack_name):
        try:
            func = partial(self.client.list_stack_resources,StackName=stack_name)
            return self.paginated_response(func, 'StackResourceSummaries')
        except Exception as e:
            self.module.fail_json(msg="Error listing stack resources - " + str(e), exception=traceback.format_exc())

    def describe_stack_events(self, stack_name):
        try:
            func = partial(self.client.describe_stack_events,StackName=stack_name)
            return self.paginated_response(func, 'StackEvents')
        except Exception as e:
            self.module.fail_json(msg="Error describing stack events - " + str(e), exception=traceback.format_exc())

    def get_stack_policy(self, stack_name):
        try:
            response = self.client.get_stack_policy(StackName=stack_name)
            stack_policy = response.get('StackPolicyBody')
            if stack_policy:
                return json.loads(stack_policy)
            return dict()
        except Exception as e:
            self.module.fail_json(msg="Error getting stack policy - " + str(e), exception=traceback.format_exc())

    def get_template(self, stack_name):
        try:
            response = self.client.get_template(StackName=stack_name)
            return response.get('TemplateBody')
        except Exception as e:
            self.module.fail_json(msg="Error getting stack template - " + str(e), exception=traceback.format_exc())

    def paginated_response(self, func, result_key, next_token=None):
        '''
        Returns expanded response for paginated operations.
        The 'result_key' is used to define the concatenated results that are combined from each paginated response.
        '''
        args=dict()
        if next_token:
            args['NextToken'] = next_token
        response = func(**args)
        result = response.get(result_key)
        next_token = response.get('NextToken')
        if not next_token:
            return result
        return result + self.paginated_response(func, result_key, next_token)

def to_dict(items, key, value):
    ''' Transforms a list of items to a Key/Value dictionary '''
    if items:
        return dict(zip([i[key] for i in items], [i[value] for i in items]))
    else:
        return dict()

def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(
        stack_name=dict(),
        all_facts=dict(required=False, default=False, type='bool'),
        stack_policy=dict(required=False, default=False, type='bool'),
        stack_events=dict(required=False, default=False, type='bool'),
        stack_resources=dict(required=False, default=False, type='bool'),
        stack_template=dict(required=False, default=False, type='bool'),
    ))

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False)

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 is required.')

    service_mgr = CloudFormationServiceManager(module)

    result = {'ansible_facts': {'cloudformation': {}}}

    for stack_description in service_mgr.describe_stacks(module.params.get('stack_name')):
        facts = {'stack_description': stack_description}
        stack_name = stack_description.get('StackName')

        # Create stack output and stack parameter dictionaries
        if facts['stack_description']:
            facts['stack_outputs'] = to_dict(facts['stack_description'].get('Outputs'), 'OutputKey', 'OutputValue')
            facts['stack_parameters'] = to_dict(facts['stack_description'].get('Parameters'), 'ParameterKey', 'ParameterValue')
            facts['stack_tags'] = boto3_tag_list_to_ansible_dict(facts['stack_description'].get('Tags'))

        # normalize stack description API output
        facts['stack_description'] = camel_dict_to_snake_dict(facts['stack_description'])

        # Create optional stack outputs
        all_facts = module.params.get('all_facts')
        if all_facts or module.params.get('stack_resources'):
            facts['stack_resource_list'] = service_mgr.list_stack_resources(stack_name)
            facts['stack_resources'] = to_dict(facts.get('stack_resource_list'), 'LogicalResourceId', 'PhysicalResourceId')
        if all_facts or module.params.get('stack_template'):
            facts['stack_template'] = service_mgr.get_template(stack_name)
        if all_facts or module.params.get('stack_policy'):
            facts['stack_policy'] = service_mgr.get_stack_policy(stack_name)
        if all_facts or module.params.get('stack_events'):
            facts['stack_events'] = service_mgr.describe_stack_events(stack_name)

        result['ansible_facts']['cloudformation'][stack_name] = facts

    result['changed'] = False
    module.exit_json(**result)

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
<mat-card>

  <mat-card-title-group>
    <mat-card-title class="mat-body-2">Kreuzung 1</mat-card-title>
  </mat-card-title-group>
  <mat-card-actions>
    <button mat-button color="accent" type="button">Steuern</button>

    <button mat-button color="accent" type="button">Kamera</button>
  </mat-card-actions>
</mat-card>

<mat-card class="app-card mat-elevation-z2">
  <mat-toolbar>
    <mat-toolbar-row role="toolbar">
      Kreuzung 1

      <button mat-icon-button>
        <mat-icon>videocam</mat-icon>
      </button>
    </mat-toolbar-row>
  </mat-toolbar>

  <mat-card-content>

Steuerung

      20 Fahrspuren

      5 Schaltungen

  </mat-card-content>
</mat-card>

<mat-card class="app-card mat-elevation-z2">
  <mat-toolbar>
    <mat-toolbar-row role="toolbar">
      Kreuzung 1

      <button mat-icon-button>
        <mat-icon>videocam</mat-icon>
      </button>
    </mat-toolbar-row>
  </mat-toolbar>

  <mat-card-content>

Steuerung

      20 Fahrspuren

      5 Schaltungen

  </mat-card-content>
  <mat-action-list>
    Kreuzung 1

    <button mat-icon-button>
      <mat-icon>videocam</mat-icon>
    </button>
  </mat-action-list>
</mat-card>

titled-card works!


text:
package com.qualogy.qafe.platform.distribution.impl;

import com.qualogy.qafe.platform.distribution.api.CacheManager;

public class DistributionManager implements com.qualogy.qafe.platform.distribution.api.DistributionManager {

	public CacheManager getCacheManager() {
		return com.qualogy.qafe.platform.distribution.impl.CacheManager.getInstance();
	}
}


text: module.exports = require('./messages').EventStore.Client.Messages;


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../libc/constant.IPV6_PMTUDISC_DONT.html">

Redirecting to ../../../libc/constant.IPV6_PMTUDISC_DONT.html...


text:
package host

import (
	"flag"
	"fmt"

	"golang.org/x/net/context"

	"github.com/RotatingFans/govmomi/govc/cli"
	"github.com/RotatingFans/govmomi/govc/flags"
	"github.com/RotatingFans/govmomi/object"
	"github.com/RotatingFans/govmomi/vim25/types"
)

type reconnect struct {
	*flags.HostSystemFlag
	*flags.HostConnectFlag

	types.HostSystemReconnectSpec
}

func init() {
	cli.Register("host.reconnect", &reconnect{})
}

func (cmd *reconnect) Register(ctx context.Context, f *flag.FlagSet) {
	cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
	cmd.HostSystemFlag.Register(ctx, f)

	cmd.HostConnectFlag, ctx = flags.NewHostConnectFlag(ctx)
	cmd.HostConnectFlag.Register(ctx, f)

	cmd.HostSystemReconnectSpec.SyncState = types.NewBool(false)
	f.BoolVar(cmd.HostSystemReconnectSpec.SyncState, "sync-state", false, "Sync state")
}

func (cmd *reconnect) Process(ctx context.Context) error {
	if err := cmd.HostSystemFlag.Process(ctx); err != nil {
		return err
	}
	if err := cmd.HostConnectFlag.Process(ctx); err != nil {
		return err
	}
	return nil
}

func (cmd *reconnect) Description() string {
	return `Reconnect host to vCenter.

This command can also be used to change connection properties (hostname, fingerprint, username, password),
without disconnecting the host.`
}

func (cmd *reconnect) Reconnect(ctx context.Context, host *object.HostSystem) error {
	task, err := host.Reconnect(ctx, &cmd.HostConnectSpec, &cmd.HostSystemReconnectSpec)
	if err != nil {
		return err
	}

	logger := cmd.ProgressLogger(fmt.Sprintf("%s reconnecting... ", host.InventoryPath))
	defer logger.Wait()

	_, err = task.WaitForResult(ctx, logger)
	return err
}

func (cmd *reconnect) Run(ctx context.Context, f *flag.FlagSet) error {
	hosts, err := cmd.HostSystems(f.Args())
	if err != nil {
		return err
	}

	for _, host := range hosts {
		err = cmd.Reconnect(ctx, host)
		if err != nil {
			return err
		}
	}

	return nil
}


text:
{% extends "base.html" %}
{% block submenu %}

List Resources

Create New Resource

{% endblock %}


text:
var xWidth = Math.max(window.innerWidth - 150, 700);

var barWidth = 2;
var numBars = Math.floor(xWidth/2);

var margin = {top: 20, right: 0, bottom: 20, left: 70},
	width = numBars*barWidth + margin.left + margin.right,
	height = Math.max(window.innerHeight - margin.top - margin.bottom - 400, 400);

var y = d3.scale.linear()
		.range([height, 0]);

var yAxis = d3.svg.axis()
		.scale(y)
		.orient("left")
		.tickFormat(d3.format("d"));

var svg = d3.select("#graph").append("svg")
		.attr("id", "svg")
		.attr("width", width + margin.left + margin.right)
		.attr("height", height + margin.top + margin.bottom)
	.append("g")
		.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
		.attr("id", "transformBox")

var tooltip = d3.select("body")
		.append("div")
		.attr("id","tooltip");

//loads unemployment data in rawdata and attaches a date object
var book;
d3.json("mobydick.json", function(error, input) {

	book = input;
	book.ltext = book.text.toLowerCase();

	//removes placeholder loading text
	document.getElementById('loadingText').innerHTML = '';

	//0s out data array
	resetData();

	svg.append("g")
			.attr("class", "y axis")
			.call(yAxis)
		.append("text")
			.attr("transform", "translate("+ (-80/2) +","+(height/2)+")rotate(-90)")
			.style("text-anchor", "middle")
			.attr("font-size",'110%')
			.text("Frequency (per " + Math.round(book.text.length/(numBars*7)/100)*100 + " words)");

	//draws histogram bars
	svg.selectAll('.bar')
		.data(data)
	.enter().append("rect")
		.attr("class", "bar")
		.attr("x", function(d, i){return (1+i)*barWidth;})
		.attr("width", barWidth)
		.attr("y", height)
		.attr("height", 0)
		.on("mouseover", function(){

			var cord = d3.mouse(this);
			var position = findIndex(Math.floor(cord[0]/barWidth), Math.floor(y.invert(cord[1])));
			d3.select(this).style("fill", "#435A82");
			document.getElementById("context").innerHTML = indexText(indices[position]).replace(new RegExp('(' + word  + ')', 'gi'), "$1").replace(/\n\r?/g, '
');
			document.getElementById("chapterTitle").innerHTML = getChapter(indices[position]);
		})
		.on("mousemove", function(){
		})
		.on("mouseout", function (){
			d3.select(this).style("fill", "");
		});

	book.chapterStarts[book.chapterStarts.length] = book.text.length;

	//draws chapter bars
	var scaleFactor = numBars*barWidth/book.text.length;
	for (var i = 0; i < book.chapterTitles.length; i++){
		var title = book.chapterTitles[i];
		svg.append("rect")
			.attr("class", "chapter " + (i%2 ? 'light' : 'dark'))
			.attr("x", book.chapterStarts[i]*scaleFactor + barWidth)
			.attr("height", 7)
			.attr("width", (book.chapterStarts[i+1] - book.chapterStarts[i])*scaleFactor)
			.attr("y", height)
			.attr("titleOfChapter", title)
			.on('mouseover', function(){
				var cord = (typeof event === 'undefined') ? ffm : [event.pageX, event.pageY];
				tooltip.style("top", (cord[1]-10)+"px").style("left",(cord[0]+10)+"px");
				tooltip.style("visibility", "visible");
				tooltip.text(d3.select(this)[0][0].attributes[5].nodeValue);
				d3.select(this).style("fill", "#422813");
			})
			.on("mousemove", function(e){
				var cord = (typeof event === 'undefined') ? ffm : [event.pageX, event.pageY];
				tooltip.style("top", (cord[1]-10)+"px").style("left",(cord[0]+10)+"px");
			})
			.on("mouseout", function (){
				tooltip.style("visibility", "hidden");
				d3.select(this).style("fill","");
			});

		$('#footer').css('margin-left', xWidth/2 - 180);

		d3.select("#container").style("display", "block");
		d3.select("#footerInfo").style("display", "block");

		 $('#autocomplete').focus()

	}
});

//given x and y value from graph, finds index
function findIndex(x, y){
	if (y + 1){
		var sum = 0;
		for (var i = 0; i < x - 2; i++){
			sum = sum + data[i];
		}
		return (sum + y);
	}
	else return -1;
}

//returns text surrounding position in book
function indexText(index){
	var start = Math.max(index - 300, 0);
	while (book.text[start] != "\n"){
		start = start + 1;
	}
	var end = Math.min(index + 300, book.text.length - 1);
	while (book.text[end] != "\n"){
		end = end - 1;
	}
	return book.text.substring(start + 1, end);
}

//returns chapter title index is in
function getChapter(index){
	console.log(index);
	var i = 0;
	while (book.chapterStarts[i] < index){
		i = i + 1;
	}
	console.log(i);
	return book.chapterTitles[i-1];
}

var data = [];			//height of bars, representing occurences of match per bucket of x chars
var indices = [];		//array of indexOfs of each occurences of word in
var word;				//matched word (or string)

//redraws graph for new match
function updateGraph(match){
	updateData(match);

	y.domain([0, d3.max(data)]);
	svg.select(".y.axis").call(yAxis);

	svg.selectAll('.bar')
			.data(data)
		.transition()
			.duration(1000)
			.attr("y", function(d){return y(d)})
			.attr("height", function(d){return height - y(d);});
};

//updates bar height values
function updateData(match){
	resetData();
	indices = indexOfArray(match);
	for (var i = 0; i < indices.length; i++){
		var index = Math.floor(numBars*indices[i]/book.text.length);
		data[index] = data[index] + 1;
	}
}

//0s out bar height array
function resetData(){
	for (var i = 0; i < numBars; i++){
		data[i] = 0;
	}
}

//creates array containing positions of each occurence of word
function indexOfArray(match) {
	match = match.toLowerCase();
	var indices = [];
	var index = 0;
	index = book.ltext.indexOf(match, index);
	while(index > 0) {
		indices.push(index);
		index = book.ltext.indexOf(match, index + 1);
	}
	return indices;
}

function updateWord(){
	word = $("#autocomplete").val();
	if (word.length > 0){
		updateGraph(word);
		d3.select("#wordNum").text(indices.length);
		d3.select("#wordText").text(word);
		d3.select("#title").style("visibility", "visible");
	}
	else{
		d3.select("#title").style("visibility", "hidden");
	}
}

var autoclose = false;

//update graph and close autocomplete
$('#autocomplete').keyup(function(e){
	if(e.keyCode == 13)
	{
		updateWord();
		$(this).autocomplete("close");
		setTimeout(function(){$('#autocomplete').autocomplete("close");}, 100);
	}
});

$( "#autocomplete" ).autocomplete({
	minLength: 0,
	select: function( event, ui ) {
		setTimeout(function(){updateWord();}, 50);
	},
	source: function( request, response ) {
		str = request.term.toLowerCase();
		var count = 0;
		var n = 0;
		var matches = [];
		var matchValues = [];
		while(n < book.fKeys.length && count < 10){
			if (str === book.fKeys[n].substring(0,str.length)){
				count = count + 1;
				matches.push({	value: book.fKeys[n],
				 				number: book.fValues[n],
				 				bold: str,
				 				nbold: book.fKeys[n].substring(str.length, book.fKeys[n].length)});
			}
			n = n + 1;
		}
		response(matches);
	}
}).data('ui-autocomplete')._renderItem = function(ul, item){
		return $( "
" )
        	.append( "" + item.bold + "" + item.nbold + " " + item.number + "" )
        	.appendTo( ul );
	};

//firefox doesn't capture mousemove propertly
var ffm;
function onMouseMove(e){
	ffm = [e.clientX, e.clientY];
}
document.addEventListener('mousemove', onMouseMove, false);


text:
package com.a21vianet.wallet.vport.library.commom.http.vchain.bean;

import com.google.gson.annotations.SerializedName;

/**
 * Created by wang.rongqiang on 2017/6/16.
 */

public class GetColor1Response {

    /**
     * result : Successful!
     * tx_id : 2f135cbc55173edaa0d65deb2ca6bd0efbbb420f92799f6d9697b2f312a58490
     */

    @SerializedName("result")
    private String result;
    @SerializedName("tx_id")
    private String txId;

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getTxId() {
        return txId;
    }

    public void setTxId(String txId) {
        this.txId = txId;
    }
}


text:
using System;

namespace Ragnar.Integration.InterestV2.Model
{
    public struct BankInterestRate
    {
        public DateTime StartDate { get; set; }

        public decimal Value { get; set; }
    }
}


text:
using System.Formats.Asn1;
using System.Runtime.InteropServices;
using System.Security;
using OpenGost.Security.Cryptography.Properties;

namespace OpenGost.Security.Cryptography.Asn1;

[SecuritySafeCritical]
[StructLayout(LayoutKind.Sequential)]
internal struct GostECDsaPublicKeyParameters
{
    public string PublicKeyParamSet;
    public string? DigestParamSet;

    [SecuritySafeCritical]
    public static GostECDsaPublicKeyParameters Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
    {
        return Decode(Asn1Tag.Sequence, encoded, ruleSet);
    }

    public static GostECDsaPublicKeyParameters Decode(
        Asn1Tag expectedTag,
        ReadOnlyMemory<byte> encoded,
        AsnEncodingRules ruleSet)
    {
        try
        {
            var reader = new AsnValueReader(encoded.Span, ruleSet);
            DecodeCore(ref reader, expectedTag, out var decoded);
            reader.ThrowIfNotEmpty();
            return decoded;
        }
        catch (AsnContentException e)
        {
            throw new CryptographicException(CryptographyStrings.CryptographicDerInvalidEncoding, e);
        }
    }

    private static void DecodeCore(
        ref AsnValueReader reader,
        Asn1Tag expectedTag,
        out GostECDsaPublicKeyParameters decoded)
    {
        decoded = default;
        var sequenceReader = reader.ReadSequence(expectedTag);
        decoded.PublicKeyParamSet = sequenceReader.ReadObjectIdentifier();
        if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(Asn1Tag.ObjectIdentifier))
            decoded.DigestParamSet = sequenceReader.ReadObjectIdentifier();
        sequenceReader.ThrowIfNotEmpty();
    }
}


text:
@class MTAlertView;

@protocol MTAlertViewDelegate <NSObject>

- (void)alertView:(MTAlertView*)alertView clickedButtonAtIndex:(NSInteger)index;

@end

@interface MTAlertView : UIView

@property (nonatomic, weak)  id<MTAlertViewDelegate>  delegate;
@property (nonatomic, strong) id customerData;

- (id)initWithContent:(NSString*)content
                image:(UIImage*)image
              buttons:(NSString*)label, ...;
- (void)show;
- (void)showInView:(UIView*)view;
- (void)miss;

@end


text:
/**
 * Error Screen
 *
    <Error text={'Server is down'} />
 *
 * React Native Starter App
 * https://github.com/mcnamee/react-native-starter-app
 */
import React, { PropTypes } from 'react';
import { View } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

// Consts and Libs
import { AppStyles } from '@theme/';

// Components
import { Spacer, Text } from '@ui/';

/* Component ==================================================================== */
const Error = ({ text }) => (
  <View style={[AppStyles.container, AppStyles.containerCentered]}>
    <Icon name={'ios-alert-outline'} size={50} color={'#CCC'} />

    <Spacer size={10} />

    <Text>{text}</Text>
  </View>
);

Error.propTypes = { text: PropTypes.string };
Error.defaultProps = { text: 'Woops, Something went wrong.' };
Error.componentName = 'Error';

/* Export Component ==================================================================== */
export default Error;


text:
import express = require("express");
import ZoneModel = require("./zone.model");

function getZones(req: express.Request, res: express.Response) {

  res.setHeader('Content-Type', 'application/json');

  ZoneModel
    .getZones()
    .then(zones => {
      res.send(JSON.stringify(zones));
    })
    .catch(error => {
      console.log('failed to get zones: ' + JSON.stringify(error));
      res.status(500).send(JSON.stringify(error));
    });
}

function getZone(req: express.Request, res: express.Response) {

  res.setHeader('Content-Type', 'application/json');

  ZoneModel
    .getZone(parseInt(req.params.zoneId))
    .then(zone => {
      res.send(JSON.stringify(zone));
    })
    .catch(error => {
      if (error instanceof ZoneModel.NotFoundError)
        return res.status(404).send(JSON.stringify({ detail: 'Not Found' }));
      console.log('failed to get zone: ' + JSON.stringify(error));
      res.status(500).send(JSON.stringify(error));
    });
}

function updateZone(req: express.Request, res: express.Response) {

  let zone = req.body as ZoneModel.Zone;
  if (!zone) {
    return res.status(400).send({ error: 'Failed to parse request body' });
  }
  zone.zoneId = parseInt(req.params.zoneId);

  ZoneModel
    .update(zone)
    .then(() => {
      res.setHeader('Content-Type', 'application/json');
      res.status(200).send(JSON.stringify(zone.zoneId));
    })
    .catch(error => {
      if (error instanceof ZoneModel.NotFoundError)
        return res.status(404).send(JSON.stringify({ detail: 'Not Found' }));
      console.log('failed to update zone: ' + JSON.stringify(error));
      res.setHeader('Content-Type', 'application/json');
      res.status(500).send(JSON.stringify(error));
    });
}

let zonesRouter = express.Router();

zonesRouter.get('', getZones);
zonesRouter.get('/:zoneId', getZone);
zonesRouter.post('/:zoneId', updateZone);

export = zonesRouter;


text:
module Puppet::Parser::Functions
  newfunction(:mmm_slaves, :type => :rvalue) do |args|
    raise Puppet::ParseError, "Expected 1 argument, got #{args.size}" if args.size != 1
    raise Puppet::ParseError, "Must pass either a hostname or an array of hostnames" if args[0].empty?

    hostnames = args[0]
    ips       = []

    hostnames = [ hostnames ] if not hostnames.is_a? Array

    hostnames.each do |hostname|
      ip = `cat /etc/hosts | grep #{hostname} | head -1 | awk '{print $1}' | xargs echo -n`

      ips << {
        "host" => hostname,
        "ip"   => ip
      }
    end

    return ips
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorGreen"/>
    <size android:height="3dp" android:width="3dp"/>
</shape>


text:
APPVER = "0.4.0"
ABOUT = """\
Mailpile.py          a tool                 Copyright 2013-2014, Mailpile ehf
               for searching and                   <https://www.mailpile.is/>
           organizing piles of e-mail

This program is free software: you can redistribute it and/or modify it under
the terms of either the GNU Affero General Public License as published by the
Free Software Foundation or the Apache License 2.0 as published by the Apache
Software Foundation. See the file COPYING.md for details.
"""
#############################################################################
import os
import time

from mailpile.config import PathDict
from mailpile.config import ConfigRule as c
from mailpile.config import CriticalConfigRule as X
from mailpile.config import PublicConfigRule as p
from mailpile.config import KeyConfigRule as k

_ = lambda string: string

DEFAULT_SENDMAIL = '|/usr/sbin/sendmail -i %(rcpt)s'
CONFIG_PLUGINS = []
CONFIG_RULES = {
    'version': [_('Mailpile program version'), False, APPVER],
    'timestamp': [_('Configuration timestamp'), int, int(time.time())],
    'master_key': k(_('Master symmetric encryption key'), str, ''),
    'sys': p(_('Technical system settings'), False, {
        'fd_cache_size':  (_('Max files kept open at once'), int,         500),
        'history_length': (_('History length (lines, <0=no save)'), int,  100),
        'http_port':     p(_('Listening port for web UI'), int,         33411),
        'postinglist_kb': (_('Posting list target size in KB'), int,       64),
        'sort_max':       (_('Max results we sort "well"'), int,         2500),
        'snippet_max':    (_('Max length of metadata snippets'), int,     250),
        'debug':         p(_('Debugging flags'), str,                      ''),
        'gpg_keyserver':  (_('Host:port of PGP keyserver'),
                           str, 'pool.sks-keyservers.net'),
        'gpg_home':      p(_('Override the home directory of GnuPG'), 'dir',
                           None),
        'http_host':     p(_('Listening host for web UI'),
                           'hostname', 'localhost'),
        'local_mailbox_id': (_('Local read/write Maildir'), 'b36',         ''),
        'mailindex_file': (_('Metadata index file'), 'file',               ''),
        'postinglist_dir': (_('Search index directory'), 'dir',            ''),
        'mailbox':        [_('Mailboxes we index'), 'str',                 []],
        'plugins':        [_('Plugins to load on startup'),
                           CONFIG_PLUGINS, []],
        'path':           [_('Locations of assorted data'), False, {
            'html_theme': [_('Default theme'),
                           'dir', os.path.join('mailpile', 'www', 'default')],
            'vcards':     [_('Location of vcards'), 'dir', 'vcards'],
            'event_log':  [_('Location of event log'), 'dir', 'logs'],
        }],
        'lockdown':       [_('Demo mode, disallow changes'), bool,      False],
        'login_banner':   [_('A custom banner for the login page'), str,   ''],
    }),
    'prefs': p(_("User preferences"), False, {
        'num_results':     (_('Search results per page'), int,             20),
        'rescan_interval': (_('New mail check frequency'), int,           900),
        'open_in_browser': (_('Open in browser on startup'), bool,       True),
        'gpg_clearsign':  X(_('Inline PGP signatures or attached'),
                            bool, False),
        'gpg_recipient':  p(_('Encrypt local data to ...'), str,           ''),
        'gpg_email_key':  (_('Attach public key to outgoing messages?'),
                            bool, True),
        'openpgp_header': X(_('Advertise GPG preferences in a header?'),
                            ['', 'sign', 'encrypt', 'signencrypt'],
                            'signencrypt'),
        'crypto_policy':  X(_('Default encryption policy for outgoing mail'),
                            str, 'none'),
        'inline_pgp':      (_('Use inline PGP when possible'), bool,     True),
        'default_order':   (_('Default sort order'), str,          'rev-date'),
        'obfuscate_index': X(_('Key to use to scramble the index'), str,    ''),
        'index_encrypted': X(_('Make encrypted content searchable'),
                             bool, False),
        'encrypt_mail':   X(_('Encrypt locally stored mail'), bool,      True),
        'encrypt_index':  X(_('Encrypt the local search index'), bool,  False),
        'encrypt_vcards': X(_('Encrypt the contact database'), bool,     True),
        'encrypt_events': X(_('Encrypt the event log'), bool,            True),
        'encrypt_misc':   X(_('Encrypt misc. local data'), bool,         True),
        'rescan_command':  (_('Command run before rescanning'), str,       ''),
        'default_email':   (_('Default outgoing e-mail address'), 'email', ''),
        'default_route':   (_('Default outgoing mail route'), str, ''),
        'always_bcc_self': (_('Always BCC self on outgoing mail'), bool, True),
        'default_messageroute': (_('Default outgoing mail route'), str,    ''),
        'language':       p(_('User interface language'), str,             ''),
        'vcard':           [_("VCard import/export settings"), False, {
            'importers':   [_("VCard import settings"), False,             {}],
            'exporters':   [_("VCard export settings"), False,             {}],
            'context':     [_("VCard context helper settings"), False,     {}],
        }],
    }),
    'web': (_("Web Interface Preferences"), False, {
        'setup_complete':  (_('User completed setup experience'), bool, False),
        'display_density': (_('Display density of interface'), str, 'comfy'),
        'quoted_reply':    (_('Quote replies to messages'), str, 'unset'),
        'nag_backup_key':  (_('Nag user to backup their key'), int, 0),
        'subtags_collapsed': (_('Collapsed subtags in sidebar'), str, []),
        'donate_visibility': (_('Hide donate link in topbar'), bool, True)
    }),
    'logins': [_('Credentials allowed to access Mailpile'), {
        'password':        (_('Salted and hashed password'), str, '')
    }, {}],
    'routes': [_('Outgoing message routes'), {
        'name':            (_('Route name'), str, ''),
        'protocol':        (_('Messaging protocol'),
                            ["smtp", "smtptls", "smtpssl", "local"],
                            'smtp'),
        'username':        (_('User name'), str, ''),
        'password':        (_('Password'), str, ''),
        'command':         (_('Shell command'), str, ''),
        'host':            (_('Host'), str, ''),
        'port':            (_('Port'), int, 587)
    }, {}],
    'sources': [_('Incoming message sources'), {
        'name':            (_('Source name'), str, ''),
        'enabled':         (_('Is this mail source enabled?'), bool, True),
        'protocol':        (_('Mailbox protocol or format'),
                            ["mbox", "maildir", "macmaildir", "gmvault",
                             "imap", "imap_ssl", "pop3", "pop3_ssl"],
                            ''),
        'pre_command':     (_('Shell command run before syncing'), str, ''),
        'post_command':    (_('Shell command run after syncing'), str, ''),
        'interval':        (_('How frequently to check for mail'), int, 300),
        'username':        (_('User name'), str, ''),
        'password':        (_('Password'), str, ''),
        'host':            (_('Host'), str, ''),
        'port':            (_('Port'), int, 993),
        'keepalive':       (_('Keep server connections alive'), bool, False),
        'discovery':       (_('Mailbox discovery policy'), False, {
            'paths':       (_('Paths to watch for new mailboxes'), str, []),
            'policy':      (_('Default mailbox policy'),
                            ['unknown', 'ignore', 'watch',
                             'read', 'move', 'sync'], 'unknown'),
            'local_copy':  (_('Copy mail to a local mailbox?'), bool, False),
            'parent_tag':  (_('Parent tag for mailbox tags'), str, '!CREATE'),
            'guess_tags':  (_('Guess which local tags match'), bool, True),
            'create_tag':  (_('Create a tag for each mailbox?'), bool, True),
            'process_new': (_('Is a potential source of new mail'), bool, True),
            'apply_tags':  (_('Tags applied to messages'), str, []),
        }),
        'mailbox': (_('Mailboxes'), {
            'name':        (_('The name of this mailbox'), str, ''),
            'path':        (_('Mailbox source path'), str, ''),
            'policy':      (_('Mailbox policy'),
                            ['unknown', 'ignore', 'read', 'move', 'sync'],
                            'ignore'),
            'local':       (_('Local mailbox path'), str, ''),
            'process_new': (_('Is a source of new mail'), bool, True),
            'primary_tag': (_('A tag representing this mailbox'), str, ''),
            'apply_tags':  (_('Tags applied to messages'), str, []),
        }, {})
    }, {}],

    ### OLD CRAP, JUST HERE SO AS NOT TO KILL CONFIG FILES
    'profiles': [_('DEPRECATED: User profiles and personalities'), {
        'name':            (_('Account name'), 'str', ''),
        'email':           (_('E-mail address'), 'email', ''),
        'signature':       (_('Message signature'), 'multiline', ''),
        'route':           (_('DEPRECATED, DO NOT USE'), str, ''),
        'messageroute':    (_('Outgoing mail route'), str, ''),
    }, []]
}

if __name__ == "__main__":
    import mailpile.defaults
    from mailpile.config import ConfigDict

    print '%s' % (ConfigDict(_name='mailpile',
                             _comment='Base configuration',
                             _rules=mailpile.defaults.CONFIG_RULES
                             ).as_config_bytes(), )


text:
Stone::Stone(ResourcesManager* tm) : GameObject(tm, GO_TYPE_GROUND, "stone_normal", vec3(1.0f), vec3(1.0f)) {

}

Stone::Stone(ResourcesManager* tm, float size) : GameObject(tm, GO_TYPE_GROUND, "stone_normal", vec3(size), vec3(1.0f)) {

}

void Stone::update(GLFWwindow* window, float deltaTime) {

}


text:
import gtk    # Linux DBus Service
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop

from time      import strftime # use for clock simulation - shows time!
from time      import sleep    # use for delay in loops - wait for n sec.!
from threading import Thread   # use to create a single threat for time

import sys   # for unicode_to_kos0006u
import types # for unicode_to_kos0006u

import socket # check if tinker is available

from tinkerforge.ip_connection        import IPConnection
from tinkerforge.brick_master         import Master
from tinkerforge.bricklet_io16        import IO16
from tinkerforge.bricklet_rotary_poti import RotaryPoti
from tinkerforge.bricklet_lcd_20x4    import LCD20x4
from tinkerforge.bricklet_joystick    import Joystick
from tinkerforge.bricklet_industrial_quad_relay import IndustrialQuadRelay

try:
    from Board import Board as B
    from Menu import Menu as M
except ImportError as err:
    print err

def isOpen(ip,port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((ip, int(port)))
        s.shutdown(2)
        return True
    except:
        return False

class master():
    """docstring for master"""
    def __init__(self):
        #super(master, self).__init__()
        print 'init...'
        self.PORT   = 4223
        self.MENU_running = False
        self.BOARD_running = False

        ### Connection for Menu
        self.MENU_HOST   = "192.168.0.150" # Manually Set IP of Controller Board
        self.MENU_lcdUID = "gFt" # LCD Screen
        self.MENU_jskUID = "hAP" # Joystick
        ### END MENU CONNECTION

        ### Connection for Board
        self.BOARD_HOST   = "192.168.0.111"
        self.BOARD_mstUID = "62eUEf" # master brick
        self.BOARD_io1UID = "ghh"    # io16
        self.BOARD_lcdUID = "9ew"    # lcd screen 20x4
        self.BOARD_iqrUID = "eRN"    # industrial quad relay
        #### END BOARD CONNECTION

        print self.start()
        return

    def start(self):
        if self.BOARD_running: return 'Board already running!'
        else: self.startBoard(); return 'Board Started!'

        if self.MENU_running: return 'Menu already running!'
        else: self.startMenu(); return 'Menu Started!'
        return 'Started!'

    def status(self):
        return 'Board: '+str(self.BOARD_running)+'\nMenu: '+str(self.MENU_running)

    def startBoard(self):
        if self.BOARD_running: return 'Board already running!'

        if isOpen(self.BOARD_HOST, self.PORT):

            self.BOARD_running = True

            self.BOARD_ipcon = IPConnection() # Create IP connection

            self.mst = Master(self.BOARD_mstUID, self.BOARD_ipcon)   # Master Brick
            self.io1 = IO16(self.BOARD_io1UID, self.BOARD_ipcon)       # io16
            self.lcd1 = LCD20x4(self.BOARD_lcdUID, self.BOARD_ipcon)  # lcd20x4
            self.iqr = IndustrialQuadRelay(self.BOARD_iqrUID, self.BOARD_ipcon) # Create device object

            self.BOARD_ipcon.connect(self.BOARD_HOST, self.PORT) # Connect to brickd

            # create Board instance
            self.BB = B(self.mst, self.io1, self.lcd1, self.iqr, self.BOARD_ipcon)
        else:
            return 'Board is offline'
        return "Hello, Board successfully started!"

    def startMenu(self):
        if self.MENU_running: return 'Menu already running!'

        if isOpen(self.MENU_HOST, self.PORT):

            self.MENU_running = True

            # Connect to WLAN Controller
            self.MENU_ipcon = IPConnection() # Create IP connection

            self.lcd = LCD20x4(self.MENU_lcdUID, self.MENU_ipcon) # Create device object LCD
            self.jsk = Joystick(self.MENU_jskUID, self.MENU_ipcon) # Create device object JOYSTICK

            # Don't use device before ipcon is connected
            self.MENU_ipcon.connect(self.MENU_HOST, self.PORT) # Connect to brickd

            # create Menu instance with the nessesary Hardware # IPCON to close Tinker Connection
            self.MM = M(self.jsk, self.lcd, self.MENU_ipcon)
        else:
            return 'Menu is offline'

        return "Hello, Menu successfully started!"

    def stop(self):
        print 'stopping devices...'
        if self.MENU_running:
            self.MENU_running = False
            self.MM.quit()
        if self.BOARD_running:
            self.BOARD_running = False
            self.BB.quit()    # Stop Board
        quit()
        return 'successfully stopped'

class MyDBUSService(dbus.service.Object):
    def __init__(self):
        bus_name = dbus.service.BusName('org.limeblack.roomcontroll', bus=dbus.SessionBus())
        dbus.service.Object.__init__(self, bus_name, '/org/limeblack/roomcontroll')
        try:
            print 'Start initalisation'

            self.masterInstance = master()
            print self.masterInstance.status()

            print self.masterInstance.BOARD_running

            print 'Initialisation ready!'

        except Exception as errtxt:
            print errtxt

    @dbus.service.method('org.limeblack.roomcontroll')
    def status(self):
        #return 'Board: '+str(self.BoardIsRunning)+'\nMenu: '+str(self.MenuIsRunning)#
        pass

    @dbus.service.method('org.limeblack.roomcontroll')
    def startBoard(self):
        #if self.BoardIsRunning: return 'Board already running!'

        #else:
        #    return 'Board is offline'
        #return "Hello, Board successfully started!"
        pass

    @dbus.service.method('org.limeblack.roomcontroll')
    def startMenu(self):
        #if self.MenuIsRunning: return 'Menu already running!'

        #else:
        #    return 'Menu is offline'

        #return "Hello, Menu successfully started!"
        pass

    @dbus.service.method('org.limeblack.roomcontroll')
    def bye(self):
        #if self.BoardIsRunning:
        #    self.BoardIsRunning = False
        #    self.BB.quit()
        #if self.MenuIsRunning:
        #    self.MenuIsRunning = False
        #    self.MM.quit()

        #return "Shutdown successfully!"
        self.masterInstance.stop()
        #pass

if __name__ == "__main__":
    try:

        DBusGMainLoop(set_as_default=True)
        myservice = MyDBUSService()
        gtk.main()

        # On Press close Application
        raw_input('Press key to exit\n') # Use input() in Python 3
        MyDBUSService.bye()

    except Exception as errtxt:
        print errtxt


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.restapi.user;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.yahoo.config.provision.TenantName;
import com.yahoo.slime.Slime;
import com.yahoo.slime.SlimeUtils;
import com.yahoo.test.json.JsonTestHelper;
import com.yahoo.vespa.flags.FetchVector;
import com.yahoo.vespa.flags.FlagId;
import com.yahoo.vespa.flags.Flags;
import com.yahoo.vespa.flags.JsonNodeRawFlag;
import com.yahoo.vespa.flags.json.Condition;
import com.yahoo.vespa.flags.json.FlagData;
import com.yahoo.vespa.flags.json.Rule;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL;
import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID;

/**
 * @author freva
 */
public class UserFlagsSerializerTest {

    @Test
    void user_flag_test() throws IOException {
        String email1 = "alice@domain.tld";
        String email2 = "bob@domain.tld";

        try (Flags.Replacer ignored = Flags.clearFlagsForTesting()) {
            Flags.defineStringFlag("string-id", "default value", List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod", CONSOLE_USER_EMAIL);
            Flags.defineIntFlag("int-id", 123, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod", CONSOLE_USER_EMAIL, TENANT_ID, APPLICATION_ID);
            Flags.defineDoubleFlag("double-id", 3.14d, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod");
            Flags.defineListFlag("list-id", List.of("a"), String.class, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod", CONSOLE_USER_EMAIL);
            Flags.defineJacksonFlag("jackson-id", new ExampleJacksonClass(123, "abc"), ExampleJacksonClass.class,
                    List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod", CONSOLE_USER_EMAIL, TENANT_ID);

            Map<FlagId, FlagData> flagData = Stream.of(
                    flagData("string-id", rule("\"value1\"", condition(CONSOLE_USER_EMAIL, Condition.Type.WHITELIST, email1))),
                    flagData("int-id", rule("456")),
                    flagData("list-id",
                            rule("[\"value1\"]", condition(CONSOLE_USER_EMAIL, Condition.Type.WHITELIST, email1), condition(APPLICATION_ID, Condition.Type.BLACKLIST, "tenant1:video:default", "tenant1:video:default", "tenant2:music:default")),
                            rule("[\"value2\"]", condition(CONSOLE_USER_EMAIL, Condition.Type.WHITELIST, email2)),
                            rule("[\"value1\",\"value3\"]", condition(APPLICATION_ID, Condition.Type.BLACKLIST, "tenant1:video:default", "tenant1:video:default", "tenant2:music:default"))),
                    flagData("jackson-id", rule("{\"integer\":456,\"string\":\"xyz\"}", condition(CONSOLE_USER_EMAIL, Condition.Type.WHITELIST, email1), condition(TENANT_ID, Condition.Type.WHITELIST, "tenant1", "tenant3")))
            ).collect(Collectors.toMap(FlagData::id, fd -> fd));

            // double-id is not here as it does not have CONSOLE_USER_EMAIL dimension
            assertUserFlags("{\"flags\":[" +
                    "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
                    "{\"id\":\"jackson-id\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"tenant\"}],\"value\":{\"integer\":456,\"string\":\"xyz\"}},{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Resolved for email
                    // Resolved for email, but conditions are empty since this user is not authorized for any tenants
                    "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\"}],\"value\":[\"value1\"]},{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\"}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
                    "{\"id\":\"string-id\",\"rules\":[{\"value\":\"value1\"}]}]}", // resolved for email
                    flagData, Set.of(), false, email1);

            // Same as the first one, but user is authorized for tenant1
            assertUserFlags("{\"flags\":[" +
                    "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
                    "{\"id\":\"jackson-id\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"tenant\",\"values\":[\"tenant1\"]}],\"value\":{\"integer\":456,\"string\":\"xyz\"}},{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Resolved for email
                    // Resolved for email, but conditions have filtered out tenant2
                    "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\"]}],\"value\":[\"value1\"]},{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\"]}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
                    "{\"id\":\"string-id\",\"rules\":[{\"value\":\"value1\"}]}]}", // resolved for email
                    flagData, Set.of("tenant1"), false, email1);

            // As operator no conditions are filtered, but the email precondition is applied
            assertUserFlags("{\"flags\":[" +
                    "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
                    "{\"id\":\"jackson-id\",\"rules\":[{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Default from code, no DB values match
                    // Includes last value from DB which is not conditioned on email and the default from code
                    "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\",\"tenant2:music:default\"]}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
                    "{\"id\":\"string-id\",\"rules\":[{\"value\":\"default value\"}]}]}", // Default from code
                    flagData, Set.of(), true, "operator@domain.tld");
        }
    }

    private static FlagData flagData(String id, Rule... rules) {
        return new FlagData(new FlagId(id), new FetchVector(), rules);
    }

    private static Rule rule(String data, Condition... conditions) {
        return new Rule(Optional.ofNullable(data).map(JsonNodeRawFlag::fromJson), conditions);
    }

    private static Condition condition(FetchVector.Dimension dimension, Condition.Type type, String... values) {
        return new Condition.CreateParams(dimension).withValues(values).createAs(type);
    }

    private static void assertUserFlags(String expected, Map<FlagId, FlagData> rawFlagData,
                                        Set<String> authorizedForTenantNames, boolean isOperator, String userEmail) throws IOException {
        Slime slime = new Slime();
        UserFlagsSerializer.toSlime(slime.setObject(), rawFlagData, authorizedForTenantNames.stream().map(TenantName::from).collect(Collectors.toSet()), isOperator, userEmail);
        JsonTestHelper.assertJsonEquals(expected,
                new String(SlimeUtils.toJsonBytes(slime), StandardCharsets.UTF_8));
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    private static class ExampleJacksonClass {
        @JsonProperty("integer") public final int integer;
        @JsonProperty("string") public final String string;
        private ExampleJacksonClass(@JsonProperty("integer") int integer, @JsonProperty("string") String string) {
            this.integer = integer;
            this.string = string;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            ExampleJacksonClass that = (ExampleJacksonClass) o;
            return integer == that.integer &&
                    Objects.equals(string, that.string);
        }

        @Override
        public int hashCode() {
            return Objects.hash(integer, string);
        }
    }
}


text:
<?php

namespace League\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\Exception\InstagramIdentityProviderException;
use League\OAuth2\Client\Token\AccessToken;
use League\OAuth2\Client\Token\AccessTokenInterface;
use Psr\Http\Message\ResponseInterface;

class Instagram extends AbstractProvider
{
    /**
     * @var string Key used in a token response to identify the resource owner.
     */
    const ACCESS_TOKEN_RESOURCE_OWNER_ID = 'user_id';

    /**
     * Default scopes
     *
     * @var array
     */
    public $defaultScopes = ['user_profile'];

    /**
     * Default host
     *
     * @var string
     */
    protected $host = 'https://api.instagram.com';

    /**
     * Default Graph API host
     *
     * @var string
     */
    protected $graphHost = 'https://graph.instagram.com';

    /**
     * Gets host.
     *
     * @return string
     */
    public function getHost()
    {
        return $this->host;
    }

    /**
     * Gets Graph API host.
     *
     * @return string
     */
    public function getGraphHost()
    {
        return $this->graphHost;
    }

    /**
     * Get the string used to separate scopes.
     *
     * @return string
     */
    protected function getScopeSeparator()
    {
        return ' ';
    }

    /**
     * Get authorization url to begin OAuth flow
     *
     * @return string
     */
    public function getBaseAuthorizationUrl()
    {
        return $this->host.'/oauth/authorize';
    }

    /**
     * Get access token url to retrieve token
     *
     * @param  array $params
     *
     * @return string
     */
    public function getBaseAccessTokenUrl(array $params)
    {
        return $this->host.'/oauth/access_token';
    }

    /**
     * Get access token url to
     *  - exchange short-lived token for a long-lived token
     *  - refresh unexpired long-lived token
     *
     * @param array $params
     * @param string $endPoint
     *
     * @return string
     */
    public function getUpdateAccessTokenUrl(array $params, $endPoint)
    {
        return $this->graphHost.'/'.$endPoint;
    }

    /**
     * Get provider url to fetch user details
     *
     * @param  AccessToken $token
     *
     * @return string
     */
    public function getResourceOwnerDetailsUrl(AccessToken $token)
    {
        return $this->graphHost.'/me?fields=id,username&access_token='.$token;
    }

    /**
     * Returns an authenticated PSR-7 request instance.
     *
     * @param  string $method
     * @param  string $url
     * @param  AccessToken|string $token
     * @param  array $options Any of "headers", "body", and "protocolVersion".
     *
     * @return \Psr\Http\Message\RequestInterface
     */
    public function getAuthenticatedRequest($method, $url, $token, array $options = [])
    {
        $parsedUrl = parse_url($url);
        $queryString = array();

        if (isset($parsedUrl['query'])) {
            parse_str($parsedUrl['query'], $queryString);
        }

        if (!isset($queryString['access_token'])) {
            $queryString['access_token'] = (string) $token;
        }

        $url = http_build_url($url, [
            'query' => http_build_query($queryString),
        ]);

        return $this->createRequest($method, $url, null, $options);
    }

    /**
     * Get the default scopes used by this provider.
     *
     * This should not be a complete list of all scopes, but the minimum
     * required for the provider user interface!
     *
     * @return array
     */
    protected function getDefaultScopes()
    {
        return $this->defaultScopes;
    }

    /**
     * Check a provider response for errors.
     *
     * @throws InstagramIdentityProviderException
     * @param  ResponseInterface $response
     * @param  string $data Parsed response data
     * @return void
     */
    protected function checkResponse(ResponseInterface $response, $data)
    {
        // Standard error response format
        if (!empty($data['error'])) {
            throw InstagramIdentityProviderException::clientException($response, $data);
        }

        // OAuthException error response format
        if (!empty($data['error_type'])) {
            throw InstagramIdentityProviderException::oauthException($response, $data);
        }
    }

    /**
     * Exchanges a short-lived access token with a long-lived access-token.
     *
     * @param string|AccessTokenInterface $accessToken
     *
     * @return \League\OAuth2\Client\Token\AccessToken
     *
     * @throws InstagramIdentityProviderException
     */
    public function getLongLivedAccessToken($accessToken)
    {
        $params = [
            'client_secret' => $this->clientSecret
        ];

        return $this->getUpdatedAccessToken($accessToken, 'ig_exchange_token', $params);
    }

    /**
     * Refresh a long-lived token
     *
     * @param string|AccessTokenInterface $accessToken
     *
     * @return \League\OAuth2\Client\Token\AccessToken
     *
     * @throws InstagramIdentityProviderException
     */
    public function getRefreshedAccessToken($accessToken)
    {
        return $this->getUpdatedAccessToken($accessToken, 'ig_refresh_token');
    }

    /**
     * Update token based on grant type
     *
     * @param string|AccessTokenInterface $accessToken
     * @param string $grant
     * @param array $params
     *
     * @return \League\OAuth2\Client\Token\AccessToken
     *
     * @throws InstagramIdentityProviderException
     */
    protected function getUpdatedAccessToken($accessToken, $grant, $params = [])
    {
        $verifiedGrant = $this->verifyGrant($grant);

        $params = array_merge([
            'access_token' => (string) $accessToken,
        ], $params);

        $params = $verifiedGrant->prepareRequestParameters($params, []);

        if ($grant === 'ig_exchange_token') {
            $updateEndpoint = 'access_token';
        } elseif ($grant === 'ig_refresh_token') {
            $updateEndpoint = 'refresh_access_token';
        } else {
            throw new \UnexpectedValueException(
                sprintf('Invalid grand type "%s". cannot generate update token url.', $grant)
            );
        }

        $url = $this->getUpdateAccessTokenUrl($params, $updateEndpoint);
        $query = $this->getAccessTokenQuery($params);

        $request = $this->getRequest(self::METHOD_GET, $this->appendQuery($url, $query));
        $response = $this->getParsedResponse($request);

        if (false === is_array($response)) {
            throw new \UnexpectedValueException(
                'Invalid response received from Authorization Server. Expected JSON.'
            );
        }

        $prepared = $this->prepareAccessTokenResponse($response);

        return $this->createAccessToken($prepared, $verifiedGrant);
    }

    /**
     * Generate a user object from a successful user details request.
     *
     * @param array $response
     * @param AccessToken $token
     * @return ResourceOwnerInterface
     */
    protected function createResourceOwner(array $response, AccessToken $token)
    {
        return new InstagramResourceOwner($response);
    }

    /**
     * Sets host.
     *
     * @param string $host
     *
     * @return self
     */
    public function setHost($host)
    {
        $this->host = $host;

        return $this;
    }

    /**
     * Sets Graph API host.
     *
     * @param string $host
     *
     * @return self
     */
    public function setGraphHost($host)
    {
        $this->graphHost = $host;

        return $this;
    }
}


text:
/****** Object:  StoredProcedure [dbo].[app_ProgramGame_Delete]    Script Date: 01/05/2015 14:43:24 ******/
--Create the Delete Proc
CREATE PROCEDURE [dbo].[app_ProgramGame_Delete] @PGID INT
AS
DELETE ProgramGameLevel
WHERE PGID = @PGID

DELETE
FROM [ProgramGame]
WHERE PGID = @PGID


text:
/**
 * This class is generated by jOOQ
 */
package io.cattle.platform.core.model.tables.records;

/**
 * This class is generated by jOOQ.
 */
@javax.annotation.Generated(value    = { "http://www.jooq.org", "3.3.0" },
                            comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
@javax.persistence.Entity
@javax.persistence.Table(name = "host", schema = "cattle")
public class HostRecord extends org.jooq.impl.UpdatableRecordImpl<io.cattle.platform.core.model.tables.records.HostRecord> implements io.cattle.platform.db.jooq.utils.TableRecordJaxb, io.cattle.platform.core.model.Host {

	private static final long serialVersionUID = 995834607;

	/**
	 * Setter for cattle.host.id.
	 */
	@Override
	public void setId(java.lang.Long value) {
		setValue(0, value);
	}

	/**
	 * Getter for cattle.host.id.
	 */
	@javax.persistence.Id
	@javax.persistence.Column(name = "id", unique = true, nullable = false, precision = 19)
	@Override
	public java.lang.Long getId() {
		return (java.lang.Long) getValue(0);
	}

	/**
	 * Setter for cattle.host.name.
	 */
	@Override
	public void setName(java.lang.String value) {
		setValue(1, value);
	}

	/**
	 * Getter for cattle.host.name.
	 */
	@javax.persistence.Column(name = "name", length = 255)
	@Override
	public java.lang.String getName() {
		return (java.lang.String) getValue(1);
	}

	/**
	 * Setter for cattle.host.account_id.
	 */
	@Override
	public void setAccountId(java.lang.Long value) {
		setValue(2, value);
	}

	/**
	 * Getter for cattle.host.account_id.
	 */
	@javax.persistence.Column(name = "account_id", precision = 19)
	@Override
	public java.lang.Long getAccountId() {
		return (java.lang.Long) getValue(2);
	}

	/**
	 * Setter for cattle.host.kind.
	 */
	@Override
	public void setKind(java.lang.String value) {
		setValue(3, value);
	}

	/**
	 * Getter for cattle.host.kind.
	 */
	@javax.persistence.Column(name = "kind", nullable = false, length = 255)
	@Override
	public java.lang.String getKind() {
		return (java.lang.String) getValue(3);
	}

	/**
	 * Setter for cattle.host.uuid.
	 */
	@Override
	public void setUuid(java.lang.String value) {
		setValue(4, value);
	}

	/**
	 * Getter for cattle.host.uuid.
	 */
	@javax.persistence.Column(name = "uuid", unique = true, nullable = false, length = 128)
	@Override
	public java.lang.String getUuid() {
		return (java.lang.String) getValue(4);
	}

	/**
	 * Setter for cattle.host.description.
	 */
	@Override
	public void setDescription(java.lang.String value) {
		setValue(5, value);
	}

	/**
	 * Getter for cattle.host.description.
	 */
	@javax.persistence.Column(name = "description", length = 1024)
	@Override
	public java.lang.String getDescription() {
		return (java.lang.String) getValue(5);
	}

	/**
	 * Setter for cattle.host.state.
	 */
	@Override
	public void setState(java.lang.String value) {
		setValue(6, value);
	}

	/**
	 * Getter for cattle.host.state.
	 */
	@javax.persistence.Column(name = "state", nullable = false, length = 128)
	@Override
	public java.lang.String getState() {
		return (java.lang.String) getValue(6);
	}

	/**
	 * Setter for cattle.host.created.
	 */
	@Override
	public void setCreated(java.util.Date value) {
		setValue(7, value);
	}

	/**
	 * Getter for cattle.host.created.
	 */
	@javax.persistence.Column(name = "created")
	@Override
	public java.util.Date getCreated() {
		return (java.util.Date) getValue(7);
	}

	/**
	 * Setter for cattle.host.removed.
	 */
	@Override
	public void setRemoved(java.util.Date value) {
		setValue(8, value);
	}

	/**
	 * Getter for cattle.host.removed.
	 */
	@javax.persistence.Column(name = "removed")
	@Override
	public java.util.Date getRemoved() {
		return (java.util.Date) getValue(8);
	}

	/**
	 * Setter for cattle.host.remove_time.
	 */
	@Override
	public void setRemoveTime(java.util.Date value) {
		setValue(9, value);
	}

	/**
	 * Getter for cattle.host.remove_time.
	 */
	@javax.persistence.Column(name = "remove_time")
	@Override
	public java.util.Date getRemoveTime() {
		return (java.util.Date) getValue(9);
	}

	/**
	 * Setter for cattle.host.data.
	 */
	@Override
	public void setData(java.util.Map<String,Object> value) {
		setValue(10, value);
	}

	/**
	 * Getter for cattle.host.data.
	 */
	@javax.persistence.Column(name = "data", length = 16777215)
	@Override
	public java.util.Map<String,Object> getData() {
		return (java.util.Map<String,Object>) getValue(10);
	}

	/**
	 * Setter for cattle.host.uri.
	 */
	@Override
	public void setUri(java.lang.String value) {
		setValue(11, value);
	}

	/**
	 * Getter for cattle.host.uri.
	 */
	@javax.persistence.Column(name = "uri", length = 255)
	@Override
	public java.lang.String getUri() {
		return (java.lang.String) getValue(11);
	}

	/**
	 * Setter for cattle.host.compute_free.
	 */
	@Override
	public void setComputeFree(java.lang.Long value) {
		setValue(12, value);
	}

	/**
	 * Getter for cattle.host.compute_free.
	 */
	@javax.persistence.Column(name = "compute_free", precision = 19)
	@Override
	public java.lang.Long getComputeFree() {
		return (java.lang.Long) getValue(12);
	}

	/**
	 * Setter for cattle.host.compute_total.
	 */
	@Override
	public void setComputeTotal(java.lang.Long value) {
		setValue(13, value);
	}

	/**
	 * Getter for cattle.host.compute_total.
	 */
	@javax.persistence.Column(name = "compute_total", precision = 19)
	@Override
	public java.lang.Long getComputeTotal() {
		return (java.lang.Long) getValue(13);
	}

	/**
	 * Setter for cattle.host.agent_id.
	 */
	@Override
	public void setAgentId(java.lang.Long value) {
		setValue(14, value);
	}

	/**
	 * Getter for cattle.host.agent_id.
	 */
	@javax.persistence.Column(name = "agent_id", precision = 19)
	@Override
	public java.lang.Long getAgentId() {
		return (java.lang.Long) getValue(14);
	}

	/**
	 * Setter for cattle.host.zone_id.
	 */
	@Override
	public void setZoneId(java.lang.Long value) {
		setValue(15, value);
	}

	/**
	 * Getter for cattle.host.zone_id.
	 */
	@javax.persistence.Column(name = "zone_id", precision = 19)
	@Override
	public java.lang.Long getZoneId() {
		return (java.lang.Long) getValue(15);
	}

	/**
	 * Setter for cattle.host.physical_host_id.
	 */
	@Override
	public void setPhysicalHostId(java.lang.Long value) {
		setValue(16, value);
	}

	/**
	 * Getter for cattle.host.physical_host_id.
	 */
	@javax.persistence.Column(name = "physical_host_id", precision = 19)
	@Override
	public java.lang.Long getPhysicalHostId() {
		return (java.lang.Long) getValue(16);
	}

	/**
	 * Setter for cattle.host.is_public.
	 */
	@Override
	public void setIsPublic(java.lang.Boolean value) {
		setValue(17, value);
	}

	/**
	 * Getter for cattle.host.is_public.
	 */
	@javax.persistence.Column(name = "is_public", nullable = false, precision = 1)
	@Override
	public java.lang.Boolean getIsPublic() {
		return (java.lang.Boolean) getValue(17);
	}

	/**
	 * Setter for cattle.host.agent_state.
	 */
	@Override
	public void setAgentState(java.lang.String value) {
		setValue(18, value);
	}

	/**
	 * Getter for cattle.host.agent_state.
	 */
	@javax.persistence.Column(name = "agent_state", length = 128)
	@Override
	public java.lang.String getAgentState() {
		return (java.lang.String) getValue(18);
	}

	/**
	 * Setter for cattle.host.local_storage_mb.
	 */
	@Override
	public void setLocalStorageMb(java.lang.Long value) {
		setValue(19, value);
	}

	/**
	 * Getter for cattle.host.local_storage_mb.
	 */
	@javax.persistence.Column(name = "local_storage_mb", precision = 19)
	@Override
	public java.lang.Long getLocalStorageMb() {
		return (java.lang.Long) getValue(19);
	}

	/**
	 * Setter for cattle.host.memory.
	 */
	@Override
	public void setMemory(java.lang.Long value) {
		setValue(20, value);
	}

	/**
	 * Getter for cattle.host.memory.
	 */
	@javax.persistence.Column(name = "memory", precision = 19)
	@Override
	public java.lang.Long getMemory() {
		return (java.lang.Long) getValue(20);
	}

	/**
	 * Setter for cattle.host.milli_cpu.
	 */
	@Override
	public void setMilliCpu(java.lang.Long value) {
		setValue(21, value);
	}

	/**
	 * Getter for cattle.host.milli_cpu.
	 */
	@javax.persistence.Column(name = "milli_cpu", precision = 19)
	@Override
	public java.lang.Long getMilliCpu() {
		return (java.lang.Long) getValue(21);
	}

	/**
	 * Setter for cattle.host.environment_id.
	 */
	@Override
	public void setStackId(java.lang.Long value) {
		setValue(22, value);
	}

	/**
	 * Getter for cattle.host.environment_id.
	 */
	@javax.persistence.Column(name = "environment_id", precision = 19)
	@Override
	public java.lang.Long getStackId() {
		return (java.lang.Long) getValue(22);
	}

	/**
	 * Setter for cattle.host.remove_after.
	 */
	@Override
	public void setRemoveAfter(java.util.Date value) {
		setValue(23, value);
	}

	/**
	 * Getter for cattle.host.remove_after.
	 */
	@javax.persistence.Column(name = "remove_after")
	@Override
	public java.util.Date getRemoveAfter() {
		return (java.util.Date) getValue(23);
	}

	/**
	 * Setter for cattle.host.host_template_id.
	 */
	@Override
	public void setHostTemplateId(java.lang.Long value) {
		setValue(24, value);
	}

	/**
	 * Getter for cattle.host.host_template_id.
	 */
	@javax.persistence.Column(name = "host_template_id", precision = 19)
	@Override
	public java.lang.Long getHostTemplateId() {
		return (java.lang.Long) getValue(24);
	}

	// -------------------------------------------------------------------------
	// Primary key information
	// -------------------------------------------------------------------------

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Record1<java.lang.Long> key() {
		return (org.jooq.Record1) super.key();
	}

	// -------------------------------------------------------------------------
	// FROM and INTO
	// -------------------------------------------------------------------------

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void from(io.cattle.platform.core.model.Host from) {
		setId(from.getId());
		setName(from.getName());
		setAccountId(from.getAccountId());
		setKind(from.getKind());
		setUuid(from.getUuid());
		setDescription(from.getDescription());
		setState(from.getState());
		setCreated(from.getCreated());
		setRemoved(from.getRemoved());
		setRemoveTime(from.getRemoveTime());
		setData(from.getData());
		setUri(from.getUri());
		setComputeFree(from.getComputeFree());
		setComputeTotal(from.getComputeTotal());
		setAgentId(from.getAgentId());
		setZoneId(from.getZoneId());
		setPhysicalHostId(from.getPhysicalHostId());
		setIsPublic(from.getIsPublic());
		setAgentState(from.getAgentState());
		setLocalStorageMb(from.getLocalStorageMb());
		setMemory(from.getMemory());
		setMilliCpu(from.getMilliCpu());
		setStackId(from.getStackId());
		setRemoveAfter(from.getRemoveAfter());
		setHostTemplateId(from.getHostTemplateId());
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public <E extends io.cattle.platform.core.model.Host> E into(E into) {
		into.from(this);
		return into;
	}

	// -------------------------------------------------------------------------
	// Constructors
	// -------------------------------------------------------------------------

	/**
	 * Create a detached HostRecord
	 */
	public HostRecord() {
		super(io.cattle.platform.core.model.tables.HostTable.HOST);
	}

	/**
	 * Create a detached, initialised HostRecord
	 */
	public HostRecord(java.lang.Long id, java.lang.String name, java.lang.Long accountId, java.lang.String kind, java.lang.String uuid, java.lang.String description, java.lang.String state, java.util.Date created, java.util.Date removed, java.util.Date removeTime, java.util.Map<String,Object> data, java.lang.String uri, java.lang.Long computeFree, java.lang.Long computeTotal, java.lang.Long agentId, java.lang.Long zoneId, java.lang.Long physicalHostId, java.lang.Boolean isPublic, java.lang.String agentState, java.lang.Long localStorageMb, java.lang.Long memory, java.lang.Long milliCpu, java.lang.Long environmentId, java.util.Date removeAfter, java.lang.Long hostTemplateId) {
		super(io.cattle.platform.core.model.tables.HostTable.HOST);

		setValue(0, id);
		setValue(1, name);
		setValue(2, accountId);
		setValue(3, kind);
		setValue(4, uuid);
		setValue(5, description);
		setValue(6, state);
		setValue(7, created);
		setValue(8, removed);
		setValue(9, removeTime);
		setValue(10, data);
		setValue(11, uri);
		setValue(12, computeFree);
		setValue(13, computeTotal);
		setValue(14, agentId);
		setValue(15, zoneId);
		setValue(16, physicalHostId);
		setValue(17, isPublic);
		setValue(18, agentState);
		setValue(19, localStorageMb);
		setValue(20, memory);
		setValue(21, milliCpu);
		setValue(22, environmentId);
		setValue(23, removeAfter);
		setValue(24, hostTemplateId);
	}
}


text:
[![Project Status: Active - The project has reached a stable, usable state and is being actively developed.](http://www.repostatus.org/badges/latest/active.svg)](http://www.repostatus.org/#active)
[![License](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](LICENSE.md)

Advanced Unicode plotting library designed for use in Julia's REPL.

## Installation

[![Package Evaluator v3](http://pkg.julialang.org/badges/UnicodePlots_0.3.svg)](http://pkg.julialang.org/?pkg=UnicodePlots&ver=0.3)
[![Package Evaluator v4](http://pkg.julialang.org/badges/UnicodePlots_0.4.svg)](http://pkg.julialang.org/?pkg=UnicodePlots&ver=0.4)
[![Package Evaluator v5](http://pkg.julialang.org/badges/UnicodePlots_0.5.svg)](http://pkg.julialang.org/?pkg=UnicodePlots&ver=0.5)

There are no dependencies on other packages.

```Julia
Pkg.add("UnicodePlots")
using UnicodePlots
```

For the latest developer version:

[![Build Status](https://travis-ci.org/Evizero/UnicodePlots.jl.svg?branch=master)](https://travis-ci.org/Evizero/UnicodePlots.jl)
[![Coverage Status](https://coveralls.io/repos/Evizero/UnicodePlots.jl/badge.svg?branch=master&service=github)](https://coveralls.io/github/Evizero/UnicodePlots.jl?branch=master)

```Julia
Pkg.checkout("UnicodePlots")
```

## High-level Interface

There are a couple of ways to generate typical plots without much verbosity. Here is a list of the main high-level functions for common scenarios:

  - Scatterplot
  - Lineplot
  - Barplot (horizontal)
  - Staircase Plot
  - Histogram (horizontal)
  - Sparsity Pattern
  - Density Plot

Here is a quick hello world example of a typical use-case:

```Julia
myPlot = lineplot([-1, 2, 3, 7], [1, 2, 9, 4], title = "My Plot", name = "my line")
```

![Basic Canvas](doc/img/hello_world.png)

There are other types of `Canvas` available (see section "Low-level Interface").
In some situations, such as printing to a file, using `AsciiCanvas`, `DotCanvas` or `BlockCanvas` might lead to better results.

```Julia
lineplot([-1, 2, 3, 7], [1, 2, 9, 4], title = "My Plot", name = "my line", canvas = AsciiCanvas, border = :ascii)
```

![Basic Canvas](doc/img/ascii.png)

Every plot has a mutating variant that ends with a exclamation mark.

```Julia
lineplot!(myPlot, [0, 4, 8], [10, 1, 10], color = :yellow, name = "other line")
```

![Basic Canvas](doc/img/hello_world2.png)

#### Scatterplot

```Julia
scatterplot(randn(50), randn(50), title = "My Scatterplot", color = :red)
```
![Scatterplot Screenshot](doc/img/scatter.png)

#### Lineplot

```Julia
lineplot([1, 2, 7], [9, -6, 8], title = "My Lineplot", color = :blue)
```
![Lineplot Screenshot1](doc/img/line.png)

It's also possible to specify a function and a range.

```Julia
myPlot = lineplot([cos, sin], -π/2, 2π)
```
![Lineplot Screenshot2](doc/img/sin.png)

You can also plot lines by specifying an intercept and slope

```Julia
lineplot!(myPlot, -0.5, .2)
```
![Lineplot Screenshot3](doc/img/abline.png)

#### Barplot

Accepts either two vectors or a dictionary

```Julia
barplot(["Paris", "New York", "Moskau", "Madrid"],
        [2.244, 8.406, 11.92, 3.165],
        title = "Population")
```
![Barplot Screenshot](doc/img/barplot.png)

_Note_: You can use the keyword argument `symb` to specify the character that should
be used to plot the bars. For example `symb = "#"`

#### Staircase plot

```Julia
# supported style are :pre and :post
stairs([1, 2, 4, 7, 8], [1, 3, 4, 2, 7], color = :red, style = :post, title = "My Staircase Plot")
```
![Staircase Screenshot](doc/img/stairs.png)

#### Histogram

```Julia
histogram(randn(1000), bins = 15, title = "Histogram")
```
![Histogram Screenshot](doc/img/hist.png)

#### Sparsity Pattern

```Julia
spy(sprandn(50, 120, .05))
```
![Spy Screenshot](doc/img/spy.png)

#### Density Plot

```Julia
myPlot = densityplot(randn(1000), randn(1000), color = :blue)
densityplot!(myPlot, randn(1000) + 2, randn(1000) + 2, color = :red)
```
![Density Screenshot](doc/img/density.png)

### Options

All plots support a common set of named parameters

- `title::String = ""`:

    Text to display on the top of the plot.

- `name::String = ""`:

    Annotation of the current drawing to displayed on the right

- `width::Int = 40`:

    Number of characters per row that should be used for plotting.

    ```Julia
    lineplot(sin, 1:.5:20, width = 80)
    ```
    ![Width Screenshot](doc/img/width.png)

- `height::Int = 20`:

    Number of rows that should be used for plotting. Not applicable to `barplot`.

    ```Julia
    lineplot(sin, 1:.5:20, height = 18)
    ```
    ![Height Screenshot](doc/img/height.png)

- `xlim::Vector = [0, 1]`:

    Plotting range for the x coordinate

- `ylim::Vector = [0, 1]`:

    Plotting range for the y coordinate

- `margin::Int = 3`:

    Number of empty characters to the left of the whole plot.

- `border::Symbol = :solid`:

    The style of the bounding box of the plot. Supports `:solid`, `:bold`, `:dashed`, `:dotted`, `:ascii`, and `:none`.

  ```Julia
  lineplot([-1.,2, 3, 7], [1.,2, 9, 4], border=:bold)
  lineplot([-1.,2, 3, 7], [1.,2, 9, 4], border=:dashed)
  lineplot([-1.,2, 3, 7], [1.,2, 9, 4], border=:dotted)
  lineplot([-1.,2, 3, 7], [1.,2, 9, 4], border=:none)
  ```
    ![Border Screenshot](doc/img/border.png)

- `padding::Int = 1`:

    Space of the left and right of the plot between the labels and the canvas.

- `labels::Bool = true`:

    Can be used to hide the labels by setting `labels=false`.

  ```Julia
  lineplot(sin, 1:.5:20, labels=false)
  ```
    ![Labels Screenshot](doc/img/labels.png)

- `grid::Bool = true`:

    Can be used to hide the gridlines at the origin

- `color::Symbol = :blue`:

    Color of the drawing. Can be any of `:blue`, `:red`, `:yellow`

- `canvas::Type = BrailleCanvas`:

    The type of canvas that should be used for drawing (see section "Low-level Interface")

- `symb::AbstractString = "▪"`:

    Barplot only. Specifies the character that should be used to render the bars

_Note_: If you want to print the plot into a file but have monospace issues with your font, you should probably try `border = :ascii` and `canvas = AsciiCanvas` (or `canvas = DotCanvas` for scatterplots).

### Methods

- `title!(plot::Plot, title::String)`

    - `title` the string to write in the top center of the plot window. If the title is empty the whole line of the title will not be drawn

- `xlabel!(plot::Plot, xlabel::String)`

    - `xlabel` the string to display on the bottom of the plot window. If the title is empty the whole line of the label will not be drawn

- `ylabel!(plot::Plot, xlabel::String)`

    - `ylabel` the string to display on the far left of the plot window.

The method `annotate!` is responsible for the setting all the textual decorations of a plot. It has two functions:

- `annotate!(plot::Plot, where::Symbol, value::String)`

    - `where` can be any of: `:tl` (top-left), `:t` (top-center), `:tr` (top-right), `:bl` (bottom-left), `:b` (bottom-center), `:br` (bottom-right), `:l` (left), `:r` (right)

- `annotate!(plot::Plot, where::Symbol, row::Int, value::String)`

    - `where` can be any of: `:l` (left), `:r` (right)

    - `row` can be between 1 and the number of character rows of the canvas

![Annotate Screenshot](doc/img/annotate.png)

## Low-level Interface

The primary structures that do all the heavy lifting behind the curtain are subtypes of `Canvas`. A canvas is a graphics object for rasterized plotting. Basically it uses Unicode characters to represent pixel.

Here is a simple example:

```Julia
canvas = BrailleCanvas(40, 10, # number of columns and rows (characters)
                       origin_x = 0., origin_y = 0., # position in virtual space
                       width = 1., height = 1.)    # size of the virtual space
lines!(canvas, 0., 0., 1., 1., :blue)     # virtual space
points!(canvas, rand(50), rand(50), :red) # virtual space
lines!(canvas, 0., 1., .5, 0., :yellow)   # virtual space
pixel!(canvas, 5, 8, :red)                # pixel space
```

![Basic Canvas](doc/img/canvas.png)

You can access the height and width of the canvas (in characters) with `nrows(canvas)` and `ncols(canvas)` respectively. You can use those functions in combination with `printrow` to embed the canvas anywhere you wish. For example, `printrow(STDOUT, canvas, 3)` writes the third character row of the canvas to the standard output.

As you can see, one issue that arises when multiple pixel are represented by one character is that it is hard to assign color. That is because each of the "pixel" of a character could belong to a different color group (each character can only have a single color). This package deals with this using a color-blend for the whole group.

![Blending Colors](doc/img/braille.png)

At the moment there are the following types of Canvas implemented:

  - **BrailleCanvas**:
    This type of canvas is probably the one with the highest resolution for Unicode plotting. It essentially uses the Unicode characters of the [Braille](https://en.wikipedia.org/wiki/Braille) symbols as pixel. This effectively turns every character into 8 pixels that can individually be manipulated using binary operations.

  - **BlockCanvas**:
    This canvas is also Unicode-based. It has half the resolution of the BrailleCanvas. In contrast to BrailleCanvas, the pixels don't have visible spacing between them. This canvas effectively turns every character into 4 pixels that can individually be manipulated using binary operations.

  - **AsciiCanvas** and **DotCanvas**:
    These two canvas utilizes only standard ASCII character for drawing. Naturally, it doesn't look quite as nice as the Unicode-based ones. However, in some situations it might yield better results. Printing plots to a file is one of those situations.

  - **DensityCanvas**:
    Unlike the BrailleCanvas, the density canvas does not simply mark a "pixel" as set. Instead it increments a counter per character that keeps track of the frequency of pixels drawn in that character. Together with a variable that keeps track of the maximum frequency, the canvas can thus draw the density of datapoints.

  - **BarplotGraphics**:
    This graphics area is special in that it does not support any pixel manipulation. It is essentially the barplot without decorations but the numbers. It does only support one method `addrow!` which allows the user to add additional bars to the graphics object

## Todo

- [ ] Animated plots using cursor movement
- [ ] Add heatmaps and hinton diagrams
- [ ] Boxplots in some form

## License

This code is free to use under the terms of the MIT license.

## Acknowledgement

Inspired by [TextPlots.jl](https://github.com/sunetos/TextPlots.jl), which in turn was inspired by [Drawille](https://github.com/asciimoo/drawille)


text:
extern int bar3(void);
int bar2(void) { return bar3(); }


text:
exports.assert = function (condition /*, msg1, msg2, msg3 */) {

    if (condition) {
        return;
    }

    if (arguments.length === 2 && arguments[1] instanceof Error) {
        throw arguments[1];
    }

    var msgs = [];
    for (var i = 1, il = arguments.length; i < il; ++i) {
        if (arguments[i] !== '') {
            msgs.push(arguments[i]);            // Avoids Array.slice arguments leak, allowing for V8 optimizations
        }
    }

    msgs = msgs.map(function (msg) {

        return typeof msg === 'string' ? msg : msg instanceof Error ? msg.message : exports.stringify(msg);
    });
    throw new Error(msgs.join(' ') || 'Unknown error');
};

exports.escapeHeaderAttribute = function (attribute) {

    // Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, "

    exports.assert(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(attribute), 'Bad attribute value (' + attribute + ')');

    return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');                             // Escape quotes and slash
};

exports.stringify = function () {

    try {
        return JSON.stringify.apply(null, arguments);
    }
    catch (err) {
        return '[Cannot display object: ' + err.message + ']';
    }
};


text:
local PLUGIN = PLUGIN

PLUGIN.name = "Areas"
PLUGIN.author = "`impulse"
PLUGIN.description = "Provides customizable area definitions."

ix.area = ix.area or {}
ix.area.types = ix.area.types or {}
ix.area.properties = ix.area.properties or {}
ix.area.stored = ix.area.stored or {}

ix.config.Add("areaTickTime", 1, "How many seconds between each time a character's current area is calculated.",
	function(oldValue, newValue)
		if (SERVER) then
			timer.Remove("ixAreaThink")
			timer.Create("ixAreaThink", newValue, 0, function()
				PLUGIN:AreaThink()
			end)
		end
	end,
	{
		data = {min = 0.1, max = 4},
		category = "areas"
	}
)

function ix.area.AddProperty(name, type, default, data)
	ix.area.properties[name] = {
		type = type,
		default = default
	}
end

function ix.area.AddType(type, name)
	name = name or type

	-- only store localized strings on the client
	ix.area.types[type] = CLIENT and name or true
end

function PLUGIN:SetupAreaProperties()
	ix.area.AddType("area")

	ix.area.AddProperty("color", ix.type.color, ix.config.Get("color"))
	ix.area.AddProperty("display", ix.type.bool, true)
end

ix.util.Include("sv_plugin.lua")
ix.util.Include("cl_plugin.lua")
ix.util.Include("sv_hooks.lua")
ix.util.Include("cl_hooks.lua")

-- return world center, local min, and local max from world start/end positions
function PLUGIN:GetLocalAreaPosition(startPosition, endPosition)
	local center = LerpVector(0.5, startPosition, endPosition)
	local min = WorldToLocal(startPosition, angle_zero, center, angle_zero)
	local max = WorldToLocal(endPosition, angle_zero, center, angle_zero)

	return center, min, max
end

do
	local COMMAND = {}
	COMMAND.description = "@cmdAreaEdit"
	COMMAND.adminOnly = true

	function COMMAND:OnRun(client)
		client:SetWepRaised(false)

		net.Start("ixAreaEditStart")
		net.Send(client)
	end

	ix.command.Add("AreaEdit", COMMAND)
end

do
	local PLAYER = FindMetaTable("Player")

	-- returns the current area the player is in, or the last valid one if the player is not in an area
	function PLAYER:GetArea()
		return self.ixArea
	end

	-- returns true if the player is in any area, this does not use the last valid area like GetArea does
	function PLAYER:IsInArea()
		return self.ixInArea
	end
end


text:
typedef byte* kevent_udata;

struct sigaction;

void	runtime·sigpanic(void);

void	runtime·setitimer(int32, Itimerval*, Itimerval*);
void	runtime·sigaction(int32, struct sigaction*, struct sigaction*);
void	runtime·sigaltstack(SigaltstackT*, SigaltstackT*);
Sigset	runtime·sigprocmask(int32, Sigset);
void	runtime·unblocksignals(void);
int32	runtime·sysctl(uint32*, uint32, byte*, uintptr*, byte*, uintptr);

enum {
	SS_DISABLE = 4,
	SIG_BLOCK = 1,
	SIG_UNBLOCK = 2,
	SIG_SETMASK = 3,
	NSIG = 33,
	SI_USER = 0,
};


text:
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/lib/core/status.h"

namespace tensorflow_compression {
namespace {
using tensorflow::Status;
using tensorflow::shape_inference::DimensionHandle;
using tensorflow::shape_inference::InferenceContext;
using tensorflow::shape_inference::ShapeHandle;

REGISTER_OP("PmfToQuantizedCdf")
    .Input("pmf: float")
    .Output("cdf: int32")
    .Attr("precision: int >= 1")
    .SetShapeFn([](InferenceContext* c) {
      ShapeHandle in;
      TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 1, &in));
      DimensionHandle last;
      TF_RETURN_IF_ERROR(c->Add(c->Dim(in, -1), 1, &last));
      ShapeHandle out;
      TF_RETURN_IF_ERROR(c->ReplaceDim(in, -1, last, &out));
      c->set_output(0, out);
      return tensorflow::OkStatus();
    })
    .Doc(R"doc(
Converts a PMF into a quantized CDF for range coding.

This op uses floating-point operations internally. Therefore the quantized
output may not be consistent across multiple platforms. For entropy encoders and
decoders to have the same quantized CDF on different platforms, the quantized
CDF should be produced once and saved, then the saved quantized CDF should be
used everywhere.

After quantization, if PMF does not sum to 2^precision, then some values of PMF
are increased or decreased to adjust the sum to equal to 2^precision.

Note that the input PMF is pre-quantization. The input PMF is not normalized
by this op prior to quantization. Therefore the user is responsible for
normalizing PMF if necessary.
)doc");

}  // namespace
}  // namespace tensorflow_compression