text:
using Newtonsoft.Json;

namespace ClientSideApp.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class Customer : BaseEntity
    {
        public Customer()
        {
            Notes = new HashSet<Note>();
        }

        [Key]
        public int Id { get; set; }

        [StringLength(50)]
        public string Name { get; set; }

        [StringLength(50)]
        public string Phone_number { get; set; }

        [StringLength(300)]
        public string Email { get; set; }

        [JsonIgnore]
        public virtual ICollection<Note> Notes { get; set; }

        public DateTime? created_at
        {
            get { return this.CreatedOn; }
        }

        public DateTime? updated_at
        {
            get { return this.UpdatedOn; }
        }
    }
}


text:
layout       : blocks/working-session
title        : Threat Modeling by Feature and Layer
type         : workshop
owasp-project: no
track        : Threat Model
technology   :
related-to   :
status       : draft
organizers   :
participants :
---

...intro text...

## Why

...why text...

## What

...what text...

## Who

... target audience ...

redpajama_set_name: RedPajamaGithub


text:
/**
 * Creates a rule that will be applied when an MDC-Web component is within the context of an RTL layout.
 *
 * Usage Example:
 * ```scss
 * .mdc-foo {
 *   position: absolute;
 *   left: 0;
 *
 *   @include mdc-rtl {
 *     left: auto;
 *     right: 0;
 *   }
 *
 *   &__bar {
 *     margin-left: 4px;
 *     @include mdc-rtl(".mdc-foo") {
 *       margin-left: auto;
 *       margin-right: 4px;
 *     }
 *   }
 * }
 *
 * .mdc-foo--mod {
 *   padding-left: 4px;
 *
 *   @include mdc-rtl {
 *     padding-left: auto;
 *     padding-right: 4px;
 *   }
 * }
 * ```
 *
 * Note that this works by checking for [dir="rtl"] on an ancestor element. While this will work
 * in most cases, it will in some cases lead to false negatives, e.g.
 *
 * ```html
 * <html dir="rtl">
 *   <!-- ... -->
 *   <div dir="ltr">
 *     <div class="mdc-foo">Styled incorrectly as RTL!</div>
 *   </div>
 * </html>
 * ```
 *
 * In the future, selectors such as :dir (http://mdn.io/:dir) will help us mitigate this.
 */
/**
 * Takes a base box-model property - e.g. margin / border / padding - along with a default
 * direction and value, and emits rules which apply the value to the
 * "<base-property>-<default-direction>" property by default, but flips the direction
 * when within an RTL context.
 *
 * For example:
 *
 * ```scss
 * .mdc-foo {
 *   @include mdc-rtl-reflexive-box(margin, left, 8px);
 * }
 * ```
 * is equivalent to:
 *
 * ```scss
 * .mdc-foo {
 *   margin-left: 8px;
 *
 *   @include mdc-rtl {
 *     margin-right: 8px;
 *     margin-left: 0;
 *   }
 * }
 * ```
 * whereas:
 *
 * ```scss
 * .mdc-foo {
 *   @include mdc-rtl-reflexive-box(margin, right, 8px);
 * }
 * ```
 * is equivalent to:
 *
 * ```scss
 * .mdc-foo {
 *   margin-right: 8px;
 *
 *   @include mdc-rtl {
 *     margin-right: 0;
 *     margin-left: 8px;
 *   }
 * }
 * ```
 *
 * You can also pass a 4th optional $root-selector argument which will be forwarded to `mdc-rtl`,
 * e.g. `@include mdc-rtl-reflexive-box-property(margin, left, 8px, ".mdc-component")`.
 *
 * Note that this function will always zero out the original value in an RTL context. If you're
 * trying to flip the values, use mdc-rtl-reflexive-property().
 */
/**
 * Takes a base property and emits rules that assign <base-property>-left to <left-value> and
 * <base-property>-right to <right-value> in a LTR context, and vice versa in a RTL context.
 * For example:
 *
 * ```scss
 * .mdc-foo {
 *   @include mdc-rtl-reflexive-property(margin, auto, 12px);
 * }
 * ```
 * is equivalent to:
 *
 * ```scss
 * .mdc-foo {
 *   margin-left: auto;
 *   margin-right: 12px;
 *
 *   @include mdc-rtl {
 *     margin-left: 12px;
 *     margin-right: auto;
 *   }
 * }
 * ```
 *
 * A 4th optional $root-selector argument can be given, which will be passed to `mdc-rtl`.
 */
/**
 * Takes an argument specifying a horizontal position property (either "left" or "right") as well
 * as a value, and applies that value to the specified position in a LTR context, and flips it in a
 * RTL context. For example:
 *
 * ```scss
 * .mdc-foo {
 *   @include mdc-rtl-reflexive-position(left, 0);
 *   position: absolute;
 * }
 * ```
 * is equivalent to:
 *
 * ```scss
 *  .mdc-foo {
 *    position: absolute;
 *    left: 0;
 *    right: initial;
 *
 *    @include mdc-rtl {
 *      right: 0;
 *      left: initial;
 *    }
 *  }
 * ```
 * An optional third $root-selector argument may also be given, which is passed to `mdc-rtl`.
 */
/*
  Precomputed linear color channel values, for use in contrast calculations.
  See https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests

  Algorithm, for c in 0 to 255:
  f(c) {
    c = c / 255;
    return c < 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
  }

  This lookup table is needed since there is no `pow` in SASS.
*/
/**
 * Calculate the luminance for a color.
 * See https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
 */
/**
 * Calculate the contrast ratio between two colors.
 * See https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
 */
/**
 * Determine whether to use dark or light text on top of given color.
 * Returns "dark" for dark text and "light" for light text.
 */
/*
  Main theme colors.
  If you're a user customizing your color scheme in SASS, these are probably the only variables you need to change.
*/
/* Indigo 500 */
/* Pink A200 */
/* White */
/* Which set of text colors to use for each main theme color (light or dark) */
/* Text colors according to light vs dark and text type */
/* Primary text colors for each of the theme colors */
/**
 * Applies the correct theme color style to the specified property.
 * $property is typically color or background-color, but can be any CSS property that accepts color values.
 * $style should be one of the map keys in $mdc-theme-property-values (_variables.scss).
 */
/**
 * Creates a rule to be used in MDC-Web components for dark theming, and applies the provided contents.
 * Should provide the $root-selector option if applied to anything other than the root selector.
 * When used with a modifier class, provide a second argument of `true` for the $compound parameter
 * to specify that this should be attached as a compound class.
 *
 * Usage example:
 *
 * ```scss
 * .mdc-foo {
 *   color: black;
 *
 *   @include mdc-theme-dark {
 *     color: white;
 *   }
 *
 *   &__bar {
 *     background: black;
 *
 *     @include mdc-theme-dark(".mdc-foo") {
 *       background: white;
 *     }
 *   }
 * }
 *
 * .mdc-foo--disabled {
 *   opacity: .38;
 *
 *   @include mdc-theme-dark(".mdc-foo", true) {
 *     opacity: .5;
 *   }
 * }
 * ```
 */
/* TODO(sgomes): Figure out what to do about desktop font sizes. */
/* TODO(sgomes): Figure out what to do about i18n and i18n font sizes. */
/* postcss-bem-linter: define snackbar */
.mdc-snackbar {
  display: flex;
  position: fixed;
  bottom: 0;
  left: 50%;
  align-items: center;
  justify-content: flex-start;
  padding-right: 24px;
  padding-left: 24px;
  transform: translate(0, 100%);
  transition: transform 0.25s 0ms cubic-bezier(0.4, 0, 1, 1);
  background-color: #323232;
  will-change: transform;
  pointer-events: none;
  /* stylelint-disable plugin/selector-bem-pattern */
  /* stylelint-enable plugin/selector-bem-pattern */ }
  @media (max-width: 599px) {
    .mdc-snackbar {
      left: 0;
      width: calc(100% - 48px); } }
  @media (min-width: 600px) {
    .mdc-snackbar {
      min-width: 288px;
      max-width: 568px;
      transform: translate(-50%, 100%);
      border-radius: 2px; } }
  .mdc-snackbar--active {
    transform: translate(0, 0);
    pointer-events: auto;
    transition: transform 0.25s 0ms cubic-bezier(0, 0, 0.2, 1); }
    @media (min-width: 600px) {
      .mdc-snackbar--active {
        transform: translate(-50%, 0); } }
  .mdc-snackbar--action-on-bottom {
    flex-direction: column; }
  .mdc-snackbar--action-on-bottom .mdc-snackbar__text {
    margin-right: inherit; }
  .mdc-snackbar--action-on-bottom .mdc-snackbar__action-wrapper {
    flex-direction: column;
    justify-content: flex-start;
    margin-top: -12px;
    margin-bottom: 8px;
    margin-left: auto;
    margin-right: 0; }
    [dir="rtl"] .mdc-snackbar--action-on-bottom .mdc-snackbar__action-wrapper, .mdc-snackbar--action-on-bottom .mdc-snackbar__action-wrapper[dir="rtl"] {
      margin-left: 0;
      margin-right: auto; }
  .mdc-snackbar__text {
    font-family: Roboto, sans-serif;
    -moz-osx-font-smoothing: grayscale;
    -webkit-font-smoothing: antialiased;
    font-size: 0.875rem;
    font-weight: 400;
    letter-spacing: 0.04em;
    line-height: 1.25rem;
    margin-left: 0;
    margin-right: auto;
    display: flex;
    align-items: center;
    height: 48px;
    transition: opacity 0.3s 0ms cubic-bezier(0.4, 0, 1, 1);
    color: white;
    opacity: 0; }
    [dir="rtl"] .mdc-snackbar .mdc-snackbar__text,
    .mdc-snackbar[dir="rtl"] .mdc-snackbar__text {
      margin-left: auto;
      margin-right: 0; }
  .mdc-snackbar--multiline .mdc-snackbar__text {
    height: 80px; }
  .mdc-snackbar--multiline.mdc-snackbar--action-on-bottom .mdc-snackbar__text {
    margin: 0; }
  .mdc-snackbar__action-button {
    color: #ff4081;
    color: var(--mdc-theme-accent, #ff4081);
    margin-left: 0;
    margin-right: -16px;
    min-width: auto;
    height: inherit;
    transition: opacity 0.3s 0ms cubic-bezier(0.4, 0, 1, 1);
    opacity: 0;
    visibility: hidden; }
    [dir="rtl"] .mdc-snackbar .mdc-snackbar__action-button,
    .mdc-snackbar[dir="rtl"] .mdc-snackbar__action-button {
      margin-left: -16px;
      margin-right: 0; }
    .mdc-snackbar__action-button::-moz-focus-inner {
      border: 0; }
    .mdc-snackbar__action-button:not([aria-hidden]) {
      visibility: inherit; }
  .mdc-snackbar--active .mdc-snackbar__text,
  .mdc-snackbar--active .mdc-snackbar__action-button:not([aria-hidden]) {
    transition: opacity 0.3s 0ms cubic-bezier(0.4, 0, 1, 1);
    opacity: 1; }

/* postcss-bem-linter: end */


text:
@interface XDPMFetchRequest (UIExtension)
- (id)valueForUndefinedKey:(id)arg1;
@end


text:
> {%= description %}

Based on [this tweet](https://twitter.com/dmosher/status/598172559650082816) with a version for web browser consoles.

{%= include("install-npm", {save: true}) %}

## Usage

```js
require('{%= name %}')(console);
```

## API
<!-- add a path or glob pattern for files with code comments to use for docs  -->
{%= apidocs("index.js") %}

## Running tests
{%= include("tests") %}

## Contributing
{%= include("contributing") %}

## Author
{%= include("author") %}

## License
{%= copyright() %}
{%= license() %}

***

{%= include("footer") %}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace WinLIRC.Configuration.Editor
{
    /// <summary>
    /// WinLIRC.NET configuration editor user interface
    /// </summary>
    public partial class ConfigurationBuilder : Form
    {
        /// <summary>
        /// List of WinLIRC.NET configurations
        /// </summary>
        private List<irconfig> _config;

        /// <summary>
        /// Source of WinLIRC configuration
        /// </summary>
        private ConfigurationSource _file;

        /// <summary>
        /// Initializes WinLIRC.NET configuration editor user interface
        /// </summary>
        public ConfigurationBuilder()
        {
            try
            {
                InitializeComponent();

                _file = new ConfigurationSource();
            }
            catch (Exception e)
            {
                Program.HandleException(e);
            }
        }

        /// <summary>
        /// Handler to save WinLIRC.NET XML formatted configuration file
        /// </summary>
        /// <param name="sender">Object which raised the event</param>
        /// <param name="e">Event arguments</param>
        private void Save(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog d = new SaveFileDialog();
                d.AddExtension = true;
                d.CheckFileExists = false;
                d.CheckPathExists = true;
                d.RestoreDirectory = true;
                d.Title = "Select XML WinLIRC configuration file to save";
                d.ValidateNames = true;
                d.Filter = "XML Files|*.xml";
                d.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                if (d.ShowDialog() == DialogResult.OK)
                {
                    Invalidate();

                    if (_file != null && _config != null)
                    {
                        _file.Write(new FileInfo(d.FileName), _config);

                        MessageBox.Show("Operation successfully completed!");
                    }
                }
            }
            catch (Exception err)
            {
                Program.HandleException(err);
            }
        }

        /// <summary>
        /// Handler to handle when WinLIRC.NET configuration object is changed in the user interface
        /// </summary>
        /// <param name="sender">Object which raised the event</param>
        /// <param name="e">Event arguments</param>
        private void OnIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (_config != null && _config[cboIndex.SelectedIndex] != null)
                    gridConfig.SelectedObject = _config[cboIndex.SelectedIndex];
            }
            catch (Exception err)
            {
                Program.HandleException(err);
            }
        }

        /// <summary>
        /// Handler to read WinLIRC native configuration
        /// </summary>
        /// <param name="sender">Object which raised the event</param>
        /// <param name="e">Event arguments</param>
        private void OnNativeConfigRead(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog d = new OpenFileDialog();
                d.AddExtension = true;
                d.CheckFileExists = true;
                d.CheckPathExists = true;
                d.Multiselect = false;
                d.RestoreDirectory = true;
                d.Title = "Select native WinLIRC configuration file to open";
                d.ValidateNames = true;
                d.Filter = "All Files|*.*";
                d.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                if (d.ShowDialog() == DialogResult.OK)
                {
                    Invalidate();

                    if (_file != null)
                    {
                        _config = _file.ReadConfig(new FileInfo(d.FileName));

                        if (_config != null && _config.Count > 0)
                        {
                            foreach (irconfig c in _config)
                                cboIndex.Items.Add(c.name);

                            cboIndex.SelectedIndex = 0;
                        }
                    }
                }
            }
            catch (Exception err)
            {
                Program.HandleException(err);
            }
        }

        /// <summary>
        /// Handler to read WinLIRC.NET XML formatted configuration
        /// </summary>
        /// <param name="sender">Object which raised the event</param>
        /// <param name="e">Event arguments</param>
        private void OnXmlConfigRead(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog d = new OpenFileDialog();
                d.AddExtension = true;
                d.CheckFileExists = true;
                d.CheckPathExists = true;
                d.Multiselect = false;
                d.RestoreDirectory = true;
                d.Title = "Select XML WinLIRC configuration file to open";
                d.ValidateNames = true;
                d.Filter = "All Files|*.*";
                d.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                if (d.ShowDialog() == DialogResult.OK)
                {
                    Invalidate();

                    if (_file != null)
                    {
                        _config = _file.ReadXml(new FileInfo(d.FileName));

                        if (_config != null && _config.Count > 0)
                        {
                            foreach (irconfig c in _config)
                                cboIndex.Items.Add(c.name);

                            cboIndex.SelectedIndex = 0;
                        }
                    }
                }
            }
            catch (Exception err)
            {
                Program.HandleException(err);
            }
        }
    }
}


text:
if [[ $# -lt 1 ]]
then
    echo "Usage: nprocess"
    exit -1
fi

rm -rf *.model
k=$1

# run linear model, the program will automatically split the inputs
../../tracker/rabit_demo.py -n $k linear.rabit ../data/agaricus.txt.train reg_L1=1

./linear.rabit ../data/agaricus.txt.test task=pred model_in=final.model


text:
class Stream < ActiveRecord::Migration
  def change
    create_table :droom_scraps do |t|
      t.string :name
      t.text :body
      t.attachment :image
      t.integer :image_offset_top
      t.integer :image_offset_left
      t.integer :image_scale_width
      t.integer :image_scale_height
      t.integer :created_by_id
      t.string :scraptype
      t.string :note
      t.timestamps
    end
  end
end


text:
var io = require('socket.io').listen(12345);
var mgmt = io.of('/management')
var monitor = io.of('/monitor')

var monitors = []
var mgmtSockets = []

registerMonitorAtMgmt = function(monitorSocket, mgmtSocket) {
  mgmtSocket.emit('monitor_connection', monitorSocket.id)
};

monitor.on('connection', function (socket) {
  monitors.push(socket)

  socket.on('disconnect', function() {
    monitors.splice(monitors.indexOf(this), 1)

    for (var i = 0; i < mgmtSockets.length; i++) {
      mgmtSockets[i].emit('monitor_disconnection', this.id)
    }
  })

  socket.emit('monitor_id', socket.id)

  for (var i = 0; i < mgmtSockets.length; i++) {
    registerMonitorAtMgmt(socket, mgmtSockets[i])
  }
});

mgmt.on('connection', function(socket) {
  mgmtSockets.push(socket)

  socket.on('disconnect', function() {
    mgmtSockets.splice(mgmtSockets.indexOf(this), 1)
  })

  socket.on('command', function(data) {
    for (var i = 0; i < monitors.length; i++) {
      var socket = monitors[i]
      socket.emit('command', data)
    }
  })

  for (var i = 0; i < monitors.length; i++) {
    registerMonitorAtMgmt(monitors[i], socket)
  }
})


text:
/*

Adel Abdalllah
Updated April 5, 2017

*/

SELECT ObjectType,InstanceName,AttributeName, UnitNameCV, InstanceName,MasterNetworkName,ScenarioName, AttributeDataTypeCV,SeasonName,SeasonValue,Mapping.MappingID
FROM Attributes

-- Join the Attributes to get their Object Types
Left JOIN  ObjectTypes
ON "ObjectTypes"."ObjectTypeID"="Attributes"."ObjectTypeID"

-- Join the Attributes to get their Mapping
LEFT JOIN Mapping
ON Mapping.AttributeID= Attributes.AttributeID

-- Join the Mapping to get their Instances
LEFT JOIN Instances
ON Instances.InstanceID= Mapping.InstanceID

-- Join the Mappings to get their ScenarioMappings
LEFT JOIN ScenarioMapping
ON ScenarioMapping.MappingID= Mapping.MappingID

-- Join the ScenarioMappings to get their Scenarios
LEFT JOIN Scenarios
ON Scenarios.ScenarioID= ScenarioMapping.ScenarioID

-- Join the Scenarios to get their MasterNetworks
LEFT JOIN MasterNetworks
ON MasterNetworks.MasterNetworkID= Scenarios.MasterNetworkID

-- Join the Mappings to get their DataValuesMappers
LEFT JOIN DataValuesMapper
ON DataValuesMapper.DataValuesMapperID = Mapping.DataValuesMapperID

-- Join the DataValuesMapper to get their SeasonalParameters
LEFT JOIN SeasonalParameters
ON SeasonalParameters.DataValuesMapperID = DataValuesMapper.DataValuesMapperID

WHERE AttributeDataTypeCV='SeasonalParameter' AND InstanceName='Node 2.02' AND AttributeName='Net Evaporation - inches'  AND ScenarioName='Bear Dry Year Model'
-- AND InstanceName='Hyrum Reservoir'

--'Net Evaporation'

--'Hyrum Reservoir'
--AND ScenarioName='BaseCaseLower'


text:
[class^="icon-"],
[class*=" icon-"] {
  font-family: 'arrow';
  font-style: normal;
  font-weight: normal;
/* fix buttons height */
  line-height: 1em;
/* you can be more comfortable with increased icons size */
/* font-size: 120%; */
}

.icon-mail { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '✉ '); }
.icon-left-circled { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }
.icon-right-circled { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }
.icon-up-circled { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }
.icon-down-circled { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }


text:
<?php
namespace psesd\serverReporter;

class Provider
{
	protected $config;

	public function __construct($config = [])
	{
		$this->config = $config;
	}
	public function provide()
	{
		header("Content-type: application/json");
		$data = $this->getData(false);
		if (!$data) {
			return false;
		}
		echo json_encode($data);
	}

	public function log($message)
	{
		$logFile = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'runtime' . DIRECTORY_SEPARATOR . 'provider.log';
		$message = date("F d, Y G:i:s") .': ' . $message . PHP_EOL;
		file_put_contents($logFile, $message, FILE_APPEND);
	}

	public function push()
	{
		if (!isset($this->config['push'])) {
			return false;
		}
		$errors = false;
		$data = $this->getData(true);
		if (!$data) {
			$this->log("Push failed because the data was stale");
			return false;
		}
		foreach ($this->config['push'] as $push) {
			$headers = ['Content-Type: application/x-www-form-urlencoded'];
			if (!empty($push['key'])) {
				$headers[] = 'X-Api-Key: ' . $push['key'];
			}
			$attemptsLeft = 3;
			$success = false;
			while (!$success && $attemptsLeft > 0) {
				echo "Attempting to send...\n";
				$attemptsLeft--;
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $push['url']);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
				curl_setopt($ch, CURLOPT_TIMEOUT, 30);
				//execute post
				$result = $rawResult = curl_exec($ch);
				if (substr($result, 0, 1) === '{' && ($result = json_decode($result, true)) && !empty($result['status']) && $result['status'] === 'accepted') {
					// $this->log("Push to {$push['url']} succeeded");
					$success = true;
					break;
				} else {
					sleep(5);
				}
				//close connection
				curl_close($ch);
			}
			if (!$success) {
				$this->log("Push to {$push['url']} failed ({$rawResult})");
				$errors = true;
			}
		}
		return !$errors;
	}

	public function getLocalSensorData()
	{
		$sensors = [];
		$sensors['disk-space-C'] = $this->getDiskSpaceSensor('C');
		$sensors['disk-space-D'] = $this->getDiskSpaceSensor('D');
		return $sensors;
	}

	protected function getDiskSpaceSensor($drive)
	{
		$sensor = [
			'class' => 'psesd\sensors\local\DynamicData',
			'id' => 'disk-space-' . $drive,
			'name' => 'Free Disk Space on ' . $drive,
			'dataValuePostfix' => '%'
		];
		$payload = [];
		$totalSpace = disk_total_space($drive .':');
		$freeSpace = disk_free_space($drive .':');
		$freePercent = ($freeSpace/$totalSpace)*100;
		if ($freePercent < 15) {
			$payload['state'] = 'low';
		} else {
			$payload['state'] = 'normal';
		}
		// $payload['total'] = $totalSpace;
		// $payload['free'] = $freeSpace;
		$payload['dataValue'] = round($freePercent, 1);
		$sensor['payload'] = $payload;
		return $sensor;
	}

	public function getData($isPush = false)
	{
		$data = ['timestamp' => time(), 'earliestNextCheck' => time(), 'provider' => null];
		$data['earliestNextCheck'] = time() + 60;
		if ($isPush) {
			$providerClass = 'psesd\sensors\providers\PushProvider';
		} else {
			$providerClass = 'psesd\sensors\providers\PullProvider';
		}
		$data['provider'] = [
			'class' => $providerClass,
			'id' => $this->config['id'] .'',
			'name' => $this->config['name'],
			'meta' => [],
			'servers' => []
		];

		$data['provider']['servers']['self'] = [
			'class' => 'psesd\sensors\servers\WindowsServer',
			'id' => $this->config['id'],
			'name' => $this->config['name'],
			'meta' => [],
			'resources' => [],
			'services' => [],
			'sensors' => $this->getLocalSensorData()
		];
		$data['provider']['servers']['self']['meta']['PHP Version'] = phpversion();

		$data['provider']['servers']['self']['services']['db'] = [
			'class' => 'psesd\sensors\services\DatabaseService'
		];

		$filePath = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'serverInfo.json';
		if (file_exists($filePath)) {
			$info = json_decode(file_get_contents($filePath), true);
			$age = false;
			if (isset($info['ips'])) {
				foreach ($info['ips'] as $ip) {
					$data['provider']['servers']['self']['resources'][] = [
						'class' => 'psesd\sensors\resources\IP',
						'ip' => $ip
					];
				}
			}
			if (isset($info['timestamp'])) {
				$age = (time() - $info['timestamp']) / 60;
				if ($age > 60) {
					$age = false;
				}
			}
			if ($age === false) {
				return false;
			}
			if (!empty($info['databases'])) {
				foreach ($info['databases'] as $database) {
					$type = 'Database';
					$base = [];
					if (isset($this->config['databaseConfig'][$database['name']])) {
						$base = $this->config['databaseConfig'][$database['name']];
					}
					if (!empty($base['ignore'])) {
						continue;
					}
					if (isset($base['type'])) {
						$type = $base['type'];
						unset($base['type']);
					}
					$sensors = [];
					if (isset($database['lastBackup'])) {
						$sensor = [
							'class' => 'psesd\sensors\local\Dynamic',
							'id' => 'database-has-backup',
							'name' => 'Database Backup'
						];
						$payload = [];
						$lastBackupAge = false;
						if ($database['lastBackup'] !== false && file_exists($database['lastBackup'])) {
							$lastBackupAge = (time()-filemtime($database['lastBackup']))/60/60;
						}
						if ($lastBackupAge === false || $lastBackupAge > 25) {
							$payload['state'] = 'error';
						} else {
							$payload['state'] = 'normal';
						}
						$sensor['payload'] = $payload;
						$sensors['database-has-backup'] = $sensor;
					}
					$databaseConfig = array_merge([
						'class' => 'psesd\sensors\resources\\' . $type,
						'dbName' => $database['name'],
						'sensors' => $sensors
					], $base);
					$data['provider']['servers']['self']['resources'][] = $databaseConfig;
				}
			}
		}
		return $data;
	}
}
?>


text:
package com.guillaumedelente.android.contacts.common.database;

import android.database.AbstractCursor;
import android.database.CursorIndexOutOfBoundsException;

/**
 * A cursor that is empty.
 * <p>
 * If you want an empty cursor, this class is better than a MatrixCursor because it has less
 * overhead.
 */
final public class EmptyCursor extends AbstractCursor {

    private String[] mColumns;

    public EmptyCursor(String[] columns) {
        this.mColumns = columns;
    }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public String[] getColumnNames() {
        return mColumns;
    }

    @Override
    public String getString(int column) {
        throw cursorException();
    }

    @Override
    public short getShort(int column) {
        throw cursorException();
    }

    @Override
    public int getInt(int column) {
        throw cursorException();
    }

    @Override
    public long getLong(int column) {
        throw cursorException();
    }

    @Override
    public float getFloat(int column) {
        throw cursorException();
    }

    @Override
    public double getDouble(int column) {
        throw cursorException();
    }

    @Override
    public boolean isNull(int column) {
        throw cursorException();
    }

    private CursorIndexOutOfBoundsException cursorException() {
        return new CursorIndexOutOfBoundsException("Operation not permitted on an empty cursor.");
    }
}


text:
import {Pipe, PipeTransform} from '@angular/core';
import {DomSanitizer} from "@angular/platform-browser";

@Pipe({
  name: 'sanitizeHtml'
})
export class SanitizerPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) {
  }

  transform(value: any): any {
    return this.sanitizer.bypassSecurityTrustHtml(value);
  }

}


text:
package org.sourcepit.common.maven.testing;

import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.io.FileUtils;
import org.apache.maven.Maven;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.InvalidRepositoryException;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.filter.CumulativeScopeArtifactFilter;
import org.apache.maven.cli.event.ExecutionEventLogger;
import org.apache.maven.cli.transfer.BatchModeMavenTransferListener;
import org.apache.maven.eventspy.internal.EventSpyDispatcher;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.ExecutionEvent;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.execution.MavenExecutionRequestPopulationException;
import org.apache.maven.execution.MavenExecutionRequestPopulator;
import org.apache.maven.execution.MavenExecutionResult;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.lifecycle.LifecycleExecutionException;
import org.apache.maven.lifecycle.internal.LifecycleDependencyResolver;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.DefaultModelWriter;
import org.apache.maven.plugin.LegacySupport;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.settings.building.DefaultSettingsBuildingRequest;
import org.apache.maven.settings.building.SettingsBuilder;
import org.apache.maven.settings.building.SettingsBuildingRequest;
import org.apache.maven.settings.building.SettingsBuildingResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sourcepit.common.maven.core.MavenProjectUtils;

@Named
public class EmbeddedMaven {

   private static final Logger logger = LoggerFactory.getLogger(EmbeddedMaven.class);

   private final Maven maven;

   private final EventSpyDispatcher eventSpyDispatcher;

   private final LifecycleDependencyResolver resolver;

   private final MavenExecutionRequestPopulator executionRequestPopulator;

   private final SettingsBuilder settingsBuilder;

   private final LegacySupport buildContext;

   private final RepositorySystem repositorySystem;

   private File userHome, userSettings, localRepo, remoteRepo;

   @Inject
   public EmbeddedMaven(Maven maven, EventSpyDispatcher eventSpyDispatcher, LifecycleDependencyResolver resolver,
      MavenExecutionRequestPopulator executionRequestPopulator, SettingsBuilder settingsBuilder,
      LegacySupport buildContext, RepositorySystem repositorySystem) {
      this.maven = maven;
      this.eventSpyDispatcher = eventSpyDispatcher;
      this.resolver = resolver;
      this.executionRequestPopulator = executionRequestPopulator;
      this.settingsBuilder = settingsBuilder;
      this.buildContext = buildContext;
      this.repositorySystem = repositorySystem;
   }

   public void dispose() {
      eventSpyDispatcher.close();
   }

   public File getUserHome() {
      return userHome;
   }

   public void setUserHome(File userHome) {
      this.userHome = userHome;
   }

   public File getUserSettings() {
      return userSettings;
   }

   public void setUserSettings(File userSettings) {
      this.userSettings = userSettings;
   }

   public File getLocalRepo() {
      return localRepo;
   }

   public void setLocalRepo(File localRepo) {
      this.localRepo = localRepo;
   }

   public File getRemoteRepo() {
      return remoteRepo;
   }

   public void setRemoteRepo(File remoteRepo) {
      this.remoteRepo = remoteRepo;
   }

   public ArtifactRepository getLocalRepository() {
      try {
         return repositorySystem.createLocalRepository(getLocalRepo());
      }
      catch (InvalidRepositoryException e) {
         throw new IllegalStateException(e);
      }
   }

   public ArtifactRepository getRemoteRepository() {
      final File remoteRepo = getRemoteRepo();
      final String id = remoteRepo.getName();
      final String url;
      try {
         url = remoteRepo.toURI().toURL().toString();
      }
      catch (MalformedURLException e) {
         throw new IllegalStateException(e);
      }
      return repositorySystem.createArtifactRepository(id, url, null, null, null);
   }

   public Artifact createProjectArtifact(Model pom) {
      return repositorySystem.createProjectArtifact(pom.getGroupId(), pom.getArtifactId(), pom.getVersion());
   }

   public Artifact createArtifact(Model pom) {
      return repositorySystem.createArtifact(pom.getGroupId(), pom.getArtifactId(), pom.getVersion(),
         pom.getPackaging());
   }

   public MavenExecutionRequest newMavenExecutionRequest(File pom) throws Exception {
      return newMavenExecutionRequest(pom, "validate");
   }

   public MavenExecutionRequest newMavenExecutionRequest(File pom, String... goals) throws Exception {
      return newMavenExecutionRequest(pom, newSystemProperties(), null, goals);
   }

   public MavenExecutionRequest newMavenExecutionRequest(File pom, Properties systemProperties,
      Properties userProperties, String... goals) throws Exception {
      final MavenExecutionRequest request = new DefaultMavenExecutionRequest();
      if (pom != null) {
         request.setBaseDirectory(pom.getParentFile());
         request.setPom(pom);
      }
      request.setSystemProperties(systemProperties == null ? new Properties() : systemProperties);
      request.setUserProperties(userProperties == null ? new Properties() : userProperties);

      request.setUserSettingsFile(userSettings);

      if (goals != null) {
         request.setGoals(Arrays.asList(goals));
      }

      populateDefaults(request);

      return request;
   }

   public void populateDefaults(final MavenExecutionRequest request)
      throws Exception, MavenExecutionRequestPopulationException {
      request.setExecutionListener(eventSpyDispatcher.chainListener(new ExecutionEventLogger(logger)));
      request.setTransferListener(new BatchModeMavenTransferListener(System.out));

      final SettingsBuildingResult settingsResult = buildSettings(null, request.getUserSettingsFile(),
         request.getSystemProperties(), request.getUserProperties());
      executionRequestPopulator.populateFromSettings(request, settingsResult.getEffectiveSettings());

      if (localRepo != null) {
         request.setLocalRepositoryPath(localRepo);
      }

      if (remoteRepo != null) {
         request.getRemoteRepositories().add(getRemoteRepository());
      }

      executionRequestPopulator.populateDefaults(request);
   }

   public Properties newSystemProperties() {
      Properties properties = new Properties();
      properties.putAll(System.getProperties());
      if (userHome != null && userHome.exists()) {
         properties.put("user.home", userHome.getAbsolutePath());
      }
      return properties;
   }

   public SettingsBuildingResult buildSettings(File globalSettingsFile, File userSettingsFile,
      Properties systemProperties, Properties userProperties) throws Exception {
      final SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
      settingsRequest.setGlobalSettingsFile(globalSettingsFile);
      settingsRequest.setUserSettingsFile(userSettingsFile);
      settingsRequest.setSystemProperties(systemProperties);
      settingsRequest.setUserProperties(userProperties);

      return settingsBuilder.build(settingsRequest);
   }

   public MavenExecutionResult2 buildStubProject(File projectDir) {
      final Model pom = new Model();
      pom.setModelVersion("4.0.0");
      pom.setGroupId("org.sourcepit");
      pom.setArtifactId("stub-project");
      pom.setVersion("1");

      try {
         final File projectPom = File.createTempFile("pom", ".xml", projectDir);
         try {
            new DefaultModelWriter().write(projectPom, null, pom);
            return buildProject(projectPom);
         }
         finally {
            FileUtils.forceDelete(projectPom);
         }
      }
      catch (Exception e) {
         throw new IllegalStateException(e);
      }
   }

   public MavenExecutionResult2 buildProject(File pom) throws Exception {
      return buildProject(pom, null, false);
   }

   public MavenExecutionResult2 buildProject(File pom, boolean resolveDependencies) throws Exception {
      return buildProject(pom, null, resolveDependencies);
   }

   public MavenExecutionResult2 buildProject(File pom, Properties userProperties, boolean resolveDependencies)
      throws Exception {
      final MavenExecutionRequest request = newMavenExecutionRequest(pom, newSystemProperties(), userProperties,
         "compile");
      request.getProjectBuildingRequest().setProcessPlugins(false);
      request.getProjectBuildingRequest().setResolveDependencies(resolveDependencies);

      final MavenSession[] session = new MavenSession[1];
      request.setExecutionListener(new ChainedExecutionListener(request.getExecutionListener()) {
         @Override
         public void sessionStarted(ExecutionEvent event) {
            super.sessionStarted(event);
            session[0] = event.getSession();
            throw new IllegalStateException();
         }
      });

      final MavenExecutionResult2 tmpResult = execute(request);
      if (session[0] == null) {
         if (tmpResult.hasExceptions()) {
            throw new IllegalStateException(tmpResult.getExceptions().get(0));
         }
      }

      final MavenExecutionResult2 result = new MavenExecutionResult2Impl(session[0], session[0].getResult());
      if (request.getProjectBuildingRequest().isResolveDependencies()) {
         Set<Artifact> projectArtifacts = new HashSet<Artifact>();

         for (MavenProject mavenProject : result.getTopologicallySortedProjects()) {
            File artifactFile = MavenProjectUtils.getOutputDir(mavenProject);
            if (artifactFile == null) {
               artifactFile = mavenProject.getBasedir();
            }
            mavenProject.getArtifact().setFile(artifactFile);
            mavenProject.getArtifact().setResolved(true);

            projectArtifacts.add(mavenProject.getArtifact());

            mavenProject.addLifecyclePhase("clean");
            mavenProject.addLifecyclePhase("process-resources");
            mavenProject.addLifecyclePhase("compile");

            ArrayList<String> scopesToCollect = new ArrayList<String>();
            Collections.addAll(scopesToCollect, "system", "compile", "provided", "runtime", "test");

            try {
               resolver.resolveProjectDependencies(mavenProject, scopesToCollect, scopesToCollect, result.getSession(),
                  true, Collections.<Artifact> emptySet());
            }
            catch (LifecycleExecutionException e) {
               result.addException(e);
            }

            mavenProject.setArtifactFilter(new CumulativeScopeArtifactFilter(scopesToCollect));
         }
      }
      if (result.hasExceptions()) {
         throw new IllegalStateException(result.getExceptions().get(0));
      }

      return result;
   }

   public MavenExecutionResult2 execute(MavenExecutionRequest request) {
      final MavenSession[] session = new MavenSession[1];
      request.setExecutionListener(new ChainedExecutionListener(request.getExecutionListener()) {
         @Override
         public void sessionStarted(ExecutionEvent event) {
            super.sessionStarted(event);
            session[0] = event.getSession();
         }
      });

      final MavenSession currentSession = buildContext.getSession();
      final MavenExecutionResult result;
      try {
         eventSpyDispatcher.onEvent(request);
         result = maven.execute(request);
         eventSpyDispatcher.onEvent(result);
      }
      finally {
         buildContext.setSession(currentSession);
      }

      return new MavenExecutionResult2Impl(session[0], result);
   }
}


text:
package org.psliwa.idea.composerJson.intellij.codeAssist.schema

import org.psliwa.idea.composerJson.ComposerBundle
import org.psliwa.idea.composerJson.intellij.codeAssist.InspectionTest

class SchemaQuickFixesTest extends InspectionTest {

  private val RequiredProperties =
    """
      |"name": "vendor/pkg",
      |"description": "desc",
    """.stripMargin

  override def setUp(): Unit = {
    super.setUp()

    myFixture.enableInspections(classOf[SchemaInspection])
  }

  private val RemoveEntryQuickFix = ComposerBundle.message("inspection.quickfix.removeEntry")
  private val RemoveQuotesQuickFix = ComposerBundle.message("inspection.quickfix.removeQuotes")
  private val CreatePropertyQuickFix = ComposerBundle.message("inspection.quickfix.createProperty", _: String)
  private val ShowValidValuesQuickFix = ComposerBundle.message("inspection.quickfix.chooseValidValue")

  def testRemoveQuotes_givenQuotedNumber_quotesShouldBeRemoved(): Unit = {
    checkQuickFix(RemoveQuotesQuickFix)(
      s"""
        |{
        |  $RequiredProperties
        |  "config": {
        |    "cache-files-ttl": "123"
        |  }
        |}
      """.stripMargin,
      s"""
        |{
        |  $RequiredProperties
        |  "config": {
        |    "cache-files-ttl": 123
        |  }
        |}
      """.stripMargin
    )
  }

  def testRemoveQuotes_givenQuotedString_quotesShouldNotBeRemoved(): Unit = {
    checkQuickFix(RemoveQuotesQuickFix, 0)(
      s"""
        |{
        |  $RequiredProperties
        |  "config": {
        |    "cache-files-ttl": "some invalid"
        |  }
        |}
      """.stripMargin,
      s"""
        |{
        |  $RequiredProperties
        |  "config": {
        |    "cache-files-ttl": "some invalid"
        |  }
        |}
      """.stripMargin
    )
  }

  def testRemoveEntry_givenUnsupportedProperty_itShouldBeRemoved(): Unit = {
    checkQuickFix(RemoveEntryQuickFix)(
      s"""
        |{
        |  $RequiredProperties
        |  "require": {},
        |  "authors": [
        |    {
        |      "unsupported": "value",
        |      "name": "psliwa"
        |    }
        |  ]
        |}
      """.stripMargin,
      s"""
        |{
        |  $RequiredProperties
        |  "require": {},
        |  "authors": [
        |    {
        |      "name": "psliwa"
        |    }
        |  ]
        |}
      """.stripMargin
    )
  }

  def testRemoveEntry_givenUnsupportedPropertyIsLastOne_commaAfterPreviousPropertyShouldBeRemoved(): Unit = {
    checkQuickFix(RemoveEntryQuickFix)(
      s"""
        |{
        |  $RequiredProperties
        |  "require": {},
        |  "unsupported": {
        |    "prop": "value"
        |  }
        |}
      """.stripMargin,
      s"""
        |{
        |  $RequiredProperties
        |  "require": {}
        |}
      """.stripMargin
    )
  }

  def testRemoveEntry_givenObjectProperty_givenPropertyIsNotLastOne_commaAfterPreviousPropertyShouldNotBeRemoved()
      : Unit = {
    checkQuickFix(RemoveEntryQuickFix)(
      s"""
        |{
        |  $RequiredProperties
        |  "require": {},
        |  "unsupported": {
        |    "prop": "value"
        |  },
        |  "require-dev": {}
        |}
      """.stripMargin,
      s"""
        |{
        |  $RequiredProperties
        |  "require": {},
        |  "require-dev": {}
        |}
      """.stripMargin
    )
  }

  def testRemoveProperty_givenStringProperty_givenPropertyIsNotLastOne_commaAfterPreviousPropertyShouldNotBeRemoved()
      : Unit = {
    checkQuickFix(RemoveEntryQuickFix)(
      s"""
        |{
        |  $RequiredProperties
        |  "require": {},
        |  "unsupported": "value",
        |  "require-dev": {}
        |}
      """.stripMargin,
      s"""
        |{
        |  $RequiredProperties
        |  "require": {},
        |  "require-dev": {}
        |}
      """.stripMargin
    )
  }

  def testRemoveProperty_givenAlreadyDefinedProperty_removeIt(): Unit = {
    checkQuickFix(RemoveEntryQuickFix)(
      s"""
         |{
         |  $RequiredProperties
          |  "require": {},
          |  "require": {}
          |}
      """.stripMargin,
      s"""
         |{
         |  $RequiredProperties
          |  "require": {}
          |}
      """.stripMargin
    )
  }

  //  TODO: Quick fix is not shown on top level, why?
  //  def testQuickFixForQuotedBooleans() = {
  //    checkQuickFix(
  //      s"""
  //        |{
  //        |  $RequiredProperties
  //        |  "prefer-stable": "true"
  //        |}
  //      """.stripMargin,
  //      s"""
  //        |{
  //        |  $RequiredProperties
  //        |  "prefer-stable": true
  //        |}
  //      """.stripMargin
  //    )
  //  }

  def testCreateProperty_propertyShouldBeCreated(): Unit = {
    checkQuickFix(CreatePropertyQuickFix("name"))(
      s"""
         |{
         |  $RequiredProperties
         |  "authors": [
         |    {<caret>
         |    }
         |  ]
         |}
      """.stripMargin,
      s"""
         |{
         |  $RequiredProperties
         |  "authors": [
         |    {
         |      "name": "<caret>"
         |    }
         |  ]
         |}
      """.stripMargin
    )
  }

  def testCreateProperty_thereAreSomePropertiesAlready_caretIsBeforeExistingProperty_propertyShouldBeCreatedBeforeExistingOne()
      : Unit = {
    checkQuickFix(CreatePropertyQuickFix("name"))(
      s"""
         |{
         |  $RequiredProperties
         |  "authors": [
         |    {<caret>
         |      "role": ""
         |    }
         |  ]
         |}
      """.stripMargin,
      s"""
         |{
         |  $RequiredProperties
         |  "authors": [
         |    {
         |      "name": "<caret>",
         |      "role": ""
         |    }
         |  ]
         |}
      """.stripMargin
    )
  }

  def testCreateProperty_thereAreSomePropertiesAlready_caretIsAfterExistingProperty_propertyShouldBeCreatedAfterExistingOne()
      : Unit = {
    checkQuickFix(CreatePropertyQuickFix("name"))(
      s"""
         |{
         |  $RequiredProperties
         |  "authors": [
         |    {
         |      "role": ""<caret>
         |    }
         |  ]
         |}
      """.stripMargin,
      s"""
         |{
         |  $RequiredProperties
         |  "authors": [
         |    {
         |      "role": "",
         |      "name": "<caret>"
         |    }
         |  ]
         |}
      """.stripMargin
    )
  }

  def testCreateProperty_thereAreSomePropertiesAlready_caretIsBetweenExistingProperties_propertyShouldBeCreatedBetweenExistingOne()
      : Unit = {
    checkQuickFix(CreatePropertyQuickFix("name"))(
      s"""
         |{
         |  $RequiredProperties
         |  "authors": [
         |    {
         |      "email": "",<caret>
         |      "role": ""
         |    }
         |  ]
         |}
      """.stripMargin,
      s"""
         |{
         |  $RequiredProperties
         |  "authors": [
         |    {
         |      "email": "",
         |      "name": "<caret>",
         |      "role": ""
         |    }
         |  ]
         |}
      """.stripMargin
    )
  }

  def testCreateProperty_thereAreSomePropertiesAlready_caretIsInsideFirstProperty_propertyShouldBeCreatedAfterThatProperty()
      : Unit = {
    checkQuickFix(CreatePropertyQuickFix("name"))(
      s"""
        |{
        |  $RequiredProperties
        |  "authors": [
        |    {
        |      "email<caret>": "",
        |      "role": ""
        |    }
        |  ]
        |}
      """.stripMargin,
      s"""
        |{
        |  $RequiredProperties
        |  "authors": [
        |    {
        |      "email": "",
        |      "name": "<caret>",
        |      "role": ""
        |    }
        |  ]
        |}
      """.stripMargin
    )
  }

  def testCreateProperty_noneNewLineGiven_newLinesShouldBeFixed(): Unit = {
    checkQuickFix(CreatePropertyQuickFix("name"))(
      s"""
         |{
         |  $RequiredProperties
         |  "authors": [
         |    {<caret>}
         |  ]
         |}
      """.stripMargin,
      s"""
         |{
         |  $RequiredProperties
         |  "authors": [
         |    {
         |      "name": "<caret>"
         |    }
         |  ]
         |}
      """.stripMargin
    )
  }

  def testFixEnum_valueShouldBeSelected(): Unit = {
    checkQuickFix(ShowValidValuesQuickFix)(
      s"""
        |{
        |  $RequiredProperties
        |  "minimum-stability": "invalid<caret>"
        |}
      """.stripMargin,
      s"""
        |{
        |  $RequiredProperties
        |  "minimum-stability": "<selection>invalid</selection>"
        |}
      """.stripMargin
    )
  }
}


text:
Login

    <form name="login" method="post" data-ng-submit="doLogin()">
        Usuario
        <input type="text" name="userName" data-ng-model="user.username" required/>
        Contraseña
        <input type="password" name="userPassword" data-ng-model="user.secretword" required/>
        <input type="submit" value="Entrar" class="btn btn-default" />
    </form>
    {{message}}


text:
begin
  require 'rack/session/memcache'
  require 'rack/mock'
  require 'thread'

  describe Rack::Session::Memcache do
    session_key = Rack::Session::Memcache::DEFAULT_OPTIONS[:key]
    session_match = /#{session_key}=([0-9a-fA-F]+);/
    incrementor = lambda do |env|
      env["rack.session"]["counter"] ||= 0
      env["rack.session"]["counter"] += 1
      Rack::Response.new(env["rack.session"].inspect).to_a
    end
    drop_session = proc do |env|
      env['rack.session.options'][:drop] = true
      incrementor.call(env)
    end
    renew_session = proc do |env|
      env['rack.session.options'][:renew] = true
      incrementor.call(env)
    end
    defer_session = proc do |env|
      env['rack.session.options'][:defer] = true
      incrementor.call(env)
    end

    it "faults on no connection" do
      if RUBY_VERSION < "1.9"
        lambda{
          Rack::Session::Memcache.new(incrementor, :memcache_server => 'nosuchserver')
        }.should.raise
      else
        lambda{
          Rack::Session::Memcache.new(incrementor, :memcache_server => 'nosuchserver')
        }.should.raise ArgumentError
      end
    end

    it "connects to existing server" do
      test_pool = MemCache.new(incrementor, :namespace => 'test:rack:session')
      test_pool.namespace.should.equal 'test:rack:session'
    end

    it "passes options to MemCache" do
      pool = Rack::Session::Memcache.new(incrementor, :namespace => 'test:rack:session')
      pool.pool.namespace.should.equal 'test:rack:session'
    end

    it "creates a new cookie" do
      pool = Rack::Session::Memcache.new(incrementor)
      res = Rack::MockRequest.new(pool).get("/")
      res["Set-Cookie"].should.include("#{session_key}=")
      res.body.should.equal '{"counter"=>1}'
    end

    it "determines session from a cookie" do
      pool = Rack::Session::Memcache.new(incrementor)
      req = Rack::MockRequest.new(pool)
      res = req.get("/")
      cookie = res["Set-Cookie"]
      req.get("/", "HTTP_COOKIE" => cookie).
        body.should.equal '{"counter"=>2}'
      req.get("/", "HTTP_COOKIE" => cookie).
        body.should.equal '{"counter"=>3}'
    end

    it "survives nonexistant cookies" do
      bad_cookie = "rack.session=blarghfasel"
      pool = Rack::Session::Memcache.new(incrementor)
      res = Rack::MockRequest.new(pool).
        get("/", "HTTP_COOKIE" => bad_cookie)
      res.body.should.equal '{"counter"=>1}'
      cookie = res["Set-Cookie"][session_match]
      cookie.should.not.match(/#{bad_cookie}/)
    end

    it "maintains freshness" do
      pool = Rack::Session::Memcache.new(incrementor, :expire_after => 3)
      res = Rack::MockRequest.new(pool).get('/')
      res.body.should.include '"counter"=>1'
      cookie = res["Set-Cookie"]
      res = Rack::MockRequest.new(pool).get('/', "HTTP_COOKIE" => cookie)
      res["Set-Cookie"].should.equal cookie
      res.body.should.include '"counter"=>2'
      puts 'Sleeping to expire session' if $DEBUG
      sleep 4
      res = Rack::MockRequest.new(pool).get('/', "HTTP_COOKIE" => cookie)
      res["Set-Cookie"].should.not.equal cookie
      res.body.should.include '"counter"=>1'
    end

    it "deletes cookies with :drop option" do
      pool = Rack::Session::Memcache.new(incrementor)
      req = Rack::MockRequest.new(pool)
      drop = Rack::Utils::Context.new(pool, drop_session)
      dreq = Rack::MockRequest.new(drop)

      res0 = req.get("/")
      session = (cookie = res0["Set-Cookie"])[session_match]
      res0.body.should.equal '{"counter"=>1}'

      res1 = req.get("/", "HTTP_COOKIE" => cookie)
      res1["Set-Cookie"][session_match].should.equal session
      res1.body.should.equal '{"counter"=>2}'

      res2 = dreq.get("/", "HTTP_COOKIE" => cookie)
      res2["Set-Cookie"].should.equal nil
      res2.body.should.equal '{"counter"=>3}'

      res3 = req.get("/", "HTTP_COOKIE" => cookie)
      res3["Set-Cookie"][session_match].should.not.equal session
      res3.body.should.equal '{"counter"=>1}'
    end

    it "provides new session id with :renew option" do
      pool = Rack::Session::Memcache.new(incrementor)
      req = Rack::MockRequest.new(pool)
      renew = Rack::Utils::Context.new(pool, renew_session)
      rreq = Rack::MockRequest.new(renew)

      res0 = req.get("/")
      session = (cookie = res0["Set-Cookie"])[session_match]
      res0.body.should.equal '{"counter"=>1}'

      res1 = req.get("/", "HTTP_COOKIE" => cookie)
      res1["Set-Cookie"][session_match].should.equal session
      res1.body.should.equal '{"counter"=>2}'

      res2 = rreq.get("/", "HTTP_COOKIE" => cookie)
      new_cookie = res2["Set-Cookie"]
      new_session = new_cookie[session_match]
      new_session.should.not.equal session
      res2.body.should.equal '{"counter"=>3}'

      res3 = req.get("/", "HTTP_COOKIE" => new_cookie)
      res3["Set-Cookie"][session_match].should.equal new_session
      res3.body.should.equal '{"counter"=>4}'
    end

    it "omits cookie with :defer option" do
      pool = Rack::Session::Memcache.new(incrementor)
      req = Rack::MockRequest.new(pool)
      defer = Rack::Utils::Context.new(pool, defer_session)
      dreq = Rack::MockRequest.new(defer)

      res0 = req.get("/")
      session = (cookie = res0["Set-Cookie"])[session_match]
      res0.body.should.equal '{"counter"=>1}'

      res1 = req.get("/", "HTTP_COOKIE" => cookie)
      res1["Set-Cookie"][session_match].should.equal session
      res1.body.should.equal '{"counter"=>2}'

      res2 = dreq.get("/", "HTTP_COOKIE" => cookie)
      res2["Set-Cookie"].should.equal nil
      res2.body.should.equal '{"counter"=>3}'

      res3 = req.get("/", "HTTP_COOKIE" => cookie)
      res3["Set-Cookie"][session_match].should.equal session
      res3.body.should.equal '{"counter"=>4}'
    end

    it "updates deep hashes correctly" do
      store = nil
      hash_check = proc do |env|
        session = env['rack.session']
        unless session.include? 'test'
          session.update :a => :b, :c => { :d => :e },
            :f => { :g => { :h => :i} }, 'test' => true
        else
          session[:f][:g][:h] = :j
        end
        [200, {}, session.inspect]
      end
      pool = Rack::Session::Memcache.new(hash_check)
      req = Rack::MockRequest.new(pool)

      res0 = req.get("/")
      session_id = (cookie = res0["Set-Cookie"])[session_match, 1]
      ses0 = pool.pool.get(session_id, true)

      res1 = req.get("/", "HTTP_COOKIE" => cookie)
      ses1 = pool.pool.get(session_id, true)

      ses1.should.not.equal ses0
    end

    # anyone know how to do this better?
    it "cleanly merges sessions when multithreaded" do
      unless $DEBUG
        1.should.equal 1 # fake assertion to appease the mighty bacon
        next
      end
      warn 'Running multithread test for Session::Memcache'
      pool = Rack::Session::Memcache.new(incrementor)
      req = Rack::MockRequest.new(pool)

      res = req.get('/')
      res.body.should.equal '{"counter"=>1}'
      cookie = res["Set-Cookie"]
      session_id = cookie[session_match, 1]

      delta_incrementor = lambda do |env|
        # emulate disconjoinment of threading
        env['rack.session'] = env['rack.session'].dup
        Thread.stop
        env['rack.session'][(Time.now.usec*rand).to_i] = true
        incrementor.call(env)
      end
      tses = Rack::Utils::Context.new pool, delta_incrementor
      treq = Rack::MockRequest.new(tses)
      tnum = rand(7).to_i+5
      r = Array.new(tnum) do
        Thread.new(treq) do |run|
          run.get('/', "HTTP_COOKIE" => cookie, 'rack.multithread' => true)
        end
      end.reverse.map{|t| t.run.join.value }
      r.each do |request|
        request['Set-Cookie'].should.equal cookie
        request.body.should.include '"counter"=>2'
      end

      session = pool.pool.get(session_id)
      session.size.should.equal tnum+1 # counter
      session['counter'].should.equal 2 # meeeh

      tnum = rand(7).to_i+5
      r = Array.new(tnum) do |i|
        delta_time = proc do |env|
          env['rack.session'][i]  = Time.now
          Thread.stop
          env['rack.session']     = env['rack.session'].dup
          env['rack.session'][i] -= Time.now
          incrementor.call(env)
        end
        app = Rack::Utils::Context.new pool, time_delta
        req = Rack::MockRequest.new app
        Thread.new(req) do |run|
          run.get('/', "HTTP_COOKIE" => cookie, 'rack.multithread' => true)
        end
      end.reverse.map{|t| t.run.join.value }
      r.each do |request|
        request['Set-Cookie'].should.equal cookie
        request.body.should.include '"counter"=>3'
      end

      session = pool.pool.get(session_id)
      session.size.should.be tnum+1
      session['counter'].should.be 3

      drop_counter = proc do |env|
        env['rack.session'].delete 'counter'
        env['rack.session']['foo'] = 'bar'
        [200, {'Content-Type'=>'text/plain'}, env['rack.session'].inspect]
      end
      tses = Rack::Utils::Context.new pool, drop_counter
      treq = Rack::MockRequest.new(tses)
      tnum = rand(7).to_i+5
      r = Array.new(tnum) do
        Thread.new(treq) do |run|
          run.get('/', "HTTP_COOKIE" => cookie, 'rack.multithread' => true)
        end
      end.reverse.map{|t| t.run.join.value }
      r.each do |request|
        request['Set-Cookie'].should.equal cookie
        request.body.should.include '"foo"=>"bar"'
      end

      session = pool.pool.get(session_id)
      session.size.should.be r.size+1
      session['counter'].should.be.nil?
      session['foo'].should.equal 'bar'
    end
  end
rescue RuntimeError
  $stderr.puts "Skipping Rack::Session::Memcache tests. Start memcached and try again."
rescue LoadError
  $stderr.puts "Skipping Rack::Session::Memcache tests (Memcache is required). `gem install memcache-client` and try again."
end


text:
var React = require('react');
var Alert = require('react-bootstrap').Alert;
var ButtonToolbar = require('react-bootstrap').ButtonToolbar;
var Button = require('react-bootstrap').Button;
var ButtonGroup = require('react-bootstrap').ButtonGroup;
var DropdownButton = require('react-bootstrap').DropdownButton;
var MenuItem = require('react-bootstrap').MenuItem;
var SplitButton = require('react-bootstrap').SplitButton;
var Panel = require('react-bootstrap').Panel;
var ListGroup = require('react-bootstrap').ListGroup;
var ListGroupItem = require('react-bootstrap').ListGroupItem;
var PanelGroup = require('react-bootstrap').PanelGroup;
var ModalTrigger = require('react-bootstrap').ModalTrigger;
var Modal = require('react-bootstrap').Modal;
var OverlayTrigger = require('react-bootstrap').OverlayTrigger;
var Tooltip = require('react-bootstrap').Tooltip;
var Popover = require('react-bootstrap').Popover;
var ProgressBar = require('react-bootstrap').ProgressBar;
var TabbedArea = require('react-bootstrap').TabbedArea;
var TabPane = require('react-bootstrap').TabPane;
var Grid = require('react-bootstrap').Grid;
var Row = require('react-bootstrap').Row;
var Col = require('react-bootstrap').Col;
var Label = require('react-bootstrap').Label;
var Badge = require('react-bootstrap').Badge;

var MyModal = React.createClass({
  render:function() {
    return (
      <Modal {...this.props} bsStyle='primary' title='Modal heading' animation={false}>

        	111

          <Button onClick={this.props.onRequestHide}>Close</Button>

      </Modal>
    );
  }
});

var dashboard = React.createClass({
	getInitialState: function() {
		return {
			activeKey: "1",
			key: 1
		};
	},
	render: function() {
		return (

alert

					<Alert bsStyle='warning'>warning</Alert>
					<Alert bsStyle='success'>success</Alert>
					<Alert bsStyle='info'>info</Alert>
					<Alert bsStyle='danger'>danger</Alert>

Button

					<ButtonToolbar>
					    {/* Standard button */}
					    <Button onClick={this.btnClick}>Default</Button>

					    {/* Provides extra visual weight and identifies the primary action in a set of buttons */}
					    <Button bsStyle='primary'>Primary</Button>

					    {/* Indicates a successful or positive action */}
					    <Button bsStyle='success'>Success</Button>

					    {/* Contextual button for informational alert messages */}
					    <Button bsStyle='info'>Info</Button>

					    {/* Indicates caution should be taken with this action */}
					    <Button bsStyle='warning'>Warning</Button>

					    {/* Indicates a dangerous or potentially negative action */}
					    <Button bsStyle='danger'>Danger</Button>

					    {/* Deemphasize a button by making it look like a link while maintaining button behavior */}
					    <Button bsStyle='link'>Link</Button>
					    <Button bsStyle='primary' bsSize="large">Primary</Button>
					    <Button bsStyle='primary' bsSize="small">Primary</Button>
					    <Button bsStyle='primary' bsSize="small" disabled>Primary</Button>
					    <Button href="#/dashboard">Link</Button>
					</ButtonToolbar>

ButtonGroup

					<ButtonToolbar>
						<ButtonGroup bsSize="small">
						    <Button>Left</Button>
						    <Button>Middle</Button>
						    <Button>Right</Button>
					    </ButtonGroup>
					    <ButtonGroup bsSize="large">
						    <Button>Left</Button>
						    <Button>Middle</Button>
						    <Button>Right</Button>
					    </ButtonGroup>
					    <ButtonGroup>
						    <Button>Left</Button>
						    <Button>Middle</Button>
						    <Button>Right</Button>
					    </ButtonGroup>
				    </ButtonToolbar>

Dropdown

				    <DropdownButton title='Dropdown' onSelect={this._menuSelect} >
				        <MenuItem eventKey='1'>Dropdown link</MenuItem>
				        <MenuItem eventKey='2'>Dropdown link</MenuItem>
				    </DropdownButton>

dropup

				    <DropdownButton title='Dropdown' onSelect={this._menuSelect} dropup>
				        <MenuItem eventKey='1'>Dropdown link</MenuItem>
				        <MenuItem eventKey='2'>Dropdown link</MenuItem>
				    </DropdownButton>

SplitButton

				    <SplitButton title='Dropdown right' pullRight>
					    <MenuItem eventKey='1'>Action</MenuItem>
					    <MenuItem eventKey='2'>Another action</MenuItem>
					    <MenuItem eventKey='3'>Something else here</MenuItem>
					    <MenuItem divider />
					    <MenuItem eventKey='4'>Separated link</MenuItem>
				  	</SplitButton>

Panel

				  	<Panel header="this is the header">
					    Basic panel example<Button onClick={this.btnClick}>Default</Button>
				  	</Panel>
				  	<Panel header="this is the header" bsStyle="primary">
					    Basic panel example
				  	</Panel>
				  	<Panel collapsable defaultExpanded header='Panel heading'>
					    <ListGroup fill>
					      	<ListGroupItem>Item 1</ListGroupItem>
					      	<ListGroupItem>Item 2</ListGroupItem>
					      	<ListGroupItem>…</ListGroupItem>
					    </ListGroup>
				  	</Panel>

				  	<PanelGroup activeKey={this.state.activeKey} onSelect={this.handleSelect} accordion>
				        <Panel header='Panel 1' eventKey='1'>
							<ListGroup fill>
						      	<ListGroupItem>Item 1</ListGroupItem>
						      	<ListGroupItem>Item 2</ListGroupItem>
						      	<ListGroupItem>…</ListGroupItem>
					    	</ListGroup>
				        </Panel>
				        <Panel header='Panel 2' eventKey='2'>
			        		<ListGroup fill>
						      	<ListGroupItem>Item 1</ListGroupItem>
						      	<ListGroupItem>Item 2</ListGroupItem>
						      	<ListGroupItem>…</ListGroupItem>
					    	</ListGroup>
				        </Panel>
			      	</PanelGroup>

modal

			      	<ModalTrigger modal={<MyModal />}>
					    <Button bsStyle='primary' bsSize='large'>Launch demo modal</Button>
				  	</ModalTrigger>

Tooltip

				  	<ButtonToolbar>
					    <OverlayTrigger placement='left' overlay={<Tooltip>Holy guacamole! Check this info.</Tooltip>}>
					      <Button bsStyle='default'>Holy guacamole!</Button>
					    </OverlayTrigger>
					    <OverlayTrigger placement='top' overlay={<Tooltip>Holy guacamole! Check this info.</Tooltip>}>
					      <Button bsStyle='default'>Holy guacamole!</Button>
					    </OverlayTrigger>
					    <OverlayTrigger placement='bottom' overlay={<Tooltip>Holy guacamole! Check this info.</Tooltip>}>
					      <Button bsStyle='default'>Holy guacamole!</Button>
					    </OverlayTrigger>
					    <OverlayTrigger placement='right' overlay={<Tooltip>Holy guacamole! Check this info.</Tooltip>}>
					      <Button bsStyle='default'>Holy guacamole!</Button>
					    </OverlayTrigger>
				  	</ButtonToolbar>

Popover

				  	<ButtonToolbar>
					    <OverlayTrigger trigger='click' placement='left' overlay={<Popover title='Popover left'>Holy guacamole! Check this info.</Popover>}>
					      <Button bsStyle='default'>Holy guacamole!</Button>
					    </OverlayTrigger>
					    <OverlayTrigger trigger='click' placement='top' overlay={<Popover title='Popover top'>Holy guacamole! Check this info.</Popover>}>
					      <Button bsStyle='default'>Holy guacamole!</Button>
					    </OverlayTrigger>
					    <OverlayTrigger trigger='click' placement='bottom' overlay={<Popover title='Popover bottom'>Holy guacamole! Check this info.</Popover>}>
					      <Button bsStyle='default'>Holy guacamole!</Button>
					    </OverlayTrigger>
					    <OverlayTrigger trigger='click' placement='right' overlay={<Popover title='Popover right'>Holy guacamole! Check this info.</Popover>}>
					      <Button bsStyle='default'>Holy guacamole!</Button>
					    </OverlayTrigger>
				  	</ButtonToolbar>

TabbedArea

				  	<TabbedArea activeKey={this.state.key} onSelect={this.handleTab} animation={false}>
				        <TabPane eventKey={1} tab='Tab 1'>TabPane 1 content</TabPane>
				        <TabPane eventKey={2} tab='Tab 2'>TabPane 2 content</TabPane>
			      	</TabbedArea>

ProgressBar

				  	<ProgressBar now={60}  active label='%(percent)s%'/>

Label

					    Default
					    Primary
					    Success
					    Info
					    Warning
					    Danger

Badges

Badges <Badge>42</Badge>

		);
	},
	btnClick:function(){
		alert(1)
	},
	_menuClick:function(e){
		e.preventDefault();
		alert(2)
	},
	_menuSelect:function(e){
		console.log(e)
	},
	handleSelect:function(activeKey){
		this.setState({ activeKey:activeKey });
	},
	handleTab:function(key){
		this.setState({key:key});
	}

});

module.exports = dashboard;


text:
TiStorekit
==========

Store Kit module for Appcelerator Titanium


text:
module ProjectEuler (
  projectEuler96
) where

import Data.Maybe
import Data.Char
import Data.List
import SudokuAbstract

projectEuler96 boards = sum $ fullAnswer boards
                                 where
                                   fullAnswer boards       = fmap (answer.fromJust) boards
                                   answer board            = (read $ map intToDigit $ map (toInt.fromJust.value) $ map (element board) [(0,0),(1,0),(2,0)]) :: Int
                                   toInt :: (SudokuValue v) => v -> Int
                                   toInt val = (+1) $ fromJust $ elemIndex val (map fromInt [1..9])


text:
<?php

declare(strict_types=1);

namespace Biplane\YandexDirect\Api\V5\Contract;

use AllowDynamicProperties;

/**
 * Auto-generated code.
 */
#[AllowDynamicProperties]
class GetVCardsRequest extends GetRequestGeneral
{
//    Can be omitted.
//    protected $SelectionCriteria = null;

    protected $FieldNames = [];

    public function getSelectionCriteria(): ?IdsCriteria
    {
        return $this->SelectionCriteria ?? null;
    }

    /**
     * @return $this
     */
    public function setSelectionCriteria(?IdsCriteria $value = null)
    {
        $this->SelectionCriteria = $value;

        return $this;
    }

    /**
     * @see VCardFieldEnum
     *
     * @return string[]
     */
    public function getFieldNames(): array
    {
        return $this->FieldNames;
    }

    /**
     * @see VCardFieldEnum
     *
     * @param string[] $value
     *
     * @return $this
     */
    public function setFieldNames(array $value)
    {
        $this->FieldNames = $value;

        return $this;
    }
}


text:
'use strict';

exports.__esModule = true;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

var _invariant = require('invariant');

var _invariant2 = _interopRequireDefault(_invariant);

var _utilsIsPlainObject = require('./utils/isPlainObject');

var _utilsIsPlainObject2 = _interopRequireDefault(_utilsIsPlainObject);

// Don't ever try to handle these action types in your code. They are private.
// For any unknown actions, you must return the current state.
// If the current state is undefined, you must return the initial state.
var ActionTypes = {
  INIT: '@@redux/INIT'
};

exports.ActionTypes = ActionTypes;

var Store = (function () {
  function Store(reducer, initialState) {
    _classCallCheck(this, Store);

    _invariant2['default'](typeof reducer === 'function', 'Expected the reducer to be a function.');

    this.state = initialState;
    this.listeners = [];
    this.replaceReducer(reducer);
  }

  Store.prototype.getReducer = function getReducer() {
    return this.reducer;
  };

  Store.prototype.replaceReducer = function replaceReducer(nextReducer) {
    this.reducer = nextReducer;
    this.dispatch({ type: ActionTypes.INIT });
  };

  Store.prototype.dispatch = function dispatch(action) {
    _invariant2['default'](_utilsIsPlainObject2['default'](action), 'Actions must be plain objects. Use custom middleware for async actions.');

    var reducer = this.reducer;

    this.state = reducer(this.state, action);
    this.listeners.forEach(function (listener) {
      return listener();
    });
    return action;
  };

  Store.prototype.getState = function getState() {
    return this.state;
  };

  Store.prototype.subscribe = function subscribe(listener) {
    var listeners = this.listeners;

    listeners.push(listener);

    return function unsubscribe() {
      var index = listeners.indexOf(listener);
      listeners.splice(index, 1);
    };
  };

  return Store;
})();

exports['default'] = Store;


text:
package net.virtualinfinity.telnet;

/**
 * Interface for things that have an option code.
 * @author Daniel Pitts
 */
public interface HasOptionCode {
    /**
     * Return an option code. These correspond to the option codes for the TELNET protocol.
     *
     * @return a number between 0-255.  Extended option ids are not supported, though none are defined either.
     */
    int optionCode();
}


text:
var add, assert;

assert = require('assert');

add = function(a, b) {
  console.assert(typeof a === 'number');
  assert(!isNaN(a));
  assert.equal(typeof b, 'number');
  assert.ok(!isNaN(b));
  return a + b;
};


text:
module Clickmeetings
  module Open
    class FileLibrary < Model
      set_resource_name 'file-library'

      attr_accessor :status, :url, :document_type, :conversion_progress, :status_message,
                    :name, :upload_date

      class << self
        def create(path: '', conference_id: nil)
          params = { uploaded: Faraday::UploadIO.new(path, '') }
          if conference_id.present?
            response = Clickmeetings.with_client(client_options) do
              Clickmeetings.client.post remote_url("conferences/#{conference_id}"),
                params.merge(default_params), default_headers
            end
            handle_response response
          else
            super(params)
          end
        end

        def for_conference(conference_id: nil)
          response = Clickmeetings.with_client(client_options) do
            Clickmeetings.client.get remote_url("conferences/#{conference_id}"),
              default_params, default_headers
          end
          handle_response response
        end
      end

      # returns content of file; use File#write to save it
      def download
        response = Clickmeetings.with_client(client_options) do
          Clickmeetings.client.connect.get remote_url(__method__, id: id) do |req|
            req.headers.merge! default_headers
          end
        end
        response.body
      end
    end
  end
end


text:
import os

from hokusai.lib import config
from hokusai.lib.exceptions import HokusaiError

from test import HokusaiUnitTestCase

TMP_CONFIG_FILE = os.path.join('/tmp', 'config.yml')

class TestConfigSetup(HokusaiUnitTestCase):
  @classmethod
  def setUpClass(cls):
    cls.__hokusai_config_file = config.HOKUSAI_CONFIG_FILE
    config.HOKUSAI_CONFIG_FILE = TMP_CONFIG_FILE

  @classmethod
  def tearDownClass(cls):
    config.HOKUSAI_CONFIG_FILE = cls.__hokusai_config_file

  def setUp(self):
    self.config = config.config

  def test_requires_config(self):
    with self.assertRaises(HokusaiError):
      self.config.check()
    self.assertFalse(self.config._check_config_present(TMP_CONFIG_FILE))

  def test_create(self):
    self.assertFalse(os.path.isfile(TMP_CONFIG_FILE))
    try:
      self.config.create('bar')
      self.assertTrue(os.path.isfile(TMP_CONFIG_FILE))
      self.assertTrue(self.config._check_config_present(TMP_CONFIG_FILE))
      self.assertEqual(self.config.project_name, 'bar')
    finally:
      os.remove(TMP_CONFIG_FILE)

  def test_check_hokusai_required_version(self):
    self.assertTrue(self.config._check_required_version(None, '0.0.1'))
    with self.assertRaises(HokusaiError):
      self.config._check_required_version('0.0.1', '0.0.1')
    with self.assertRaises(HokusaiError):
      self.config._check_required_version('someinvalidversionspecifier', '0.0.1')
    self.assertTrue(self.config._check_required_version('~=0.1', '0.1.1'))
    self.assertTrue(self.config._check_required_version('~=0.1', '0.2'))
    self.assertFalse(self.config._check_required_version('~=0.1', '1.0'))
    self.assertTrue(self.config._check_required_version('==0.0.1', '0.0.1'))
    self.assertFalse(self.config._check_required_version('==0.0.1', '0.0.2'))
    self.assertFalse(self.config._check_required_version('==1.0', '0.2'))
    self.assertTrue(self.config._check_required_version('<0.0.2.post2', '0.0.2.post1'))
    self.assertTrue(self.config._check_required_version('<1.1', '1.0.2'))
    self.assertFalse(self.config._check_required_version('<1.1', '2.0.2'))
    self.assertFalse(self.config._check_required_version('<=0.0.2', '2.2'))
    self.assertTrue(self.config._check_required_version('<=2.2', '2.2'))
    self.assertTrue(self.config._check_required_version('>0.0.1', '1.2.3'))
    self.assertTrue(self.config._check_required_version('>0.0.1.post1', '0.0.1.post3'))
    self.assertTrue(self.config._check_required_version('>=0.0.1', '1.2.3'))
    self.assertTrue(self.config._check_required_version('>=1.2.3', '1.2.3'))
    self.assertTrue(self.config._check_required_version('!=0.0.1', '1.2.3'))
    self.assertFalse(self.config._check_required_version('!=0.0.1', '0.0.1'))
    self.assertFalse(self.config._check_required_version('!=0.1.*', '0.1.1'))
    self.assertTrue(self.config._check_required_version('===1.0+trololo', '1.0+trololo'))
    self.assertFalse(self.config._check_required_version('===1.0+trololo', '1.0+tralala'))
    self.assertTrue(self.config._check_required_version('>0.0.1,~=0.2,!=0.2.3', '0.2.2'))
    self.assertFalse(self.config._check_required_version('>0.0.1,~=0.2,!=0.2.3', '0.2.3'))

class TestConfig(HokusaiUnitTestCase):
  def test_config_from_file(self):
    self.assertEqual(config.config.project_name, 'hello')
    self.assertEqual(config.config.pre_deploy, 'migrate.sh')
    self.assertEqual(config.config.post_deploy, 'sh -c report.sh')
    self.assertEqual(config.config.git_remote, 'git@github.com:artsy/hokusai.git')
    self.assertEqual(config.config.template_config_files, ['./test/fixtures/template_config.yml'])

  def test_config_from_environment(self):
    self.assertEqual(config.config.run_tty, False)
    os.environ['HOKUSAI_RUN_TTY'] = 'True'
    self.assertEqual(config.config.run_tty, True)


text:
package org.eclipse.jface.text.revisions;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.eclipse.swt.graphics.RGB;

import org.eclipse.jface.internal.text.revisions.ChangeRegion;
import org.eclipse.jface.internal.text.revisions.Hunk;

import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.source.ILineRange;

/**
 * Describes a revision of a document. A revision consists of one ore more {@link ILineRange}s.
 *

 * Clients may subclass.
 *

 *
 * @since 3.2
 */
public abstract class Revision {
	/** The original list of change regions, element type: {@link ChangeRegion}. */
	private final List fChangeRegions= new ArrayList();
	/**
	 * The cached list of adjusted ranges, element type: {@link RevisionRange}. null
	 * if the list must be re-computed. Unmodifiable.
	 *
	 * @since 3.3
	 */
	private List fRanges= null;

	/**
	 * Creates a new revision.
	 */
	protected Revision() {
	}

	/**
	 * Adds a line range to this revision. The range must be non-empty and have a legal start line
	 * (not -1).
	 *
	 * @param range a line range that was changed with this revision
	 * @throws IndexOutOfBoundsException if the line range is empty or has a negative start line
	 */
	public final void addRange(ILineRange range) throws IndexOutOfBoundsException {
		fChangeRegions.add(new ChangeRegion(this, range));
	}

	/**
	 * Returns the contained {@link RevisionRange}s adapted to the current diff state. The returned
	 * information is only valid at the moment it is returned, and may change as the annotated
	 * document is modified.
	 *
	 * @return an unmodifiable view of the contained ranges (element type: {@link RevisionRange})
	 */
	public final List getRegions() {
		if (fRanges == null) {
			List ranges= new ArrayList(fChangeRegions.size());
			for (Iterator it= fChangeRegions.iterator(); it.hasNext();) {
				ChangeRegion region= (ChangeRegion) it.next();
				for (Iterator inner= region.getAdjustedRanges().iterator(); inner.hasNext();) {
					ILineRange range= (ILineRange) inner.next();
					ranges.add(new RevisionRange(this, range));
				}
			}
			fRanges= Collections.unmodifiableList(ranges);
		}
		return fRanges;
	}

	/**
	 * Adjusts the revision information to the given diff information. Any previous diff information
	 * is discarded.
	 *
	 * @param hunks the diff hunks to adjust the revision information to
	 * @since 3.3
	 */
	final void applyDiff(Hunk[] hunks) {
		fRanges= null; // mark for recomputation
		for (Iterator regions= fChangeRegions.iterator(); regions.hasNext();) {
			ChangeRegion region= (ChangeRegion) regions.next();
			region.clearDiff();
			for (int i= 0; i < hunks.length; i++) {
				Hunk hunk= hunks[i];
				region.adjustTo(hunk);
			}
		}
	}

	/**
	 * Returns the hover information that will be shown when the user hovers over the a change
	 * region of this revision.
	 *

	 * Note: The hover information control which is used to display the information
	 * must be able process the given object. If the default information control creator is used
	 * the supported format is simple text, full HTML or an HTML fragment.
	 *

	 *
	 * @return the hover information for this revision or null for no hover
	 * @see RevisionInformation#setHoverControlCreator(IInformationControlCreator)
	 */
	public abstract Object getHoverInfo();

	/**
	 * Returns the author color for this revision. This color can be used to visually distinguish
	 * one revision from another, for example as background color.
	 *

	 * Revisions from the same author must return the same color and revisions from different authors
	 * must return distinct colors.

	 *
	 * @return the RGB color for this revision's author
	 */
	public abstract RGB getColor();

	/**
	 * Returns the unique (within the document) id of this revision. This may be the version string
	 * or a different identifier.
	 *
	 * @return the id of this revision
	 */
	public abstract String getId();

	/**
	 * Returns the modification date of this revision.
	 *
	 * @return the modification date of this revision
	 */
	public abstract Date getDate();

	/*
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		return "Revision " + getId(); //$NON-NLS-1$
	}

	/**
	 * Returns the display string for the author of this revision.
	 *

	 * Subclasses should replace - the default implementation returns the empty string.
	 *

	 *
	 * @return the author name
	 * @since 3.3
	 */
	public String getAuthor() {
		return ""; //$NON-NLS-1$
	}
}


text:
/* Minimal test with all headers generated into a single file. */
#include "monster_test.h"

int main(int argc, char *argv[])
{
    int ret;
    void *buf;
    size_t size;
    flatcc_builder_t builder, *B;

    (void)argc;
    (void)argv;

    B = &builder;
    flatcc_builder_init(B);

    MyGame_Example_Monster_start_as_root(B);
    MyGame_Example_Monster_name_create_str(B, "MyMonster");
    MyGame_Example_Monster_end_as_root(B);
    buf = flatcc_builder_get_direct_buffer(B, &size);
    ret = MyGame_Example_Monster_verify_as_root(buf, size);
    flatcc_builder_clear(B);
    return ret;
}


text:
using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Input;

#endregion

namespace HoneycombRush
{
    class LoadingAndInstructionScreen : GameScreen
    {
        #region Fields

        SpriteFont font;
        bool isLoading;
        GameplayScreen gameplayScreen;
        System.Threading.Thread thread;

        #endregion

        #region Initialization

        public LoadingAndInstructionScreen()
        {
            TransitionOnTime = TimeSpan.FromSeconds(0);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);

            EnabledGestures = GestureType.Tap;
        }

        /// <summary>
        /// Load the screen resources
        /// </summary>
        public override void LoadContent()
        {
            font = Load<SpriteFont>(@"Fonts\MenuFont");

            // Create a new instance of the gameplay screen
            gameplayScreen = new GameplayScreen(DifficultyMode.Easy);
            gameplayScreen.ScreenManager = ScreenManager;
        }

        #endregion

        #region Update

        /// <summary>
        /// Exit the screen after a tap gesture
        /// </summary>
        /// <param name="input"></param>
        public override void HandleInput(GameTime gameTime, InputState input)
        {
            if (!isLoading)
            {
                PlayerIndex player;

                // Handle touch input
                if (input.Gestures.Count > 0)
                {
                    if (input.Gestures[0].GestureType == GestureType.Tap)
                    {
                        LoadResources();
                    }
                }
                else if (input.IsNewKeyPress(Keys.Escape, ControllingPlayer, out player))
                {
                    foreach (GameScreen screen in ScreenManager.GetScreens())
                    {
                        screen.ExitScreen();
                    }

                    ScreenManager.AddScreen(new BackgroundScreen("titleScreen"), null);
                    ScreenManager.AddScreen(new MainMenuScreen(), PlayerIndex.One);
                }
                else if (input.IsNewKeyPress(Keys.Enter, ControllingPlayer, out player) ||
                    input.IsNewKeyPress(Keys.Space, ControllingPlayer, out player))
                {
                    LoadResources();
                }
            }

            base.HandleInput(gameTime, input);
        }

        /// <summary>
        /// Screen update logic
        /// </summary>
        /// <param name="gameTime"></param>
        /// <param name="otherScreenHasFocus"></param>
        /// <param name="coveredByOtherScreen"></param>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            // If necessary, load the highscore. Remember that calling LoadHighscores multiple times does not have
            // and adverse effect. Highscore will only be loaded once.
            if (!HighScoreScreen.HighscoreLoaded)
            {
                HighScoreScreen.LoadHighscores();
            }
            // If additional thread is running, do nothing
            else if (null != thread)
            {
                // If additional thread finished loading and the screen is not exiting
                if (thread.ThreadState == ThreadState.Stopped && !IsExiting)
                {
                    // Move on to the game play screen once highscore data is loaded
                    foreach (GameScreen screen in ScreenManager.GetScreens())
                    {
                        screen.ExitScreen();
                    }

                    ScreenManager.AddScreen(gameplayScreen, null);
                }
            }

            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
        }

        #endregion

        #region Render

        /// <summary>
        /// Render screen
        /// </summary>
        /// <param name="gameTime"></param>
        public override void Draw(GameTime gameTime)
        {
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

            spriteBatch.Begin();

            // If loading game play screen resource in the
            // background, show "Loading..." text

            if (isLoading)
            {
                string text = "Loading...";
                Vector2 size = font.MeasureString(text);
                Vector2 position = new Vector2((ScreenManager.GraphicsDevice.Viewport.Width - size.X) / 2,
                    (ScreenManager.GraphicsDevice.Viewport.Height - size.Y) / 2);
                spriteBatch.DrawString(font, text, position, Color.White);
            }

            spriteBatch.End();
        }

        #endregion

        #region Private functionality

        private void LoadResources()
        {
            // Start loading the resources in an additional thread
            thread = new Thread(new ThreadStart(gameplayScreen.LoadAssets));

            thread.Start();
            isLoading = true;
        }

        #endregion
    }
}


text:
<link rel="import" href="chrome://resources/html/polymer.html">

<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="profile_info_browser_proxy.html">
<link rel="import" href="sync_browser_proxy.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../settings_shared_css.html">

<dom-module id="settings-signout-dialog">
  <template>

    <cr-dialog id="dialog" ignore-enter-key close-text="$i18n{close}">

$i18n{syncDisconnectTitle}

        <cr-button id="disconnectCancel" class="cancel-button"
            on-click="onDisconnectCancel_" >
          $i18n{cancel}
        </cr-button>
        <cr-button id="disconnectConfirm" class="action-button"
            hidden="[[syncStatus.domain]]" on-click="onDisconnectConfirm_">
          $i18n{syncDisconnect}
        </cr-button>
        <cr-button id="disconnectManagedProfileConfirm"
            class="action-button" hidden="[[!syncStatus.domain]]"
            on-click="onDisconnectConfirm_">
          $i18n{syncDisconnectConfirm}
        </cr-button>

<if expr="(not chromeos and is_posix) or is_win or is_macosx">
      <template is="dom-if" if="[[!syncStatus.domain]]">

            <cr-checkbox id="deleteProfile" class="flex"
                checked="{{deleteProfile_}}">
              $i18n{syncDisconnectDeleteProfile}
            </cr-checkbox>
            <cr-expand-button expanded="{{deleteProfileWarningVisible_}}"
                alt="$i18n{deleteProfileWarningExpandA11yLabel}">
            </cr-expand-button>

          <iron-collapse opened="[[deleteProfileWarningVisible_]]">

              [[deleteProfileWarning_]]

          </iron-collapse>

      </template>
</if>
    </cr-dialog>
  </template>

</dom-module>


text:
require 'nokogiri'
require 'uri'
require 'json'
require 'serper/crawler'
require 'serper/helper'

module Serper
  class Parser
    attr_reader :engine_name, :keyword, :page, :html, :doc, :result

    def initialize(engine_name,keyword,page=1)
      @engine_name = engine_name
      @engine = ENGINES[@engine_name].new
      @keyword = keyword
      @page = page
    end

    def search
      html = @engine.search(@keyword,@page)
      parse html
    end

    def parse(html)
      html = html.encode!('UTF-8','UTF-8',:invalid => :replace)
      @file = Hash.new
      @result = Hash.new

      @file[:html] = html
      @file[:doc] = Nokogiri::HTML(html)

      @engine.methods.each do |m|
        next unless m =~ /^_parse_/
        begin
          @result[m.to_s.sub('_parse_','').to_sym] = @engine.send m,@file
        rescue Exception => e
          issue_file = "/tmp/serper_issue_#{Time.now.strftime("%Y%m%d%H%M%S")}.html"
          open(issue_file,'w').puts(html)
          puts "Notice:"
          puts "Serper gem have a bug, please email to zmingqian@qq.com to report it."
          puts "Please attach file #{issue_file} in the email and the error information below, thanks!"
          puts e.message
          puts e.inspect
          puts e.backtrace
          raise "Serper Parser Get An Error!"
        end
      end

      @result
    end

    def weights
      result = []
      [:left,:right].each do |side|
        side_rank = 0

        @engine.weight_config["#{side}_parts".to_sym].each do |part|
          rs,side_rank = @engine.send("_weight_of_#{part}",@result,side_rank)
          raise '!Weight Error!' if rs.nil?

          rs.each do |r|
            r[:side] = side.to_s
            r[:part] = part

            r[:weight] = r[:weight].to_f * @engine.weight_config["#{side}_part_weight".to_sym].to_f
            result << r
          end
        end
      end
      Serper::Helper.normalize(result,:side_weight,:weight)
    end
  end
end


text:
@implementation DRApiResponse

+ (instancetype)responseWithError:(NSError *)error {
    DRApiResponse *model = [DRApiResponse new];
    model.error = error;
    return model;
}

+ (instancetype)responseWithObject:(id)data {
    DRApiResponse *model = [DRApiResponse new];
    model.object = data;
    return model;
}

+ (instancetype)responseWithObject:(id)data error:(NSError *)error {
    DRApiResponse *model = [DRApiResponse new];
    model.object = data;
    model.error = error;
    return model;
}

@end


text:
Title: this is "matching-game" schema.

Feature Tasks:

wireframe: 4 pages: user splash page, feature game (theme), About-us, (game-score)

flow charts:

Page Requirement:
1) user splash page:
   login/sign-up
   A) function new user  (name, password){
      , navigate to feature game page,
      userArray = [];}

      function name (name, password){
        this.name;
        this.password;
        this.score;
        game-status = render state of table from previous session = [];
        userArray.push(this);
        this.active = true;
      }

      eventHandler function (){
        set active status;
        localStorage(if not true, set localStorage);
        go to another html page;
}

  B) function repeat user: retrieve and verify localStorage array (name, password) {
    game-status = render state of table from previous session
    }

      eventHandler function (){
      if validation fails, return alert;

      set active status;
      update localStorage (setItem);
      game-status = render state of table from previous session = [];
      navigate to feature game page;
    }

2) Feature game:

A) instruction (one user);
    eventHandler singleUser button ()
    {userPrompt(how many squares do you want?)
     for initial build, we only input "4"
     alert (verify if number square = 2 || 4 || 6 || 8);
   }

  cardArray = [ 32 images, faceup_card, shown_card];

B) set up number of card instances based on number of squares (numSquares){
  this.name;
  this.imgLocation;
  this.face up = false;
  this.location;
  game-level = numSquares;
  this.removed = false;
  cardArray.push(this);
  }

C) function render table(set up number of squares {
    (for initial build, set up 4 x 4 pairs/grid, increase difficulties with more squares), each square with id("x,y")) ()};

D) function random generator for card location (){
    rules TBD;
    };

E) function render card (cardArray[i].location, render table){

    }

    numClick = 0;
F) evenHandler for clicking one of the squares function (click) {
      alert(for not clicking card);
    query card,
    if first click, flip card(imglocation)/card.faceup = true, numClick += 1;
    if second click, flip second card(imglocation)/card.faceup = true, timeDelay, if match, remove card from table;
      render cards(); this.removed = true} else
      { flip both cards, set both first and second card.faceup = false, render cards();
        }
    }

F) score object(boardSquare):{
    this.squares = boardSquares;
    this.SessionDuration(getStartTime,getStopTime);
  }

3) About-us:
add team-member bio;


text:
/**
 * Provides the API (classes and interfaces) for streams builders.
 *
 * @author akausinis
 * @version 1.0
 */

package com.jkoolcloud.tnt4j.streams.configure.build;


text:
package org.apache.carbondata.core.cache;

import org.apache.carbondata.core.datastore.TableSegmentUniqueIdentifier;
import org.apache.carbondata.core.datastore.block.AbstractIndex;

/**
 * class which defines different cache types. cache type can be dictionary cache for
 * forward (surrogate key to byte array mapping) and reverse (byte array to
 * surrogate mapping) dictionary or a B-tree cache
 */
public class CacheType<K, V> {

  /**
   * Executor BTree cache which maintains size of BTree metadata
   */
  public static final CacheType<TableSegmentUniqueIdentifier, AbstractIndex>
      DRIVER_BLOCKLET_DATAMAP = new CacheType("driver_blocklet_datamap");

  /**
   * cacheName which is unique name for a cache
   */
  private String cacheName;

  /**
   * @param cacheName
   */
  public CacheType(String cacheName) {
    this.cacheName = cacheName;
  }

  /**
   * @return cache unique name
   */
  public String getCacheName() {
    return cacheName;
  }
}


text:
using System;
using System.Collections;
using Approve.EntityBase;
using System.Data;

namespace Approve.EntityCenter
{
    [Serializable]
    public class EaQualiConditionData : EEnterpriseBase
    {
        public EaQualiConditionData()
            : base()
        {
            m_EntityType = EntityTypeEnum.EaQualiConditionData;
        }

        public EaQualiConditionData(IDictionary iDictionary)
            : base(iDictionary)
        {
            m_EntityType = EntityTypeEnum.EaQualiConditionData;
        }

        public EaQualiConditionData(DataRow dr)
            : base(dr)
        {
            m_EntityType = EntityTypeEnum.EaQualiConditionData;
        }

        public EaQualiConditionData(DataRow dr, IDictionary rel)
            : base(dr, rel)
        {
            m_EntityType = EntityTypeEnum.EaQualiConditionData;
        }
    }
}


text:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Author } from '../entities/author';

@Injectable()
export class AuthorService {
  private baseUrl: string = 'https://api.github.com';

  constructor(private http: Http) { }

  getAuthor(name: string): Promise<Author> {
    return this.http
      .get(`${this.baseUrl}/users/${name}`)
      .toPromise()
      .then(this.mapAuthor)
      .catch(this.handleError);
  }

  private mapAuthor(response: Response): Author {
    const res = response.json();

    let url = '';

    if (res.blog !== undefined && res.blog !== null && res.blog !== '') {
      url = res.blog;
    } else {
      url = res.html_url;
    }

    const author = <Author>({
      userName: res.login,
      name: res.name,
      avatarUrl: res.avatar_url,
      homepage: url,
      company: res.company,
      location: res.location,
      email: res.email,
      bio: res.bio
    });

    return author;
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);

    return Promise.reject(error.message || error);
  }
}