text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Constant Field Values (appsensor-parent 2.2.0 API)</title>
<meta name="date" content="2015-10-02">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Constant Field Values

Contents

org.owasp.*

org.owasp.*

org.owasp.appsensor.amqp.rabbitmq.RabbitMqConstants

Modifier and Type
Constant Field
Value

public static final String
APPSENSOR_ADD_ATTACK_QUEUE
"appsensor.add.attack.queue"

public static final String
APPSENSOR_ADD_EVENT_QUEUE
"appsensor.add.event.queue"

public static final String
APPSENSOR_CLIENT_APPLICATION_NAME
"APPSENSOR_CLIENT_APPLICATION_NAME"

public static final String
APPSENSOR_EXCHANGE_NAME
"appsensor.exchange"

public static final String
APPSENSOR_GET_RESPONSES_QUEUE_PREFIX
"appsensor."

public static final String
APPSENSOR_GET_RESPONSES_QUEUE_SUFFIX
".response.queue"

public static final String
RABBITMQ_HOST_ENV_VAR_NAME
"APPSENSOR_RABBITMQ_HOST"

public static final String
RABBITMQ_PASSWORD_ENV_VAR_NAME
"APPSENSOR_RABBITMQ_PASSWORD"

public static final String
RABBITMQ_PORT_ENV_VAR_NAME
"APPSENSOR_RABBITMQ_PORT"

public static final String
RABBITMQ_USERNAME_ENV_VAR_NAME
"APPSENSOR_RABBITMQ_USERNAME"

org.owasp.appsensor.core.DetectionPoint.Category

Modifier and Type
Constant Field
Value

public static final String
ACCESS_CONTROL
"Access Control"

public static final String
AUTHENTICATION
"Authentication"

public static final String
COMMAND_INJECTION
"Command Injection"

public static final String
FILE_IO
"File IO"

public static final String
HONEY_TRAP
"Honey Trap"

public static final String
INPUT_VALIDATION
"Input Validation"

public static final String
OUTPUT_ENCODING
"Output Encoding"

public static final String
REPUTATION
"Reputation"

public static final String
REQUEST
"Request"

public static final String
SESSION_MANAGEMENT
"Session Management"

public static final String
SYSTEM_TREND
"System Trend"

public static final String
USER_TREND
"User Trend"

org.owasp.appsensor.core.Interval

Modifier and Type
Constant Field
Value

public static final String
DAYS
"days"

public static final String
HOURS
"hours"

public static final String
MINUTES
"minutes"

public static final String
SECONDS
"seconds"

org.owasp.appsensor.core.RequestHandler

Modifier and Type
Constant Field
Value

public static final String
APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR
"APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR"

org.owasp.appsensor.core.response.ResponseHandler

Modifier and Type
Constant Field
Value

public static final String
DISABLE_COMPONENT_FOR_ALL_USERS
"disableComponentForAllUsers"

public static final String
DISABLE_COMPONENT_FOR_SPECIFIC_USER
"disableComponentForSpecificUser"

public static final String
DISABLE_USER
"disableUser"

public static final String
LOG
"log"

public static final String
LOGOUT
"logout"

org.owasp.appsensor.core.util.StringUtils

Modifier and Type
Constant Field
Value

public static final String
EMPTY
""

org.owasp.appsensor.integration.influxdb.InfluxDbEmitter

Modifier and Type
Constant Field
Value

public static final String
INFLUXDB_PASSWORD
"APPSENSOR_INFLUXDB_PASSWORD"

public static final String
INFLUXDB_URL
"APPSENSOR_INFLUXDB_URL"

public static final String
INFLUXDB_USERNAME
"APPSENSOR_INFLUXDB_USERNAME"

org.owasp.appsensor.kafka.KafkaConstants

Modifier and Type
Constant Field
Value

public static final String
APPSENSOR_ADD_ATTACK_TOPIC
"appsensor-add-attack-topic"

public static final String
APPSENSOR_ADD_EVENT_TOPIC
"appsensor-add-event-topic"

public static final String
APPSENSOR_CLIENT_APPLICATION_NAME
"APPSENSOR_CLIENT_APPLICATION_NAME"

public static final String
APPSENSOR_GET_RESPONSES_TOPIC_PREFIX
"appsensor-"

public static final String
APPSENSOR_GET_RESPONSES_TOPIC_SUFFIX
"-response-topic"

public static final String
ATTACK_TYPE
"ATTACK"

public static final String
EVENT_TYPE
"EVENT"

public static final String
KAFKA_CONSUMER_GROUP_ID
"APPSENSOR_KAFKA_CONSUMER_GROUP_ID"

public static final String
KAFKA_CONSUMER_ZOOKEEPER_CONNECT
"APPSENSOR_KAFKA_CONSUMER_ZOOKEEPER_CONNECT"

public static final String
KAFKA_PRODUCER_BOOTSTRAP_SERVERS
"APPSENSOR_KAFKA_PRODUCER_BOOTSTRAP_SERVERS"

public static final String
KAFKA_PRODUCER_KEY
"APPSENSOR_KAFKA_PRODUCER_KEY"

public static final String
KAFKA_PRODUCER_PARTITION
"APPSENSOR_KAFKA_PRODUCER_PARTITION"

public static final String
RESPONSE_TYPE
"RESPONSE"

org.owasp.appsensor.storage.file.FileBasedAttackStore

Modifier and Type
Constant Field
Value

public static final String
DEFAULT_FILE_NAME
"attacks.txt"

public static final String
FILE_NAME_CONFIGURATION_KEY
"fileName"

public static final String
FILE_PATH_CONFIGURATION_KEY
"filePath"

org.owasp.appsensor.storage.file.FileBasedEventStore

Modifier and Type
Constant Field
Value

public static final String
DEFAULT_FILE_NAME
"events.txt"

public static final String
FILE_NAME_CONFIGURATION_KEY
"fileName"

public static final String
FILE_PATH_CONFIGURATION_KEY
"filePath"

org.owasp.appsensor.storage.file.FileBasedResponseStore

Modifier and Type
Constant Field
Value

public static final String
DEFAULT_FILE_NAME
"responses.txt"

public static final String
FILE_NAME_CONFIGURATION_KEY
"fileName"

public static final String
FILE_PATH_CONFIGURATION_KEY
"filePath"

Copyright © 2015 The Open Web Application Security Project (OWASP). All rights reserved.


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__float_zero_54b.c
Label Definition File: CWE369_Divide_by_Zero__float.label.xml
Template File: sources-sinks-54b.tmpl.c
*/
/*
 * @description
 * CWE: 369 Divide by Zero
 * BadSource: zero Fixed value of zero
 * GoodSource: A hardcoded non-zero number (two)
 * Sinks:
 *    GoodSink: Check value of or near zero before dividing
 *    BadSink : Divide a constant by data
 * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
 *
 * */

#include "std_testcase.h"

#include <math.h>

#ifndef OMITBAD

/* bad function declaration */
void CWE369_Divide_by_Zero__float_zero_54c_badSink(float data);

void CWE369_Divide_by_Zero__float_zero_54b_badSink(float data)
{
    CWE369_Divide_by_Zero__float_zero_54c_badSink(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE369_Divide_by_Zero__float_zero_54c_goodG2BSink(float data);

void CWE369_Divide_by_Zero__float_zero_54b_goodG2BSink(float data)
{
    CWE369_Divide_by_Zero__float_zero_54c_goodG2BSink(data);
}

/* goodB2G uses the BadSource with the GoodSink */
void CWE369_Divide_by_Zero__float_zero_54c_goodB2GSink(float data);

void CWE369_Divide_by_Zero__float_zero_54b_goodB2GSink(float data)
{
    CWE369_Divide_by_Zero__float_zero_54c_goodB2GSink(data);
}

#endif /* OMITGOOD */

redpajama_set_name: RedPajamaGithub


text:
<?php

class Google_Service_Bigquery_DatasetListDatasets extends Google_Model
{
  protected $datasetReferenceType = 'Google_Service_Bigquery_DatasetReference';
  protected $datasetReferenceDataType = '';
  public $friendlyName;
  public $id;
  public $kind;

  public function setDatasetReference(Google_Service_Bigquery_DatasetReference $datasetReference)
  {
    $this->datasetReference = $datasetReference;
  }
  public function getDatasetReference()
  {
    return $this->datasetReference;
  }
  public function setFriendlyName($friendlyName)
  {
    $this->friendlyName = $friendlyName;
  }
  public function getFriendlyName()
  {
    return $this->friendlyName;
  }
  public function setId($id)
  {
    $this->id = $id;
  }
  public function getId()
  {
    return $this->id;
  }
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
}


text:
package paths

import (
	"log"
	"os"
	"path/filepath"
	"strings"
)

// EventContentPath returns the path for content for an event based upon city and year
func EventContentPath(city, year string) (eventContentPath string) {
	s := []string{strings.TrimSpace(year), "-", strings.Replace(strings.TrimSpace(strings.ToLower(city)), " ", "-", 10)}
	if err := os.MkdirAll(filepath.Join(GetWebdir(), "content", "events", strings.Join(s, "")), 0777); err != nil {
		log.Fatal(err)
	}
	return filepath.Join(GetWebdir(), "content", "events", strings.Join(s, ""))
}


text:
package org.mifos.dto.domain;

@SuppressWarnings("PMD")
public class LowerUpperMinMaxDefaultDto {

    private final Number lower;
    private final Number upper;
    private final Number min;
    private final Number max;
    private final Number theDefault;

    public static LowerUpperMinMaxDefaultDto create(Number lower, Number upper, Number min, Number max, Number theDefault) {
        return new LowerUpperMinMaxDefaultDto(lower, upper, min, max, theDefault);
    }

    private LowerUpperMinMaxDefaultDto(Number lower, Number upper, Number min, Number max, Number theDefault) {
        this.lower = lower;
        this.upper = upper;
        this.min = min;
        this.max = max;
        this.theDefault = theDefault;
    }

    public Number getLower() {
        return this.lower;
    }

    public Number getUpper() {
        return this.upper;
    }

    public Number getMin() {
        return this.min;
    }

    public Number getMax() {
        return this.max;
    }

    public Number getTheDefault() {
        return this.theDefault;
    }
}


text:
#ifndef __TLM_WRITE_IF_H__
#define __TLM_WRITE_IF_H__

#include <systemc>

namespace tlm {

template <typename T>
class tlm_write_if : public virtual sc_core::sc_interface {
public:
  virtual void write(const T& t) = 0;
};

template <typename T>
class tlm_delayed_write_if : public virtual sc_core::sc_interface {
public:
  virtual void write(const T& t, const sc_core::sc_time& time) = 0;
};

} // namespace tlm

#endif


text:
package ch.alv.components.web.dto;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Test cases for the {@link TranslatedText} class
 *
 * @since 1.0.0
 */
public class TranslatedTextTest {

    @Test
    public void testDto() {
        TranslatedText text = new TranslatedText("testText");
        assertEquals("testText", text.getText());
        text.setText("newText");
        assertEquals("newText", text.getText());
    }

}


text:
using System.Collections.Generic;
using Magecrawl.Interfaces;

namespace Magecrawl.GameUI.ListSelection.Requests
{
    public class ShowListSelectionWindow : RequestBase
    {
        private bool m_show;
        private List<INamedItem> m_data;
        private string m_title;
        private ListItemShouldBeEnabled m_selectionDelegate;
        private bool m_useLetters;

        public ShowListSelectionWindow(bool enable)
        {
            m_show = enable;
            m_data = null;
            m_title = null;

            if (m_show)
                throw new System.ArgumentException("ShowListSelectionWindow(bool show) must only be called if show is false");
        }

        public ShowListSelectionWindow(bool enable, List<INamedItem> data,  bool useLetters, string title)
            : this(enable, data, useLetters, title, i => { return true; })
        {
        }

        public ShowListSelectionWindow(bool enable, List<INamedItem> data, bool useLetters, string title, ListItemShouldBeEnabled selectionDelegate)
        {
            m_show = enable;
            m_data = data;
            m_title = title;
            m_useLetters = useLetters;
            m_selectionDelegate = selectionDelegate;
        }

        internal override void DoRequest(IHandlePainterRequest painter)
        {
            ListSelectionPainter l = painter as ListSelectionPainter;
            if (l != null)
            {
                if (m_show)
                    l.Enable(m_data, m_title, m_useLetters, m_selectionDelegate);
                else
                    l.Disable();
            }
        }
    }
}


text:
/**
 * Write a function on_all that applies a function to every element of a list.
 * You cannot use Array.map, but have to implement it yourself.
 */
var MyFunction = function() {
  'use strict';

  function applyFunction(list, f) {
		list.forEach(function(val, i, arr) {
  			arr[i] = f(val);
  		});

  		return list;
  }

  return {
    applyFunction: applyFunction
  };
};


text:
package first.pack.addressbook.tests;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import first.pack.addressbook.model.GroupData;
import first.pack.addressbook.model.Groups;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.*;

public class GroupCreationTests extends TestBase{

    @DataProvider
    public Iterator<Object[]> validGroups() throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/groups.json")))){
            String json = "";
            String line = reader.readLine();
            while (line != null) {
                json += line;
                line = reader.readLine();
            }
            Gson gson = new Gson();
            List<GroupData> groups = gson.fromJson(json, new TypeToken<List<GroupData>>(){}.getType());
            return groups.stream().map((g) -> new Object[] {g}).collect(Collectors.toList()).iterator();
        }
    }

    @Test(dataProvider = "validGroups")
    public void testGroupCreation(GroupData group) {
        app.goTo().groupPage();
        Groups before = app.db().readGroups();
        app.group().create(group);
        assertThat(app.group().count(), equalTo(before.size() + 1));
        Groups after = app.db().readGroups();
        assertThat(after, equalTo(
                before.withAdded(group.withValue(after.stream().mapToInt((g) -> g.getValue()).max().getAsInt()))));
        verifyGroupListInUI();
    }

    @Test
    public void testBadGroupCreation() {
        app.goTo().groupPage();
        Groups before = app.db().readGroups();
        GroupData group = new GroupData().withName("Group XX'").withHeader("Group XX header").withFooter("Group XX footer");
        app.group().create(group);
        assertThat(app.group().count(), equalTo(before.size()));
        Groups after = app.db().readGroups();
        assertThat(after, equalTo(before));
    }

}


text:
let pkg = require('./package.json');
let buble = require('rollup-plugin-buble');

module.exports = {
    input: `src/virtual-scrolling-tree/VirtualScrollingTree.js`,
    plugins: [
        buble({
            objectAssign: 'Object.assign'
        })
    ],
    output: [
        { file: pkg.main, format: 'cjs' },
        { file: pkg.browser, format: 'umd', name: 'VirtualScrollingTree'},
        { file: pkg.module, format: 'es' }
    ]
}


text:
define(function(require, exports, module) {

var RangeList = require("./range_list").RangeList;
var Range = require("./range").Range;
var Selection = require("./selection").Selection;
var onMouseDown = require("./mouse/multi_select_handler").onMouseDown;
exports.commands = require("./commands/multi_select_commands");

// Todo: session.find or editor.findVolatile that returns range
var Search = require("./search").Search;
var search = new Search();

function find(session, needle, dir) {
    search.$options.wrap = true;
    search.$options.needle = needle;
    search.$options.backwards = dir == -1;
    return search.find(session);
}

// extend EditSession
var EditSession = require("./edit_session").EditSession;
(function() {
    this.getSelectionMarkers = function() {
        return this.$selectionMarkers;
    };
}).call(EditSession.prototype);

// extend Selection
(function() {
    // list of ranges in reverse addition order
    this.ranges = null;

    // automatically sorted list of ranges
    this.rangeList = null;

    /**
     * Selection.addRange(Range) -> Void
     *
     * adds a range to selection entering multiselect mode if necessary
     **/
    this.addRange = function(range, $blockChangeEvents) {
        if (!range)
            return;

        if (!this.inMultiSelectMode && this.rangeCount == 0) {
            var oldRange = this.toOrientedRange();
            if (range.intersects(oldRange))
                return $blockChangeEvents || this.fromOrientedRange(range);

            this.rangeList.add(oldRange);
            this.$onAddRange(oldRange);
        }

        if (!range.cursor)
            range.cursor = range.end;

        var removed = this.rangeList.add(range);

        this.$onAddRange(range);

        if (removed.length)
            this.$onRemoveRange(removed);

        if (this.rangeCount > 1 && !this.inMultiSelectMode) {
            this._emit("multiSelect");
            this.inMultiSelectMode = true;
            this.session.$undoSelect = false;
            this.rangeList.attach(this.session);
        }

        return $blockChangeEvents || this.fromOrientedRange(range);
    };

    this.toSingleRange = function(range) {
        range = range || this.ranges[0];
        var removed = this.rangeList.removeAll();
        if (removed.length)
            this.$onRemoveRange(removed);

        range && this.fromOrientedRange(range);
    };

    /**
     * Selection.addRange(pos) -> Range
     * pos: {row, column}
     *
     * removes range containing pos (if exists)
     **/
    this.substractPoint = function(pos) {
        var removed = this.rangeList.substractPoint(pos);
        if (removed) {
            this.$onRemoveRange(removed);
            return removed[0];
        }
    };

    /**
     * Selection.mergeOverlappingRanges() -> Void
     *
     * merges overlapping ranges ensuring consistency after changes
     **/
    this.mergeOverlappingRanges = function() {
        var removed = this.rangeList.merge();
        if (removed.length)
            this.$onRemoveRange(removed);
        else if(this.ranges[0])
            this.fromOrientedRange(this.ranges[0]);
    };

    this.$onAddRange = function(range) {
        this.rangeCount = this.rangeList.ranges.length;
        this.ranges.unshift(range);
        this._emit("addRange", {range: range});
    };

    this.$onRemoveRange = function(removed) {
        this.rangeCount = this.rangeList.ranges.length;
        if (this.rangeCount == 1 && this.inMultiSelectMode) {
            var lastRange = this.rangeList.ranges.pop();
            removed.push(lastRange);
            this.rangeCount = 0;
        }

        for (var i = removed.length; i--; ) {
            var index = this.ranges.indexOf(removed[i]);
            this.ranges.splice(index, 1);
        }

        this._emit("removeRange", {ranges: removed});

        if (this.rangeCount == 0 && this.inMultiSelectMode) {
            this.inMultiSelectMode = false;
            this._emit("singleSelect");
            this.session.$undoSelect = true;
            this.rangeList.detach(this.session);
        }

        lastRange = lastRange || this.ranges[0];
        if (lastRange && !lastRange.isEqual(this.getRange()))
            this.fromOrientedRange(lastRange);
    };

    // adds multicursor support to selection
    this.$initRangeList = function() {
        if (this.rangeList)
            return;

        this.rangeList = new RangeList();
        this.ranges = [];
        this.rangeCount = 0;
    };

    this.getAllRanges = function() {
        return this.rangeList.ranges.concat();
    };

    this.splitIntoLines = function () {
        if (this.rangeCount > 1) {
            var ranges = this.rangeList.ranges;
            var lastRange = ranges[ranges.length - 1];
            var range = Range.fromPoints(ranges[0].start, lastRange.end);

            this.toSingleRange();
            this.setSelectionRange(range, lastRange.cursor == lastRange.start);
        } else {
            var cursor = this.session.documentToScreenPosition(this.selectionLead);
            var anchor = this.session.documentToScreenPosition(this.selectionAnchor);

            var rectSel = this.rectangularRangeBlock(cursor, anchor);
            rectSel.forEach(this.addRange, this);
        }
    };

    /**
     *   Selection.rectangularRangeBlock(screenCursor, screenAnchor, includeEmptyLines) -> [Range]
     *   gets list of ranges composing rectangular block on the screen
     *   @includeEmptyLines if true includes ranges inside the block which
     *         are empty becuase of the clipping
     */
    this.rectangularRangeBlock = function(screenCursor, screenAnchor, includeEmptyLines) {
        var rectSel = [];

        var xBackwards = screenCursor.column < screenAnchor.column;
        if (xBackwards) {
            var startColumn = screenCursor.column;
            var endColumn = screenAnchor.column;
        } else {
            var startColumn = screenAnchor.column;
            var endColumn = screenCursor.column;
        }

        var yBackwards = screenCursor.row < screenAnchor.row;
        if (yBackwards) {
            var startRow = screenCursor.row;
            var endRow = screenAnchor.row;
        } else {
            var startRow = screenAnchor.row;
            var endRow = screenCursor.row;
        }

        if (startColumn < 0)
            startColumn = 0;
        if (startRow < 0)
            startRow = 0;

        if (startRow == endRow)
            includeEmptyLines = true;

        for (var row = startRow; row <= endRow; row++) {
            var range = Range.fromPoints(
                this.session.screenToDocumentPosition(row, startColumn),
                this.session.screenToDocumentPosition(row, endColumn)
            );
            if (range.isEmpty()) {
                if (docEnd && isSamePoint(range.end, docEnd))
                    break;
                var docEnd = range.end;
            }
            range.cursor = xBackwards ? range.start : range.end;
            rectSel.push(range);
        }

        if (yBackwards)
            rectSel.reverse();

        if (!includeEmptyLines) {
            var end = rectSel.length - 1;
            while (rectSel[end].isEmpty() && end > 0)
                end--;
            if (end > 0) {
                var start = 0;
                while (rectSel[start].isEmpty())
                    start++;
            }
            for (var i = end; i >= start; i--) {
                if (rectSel[i].isEmpty())
                    rectSel.splice(i, 1);
            }
        }

        return rectSel;
    };
}).call(Selection.prototype);

// extend Editor
var Editor = require("./editor").Editor;
(function() {
    /**
     * Editor.updateSelectionMarkers() -> Void
     *
     * updates cursor and marker layers
     **/
    this.updateSelectionMarkers = function() {
        this.renderer.updateCursor();
        this.renderer.updateBackMarkers();
    };

    /**
     * Editor.addSelectionMarker(orientedRange) -> Range
     * - orientedRange: range with cursor
     *
     * adds selection and cursor
     **/
    this.addSelectionMarker = function(orientedRange) {
        if (!orientedRange.cursor)
            orientedRange.cursor = orientedRange.end;

        var style = this.getSelectionStyle();
        orientedRange.marker = this.session.addMarker(orientedRange, "ace_selection", style);

        this.session.$selectionMarkers.push(orientedRange);
        this.session.selectionMarkerCount = this.session.$selectionMarkers.length;
        return orientedRange;
    };

    /**
     * Editor.removeSelectionMarker(range) -> Void
     * - range: selection range added with addSelectionMarker
     *
     * removes selection marker
     **/
    this.removeSelectionMarker = function(range) {
        if (!range.marker)
            return;
        this.session.removeMarker(range.marker);
        var index = this.session.$selectionMarkers.indexOf(range);
        if (index != -1)
            this.session.$selectionMarkers.splice(index, 1);
        this.session.selectionMarkerCount = this.session.$selectionMarkers.length;
    };

    this.removeSelectionMarkers = function(ranges) {
        var markerList = this.session.$selectionMarkers;
        for (var i = ranges.length; i--; ) {
            var range = ranges[i];
            if (!range.marker)
                continue;
            this.session.removeMarker(range.marker);
            var index = markerList.indexOf(range);
            if (index != -1)
                markerList.splice(index, 1);
        }
        this.session.selectionMarkerCount = markerList.length;
    };

    this.$onAddRange = function(e) {
        this.addSelectionMarker(e.range);
        this.renderer.updateCursor();
        this.renderer.updateBackMarkers();
    };

    this.$onRemoveRange = function(e) {
        this.removeSelectionMarkers(e.ranges);
        this.renderer.updateCursor();
        this.renderer.updateBackMarkers();
    };

    this.$onMultiSelect = function(e) {
        if (this.inMultiSelectMode)
            return;
        this.inMultiSelectMode = true;

        this.setStyle("multiselect");
        this.keyBinding.addKeyboardHandler(exports.commands.keyboardHandler);
        this.commands.on("exec", this.$onMultiSelectExec);

        this.renderer.updateCursor();
        this.renderer.updateBackMarkers();
    };

    this.$onSingleSelect = function(e) {
        if (this.session.multiSelect.inVirtualMode)
            return;
        this.inMultiSelectMode = false;

        this.unsetStyle("multiselect");
        this.keyBinding.removeKeyboardHandler(exports.commands.keyboardHandler);

        this.commands.removeEventListener("exec", this.$onMultiSelectExec);
        this.renderer.updateCursor();
        this.renderer.updateBackMarkers();
    };

    this.$onMultiSelectExec = function(e) {
        var command = e.command;
        var editor = e.editor;
        if (!command.multiSelectAction) {
            command.exec(editor, e.args || {});
            editor.multiSelect.addRange(editor.multiSelect.toOrientedRange());
            editor.multiSelect.mergeOverlappingRanges();
        } else if (command.multiSelectAction == "forEach") {
            editor.forEachSelection(command, e.args);
        } else if (command.multiSelectAction == "single") {
            editor.exitMultiSelectMode();
            command.exec(editor, e.args || {});
        } else {
            command.multiSelectAction(editor, e.args || {});
        }
        e.preventDefault();
    };

    /**
     * Editor.forEachSelection(cmd, args) -> Void
     * - cmd: command to execute
     * - args: arguments to the command
     *
     * executes command for each selection range
     **/
    this.forEachSelection = function(cmd, args) {
        if (this.inVirtualSelectionMode)
            return;

        var session = this.session;
        var selection = this.selection;
        var rangeList = selection.rangeList;

        var reg = selection._eventRegistry;
        selection._eventRegistry = {};

        var tmpSel = new Selection(session);
        this.inVirtualSelectionMode = true;
        for (var i = rangeList.ranges.length; i--;) {
            tmpSel.fromOrientedRange(rangeList.ranges[i]);
            this.selection = session.selection = tmpSel;
            cmd.exec(this, args || {});
            tmpSel.toOrientedRange(rangeList.ranges[i]);
        }
        tmpSel.detach();

        this.selection = session.selection = selection;
        this.inVirtualSelectionMode = false;
        selection._eventRegistry = reg;
        selection.mergeOverlappingRanges();

        this.onCursorChange();
        this.onSelectionChange();
    };

    /**
    * Editor.exitMultiSelectMode() -> Void
    *
    * removes all selections except the last added one.
    **/
    this.exitMultiSelectMode = function() {
        if (this.inVirtualSelectionMode)
            return;
        this.multiSelect.toSingleRange();
    };

    this.getCopyText = function() {
        var text = "";
        if (this.inMultiSelectMode) {
            var ranges = this.multiSelect.rangeList.ranges;
            text = [];
            for (var i = 0; i < ranges.length; i++) {
                text.push(this.session.getTextRange(ranges[i]));
            }
            text = text.join(this.session.getDocument().getNewLineCharacter());
        } else if (!this.selection.isEmpty()) {
            text = this.session.getTextRange(this.getSelectionRange());
        }

        return text;
    };

    /**
     * Editor.findAll(dir, options) -> Number
     * - needle: text to find
     * - options: search options
     * - additive: keeps
     *
     * finds and selects all the occurencies of needle
     * returns number of found ranges
     **/
    this.findAll = function(needle, options, additive) {
        options = options || {};
        options.needle = needle || options.needle;
        this.$search.set(options);

        var ranges = this.$search.findAll(this.session);
        if (!ranges.length)
            return 0;

        this.$blockScrolling += 1;
        var selection = this.multiSelect;

        if (!additive)
            selection.toSingleRange(ranges[0]);

        for (var i = ranges.length; i--; )
            selection.addRange(ranges[i], true);

        this.$blockScrolling -= 1;

        return ranges.length;
    };

    // commands
    /**
     * Editor.selectMoreLines(dir, skip) -> Void
     * - dir: -1 up, 1 down
     * - skip: remove active selection range if true
     *
     * adds cursor above or bellow active cursor
     **/
    this.selectMoreLines = function(dir, skip) {
        var range = this.selection.toOrientedRange();
        var isBackwards = range.cursor == range.end;

        var screenLead = this.session.documentToScreenPosition(range.cursor);
        if (this.selection.$desiredColumn)
            screenLead.column = this.selection.$desiredColumn;

        var lead = this.session.screenToDocumentPosition(screenLead.row + dir, screenLead.column);

        if (!range.isEmpty()) {
            var screenAnchor = this.session.documentToScreenPosition(isBackwards ? range.end : range.start);
            var anchor = this.session.screenToDocumentPosition(screenAnchor.row + dir, screenAnchor.column);
        } else {
            var anchor = lead;
        }

        if (isBackwards) {
            var newRange = Range.fromPoints(lead, anchor);
            newRange.cursor = newRange.start;
        } else {
            var newRange = Range.fromPoints(anchor, lead);
            newRange.cursor = newRange.end;
        }

        newRange.desiredColumn = screenLead.column;
        if (!this.selection.inMultiSelectMode) {
            this.selection.addRange(range);
        } else {
            if (skip)
                var toRemove = range.cursor;
        }

        this.selection.addRange(newRange);
        if (toRemove)
            this.selection.substractPoint(toRemove);
    };

    /**
     * Editor.transposeSelections(dir) -> Void
     * - dir: direction to rotate selections
     *
     * contents
     * empty ranges are expanded to word
     **/
    this.transposeSelections = function(dir) {
        var session = this.session;
        var sel = session.multiSelect;
        var all = sel.ranges;

        for (var i = all.length; i--; ) {
            var range = all[i];
            if (range.isEmpty()) {
                var tmp = session.getWordRange(range.start.row, range.start.column);
                range.start.row = tmp.start.row;
                range.start.column = tmp.start.column;
                range.end.row = tmp.end.row;
                range.end.column = tmp.end.column;
            }
        }
        sel.mergeOverlappingRanges();

        var words = [];
        for (var i = all.length; i--; ) {
            var range = all[i];
            words.unshift(session.getTextRange(range));
        }

        if (dir < 0)
            words.unshift(words.pop());
        else
            words.push(words.shift());

        for (var i = all.length; i--; ) {
            var range = all[i];
            var tmp = range.clone();
            session.replace(range, words[i]);
            range.start.row = tmp.start.row;
            range.start.column = tmp.start.column;
        }
    }

    /**
     * Editor.selectMore(dir, skip) -> Void
     * - dir: 1 next, -1 previous
     * - skip: remove active selection range if true
     *
     * finds next occurence of text in active selection
     * and adds it to the selections
     **/
    this.selectMore = function (dir, skip) {
        var session = this.session;
        var sel = session.multiSelect;

        var range = sel.toOrientedRange();
        if (range.isEmpty()) {
            var range = session.getWordRange(range.start.row, range.start.column);
            range.cursor = range.end;
            this.multiSelect.addRange(range);
        }
        var needle = session.getTextRange(range);

        var newRange = find(session, needle, dir);
        if (newRange) {
            newRange.cursor = dir == -1 ? newRange.start : newRange.end;
            this.multiSelect.addRange(newRange);
        }
        if (skip)
            this.multiSelect.substractPoint(range.cursor);
    };
}).call(Editor.prototype);

function isSamePoint(p1, p2) {
    return p1.row == p2.row && p1.column == p2.column;
}

// patch
// adds multicursor support to a session
exports.onSessionChange = function(e) {
    var session = e.session;
    if (!session.multiSelect) {
        session.$selectionMarkers = [];
        session.selection.$initRangeList();
        session.multiSelect = session.selection;
    }
    this.multiSelect = session.multiSelect;

    var oldSession = e.oldSession;
    if (oldSession) {
        // todo use events
        if (oldSession.multiSelect && oldSession.multiSelect.editor == this)
            oldSession.multiSelect.editor = null;

        session.multiSelect.removeEventListener("addRange", this.$onAddRange);
        session.multiSelect.removeEventListener("removeRange", this.$onRemoveRange);
        session.multiSelect.removeEventListener("multiSelect", this.$onMultiSelect);
        session.multiSelect.removeEventListener("singleSelect", this.$onSingleSelect);
    }

    session.multiSelect.on("addRange", this.$onAddRange);
    session.multiSelect.on("removeRange", this.$onRemoveRange);
    session.multiSelect.on("multiSelect", this.$onMultiSelect);
    session.multiSelect.on("singleSelect", this.$onSingleSelect);

    // this.$onSelectionChange = this.onSelectionChange.bind(this);

    if (this.inMultiSelectMode != session.selection.inMultiSelectMode) {
        if (session.selection.inMultiSelectMode)
            this.$onMultiSelect();
        else
            this.$onSingleSelect();
    }
};

/**
 * MultiSelect(editor) -> Void
 *
 * adds multiple selection support to the editor
 * (note: should be called only once for each editor instance)
 **/
function MultiSelect(editor) {
    editor.$onAddRange = editor.$onAddRange.bind(editor);
    editor.$onRemoveRange = editor.$onRemoveRange.bind(editor);
    editor.$onMultiSelect = editor.$onMultiSelect.bind(editor);
    editor.$onSingleSelect = editor.$onSingleSelect.bind(editor);

    exports.onSessionChange.call(editor, editor);
    editor.on("changeSession", exports.onSessionChange.bind(editor));

    editor.on("mousedown", onMouseDown);
    editor.commands.addCommands(exports.commands.defaultCommands);

    addAltCursorListeners(editor);
}

function addAltCursorListeners(editor){
    var el = editor.textInput.getElement();
    var altCursor = false;
    var contentEl = editor.renderer.content;
    el.addEventListener("keydown", function(e) {
        if (e.keyCode == 18 && !(e.ctrlKey || e.shiftKey || e.metaKey)) {
            if (!altCursor) {
                contentEl.style.cursor = "crosshair";
                altCursor = true;
            }
        } else if (altCursor) {
            contentEl.style.cursor = "";
        }
    });

    el.addEventListener("keyup", reset);
    el.addEventListener("blur", reset);
    function reset() {
        if (altCursor) {
            contentEl.style.cursor = "";
            altCursor = false;
        }
    }
}

exports.MultiSelect = MultiSelect;

});


text:
#ifndef TLIST_H
#define TLIST_H

#include "nodes/relation.h"

extern TargetEntry *tlist_member(Node *node, List *targetlist);
extern TargetEntry *tlist_member_ignore_relabel(Node *node, List *targetlist);
extern TargetEntry *tlist_member_match_var(Var *var, List *targetlist);

extern List *flatten_tlist(List *tlist);
extern List *add_to_flat_tlist(List *tlist, List *exprs);

extern List *get_tlist_exprs(List *tlist, bool includeJunk);
extern bool tlist_same_datatypes(List *tlist, List *colTypes, bool junkOK);

extern TargetEntry *get_sortgroupref_tle(Index sortref,
					 List *targetList);
extern TargetEntry *get_sortgroupclause_tle(SortGroupClause *sgClause,
						List *targetList);
extern Node *get_sortgroupclause_expr(SortGroupClause *sgClause,
						 List *targetList);
extern List *get_sortgrouplist_exprs(List *sgClauses,
						List *targetList);

extern Oid *extract_grouping_ops(List *groupClause);
extern AttrNumber *extract_grouping_cols(List *groupClause, List *tlist);
extern bool grouping_is_sortable(List *groupClause);
extern bool grouping_is_hashable(List *groupClause);

#endif   /* TLIST_H */


text:
export default class Armor implements Elixr.Api.ViewModels.ArmorViewModel {

    author: Elixr.Api.ViewModels.PlayerViewModel;
    cost = 0;
    createdAtMS = 0;
    description = "";
    enchantments: Elixr.Api.ViewModels.EnchantmentViewModel[];
    equipmentId = 0;
    imageUrl = "";
    name = "";
    weightInPounds = 0;
    defenseBonus = 0;
    speedPenalty = 0;

    get roundsToDon(): number {
        if (this.weightInPounds < 25) {
            return 5;
        }
        if (this.weightInPounds < 45) {
            return 10;
        }
        return 20;
    }
    get bestowsDisadvantage(): boolean {
        return this.weightInPounds >= 45;
    }

}


text:
<?php

namespace Soluble\FlexStore\Writer;

use Soluble\FlexStore\Writer\Http\SimpleHeaders;

abstract class AbstractSendableWriter extends AbstractWriter implements HttpSendableInterface
{
    /**
     * Return (default) headers for sending store data via http.
     *
     * @return \Soluble\FlexStore\Writer\Http\SimpleHeaders
     */
    abstract public function getHttpHeaders();

    /**
     * Send the store data via http.
     *
     * @throws \Exception if error occurs in getData
     *
     * @param SimpleHeaders $headers
     * @param bool          $die_after
     */
    public function send(SimpleHeaders $headers = null, $die_after = true)
    {
        if ($headers === null) {
            $headers = $this->getHttpHeaders();
        }

        ob_end_clean();

        try {
            $data = $this->getData();
        } catch (\Exception $e) {
            throw $e;
        }
        $headers->outputHeaders($replace = true);
        echo $data;
        if ($die_after) {
            die();
        }
    }
}


text:
@implementation LocationCardFlowLayout

- (void)prepareLayout {
    [super prepareLayout];

    CGFloat locationCardWidth = self.collectionView.frame.size.width - 2 * kLocationCardHorizontalInset;
    CGFloat locationCardHeigth = self.collectionView.frame.size.height - 2 * kLocationCardVerticalInset;
    self.itemSize = CGSizeMake(locationCardWidth,
                               locationCardHeigth);

    self.minimumLineSpacing = kLocationCardHorizontalInset / 2;
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.sectionInset = UIEdgeInsetsMake(0.0,
                                         kLocationCardHorizontalInset,
                                         0.0,
                                         kLocationCardHorizontalInset);
}

- (CGFloat)pageWidth {
    return self.itemSize.width + self.minimumLineSpacing;
}

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
                                 withScrollingVelocity:(CGPoint)velocity {
    CGFloat rawPageValue = self.collectionView.contentOffset.x / self.pageWidth;
    CGFloat currentPage = (velocity.x > 0.0) ? floor(rawPageValue) : ceil(rawPageValue);
    CGFloat nextPage = (velocity.x > 0.0) ? ceil(rawPageValue) : floor(rawPageValue);

    BOOL pannedLessThanAPage = fabs(1 + currentPage - rawPageValue) > 0.5;
    BOOL flicked = fabs(velocity.x) > [self flickVelocity];
    if (pannedLessThanAPage && flicked) {
        proposedContentOffset.x = nextPage * self.pageWidth;
    } else {
        proposedContentOffset.x = round(rawPageValue) * self.pageWidth;
    }

    return proposedContentOffset;
}

- (CGFloat)flickVelocity {
    return kLocationCardFlickVelocity;
}

@end


text:
package net.sf.mmm.util.value.impl.pojo2;

import java.util.List;

/**
 * This is some code only used for {@link net.sf.mmm.util.value.impl.ComposedValueConverterTest}.
 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @since 1.1.0
 */
@SuppressWarnings("all")
public class MyPojoImpl implements MyPojo {

  private List<SubPojo> subPojos;

  @Override
  public List<SubPojo> getSubPojos() {

    return this.subPojos;
  }

  public void setSubPojos(List<SubPojo> subPojos) {

    this.subPojos = subPojos;
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2016 Red Hat, Inc. and/or its affiliates.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>kie-wb-common-examples-screen</artifactId>
    <groupId>org.kie.workbench.screens</groupId>
    <version>7.40.0-SNAPSHOT</version>
  </parent>

  <artifactId>kie-wb-common-examples-screen-backend</artifactId>
  <packaging>jar</packaging>

  <name>Kie Workbench - Common - Examples Backend</name>
  <description>Kie Workbench - Common - Examples Backend</description>

  <properties>
    <java.module.name>org.kie.wb.common.examples.screen.backend</java.module.name>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.kie.workbench.screens</groupId>
      <artifactId>kie-wb-common-examples-screen-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.eclipse.jgit</groupId>
      <artifactId>org.eclipse.jgit</artifactId>
      <exclusions>
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-bus</artifactId>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-model</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-security-server</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-backend-server</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-io</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-nio2-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-nio2-jgit</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-nio2-model</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-commons</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.soup</groupId>
      <artifactId>kie-soup-commons</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-project-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-structure-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-services-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-services-backend</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-project-backend</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.services</groupId>
      <artifactId>kie-wb-common-services-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.screens</groupId>
      <artifactId>kie-wb-common-project-editor-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.services</groupId>
      <artifactId>kie-wb-common-services-backend</artifactId>
    </dependency>

    <!-- Test dependencies -->
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-structure-backend</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.playground</groupId>
      <artifactId>kie-all-playground</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-testing-utils</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
      <resource>
        <directory>src/main/filtered-resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
  </build>

</project>


text:
from enum import Enum

class AccessRights(str, Enum):
    """Access rights of an authorization
    """

    manage = "Manage"
    send = "Send"
    listen = "Listen"

class EntityAvailabilityStatus(str, Enum):
    """Availability status of the entity
    """

    available = "Available"
    limited = "Limited"
    renaming = "Renaming"
    restoring = "Restoring"
    unknown = "Unknown"

class EntityStatus(str, Enum):
    """Status of a Service Bus resource
    """

    active = "Active"
    creating = "Creating"
    deleting = "Deleting"
    disabled = "Disabled"
    receive_disabled = "ReceiveDisabled"
    renaming = "Renaming"
    restoring = "Restoring"
    send_disabled = "SendDisabled"
    unknown = "Unknown"

class MessagingSku(str, Enum):
    """The SKU for the messaging entity.
    """

    basic = "Basic"
    standard = "Standard"
    premium = "Premium"

class NamespaceType(str, Enum):
    """The type of entities the namespace can contain.
    """

    messaging = "Messaging"
    notification_hub = "NotificationHub"
    mixed = "Mixed"
    event_hub = "EventHub"
    relay = "Relay"


text:
<?php

namespace Solarium\Tests\Core\Client\Adapter;
use Solarium\Core\Client\Adapter\Http as HttpAdapter;
use Solarium\Core\Client\Request;
use Solarium\Core\Client\Endpoint;
use Solarium\Exception\HttpException;

class HttpTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var HttpAdapter
     */
    protected $adapter;

    public function setUp()
    {
        $this->adapter = new HttpAdapter();
    }

    public function testExecute()
    {
        $data = 'test123';

        $request = new Request();
        $request->setMethod(Request::METHOD_GET);

        $endpoint = new Endpoint();

        $mock = $this->getMock('Solarium\Core\Client\Adapter\Http', array('getData','check'));
        $mock->expects($this->once())
             ->method('getData')
             ->with($this->equalTo('http://127.0.0.1:8983/solr/?'), $this->isType('resource'))
             ->will($this->returnValue(array($data, array('HTTP 1.1 200 OK'))));

        $mock->execute($request, $endpoint);
    }

    public function testExecuteErrorResponse()
    {
        $data = 'test123';

        $request = new Request();
        $endpoint = new Endpoint();

        $mock = $this->getMock('Solarium\Core\Client\Adapter\Http', array('getData','check'));
        $mock->expects($this->once())
             ->method('getData')
             ->with($this->equalTo('http://127.0.0.1:8983/solr/?'), $this->isType('resource'))
             ->will($this->returnValue(array($data, array('HTTP 1.1 200 OK'))));
        $mock->expects($this->once())
             ->method('check')
             ->will($this->throwException(new HttpException("HTTP request failed")));

        $this->setExpectedException('Solarium\Exception\HttpException');
        $mock->execute($request, $endpoint);
    }

    public function testCheckError()
    {
        $this->setExpectedException('Solarium\Exception\HttpException');
        $this->adapter->check(false, array());

    }

    public function testCheckOk()
    {
        $value = $this->adapter->check('dummydata',array('HTTP 1.1 200 OK'));

        $this->assertEquals(
            null,
            $value
        );
    }

    public function testCreateContextGetRequest()
    {
        $timeout = 13;
        $method = Request::METHOD_HEAD;

        $request = new Request();
        $request->setMethod($method);
        $endpoint = new Endpoint();
        $endpoint->setTimeout($timeout);

        $context = $this->adapter->createContext($request, $endpoint);

        $this->assertEquals(
            array('http' => array('method' => $method, 'timeout' => $timeout)),
            stream_context_get_options($context)
        );
    }

    public function testCreateContextWithHeaders()
    {
        $timeout = 13;
        $method = Request::METHOD_HEAD;
        $header1 = 'Content-Type: text/xml; charset=UTF-8';
        $header2 = 'X-MyHeader: dummyvalue';

        $request = new Request();
        $request->setMethod($method);
        $request->addHeader($header1);
        $request->addHeader($header2);
        $endpoint = new Endpoint();
        $endpoint->setTimeout($timeout);

        $context = $this->adapter->createContext($request, $endpoint);

        $this->assertEquals(
            array('http' => array('method' => $method, 'timeout' => $timeout, 'header' => $header1."\r\n".$header2)),
            stream_context_get_options($context)
        );
    }

    public function testCreateContextPostRequest()
    {
        $timeout = 13;
        $method = Request::METHOD_POST;
        $data = 'test123';

        $request = new Request();
        $request->setMethod($method);
        $request->setRawData($data);
        $endpoint = new Endpoint();
        $endpoint->setTimeout($timeout);

        $context = $this->adapter->createContext($request, $endpoint);

        $this->assertEquals(
            array('http' => array('method' => $method, 'timeout' => $timeout, 'content' => $data, 'header' => 'Content-Type: text/xml; charset=UTF-8')),
            stream_context_get_options($context)
        );
    }

    public function testCreateContextPostFileRequest()
    {
        $timeout = 13;
        $method = Request::METHOD_POST;
        $data = 'test123';

        $request = new Request();
        $request->setMethod($method);
        $request->setFileUpload(__FILE__);
        $endpoint = new Endpoint();
        $endpoint->setTimeout($timeout);

        $context = $this->adapter->createContext($request, $endpoint);

        $this->assertEquals(
            array('http' => array('method' => $method, 'timeout' => $timeout, 'content' => file_get_contents(__FILE__), 'header' => 'Content-Type: multipart/form-data')),
            stream_context_get_options($context)
        );
    }

    public function testCreateContextWithAuthorization()
    {
        $timeout = 13;
        $method = Request::METHOD_HEAD;

        $request = new Request();
        $request->setMethod($method);
        $request->setAuthentication('someone', 'S0M3p455');

        $endpoint = new Endpoint();
        $endpoint->setTimeout($timeout);

        $context = $this->adapter->createContext($request, $endpoint);

        $this->assertEquals(
            array('http' => array('method' => $method, 'timeout' => $timeout, 'header' => 'Authorization: Basic c29tZW9uZTpTME0zcDQ1NQ==')),
            stream_context_get_options($context)
        );
    }

}


text:
package budgetApplication.BudgetSummary.DataAccess;

import budgetApplication.dataContracts.*;
import static budgetApplication.baseClasses.Utilities.getCategoryAsEnum;
import budgetApplication.baseClasses.DatabaseFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class ItemDataAccess implements AutoCloseable {

    public List<Item> getAllItemsByBudgetId(int budgetId) throws Exception {
        try {
            String query = "SELECT i.id, i.name, i.category, i.amount, SUM(t.amount) as spent "
                         + "FROM item i "
                         + "LEFT JOIN transaction t ON i.id = t.itemId "
                         + "WHERE budgetId = ? "
                         + "GROUP BY i.id";

            Item item;
            List<Item> items;
            ResultSet data;
            try (Connection mySqlConnection = DatabaseFactory.getMySqlConnection()) {

                PreparedStatement statement;
                statement = mySqlConnection.prepareStatement(query);
                statement.setInt(1, budgetId);
                data = statement.executeQuery();

                items = new ArrayList();
                while(data.next()) {
                    item = new Item();
                    item.setId(data.getInt("id"));
                    item.setName(data.getString("name"));
                    item.setCategory(getCategoryAsEnum(data.getString("category")));
                    item.setAmount(data.getDouble("amount"));
                    item.setSpent(data.getDouble("spent"));
                    items.add(item);
                }

                mySqlConnection.close();
            }

            return items;
        }
        catch (Exception ex) {
            throw ex;
        }
    }

    public Item getItemById(int id) throws Exception {
        try {
            String query = "SELECT i.id as itemId, i.name, i.category, i.amount as planned, SUM(t.amount) as spent "
                         + "FROM item i "
                         + "LEFT JOIN transaction t ON i.id = t.itemId "
                         + "WHERE i.id = ? "
                         + "GROUP BY i.id";

            Item item = new Item();
            ResultSet data;
            try (Connection mySqlConnection = DatabaseFactory.getMySqlConnection()) {

                PreparedStatement statement;
                statement = mySqlConnection.prepareStatement(query);
                statement.setInt(1, id);
                data = statement.executeQuery();

                while(data.next()) {
                    item.setId(data.getInt("itemId"));
                    item.setName(data.getString("name"));
                    item.setCategory(getCategoryAsEnum(data.getString("category")));
                    item.setAmount(data.getDouble("planned"));
                    item.setSpent(data.getDouble("spent"));
                }

                mySqlConnection.close();
            }

            return item;
        }
        catch (Exception ex) {
            throw ex;
        }
    }

    public int getItemIdByName(String name) throws Exception {
        try {
            String query = "SELECT id "
                         + "FROM item "
                         + "WHERE name = ?";
            int id = 0;
            ResultSet data;
            try (Connection mySqlConnection = DatabaseFactory.getMySqlConnection()) {

                PreparedStatement statement;
                statement = mySqlConnection.prepareStatement(query);
                statement.setString(1, name);
                data = statement.executeQuery();

                while(data.next()) {
                    id = data.getInt("id");
                }

                mySqlConnection.close();
            }

            return id;
        }
        catch (Exception ex) {
            throw ex;
        }
    }

    public void insertItemByBudgetId(Item item, int budgetId) throws Exception {
        try {
            String query = "INSERT INTO item (budgetId, name, category, amount) VALUES (?, ?, ?, ?)";

            try (Connection mySqlConnection = DatabaseFactory.getMySqlConnection()) {

                PreparedStatement statement;
                statement = mySqlConnection.prepareStatement(query);
                statement.setInt(1, budgetId);
                statement.setString(2, item.getName());
                statement.setString(3, item.getCategory().name());
                statement.setDouble(4, item.getAmount());
                statement.executeUpdate();
                mySqlConnection.close();
            }
        }
        catch (Exception ex) {
            throw ex;
        }
    }

    public void updateItem(Item item) throws Exception {
        try {
            String query = "UPDATE item SET name = ?, amount = ? WHERE id = ?";

            try (Connection mySqlConnection = DatabaseFactory.getMySqlConnection()) {

                PreparedStatement statement;
                statement = mySqlConnection.prepareStatement(query);
                statement.setString(1, item.getName());
                statement.setDouble(2, item.getAmount());
                statement.setInt(3, item.getId());
                statement.executeUpdate();
                mySqlConnection.close();
            }
        }
        catch (Exception ex) {
            throw ex;
        }
    }

    public void deletItemById(int id) throws Exception {
        try {

            String deleteFromItemQuery = "DELETE FROM item WHERE id = ?";

            try (Connection mySqlConnection = DatabaseFactory.getMySqlConnection()) {

                PreparedStatement statement;
                statement = mySqlConnection.prepareStatement(deleteFromItemQuery);
                statement.setInt(1, id);
                statement.executeUpdate();
                mySqlConnection.close();
            }
        }
        catch (Exception ex) {
            throw ex;
        }
    }

    public int getLastIdByBudgetId(int budgetId) throws Exception {

        try {
            String query = "SELECT MAX(i.id) as maxId "
                         + "FROM item i "
                         + "WHERE i.budgetId = ?";

            int maxId = 0;
            ResultSet data;
            try (Connection mySqlConnection = DatabaseFactory.getMySqlConnection()) {

                PreparedStatement statement;
                statement = mySqlConnection.prepareStatement(query);
                statement.setInt(1, budgetId);
                data = statement.executeQuery();

                while(data.next()) {
                    maxId = data.getInt("maxId");
                }

                mySqlConnection.close();
            }

            return maxId;
        }
        catch (Exception ex) {
            throw ex;
        }
    }

    @Override
    public void close() throws Exception {
        try {

        }
        catch(Exception ex) {
            throw ex;
        }
    }
}


text:
<component name="ArtifactManager">
  <artifact type="exploded-war" build-on-make="true" name="fincalcms:war exploded">
    <output-path>$PROJECT_DIR$/out/artifacts/fincalcms_war_exploded</output-path>
    <root id="root">
      <element id="javaee-facet-resources" facet="fincalcms/web/Web" />
      <element id="directory" name="WEB-INF">
        <element id="directory" name="classes">
          <element id="module-output" name="fincalcms" />
        </element>
        <element id="directory" name="lib">
          <element id="library" level="project" name="jfinal-2.2-bin-with-src" />
        </element>
      </element>
    </root>
  </artifact>
</component>


text:
namespace blink {

BeginFilterDisplayItem::BeginFilterDisplayItem(DisplayItemClient client, PassRefPtr<ImageFilter> imageFilter, const LayoutRect& bounds)
    : PairedBeginDisplayItem(client, BeginFilter)
    , m_imageFilter(imageFilter)
    , m_bounds(bounds)
{
}

BeginFilterDisplayItem::BeginFilterDisplayItem(DisplayItemClient client, PassRefPtr<ImageFilter> imageFilter, const LayoutRect& bounds, PassOwnPtr<WebFilterOperations> webFilterOperations)
    : PairedBeginDisplayItem(client, BeginFilter)
    , m_imageFilter(imageFilter)
    , m_webFilterOperations(webFilterOperations)
    , m_bounds(bounds)
{
}

void BeginFilterDisplayItem::replay(GraphicsContext* context)
{
    context->save();
    FloatRect boundaries = mapImageFilterRect(m_imageFilter.get(), m_bounds);
    context->translate(m_bounds.x().toFloat(), m_bounds.y().toFloat());
    boundaries.move(-m_bounds.x().toFloat(), -m_bounds.y().toFloat());
    context->beginLayer(1, SkXfermode::kSrcOver_Mode, &boundaries, ColorFilterNone, m_imageFilter.get());
    context->translate(-m_bounds.x().toFloat(), -m_bounds.y().toFloat());
}

void BeginFilterDisplayItem::appendToWebDisplayItemList(WebDisplayItemList* list) const
{
    list->appendFilterItem(*m_webFilterOperations, FloatRect(m_bounds));
}

bool BeginFilterDisplayItem::drawsContent() const
{
    // A filter with no inputs must produce its own content.
    return m_imageFilter->countInputs() == 0;
}

#ifndef NDEBUG
void BeginFilterDisplayItem::dumpPropertiesAsDebugString(WTF::StringBuilder& stringBuilder) const
{
    DisplayItem::dumpPropertiesAsDebugString(stringBuilder);
    stringBuilder.append(WTF::String::format(", filter bounds: [%f,%f,%f,%f]",
        m_bounds.x().toFloat(), m_bounds.y().toFloat(), m_bounds.width().toFloat(), m_bounds.height().toFloat()));
}
#endif

void EndFilterDisplayItem::replay(GraphicsContext* context)
{
    context->endLayer();
    context->restore();
}

void EndFilterDisplayItem::appendToWebDisplayItemList(WebDisplayItemList* list) const
{
    list->appendEndFilterItem();
}

} // namespace blink


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ripartites tricholoma var. pumila

### Remarks
null


text:
package net.kwmt27.codesearch.model.rx;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.HttpException;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.functions.Func1;

public class RxErrorHandlingCallAdapterFactory extends CallAdapter.Factory {

    private final RxJavaCallAdapterFactory mOriginal;

    private RxErrorHandlingCallAdapterFactory() {
        mOriginal = RxJavaCallAdapterFactory.create();
    }

    public static CallAdapter.Factory create() {
        return new RxErrorHandlingCallAdapterFactory();
    }

    @Override
    public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
        return new RxCallAdapterWrapper(retrofit, mOriginal.get(returnType, annotations, retrofit));
    }

    private static class RxCallAdapterWrapper implements CallAdapter<Observable<?>> {
        private final Retrofit mRetrofit;
        private final CallAdapter<?> mWrapped;

        public RxCallAdapterWrapper(Retrofit retrofit, CallAdapter<?> wrapped) {
            mRetrofit = retrofit;
            mWrapped = wrapped;
        }

        @Override
        public Type responseType() {
            return mWrapped.responseType();
        }

        @Override
        public <R> Observable<?> adapt(Call<R> call) {
            return ((Observable) mWrapped.adapt(call))
                    .onErrorResumeNext(new Func1<Throwable, Observable>() {
                        @Override
                        public Observable call(Throwable throwable) {
                            return Observable.error(asRetrofitException(throwable));
                        }
                    });
        }

        private RetrofitException asRetrofitException(Throwable throwable) {
            if (throwable instanceof HttpException) {
                Response response = ((HttpException) throwable).response();
                return RetrofitException.httpError(response.raw().request().url().toString(), response, throwable, mRetrofit);
            }
            if (throwable instanceof IOException) {
                return RetrofitException.networkError((IOException) throwable);
            }
            return RetrofitException.unexpectedError(throwable);
        }

    }

}


text:
package com.exp.tracker.services.impl;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ JpaAuthServiceTests.class, JpaExpenseServiceTests.class,
		JpaRoleServiceTests.class, JpaSettlementServiceTests.class,
		JpaUserServiceTests.class, JasperReportGenerationServiceTests.class,
		ReportControllerTests.class, GroupServiceImplTests.class,
		TestPasswordgeneratorTests.class })
public class ExpenseTrackerTestSuite {

}


text:
#include <oBasis/oInterface.h>
#include <oBase/types.h>

// Manipulators are geometries that are used to visual manipulate
// the position, scale and rotation of other geometries.  This
// idea is encapsulated here by abstractly manipulating a transform
// that represents the other geometry.  The end result is a series
// of lines that can be drawn to control the maniuplation.  For
// a higher level visual manipulator look at oGPUManipulators use
// of oManipulator.
interface oManipulator : oInterface
{
	static const unsigned int ROTATION_CIRCLE_VCOUNT = 360;
	static const unsigned int ROTATION_PICK_TORUS_DIVIDE = 120;
	static const unsigned int ROTATION_PICK_TORUS_FACET = 8;
	static const unsigned int ROTATION_PICK_ARCBALL_VCOUNT = 64;

	enum AXIS
	{
		X,
		Y,
		Z,
		SCREEN,
		FREE, //only for rotation, arcball
		NUM_AXES,
	};

	struct DESC
	{
		enum MODE
		{
			OBJECT,
			WORLD,
			NUM_MODES,
		};

		enum TYPE
		{
			TRANSLATION,
			SCALE,
			ROTATION,
			NUM_TYPES,
		};

		DESC()
			: Type(TRANSLATION)
			, Mode(WORLD)
			, PickWidth(0.02f)
			, ManipularScale(1.0f)
		{}
		TYPE Type;
		MODE Mode;
		float PickWidth;
		float ManipularScale;
	};

	virtual void GetDesc(DESC* _pDesc) const = 0;

	virtual void GetTransform(float4x4 *_pTransform) const = 0;

	// This should be called whenever the axis is changed
	virtual void BeginManipulation(AXIS _Axis, const float2& _ScreenPosition) = 0;
	virtual void EndManipulation() = 0;

	// Updates the transform based on new matrices and scren position
	virtual void Update(const float2& _ScreenPosition, const float4x4 &_World, const float4x4 &_View, const float4x4 &_Proj) = 0;

	// Maximum sizes of geometry computed for allocation purposes
	virtual void GetMaxSizes(size_t &_maxNumLines, size_t &_maxNumPickGeometry) const = 0;

	// Returns the visual lines that visualize the axis
	virtual void GetLines(AXIS _Axis, float3 *_lines, size_t &_numWritten) const = 0;

	// Returns a geometry that represents the lines but is larger for picking
	virtual void GetLinesPickGeometry(AXIS _Axis, float3 *_vertices, size_t &_numWritten) const = 0;

	// Returns the transform of the cap which usually contains a translation and scale
	virtual void GetCapTransform(AXIS _Axis, float4x4 &_transforms) const = 0;
	virtual bool IsClipped(AXIS _Axis) const = 0;
};

bool oManipulatorCreate(const oManipulator::DESC& _Desc, oManipulator** _ppManipulator);

#endif // oManipulator_h


text:
import AV from '../libs/leanengine.min'
import store from '../utils/store'
import formatDate from '../utils/formatDate'
import calculate from '../utils/calculate'
import called from '../utils/called'
import { casting, loading, score } from '../common/strings'
import {
  ON_PANEL_LOAD_START,
  ON_PANEL_LOAD_SUCCESS,
  ON_PANEL_LOAD_FAILURE,
} from '../common/constants'

export default target => {
  const exchangeQuery = new AV.Query('Exchange')

  wx.setNavigationBarTitle({ title: score })
  wx.showLoading({ title: loading })
  store.dispatch({ type: ON_PANEL_LOAD_START, payload: target})

  exchangeQuery.get(target)
  .then(exchange => {
    const exchangeToJSON = exchange.toJSON()

    exchangeToJSON.formatCreatedAt = formatDate(new Date(exchangeToJSON.createdAt))
    exchangeToJSON.duration = calculate(exchangeToJSON.createdAt).duration
    exchangeToJSON.unixDuration = calculate(exchangeToJSON.createdAt).unixDuration
    exchangeToJSON.called = called(exchangeToJSON.unixDuration)

    store.dispatch({ type: ON_PANEL_LOAD_SUCCESS, payload: exchangeToJSON })
    wx.hideLoading()
  })
  .catch(err => {
    store.dispatch({ type: ON_PANEL_LOAD_FAILURE, payload: err })
    wx.hideLoading()
  })
}


text:
package com.github.mahui53541.blog.mapper;

import com.github.mahui53541.blog.po.Post;
import com.github.mahui53541.blog.util.base.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;

import java.util.List;

/**
 * 文章
 * @author 马辉
 * @since JDK1.8
 * @history 2017年4月7日下午7:33:36 马辉 新建
 */
public interface PostMapper extends BaseMapper<Post,Integer> {
    /**
     * 分页查询post,亦可搜索
     * @param rowBounds
     * @param categoryId
     * @param searchText
     * @return
     */
    List<Post> queryByPage(@Param("rowBounds") RowBounds rowBounds,@Param("categoryId")Integer categoryId ,@Param("searchText")String searchText);

    /**
     * 文章管理模块查询
     * @param rowBounds
     * @param userId
     * @return
     */
    List<Post> queryByUserId(@Param("rowBounds") RowBounds rowBounds,@Param("userId")Integer userId);

    /**
     * 评论管理管理模块查询不分页
     * @param categoryId
     * @return
     */
    List<Post> queryByCategoryId(@Param("categoryId")Integer categoryId);

    /**
     * 浏览次数加一
     * @param id
     */
    void readTimesPlusOne(@Param("id") Integer id);

    /**
     * 评论数加一
     * @param id
     */
    void commentTimesPlusOne(@Param("id") Integer id);

    /**
     * 评论数减一
     * @param id
     */
    void commentTimesMinusOne(@Param("id") Integer id);

    /**
     * 查询文章数
     * @return
     */
    int countAll();

    /**
     * 浏览数
     * @return
     */
    int countReadTimes();

    /**
     * 评论查询post
     * @param id
     * @return
     */
    Post queryByCommentId(Integer id);
}


text:
using FP.PostSharpSamples.UI.Business;
using System;

namespace EventHandlerLogging
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var controller = new TestController();
                controller.LoadData();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            Console.ReadLine();
        }
    }
}


text:
require 'spec_helper'

# TODO(alexstephen): Reformat tests to use nested describe blocks
# TODO(alexstephen): Add title == name tests
# Test Matrix:
#
# +--------------------------------------------------------+
# | Action  | Exists | Changes | Success | Result          |
# +--------------------------------------------------------+
# | create  | Y      | Y       | Y       | Edit            |
# | create  | Y      | Y       | N       | Fail            |
# | create  | Y      | N       | Y       | Fetch (no-op)   |
# | create  | Y      | N       | N       | Fail            |
# | create  | N      | Y       | Y       | Create          |
# | create  | N      | Y       | N       | Fail            |
# +--------------------------------------------------------+
# | delete  | Y      | Y       | Y       | Delete          |
# | delete  | Y      | Y       | N       | Fail            |
# | delete  | N      | Y       | Y       | Fail (no delete)|
# | delete  | N      | Y       | N       | Fail            |
# +--------------------------------------------------------+
# TODO(alexstephen): Add tests for manage
# TODO(alexstephen): Add tests for modify
context 'gspanner_instance_config' do
  context 'resource exists' do
    # Ensure ignore: resource exists, no change
    context 'no changes == no action' do
      # Ensure ignore: resource exists, no change, no name, pass
      context 'title == name (pass)' do
        # TODO(alexstephen): Implement new test format.
      end

      # Ensure ignore: resource exists, no change, has name, pass
      context 'title != name (pass)' do
        # TODO(alexstephen): Implement new test format.
      end
    end

    # Ensure ignore: resource exists, changes
    context 'changes == action' do
      # Ensure ignore: resource exists, changes, no name, fail
      context 'title == name (fail)' do
        # TODO(alexstephen): Implement new test format.
        subject { -> { raise '[placeholder] This should fail.' } }
        it { is_expected.to raise_error(RuntimeError, /placeholder/) }
      end

      # Ensure ignore: resource exists, changes, has name, fail
      context 'title != name (fail)' do
        # TODO(alexstephen): Implement new test format.
        subject { -> { raise '[placeholder] This should fail.' } }
        it { is_expected.to raise_error(RuntimeError, /placeholder/) }
      end
    end
  end

  context 'resource missing' do
    # Ensure ignore: resource missing, ignore, no name, fail
    context 'title == name (fail)' do
      # TODO(alexstephen): Implement new test format.
      subject { -> { raise '[placeholder] This should fail.' } }
      it { is_expected.to raise_error(RuntimeError, /placeholder/) }
    end

    # Ensure ignore: resource missing, ignore, has name, fail
    context 'title != name (fail)' do
      # TODO(alexstephen): Implement new test format.
      subject { -> { raise '[placeholder] This should fail.' } }
      it { is_expected.to raise_error(RuntimeError, /placeholder/) }
    end
  end

  def expand_variables(template, data, extra_data = {})
    Google::GSPANNER::InstanceConfig
      .action_class.expand_variables(template, data, extra_data)
  end

  def encode_request(resource)
    Google::GSPANNER::InstanceConfig
      .action_class.encode_request(resource)
  end

  def expect_network_get_success(id, data = {})
    id_data = data.fetch(:name, '').include?('title') ? 'title' : 'name'
    body = load_network_result("success#{id}~#{id_data}.yaml").to_json

    request = double('request')
    allow(request).to receive(:send).and_return(http_success(body))

    debug_network "!! GET #{self_link(uri_data(id).merge(data))}"
    expect(Google::Spanner::Network::Get).to receive(:new)
      .with(self_link(uri_data(id).merge(data)),
            instance_of(Google::FakeAuthorization)) do |args|
      debug_network ">> GET #{args}"
      request
    end
  end

  def http_success(body)
    response = Net::HTTPOK.new(1.0, 200, 'OK')
    response.body = body
    response.instance_variable_set(:@read, true)
    response
  end

  def expect_network_get_failed(id, data = {})
    request = double('request')
    allow(request).to receive(:send).and_return(http_failed_object_missing)

    debug_network "!! #{self_link(uri_data(id).merge(data))}"
    expect(Google::Spanner::Network::Get).to receive(:new)
      .with(self_link(uri_data(id).merge(data)),
            instance_of(Google::FakeAuthorization)) do |args|
      debug_network ">> GET [failed] #{args}"
      request
    end
  end

  def http_failed_object_missing
    Net::HTTPNotFound.new(1.0, 404, 'Not Found')
  end

  def load_network_result(file)
    results = File.join(File.dirname(__FILE__), 'data', 'network',
                        'gspanner_instance_config', file)
    debug("Loading result file: #{results}")
    raise "Network result data file #{results}" unless File.exist?(results)
    data = YAML.safe_load(File.read(results))
    raise "Invalid network results #{results}" unless data.class <= Hash
    data
  end

  def debug(message)
    puts(message) if ENV['RSPEC_DEBUG']
  end

  def debug_network(message)
    puts("Network #{message}") \
      if ENV['RSPEC_DEBUG'] || ENV['RSPEC_HTTP_VERBOSE']
  end

  def collection(data)
    URI.join(
      'https://spanner.googleapis.com/v1/',
      expand_variables(
        'projects/{{project}}/instanceConfigs',
        data
      )
    )
  end

  def self_link(data)
    URI.join(
      'https://spanner.googleapis.com/v1/',
      expand_variables(
        'projects/{{project}}/instanceConfigs/{{name}}',
        data
      )
    )
  end

  # Creates variable test data to comply with self_link URI parameters
  def uri_data(id)
    {
      project: GoogleTests::Constants::IC_PROJECT_DATA[(id - 1) \
        % GoogleTests::Constants::IC_PROJECT_DATA.size],
      name: GoogleTests::Constants::IC_NAME_DATA[(id - 1) \
        % GoogleTests::Constants::IC_NAME_DATA.size]
    }
  end

  def build_cred
    <<-CRED
    gauth_credential 'mycred' do
      action :serviceaccount
      path '/home'
      scopes [
        'test_path'
      ]
    end
    CRED
  end

  # Creates a test recipe file and runs a block before destroying the file
  def apply_recipe(recipe)
    # Creates a random string name
    recipe_name = "recipe~test~#{(0...8).map { (65 + rand(26)).chr }.join}"
    recipe_loc = File.join(File.dirname(__FILE__), '..', 'recipes',
                           "#{recipe_name}.rb")

    File.open(recipe_loc, 'w') do |file|
      file.write([build_cred, recipe].join("\n"))
    end
    recipe_path = "google-gspanner::#{recipe_name}"
    begin
      yield recipe_path
    ensure
      File.delete(recipe_loc)
    end
  end
end


text:
<?xml version="1.0"?>
<scene id="1">
	<attribute name="Name" value="" />
	<attribute name="Time Scale" value="1" />
	<attribute name="Smoothing Constant" value="50" />
	<attribute name="Snap Threshold" value="5" />
	<attribute name="Elapsed Time" value="0" />
	<attribute name="Next Replicated Node ID" value="8" />
	<attribute name="Next Replicated Component ID" value="8" />
	<attribute name="Next Local Node ID" value="16777221" />
	<attribute name="Next Local Component ID" value="16777276" />
	<attribute name="Variables" />
	<attribute name="Variable Names" value="" />
	<component type="Octree" id="1" />
	<component type="DebugRenderer" id="2" />
	<node id="3">
		<attribute name="Is Enabled" value="true" />
		<attribute name="Name" value="Mushroom" />
		<attribute name="Tags" />
		<attribute name="Position" value="0 0 0" />
		<attribute name="Rotation" value="0.966061 0 0.258313 0" />
		<attribute name="Scale" value="1 1 1" />
		<attribute name="Variables" />
		<component type="StaticModel" id="3">
			<attribute name="Model" value="Model;Models/Mushroom.mdl" />
			<attribute name="Material" value="Material;Materials/MushroomWind.xml" />
			<attribute name="Cast Shadows" value="true" />
		</component>
	</node>
	<node id="4">
		<attribute name="Is Enabled" value="true" />
		<attribute name="Name" value="Sun" />
		<attribute name="Tags" />
		<attribute name="Position" value="0 2.5987 0" />
		<attribute name="Rotation" value="0.934981 0.354699 0 0" />
		<attribute name="Scale" value="1 1 1" />
		<attribute name="Variables" />
		<component type="Light" id="4">
			<attribute name="Light Type" value="Directional" />
			<attribute name="Color" value="1 0.7 0.4 1" />
			<attribute name="Cast Shadows" value="true" />
		</component>
	</node>
	<node id="5">
		<attribute name="Is Enabled" value="true" />
		<attribute name="Name" value="Zone" />
		<attribute name="Tags" />
		<attribute name="Position" value="0 0 0" />
		<attribute name="Rotation" value="1 0 0 0" />
		<attribute name="Scale" value="1 1 1" />
		<attribute name="Variables" />
		<component type="Zone" id="5">
			<attribute name="Bounding Box Min" value="-1000 -1000 -1000" />
			<attribute name="Bounding Box Max" value="1000 1000 1000" />
			<attribute name="Ambient Color" value="0.3 0.6 0.9 1" />
			<attribute name="Fog Color" value="0.3 0.6 0.9 1" />
		</component>
	</node>
	<node id="7">
		<attribute name="Is Enabled" value="true" />
		<attribute name="Name" value="Camera" />
		<attribute name="Tags" />
		<attribute name="Position" value="-2.3181 2.43787 -2.90237" />
		<attribute name="Rotation" value="0.8962 0.264191 0.341867 -0.100779" />
		<attribute name="Scale" value="1 1 1" />
		<attribute name="Variables" />
		<component type="Camera" id="7">
			<attribute name="Aspect Ratio" value="1.77778" />
		</component>
	</node>
</scene>


text:
#ifndef HK_COLLIDE2_MULTI_SPHERE_AGENT_H
#define HK_COLLIDE2_MULTI_SPHERE_AGENT_H

#include <Physics2012/Collide/Agent/hkpCollisionAgent.h>
#include <Physics2012/Collide/Shape/Deprecated/MultiSphere/hkpMultiSphereShape.h>

class hkpCollisionDispatcher;

/// This agent handles collisions between hkMultiSpheres
/// and other shapes.
class hkpMultiSphereAgent : public hkpCollisionAgent
{
	public:
	HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_BASE);
		/// Registers this agent with the collision dispatcher.
		static void HK_CALL registerAgent(hkpCollisionDispatcher* dispatcher);

		// hkpCollisionAgent interface implementation.
		virtual void processCollision(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpProcessCollisionInput& input, hkpProcessCollisionOutput& result);

		// hkpCollisionAgent interface implementation.
		virtual void linearCast( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpLinearCastCollisionInput& input, hkpCdPointCollector& collector, hkpCdPointCollector* startCollector );

		// hkpCollisionAgent interface implementation.
		static void HK_CALL staticLinearCast( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpLinearCastCollisionInput& input, hkpCdPointCollector& collector, hkpCdPointCollector* startCollector );

			// hkpCollisionAgent interface implementation.
		virtual void getClosestPoints( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdPointCollector& pointDetails);

			// hkpCollisionAgent interface implementation.
		static void HK_CALL staticGetClosestPoints( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, class hkpCdPointCollector& collector  );

		// hkpCollisionAgent interface implementation.
		virtual void getPenetrations( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdBodyPairCollector& collector );

			// hkpCollisionAgent interface implementation.
		static void HK_CALL staticGetPenetrations( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdBodyPairCollector& collector );

		// hkpCollisionAgent interface implementation.
		virtual void cleanup(hkCollisionConstraintOwner& info);

	protected:

		/// Constructor, called by the agent creation functions.
		hkpMultiSphereAgent( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr);

		/// Agent creation function used by the hkpCollisionDispatcher.
		static hkpCollisionAgent* HK_CALL createListAAgent(const 	hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr);

		/// Agent creation function used by the hkpCollisionDispatcher.
		static hkpCollisionAgent* HK_CALL createListBAgent(	const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr);

	protected:
		struct KeyAgentPair
		{
			HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpMultiSphereAgent::KeyAgentPair );

			hkpShapeKey m_key;
			hkpCollisionAgent* m_agent;
		};

		hkInplaceArray<KeyAgentPair,4> m_agents;

};

#endif // HK_COLLIDE2_MULTI_SPHERE_AGENT_H

/*
 * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907)
 *
 * Confidential Information of Havok.  (C) Copyright 1999-2014
 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
 * Logo, and the Havok buzzsaw logo are trademarks of Havok.  Title, ownership
 * rights, and intellectual property rights in the Havok software remain in
 * Havok and/or its suppliers.
 *
 * Use of this software for evaluation purposes is subject to and indicates
 * acceptance of the End User licence Agreement for this product. A copy of
 * the license is included with this software and is also available at www.havok.com/tryhavok.
 *
 */


text:
require 'spec_helper'

describe Cwsrb do
  it 'has a version number' do
    expect(Cwsrb::VERSION).not_to be nil
  end
end

describe Cwsrb::Helpers do
  describe '.resolve' do
    context 'with an username' do
      it 'returns a @-prefixed username' do
        expect(Cwsrb::Helpers.resolve('test')).to eq '@test'
        expect(Cwsrb::Helpers.resolve('1test')).to eq '@1test'
        expect(Cwsrb::Helpers.resolve('111')).not_to eq '@111'
        expect(Cwsrb::Helpers.resolve('S111')).not_to eq '@S111'
      end
    end

    context 'with an id' do
      it 'returns the same id' do
        expect(Cwsrb::Helpers.resolve('111')).to eq '111'
        expect(Cwsrb::Helpers.resolve('S111')).to eq 'S111'
        expect(Cwsrb::Helpers.resolve('test')).not_to eq 'test'
        expect(Cwsrb::Helpers.resolve('1test')).not_to eq '1test'
      end
    end
  end
end


text:
xt_core_message_t *xt_net_test_message_create(int client_socket,
    unsigned long message_type)
{
  return xt_core_message_create(client_socket, XT_NET_ENGINE_TEST,
      message_type, XT_CORE_IMESSAGE_NULL_DATA,
      XT_CORE_IMESSAGE_ZERO_DATA_SIZE);
}


text:
package com.liferay.portal.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

import javax.portlet.ClientDataRequest;
import javax.portlet.PortletRequest;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

public class HttpServletRequestAdapter extends HttpServletRequest_3_0_Adapter {

	// Private Data Members
	private PortletRequest wrappedPortletRequest;

	public HttpServletRequestAdapter(PortletRequest portletRequest) {

		super(portletRequest);
		this.wrappedPortletRequest = portletRequest;
	}

	@Override
	public void removeAttribute(String name) {
		getWrapped().removeAttribute(name);
	}

	@Override
	public Object getAttribute(String name) {
		return getWrapped().getAttribute(name);
	}

	@Override
	public void setAttribute(String name, Object value) {
		getWrapped().setAttribute(name, value);
	}

	@Override
	public Enumeration<String> getAttributeNames() {
		return getWrapped().getAttributeNames();
	}

	@Override
	public String getAuthType() {
		return getWrapped().getAuthType();
	}

	public String getCharacterEncoding() {

		PortletRequest portletRequest = getWrapped();

		if (portletRequest instanceof ClientDataRequest) {
			ClientDataRequest clientDataRequest = (ClientDataRequest) portletRequest;

			return clientDataRequest.getCharacterEncoding();
		} else {

			return null;
		}
	}

	public void setCharacterEncoding(String enc)
			throws UnsupportedEncodingException {
		PortletRequest portletRequest = getWrapped();

		if (portletRequest instanceof ClientDataRequest) {
			ClientDataRequest clientDataRequest = (ClientDataRequest) portletRequest;

			clientDataRequest.setCharacterEncoding(enc);
		} else {
			throw new UnsupportedOperationException();
		}
	}

	public int getContentLength() {

		PortletRequest portletRequest = getWrapped();

		if (portletRequest instanceof ClientDataRequest) {
			ClientDataRequest clientDataRequest = (ClientDataRequest) portletRequest;

			return clientDataRequest.getContentLength();
		} else {
			throw new UnsupportedOperationException();
		}
	}

	public String getContentType() {

		PortletRequest portletRequest = getWrapped();

		if (portletRequest instanceof ClientDataRequest) {
			ClientDataRequest clientDataRequest = (ClientDataRequest) portletRequest;

			return clientDataRequest.getContentType();
		} else {
			throw new UnsupportedOperationException();
		}
	}

	@Override
	public String getContextPath() {
		return getWrapped().getContextPath();
	}

	@Override
	public Cookie[] getCookies() {
		return getWrapped().getCookies();
	}

	@Override
	public boolean isRequestedSessionIdValid() {
		return getWrapped().isRequestedSessionIdValid();
	}

	public long getDateHeader(String name) {
		throw new UnsupportedOperationException();
	}

	public boolean isRequestedSessionIdFromCookie() {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean isSecure() {
		return getWrapped().isSecure();
	}

	@Override
	public boolean isUserInRole(String role) {
		return getWrapped().isUserInRole(role);
	}

	public String getHeader(String name) {
		throw new UnsupportedOperationException();
	}

	public Enumeration<String> getHeaderNames() {
		throw new UnsupportedOperationException();
	}

	public Enumeration<String> getHeaders(String name) {
		throw new UnsupportedOperationException();
	}

	public ServletInputStream getInputStream() throws IOException {
		throw new UnsupportedOperationException();
	}

	public int getIntHeader(String arg0) {
		throw new UnsupportedOperationException();
	}

	public boolean isRequestedSessionIdFromURL() {
		throw new UnsupportedOperationException();
	}

	public boolean isRequestedSessionIdFromUrl() {
		throw new UnsupportedOperationException();
	}

	public String getLocalAddr() {
		throw new UnsupportedOperationException();
	}

	@Override
	public Locale getLocale() {
		return getWrapped().getLocale();
	}

	@Override
	public Enumeration<Locale> getLocales() {
		return getWrapped().getLocales();
	}

	public String getLocalName() {
		return getWrapped().getLocale().getDisplayName();
	}

	public int getLocalPort() {
		return getWrapped().getServerPort();
	}

	public String getMethod() {

		PortletRequest portletRequest = getWrapped();

		if (portletRequest instanceof ClientDataRequest) {
			ClientDataRequest clientDataRequest = (ClientDataRequest) portletRequest;

			return clientDataRequest.getMethod();
		} else {
			throw new UnsupportedOperationException();
		}
	}

	@Override
	public String getParameter(String name) {
		return getWrapped().getParameter(name);
	}

	@Override
	public Map<String, String[]> getParameterMap() {
		return getWrapped().getParameterMap();
	}

	@Override
	public Enumeration<String> getParameterNames() {
		return getWrapped().getParameterNames();
	}

	@Override
	public String[] getParameterValues(String name) {
		return getWrapped().getParameterValues(name);
	}

	public String getPathInfo() {
		throw new UnsupportedOperationException();
	}

	public String getPathTranslated() {
		throw new UnsupportedOperationException();
	}

	public String getProtocol() {
		throw new UnsupportedOperationException();
	}

	public String getQueryString() {
		throw new UnsupportedOperationException();
	}

	public BufferedReader getReader() throws IOException {

		PortletRequest portletRequest = getWrapped();

		if (portletRequest instanceof ClientDataRequest) {
			ClientDataRequest clientDataRequest = (ClientDataRequest) portletRequest;

			return clientDataRequest.getReader();
		} else {
			throw new UnsupportedOperationException();
		}
	}

	public String getRealPath(String path) {
		throw new UnsupportedOperationException();
	}

	public String getRemoteAddr() {
		throw new UnsupportedOperationException();
	}

	public String getRemoteHost() {
		throw new UnsupportedOperationException();
	}

	public int getRemotePort() {
		throw new UnsupportedOperationException();
	}

	@Override
	public String getRemoteUser() {
		return getWrapped().getRemoteUser();
	}

	public RequestDispatcher getRequestDispatcher(String path) {
		throw new UnsupportedOperationException();
	}

	@Override
	public String getRequestedSessionId() {
		return getWrapped().getRequestedSessionId();
	}

	public String getRequestURI() {
		throw new UnsupportedOperationException();
	}

	public StringBuffer getRequestURL() {
		throw new UnsupportedOperationException();
	}

	@Override
	public String getScheme() {
		return getWrapped().getScheme();
	}

	@Override
	public String getServerName() {
		return getWrapped().getServerName();
	}

	@Override
	public int getServerPort() {
		return getWrapped().getServerPort();
	}

	public String getServletPath() {
		throw new UnsupportedOperationException();
	}

	public HttpSession getSession() {
		throw new UnsupportedOperationException();
	}

	public HttpSession getSession(boolean create) {
		throw new UnsupportedOperationException();
	}

	@Override
	public Principal getUserPrincipal() {
		return getWrapped().getUserPrincipal();
	}

	public PortletRequest getWrapped() {
		return wrappedPortletRequest;
	}
}


text:
paasta_tools.paasta_serviceinit module
======================================

.. automodule:: paasta_tools.paasta_serviceinit
    :members:
    :undoc-members:
    :show-inheritance:


text:
'use strict'

const { type, platform, arch, release, cpus } = require('os')
const { resolve, join } = require('path')
const spawn = require('child_process').spawn
const pump = require('pump')
const split = require('split2')
const through = require('through2')
const steed = require('steed')

function usage () {
  console.log(`
    Pino Benchmarks

    To run a benchmark, specify which to run:

    ・all        ⁃ run all benchmarks (takes a while)
    ・basic      ⁃ log a simple string
    ・object     ⁃ logging a basic object
    ・deep-object ⁃ logging a large object
    ・multi-arg   ⁃ multiple log method arguments
    ・child      ⁃ child from a parent
    ・child-child ⁃ child from a child
    ・child-creation ⁃ child constructor

    Example:

      node runbench basic
  `)
}

if (!process.argv[2]) {
  usage()
  process.exit()
}

const quiet = process.argv[3] === '-q'

const selectedBenchmark = process.argv[2].toLowerCase()
const benchmarkDir = resolve(__dirname, '..')
const benchmarks = {
  basic: 'basic.bench.js',
  object: 'object.bench.js',
  'deep-object': 'deep-object.bench.js',
  'multi-arg': 'multi-arg.bench.js',
  'long-string': 'long-string.bench.js',
  child: 'child.bench.js',
  'child-child': 'child-child.bench.js',
  'child-creation': 'child-creation.bench.js'
}

function runBenchmark (name, done) {
  const benchmarkResults = {}
  benchmarkResults[name] = {}

  const processor = through(function (line, enc, cb) {
    const [label, time] = ('' + line).split(': ')
    const [target, iterations] = label.split('*')
    const logger = target.replace('bench', '')

    if (!benchmarkResults[name][logger]) benchmarkResults[name][logger] = []

    benchmarkResults[name][logger].push({
      time: time.replace('ms', ''),
      iterations: iterations.replace(':', '')
    })

    cb()
  })

  if (quiet === false) console.log(`Running ${name.toUpperCase()} benchmark\n`)

  const benchmark = spawn(
    process.argv[0],
    [join(benchmarkDir, benchmarks[name])]
  )

  if (quiet === false) {
    benchmark.stdout.pipe(process.stdout)
  }

  pump(benchmark.stdout, split(), processor)

  benchmark.on('exit', () => {
    console.log()
    if (done && typeof done === 'function') done(null, benchmarkResults)
  })
}

function sum (arr) {
  var result = 0
  for (var i = 0; i < arr.length; i += 1) {
    result += Number.parseFloat(arr[i].time)
  }
  return result
}

function displayResults (results) {
  if (quiet === false) console.log('==========')
  const benchNames = Object.keys(results)
  for (var i = 0; i < benchNames.length; i += 1) {
    console.log(`${benchNames[i].toUpperCase()} benchmark averages`)
    const benchmark = results[benchNames[i]]
    const loggers = Object.keys(benchmark)
    for (var j = 0; j < loggers.length; j += 1) {
      var logger = benchmark[loggers[j]]
      var average = sum(logger) / logger.length
      console.log(`${loggers[j]} average: ${average.toFixed(3)}ms`)
    }
  }
  if (quiet === false) {
    console.log('==========')
    console.log(
      `System: ${type()}/${platform()} ${arch()} ${release()}`,
      `~ ${cpus()[0].model} (cores/threads: ${cpus().length})`
    )
  }
}

function toBench (done) {
  runBenchmark(this.name, done)
}

const benchQueue = []
if (selectedBenchmark !== 'all') {
  benchQueue.push(toBench.bind({ name: selectedBenchmark }))
} else {
  const keys = Object.keys(benchmarks)
  for (var i = 0; i < keys.length; i += 1) {
    benchQueue.push(toBench.bind({ name: keys[i] }))
  }
}
steed.series(benchQueue, function (err, results) {
  if (err) return console.error(err.message)
  results.forEach(displayResults)
})


text:
class StageEntity < Grape::Entity
  include RequestAwareEntity

  expose :name

  expose :title do |stage|
    "#{stage.name}: #{detailed_status.label}"
  end

  expose :groups,
    if: -> (_, opts) { opts[:grouped] },
    with: JobGroupEntity

  expose :latest_statuses,
    if: -> (_, opts) { opts[:details] },
    with: JobEntity do |stage|
    latest_statuses
  end

  expose :retried,
         if: -> (_, opts) { opts[:retried] },
         with: JobEntity do |stage|
    retried_statuses
  end

  expose :detailed_status, as: :status, with: DetailedStatusEntity

  expose :path do |stage|
    project_pipeline_path(
      stage.pipeline.project,
      stage.pipeline,
      anchor: stage.name)
  end

  expose :dropdown_path do |stage|
    stage_project_pipeline_path(
      stage.pipeline.project,
      stage.pipeline,
      stage: stage.name,
      format: :json)
  end

  private

  alias_method :stage, :object

  def detailed_status
    stage.detailed_status(request.current_user)
  end

  def grouped_statuses
    @grouped_statuses ||= stage.statuses.latest_ordered.group_by(&:status)
  end

  def grouped_retried_statuses
    @grouped_retried_statuses ||= stage.statuses.retried_ordered.group_by(&:status)
  end

  def latest_statuses
    HasStatus::ORDERED_STATUSES.flat_map do |ordered_status|
      grouped_statuses.fetch(ordered_status, [])
    end
  end

  def retried_statuses
    HasStatus::ORDERED_STATUSES.flat_map do |ordered_status|
      grouped_retried_statuses.fetch(ordered_status, [])
    end
  end
end