text:
// WebKit Specfic code.  Add your own here.
function initNonKhronosFramework(waitUntilDone) {
  if (window.layoutTestController) {
    layoutTestController.overridePreference("WebKitWebGLEnabled", "1");
    layoutTestController.dumpAsText();
    if (waitUntilDone) {
      layoutTestController.waitUntilDone();
    }
  }
}

function nonKhronosFrameworkNotifyDone() {
  if (window.layoutTestController) {
    layoutTestController.notifyDone();
  }
}

function reportTestResultsToHarness(success, msg) {
  if (window.parent.webglTestHarness) {
    window.parent.webglTestHarness.reportResults(success, msg);
  }
}

function notifyFinishedToHarness() {
  if (window.parent.webglTestHarness) {
    window.parent.webglTestHarness.notifyFinished();
  }
}

function description(msg)
{
    // For MSIE 6 compatibility
    var span = document.createElement("span");
    span.innerHTML = '
' + msg + '

On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
';
    var description = document.getElementById("description");
    if (description.firstChild)
        description.replaceChild(span, description.firstChild);
    else
        description.appendChild(span);
}

function debug(msg)
{
    var span = document.createElement("span");
    document.getElementById("console").appendChild(span); // insert it first so XHTML knows the namespace
    span.innerHTML = msg + '
';
}

function escapeHTML(text)
{
    return text.replace(/&/g, "&").replace(/</g, "<");
}

function testPassed(msg)
{
    reportTestResultsToHarness(true, msg);
    debug('PASS ' + escapeHTML(msg) + '');
}

function testFailed(msg)
{
    reportTestResultsToHarness(false, msg);
    debug('FAIL ' + escapeHTML(msg) + '');
}

function areArraysEqual(_a, _b)
{
    try {
        if (_a.length !== _b.length)
            return false;
        for (var i = 0; i < _a.length; i++)
            if (_a[i] !== _b[i])
                return false;
    } catch (ex) {
        return false;
    }
    return true;
}

function isMinusZero(n)
{
    // the only way to tell 0 from -0 in JS is the fact that 1/-0 is
    // -Infinity instead of Infinity
    return n === 0 && 1/n < 0;
}

function isResultCorrect(_actual, _expected)
{
    if (_expected === 0)
        return _actual === _expected && (1/_actual) === (1/_expected);
    if (_actual === _expected)
        return true;
    if (typeof(_expected) == "number" && isNaN(_expected))
        return typeof(_actual) == "number" && isNaN(_actual);
    if (Object.prototype.toString.call(_expected) == Object.prototype.toString.call([]))
        return areArraysEqual(_actual, _expected);
    return false;
}

function stringify(v)
{
    if (v === 0 && 1/v < 0)
        return "-0";
    else return "" + v;
}

function evalAndLog(_a)
{
  if (typeof _a != "string")
    debug("WARN: tryAndLog() expects a string argument");

  // Log first in case things go horribly wrong or this causes a sync event.
  debug(_a);

  var _av;
  try {
     _av = eval(_a);
  } catch (e) {
    testFailed(_a + " threw exception " + e);
  }
  return _av;
}

function shouldBe(_a, _b, quiet)
{
    if (typeof _a != "string" || typeof _b != "string")
        debug("WARN: shouldBe() expects string arguments");
    var exception;
    var _av;
    try {
        _av = eval(_a);
    } catch (e) {
        exception = e;
    }
    var _bv = eval(_b);

    if (exception)
        testFailed(_a + " should be " + _bv + ". Threw exception " + exception);
    else if (isResultCorrect(_av, _bv)) {
        if (!quiet) {
            testPassed(_a + " is " + _b);
        }
    } else if (typeof(_av) == typeof(_bv))
        testFailed(_a + " should be " + _bv + ". Was " + stringify(_av) + ".");
    else
        testFailed(_a + " should be " + _bv + " (of type " + typeof _bv + "). Was " + _av + " (of type " + typeof _av + ").");
}

function shouldNotBe(_a, _b, quiet)
{
    if (typeof _a != "string" || typeof _b != "string")
        debug("WARN: shouldNotBe() expects string arguments");
    var exception;
    var _av;
    try {
        _av = eval(_a);
    } catch (e) {
        exception = e;
    }
    var _bv = eval(_b);

    if (exception)
        testFailed(_a + " should not be " + _bv + ". Threw exception " + exception);
    else if (!isResultCorrect(_av, _bv)) {
        if (!quiet) {
            testPassed(_a + " is not " + _b);
        }
    } else
        testFailed(_a + " should not be " + _bv + ".");
}

function shouldBeTrue(_a) { shouldBe(_a, "true"); }
function shouldBeFalse(_a) { shouldBe(_a, "false"); }
function shouldBeNaN(_a) { shouldBe(_a, "NaN"); }
function shouldBeNull(_a) { shouldBe(_a, "null"); }

function shouldBeEqualToString(a, b)
{
  var unevaledString = '"' + b.replace(/"/g, "\"") + '"';
  shouldBe(a, unevaledString);
}

function shouldEvaluateTo(actual, expected) {
  // A general-purpose comparator.  'actual' should be a string to be
  // evaluated, as for shouldBe(). 'expected' may be any type and will be
  // used without being eval'ed.
  if (expected == null) {
    // Do this before the object test, since null is of type 'object'.
    shouldBeNull(actual);
  } else if (typeof expected == "undefined") {
    shouldBeUndefined(actual);
  } else if (typeof expected == "function") {
    // All this fuss is to avoid the string-arg warning from shouldBe().
    try {
      actualValue = eval(actual);
    } catch (e) {
      testFailed("Evaluating " + actual + ": Threw exception " + e);
      return;
    }
    shouldBe("'" + actualValue.toString().replace(/\n/g, "") + "'",
             "'" + expected.toString().replace(/\n/g, "") + "'");
  } else if (typeof expected == "object") {
    shouldBeTrue(actual + " == '" + expected + "'");
  } else if (typeof expected == "string") {
    shouldBe(actual, expected);
  } else if (typeof expected == "boolean") {
    shouldBe("typeof " + actual, "'boolean'");
    if (expected)
      shouldBeTrue(actual);
    else
      shouldBeFalse(actual);
  } else if (typeof expected == "number") {
    shouldBe(actual, stringify(expected));
  } else {
    debug(expected + " is unknown type " + typeof expected);
    shouldBeTrue(actual, "'"  +expected.toString() + "'");
  }
}

function shouldBeNonZero(_a)
{
  var exception;
  var _av;
  try {
     _av = eval(_a);
  } catch (e) {
     exception = e;
  }

  if (exception)
    testFailed(_a + " should be non-zero. Threw exception " + exception);
  else if (_av != 0)
    testPassed(_a + " is non-zero.");
  else
    testFailed(_a + " should be non-zero. Was " + _av);
}

function shouldBeNonNull(_a)
{
  var exception;
  var _av;
  try {
     _av = eval(_a);
  } catch (e) {
     exception = e;
  }

  if (exception)
    testFailed(_a + " should be non-null. Threw exception " + exception);
  else if (_av != null)
    testPassed(_a + " is non-null.");
  else
    testFailed(_a + " should be non-null. Was " + _av);
}

function shouldBeUndefined(_a)
{
  var exception;
  var _av;
  try {
     _av = eval(_a);
  } catch (e) {
     exception = e;
  }

  if (exception)
    testFailed(_a + " should be undefined. Threw exception " + exception);
  else if (typeof _av == "undefined")
    testPassed(_a + " is undefined.");
  else
    testFailed(_a + " should be undefined. Was " + _av);
}

function shouldBeDefined(_a)
{
  var exception;
  var _av;
  try {
     _av = eval(_a);
  } catch (e) {
     exception = e;
  }

  if (exception)
    testFailed(_a + " should be defined. Threw exception " + exception);
  else if (_av !== undefined)
    testPassed(_a + " is defined.");
  else
    testFailed(_a + " should be defined. Was " + _av);
}

function shouldBeGreaterThanOrEqual(_a, _b) {
    if (typeof _a != "string" || typeof _b != "string")
        debug("WARN: shouldBeGreaterThanOrEqual expects string arguments");

    var exception;
    var _av;
    try {
        _av = eval(_a);
    } catch (e) {
        exception = e;
    }
    var _bv = eval(_b);

    if (exception)
        testFailed(_a + " should be >= " + _b + ". Threw exception " + exception);
    else if (typeof _av == "undefined" || _av < _bv)
        testFailed(_a + " should be >= " + _b + ". Was " + _av + " (of type " + typeof _av + ").");
    else
        testPassed(_a + " is >= " + _b);
}

function shouldThrow(_a, _e)
{
  var exception;
  var _av;
  try {
     _av = eval(_a);
  } catch (e) {
     exception = e;
  }

  var _ev;
  if (_e)
      _ev =  eval(_e);

  if (exception) {
    if (typeof _e == "undefined" || exception == _ev)
      testPassed(_a + " threw exception " + exception + ".");
    else
      testFailed(_a + " should throw " + (typeof _e == "undefined" ? "an exception" : _ev) + ". Threw exception " + exception + ".");
  } else if (typeof _av == "undefined")
    testFailed(_a + " should throw " + (typeof _e == "undefined" ? "an exception" : _ev) + ". Was undefined.");
  else
    testFailed(_a + " should throw " + (typeof _e == "undefined" ? "an exception" : _ev) + ". Was " + _av + ".");
}

function assertMsg(assertion, msg) {
    if (assertion) {
        testPassed(msg);
    } else {
        testFailed(msg);
    }
}

function gc() {
    if (typeof GCController !== "undefined")
        GCController.collect();
    else {
        function gcRec(n) {
            if (n < 1)
                return {};
            var temp = {i: "ab" + i + (i / 100000)};
            temp += "foo";
            gcRec(n-1);
        }
        for (var i = 0; i < 1000; i++)
            gcRec(10)
    }
}

function finishTest() {
  successfullyParsed = true;
  var epilogue = document.createElement("script");
  epilogue.onload = function() {
    if (window.nonKhronosFrameworkNotifyDone) {
      window.nonKhronosFrameworkNotifyDone();
    }
  };

  var basePath = "";
  var expectedBase = "js-test-pre.js";
  var scripts = document.getElementsByTagName('script');
  for (var script, i = 0; script = scripts[i]; i++) {
    var src = script.src;
    var l = src.length;
    if (src.substr(l - expectedBase.length) == expectedBase) {
      basePath = src.substr(0, l - expectedBase.length);
      break;
    }
  }
  epilogue.src = basePath + "js-test-post.js";
  document.body.appendChild(epilogue);
}


text:
import { combineReducers } from 'redux';
import getModuleStatusReducer from '../../lib/getModuleStatusReducer';
import callStatus from './callStatus';

export function getCallsReducer(types) {
  return (state = {}, { type, contact, calls, sessionId }) => {
    const contactId = String(contact && contact.id);
    if (type === types.loadSuccess) {
      return {
        ...state,
        [sessionId ? `${contactId}-${sessionId}` : contactId]: calls,
      };
    } else if (type === types.loadReset) {
      const {
        [sessionId ? `${contactId}-${sessionId}` : contactId]: _,
        ...rest
      } = state;
      return rest;
    }
    return state;
  };
}

export function getCallStatusReducer(types) {
  return (state = null, { type }) => {
    switch (type) {
      case types.initLoad:
        return callStatus.loading;
      case types.loadReset:
      case types.loadSuccess:
        return callStatus.loaded;
      default:
        return state;
    }
  };
}

export default function getRecentCallsReducer(types) {
  return combineReducers({
    status: getModuleStatusReducer(types),
    calls: getCallsReducer(types),
    callStatus: getCallStatusReducer(types),
  });
}

redpajama_set_name: RedPajamaGithub


text:
bench_bin=~/libzbc/bench_fwu

if [ $# -ne 3 ]
then
    echo Usage: $0 [sample_num] [lba_count] [zone_num]
    echo sample_num: the number of random lbas to run
    exit -1
fi

start_stamp=$(date +%s)

sample_num=$1

#result_file="long_range.csv"
result_file=bw_range_zone${3}_${sample_num}.csv
echo "" > $result_file

echo $bench_bin/zone_range_rand_gen.sh 64 $(($3 + 63)) -2 $2
$bench_bin/zone_range_rand_gen.sh 64 $(($3 + 63)) -2 $2 > range.job

echo $bench_bin/zbc_write_zone3 -p range.job -k $(($sample_num/$3)) /dev/sdb
$bench_bin/zbc_write_zone3 -p range.job -k $(($sample_num/$3)) /dev/sdb > range_$sample_num.log
#$bench_bin/reset_write_ptr_all.sh /dev/sdb > /dev/null
$bench_bin/extract_bw.sh range_$sample_num.log > $result_file
$bench_bin/extract_timestamp.sh range_$sample_num.log > timestamp.csv

paste $result_file timestamp.csv > temp.csv
mv temp.csv $result_file
rm timestamp.csv

echo cp $result_file ~
cp $result_file ~
#tar cf ~/bw_range_large.tar *.csv
#rm *.csv *.log *.job

end_stamp=$(date +%s)
echo time taken: $(($end_stamp - $start_stamp)) sec.


text:
require 'user_agent/comparable'
require 'user_agent/browsers'
require 'user_agent/operating_systems'
require 'user_agent/version'

class UserAgent
  # http://www.texsoft.it/index.php?m=sw.php.useragent
  MATCHER = %r{
    ^([^/\s]+)        # Product
    /?([^\s]*)        # Version
    (\s\(([^\)]*)\))? # Comment
  }x.freeze

  DEFAULT_USER_AGENT = "Mozilla/4.0 (compatible)"

  def self.parse(string)
    if string.nil? || string == ""
      string = DEFAULT_USER_AGENT
    end

    agents = Browsers::Base.new
    while m = string.to_s.match(MATCHER)
      agents << new(m[1], m[2], m[4])
      string = string[m[0].length..-1].strip
    end
    Browsers.extend(agents)
  end

  attr_reader :product, :version, :comment

  def initialize(product, version = nil, comment = nil)
    if product
      @product = product
    else
      raise ArgumentError, "expected a value for product"
    end

    if version && !version.empty?
      @version = Version.new(version)
    else
      @version = Version.new
    end

    if comment.respond_to?(:split)
      @comment = comment.split("; ")
    else
      @comment = comment
    end
  end

  include Comparable

  # Any comparsion between two user agents with different products will
  # always return false.
  def <=>(other)
    if @product == other.product
      @version <=> other.version
    else
      false
    end
  end

  def eql?(other)
    @product == other.product &&
      @version == other.version &&
      @comment == other.comment
  end

  def to_s
    to_str
  end

  def to_str
    if @product && !@version.nil? && @comment
      "#{@product}/#{@version} (#{@comment.join("; ")})"
    elsif @product && !@version.nil?
      "#{@product}/#{@version}"
    elsif @product && @comment
      "#{@product} (#{@comment.join("; ")})"
    else
      @product
    end
  end
end


text:
package com.catherine.adapter;

public enum Cable {
	HDMI, VGA
}


text:
"""Tests for the thumbs module"""

import pytest
from bok_choy.promise import EmptyPromise

from workbench import scenarios
from workbench.test.selenium_test import SeleniumTest

class ThreeThumbsTest(SeleniumTest):
    """Test the functionalities of the three thumbs test XBlock."""

    def setUp(self):
        super().setUp()

        scenarios.add_xml_scenario(
            "test_three_file_thumbs", "three file thumbs test",
            """<vertical_demo><filethumbs/><filethumbs/><filethumbs/></vertical_demo>"""
        )
        self.addCleanup(scenarios.remove_scenario, "test_three_file_thumbs")

        # Suzy opens the browser to visit the workbench
        self.browser.get(self.live_server_url)

        # She knows it's the site by the header
        header1 = self.browser.find_element_by_css_selector('h1')
        self.assertEqual(header1.text, 'XBlock scenarios')

    @pytest.mark.flaky(reruns=5, reruns_delay=2)
    def test_three_thumbs_initial_state(self):
        # She clicks on the three thumbs at once scenario
        link = self.browser.find_element_by_link_text('three file thumbs test')
        link.click()
        self.wait_for_page_load(link, timeout=10)

        # The header reflects the XBlock
        header1 = self.browser.find_element_by_css_selector('h1')
        self.assertEqual(header1.text, 'XBlock: three file thumbs test')

        # She sees that there are 3 sets of thumbs
        vertical_css = 'div.student_view > div.xblock-v1 > div.vertical'

        # The following will give a NoSuchElementException error
        # if it is not there
        vertical = self.browser.find_element_by_css_selector(vertical_css)

        # Make sure there are three thumbs blocks
        thumb_css = 'div.xblock-v1[data-block-type="filethumbs"]'
        thumbs = vertical.find_elements_by_css_selector(thumb_css)
        self.assertEqual(3, len(thumbs))

        # Make sure they all have 0 for upvote and downvote counts
        up_count_css = 'span.upvote span.count'
        down_count_css = 'span.downvote span.count'

        for thumb in thumbs:
            # pylint: disable=cell-var-from-loop
            up_count = thumb.find_element_by_css_selector(up_count_css)
            down_count = thumb.find_element_by_css_selector(down_count_css)
            initial_up = int(up_count.text)
            initial_down = int(down_count.text)

            # upvote
            thumb.find_element_by_css_selector('span.upvote').click()
            _ = EmptyPromise(
                lambda: int(thumb.find_element_by_css_selector(up_count_css).text) == initial_up + 1,
                "upvote action succeeded"
            ).fulfill()
            self.assertEqual(initial_down, int(thumb.find_element_by_css_selector(down_count_css).text))

            # downvote
            thumb.find_element_by_css_selector('span.downvote').click()
            _ = EmptyPromise(
                lambda: int(thumb.find_element_by_css_selector(down_count_css).text) == initial_down + 1,
                "downvote action succeeded"
            ).fulfill()
            self.assertEqual(initial_up + 1, int(thumb.find_element_by_css_selector(up_count_css).text))


text:
/**
 * Returns a description of this date in relative terms.

 * Examples, where new Date().toString() == "Mon Nov 23 2009 17:36:51 GMT-0500 (EST)":
 *
 * new Date().toRelativeTime()
 * --> 'Just now'
 *
 * new Date("Nov 21, 2009").toRelativeTime()
 * --> '2 days ago'
 *
 * new Date("Nov 25, 2009").toRelativeTime()
 * --> '2 days from now'
 *
 * // One second ago
 * new Date("Nov 23 2009 17:36:50 GMT-0500 (EST)").toRelativeTime()
 * --> '1 second ago'
 *
 * toRelativeTime() takes an optional argument - a configuration object.
 * It can have the following properties:
 * - now - Date object that defines "now" for the purpose of conversion.
 *         By default, current date & time is used (i.e. new Date())
 * - nowThreshold - Threshold in milliseconds which is considered "Just now"
 *                  for times in the past or "Right now" for now or the immediate future
 * - smartDays - If enabled, dates within a week of now will use Today/Yesterday/Tomorrow
 *               or weekdays along with time, e.g. "Thursday at 15:10:34"
 *               rather than "4 days ago" or "Tomorrow at 20:12:01"
 *               instead of "1 day from now"
 * - texts - If provided it will be the source of all texts used for creation
 *           of time difference text, it should also provide pluralization function
 *           which will be feed up with time units
 *
 * If a single number is given as argument, it is interpreted as nowThreshold:
 *
 * // One second ago, now setting a now_threshold to 5 seconds
 * new Date("Nov 23 2009 17:36:50 GMT-0500 (EST)").toRelativeTime(5000)
 * --> 'Just now'
 *
 * // One second in the future, now setting a now_threshold to 5 seconds
 * new Date("Nov 23 2009 17:36:52 GMT-0500 (EST)").toRelativeTime(5000)
 * --> 'Right now'
 *
 */
 Date.prototype.toRelativeTime = (function() {

  var _ = function(options) {
    var opts = processOptions(options);

    var now = opts.now || new Date();
    var texts = opts.texts || TEXTS;
    var delta = now - this;
    var future = (delta <= 0);
    delta = Math.abs(delta);

    // special cases controlled by options
    if (delta <= opts.nowThreshold) {
      return future ? texts.right_now : texts.just_now;
    }
    if (opts.smartDays && delta <= 6 * MS_IN_DAY) {
      return toSmartDays(this, now, texts);
    }

    var units = null;
    for (var key in CONVERSIONS) {
      if (delta < CONVERSIONS[key])
        break;
      units = key; // keeps track of the selected key over the iteration
      delta = delta / CONVERSIONS[key];
    }

    // pluralize a unit when the difference is greater than 1.
    delta = Math.floor(delta);
    units = texts.pluralize(delta, units);
    return [delta, units, future ? texts.from_now : texts.ago].join(" ");
  };

  var processOptions = function(arg) {
    if (!arg) arg = 0;
    if (typeof arg === 'string') {
      arg = parseInt(arg, 10);
    }
    if (typeof arg === 'number') {
      if (isNaN(arg)) arg = 0;
      return {nowThreshold: arg};
    }
    return arg;
  };

  var toSmartDays = function(date, now, texts) {
    var day;
    var weekday = date.getDay(),
        dayDiff = weekday - now.getDay();
    if (dayDiff == 0)       day = texts.today;
    else if (dayDiff == -1) day = texts.yesterday;
    else if (dayDiff == 1 && date > now)
                            day = texts.tomorrow;
    else                    day = texts.days[weekday];
    return day + " " + texts.at + " " + date.toLocaleTimeString();
  };

  var CONVERSIONS = {
    millisecond: 1, // ms    -> ms
    second: 1000,   // ms    -> sec
    minute: 60,     // sec   -> min
    hour:   60,     // min   -> hour
    day:    24,     // hour  -> day
    month:  30,     // day   -> month (roughly)
    year:   12      // month -> year
  };

  var MS_IN_DAY = (CONVERSIONS.millisecond * CONVERSIONS.second * CONVERSIONS.minute * CONVERSIONS.hour * CONVERSIONS.day);

  var WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

  var TEXTS = {today:        'Today',
               yesterday:    'Yesterday',
               tomorrow:     'Tomorrow',
               at:           'at',
               from_now:     'from now',
               ago:          'ago',
               right_now:    'Right now',
               just_now:     'Just now',
               days:         WEEKDAYS,
               pluralize:    function(val, text) {
                                if(val > 1)
                                    return text + "s";
                                return text;
                             }
               };
  return _;
})();

/*
 * Wraps up a common pattern used with this plugin whereby you take a String
 * representation of a Date, and want back a date object.
 */
Date.fromString = function(str) {
  return new Date(Date.parse(str));
};


text:
require 'aws/core'
require 'aws/dynamo_db/config'

module AWS

  # Provides a high-level interface for using DynamoDB.
  #
  #   dynamo_db = AWS::DynamoDB.new(
  #     :access_key_id => '...',
  #     :secret_access_key => '...',
  #     :session_token => '...')
  #
  # = Credentials
  #
  # Amazon DynamoDB requires that all requests are made with short-term
  # credentials (e.g. requires a session token).
  #
  # @note If you make a request using AWS::DynamoDB with long-term credentials
  #   a request is made to Amazon STS for temproary session credentials.
  #   These will be cached in the process and re-used.
  #
  # = Tables
  #
  # Tables contain items, and organize information into discrete
  # areas. All items in the table have the same primary key
  # scheme. You designate the attribute name (or names) to use for the
  # primary key when you create a table, and the table requires each
  # item in the table to have a unique primary key value. The first
  # step in writing data to DynamoDB is to create a table and
  # designate a table name with a primary key.
  #
  #   table = dynamo_db.tables.create(
  #     "MyTable",
  #     :hash_key => { :id => :string }
  #   )
  #   sleep 1 while table.status == :creating
  #
  # See {Table} and {TableCollection} for more information on creating
  # and managing tables.
  #
  # = Items and Attributes
  #
  # An item is a collection of one or more attributes, where each
  # attribute has a string name and a string, number, string set or
  # number set value.
  #
  # The identity of an item consists of its hash key value and -- if
  # the table's schema includes a range key -- its range key value.
  #
  #   item = table.items.put(:id => "abc123")
  #   item.hash_value # => "abc123"
  #   item.attributes.set(
  #     :colors => ["red", "blue"],
  #     :numbers => [12, 24]
  #   )
  #
  # See {Item} and {ItemCollection} for more information on creating
  # and managing items.  For more information on managing attributes,
  # see {AttributeCollection}.
  #
  # = Examples
  #
  #   # create a table (10 read and 5 write capacity units) with the
  #   # default schema (id string hash key)
  #   dynamo_db = AWS::DynamoDB.new
  #   table = dynamo_db.tables.create('my-table', 10, 5)
  #
  #   sleep 1 while table.status == :creating
  #   table.status #=> :active
  #
  #   # get an existing table by name and specify its hash key
  #   table = dynamo_db.tables['another-table']
  #   table.hash_key = [:id, :number]
  #
  #   # add an item
  #   item = table.items.create('id' => 12345, 'foo' => 'bar')
  #
  #   # add attributes to an item
  #   item.attributes.add 'category' => %w(demo), 'tags' => %w(sample item)
  #
  #   # update an item with mixed add, delete, update
  #   item.attributes.update do |u|
  #     u.add 'colors' => %w(red)
  #     u.set 'category' => 'demo-category'
  #     u.delete 'foo'
  #   end
  #
  #   # delete attributes
  #   item.attributes.delete 'colors', 'category'
  #
  #   # get attributes
  #   item.attributes.to_h
  #   #=> {"id"=>#<BigDecimal:10155f5d0,'0.12345E5',9(18)>, "tags"=>#<Set: {"item", "sample"}>}
  #
  #   # delete an item and all of its attributes
  #   item.delete
  #
  class DynamoDB

    AWS.register_autoloads(self, 'aws/dynamo_db') do
      autoload :AttributeCollection, 'attribute_collection'
      autoload :BatchGet, 'batch_get'
      autoload :Client, 'client'
      autoload :Errors, 'errors'
      autoload :Expectations, 'expectations'
      autoload :Item, 'item'
      autoload :ItemData, 'item_data'
      autoload :ItemCollection, 'item_collection'
      autoload :Keys, 'keys'
      autoload :PrimaryKeyElement, 'primary_key_element'
      autoload :Request, 'request'
      autoload :Resource, 'resource'
      autoload :Table, 'table'
      autoload :TableCollection, 'table_collection'
      autoload :Types, 'types'
    end

    include Core::ServiceInterface

    # Returns a collection representing all the tables in your account.
    #
    # @return [TableCollection]
    def tables
      TableCollection.new(:config => config)
    end

    # Request attributes for items spanning multiple tables.  You configure
    # you batch get request using a block:
    #
    #   attributes = dynamo_db.batch_get do |batch|
    #     # call methods on batch specify tables, attributes and items
    #     # ...
    #   end
    #
    # The value returned by #batch_get is an enumerable object that yields
    # the table name (as a string) and a hash of attributes.  The
    # enumerable yields once per item received in the batch get.
    #
    # == Configuring the batch
    #
    # You can call two methods on the yielded batch object:
    #
    # * #table
    # * #items
    #
    # For more information on these methods, see {BatchGet}.
    #
    # @yield [String, Hash] Yields the table name as a string and a hash
    #   of attributes for each item received in the bach get request.
    #
    # @return [Enumerable]
    #
    def batch_get &block
      batch = BatchGet.new(:config => config)
      yield(batch)
      batch.enumerator
    end

  end
end


text:
from django.core.management.base import BaseCommand, CommandError
from resources.models import SkillEnjoyment

class Command(BaseCommand):
    help = ('Populates the database with a suggested set of '
            'Skill Enjoyment Levels.')

    def handle(self, *args, **options):
        enjoyment_levels = [
            ('None', 0, 'Please don\'t make me do this.'),
            ('Little', 1, 'Not my favorite but I\'ll do it if needed.'),
            ('Enjoy', 4, 'I enjoy doing this.'),
            ('Favorite', 9, 'This is (one of) my favorite part(s) of my job.'),
        ]
        for enjoyment_level in enjoyment_levels:
            SkillEnjoyment.objects.create(
                slug=enjoyment_level[0],
                value=enjoyment_level[1],
                description=enjoyment_level[2]
            )

        self.stdout.write(
            self.style.SUCCESS('Successfully loaded Skill Levels.')
        )


text:
from django.contrib import admin
from .models import Article

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug', 'created_at')
    list_filter = ('created_at',)
    search_fields = ('title',)

admin.site.register(Article, ArticleAdmin)


text:
package com.xjt.crazypic.edit.pipeline;

import android.graphics.Bitmap;

import com.xjt.crazypic.edit.filters.FiltersManager;

public class FullresRenderingRequestTask extends ProcessingTask {

    private CachingPipeline mFullresPipeline = null;
    private boolean mPipelineIsOn = false;

    public void setPreviewScaleFactor(float previewScale) {
        mFullresPipeline.setPreviewScaleFactor(previewScale);
    }

    static class Render implements Request {
        RenderingRequest request;
    }

    static class RenderResult implements Result {
        RenderingRequest request;
    }

    public FullresRenderingRequestTask() {
        mFullresPipeline = new CachingPipeline(FiltersManager.getHighresManager(), "Fullres");
    }

    public void setOriginal(Bitmap bitmap) {
        mFullresPipeline.setOriginal(bitmap);
        mPipelineIsOn = true;
    }

    public void stop() {
        mFullresPipeline.stop();
    }

    public void postRenderingRequest(RenderingRequest request) {
        if (!mPipelineIsOn) {
            return;
        }
        postRequest(request);
    }

    @Override
    public Result doInBackground(Request message) {
        RenderingRequest request = (RenderingRequest) message;
        RenderResult result = null;
        mFullresPipeline.render(request);
        result = new RenderResult();
        result.request = request;
        return result;
    }

    @Override
    public void onResult(Result message) {
        if (message == null) {
            return;
        }
        RenderingRequest request = ((RenderResult) message).request;
        request.markAvailable();
    }

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


text:
/*****************************************************************************
 OSSLSHA256.h

 OpenSSL SHA256 implementation
 *****************************************************************************/

#ifndef _SOFTHSM_V2_OSSLSHA256_H
#define _SOFTHSM_V2_OSSLSHA256_H

#include "config.h"
#include "OSSLEVPHashAlgorithm.h"
#include <openssl/evp.h>

class OSSLSHA256 : public OSSLEVPHashAlgorithm
{
	virtual int getHashSize();
protected:
	virtual const EVP_MD* getEVPHash() const;
};

#endif // !_SOFTHSM_V2_OSSLSHA256_H


text:
import {Component, OnInit} from "@angular/core";
import {ActivatedRoute, Params} from "@angular/router";
import {DicewareService} from "../services/diceware-service";
import {Diceware} from "../classes/diceware";

@Component({
	templateUrl: "./templates/diceware.html"
})

export class DicewareComponent implements OnInit {
	diceware: Diceware = new Diceware("", "");

	constructor(private dicewareService: DicewareService, private route: ActivatedRoute) {}

	ngOnInit() : void {
		this.route.params.forEach((params : Params) => {
			let roll = +params["roll"];
			this.dicewareService.getDiceware(roll)
				.subscribe(diceware => this.diceware = diceware);
		});
	}
}


text:
pymatgen\.analysis\.defects\.point\_defects module
==================================================

.. automodule:: pymatgen.analysis.defects.point_defects
    :members:
    :undoc-members:
    :show-inheritance:


text:
'use babel';

import MapQueriesView from '../lib/map-queries-view';

describe('MapQueriesView', () => {
  it('has one valid test', () => {
    expect('life').toBe('easy');
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3b5998</color>
    <color name="colorPrimaryDark">#243c6d</color>
    <color name="colorAccent">#FF4444</color>
</resources>


text:
package org.apache.camel.component.flink;

import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.support.DefaultEndpoint;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.streaming.api.datastream.DataStream;

/**
 * The flink component can be used to send DataSet jobs to Apache Flink cluster.
 */
@UriEndpoint(firstVersion = "2.18.0", scheme = "flink", title = "Apache Flink", syntax = "flink:endpointType", producerOnly = true, label = "hadoop")
public class FlinkEndpoint extends DefaultEndpoint {

    @UriPath
    @Metadata(required = true)
    private EndpointType endpointType;
    @UriParam
    private DataSet dataSet;
    @UriParam
    private DataSetCallback dataSetCallback;
    @UriParam
    private DataStream dataStream;
    @UriParam
    private DataStreamCallback dataStreamCallback;
    @UriParam(defaultValue = "true")
    private boolean collect = true;

    public FlinkEndpoint(String endpointUri, FlinkComponent component, EndpointType endpointType) {
        super(endpointUri, component);
        this.endpointType = endpointType;
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();

        if (dataSet == null) {
            dataSet = getComponent().getDataSet();
        }

        if (dataSetCallback == null) {
            dataSetCallback = getComponent().getDataSetCallback();
        }
    }

    @Override
    public Producer createProducer() throws Exception {
        if (endpointType == EndpointType.dataset) {
            return new DataSetFlinkProducer(this);
        } else if (endpointType == EndpointType.datastream) {
            return new DataStreamFlinkProducer(this);
        } else {
            return null;
        }
    }

    @Override
    public Consumer createConsumer(Processor processor) throws Exception {
        throw new UnsupportedOperationException("Flink Component supports producer endpoints only.");
    }

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

    @Override
    public FlinkComponent getComponent() {
        return (FlinkComponent) super.getComponent();
    }

    /**
     * Type of the endpoint (dataset, datastream).
     */
    public void setEndpointType(EndpointType endpointType) {
        this.endpointType = endpointType;
    }

    public DataSet getDataSet() {
        return dataSet;
    }

    public DataStream getDataStream() {
        return dataStream;
    }

    /**
     * DataSet to compute against.
     */
    public void setDataSet(DataSet ds) {
        this.dataSet = ds;
    }

    /**
     * DataStream to compute against.
     */
    public void setDataStream(DataStream ds) {
        this.dataStream = ds;
    }

    public DataSetCallback getDataSetCallback() {
        return dataSetCallback;
    }

    public DataStreamCallback getDataStreamCallback() {
        return dataStreamCallback;
    }

    /**
     * Function performing action against a DataSet.
     */
    public void setDataSetCallback(DataSetCallback dataSetCallback) {
        this.dataSetCallback = dataSetCallback;
    }

    /**
     * Function performing action against a DataStream.
     */
    public void setDataStreamCallback(DataStreamCallback dataStreamCallback) {
        this.dataStreamCallback = dataStreamCallback;
    }

    public boolean isCollect() {
        return collect;
    }

    /**
     * Indicates if results should be collected or counted.
     */
    public void setCollect(boolean collect) {
        this.collect = collect;
    }
}


text:
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';

import { preloadedState, reducers } from 'modules/index';

const reducer = combineReducers(reducers);

const middleware = applyMiddleware(
	thunk,
	createLogger({
		collapsed: () => true,
		titleFormatter: ({ type }) => `${type[0]}${type.slice(1).split('_').join(' ').toLowerCase()}`
	})
);

export default createStore(reducer, preloadedState, middleware);


text:
<?php namespace Collectively\Registration;

use Laracasts\Commander\CommandHandler;
use Collectively\Users\UserRepository;
use Collectively\Users\User;

class RegisterUserCommandHandler implements CommandHandler {

    protected $repository;

    function __construct(UserRepository $repository) {
        $this->repository = $repository;
    }

    /**
     * Handle the command
     *
     * @param $command
     * $return mixed
     */
    public function handle($command)
    {
        $user = User::register(
            $command->email,
            $command->password,
            $command->firstname,
            $command->lastname
        );

        $this->repository->save($user);
        return $user;
    }
}


text:
require "spec_helper"

module HtmlSanitationSpec
  class Entity < Shamu::Entities::Entity
    include Shamu::Entities::HtmlSanitation

    attribute :name
  end
end

describe Shamu::Attributes::HtmlSanitation do
  let( :entity ) { HtmlSanitationSpec::Entity.new( name: "Bold
Name
" ) }

  it "removes all HTML by default" do
    expect( entity.name ).to eq "Bold Name"
  end
end


text:
#pragma once
#include <aws/ce/CostExplorer_EXPORTS.h>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace CostExplorer
{
namespace Model
{
  class AWS_COSTEXPLORER_API DeleteAnomalySubscriptionResult
  {
  public:
    DeleteAnomalySubscriptionResult();
    DeleteAnomalySubscriptionResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DeleteAnomalySubscriptionResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

  };

} // namespace Model
} // namespace CostExplorer
} // namespace Aws


text:
/**
 * Simple service to activate noty2 message to GUI. This service can be used every where in application. Generally
 * all $http and $socket queries uses this service to show specified errors to user.
 *
 * Service can be used as in following examples (assuming that you have inject this service to your controller):
 *  Message.success(message, [title], [options]);
 *  Message.error(message, [title], [options]);
 *  Message.message(message, [title], [options]);
 *
 * Feel free to be happy and code some awesome stuff!
 *
 * @todo do we need some queue dismiss?
 */
(function() {
    'use strict';

    angular.module('phpucMonitor.core.services')
        .factory('MessageService',
            function(toastr, _) {
                var service = {};

                /**
                 * Private helper function to make actual message via toastr component.
                 *
                 * @param   {string}    message         Message content
                 * @param   {string}    title           Message title
                 * @param   {{}}        options         Message specified options
                 * @param   {{}}        defaultOptions  Default options for current message type
                 * @param   {string}    type            Message type
                 * @private
                 */
                function _makeMessage(message, title, options, defaultOptions, type) {
                    title = title || '';
                    options = options || {};

                    toastr[type](message, title, _.assign(defaultOptions, options));
                }

                /**
                 * Method to generate 'success' message.
                 *
                 * @param   {string}    message     Message content
                 * @param   {string}    [title]     Message title
                 * @param   {{}}        [options]   Message options
                 */
                service.success = function success(message, title, options) {
                    var defaultOptions = {
                        timeOut: 2000
                    };

                    _makeMessage(message, title, options, defaultOptions, 'success');
                };

                /**
                 * Method to generate 'info' message.
                 *
                 * @param   {string}    message     Message content
                 * @param   {string}    [title]     Message title
                 * @param   {{}}        [options]   Message options
                 */
                service.info = function error(message, title, options) {
                    var defaultOptions = {
                        timeout: 3000
                    };

                    _makeMessage(message, title, options, defaultOptions, 'info');
                };

                /**
                 * Method to generate 'warning' message.
                 *
                 * @param   {string}    message     Message content
                 * @param   {string}    [title]     Message title
                 * @param   {{}}        [options]   Message options
                 */
                service.warning = function error(message, title, options) {
                    var defaultOptions = {
                        timeout: 3000
                    };

                    _makeMessage(message, title, options, defaultOptions, 'warning');
                };

                /**
                 * Method to generate 'error' message.
                 *
                 * @param   {string}    message     Message content
                 * @param   {string}    [title]     Message title
                 * @param   {{}}        [options]   Message options
                 */
                service.error = function error(message, title, options) {
                    var defaultOptions = {
                        timeout: 4000
                    };

                    _makeMessage(message, title, options, defaultOptions, 'error');
                };

                return service;
            }
        );
}());


text:
using Gx.Common;
// <auto-generated>
//
//
// Generated by Enunciate.
// </auto-generated>
using System;

namespace Gx.Fs.Tree
{

    /// <remarks>
    ///
    /// </remarks>
    ///
    ///
    ///
    // TODO: Create attribute equivalent to JsonWrapper (for each call to FindExtensionsOfType<T>() and FindExtensionOfType<T>())
    [System.SerializableAttribute()]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://familysearch.org/v1/", TypeName = "DiscussionReference")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://familysearch.org/v1/", ElementName = "discussion-reference")]
    public sealed partial class DiscussionReference : Gx.Links.HypermediaEnabledData
    {

        private string _resourceId;
        private string _resource;
        private Gx.Common.Attribution _attribution;
        ///
        ///  The id of the discussion being referenced.
        ///
        [System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "resourceId")]
        [Newtonsoft.Json.JsonProperty("resourceId")]
        public string ResourceId
        {
            get
            {
                return this._resourceId;
            }
            set
            {
                this._resourceId = value;
            }
        }
        ///
        ///  The URI to the resource.
        ///
        [System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "resource")]
        [Newtonsoft.Json.JsonProperty("resource")]
        public string Resource
        {
            get
            {
                return this._resource;
            }
            set
            {
                this._resource = value;
            }
        }
        ///
        ///  The attribution metadata for this discussion reference.
        ///
        [System.Xml.Serialization.XmlElementAttribute(ElementName = "attribution", Namespace = "http://familysearch.org/v1/")]
        [Newtonsoft.Json.JsonProperty("attribution")]
        public Gx.Common.Attribution Attribution
        {
            get
            {
                return this._attribution;
            }
            set
            {
                this._attribution = value;
            }
        }

        /**
         * Build up this discussion reference with a resource id.
         *
         * @param resourceId The resource id.
         * @return this.
         */
        public DiscussionReference SetResourceId(String resourceId)
        {
            ResourceId = resourceId;
            return this;
        }

        /**
         * Build up this discussion reference with attribution.
         *
         * @param attribution The attribution.
         * @return this.
         */
        public DiscussionReference SetAttribution(Attribution attribution)
        {
            Attribution = attribution;
            return this;
        }
    }
}


text:
/*==================================================
 *  German localization
 *==================================================
 */
(function() {
    var javascriptFiles = [
        "exhibit-l10n.js",
        "data/database-l10n.js",
        "ui/ui-context-l10n.js",
        "ui/lens-l10n.js",
        "ui/formatter-l10n.js",
        "ui/widgets/collection-summary-widget-l10n.js",
        "ui/views/view-panel-l10n.js",
        "ui/views/ordered-view-frame-l10n.js",
        "ui/views/tile-view-l10n.js",
        "ui/views/thumbnail-view-l10n.js",
        "ui/views/tabular-view-l10n.js",
        "util/coders-l10n.js",
        "util/facets-l10n.js",
        "util/views-l10n.js"
    ];
    var cssFiles = [
    ];

    var urlPrefix = Exhibit.urlPrefix + "locales/de/";
    if (Exhibit.params.bundle) {
        SimileAjax.includeJavascriptFiles(document, urlPrefix, [ "exhibit-de-bundle.js" ]);
        if (cssFiles.length > 0) {
            SimileAjax.includeCssFiles(document, urlPrefix, [ "exhibit-de-bundle.css" ]);
        }
    } else {
        SimileAjax.includeJavascriptFiles(document, urlPrefix + "scripts/", javascriptFiles);
        SimileAjax.includeCssFiles(document, urlPrefix + "styles/", cssFiles);
    }
})();


text:
class Show < ActiveRecord::Base
  has_many :proposals
end


text:
using Faker.Extensions;

namespace Faker
{
    public static class Currency
    {
        public static string ThreeLetterCode()
        {
            return Resources.Currency.Iso3LetterCodes.Split(Config.Separator)
                .Random();
        }

        public static string Name()
        {
            return Resources.Currency.Names.Split(Config.Separator)
                .Random();
        }
    }
}


text: a system for shadow-bumping 4chan threads


text:
//============================================================================
//
// Copyright (C) 2006-2022 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
//============================================================================

package org.talend.components.netsuite.v2019_2;

import org.talend.components.netsuite.NetSuiteSourceOrSink;
import org.talend.components.netsuite.v2019_2.client.NetSuiteClientFactoryImpl;

/**
 *
 */
public class NetSuiteSourceOrSinkImpl extends NetSuiteSourceOrSink {

    public NetSuiteSourceOrSinkImpl() {
        clientFactory = NetSuiteClientFactoryImpl.INSTANCE;
    }
}


text:
bool ofGetUsingArbTex();

/// \brief Use GL_TEXTURE_RECTANGLE textures.
///
/// GL_TEXTURE_RECTANGLE textures are more intuitive since they allow pixel
/// based coordinates and are enabled by default.
///
/// GL_TEXTURE_2D textures use normalised texture coordinates (a float value
/// between 0 and 1 is used to express texture coordinates along width and
/// height).
///
/// GL_TEXTURE_2D textures are more widely supported and allow advanced features
/// such as mipmaps and texture compression.
///
/// \sa ofDisableArbTex()
/// \warning GL_TEXTURE_RECTANGLE is not available in OpenGL ES.
/// \warning GL_TEXTURE_RECTANGLE does not support mipmaps.
void ofEnableArbTex();

/// \brief Use GL_TEXTURE_2D textures.
///
/// GL_TEXTURE_2D is OpenGL's default way of handling textures and supports a
/// wider range of core OpenGL features such as mipmaps.
///
/// \sa ofEnableArbTex()
void ofDisableArbTex();

/// \brief Check whether OF is using normalized or pixel texture coordinates.
/// \sa ofEnableNormalizedTexCoords()
/// \returns true if using normalized (0 - 1) texture coordinates.
bool ofGetUsingNormalizedTexCoords();

/// \brief Use normalized (0 - 1) texture coordinates.
///
/// By default, textures in OF work with pixel-based coordinates based on given
/// content dimensions (images size, fbo size, etc). Normalized (0 - 1)
/// coordinates are the traditional OpenGL default as they allow working with
/// internal texture data without having to worry about specific dimensions of
/// the content.
///
/// This overrides individual ofTexture wrap settings.
///
/// \sa http://www.opengl.org/sdk/docs/man4/html/glTexParameter.xhtml
void ofEnableNormalizedTexCoords();

/// \brief Use pixel-based texture coordinates.
/// \sa ofEnableNormalizedTexCoords()
void ofDisableNormalizedTexCoords();

/// \brief Set custom global texture wrapping.
///
/// By default, textures are clamped to their edges with GL_CLAMP_TO_EDGE.
/// Setting a repeat mode like GL_REPEAT allows you to create tiled backgrounds
/// with small textures.
///
/// This overrides individual ofTexture wrap settings.
///
/// \sa ofTexture::setTextureWrap
/// \sa http://www.opengl.org/sdk/docs/man4/html/glTexParameter.xhtml
///
/// \warning Deprecated. Use member methods instead.
///
/// \param wrapS wrap parameter for texture coordinate s.
/// \param wrapT wrap parameter for texture coordinate t.
OF_DEPRECATED_MSG("Use member method ofTexture::setTextureWrap() instead.",void ofSetTextureWrap(GLfloat wrapS = GL_CLAMP_TO_EDGE, GLfloat wrapT = GL_CLAMP_TO_EDGE));

/// \brief Check whether OF is using custom global texture wrapping.
///
/// \warning Deprecated. Use member methods instead.
///
/// \sa ofSetTextureWrap()
/// \returns true if OF is currently using custom global texture wrapping.
OF_DEPRECATED_MSG("Use member method ofTexture::setTextureWrap() instead.",bool ofGetUsingCustomTextureWrap());

/// \brief Removes global custom texture wrapping.
///
/// Restores individual ofTexture wrap settings.
///
/// \warning Deprecated. Use member methods instead.
///
/// \sa ofSetTextureWrap()
OF_DEPRECATED_MSG("Use member method ofTexture::setTextureWrap() instead.",void ofRestoreTextureWrap());

/// \brief Set custom global texture minification/magnification scaling filters.
///
/// This setting allows global control over how OpenGL scales textures. It
/// overrides individual ofTexture min & mag filter settings.
///
/// \warning Deprecated. Use member methods instead.
///
/// \sa ofTexture::setTextureMinMagFilter()
/// \param minFilter minifying filter for scaling a pixel to a smaller area.
/// \param magFilter magnifying filter for scaling a pixel to a larger area.
OF_DEPRECATED_MSG("Use member method ofTexture::setTextureMinMagFilter() instead.",void ofSetMinMagFilters(GLfloat minFilter = GL_LINEAR, GLfloat magFilter = GL_LINEAR));

/// \brief Check whether OF is using custom global texture scaling filters.
/// \returns true if OF is currently using custom texture scaling filters.
/// \warning Deprecated. Use member methods instead.
OF_DEPRECATED_MSG("Use member method ofTexture::setTextureMinMagFilter() instead.",bool ofGetUsingCustomMinMagFilters());

/// \brief Removes global custom texture wrapping.
///
/// Restores individual ofTexture min mag filter settings.
/// \warning Deprecated. Use member methods instead.
OF_DEPRECATED_MSG("Use member method ofTexture::setTextureMinMagFilter() instead.",void ofRestoreMinMagFilters());

/// \}

/// \brief Texture compression types.
///
/// Compression is only available through OpenGL for textures using
/// GL_TEXTURE_2D, *not* GL_TEXTURE_RECTANGLE, also note that most compression
/// algorithms work on blocks of 4x4 pixels, and therefore expect compressed
/// textures to have multiple-of-four dimensions.
enum ofTexCompression {
	OF_COMPRESS_NONE,	///< No compression.
	OF_COMPRESS_SRGB,	///< sRGB compression.
	OF_COMPRESS_ARB		///< ARB compression.
};

/// \cond INTERNAL

/// \class ofTextureData
/// \brief Internal texture data structure.
///
/// Used by ofTexture internally. You won't need to work with this in most cases.
class ofTextureData {
public:
	ofTextureData() {
		textureID = 0;
#ifndef TARGET_OPENGLES
		glInternalFormat = GL_RGB8;
		textureTarget = GL_TEXTURE_RECTANGLE_ARB;
#else
		glInternalFormat = GL_RGB;
		textureTarget = GL_TEXTURE_2D;
#endif

		tex_t = 0;
		tex_u = 0;
		tex_w = 0;
		tex_h = 0;
		width = 0;
		height = 0;

		bFlipTexture = false;
		compressionType = OF_COMPRESS_NONE;
		bAllocated = false;
		bUseExternalTextureID = false;
		useTextureMatrix = false;

		minFilter = GL_LINEAR;
		magFilter = GL_LINEAR;

		wrapModeHorizontal = GL_CLAMP_TO_EDGE;
		wrapModeVertical = GL_CLAMP_TO_EDGE;
		hasMipmap = false;
		bufferId = 0;

	}

	unsigned int textureID; ///< GL internal texture ID.
	int textureTarget; ///< GL texture type, either GL_TEXTURE_2D or
	                   ///< GL_TEXTURE_RECTANGLE_ARB.
	int glInternalFormat; ///< GL internal format, e.g. GL_RGB8.
                        ///< \sa http://www.opengl.org/wiki/Image_Format

	float tex_t; ///< Texture horizontal coordinate, ratio of width to display width.
	float tex_u; ///< Texture vertical coordinate, ratio of height to display height.
	float tex_w; ///< Texture width (in pixels).
	float tex_h; ///< Texture height (in pixels).
	float width, height; ///< Texture display size.

	bool bFlipTexture; ///< Should the texture be flipped vertically?
	ofTexCompression compressionType; ///< Texture compression type.
	bool bAllocated; ///< Has the texture been allocated?

	GLint minFilter; ///< Filter to use for minification (reduction).
	GLint magFilter; ///< Filter to use for magnification (enlargement).

	GLint wrapModeHorizontal; ///< How will the texture wrap around horizontally?
	GLint wrapModeVertical; ///< How will the texture wrap around vertically?

	unsigned int bufferId; ///< Optionally if the texture is backed by a buffer so we can bind it
private:
	shared_ptr<ofTexture> alphaMask; ///< Optional alpha mask to bind
	bool bUseExternalTextureID; ///< Are we using an external texture ID?
	ofMatrix4x4 textureMatrix; ///< For required transformations.
	bool useTextureMatrix; ///< Apply the transformation matrix?
	bool hasMipmap; ///< True if mipmap has been generated for this texture, false by default.

	friend class ofTexture;

};

/// \endcond

/// \brief Enable the global texture "edge hack" to compensate for edge artifacts.
///
/// Adds a 2 pixel offset to avoid possible edge artifacts (typically a black or
/// white border). This *very slightly* alters the image by scaling.  This is
/// enabled by default.
void ofEnableTextureEdgeHack();

/// \todo Add docs on why the "edge hack" is needed.

/// \brief Disable global texture "edge hack".
/// \sa ofEnableTextureEdgeHack()
void ofDisableTextureEdgeHack();

/// \brief Check whether OF is using the texture "edge hack".
/// \sa ofEnableTextureEdgeHack()
/// \returns true if OF is currently using the texture "edge hack".
bool ofIsTextureEdgeHackEnabled();

/// \class ofTexture
/// \brief A wrapper class for an OpenGL texture.
class ofTexture : public ofBaseDraws {
	public :

	/// \name Construction and allocation
	/// \{

	/// \brief Construct an ofTexture instance.
	ofTexture();

	/// \brief Construct an ofTexture from an existing ofTexture.
	/// \param mom The ofTexture to copy. Reuses internal GL texture ID.
	ofTexture(const ofTexture & mom);
    ofTexture(ofTexture && mom);

	/// \brief Allocate the texture using the given settings.
	///
	/// This is useful if you need manual control over loading a number of
	/// textures with the same settings. Make sure to set the texture data
	/// parameters first.
	///
	/// \param textureData The settings to use when allocating the ofTexture.
	virtual void allocate(const ofTextureData & textureData);

	/// \brief Allocate the texture using the given settings and custom format.
	/// \param textureData The settings to use when allocating the ofTexture.
	/// \param glFormat GL texture format: GL_RGBA, GL_LUMINANCE, etc.
	/// \param pixelType GL pixel type: GL_UNSIGNED_BYTE, GL_FLOAT, etc.
	virtual void allocate(const ofTextureData & textureData, int glFormat, int pixelType);

	/// \brief Allocate texture of a given size and format.
	///
	/// The width (w) and height (h) do not necessarily need to be powers of 2,
	/// but they do need to be large enough to contain the data you will upload
	/// to the texture.
	///
	/// The internal data type `glFormat` describes how OpenGL will store this
	/// texture internally. For example, if you want a grayscale texture, you
	/// can use `GL_LUMINANCE`. You can upload what ever type of data you want
	/// (using `loadData()`) but internally, opengl will store the information
	/// as grayscale. Other types include: `GL_RGB`, `GL_RGBA`.
	///
	/// This method applies the currently set OF texture type and defaults to
	/// ARB rectangular textures if they are supported. (They are not supported
	/// on OpenGL ES).
	///
	/// \param w Desired width in pixels.
	/// \param h Desired height in pixels.
	/// \param glInternalFormat OpenGL internal data format: `GL_RGBA`, `GL_LUMINANCE`, etc.
	virtual void allocate(int w, int h, int glInternalFormat);

	/// \brief Allocate texture of a given size and format.
	///
	/// \sa allocate(int w, int h, int glInternalFormat)
	/// \param w Desired width in pixels.
	/// \param h Desired height in pixels.
	/// \param glInternalFormat The internal openGL format.
	/// \param glFormat The openGL format.
	/// \param pixelType GL pixel type: GL_UNSIGNED_BYTE, GL_FLOAT, etc.
	virtual void allocate(int w, int h, int glInternalFormat, int glFormat, int pixelType);

	/// \brief Allocate texture of a given size and format. Specify texture type.
	///
	/// This allows to enable the ARBE extension for this texture.
	/// This will overide the default OF texture type, in case you need a
	/// square texture (`GL_TEXTURE_2D`).
	///
	/// \warning ARB textures are not available in OpenGL ES.
	/// \sa ofEnableArbTex()
	/// \sa allocate(int w, int h, int glInternalFormat)
	/// \param w Desired width in pixels.
	/// \param h Desired height in pixels.
	/// \param glInternalFormat The internal openGL format.
	/// \param bUseARBExtension Set to true to use rectangular textures.
	virtual void allocate(int w, int h, int glInternalFormat, bool bUseARBExtension);

	/// \brief Allocate texture of a given size, format, & type.
	///
	/// \sa allocate(int w, int h, int glInternalFormat)
	/// \param w Desired width in pixels.
	/// \param h Desired height in pixels.
	/// \param glInternalFormat OpenGL data format: `GL_RGBA`, `GL_LUMINANCE`, etc.
	/// \param bUseARBExtension Set to true to use rectangular textures.
	/// \param glFormat The OpenGL format.
	/// \param pixelType OpenGL pixel type: `GL_UNSIGNED_BYTE`, `GL_FLOAT`, etc.
	virtual void allocate(int w, int h, int glInternalFormat, bool bUseARBExtension, int glFormat, int pixelType);

	/// \todo Not sure how the two texture format parameters are different:
	/// glFormat & glInternalFormat.

	/// \brief Allocate texture using an ofPixels instance.
	///
	/// Pixel type and OpenGL format are determined from pixel settings.
	///
	/// \param pix Reference to ofPixels instance.
	virtual void allocate(const ofPixels& pix);

	/// \brief Allocate texture using an ofPixels instance and type.
	///
	/// This lets you overide the default OF texture type in case you need a
	/// square GL_TEXTURE_2D texture.
	///
	/// \warning ARB textures are not available in OpenGL ES.
	/// \sa ofEnableArbTex()
	/// \sa allocate(const ofPixels& pix)
	/// \param pix Reference to ofPixels instance.
	/// \param bUseARBExtension Set to true to use rectangular textures.
	virtual void allocate(const ofPixels& pix, bool bUseARBExtension);

	/// \brief Allocate texture using an ofShortPixels instance.
	///
	/// Same as void allocate(const ofPixels& pix), except using ofShortPixels.
	///
	/// \sa allocate(const ofPixels& pix)
	/// \param pix Reference to ofShortPixels instance.
	virtual void allocate(const ofShortPixels& pix);

	/// \brief Allocate texture using an ofShortPixels instance and type.
	///
	/// Same as void void allocate(const ofPixels& pix), except using ofShortPixels.
	///
	/// \sa allocate(const ofShortPixels& pix)
	/// \param pix Reference to ofShortPixels instance.
	/// \param bUseARBExtension Set to true to use rectangular textures.
	virtual void allocate(const ofShortPixels& pix, bool bUseARBExtension);

	/// \brief Allocate texture using an ofFloatPixels instance.
	///
	/// Same as void allocate(const ofPixels& pix), except using ofFloatPixels.
	///
	/// \sa allocate(const ofPixels& pix)
	/// \param pix Reference to ofFloatPixels instance.
	virtual void allocate(const ofFloatPixels& pix);

	/// \brief Allocate texture using an ofShortPixels instance and type.
	///
	/// Same as void void allocate(const ofPixels& pix), except using ofShortPixels.
	///
	/// \sa allocate(const ofFloatPixels& pix)
	/// \param pix Reference to ofFloatPixels instance.
	/// \param bUseARBExtension Set to true to use rectangular textures.
	virtual void allocate(const ofFloatPixels& pix, bool bUseARBExtension);

#ifndef TARGET_OPENGLES
	/// \brief Allocate texture as a Buffer Texture.
	///
	/// Uses a GPU buffer as data for the texture instead of pixels in RAM
	/// Allows to use texture buffer objects (TBO) which make it easier to send big
	/// amounts of data to a shader as a uniform.
	///
	/// Buffer textures are 1D textures, and may only be sampled using texelFetch
	/// in GLSL.
	///
	/// See textureBufferInstanceExample and https://www.opengl.org/wiki/Buffer_Texture
	///
	/// \sa allocate(const ofBufferObject & buffer, int glInternalFormat)
	/// \param buffer Reference to ofBufferObject instance.
	/// \param glInternalFormat Internal pixel format of the data.
	void allocateAsBufferTexture(const ofBufferObject & buffer, int glInternalFormat);
#endif

	/// \brief Determine whether the texture has been allocated.
	///
	/// This lets you check if a texture is safe to draw.  The texture can both
	/// be allocated by using `allocate()` or loading it with data `loadData()`.
	///
	/// \returns true if the texture has been allocated.
	bool isAllocated() const;

	/// \brief Has the texture been allocated?
	///
	/// Legacy function for backwards compatibility.
	///
	/// \returns true if the texture has been allocated.
	OF_DEPRECATED_MSG("Use isAllocated instead",bool bAllocated() const);

	/// \brief Destroy an ofTexture instance.
	///
	/// ofTexture keeps a reference count for the internal OpenGL texture ID.
	/// Thus, the texture ID is only released if there are no additional
	/// references to the internal texture ID.
	virtual ~ofTexture();

	/// \}

	/// \name Update texture
	/// \{

	/// \brief Copy a given ofTexture into this texture.
	/// \param mom The ofTexture to copy from. Reuses internal GL texture ID.
	ofTexture& operator=(const ofTexture & mom);
    ofTexture& operator=(ofTexture && mom);

	/// \brief Clears the texture.
	///
	/// Clears / frees the texture memory, if something was already allocated.
	/// Useful if you need to control the memory on the graphics card.
	///
	/// The internal GL texture ID is only released if this is the last texture
	/// using it.
	void clear();

	/// \brief Set the texture ID.
	///
	/// Allows you to point the texture id to an externally allocated id
	/// (perhaps from another texture). It's up to you to set the rest of the
	/// textData parameters manually.
	///
	/// \warning When setting an external texture ID, the user must set the
	/// remaining ofTextureData parameters manually.
	/// \param externTexID New texture ID.
	void setUseExternalTextureID(GLuint externTexID);

	/// \brief Load byte pixel data.
	///
	/// glFormat can be different to the internal format of the texture on each
	/// load, i.e. we can upload GL_BGRA pixels into a GL_RGBA texture but the
	/// number of channels need to match according to the OpenGL standard.
	///
	/// \param data Pointer to byte pixel data. Must not be nullptr.
	/// \param w Pixel data width.
	/// \param h Pixel data height.
	/// \param glFormat GL pixel type: GL_RGBA, GL_LUMINANCE, etc.
	void loadData(const unsigned char* const data, int w, int h, int glFormat);

	/// \brief Load short (2 byte) pixel data.
	/// \sa loadData(const unsigned char* const data, int w, int h, int glFormat)
	/// \param data Pointer to byte pixel data. Must not be nullptr.
	/// \param w Pixel data width.
	/// \param h Pixel data height.
	/// \param glFormat GL pixel type: GL_RGBA, GL_LUMINANCE, etc.
	void loadData(const unsigned short* data, int w, int h, int glFormat);

	/// \brief Load float pixel data.
	/// \sa loadData(const unsigned char* const data, int w, int h, int glFormat)
	/// \param data Pointer to byte pixel data. Must not be nullptr.
	/// \param w Pixel data width.
	/// \param h Pixel data height.
	/// \param glFormat GL pixel type: GL_RGBA, GL_LUMINANCE, etc.
	void loadData(const float* data, int w, int h, int glFormat);

	/// \brief Load pixels from an ofPixels instance.
	/// \param pix Reference to ofPixels instance.
	void loadData(const ofPixels & pix);

	/// \brief Load pixels from an ofShortPixels instance.
	///
	/// Same as loadData(ofPixels &) but for ofShortPixels.
	///
	/// \sa loadData(const ofPixels & pix)
	/// \param pix Reference to ofShortPixels instance.
	void loadData(const ofShortPixels & pix);

	/// \brief Load pixels from an ofFloatPixels instance.
	///
	/// Same as loadData(ofPixels &) but for ofFloatPixels.
	///
	/// \sa loadData(const ofPixels & pix)
	/// \param pix Reference to ofFloatPixels instance.
	void loadData(const ofFloatPixels & pix);

	/// \brief Load pixels from an ofPixels instance and specify the format.
	///
	/// glFormat can be different to the internal format of the texture on each
	/// load, ie. we can upload GL_BGRA pixels into a GL_RGBA texture, but the
	/// number of channels need to match according to the OpenGL standard.
	///
	/// \param pix Reference to ofPixels instance.
	/// \param glFormat GL pixel type: GL_RGBA, GL_LUMINANCE, etc.
	void loadData(const ofPixels & pix, int glFormat);

	/// \brief Load pixels from an ofShortPixels instance & specify the format.
	///
	/// \sa loadData(const ofPixels & pix, int glFormat)
	/// \param pix Reference to ofShortPixels instance.
	/// \param glFormat GL pixel type: GL_RGBA, GL_LUMINANCE, etc.
	void loadData(const ofShortPixels & pix, int glFormat);

	/// \brief Load pixels from an ofFloatPixels instance and specify the format.
	///
	/// \sa loadData(const ofPixels & pix, int glFormat)
	/// \param pix Reference to ofFloatPixels instance.
	/// \param glFormat GL pixel type: GL_RGBA, GL_LUMINANCE, etc.
	void loadData(const ofFloatPixels & pix, int glFormat);

#ifndef TARGET_OPENGLES
	/// \brief Load pixels from an ofBufferObject
	///
	/// This is different to allocate(ofBufferObject,internal). That
	/// creates a texture which data lives in GL buffer while this
	/// copies the data from the buffer to the texture.
	///
	/// This is usually used to upload data to be shown asynchronously
	/// by using a buffer object binded as a PBO
	///
	/// \param buffer The buffer to load.
	/// \param glFormat GL pixel type: GL_RGBA, GL_LUMINANCE, etc.
	/// \param glType the GL type to load.
	void loadData(const ofBufferObject & buffer, int glFormat, int glType);
#endif

	/// \brief Copy an area of the screen into this texture.
	///
	/// Specifiy the position (x,y) you wish to grab from, with the width (w)
	/// and height (h) of the region.
	///
	/// Make sure that you have allocated your texture (using `allocate()`)
	/// to be large enough to hold the region of the screen you wish to load.
	///
	/// \sa http://www.opengl.org/sdk/docs/man4/html/glCopyTexSubImage2D.xhtml
	///
	/// \param x Upper left corner horizontal screen position.
	/// \param y Upper left corner vertical screen position.
	/// \param w Width of the area to copy in pixels.
	/// \param h Height of the area to copy in pixels.
	void loadScreenData(int x, int y, int w, int h);

	/// \}

	/// \name Drawing
	/// \{

	using ofBaseDraws::draw;

	void draw(float x, float y) const;
	void draw(float x, float y, float z) const;

	void draw(float x, float y, float w, float h) const;

	/// \brief Draw the texture at a given size witdh and depth.
	///
	/// \param x Draw position on the x axis.
	/// \param y Draw position on the y axis.
	/// \param z Draw position on the z axis.
	/// \param w Draw width.
	/// \param h Draw height.
	void draw(float x, float y, float z, float w, float h) const;

	/// \brief Draws the texture at 4 points passed in as if you created 4 glVertices.
	///
	/// \param p1 Upper left position on the x axis.
	/// \param p2 Upper left position on the y axis.
	/// \param p3 Lower right position on the x axis.
	/// \param p4 Lower right position on the y axis.
	void draw(const ofPoint & p1, const ofPoint & p2, const ofPoint & p3, const ofPoint & p4) const;

	/// \brief Draw a subsection of the texture.
	///
	/// Like ofRect() depend on the current `OF_RECT_MODE`:
	///
	/// * `OF_RECT_MODE_CORNER`: drawn with the upper left corner = (x,y)
	/// * `OF_RECT_MODE_CENTER`: drawn centered on (x,y)
	///
	/// \sa ofSetRectMode()
	///
	/// \param x Draw position on the x axis.
	/// \param y Draw position on the y axis.
	/// \param w Draw width.
	/// \param h Draw height.
	/// \param sx Subsection x axis offset within the texture.
	/// \param sy Subsection y axis offset within the texture.
	void drawSubsection(float x, float y, float w, float h, float sx, float sy) const;

	/// \brief Draw a subsection of the texture with depth.
	///
	/// \sa drawSubsection(float x, float y, float w, float h, float sx, float sy)
	/// \param x Draw position on the x axis.
	/// \param y Draw position on the y axis.
	/// \param z Draw position on the z axis.
	/// \param w Draw width.
	/// \param h Draw height.
	/// \param sx Subsection x axis offset within the texture.
	/// \param sy Subsection y axis offset within the texture.
	void drawSubsection(float x, float y, float z, float w, float h, float sx, float sy) const;

	/// \brief Draw a subsection of the texture with an offset.
	///
	/// \sa drawSubsection(float x, float y, float w, float h, float sx, float sy)
	/// \param x Draw position on the x axis.
	/// \param y Draw position on the y axis.
	/// \param w Draw width.
	/// \param h Draw height.
	/// \param sx Subsection x axis offset within the texture.
	/// \param sy Subsection y axis offset within the texture.
	/// \param sw Subsection width within the texture.
	/// \param sh Subsection height within the texture.
	void drawSubsection(float x, float y, float w, float h, float sx, float sy, float sw, float sh) const;

	/// \brief Draw a subsection of the texture with an offset and depth.
	///
	/// \sa drawSubsection(float x, float y, float w, float h, float sx, float sy)
	/// \param x Draw position on the x axis.
	/// \param y Draw position on the y axis.
	/// \param z Draw position on the z axis.
	/// \param w Draw width.
	/// \param h Draw height.
	/// \param sx Subsection x axis offset within the texture.
	/// \param sy Subsection y axis offset within the texture.
	/// \param sw Subsection width within the texture.
	/// \param sh Subsection height within the texture.
	void drawSubsection(float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh) const;

	ofMesh getQuad(const ofPoint & p1, const ofPoint & p2, const ofPoint & p3, const ofPoint & p4) const;

	/// \brief Get a mesh that has the texture coordinates set.
	///
	/// \sa drawSubsection(float x, float y, float w, float h, float sx, float sy)
	/// \param x Draw position on the x axis.
	/// \param y Draw position on the y axis.
	/// \param z Draw position on the z axis.
	/// \param w Draw width.
	/// \param h Draw height.
	/// \param sx Subsection x axis offset within the texture.
	/// \param sy Subsection y axis offset within the texture.
	/// \param sw Subsection width within the texture.
	/// \param sh Subsection height within the texture.
	/// \param vflipped Takes into account the flipped state in OF.
	/// \param rectMode rectMode Taking x,y as the center or the top left corner.
	ofMesh getMeshForSubsection(float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh, bool vflipped, ofRectMode rectMode) const;

	/// \brief Bind the texture.
	///
	/// For advanced users who need to manually manage texture drawing without
	/// calling ofTexture::draw.
	///
	/// \sa http://www.opengl.org/sdk/docs/man4/html/glBindTexture.xhtml
	void bind(int textureLocation=0) const;

	/// \brief Unbind the texture.
	///
	/// For advanced users who need to manually manage texture drawing without
	/// calling ofTexture::draw.
	///
	/// \sa http://www.opengl.org/sdk/docs/man4/html/glBindTexture.xhtml
	///
	void unbind(int textureLocation=0) const;

#if !defined(TARGET_OPENGLES) && defined(glBindImageTexture)
	/// Calls glBindImageTexture on the texture
	///
	/// Binds the texture as an read or write image, only available since OpenGL 4.2
	/// \warning This is not available in OpenGLES
	/// \sa http://www.opengl.org/wiki/GLAPI/glBindImageTexture
	void bindAsImage(GLuint unit, GLenum access, GLint level=0, GLboolean layered=0, GLint layer=0);
#endif

	const ofTexture * getAlphaMask() const;
	/// \}

	/// \name Size and coordinates
	/// \{

	/// \brief Display height of texture.
	///
	/// Return value is pixel size (default) or normalized (0 - 1) if ofEnableNormalizedTextures() is set to true.
	///
	/// \sa ofEnabledNormalizedTextures()
	///
	/// \returns Display height of texture in pixels.
	float getHeight() const;

	/// \brief Display width of texture.
	///
	/// Return value is pixel size (default) or normalized (0 - 1) if ofEnableNormalizedTextures() is set to true.
	///
	/// \sa ofEnabledNormalizedTextures()
	///
	/// \returns Display width of texture in pixels.
	float getWidth() const;

	/// \brief Set the anchor point the texture is drawn around as a percentage.
	///
	/// This can be useful if you want to rotate an image around a particular
	/// point.
	///
	/// \param xPct Horizontal texture position as a percentage (0 - 1).
	/// \param yPct Vertical texture position as a percentage (0 - 1).
	void setAnchorPercent(float xPct, float yPct);

	/// \brief Set the anchor point the texture is drawn around in pixels.
	///
	/// This can be useful if you want to rotate an image around a particular
	/// point.
	///
	/// \param x Horizontal texture position in pixels.
	/// \param y Vertical texture position in pixels.
	void setAnchorPoint(float x, float y);

	/// \brief Reset the anchor point to (0, 0).
	void resetAnchor();

	/// \brief Helper to convert display coordinate to texture coordinate.
	/// \param xPos Horizontal position in pixels.
	/// \param yPos Vertical position in pixels.
	/// \returns Texture coordinate or ofPoint::zero() if texture is not allocated.
	ofPoint getCoordFromPoint(float xPos, float yPos) const;

	/// \brief Helper to convert display coordinate to texture coordinate.
	/// \param xPts Horizontal position in a normalized percentage (0 - 1).
	/// \param yPts Vertical position in a normalized percentage (0 - 1).
	/// \returns Texture coordinate or ofPoint::zero() if texture is not allocated.
	ofPoint getCoordFromPercent(float xPts, float yPts) const;

	/// \}

	/// \name Texture settings
	/// \{

	/// \brief Set another ofTexture to use as an alpha mask.
	/// \param mask The texture to use as alpha mask.
	void setAlphaMask(ofTexture & mask);

	/// \brief Disable the alpha mask.
	void disableAlphaMask();

	/// \brief Set texture wrapping.
	///
	/// By default, textures are clamped to their edges with `GL_CLAMP_TO_EDGE`.
	/// Setting a repeat mode like `GL_REPEAT` allows you to create tiled
	/// backgrounds with small textures.
	///
	/// \sa ofTextureSetWrap()
	/// \sa http://www.opengl.org/sdk/docs/man4/html/glTexParameter.xhtml
	///
	/// \warning May be overridden.
	///
	/// \param wrapModeHorizontal wrap parameter for texture coordinate s.
	/// \param wrapModeVertical wrap parameter for texture coordinate t.
	void setTextureWrap(GLint wrapModeHorizontal, GLint wrapModeVertical);

	/// \brief Set texture minification/magnification scaling filters.
	///
	/// Controls how OpenGL will scale this texture.
	///
	/// \sa http://www.opengl.org/sdk/docs/man4/html/glTexParameter.xhtml
	/// \sa ofTextureSetMinMagFilters()
	///
	/// \warning May be overridden.
	///
	/// \param minFilter minifying filter for scaling a pixel to a smaller area.
	/// \param magFilter magnifying filter for scaling a pixel to a larger area.
	void setTextureMinMagFilter(GLint minFilter, GLint magFilter);

	/// \brief Sets a texture matrix to be uploaded whenever the texture is bound.
	/// \param m The 4x4 texture matrix.
	void setTextureMatrix(const ofMatrix4x4 & m);

	const ofMatrix4x4 & getTextureMatrix() const;

	bool isUsingTextureMatrix() const;

	/// Disable the texture matrix.
	/// \brief Disable the texture matrix.
	void disableTextureMatrix();

	/// \brief Set the texture compression.
	///
	/// \warning: not yet implemented.
	/// \sa ofTexCompression
	void setCompression(ofTexCompression compression);

	/// \todo Define Swizzle in the documentation.
	/// \brief Swizzle RGBA to grayscale with alpha in the red channel.
	///
	/// Use 1 channel GL_R as luminance instead of red channel in OpenGL 3+.
	///
	/// \warning This is not supported in OpenGL ES and does nothing.
	/// \sa https://en.wikipedia.org/wiki/Swizzling_(computer_graphics)
	void setRGToRGBASwizzles(bool rToRGBSwizzles);

	/// \brief Swizzle a channel to another
	///
	/// Example:
	///
	/// ~~~~~
	/// ofTexture tex;
	/// tex.setSwizzle(GL_TEXTURE_SWIZZLE_R,GL_ALPHA);
	/// ~~~~~
	///
	/// will make channel 0 appear as alpha in the shader.
	///
	/// \warning This is not supported in OpenGL ES and does nothing.
	/// \sa https://en.wikipedia.org/wiki/Swizzling_(computer_graphics)
	void setSwizzle(GLenum srcSwizzle, GLenum dstChannel);

	/// \}

	/// \name Read pixel data
	/// \{

	/// \brief Read current texture data from the GPU into pixels.
	///
	/// \warning This is not supported in OpenGL ES and does nothing.
	///
	/// \param pixels Target ofPixels reference.
	void readToPixels(ofPixels & pixels) const;

	/// \brief Read current texture data from the GPU into pixels.
	///
	/// \warning This is not supported in OpenGL ES and does nothing.
	///
	/// \param pixels Target pixels reference.
	void readToPixels(ofShortPixels & pixels) const;

	/// \brief Read current texture data from the GPU into pixels.
	///
	/// \warning This is not supported in OpenGL ES and does nothing.
	///
	/// \param pixels Target pixels reference.
	void readToPixels(ofFloatPixels & pixels) const;

#ifndef TARGET_OPENGLES
	/// \brief Copy the texture to an ofBufferObject.
	/// \param buffer the target buffer to copy to.
	void copyTo(ofBufferObject & buffer) const;
#endif

	/// \}

	/// \name Texture data
	/// \{

	/// \brief Internal texture data access.
	///
	/// This returns the internal texture data for this texture, for instance,
	/// its textureID, type of texture, whether it's been allocated and other
	/// data about the state of the texture.
	///
	/// \returns a reference to the internal texture data struct.
	ofTextureData& getTextureData();

	/// \brief Const version of getTextureData().
	/// \sa ofTextureData::getTextureData()
	const ofTextureData& getTextureData() const;

	/// \}

	/// \name Mipmapping
	/// \{

	/// \brief Sets flag allowing texture to auto-generate a mipmap.
	///
	/// By default, this will set your minFilter to GL_LINEAR_MIPMAP_LINEAR.
	/// If you want to change your minFilter later use setTextureMinMagFilter()
	///
	///	If you want to generate a mipmap later, or at a specific
	/// point in your code, use generateMipmap() instead.
	///
	/// \sa generateMipmap()
	/// \sa disableMipmap()
	/// \sa setTextureMinMagFilter()
	void enableMipmap();

	/// \brief Sets flag disallowing texture to auto-generate mipmap.
	///
	/// By default, this will set your minFilter to GL_LINEAR_MIPMAP_LINEAR.
	/// If you want to change your minFilter later use setTextureMinMagFilter()
	///
	///	If you want to generate a mipmap later, or at a specific
	/// point in your code, use ofTexture::generateMipmap() instead.
	///
	/// \sa generateMipmap()
	/// \sa enableMipmap()
	/// \sa setTextureMinMagFilter()
	void disableMipmap();

	/// \brief Generate mipmap for the current texture.
	///
	/// \warning Only GL_TEXTURE_RECTANGLE - which is the default openFrameworks
	/// texture target - does *not* support mipmaps, so make sure to call
	/// ofDisableArbTex() before loading texture
	/// data for a texture you want to generate mipmaps for.
	///
	/// \sa ofEnableArbTex()
	/// \sa ofDisableArbTex()
	void generateMipmap();

	/// \brief Find out if a mipmap has been generated for the current texture.
	///
	/// \sa generateMipmap()
	/// \sa enableMipmap()
	bool hasMipmap() const;

	/// \}

	/// \cond INTERNAL
	ofTextureData texData; ///< Internal texture data access.
	                       ///< For backwards compatibility.

protected:
	/// \brief Load byte pixel data.
	///
	/// glFormat can be different to the internal format of the texture on each
	/// load, i.e. we can upload GL_BGRA pixels into a GL_RGBA texture but the
	/// number of channels need to match according to the OpenGL standard.
	///
	/// \param data Pointer to byte pixel data. Must not be nullptr.
	/// \param w Pixel data width.
	/// \param h Pixel data height.
	/// \param glFormat GL pixel type: GL_RGBA, GL_LUMINANCE, etc.
	/// \param glType the OpenGL type of the data.
    void loadData(const void * data, int w, int h, int glFormat, int glType);

	/// \brief Enable a texture target.
	/// \param textureLocation the OpenGL texture ID to enable as a target.
	void enableTextureTarget(int textureLocation) const;

	/// \brief Disable a texture target.
	/// \param textureLocation the OpenGL texture ID to enable as a target.
	void disableTextureTarget(int textureLocation) const;

	ofPoint anchor; ///< The texture's anchor point.

	bool bAnchorIsPct; ///< Is the anchor point represented as a normalized
					   ///< (0 - 1) coordinate?

	/// \endcond

private:
	bool bWantsMipmap; ///< Should mipmaps be created?

};


text:
/*
 * 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.
 */

package kr.co.bitnine.octopus;

import org.postgresql.jdbc4.Jdbc4Connection;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class OctopusDatabaseMetaData extends AbstractDatabaseMetaData {
    private final Connection connection;

    OctopusDatabaseMetaData(Jdbc4Connection conn) {
        this.connection = conn;
    }

    @Override
    public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException {
        Statement stmt = createMetaDataStatement();

        String sql = "SHOW TABLES";
        if (catalog != null)
            sql += " DATASOURCE \"" + catalog + '"';
        if (schemaPattern != null)
            sql += " SCHEMA '" + schemaPattern + "'";
        if (tableNamePattern != null)
            sql += " TABLE '" + tableNamePattern + "'";

        return stmt.executeQuery(sql);
    }

    @Override
    public ResultSet getSchemas() throws SQLException {
        return createMetaDataStatement().executeQuery("SHOW SCHEMAS");
    }

    @Override
    public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException {
        Statement stmt = createMetaDataStatement();

        String sql = "SHOW SCHEMAS";
        if (catalog != null)
            sql += " DATASOURCE \"" + catalog + '"';
        if (schemaPattern != null)
            sql += " SCHEMA '" + schemaPattern + "'";

        return stmt.executeQuery(sql);
    }

    @Override
    public ResultSet getCatalogs() throws SQLException {
        return createMetaDataStatement().executeQuery("SHOW DATASOURCES");
    }

    @Override
    public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException {
        Statement stmt = createMetaDataStatement();

        String sql = "SHOW COLUMNS";
        if (catalog != null)
            sql += " DATASOURCE \"" + catalog + '"';
        if (schemaPattern != null)
            sql += " SCHEMA '" + schemaPattern + "'";
        if (tableNamePattern != null)
            sql += " TABLE '" + tableNamePattern + "'";
        if (columnNamePattern != null)
            sql += " COLUMN '" + columnNamePattern + "'";

        return stmt.executeQuery(sql);
    }

    @Override
    public Connection getConnection() throws SQLException {
        return connection;
    }

    private Statement createMetaDataStatement() throws SQLException {
        return getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    }
}


text:
package org.apache.servicecomb.swagger.invocation.schemas;

import org.apache.servicecomb.swagger.invocation.schemas.models.AddWrapperV2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping
public interface SpringmvcAddWrapperV2 {
  @GetMapping(path = "/add")
  int add(AddWrapperV2 wrapper);
}


text:
package commands

import (
	"github.com/purrgil/purrgil/configs"
	"github.com/purrgil/purrgil/file"
	"github.com/purrgil/purrgil/interactiveshell"
	"os"
)

func Add(pkgId string, opts configs.AddConfig) {
	ishell.PurrgilAlert("Starting Purrgil Add on Package: " + pkgId)

	path, _ := os.Getwd()

	purrgilconfig := file.NewPurrgil(path, "")
	dockercompose := file.NewDockerCompose(path)
	gitignore := file.NewGitIgnore(path)
	purrgilNewPackage := file.NewPurrgilPackage(pkgId, opts)

	PackageInstall(purrgilNewPackage)

	purrgilconfig.AddPackage(purrgilNewPackage)
	gitignore.AddIgnoredPath(purrgilNewPackage.Name)

	ishell.PurrgilAlert("Preparing to Collect Aditional Information...")

	if opts.ComposeConfig {
		callComposeConfigInterface(purrgilNewPackage, &dockercompose)
	}

	purrgilconfig.SaveFile()
	dockercompose.SaveFile()
	gitignore.SaveFile()

	ishell.PurrgilAlert(purrgilNewPackage.Name + " was successfuly added")
}

func callComposeConfigInterface(pkg file.PurrgilPackage, dc *file.DockerComposeFile) {
	if pkg.Service {
		serviceName, service := ishell.CollectDockerServiceInfo(pkg, *dc)
		dc.AddService(serviceName, service)
	} else {
		packages := ishell.CollectLinkPossibility(pkg)
		dc.LinkInService(pkg.Name, packages)
	}
}


text:
package com.twitter.graphjet.bipartite.segment;

import java.util.List;

import com.twitter.graphjet.bipartite.api.EdgeTypeMask;
import com.twitter.graphjet.bipartite.api.LeftIndexedBipartiteGraph;
import com.twitter.graphjet.bipartite.api.NodeMetadataDynamicBipartiteGraph;
import com.twitter.graphjet.hashing.IntToIntArrayMap;
import com.twitter.graphjet.stats.StatsReceiver;

/**
 * A graph segment is a bounded portion of the graph with a cap on the number of nodes and edges
 * one can store in it. This class abstracts away the logic of maintain common indexes for all
 * bipartite graph segments and in particular it is transparent to the kind of edge pools used
 * for the actual segment. A client can plug in the kind of pools it wants to use for the left
 * and right side.
 *

 * The way the graph segment here works is via having separate edge pools for left and right side
 * adjacency lists. These pools hold all the logic of addition/deletion/retrieval of edges with the
 * role of this class being to maintain a mapping from the incoming long ids for nodes to ints.
 * This allows the edge pools to deal only with ints, hence reducing the memory usage a lot since
 * edges take up most of the memory. The transformation being long to ints however does impose a
 * limit on how many id's we can store in a segment, and this is constraint mentioned above.
 *

 * This class is thread-safe even though it does not do any locking: it achieves this by leveraging
 * the assumptions stated below and using a "memory barrier" between writes and reads to sync
 * updates.
 *
 * Here are the client assumptions needed to enable lock-free read/writes:
 * 1. There is a SINGLE writer thread -- this is extremely important as we don't lock during writes.
 * 2. Readers are OK reading stale data, i.e. if even if a reader thread arrives after the writer
 * thread started doing a write, the update is NOT guaranteed to be available to it.
 *
 * This class enables lock-free read/writes by guaranteeing the following:
 * 1. The writes that are done are always "safe", i.e. in no time during the writing do they leave
 *    things in a state such that a reader would either encounter an exception or do wrong
 *    computation.
 * 2. After a write is done, it is explicitly "published" such that a reader that arrives after
 *    the published write it would see updated data.
 *
 * The way this works is as follows: suppose we have some linked objects X, Y and Z that need to be
 * maintained in a consistent state. First, our setup ensures that the reader is _only_ allowed to
 * access these in a linear manner as follows: read X -> read Y -> read Z. Then, we ensure that the
 * writer behavior is to write (safe, atomic) updates to each of these in the exact opposite order:
 * write Z --flush--> write Y --flush--> write X.
 *
 * Note that the flushing ensures that if a reader sees Y then it _must_ also see the updated Z,
 * and if sees X then it _must_ also see the updated Y and Z. Further, each update itself is safe.
 * For instance, a reader can safely access an updated Z even if X and Y are not updated since the
 * updated information will only be accessible through the updated X and Y (the converse though is
 * NOT true). Together, this ensures that the reader accesses to the objects are always consistent
 * with each other and safe to access by the reader.
 */
public abstract class NodeMetadataLeftIndexedBipartiteGraphSegment
  extends LeftIndexedBipartiteGraphSegment
  implements LeftIndexedBipartiteGraph,
  NodeMetadataDynamicBipartiteGraph,
  ReusableLeftIndexedBipartiteGraphSegment {

  // This object contains ALL the reader-accessible data
  private final NodeMetadataLeftIndexedReaderAccessibleInfoProvider readerAccessibleInfoProvider;

  /**
   * The constructor tries to reserve most of the memory that is needed for the graph.
   *
   * @param expectedNumLeftNodes               is the expected number of left nodes that
   *                                           would be inserted in the segment
   * @param expectedNumRightNodes              is the expected number of right nodes that
   *                                           would be inserted in the segment
   * @param maxNumberOfEdges                   is the maximum number of edges to keep in
   *                                           the segment
   * @param readerAccessibleInfoProvider       provides the {@link
   *                                           NodeMetadataLeftIndexedReaderAccessibleInfoProvider}
   *                                           that encapsulates all the info that a
   *                                           reader of the segment would access
   * @param edgeTypeMask                       is the mask to encode edge type into integer node id
   * @param statsReceiver                      tracks the internal stats
   */
  public NodeMetadataLeftIndexedBipartiteGraphSegment(
    int expectedNumLeftNodes,
    int expectedNumRightNodes,
    int maxNumberOfEdges,
    NodeMetadataLeftIndexedReaderAccessibleInfoProvider readerAccessibleInfoProvider,
    EdgeTypeMask edgeTypeMask,
    StatsReceiver statsReceiver) {
    super(
      expectedNumLeftNodes,
      expectedNumRightNodes,
      maxNumberOfEdges,
      readerAccessibleInfoProvider,
      edgeTypeMask,
      statsReceiver.scope("NodeMetadataLeftIndexedBipartiteGraphSegment")
    );
    this.readerAccessibleInfoProvider = readerAccessibleInfoProvider;
  }

  @Override
  public void addEdge(
    long leftNode,
    long rightNode,
    byte edgeType,
    long edgeMetadata,
    int[][] leftNodeMetadata,
    int[][] rightNodeMetadata
  ) {
    // We need to the nodes to the map at the very top since once we write an edge, we need to be
    // able to find it's corresponding external id. On the other hand, if a reader finds an id in
    // the map it still won't be able to get to the edges till the edge is written so this is safe.
    // The following gets the internal id's and add the nodes if they're not already in there.
    int leftNodeInternalId = readerAccessibleInfoProvider
      .getReaderAccessibleInfo().addLeftNode(leftNode);
    int rightNodeInternalId = readerAccessibleInfoProvider
      .getReaderAccessibleInfo().addRightNode(rightNode);

    // Update RightNodesToMetadataMap, which has its own memory barrier internally.
    if (rightNodeMetadata != null) {
      for (int i = 0; i < rightNodeMetadata.length; i++) {
        readerAccessibleInfoProvider.getReaderAccessibleInfo().
          getRightNodesToMetadataMap(i).put(rightNodeInternalId, rightNodeMetadata[i]);
      }
    }

    // At this point there is an internal memory barrier deep inside LeftIndexedReaderAccessibleInfo
    // so that node mappings are visible if the edge is visible

    // Now we can add the edge

    // First we add the edges to the left pool so that it is ready to be accessed
    readerAccessibleInfoProvider
      .getLeftIndexedReaderAccessibleInfo().getLeftNodeEdgePool().addEdge(
      leftNodeInternalId, edgeTypeMask.encode(rightNodeInternalId, edgeType), edgeMetadata);

    // Finally, explicitly flush the edge write so that the edge is visible to the readers
    currentNumEdges++;

    numEdgesCounter.incr();
  }

  public List<IntToIntArrayMap> getLeftNodesToMetadataMap() {
    return null;
  }

  public List<IntToIntArrayMap> getRightNodesToMetadataMap() {
    return readerAccessibleInfoProvider
      .getReaderAccessibleInfo().getRightNodesToMetadataMap();
  }
}


text: <mat-toolbar>My App</mat-toolbar>


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
  <meta name="description" content="Eureka Solutions, C.A">
  <meta name="keywords" content="Eureka, Solutions, Eureka Solutions, Venezuela innovación, startup">
  <meta name="author" content="Eureka Solutions, C.A">
  <link rel="icon" type="image/vnd.microsoft.icon" href="image/favicon-16x16.png" />
  <title>Eureka Solutions</title>
  <link rel="shortcut icon" href="imagen/favicon-16x16.ico" type="image/x-icon" />

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

          Portafolio

...seguimos evolucionando...

            work

Lo que hacemos

User Experience Focused

User Experience Focused

User Experience Focused

User Experience Focused

User Experience Focused

User Experience Focused

            payment

Medios de pago

                    MERCANTIL
                    BANESCO

                  Cuenta corriente

                      J404590749

                      0105015791157053025

                  Cuenta corriebte

                    J404590749

                    01340066180661047240

            location_on

Nuestra ubicación

Internet

            Los teques, calle 19 de abril, Miranda Venezuela

        Si quieres contactarnos, por ahora tenemos estos medios

 Marcos Ramírez

                   more_vert

                  close

                            phone
                            +58 414-3453988

                            email
                            mramirez@eureksolutions.com

                    Edgar Leal

                  more_vert

                  close

                          phone
                          +58 414-3189549

                            email
                            eleal@eureksolutions.com

O envianos un mensaje

      <form class="col s12" action="">

            <input id="nombre" type="text" length="10" class="validate">
            Nombre

            <input id="apellido" type="text" length="11">
            Apellido

            <input id="tlf" type="number" length="11" class="validate">
            Telefono

            <input id="email" type="email" class="validate">
            Correo

            <textarea id="textarea1" class="materialize-textarea" length="120"></textarea>
            Mensaje

          <button class="btn waves-effect waves-light" type="submit" name="action" >
          send
          </button>

      </form>

O envianos un correo a:

email

        eureka@eureksolutions.com

email

info@eureksolutions.com

email

soporte@eureksolutions.com

NOSOTROS

Eureka es mas que una startup, es más que un equipo, somos una familia. Nos dedicamos a la programación web y móvil, contamos con una ambición grande, la de desarrollar productos que beneficien a la mayor cantidad de personas, que les ayude en sus tareas básicas.

                  ¿Deseas trabajar en Eureka?

                Envía un correo con tu resumen y portafolio a:

                  email
                  rrhh@eureksolutions.com

HORARIOS PARA

                  Desarrollo
                  Atención al cliente
                  Soporte

                Siempre
                Lunes a Viernes
8:00am-12:00m
2:00pm-6:00pm
                Martes y Jueves
8:00am - 12:00m

          <form class="col s12" action="">

                <input id="newsletter" type="email" class="validate">
                Newsletter

                <button class="btn waves-effect waves-light" type="submit" name="action" >
                  send
                </button>

          </form>

      Eureka Solutions, C.A - J404590749
      Inscritos ante el Registro Nacional de Contratistas