text:
#ifndef __TEXTFILE_H
#define __TEXTFILE_H

int create_file(const char *filename, const mode_t mode);
int create_name(char *buf, size_t size, const char *path,
				const char *address, const char *name);

int textfile_put(const char *pathname, const char *key, const char *value);
int textfile_del(const char *pathname, const char *key);
char *textfile_get(const char *pathname, const char *key);

typedef void (*textfile_cb) (char *key, char *value, void *data);

int textfile_foreach(const char *pathname, textfile_cb func, void *data);

#endif /* __TEXTFILE_H */


text:
set -ex

cd `dirname $0`/../..
git_root=`pwd`
cd -

mkdir -p /tmp/ccache

# Create a local branch so the child Docker script won't complain
git branch -f jenkins-docker

# Use image name based on Dockerfile checksum
DOCKER_IMAGE_NAME=grpc_jenkins_slave${docker_suffix}_`sha1sum tools/jenkins/grpc_jenkins_slave/Dockerfile | cut -f1 -d\ `

# Make sure docker image has been built. Should be instantaneous if so.
docker build -t $DOCKER_IMAGE_NAME tools/jenkins/grpc_jenkins_slave$docker_suffix

# Make sure the CID file is gone.
rm -f docker.cid

# Run tests inside docker
docker run \
  -e "RUN_TESTS_COMMAND=$RUN_TESTS_COMMAND" \
  -e "config=$config" \
  -e "arch=$arch" \
  -e CCACHE_DIR=/tmp/ccache \
  -i $TTY_FLAG \
  -v "$git_root:/var/local/jenkins/grpc" \
  -v /tmp/ccache:/tmp/ccache \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -v $(which docker):/bin/docker \
  -w /var/local/git/grpc \
  --cidfile=docker.cid \
  $DOCKER_IMAGE_NAME \
  bash -l /var/local/jenkins/grpc/tools/jenkins/docker_run_tests.sh || DOCKER_FAILED="true"

DOCKER_CID=`cat docker.cid`

if [ "$XML_REPORT" != "" ]
then
  docker cp "$DOCKER_CID:/var/local/git/grpc/$XML_REPORT" $git_root
fi

# remove the container, possibly killing it first
docker rm -f $DOCKER_CID || true

if [ "$DOCKER_FAILED" != "" ] && [ "$XML_REPORT" == "" ]
then
  exit 1
fi

redpajama_set_name: RedPajamaGithub


text:
"""The Netatmo integration."""
import logging

from homeassistant.core import callback

from .const import (
    ATTR_EVENT_TYPE,
    ATTR_FACE_URL,
    ATTR_ID,
    ATTR_IS_KNOWN,
    ATTR_NAME,
    ATTR_PERSONS,
    DATA_PERSONS,
    DEFAULT_PERSON,
    DOMAIN,
    NETATMO_EVENT,
)

_LOGGER = logging.getLogger(__name__)

async def handle_webhook(hass, webhook_id, request):
    """Handle webhook callback."""
    try:
        data = await request.json()
    except ValueError:
        return None

    _LOGGER.debug("Got webhook data: %s", data)

    event_type = data.get(ATTR_EVENT_TYPE)

    if event_type == "outdoor":
        hass.bus.async_fire(
            event_type=NETATMO_EVENT, event_data={"type": event_type, "data": data}
        )
        for event_data in data.get("event_list"):
            async_evaluate_event(hass, event_data)
    else:
        async_evaluate_event(hass, data)

@callback
def async_evaluate_event(hass, event_data):
    """Evaluate events from webhook."""
    event_type = event_data.get(ATTR_EVENT_TYPE)

    if event_type == "person":
        for person in event_data.get(ATTR_PERSONS):
            person_event_data = dict(event_data)
            person_event_data[ATTR_ID] = person.get(ATTR_ID)
            person_event_data[ATTR_NAME] = hass.data[DOMAIN][DATA_PERSONS].get(
                person_event_data[ATTR_ID], DEFAULT_PERSON
            )
            person_event_data[ATTR_IS_KNOWN] = person.get(ATTR_IS_KNOWN)
            person_event_data[ATTR_FACE_URL] = person.get(ATTR_FACE_URL)
            hass.bus.async_fire(
                event_type=NETATMO_EVENT,
                event_data={"type": event_type, "data": person_event_data},
            )
    else:
        hass.bus.async_fire(
            event_type=NETATMO_EVENT,
            event_data={"type": event_type, "data": event_data},
        )


text:
import { Injectable } from '@angular/core';
import { BaThemeConfigProvider } from '../../../../../../theme';
import { ChartsAPI } from './../../../../chartsAPI.services';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ChartRankingPurchaseCategoryService {
  private dbdata: Observable<JSON[]>
  private products: JSON[] = [];
  private errorMessage: any;
  private _dataCategory = {
    stackedBarData: {
      labels: [],
      series: [],
    },
    stackedBarOptions: {
      fullWidth: true,
      height: '300px',
      stackBars: true,
      axisY: {
        labelInterpolationFnc: function(value) {
          return (value / 1000 + 'k');
        }
      }
    },

  };
  private dataSeller: JSON[] = [];

  constructor(
    private _baConfig: BaThemeConfigProvider,
    private _chartAPI: ChartsAPI) {
  }

  getAll() {
    return this._dataCategory;
  }

  getPurchaseCategory(filter: JSON): any {

    //Retorna el observable de la data
    return this._chartAPI.getRankPurchaseC(filter);
  }
  removeData() {
    this._dataCategory.stackedBarData.labels.splice(0);
    this._dataCategory.stackedBarData.series.splice(0);

  }
  setData(dbdata: Array<JSON[]>) {
    this.removeData();
    let list: string[] = [];
    dbdata.forEach(variable => {
      list.push(JSON.stringify(variable))
    });
    console.log(list);
    let data_chart: string[] = [];
    for (let i = 0; i < list.length; i++) {
      let data_db = JSON.parse(list[i]);
      const name = data_db.Name;
      const total = data_db.Total;
      console.log(total);
      this._dataCategory.stackedBarData.labels.push(name);
      let data_series: any[] = [];
      for (let j = 0; j < list.length; j++) {
        if (j == i) {
          data_series[j] = total;
        } else {
          data_series[j] = 0;
        }
      }
      console.log(data_series);
      this._dataCategory.stackedBarData.series.push(data_series);
    }
    return this._dataCategory;
  }
  printDATA(data: any) {
    console.log(data);
  }
  getData() {
    return this.dataSeller;
  }

  getResponsive(padding, offset) {
    return [
      ['screen and (min-width: 1550px)', {
        chartPadding: padding,
        labelOffset: offset,
        labelDirection: 'explode',
        labelInterpolationFnc: function(value) {
          return value;
        }
      }],
      ['screen and (max-width: 1200px)', {
        chartPadding: padding,
        labelOffset: offset,
        labelDirection: 'explode',
        labelInterpolationFnc: function(value) {
          return value;
        }
      }],
      ['screen and (max-width: 600px)', {
        chartPadding: 0,
        labelOffset: 0,
        labelInterpolationFnc: function(value) {
          return value[0];
        }
      }]
    ];
  }
}


text:
<!DOCTYPE html>

  <meta charset='utf-8'>
  <title>alexyoung/ico @ GitHub</title>
  <link href="prettify.css" type="text/css" rel="stylesheet" />

ico
      by alexyoung

Ico

Ico (GitHub: alexyoung / ico, License: MIT) is a JavaScript graph library.

The Ico Example Page has a lot of examples that demonstrate Ico's usage.

Usage

Graphs are created by instantiated classes.  The available classes are:

Ico.SparkLine: Creates a small line graph intended for use within text

Ico.SparkBar: Creates a small bar graph intended for use within text

Ico.BarGraph: Creates a bar graph

Ico.HorizontalBarGraph: Creates a horizontal bar graph

Ico.LineGraph: Creates a line graph

Each of these classes can be instantiated with the same arguments.  The following examples use jQuery, but jQuery is not required to use Ico.

// Basic signature
new Ico.SparkLine(element, data, options);

// Real examples
new Ico.SparkLine($('#sparkline'),
  [21, 41, 32, 1, 10, 5, 32, 10, 23],
  { width: 30, height: 14, background_colour: '#ccc' }
);

new Ico.BarGraph($('#bargraph'), { one: [44, 12, 17, 30, 11] }, { bar_labels: true });

The third argument, options, may vary between graphs.

Live Example

new Ico.LineGraph($('#linegraph'), {
    one: [30, 5, 1, 10, 15, 18, 20, 25, 1],
    two: [10, 9, 3, 30, 1, 10, 5, 33, 33],
    three: [5, 4, 10, 1, 30, 11, 33, 12, 22]
  }, {
    markers: 'circle',
    colours: { one: '#990000', two: '#009900', three: '#000099'},
    labels: ['one', 'two', 'three', 'four',
             'five', 'six', 'seven', 'eight', 'nine'],
    meanline: true,
    grid: true
  }
);

Options for Ico.SparkLine

width: Width of the graph, defaults to the element's width

height: Height of the graph, defaults to the element's height

highlight: Highlight options highlight: { colour: '#ff0000' } -- used to pick out the last value

background_colour: The graph's background colour, defaults to the element's background colour if set

colour: The colour for drawing lines

acceptable_range: An array of two values, [min, max], for setting the size of the background rectangle

Options for Ico.SparkBar

Ico.SparkBar options are the same as Ico.SparkLine.

Shared Options for Ico.BarGraph, Ico.HorizontalBarGraph, and Ico.LineGraph

width: The width of the container element, defaults to the element's width

height: The height of the container element, defaults to the element's height

background_colour: The graph's background colour, defaults to the element's background colour if set

labels: An array of text labels (for each bar or line)

show_horizontal_labels: Set to false to hide horizontal labels

show_vertical_labels: Set to false to hide vertical labels

label_count: The number of numerical labels to display

label_step: The value to increment each numerical label

start_value: The value to start plotting from (generally 0).  This can be used to force 0 in cases where the normaliser starts from another value

font_size: The size of the fonts used in the graph

meanline: Display a line through the mean value

grid: Display a grid to make reading values easier

grid_colour: Change the colour of the grid

Options for Ico.BarGraph

colour: The colour for the bars

colours: An array of colours for each bar

highlight_colours: An object with the index of a bar (starting from 0) and a colour, like this { 3: '#ff0000' }

bar_size: Set the size for a bar in a bar graph

max_bar_size: Set the maximum size for a bar in a bar graph

bar_labels: Display the actual value of each bar in a bar graph

line: Provide an array to plot a line alongside a bar graph

Options for Ico.LineGraph

stroke_width: Sets the stroke width, defaults to 3px.  Set to 0 to get a scatter plot

Grouped Bar Graphs

Multidimensional arrays will be rendered as 'grouped' bar graphs.  Notice that two colours are specified, one for each bar in the group.  This is still a work in progress and hasn't been tested thoroughly yet.

In grouped bar graphs, the index for highlight_colours is the index from left to right, starting from zero.

new Ico.BarGraph(
  $('grouped_bars'),
  [[10, 15], [18, 19], [17, 23], [11, 22]],
  { grid: true, font_size: 10,
    colours: ['#ff0099', '#339933'],
    labels: ['Winter', 'Spring', 'Summer', 'Autumn']
  }
);

Options for Ico.HorizontalBarGraph

bar_size: Set the size for a bar in a bar graph

max_bar_size: Set the maximum size for a bar in a bar graph

Options for Ico.LineGraph

markers: Set to 'circle' to display markers at each point on a line graph

marker_size: The size of each marker

Data Normalisation

Data is mapped to plottable values by Ico.Normaliser.  In addition, this class attempts to calculate a sensible value to start plotting from on the X axis, and also calculates the width for each item (the "step").

These values can be overridden by setting start_value and label_step.  This can help display data that is difficult to plot, but you can raise issues through GitHub to report such data.


text:
set -x

SPARK_CONFIG_DIR=$1

log4j_properties_file="${SPARK_CONFIG_DIR}/log4j.properties"

cat <<'EOF' > "${log4j_properties_file}"

# default log file, overridden by Java System property -Dlog4j.logFile=...
log4j.logFile=/var/log/jnbg/spark-driver-${user.name}.log

# default (root) log level, overridable by Java System property -Dlog4j.logLevel=...
log4j.logLevel=INFO

# default log file size limit, overridable by Java System property -Dlog4j.fileSize=... (KB, MB, GB)
log4j.fileSize=10MB

# default max number of log file backups, overridable by Java System property -Dlog4j.backupFiles=...
log4j.backupFiles=10

# log to file using rolling log strategy with one backup file
# NOTE: Spark REPL overrides rootCategory, set log4j.logLevel above
log4j.rootCategory=${log4j.logLevel}, logfile
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${log4j.logFile}
log4j.appender.logfile.MaxFileSize=${log4j.fileSize}
log4j.appender.logfile.MaxBackupIndex=${log4j.backupFiles}
log4j.appender.logfile.encoding=UTF-8
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n

# Reduce Toree related "noise"
log4j.logger.org.apache.toree.kernel.protocol.v5.stream.KernelOutputStream=ERROR

# Modified Spark 2.1 default settings:

# Spark overrides rootCategory level with the level set for the Scala & PySpark REPLs (default=WARN)
# This is intended to reduce log verbosity while working with a Spark shell or PySpark shell.
# However, notebook kernels internally use the spark-shell and pyspark shell implementation, but
# since notebooks are logging to a log file, we want potentially more verbose logs.
# We need to set the spark-shell and pyspark shell log level to the same level as the rootCategory.
# See: org.apache.spark.internal.Logging#initializeLogging(isInterpreter=true)
log4j.logger.org.apache.spark.repl.Main=${log4j.rootCategory}
log4j.logger.org.apache.spark.api.python.PythonGatewayServer=${log4j.rootCategory}

# Settings to quiet third party logs that are too verbose
log4j.logger.org.spark_project.jetty=WARN
log4j.logger.org.spark_project.jetty.util.component.AbstractLifeCycle=ERROR
log4j.logger.org.apache.spark.repl.SparkIMain$exprTyper=INFO
log4j.logger.org.apache.spark.repl.SparkILoop$SparkILoopInterpreter=INFO
log4j.logger.org.apache.parquet=ERROR
log4j.logger.parquet=ERROR

# SPARK-9183: Settings to avoid annoying messages when looking up nonexistent UDFs in SparkSQL with Hive support
log4j.logger.org.apache.hadoop.hive.metastore.RetryingHMSHandler=FATAL
log4j.logger.org.apache.hadoop.hive.ql.exec.FunctionRegistry=ERROR

EOF


text:
(function(window) {
    "use strict";

    var Backprop = {};

    // Transform a given input value, using a property spec object.
    // propSpec: an object that defines a Backprop property. Supported keys
    //           (see the README for explanations) include:
    //           'coerce', 'choices', 'trim', 'max', 'min'
    // inputVal: the value that the caller has assigned to the property
    // fallbackValue (optional): a default value to use if the input is invalid
    function transformValue(propSpec, inputVal, fallbackValue) {
        var value = inputVal;
        if (typeof propSpec.coerce === 'function') value = propSpec.coerce(value);

        // If an array of choices was passed in, validate that the input is one of
        // the valid choices:
        var choices = propSpec.choices;
        if (choices && choices.constructor && choices.constructor.name === 'Array') {
            if (choices.indexOf(value) === -1) {
                if (fallbackValue !== undefined) value = fallbackValue;
                else return undefined;
            }
        }

        if (propSpec.trim && (typeof value.trim === 'function')) value = value.trim();
        if (propSpec.max && (value > propSpec.max)) value = propSpec.max;
        if (propSpec.min && (value < propSpec.min)) value = propSpec.min;
        return value;
    }

    // Small class whose instances are used as placeholders for the ES5 properties
    // that appear on models.
    function PropPlaceholder(spec) {
        this.spec = spec;
    }

    // Create the actual property on the "class" prototype
    PropPlaceholder.prototype.createProperty = function(objProto, name) {
        // Allow defaults to be specified right in the property (rather than
        // seperately in Backbone's usual defaults hash). This will override
        // whatever's in objProto.defaults for this property.
        var propSpec = this.spec || {};

        // Don't allow property names to shadow ones that are already defined
        // (eg. by Backbone.Model.prototype):
        if (name in objProto.constructor.__super__) {
            throw new Error('The name ' + name + ' is already used by this model');
        }

        if (typeof propSpec.default !== 'undefined') {
            objProto.defaults = objProto.defaults || {};
            objProto.defaults[name] = propSpec.default;
        }
        Object.defineProperty(objProto, name, {
            get: function() { return this.get(name); },
            set: function(value) {
                //propSpec.default = objProto.defaults[name];   // breaks things ...?
                var fallbackValue = this.get(name); // || objProto.defaults[name];
                value = transformValue(propSpec, value, fallbackValue);
                this.set(name, value);
            },
            configurable: true,
            enumerable: true
        });
    };

    // Backprop configuration method. Pass in the base model class that you want
    // to extend. Before your model definitions, you will want to invoke it as
    // follows:
    //
    // Backprop.extendModel(Backbone.Model);
    Backprop.extendModel = function(BaseModel) {

        // Add a setProperties() method on Backprop.Model's prototype.
        // This sets a hash of values to the model, just like Backbone.Model.set().
        // The difference is that this will apply transforms for all of the
        // properties before setting.
        Backprop.Model = BaseModel.extend({
            setProperties: function(attrs, options) {
                var schema = this.constructor._schema || {};
                for (var name in attrs) {
                    var propSpec = schema[name] || {};
                    attrs[name] = transformValue(propSpec, attrs[name], this.get(name));
                }
                this.set(attrs, options);
            }
        });

        // Use a modified version of Backbone.Model's extend(), so
        // it can parse Backprop properties in model definitions
        Backprop.Model.extend = function(protoAttrs, staticAttrs) {
            protoAttrs = protoAttrs || {};

            // Apply Backbone.Model's original extend() function:
            var objConstructor = BaseModel.extend.apply(this, [].slice.call(arguments));

            // Go through the prototype attributes and create ES5 properties for every
            // attribute that used Backbone.property():
            objConstructor._schema = {};
            for (var name in protoAttrs) {
                var val = protoAttrs[name];
                if (val instanceof PropPlaceholder) {
                    val.createProperty(objConstructor.prototype, name);
                    objConstructor._schema[name] = val.spec;
                }
            }
            return objConstructor;
        };

        return Backprop.Model;
    };

    // Allow use of shorthand properties like "myprop: Backprop.Boolean()". This avoids
    // having to pass in an explicit coerce function when you are just casting to a JS type.
    // If you do pass in a coerce function, it will still work, but the type cast will
    // be applied first.
    var makeShorthandProp = function(typeCoerce) {
        return function(specObj) {
            specObj = specObj || {};
            var innerCoerce = specObj.coerce;

            if (typeof innerCoerce === 'function') {
                specObj.coerce = function(x) { return innerCoerce(typeCoerce(x)); };
            } else {
                specObj.coerce = typeCoerce;
            }
            return new PropPlaceholder(specObj);
        };
    };

    // The built-in shorthand properties (aka fields) follow:
    Backprop.fields = {
        Generic: makeShorthandProp(function(x) { return x; }),
        Boolean: makeShorthandProp(Boolean),
        String: makeShorthandProp(String),
        Number: makeShorthandProp(Number),
        Integer: makeShorthandProp(function(x) { return parseInt(x, 10); }),
        Date: makeShorthandProp(function(x) { return new Date(x); }),
    };

    // Alias all fields directly on Backprop's top level object for convenience:
    for (var k in Backprop.fields) Backprop[k] = Backprop.fields[k];

    // Export for Node/Browserify, or fallback to a window assignment:
    if (typeof module !== 'undefined' && module.exports) module.exports = Backprop;
    else window.Backprop = Backprop;
}(this));


text:
package prometheus

import (
	"net/http"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

var exptime = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)

const validUniqueGauge = `# HELP cadvisor_version_info A metric with a constant '1' value labeled by kernel version, OS version, docker version, cadvisor version & cadvisor revision.
# TYPE cadvisor_version_info gauge
cadvisor_version_info{cadvisorRevision="",cadvisorVersion="",dockerVersion="1.8.2",kernelVersion="3.10.0-229.20.1.el7.x86_64",osVersion="CentOS Linux 7 (Core)"} 1
`

const validUniqueCounter = `# HELP get_token_fail_count Counter of failed Token() requests to the alternate token source
# TYPE get_token_fail_count counter
get_token_fail_count 0
`

const validUniqueLine = `# HELP get_token_fail_count Counter of failed Token() requests to the alternate token source
`

const validUniqueSummary = `# HELP http_request_duration_microseconds The HTTP request latencies in microseconds.
# TYPE http_request_duration_microseconds summary
http_request_duration_microseconds{handler="prometheus",quantile="0.5"} 552048.506
http_request_duration_microseconds{handler="prometheus",quantile="0.9"} 5.876804288e+06
http_request_duration_microseconds{handler="prometheus",quantile="0.99"} 5.876804288e+06
http_request_duration_microseconds_sum{handler="prometheus"} 1.8909097205e+07
http_request_duration_microseconds_count{handler="prometheus"} 9
`

const validUniqueHistogram = `# HELP apiserver_request_latencies Response latency distribution in microseconds for each verb, resource and client.
# TYPE apiserver_request_latencies histogram
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="125000"} 1994
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="250000"} 1997
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="500000"} 2000
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="1e+06"} 2005
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="2e+06"} 2012
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="4e+06"} 2017
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="8e+06"} 2024
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="+Inf"} 2025
apiserver_request_latencies_sum{resource="bindings",verb="POST"} 1.02726334e+08
apiserver_request_latencies_count{resource="bindings",verb="POST"} 2025
`

const validData = `# HELP cadvisor_version_info A metric with a constant '1' value labeled by kernel version, OS version, docker version, cadvisor version & cadvisor revision.
# TYPE cadvisor_version_info gauge
cadvisor_version_info{cadvisorRevision="",cadvisorVersion="",dockerVersion="1.8.2",kernelVersion="3.10.0-229.20.1.el7.x86_64",osVersion="CentOS Linux 7 (Core)"} 1
# HELP go_gc_duration_seconds A summary of the GC invocation durations.
# TYPE go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 0.013534896000000001
go_gc_duration_seconds{quantile="0.25"} 0.02469263
go_gc_duration_seconds{quantile="0.5"} 0.033727822000000005
go_gc_duration_seconds{quantile="0.75"} 0.03840335
go_gc_duration_seconds{quantile="1"} 0.049956604
go_gc_duration_seconds_sum 1970.341293002
go_gc_duration_seconds_count 65952
# HELP http_request_duration_microseconds The HTTP request latencies in microseconds.
# TYPE http_request_duration_microseconds summary
http_request_duration_microseconds{handler="prometheus",quantile="0.5"} 552048.506
http_request_duration_microseconds{handler="prometheus",quantile="0.9"} 5.876804288e+06
http_request_duration_microseconds{handler="prometheus",quantile="0.99"} 5.876804288e+06
http_request_duration_microseconds_sum{handler="prometheus"} 1.8909097205e+07
http_request_duration_microseconds_count{handler="prometheus"} 9
# HELP get_token_fail_count Counter of failed Token() requests to the alternate token source
# TYPE get_token_fail_count counter
get_token_fail_count 0
# HELP apiserver_request_latencies Response latency distribution in microseconds for each verb, resource and client.
# TYPE apiserver_request_latencies histogram
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="125000"} 1994
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="250000"} 1997
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="500000"} 2000
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="1e+06"} 2005
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="2e+06"} 2012
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="4e+06"} 2017
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="8e+06"} 2024
apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="+Inf"} 2025
apiserver_request_latencies_sum{resource="bindings",verb="POST"} 1.02726334e+08
apiserver_request_latencies_count{resource="bindings",verb="POST"} 2025
`

const prometheusMulti = `
cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1
cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1
cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1
cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1
cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1
cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1
cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1
`

const prometheusMultiSomeInvalid = `
cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1
cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1
cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1
cpu,cpu=cpu3, host=foo,datacenter=us-east usage_idle=99,usage_busy=1
cpu,cpu=cpu4 , usage_idle=99,usage_busy=1
cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1
`

func TestParseValidPrometheus(t *testing.T) {
	// Gauge value
	metrics, err := Parse([]byte(validUniqueGauge), http.Header{})
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "cadvisor_version_info", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"gauge": float64(1),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{
		"osVersion":     "CentOS Linux 7 (Core)",
		"dockerVersion": "1.8.2",
		"kernelVersion": "3.10.0-229.20.1.el7.x86_64",
	}, metrics[0].Tags())

	// Counter value
	metrics, err = Parse([]byte(validUniqueCounter), http.Header{})
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "get_token_fail_count", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"counter": float64(0),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{}, metrics[0].Tags())

	// Summary data
	//SetDefaultTags(map[string]string{})
	metrics, err = Parse([]byte(validUniqueSummary), http.Header{})
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "http_request_duration_microseconds", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"0.5":   552048.506,
		"0.9":   5.876804288e+06,
		"0.99":  5.876804288e+06,
		"count": 9.0,
		"sum":   1.8909097205e+07,
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{"handler": "prometheus"}, metrics[0].Tags())

	// histogram data
	metrics, err = Parse([]byte(validUniqueHistogram), http.Header{})
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "apiserver_request_latencies", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"500000": 2000.0,
		"count":  2025.0,
		"sum":    1.02726334e+08,
		"250000": 1997.0,
		"2e+06":  2012.0,
		"4e+06":  2017.0,
		"8e+06":  2024.0,
		"+Inf":   2025.0,
		"125000": 1994.0,
		"1e+06":  2005.0,
	}, metrics[0].Fields())
	assert.Equal(t,
		map[string]string{"verb": "POST", "resource": "bindings"},
		metrics[0].Tags())

}


text:
<TITLE>Review for Beach, The (2000)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Beach, The (2000)

reviewed by
Scott Renshaw

THE BEACH
(20th Century Fox)
Starring:  Leonardo DiCaprio, Tilda Swinton, Virginie Ledoyen, Guillaume
Canet, Robert Carlyle, Paterson Joseph.
Screenplay:  John Hodge, based on the novel by Alex Garland.
Producer:  Andrew MacDonald.
Director:  Danny Boyle.
MPAA Rating:  R (sexual situations, violence, nudity, graphic gore,
profanity, drug use)
Running Time:  116 minutes.
Reviewed by Scott Renshaw.

     When we are introduced to Richard (Leonardo DiCaprio), the young
American protagonist of THE BEACH, he says, "My name is Richard. What else
do you need to know about me?" He tries to convince us that he's a blank
slate, a walking receptor for experiences using his backpacking trip
through Thailand as a way to shake up his life. It's an intriguing start,
except for one small problem: There's a lot more we need to know about
Richard. In fact, there's a lot more we need to know about virtually
everyone and everything in THE BEACH. Director Danny Boyle's
travelogue-cum-human nature treatise proves to be a tremendously
frustrating experience -- it's a lazy film that thinks it's being
profound.

     The titular beach is a hidden cove on a remote island off the Thai
coast, a place that has become a sort of myth among tourists in Thailand.
Richard learns the truth when Daffy (Robert Carlyle), a crazed former
resident of the island, hands over a map to its location. Accompanied by a
young French couple named Francoise (Virginie Ledoyen) and Etienne
(Guillaume Canet), Richard makes the difficult journey to the island,
where they find a community of self-imposed outcasts from civilization. It
all seems to be a paradise on earth, except for the presence of a
pseudo-benevolent pseudo-dictator named Sal (Tilda Swinton) whose paranoia
over keeping the island secret is rivaled only by her libido, and the
unsettling willingness of the residents to leave their dying in the middle
of the jungle. Soon Richard begins suspecting that the threats to the
community from without -- edgy marijuana farmers, more Americans -- may be
less troubling than the threats from within.

     During its first hour, THE BEACH does an effective job of setting
tone, largely through the efforts of superb technical craftsmen. Darius
Khondji works his now-typical magic with darkness, adding a shadow of
creepiness to Richard's cynical vision of tourism in "exotic" lands. The
island locations are spectacular, and Donald McAlpine's production design
of the islanders' camp is a tidy marvel. THE BEACH wants to set up an
initial dichotomy -- the pasteurized pleasures of most tourist
destinations compared to the raw glory of the island -- that eventually
proves to be false. On a visual level, it's hard not to argue that Boyle
and company succeed.

     Unfortunately for Boyle and company -- and for you, John or Jane
Q. Potential Audience Member -- the characters eventually have to play a
role in the film. When they do, it becomes quite clear that nobody
understands why anybody is doing anything. Richard's vague motivations and
frustrations over sanitized tourist experiences seem provocative as the
film begins, but soon the script begins dropping in details about his past
-- e.g. he's a video game junkie -- without bothering to explain why that
matters except as an excuse for Boyle to include an admittedly creative
fantasy sequence. That complete apathy over exploring motivation spills
over into every other character, as screenwriter John Hodge never bothers
with the tiny matter of what the islanders want their paradise to
represent, or why Sal above all others treats the place as a holy secret.
The characters -- including DiCaprio, whose performance is about as good
as you can expect in a role so under-written -- generally appear to be
occupying space and serving plot functions, to the ridiculous extreme that
the head marijuana farmer gives a knowing nod after his solution to the
film's climactic problem proves him a worthy successor to Solomon in the
despotic wisdom department.

     Of course, letting the complexities of the characters come to the
surface would have required some actual effort, as opposed to offering up
the premise as it stands. THE BEACH comes to the staggering conclusion
that a perfect society is not possible when imperfect human beings are
involved (particularly when some of those imperfect human beings happen to
be surly neighboring marijuana farmers). It's ridiculously obvious
thematic material, yet the makers of THE BEACH seem convinced that
presenting that theme is enough to earn them philosophical style points.
Ultimately, style points are all they earn, though they earn those style
points in impressive quantities. There are several instances when THE
BEACH has the power to grab you viscerally -- the squeamish might want to
turn away after the consequences of a shark attack -- but the concept
clearly wants to grab you intellectually as well. And THE BEACH just can't
do that, not when its creators decide the characters' names are all you
need to know about them.

     On the Renshaw scale of 0 to 10 sons of beaches:  5.

                   Visit Scott Renshaw's Screening Room
                    http://www.inconnect.com/~renshaw/
                                   ***
             Subscribe to receive new reviews directly by email!
 See the Screening Room for details, or reply to this message with subject
                               "Subscribe".

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package rest.github.frankhassanabad.com;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

import javax.xml.ws.Response;
import java.util.Random;

/**
 * Simple client to post a string and a random number
 * to the service.  This uses the service of
 * <pre>
 * http://localhost:8080/rest/resource/strings/post/single
 * </pre>
 * See ths class of StringPostGetResource from the
 * RestfulExample war file
 */
public class PostStrings {

    /**
     * Main method for the client
     * @param args None are used
     */
    public static void main(String[] args) {
        Client client = Client.create();
        WebResource resource = client.resource("http://localhost:8080/rest/resource/strings/post/single");
        //Post the string typical without a care in the world about the return code.
        resource.post("A single String with random number of:" + new Random().nextInt());

        //Now post the string and return the status code which should be 201 for success
        ClientResponse response = resource.post(ClientResponse.class, "A single String with random number of:" + new Random().nextInt());
        int status = response.getStatus();
        System.out.println("Return status code is:" + status);
    }
}


text:
package com.google.edwmigration.dumper.plugin.lib.dumper.spi;

/**
 *
 * @author matt
 */
public interface SnowflakeLogsDumpFormat {

    String FORMAT_NAME = "snowflake.logs.zip";

    String ZIP_ENTRY_PREFIX = "query_history_";

    enum Header {
        DatabaseName,
        SchemaName,
        UserName,
        WarehouseName,
        ExecutionStatus,
        ErrorCode,
        StartTime,
        EndTime,
        TotalElapsedTime,
        BytesScanned,
        RowsProduced,
        CreditsUsedCloudServices,
        QueryText
    }
}


text: export { default } from './PaneFooter';


text:
package edu.gatech.sjpcap;

public class TCPPacket extends IPPacket{

    public TCPPacket(IPPacket packet){
	super(packet.timestamp);

	this.src_ip = packet.src_ip;
	this.dst_ip = packet.dst_ip;
    }

    public int src_port;
    public int dst_port;

    public byte[] data;
}


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

package com.uber.m3.tally;

import java.util.Map;

/**
 * A snapshot of values since last report execution.
 */
public interface Snapshot {
    /**
     * Returns a {@link CounterSnapshot} of all {@link Counter} summations since last report execution.
     * @return a {@link CounterSnapshot} of all {@link Counter} summations since last report execution
     */
    Map<String, CounterSnapshot> counters();

    /**
     * Returns a {@link GaugeSnapshot} of {@link Gauge} last values since last report execution.
     * @return a {@link GaugeSnapshot} of {@link Gauge} last values since last report execution
     */
    Map<String, GaugeSnapshot> gauges();

    /**
     * Returns a {@link TimerSnapshot} of {@link Timer} values since last report execution.
     * @return a {@link TimerSnapshot} of {@link Timer} values since last report execution
     */
    Map<String, TimerSnapshot> timers();

    /**
     * Returns a {@link HistogramSnapshot} of {@link Histogram} samples since last report execution.
     * @return a {@link HistogramSnapshot} of {@link Histogram} samples since last report execution
     */
    Map<String, HistogramSnapshot> histograms();
}


text:
import subprocess

from distutils.core import setup

def get_version():
    version_cmd = 'bin/dodo-version.sh'
    proc = subprocess.Popen(args=version_cmd.split(), stdout=subprocess.PIPE)
    (out, err) = proc.communicate()

    with file('lib/dodo/.version', 'w') as fobj:
        fobj.write(out)

    return out

setup(
    name = 'dodo',
    version = get_version(),
    description = 'Very simple task management tool for a terminal access',

    author = 'Eino Malinen',
    author_email = 'volinthius@sci.fi',

    packages = [ 'dodo' ],
    package_dir = { '': 'lib' },
    package_data = { '': [ '.version' ] },
    scripts = [ 'bin/dodo' ]
    )


text:
package monocle.function

import monocle.MonocleSuite
import monocle.law.discipline.function.Cons1Tests

import scalaz.IList

class Cons1Spec extends MonocleSuite {

  implicit val clistCons1: Cons1[CNel, Char, IList[Char]] = Cons1.fromIso(CNel.toNel)

  checkAll("fromIso", Cons1Tests[CNel, Char, IList[Char]])

}


text:
#ifndef XSBAUD_H
#define XSBAUD_H

#include "xstypesconfig.h"

/*!	\addtogroup enums Global enumerations
	@{
*/

#include "xsbaudcode.h"
#include "xsbaudrate.h"

/*! @} */

typedef enum XsBaudCode XsBaudCode;
typedef enum XsBaudRate XsBaudRate;

#ifdef __cplusplus
extern "C" {
#endif

XSTYPES_DLL_API XsBaudRate XsBaud_codeToRate(XsBaudCode baudcode);
XSTYPES_DLL_API XsBaudCode XsBaud_rateToCode(XsBaudRate baudrate);
XSTYPES_DLL_API int XsBaud_rateToNumeric(XsBaudRate baudrate);
XSTYPES_DLL_API XsBaudRate XsBaud_numericToRate(int numeric);

#ifdef __cplusplus
} // extern "C"

/*! \namespace XsBaud
	\brief Namespace for Baud rate and Baud code constants and conversions
*/
namespace XsBaud {
	/*! \copydoc XsBaud_codeToRate */
	inline XsBaudRate codeToRate(XsBaudCode baudcode)
	{
		return XsBaud_codeToRate(baudcode);
	}
	/*! \copydoc XsBaud_rateToCode */
	inline XsBaudCode rateToCode(XsBaudRate baudrate)
	{
		return XsBaud_rateToCode(baudrate);
	}
	/*! \copydoc XsBaud_rateToNumeric */
	inline int rateToNumeric(XsBaudRate baudrate)
	{
		return XsBaud_rateToNumeric(baudrate);
	}
	/*! \copydoc XsBaud_numericToRate*/
	inline XsBaudRate numericToRate(int numeric)
	{
		return XsBaud_numericToRate(numeric);
	}
}

#endif

#endif // file guard


text:
describe TreeBuilderOpsRbac do
  before do
    MiqRegion.seed
    EvmSpecHelper.local_miq_server
  end

  describe ".new" do
    def assert_tree_nodes(expected)
      tree_json  = TreeBuilderOpsRbac.new("rbac_tree", "rbac", {}).tree_nodes
      tree_nodes = JSON.parse(tree_json).first['children'].collect { |h| h['title'] }
      expect(tree_nodes).to match_array expected
    end

    it "with user with rbac_group role" do
      login_as FactoryGirl.create(:user, :features => 'rbac_group_view')
      assert_tree_nodes(["Groups"])
    end

    it "with user with rbac_role_view role" do
      login_as FactoryGirl.create(:user, :features => 'rbac_role_view')
      assert_tree_nodes(["Roles"])
    end

    it "with user with rbac_tenant role" do
      login_as FactoryGirl.create(:user, :features => 'rbac_tenant_view')
      assert_tree_nodes(["Tenants"])
    end

    it "with user with rbac_user role" do
      login_as FactoryGirl.create(:user, :features => 'rbac_user_view')
      assert_tree_nodes(["Users"])
    end

    it "with user with multiple rbac roles" do
      login_as FactoryGirl.create(:user,
        :features => %w(rbac_group_view rbac_user_view rbac_role_view rbac_tenant_view)
      )
      assert_tree_nodes(%w(Groups Users Roles Tenants))
    end
  end

  describe "#x_get_tree_custom_kids" do
    let(:group) { FactoryGirl.create(:miq_group) }
    let(:user) { FactoryGirl.create(:user, :miq_groups => [group]) }
    let(:other_group) { FactoryGirl.create(:miq_group) }
    let(:other_user) { FactoryGirl.create(:user, :miq_groups => [other_group]) }

    before :each do
      login_as user
    end

    def x_get_tree_custom_kids_for_and_expect_objects(type_of_model, expected_objects)
      tree_builder = TreeBuilderOpsRbac.new("rbac_tree", "rbac", {})
      objects = tree_builder.send(:x_get_tree_custom_kids, {:id => type_of_model}, false, {})
      expect(objects).to match_array(expected_objects)
    end

    it "is listing all users" do
      x_get_tree_custom_kids_for_and_expect_objects("u", [user, other_user])
    end

    it "is listing all groups" do
      x_get_tree_custom_kids_for_and_expect_objects("g", [user.current_group, other_group])
    end

    context "User with self service user" do
      before :each do
        allow_any_instance_of(User).to receive_messages(:self_service? => true)
      end

      it "is listing only current user" do
        x_get_tree_custom_kids_for_and_expect_objects("u", [user])
      end

      it "is listing only user's group" do
        x_get_tree_custom_kids_for_and_expect_objects("g", [user.current_group])
      end
    end
  end
end


text:
@implementation UIView (AutoLayout)

- (void)addConstraintsFittingSubviewToSelf:(UIView *)subview
{
	NSArray *constraints = [NSLayoutConstraint constraintsFittingSubviewToSuperview:subview];

	if (constraints)
	{
		[subview setTranslatesAutoresizingMaskIntoConstraints:NO];
		[self addConstraints:constraints];
	}
	else
	{
		NSAssert(0, @"Can't obtain constraints to fit subview (%@) to self", subview);
	}
}

- (void)addConstraintsCenteringSubviewInSelf:(UIView *)subview
{
	NSArray *constraints = [NSLayoutConstraint constraintsCenteringSubview:subview inSuperview:self];

	if (constraints)
	{
		[subview setTranslatesAutoresizingMaskIntoConstraints:NO];
		[self addConstraints:constraints];
	}
	else
	{
		NSAssert(0, @"Can't obtain constraints to center subview (%@) in self", subview);
	}
}

- (void)addConstraintsSizingSubview:(UIView *)subview toWidth:(CGFloat)width height:(CGFloat)height
{
	NSArray *constraints = [NSLayoutConstraint constraintsOfWidth:width height:height forSubview:subview];

	if (constraints)
	{
		[subview setTranslatesAutoresizingMaskIntoConstraints:NO];
		[self addConstraints:constraints];
	}
	else
	{
		NSAssert(0, @"Can't obtain constraints to size subview (%@) to %.2f x %.2f", subview, width, height);
	}
}

- (void)addConstraintsSizingSubview:(UIView *)subview toWidth:(CGFloat)width height:(CGFloat)height withMinimumInsetsFromSelf:(UIEdgeInsets)insets
{
	NSArray *constraints = [NSLayoutConstraint constraintsOfWidth:width height:height minimumInsetsFromSuperview:insets forSubview:subview];

	if (constraints)
	{
		[subview setTranslatesAutoresizingMaskIntoConstraints:NO];
		[self addConstraints:constraints];
	}
	else
	{
		NSAssert(0, @"Can't obtain constraints to size subview (%@) to %.2f x %.2f", subview, width, height);
	}
}

@end

@implementation NSLayoutConstraint (AutoLayout)

+ (NSArray *)constraintsFittingSubviewToSuperview:(UIView *)subview
{
	NSMutableArray *allConstraints = [NSMutableArray arrayWithCapacity:4];

	NSDictionary *bindings = NSDictionaryOfVariableBindings(subview);

	NSArray *constraints =
	[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[subview]|"
											options:0
											metrics:nil
											  views:bindings];

	if ([constraints count])
	{
		[allConstraints addObjectsFromArray:constraints];
	}

	constraints =
	[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[subview]|"
											options:0
											metrics:nil
											  views:bindings];

	if ([constraints count])
	{
		[allConstraints addObjectsFromArray:constraints];
	}

	return [allConstraints copy];;
}

+ (NSLayoutConstraint *)constraintVerticallyCenteringSubview:(UIView *)subview inSuperview:(UIView *)superview
{
	return [NSLayoutConstraint constraintWithItem:subview
										attribute:NSLayoutAttributeCenterY
										relatedBy:NSLayoutRelationEqual
										   toItem:superview
										attribute:NSLayoutAttributeCenterY
									   multiplier:1
										 constant:0];
}

+ (NSLayoutConstraint *)constraintHorizontallyCenteringSubview:(UIView *)subview inSuperview:(UIView *)superview
{
	return [NSLayoutConstraint constraintWithItem:subview
										attribute:NSLayoutAttributeCenterX
										relatedBy:NSLayoutRelationEqual
										   toItem:superview
										attribute:NSLayoutAttributeCenterX
									   multiplier:1
										 constant:0];
}

+ (NSArray *)constraintsCenteringSubview:(UIView *)subview inSuperview:(UIView *)superview
{
	NSLayoutConstraint *constraintX = [self constraintHorizontallyCenteringSubview:subview inSuperview:superview];
	NSLayoutConstraint *constraintY = [self constraintVerticallyCenteringSubview:subview inSuperview:superview];

	if (constraintX && constraintY)
	{
		return @[constraintX, constraintY];
	}

	return nil;
}

+ (NSLayoutConstraint *)constraintAligningSubview:(UIView *)subview toSuperview:(UIView *)superview attribute:(NSLayoutAttribute)attribute padding:(CGFloat)padding
{
	return [NSLayoutConstraint constraintWithItem:subview
										attribute:attribute
										relatedBy:NSLayoutRelationEqual
										   toItem:superview
										attribute:attribute
									   multiplier:1
										 constant:padding];
}

+ (NSArray *)constraintsOfWidth:(CGFloat)width forSubview:(UIView *)subview
{
	NSMutableArray *allConstraints = [NSMutableArray arrayWithCapacity:4];

	NSDictionary *bindings = NSDictionaryOfVariableBindings(subview);
	NSDictionary *metrics = @{@"width" : @(width)};

	NSArray *constraints =
	[NSLayoutConstraint constraintsWithVisualFormat:@"H:[subview(width)]"
											options:0
											metrics:metrics
											  views:bindings];

	if ([constraints count])
	{
		[allConstraints addObjectsFromArray:constraints];
	}

	return [allConstraints copy];
}

+ (NSArray *)constraintsOfHeight:(CGFloat)height forSubview:(UIView *)subview
{
	NSMutableArray *allConstraints = [NSMutableArray arrayWithCapacity:4];

	NSDictionary *bindings = NSDictionaryOfVariableBindings(subview);
	NSDictionary *metrics = @{@"height" : @(height)};

	NSArray *constraints =
	[NSLayoutConstraint constraintsWithVisualFormat:@"V:[subview(height)]"
											options:0
											metrics:metrics
											  views:bindings];

	if ([constraints count])
	{
		[allConstraints addObjectsFromArray:constraints];
	}

	return [allConstraints copy];
}

+ (NSArray *)constraintsOfWidth:(CGFloat)width height:(CGFloat)height forSubview:(UIView *)subview
{
	NSMutableArray *allConstraints = [NSMutableArray arrayWithCapacity:4];

	NSDictionary *bindings = NSDictionaryOfVariableBindings(subview);
	NSDictionary *metrics = @{@"width" : @(width), @"height" : @(height)};

	NSArray *constraints =
	[NSLayoutConstraint constraintsWithVisualFormat:@"V:[subview(height)]"
											options:0
											metrics:metrics
											  views:bindings];

	if ([constraints count])
	{
		[allConstraints addObjectsFromArray:constraints];
	}

	constraints =
	[NSLayoutConstraint constraintsWithVisualFormat:@"H:[subview(width)]"
											options:0
											metrics:metrics
											  views:bindings];

	if ([constraints count])
	{
		[allConstraints addObjectsFromArray:constraints];
	}

	return [allConstraints copy];
}

+ (NSArray *)constraintsOfWidth:(CGFloat)width height:(CGFloat)height minimumInsetsFromSuperview:(UIEdgeInsets)insets forSubview:(UIView *)subview
{
	NSMutableArray *allConstraints = [NSMutableArray arrayWithCapacity:6];

	NSDictionary *bindings = NSDictionaryOfVariableBindings(subview);
	NSDictionary *metrics = @{@"width" : @(width),
							  @"height" : @(height),
							  @"top" : @(insets.top),
							  @"bottom" : @(insets.bottom),
							  @"left" : @(insets.left),
							  @"right" : @(insets.right)
							  };

	NSArray *constraints =
	[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=top@1000)-[subview(height@750)]-(>=bottom@1000)-|"
											options:0
											metrics:metrics
											  views:bindings];

	if ([constraints count])
	{
		[allConstraints addObjectsFromArray:constraints];
	}

	constraints =
	[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(>=left@1000)-[subview(width@750)]-(>=right@1000)-|"
											options:0
											metrics:metrics
											  views:bindings];

	if ([constraints count])
	{
		[allConstraints addObjectsFromArray:constraints];
	}

	return [allConstraints copy];
}

@end


text:
from django import template
import urllib.request, urllib.error, urllib.parse

register = template.Library()

# Cribbed from coderwall
# https://coderwall.com/p/4zcoxa/urlencode-filter-in-jinja2

@register.filter
def urlencode(value):
    """Passes string through urlencode"""
    output = urllib.parse.quote(value)
    return output


text:
#ifndef SPROCKIT_SPROCKIT_PREPROCESSOR_H_
#define SPROCKIT_SPROCKIT_PREPROCESSOR_H_

#include <sprockit/spkt_config.h>

#if SPKT_HAVE_CPP11
#  define spkt_static_assert(...) static_assert(__VA_ARGS__)
#endif

//================================================================================//
//================================================================================//
//================================================================================//

#if SPKT_HAVE_CPP11
// Note: these validation metafunctions will not work if the class in question is final
#include <type_traits>  // for std::integral_constant
/**
 * A macro to generate a metafunction that checks if a class has a member type with a name
 *   given by the macro parameter.
 * Adapted from http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Member_Detector
 *
 * Example usage: (adapted from the same page as above)
 *
 *   GENERATE_HAS_MEMBER_TYPE(Foo) // Creates 'has_member_type_Foo'.
 *
 *   struct A
 *   {
 *       struct Foo;
 *   };
 *
 *   struct B
 *   {
 *       using Foo = int;
 *   };
 *
 *   struct D
 *   {
 *       typedef char* Foo;
 *   };
 *
 *   struct C : A, B { }; // Will also work on incomplete or ambiguous types.
 *
 *
 *   int main ( )
 *   {
 *       std::cout << std::boolalpha
 *                 << "'Foo' in 'C' : "
 *                 << sprockit::validation::has_member_type_Foo<C>::value
 *                 << "\n";
 *                 << "'Foo' in 'D' : "
 *                 << sprockit::validation::has_member_type_Foo<D>::value
 *                 << "\n";
 *   }
 */
#define SPKT_GENERATE_HAS_MEMBER_TYPE(Type)                                       \
                                                                                \
namespace sprockit { namespace validation {                                       \
template < class T >                                                              \
class HasMemberType_##Type                                                        \
{                                                                                \
private:                                                                          \
    using Yes = char[2];                                                          \
    using  No = char[1];                                                          \
                                                                                \
    struct Fallback { struct Type { }; };                                         \
    struct Derived : T, Fallback { };                                             \
                                                                                \
    template < class U >                                                          \
    static No& test ( typename U::Type* );                                        \
    template < typename U >                                                       \
    static Yes& test ( U* );                                                      \
                                                                                \
public:                                                                           \
    static constexpr bool RESULT = sizeof(test<Derived>(nullptr)) == sizeof(Yes); \
};                                                                                \
                                                                                \
template < class T >                                                              \
struct has_member_type_##Type                                                     \
: public std::integral_constant<bool, HasMemberType_##Type<T>::RESULT>            \
{ };                                                                              \
} } /* end of namespaces */

// And a flag to let the compiler know this feature is available
#  define SPKT_HAS_MEMBER_TYPE_VALIDATION 1

////////////////////////////////////////////////////////////////////////////////

/**
 * A macro to generate a metafunction that checks if a class has a member with a name
 *   given by the macro parameter.
 * Adapted from http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Member_Detector
 *
 * Example usage: (adapted from the same page as above)
 *
 *   GENERATE_HAS_MEMBER(att)  // Creates 'has_member_att'.
 *   GENERATE_HAS_MEMBER(func) // Creates 'has_member_func'.
 *
 *
 *   struct A
 *   {
 *       int att;
 *       void func ( double );
 *   };
 *
 *   struct B
 *   {
 *       char att[3];
 *       double func ( const char* );
 *   };
 *
 *   struct C : A, B { }; // It will also work with ambiguous members.
 *
 *
 *   int main ( )
 *   {
 *       std::cout << std::boolalpha
 *                 << "\n" "'att' in 'C' : "
 *                 << has_member_att<C>::value // <type_traits>-like interface.
 *                 << "\n" "'func' in 'C' : "
 *                 << has_member_func<C>() // Implicitly convertible to 'bool'.
 *                 << "\n";
 *   }
 */
#define SPKT_GENERATE_HAS_MEMBER(member)                                          \
                                                                                \
namespace sprockit { namespace validation {                                       \
template < class T >                                                              \
class HasMember_##member                                                          \
{                                                                                \
private:                                                                          \
    using Yes = char[2];                                                          \
    using  No = char[1];                                                          \
                                                                                \
    struct Fallback { int member; };                                              \
    struct Derived : T, Fallback { };                                             \
                                                                                \
    template < class U >                                                          \
    static No& test ( decltype(U::member)* );                                     \
    template < typename U >                                                       \
    static Yes& test ( U* );                                                      \
                                                                                \
public:                                                                           \
    static constexpr bool RESULT = sizeof(test<Derived>(nullptr)) == sizeof(Yes); \
};                                                                                \
                                                                                \
template < class T >                                                              \
struct has_member_##member                                                        \
: public std::integral_constant<bool, HasMember_##member<T>::RESULT>              \
{ };                                                                              \
} } /* end namespaces */
// And a flag to let the compiler know this feature is available
#  define SPKT_HAS_MEMBER_VALIDATION 1

////////////////////////////////////////////////////////////////////////////////

// TODO overloaded member function detection macro

////////////////////////////////////////////////////////////////////////////////

#else // No validation when CPP11 is not available

// TODO non-c++11 versions of these macros

#endif // SPKT_HAVE_CPP11

//================================================================================//
//================================================================================//
//================================================================================//

#endif /* SPROCKIT_SPROCKIT_PREPROCESSOR_H_ */


text:
SideComments.js is a UI component to give you [Medium.com](http://medium.com/) style comment management on the front-end. It allows users to comment directly on sections of content rather than the boring comment stream on the bottom of the page that we're so used to.

**Note:** This component only handles the display / user interface of how your comments are presented. It does _not_ provide any utilities to help manage storing or retreiving your comment data from your server, how you do that is entirely up to you. Check out the integrations section for resources related to back-end integration.

## Demo

Check out a sweet demo of SideComments here: [https://aroc.github.io/side-comments-demo](https://aroc.github.io/side-comments-demo)

## Get Started
**How to start using SideComments.js on your website immediately.**

### 1. Download SideComments.js

Download SideComments immediately:
[](https://github.com/aroc/side-comments/archive/master.zip)

Install with [Component](https://github.com/component/component):
`component install aroc/side-comments`

or include side-comments in your `component.json` file's `dependencies: {}` object.

### 2. Include SideComments.js in your project.

**Note: jQuery is required**
You must include jQuery in your project in order for SideComments.js to work. This component uses jQuery to manage DOM manipulation and will not work without it.

You'll need to include the following single JavaScript file and two CSS files to get SideComments.js working.
- `release/side-comments.js`
- `release/side-comments.css`
- `release/themes/default-theme.css`

You can choose **not** to include `default-theme.css`, but you'll need to style SideComments youself if you choose not to include it, as `side-comments.css` handles only the basic layout styling and not making it all pretty and looking like Medium.com.

### 3. Set up your HTML.

You need to have a wrapper element to point SideComments at and two things on each commentable section; the class `commentable-section` and the data attribute `data-section-id`, which holds the unique ID of that commentable-section for this page.

```
<div id="commentable-area">
  <p data-section-id="1" class="commentable-section">
    This is a section that can be commented on.
  </p>
  <p data-section-id="2" class="commentable-section">
    This is a another section that can be commented on.
  </p>
  <p data-section-id="3" class="commentable-section">
    This is yet another section that can be commented on.
  </p>
</div>
```

### 4. Initialize a new SideComments object.

```
// First require it.
var SideComments = require('side-comments');

// Then, create a new SideComments instance, passing in the wrapper element and the optional the current user and any existing comments.
sideComments = new SideComments('#commentable-area', currentUser, existingComments);
```

The current user is an object and is expected to be in the following format:

```
{
  id: 1,
  avatarUrl: "http://f.cl.ly/items/0s1a0q1y2Z2k2I193k1y/default-user.png",
  name: "You"
}
```

The existing comments argument is expected to be an array of sections with a nested array of comments. It needs to look like the following:

```
[
  {
    "sectionId": "1",
    "comments": [
      {
        "authorAvatarUrl": "http://f.cl.ly/items/1W303Y360b260u3v1P0T/jon_snow_small.png",
        "authorName": "Jon Sno",
        "comment": "I'm Ned Stark's bastard. Related: I know nothing."
      },
      {
        "authorAvatarUrl": "http://f.cl.ly/items/2o1a3d2f051L0V0q1p19/donald_draper.png",
        "authorName": "Donald Draper",
        "comment": "I need a scotch."
      }
    ]
  },
  {
    "sectionId": "3",
    "comments": [
      {
        "authorAvatarUrl": "http://f.cl.ly/items/0l1j230k080S0N1P0M3e/clay-davis.png",
        "authorName": "Senator Clay Davis",
        "comment": "These Side Comments are incredible. Sssshhhiiiiieeeee."
      }
    ]
  }
];
```

### 5. Listen to post and delete events.

Finally, in order to know when a comment has been posted or deleted, just bind to your SideComments' object events and then do whatever you want with them, (likely save and delete from your database).

```
// Listen to "commentPosted", and send a request to your backend to save the comment.
// More about this event in the "docs" section.
sideComments.on('commentPosted', function( comment ) {
    $.ajax({
        url: '/comments',
        type: 'POST',
        data: comment,
        success: function( savedComment ) {
            // Once the comment is saved, you can insert the comment into the comment stream with "insertComment(comment)".
            sideComments.insertComment(comment);
        }
    });
});

// Listen to "commentDeleted" and send a request to your backend to delete the comment.
// More about this event in the "docs" section.
sideComments.on('commentDeleted', function( commentId ) {
    $.ajax({
        url: '/comments/' + commentId,
        type: 'DELETE',
        success: function( success ) {
            // Do something.
        }
    });
});
```

## Docs [![Inline docs](http://inch-ci.org/github/aroc/side-comments.svg?branch=master)](http://inch-ci.org/github/aroc/side-comments)

**Overview of all events and method you can leverage in SideComments.js**

### SideComments Constructor
The constructor takes one required and two optional arguments:

- `$el` (String): The element which contains all the `.commentable-section` elements.

- `currentUser` (Object): The user representation new comments will be posted under. As it's optional, you can just pass `null` if there is no current user at the time and set one at a later time with the `setCurrentUser` method, which is documented below. The current user object needs to look like this: [https://gist.github.com/aroc/02a0f8badf219da12667](https://gist.github.com/aroc/02a0f8badf219da12667)

- `existingComments` (Array): An array of existing comments that you want inserted at initialization time. You can also insert comments yourself at later time with the `insertComment` method, outlined below. The structure of the objects in this array needs to look like this: [https://gist.github.com/aroc/54a2669783231a0d2215](https://gist.github.com/aroc/54a2669783231a0d2215)

### Methods

#### deselectSection(sectionId)

De-select a section and make it inactive, hiding the side comments. If the side comments are already hidden, this method will have no effect.

```
sideComments.deselectSection(12);
```

#### setCurrentUser(currentUser)

Sets the currentUser to be used for all new comments.

```
var currentUser = {
  "id": 1,
  "avatarUrl": "users/avatars/user1.png",
  "name": "Jim Jones"
};
sideComments.setCurrentUser(currentUser);
```

#### removeCurrentUser()

Removes the currentUser. Without a currentUser, comments amy not be posted. Instead, the `addCommentAttempted` event gets triggered when a user clicks the "Add Comment" button.

#### insertComment(comment)

Inserts a comment into the markup. It will insert into the section specified by the comment object.

```
var comment = {
  sectionId: 12,
  comment: "Hey there!",
  authorAvatarUrl: "users/avatars/test1.png",
  authorName: "Jim Jones",
  authorId: 16
};
sideComments.insertComment(comment);
```

#### removeComment(sectionId, commentId)

Removes a comment from the SideComments object and from the markup.

#### commentsAreVisible()

Returns true if the comments are visbile, false if they are not.

#### destroy()

Removing the sideComments object, cleaning up any event bindings and removing any markup from the DOM.

### Events

#### commentPosted
Values passed: `comment (Object)`
Fired after a user fills out the comment form and clicks "Post".

#### addCommentAttempted
Values passed: None.
Fired when a sideComments object doesn't have a current user and the "Add Comment" button is clicked.

#### commentDeleted
Values passed: `comment (Object)`
Fired after a user has clicked "Delete" on one of their comments and has confirmed with the dialog that they do want to delete it.

## Integrating with your back-end

SideComments has no opinion on how you should integrate with your back-end or what technology stack you should use on your back-end. However, here are some resources that may help you depending on your platform:

### WordPress

- WP-Side-Comments by [@richardtape](https://github.com/richardtape): A WP plugin that wraps this project in a plugin (currently very early stage) [https://github.com/richardtape/wp-side-comments](https://github.com/richardtape/wp-side-comments)

- WPSideComments by [@strategio](https://github.com/strategio): Another WP plugin that wraps this project (early stage) [http://wordpress.org/plugins/wp-side-comments/](http://wordpress.org/plugins/wp-side-comments/)

- [@dcondrey](https://github.com/dcondrey) has an exmaple of how you might be able to enqueue the SideComments scripts for WordPress: [https://github.com/aroc/side-comments/pull/14](https://github.com/aroc/side-comments/pull/14)

### Hull [hull.io](http://hull.io/)

A component to integrate SideComments with Hull, which gives you a full back-end to power your comments.
[http://hull-components.github.io/side-comments/](http://hull-components.github.io/side-comments/)

## License

The MIT License (MIT)

Copyright (c) 2014 Eric Anderson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
<?php

namespace Ilios\CoreBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

use Ilios\CoreBundle\Traits\IdentifiableEntityInterface;

use Ilios\CoreBundle\Traits\TitledEntityInterface;
use Ilios\CoreBundle\Traits\CoursesEntityInterface;

/**
 * Interface CohortInterface
 */
interface CohortInterface extends
    IdentifiableEntityInterface,
    TitledEntityInterface,
    CoursesEntityInterface,
    LoggableEntityInterface
{
    /**
     * @param ProgramYearInterface $programYear
     */
    public function setProgramYear(ProgramYearInterface $programYear = null);

    /**
     * @return ProgramYearInterface
     */
    public function getProgramYear();

    /**
     * @return LearnerGroupInterface[]|ArrayCollection
     */
    public function getLearnerGroups();

    /**
    * @param Collection $learnerGroups
    */
    public function setLearnerGroups(Collection $learnerGroups);

    /**
    * @param LearnerGroupInterface $learnerGroup
    */
    public function addLearnerGroup(LearnerGroupInterface $learnerGroup);

    /**
     * @param Collection $users
     */
    public function setUsers(Collection $users = null);

    /**
     * @param UserInterface $user
     */
    public function addUser(UserInterface $user);

    /**
     * @return ArrayCollection|UserInterface[]
     */
    public function getUsers();

    /**
     * Get the school we belong to
     * @return SchoolInterface|null
     */
    public function getSchool();

    /**
     * Gets the program that this cohort belongs to.
     * @return ProgramInterface|null
     */
    public function getProgram();
}


text:
<?php
class Session {

	private static $isStarted = false;

	public static function start() {
		if (!self::$isStarted) {
			session_start();
			self::$isStarted = true;
		}
	}

	public static function close() {
		if (self::$isStarted) {
			session_write_close ();
			self::$isStarted = false;
		}
	}

}
?>


text:
<!DOCTYPE HTML>

<title>Uses of Class com.bitpay.sdk.model.Rate.Rate (BitPay 8.6.2 API)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-11-21">
<meta name="description" content="use: package: com.bitpay.sdk.model.Rate, class: Rate">
<meta name="generator" content="javadoc/ClassUseWriter">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../jquery-ui.overrides.css" title="Style">

JavaScript is disabled on your browser.

<button id="navbar-toggle-button" aria-controls="navbar-top" aria-expanded="false" aria-label="Toggle navigation links"></button>

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

SEARCH:
<input type="text" id="search-input" disabled placeholder="Search">
<input type="reset" id="reset-button" disabled value="reset">

Uses of Class
com.bitpay.sdk.model.Rate.Rate

Packages that use Rate

Package

Description

com.bitpay.sdk.model.Rate

BitPay SDK Rate.

Uses of Rate in com.bitpay.sdk.model.Rate

Methods in com.bitpay.sdk.model.Rate that return types with arguments of type Rate

Modifier and Type

Method

Description

List<Rate>

Rates.getRates()

Gets rates.

Constructor parameters in com.bitpay.sdk.model.Rate with type arguments of type Rate

Modifier

Constructor

Description

Rates<wbr>(List<Rate> rates,
 Client bp)

Instantiates a new Rates.

Copyright © 2022 BitPay. All rights reserved.


text:
<?php

namespace EklundChristopher\ViewPress\Filters\Templates;

use EklundChristopher\ViewPress\Filters\TemplateHandler as Handler;

class HomeHandler extends Handler
{
    /**
     * Return an array of templates in order of precedence.
     *
     * ./home.php
     * ./index.php
     *
     * @param  array  $templates
     * @return array
     */
    public function templates(array $templates)
    {
        $templates[] = 'home.php';
        $templates[] = 'index.php';

        return $templates;
    }
}


text:
This repository holds the samples used in the python documentation on [cloud.google.com](https://cloud.google.com).

[![Build Status](https://travis-ci.org/GoogleCloudPlatform/python-docs-samples.svg)](https://travis-ci.org/GoogleCloudPlatform/python-docs-samples)
[![Coverage Status](https://coveralls.io/repos/github/GoogleCloudPlatform/python-docs-samples/badge.svg?branch=HEAD)](https://coveralls.io/github/GoogleCloudPlatform/python-docs-samples?branch=HEAD)

For more detailed introduction to a product, check the README.md in the
corresponding folder.

## Contributing changes

* See [CONTRIBUTING.md](CONTRIBUTING.md)

## Licensing

* See [LICENSE](LICENSE)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Animal xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />

View Javadoc

1
16  package org.yaml.snakeyaml.immutable;
17
18  public interface Animal {
19      public String getName();
20  }

This page was automatically generated by Maven


text:
using System;
using System.Net;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Amazon.Runtime;
using System.Threading.Tasks;

namespace Elasticsearch.Net.Aws
{
    internal static class SignV4Util
    {
        static readonly char[] _datePartSplitChars = { 'T' };

        public static async Task SignRequestAsync(IRequest request, ImmutableCredentials credentials, string region, string service)
        {
            await request.PrepareForSigningAsync().ConfigureAwait(false);
            var date = DateTime.UtcNow;
            var dateStamp = date.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
            var amzDate = date.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
            request.Headers.XAmzDate = amzDate;

            var signingKey = GetSigningKey(credentials.SecretKey, dateStamp, region, service);
            var stringToSign = GetStringToSign(request, region, service);
            Debug.Write($"========== String to Sign ==========\r\n{stringToSign}\r\n========== String to Sign ==========\r\n");
            var signature = signingKey.GetHmacSha256Hash(stringToSign).ToLowercaseHex();
            var auth = string.Format(
                "AWS4-HMAC-SHA256 Credential={0}/{1}, SignedHeaders={2}, Signature={3}",
                credentials.AccessKey,
                GetCredentialScope(dateStamp, region, service),
                GetSignedHeaders(request),
                signature);

            request.Headers.Authorization = auth;
            if (!string.IsNullOrWhiteSpace(credentials.Token))
                request.Headers.XAmzSecurityToken = credentials.Token;
        }

        public static byte[] GetSigningKey(string secretKey, string dateStamp, string region, string service)
        {
            return _encoding.GetBytes("AWS4" + secretKey)
                .GetHmacSha256Hash(dateStamp)
                .GetHmacSha256Hash(region)
                .GetHmacSha256Hash(service)
                .GetHmacSha256Hash("aws4_request");
        }

        private static byte[] GetHmacSha256Hash(this byte[] key, string data)
        {
            using (var kha = new HMACSHA256())
            {
                kha.Key = key;
                return kha.ComputeHash(_encoding.GetBytes(data));
            }
        }

        public static string GetStringToSign(IRequest request, string region, string service)
        {
            var canonicalRequest = GetCanonicalRequest(request);
            Debug.Write($"========== Canonical Request ==========\r\n{canonicalRequest}\r\n========== Canonical Request ==========\r\n");
            var awsDate = request.Headers.XAmzDate;
            Debug.Assert(Regex.IsMatch(awsDate, @"\d{8}T\d{6}Z"));
            var datePart = awsDate.Split(_datePartSplitChars, 2)[0];
            return string.Join("\n",
                "AWS4-HMAC-SHA256",
                awsDate,
                GetCredentialScope(datePart, region, service),
                GetHash(canonicalRequest).ToLowercaseHex()
            );
        }

        private static string GetCredentialScope(string date, string region, string service)
        {
            return string.Format("{0}/{1}/{2}/aws4_request", date, region, service);
        }

        public static string GetCanonicalRequest(IRequest request)
        {
            var canonicalHeaders = request.GetCanonicalHeaders();
            var result = new StringBuilder();
            result.Append(request.Method);
            result.Append('\n');
            result.Append(GetPath(request.RequestUri));
            result.Append('\n');
            result.Append(request.RequestUri.GetCanonicalQueryString());
            result.Append('\n');
            WriteCanonicalHeaders(canonicalHeaders, result);
            result.Append('\n');
            WriteSignedHeaders(canonicalHeaders, result);
            result.Append('\n');
            WriteRequestPayloadHash(request.Content, result);
            return result.ToString();
        }

        private static string GetPath(Uri uri)
        {
            var path = uri.AbsolutePath;
            if (path.Length == 0) return "/";

            IEnumerable<string> segments = path
                .Split('/')
                .Select(segment =>
                {
                    string escaped = WebUtility.UrlEncode(segment);
                    escaped = escaped.Replace("*", "%2A");
                    return escaped;
                }
                );
            return string.Join("/", segments);
        }

        static bool ShouldSignHeader(string headerName)
            => headerName.StartsWith("x-amz-")
            || headerName == "content-type"
            || headerName == "content-encoding"
            || headerName == "accept-encoding"
            || headerName == "date";

        private static Dictionary<string, string> GetCanonicalHeaders(this IRequest request)
        {
            var q = from string key in request.Headers.Keys
                    let headerName = key.ToLowerInvariant()
                    where ShouldSignHeader(headerName)
                    let headerValues = string.Join(", ",
                        request.Headers
                        .GetValues(key) ?? Enumerable.Empty<string>()
                        .Select(v => v.Trimall())
                    )
                    select new { headerName, headerValues };
            var result = q.ToDictionary(v => v.headerName, v => v.headerValues);
            result["host"] = request.RequestUri.Host.ToLowerInvariant();
            return result;
        }

        private static void WriteCanonicalHeaders(Dictionary<string, string> canonicalHeaders, StringBuilder output)
        {
            var q = from pair in canonicalHeaders
                    orderby pair.Key ascending
                    select string.Format("{0}:{1}\n", pair.Key, pair.Value);
            foreach (var line in q)
            {
                output.Append(line);
            }
        }

        private static string GetSignedHeaders(IRequest request)
        {
            var canonicalHeaders = request.GetCanonicalHeaders();
            var result = new StringBuilder();
            WriteSignedHeaders(canonicalHeaders, result);
            return result.ToString();
        }

        private static void WriteSignedHeaders(Dictionary<string, string> canonicalHeaders, StringBuilder output)
        {
            bool started = false;
            foreach (var pair in canonicalHeaders.OrderBy(v => v.Key))
            {
                if (started) output.Append(';');
                output.Append(pair.Key.ToLowerInvariant());
                started = true;
            }
        }

        private static NameValueCollection ParseQueryString(string query) =>
            Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(query)
                .Aggregate(new NameValueCollection(), (col, kv) =>
                {
                    kv.Value.ToList().ForEach(v => col.Add(kv.Key, v));
                    return col;
                });

        public static string GetCanonicalQueryString(this Uri uri)
        {
            if (string.IsNullOrWhiteSpace(uri.Query)) return string.Empty;
            var queryParams = ParseQueryString(uri.Query);
            var q = from string key in queryParams
                    orderby key
                    from value in queryParams.GetValues(key)
                    select new { key, value };

            var output = new StringBuilder();
            foreach (var param in q)
            {
                if (output.Length > 0) output.Append('&');
                output.WriteEncoded(param.key);
                output.Append('=');
                output.WriteEncoded(param.value);
            }
            return output.ToString();
        }

        private static void WriteEncoded(this StringBuilder output, string value)
        {
            for (var i = 0; i < value.Length; ++i)
            {
                if (value[i].RequiresEncoding())
                {
                    output.Append(Uri.EscapeDataString(value[i].ToString()));
                }
                else
                {
                    output.Append(value[i]);
                }
            }
        }

        private static bool RequiresEncoding(this char value)
        {
            if ('A' <= value && value <= 'Z') return false;
            if ('a' <= value && value <= 'z') return false;
            if ('0' <= value && value <= '9') return false;
            switch (value)
            {
                case '-':
                case '_':
                case '.':
                case '~':
                    return false;
            }
            return true;
        }

        static readonly byte[] _emptyBytes = new byte[0];

        private static void WriteRequestPayloadHash(byte[] data, StringBuilder output)
        {
            data = data ?? _emptyBytes;
            var hash = GetHash(data);
            foreach (var b in hash)
            {
                output.AppendFormat("{0:x2}", b);
            }
        }

        private static string ToLowercaseHex(this byte[] data)
        {
            var result = new StringBuilder();
            foreach (var b in data)
            {
                result.AppendFormat("{0:x2}", b);
            }
            return result.ToString();
        }

        static readonly UTF8Encoding _encoding = new UTF8Encoding(false);

        private static byte[] GetHash(string data)
        {
            return GetHash(_encoding.GetBytes(data));
        }

        private static byte[] GetHash(this byte[] data)
        {
            using (var algo = SHA256.Create())
            {
                return algo.ComputeHash(data);
            }
        }
    }
}


text:
<?php

namespace Dcms\Bundle\CoreBundle\NodeFinder;

/**
 * Node finder interface.
 *
 * @author Daniel Leech <daniel@dantleech.com>
 */
interface NodeFinder
{
    /**
     * Find the node with the given relative path.
     *
     * @param string $relativePath
     */
    public function findNode($relativePath);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<objects serializationModel="Studio.01.08.00">
    <object class="EncodableAsset" id="{2264ae3d-76f0-4d87-b857-304552f7c639}">
        <property name="assetPath">
            <value>Environment/</value>
        </property>
        <relationship name="masterAssetFolder">
            <destination>{cbdaacbf-f328-457b-bedb-8c33cacc0690}</destination>
        </relationship>
    </object>
</objects>


text:
#pragma once

#include <cusp/detail/config.h>

// this system inherits elementwise
#include <cusp/system/detail/sequential/graph/maximal_independent_set.h>


text:
package gocyk

import (
	grm "github.com/ghigt/gocyk/grammar"
	"github.com/ghigt/gocyk/ptree"
	"github.com/ghigt/gocyk/rtable"
)

// GoCYK type contains the recognition table, the parsing tree,
// the grammar and the substrings. It provides methods to abstract
// the calculation of the CYK algorithm to modify the parsing text.
type GoCYK struct {
	Table   *rtable.RTable
	Tree    *ptree.PTree
	Grammar *grm.Grammar
	Sub     []string
}

// New instanciate a GoCYK structure and returns its address.
func New(grammar *grm.Grammar) *GoCYK {
	return &GoCYK{
		Table:   &rtable.RTable{},
		Tree:    &ptree.PTree{},
		Grammar: grammar,
	}
}

// Add adds a new substring at the end then recalculate the
// recognition table and the parsing tree.
func (g *GoCYK) Add(s string) error {
	return g.Insert(s, g.Table.Size())
}

// Insert inserts a new substring at the given position then
// recalculate the recognition table and the parsing tree.
func (g *GoCYK) Insert(s string, pos int) error {
	c, err := g.Table.Insert(pos)
	if err != nil {
		return err
	}
	g.Sub = append(g.Sub, "")
	copy(g.Sub[pos+1:], g.Sub[pos:])
	g.Sub[pos] = s
	g.completeColumn(s, c, pos)
	if pos < g.Table.Size()-1 {
		g.insertFollowing(pos)
	}
	return nil
}

// InsertNC inserts a new substring at the given position then
// recalculate the recognition table and the parsing tree
// (wihtout concurrency).
func (g *GoCYK) InsertNC(s string, pos int) error {
	c, err := g.Table.Insert(pos)
	if err != nil {
		return err
	}
	g.Sub = append(g.Sub, "")
	copy(g.Sub[pos+1:], g.Sub[pos:])
	g.Sub[pos] = s
	g.completeColumn(s, c, pos)
	if pos < g.Table.Size()-1 {
		g.insertFollowingWithoutC(pos)
	}
	return nil
}

// Remove removes the substring at the given position then
// recalculate the recognition table and the parsing tree.
func (g *GoCYK) Remove(pos int) error {
	if err := g.Table.Remove(pos); err != nil {
		return err
	}
	g.Sub = append(g.Sub[:pos], g.Sub[pos+1:]...)
	g.removeFollowing(pos)
	return nil
}

// IsValid returns true if the parsing string follows the grammar.
func (g *GoCYK) IsValid() bool {
	return g.Table.IsValid()
}


text:
'use strict';

const mongoose = require('mongoose');
const logger = require('heroku-logger');
const Promise = require('bluebird');

const utilHelper = require('../../lib/helpers/util');

/**
 * Schema.
 */
const messageSchema = new mongoose.Schema({
  conversationId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Conversation',
    index: true,
  },
  direction: {
    type: String,
    enum: ['inbound', 'outbound-reply', 'outbound-api-send', 'outbound-api-import'],
    required: true,
  },
  // Populated when a member has been anonymized
  deletedAt: Date,
  userId: { type: String, index: true },
  platformMessageId: { type: String, index: true },
  campaignId: Number,
  template: String,
  text: String,
  topic: String,
  attachments: Array,
  broadcastId: String,
  agentId: String,
  match: String,
  macro: String,
  metadata: {
    // CampaignId associated with this broadcast outbound message.
    // Not set for inbound or non broadcast outbound messages.
    campaignId: Number,
    // Delivery metadata reported by Twilio via the statusCallback webhook for outbound messages
    delivery: {
      queuedAt: Date,
      deliveredAt: Date,
      failedAt: Date,
      failureData: { type: mongoose.Schema.Types.Mixed },
      totalSegments: Number,
    },
    requestId: { type: String, index: true },
    retryCount: Number,
  },
}, { timestamps: true });

messageSchema.index({ createdAt: 1 });
messageSchema.index({ createdAt: -1, broadcastId: 1, direction: 1, macro: 1 });
messageSchema.index({ broadcastId: -1, direction: 1, macro: 1 });

/**
 * Instance Methods
 */
messageSchema.methods.updateMacro = function (macroName) {
  this.macro = macroName;
  return this.save();
};

/**
 * Static Methods
 */

/**
 * Gets the message that matches this metadata.requestId and direction.
 * Updates it with the new properties passed in the update object.
 * @param {string} requestId
 * @param {object} update
 * @return {object}
 */
messageSchema.statics.updateMessageByRequestIdAndDirection = function (requestId,
  update = {}, direction) {
  if (!direction) {
    logger.error('updateMessageByRequestIdAndDirection: direction argument missing.');
    return Promise.resolve(null);
  }
  const query = {
    'metadata.requestId': requestId,
    direction,
  };
  const options = { new: true };

  return utilHelper.deepUpdateWithDotNotationParser(update)
    .then(parsedUpdate => this.findOneAndUpdate(query, parsedUpdate, options));
};

/**
 * gets the inbound message that matches this metadata.requestId
 * and updates its metadata with the new one.
 * @param {string} requestId
 * @param {object} metadata
 * @return {object}
 */
messageSchema.statics.updateInboundMessageMetadataByRequestId = function (requestId,
  metadata = {}) {
  return this.updateMessageByRequestIdAndDirection(requestId, { metadata }, 'inbound');
};

module.exports = mongoose.model('Message', messageSchema);


text:
package com.googlecode.jmxtrans.connections;

import org.apache.commons.pool.BaseKeyedPoolableObjectFactory;

import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import java.io.IOException;

/**
 * Allows us to pool connections to remote jmx servers.
 */
public class JmxConnectionFactory extends BaseKeyedPoolableObjectFactory<JMXConnectionParams, JMXConnector> {

	/**
	 * Creates the connection.
	 */
	@Override
	public JMXConnector makeObject(JMXConnectionParams params) throws Exception {
		return JMXConnectorFactory.connect(params.getUrl(), params.getEnvironment());
	}

	/**
	 * Closes the connection.
	 */
	@Override
	public void destroyObject(JMXConnectionParams params, JMXConnector connector) throws Exception {
		connector.close();
	}

	/**
	 * Validates that the connection is good.
	 */
	@Override
	public boolean validateObject(JMXConnectionParams params, JMXConnector connector) {
		boolean result = false;
		try {
			connector.getConnectionId();
			connector.getMBeanServerConnection().getMBeanCount();
			result = true;
		} catch (IOException ex) {
			// ignored
		}
		return result;
	}
}


text:
module.exports.stage = require("./stage");
module.exports.seqElement = require("./seqElement");
module.exports.labelElement = require("./labelElement");
module.exports.featureElement = require("./FeatureElement");