text:
"""Tests for stats.py."""

import datetime
import os

from google.appengine.api import datastore
from absl.testing import absltest as unittest

from google.appengine.ext.ndb import stats
from google.appengine.ext.ndb import test_utils

class StatsTests(test_utils.NDBTest):

  def setUp(self):
    """Setup test infrastructure."""
    super(StatsTests, self).setUp()
    self.PopulateStatEntities()

  the_module = stats

  def PopulateStatEntities(self):
    """Insert stat entities into Cloud Datastore."""

    self.CreateStatEntity(stats.GlobalStat.STORED_KIND_NAME,
                          has_entity_bytes=True,
                          has_builtin_index_stats=True,
                          has_composite_index_stats=True)

    self.CreateStatEntity(stats.NamespaceStat.STORED_KIND_NAME,
                          subject_namespace='name-space',
                          has_entity_bytes=True,
                          has_builtin_index_stats=True,
                          has_composite_index_stats=True)

    self.CreateStatEntity(stats.KindStat.STORED_KIND_NAME, 'foo',
                          has_entity_bytes=True,
                          has_builtin_index_stats=True,
                          has_composite_index_stats=True)
    self.CreateStatEntity(stats.KindStat.STORED_KIND_NAME, 'foo2',
                          has_entity_bytes=True,
                          has_builtin_index_stats=True,
                          has_composite_index_stats=True)

    self.CreateStatEntity(stats.KindRootEntityStat.STORED_KIND_NAME, 'foo3',
                          has_entity_bytes=True)
    self.CreateStatEntity(stats.KindRootEntityStat.STORED_KIND_NAME, 'foo4',
                          has_entity_bytes=True)

    self.CreateStatEntity(stats.KindNonRootEntityStat.STORED_KIND_NAME, 'foo5',
                          has_entity_bytes=True)
    self.CreateStatEntity(stats.KindNonRootEntityStat.STORED_KIND_NAME, 'foo6',
                          has_entity_bytes=True)

    self.CreateStatEntity(stats.PropertyTypeStat.STORED_KIND_NAME,
                          property_type='pt1',
                          has_entity_bytes=True,
                          has_builtin_index_stats=True)
    self.CreateStatEntity(stats.PropertyTypeStat.STORED_KIND_NAME,
                          property_type='pt2',
                          has_entity_bytes=True,
                          has_builtin_index_stats=True)

    self.CreateStatEntity(stats.KindPropertyTypeStat.STORED_KIND_NAME,
                          kind_name='foo1',
                          property_type='pt1',
                          has_entity_bytes=True,
                          has_builtin_index_stats=True)
    self.CreateStatEntity(stats.KindPropertyTypeStat.STORED_KIND_NAME,
                          kind_name='foo1',
                          property_type='pt2',
                          has_entity_bytes=True,
                          has_builtin_index_stats=True)
    self.CreateStatEntity(stats.KindPropertyTypeStat.STORED_KIND_NAME,
                          kind_name='foo2',
                          property_type='pt2',
                          has_entity_bytes=True,
                          has_builtin_index_stats=True)

    self.CreateStatEntity(stats.KindPropertyNameStat.STORED_KIND_NAME,
                          kind_name='foo11',
                          property_name='pn1',
                          has_entity_bytes=True,
                          has_builtin_index_stats=True)
    self.CreateStatEntity(stats.KindPropertyNameStat.STORED_KIND_NAME,
                          kind_name='foo11',
                          property_name='pn2',
                          has_entity_bytes=True,
                          has_builtin_index_stats=True)
    self.CreateStatEntity(stats.KindPropertyNameStat.STORED_KIND_NAME,
                          kind_name='foo21',
                          property_name='pn2',
                          has_entity_bytes=True,
                          has_builtin_index_stats=True)

    self.CreateStatEntity(
        stats.KindPropertyNamePropertyTypeStat.STORED_KIND_NAME,
        kind_name='foo12',
        property_type='pt1',
        property_name='pn1',
        has_entity_bytes=True,
        has_builtin_index_stats=True)

    self.CreateStatEntity(
        stats.KindPropertyNamePropertyTypeStat.STORED_KIND_NAME,
        kind_name='foo12',
        property_type='pt2',
        property_name='pn2',
        has_entity_bytes=True,
        has_builtin_index_stats=True)

    self.CreateStatEntity(
        stats.KindPropertyNamePropertyTypeStat.STORED_KIND_NAME,
        kind_name='foo22',
        property_type='pt2',
        property_name='pn2',
        has_entity_bytes=True,
        has_builtin_index_stats=True)

    self.CreateStatEntity(
        stats.KindCompositeIndexStat.STORED_KIND_NAME,
        kind_name='foo12',
        composite_index_id=1)
    self.CreateStatEntity(
        stats.KindCompositeIndexStat.STORED_KIND_NAME,
        kind_name='foo12',
        composite_index_id=2)
    self.CreateStatEntity(
        stats.KindCompositeIndexStat.STORED_KIND_NAME,
        kind_name='foo22',
        composite_index_id=3)

  def CreateStatEntity(self,
                       kind,
                       kind_name=None,
                       property_type=None,
                       property_name=None,
                       subject_namespace=None,
                       composite_index_id=None,
                       has_entity_bytes=None,
                       has_builtin_index_stats=None,
                       has_composite_index_stats=None):
    """Create a single Statistic datastore entity.

    Args:
      kind: The name of the kind to store.
      kind_name: The value of the 'kind_name' property to set on the entity.
      property_type: The value of the 'property_type' property to set on the
        entity.
      property_name: The value of the 'property_name' property to set on the
        entity.
      subject_namespace: The namespace for NamespaceStat entities.
      composite_index_id: The index id of composite index.
      has_entity_bytes: The stat has the entity_bytes property.
      has_builtin_index_stats: The stat entity has builtin_index_bytes and
        builtin_index_count.
      has_composite_index_stats: The stat entity has composite_index_bytes and
        composite_index_count.
    """
    stat = datastore.Entity(kind)
    stat['bytes'] = 4
    stat['count'] = 2
    stat['timestamp'] = datetime.datetime.utcfromtimestamp(40)
    if has_entity_bytes:
      stat['entity_bytes'] = 2
    if has_builtin_index_stats:
      stat['builtin_index_count'] = 3
      stat['builtin_index_bytes'] = 1
    if has_composite_index_stats:
      stat['composite_index_count'] = 2
      stat['composite_index_bytes'] = 1
    if kind_name is not None:
      stat['kind_name'] = kind_name
    if property_type is not None:
      stat['property_type'] = property_type
    if property_name is not None:
      stat['property_name'] = property_name
    if subject_namespace is not None:
      stat['subject_namespace'] = subject_namespace
    if composite_index_id is not None:
      stat['index_id'] = composite_index_id
    datastore.Put(stat)

  def testGlobalStat(self):
    """Test fetching the global stat singleton."""
    res = stats.GlobalStat.query().fetch()
    self.assertEqual(1, len(res))
    self.assertEqual(4, res[0].bytes)
    self.assertEqual(2, res[0].entity_bytes)
    self.assertEqual(3, res[0].builtin_index_count)
    self.assertEqual(1, res[0].builtin_index_bytes)
    self.assertEqual(2, res[0].composite_index_count)
    self.assertEqual(1, res[0].composite_index_bytes)

  def testNamespaceStat(self):
    """Test fetching the global stat singleton."""
    res = stats.NamespaceStat.query().fetch()
    self.assertEqual(1, len(res))
    self.assertEqual(4, res[0].bytes)
    self.assertEqual('name-space', res[0].subject_namespace)
    self.assertEqual(2, res[0].entity_bytes)
    self.assertEqual(3, res[0].builtin_index_count)
    self.assertEqual(1, res[0].builtin_index_bytes)
    self.assertEqual(2, res[0].composite_index_count)
    self.assertEqual(1, res[0].composite_index_bytes)

  def testKindStat(self):
    """Test fetching the Kind stats."""
    res = stats.KindStat.query().fetch()
    self.assertEqual(2, len(res))
    self.assertEqual('foo', res[0].kind_name)
    self.assertEqual('foo2', res[1].kind_name)
    self.assertEqual(2, res[0].entity_bytes)
    self.assertEqual(3, res[0].builtin_index_count)
    self.assertEqual(1, res[0].builtin_index_bytes)
    self.assertEqual(2, res[0].composite_index_count)
    self.assertEqual(1, res[0].composite_index_bytes)

  def testKindRootEntityStat(self):
    """Test fetching the Kind root entity stats."""
    res = stats.KindRootEntityStat.query().fetch()
    self.assertEqual(2, len(res))
    self.assertEqual('foo3', res[0].kind_name)
    self.assertEqual('foo4', res[1].kind_name)
    self.assertEqual(2, res[0].entity_bytes)

  def testKindNonRootEntityStat(self):
    """Test fetching the Kind non-root entity stats."""
    res = stats.KindNonRootEntityStat.query().fetch()
    self.assertEqual(2, len(res))
    self.assertEqual('foo5', res[0].kind_name)
    self.assertEqual('foo6', res[1].kind_name)
    self.assertEqual(2, res[0].entity_bytes)

  def testPropertyTypeStat(self):
    """Test fetching the property type stats."""
    res = stats.PropertyTypeStat.query().fetch()
    self.assertEqual(2, len(res))
    self.assertEqual('pt1', res[0].property_type)
    self.assertEqual('pt2', res[1].property_type)
    self.assertEqual(2, res[0].entity_bytes)
    self.assertEqual(3, res[0].builtin_index_count)
    self.assertEqual(1, res[0].builtin_index_bytes)

  def testKindPropertyTypeStat(self):
    """Test fetching the (kind, property type) stats."""
    res = stats.KindPropertyTypeStat.query().fetch()
    self.assertEqual(3, len(res))
    self.assertEqual('foo1', res[0].kind_name)
    self.assertEqual('pt1', res[0].property_type)
    self.assertEqual('foo1', res[1].kind_name)
    self.assertEqual('pt2', res[1].property_type)
    self.assertEqual('foo2', res[2].kind_name)
    self.assertEqual('pt2', res[2].property_type)
    self.assertEqual(2, res[0].entity_bytes)
    self.assertEqual(3, res[0].builtin_index_count)
    self.assertEqual(1, res[0].builtin_index_bytes)

    query = stats.KindPropertyTypeStat.query(
        stats.KindPropertyTypeStat.kind_name == 'foo2')
    res = query.fetch()
    self.assertEqual(1, len(res))
    self.assertEqual('foo2', res[0].kind_name)

  def testKindPropertyNameStat(self):
    """Test fetching the (kind, property name) type stats."""
    res = stats.KindPropertyNameStat.query().fetch()
    self.assertEqual(3, len(res))
    self.assertEqual('foo11', res[0].kind_name)
    self.assertEqual('pn1', res[0].property_name)
    self.assertEqual('foo11', res[1].kind_name)
    self.assertEqual('pn2', res[1].property_name)
    self.assertEqual('foo21', res[2].kind_name)
    self.assertEqual('pn2', res[2].property_name)
    self.assertEqual(2, res[0].entity_bytes)
    self.assertEqual(3, res[0].builtin_index_count)
    self.assertEqual(1, res[0].builtin_index_bytes)

    query = stats.KindPropertyNameStat.query(
        stats.KindPropertyNameStat.kind_name == 'foo21')
    res = query.fetch()
    self.assertEqual(1, len(res))
    self.assertEqual('foo21', res[0].kind_name)

  def testKindPropertyNamePropertyTypeStat(self):
    """Test fetching the (kind, property name, property type) stats."""
    res = stats.KindPropertyNamePropertyTypeStat.query().fetch()
    self.assertEqual(3, len(res))
    self.assertEqual('foo12', res[0].kind_name)
    self.assertEqual('pn1', res[0].property_name)
    self.assertEqual('pt1', res[0].property_type)
    self.assertEqual('foo12', res[1].kind_name)
    self.assertEqual('pn2', res[1].property_name)
    self.assertEqual('pt2', res[1].property_type)
    self.assertEqual('foo22', res[2].kind_name)
    self.assertEqual('pn2', res[2].property_name)
    self.assertEqual('pt2', res[2].property_type)
    self.assertEqual(2, res[0].entity_bytes)
    self.assertEqual(3, res[0].builtin_index_count)
    self.assertEqual(1, res[0].builtin_index_bytes)

    query = stats.KindPropertyNamePropertyTypeStat.query(
        stats.KindPropertyNamePropertyTypeStat.kind_name == 'foo22')
    res = query.fetch()
    self.assertEqual(1, len(res))
    self.assertEqual('foo22', res[0].kind_name)

  def testKindCompositeIndex(self):
    """Test fetching the (kind, composite index id) stats."""
    res = stats.KindCompositeIndexStat.query().fetch()
    self.assertEqual(3, len(res))
    self.assertEqual('foo12', res[0].kind_name)
    self.assertEqual(1, res[0].index_id)
    self.assertEqual('foo12', res[1].kind_name)
    self.assertEqual(2, res[1].index_id)
    self.assertEqual('foo22', res[2].kind_name)
    self.assertEqual(3, res[2].index_id)
    self.assertEqual(4, res[0].bytes)
    self.assertEqual(2, res[0].count)

if __name__ == '__main__':
  unittest.main()


text:
CREATE TABLE state_flow
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
from_id BIGINT,
to_id BIGINT,
FOREIGN KEY (from_id) REFERENCES states(id),
FOREIGN KEY (to_id) REFERENCES states(id)
)

redpajama_set_name: RedPajamaGithub


text: export default function tryCatch(fn: Function): Function;


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

var _functionalCurry = require('../functional/curry');

var _shallowClone = require('./shallowClone');

var assoc = (0, _functionalCurry.curry)(function (key, value, obj) {
  var newObj = (0, _shallowClone.shallowClone)(obj);
  newObj[key] = value;
  return newObj;
});
exports.assoc = assoc;


text:
namespace WPFAddressBook.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class AddedAddressTable2 : DbMigration
    {
        public override void Up()
        {
        }

        public override void Down()
        {
        }
    }
}


text:
<resources>
    <string name="app_name" translatable="false">PGPClipper</string>
    <string name="enabledService">Enable Service</string>
    <string name="enabledServiceSummary">Check this box to allow PGPClipper stay alive in background.\nNote that this application *will* access clipboard data.</string>
    <string name="pgpServiceProviderAppTitleString">OpenPGP Service Provider status</string>
    <string name="appVersionString" translatable="false">0.22</string>
    <string name="appVersionTitleString">Version</string>
    <string name="licenseTitleString">License</string>
    <string name="licenseContentString" translatable="false">Apache License 2.0</string>
    <string name="thirdPartyLicenseTitleString">Third Party License</string>
    <string name="thirdPartyLibraryContentString" translatable="false">OpenPGP API Library - Apache License 2.0\nGoldfinger - Apache License 2.0</string>
    <string name="issueTrackingTitleString">Issue tracking and source code</string>
    <string name="issueTrackingContentString" translatable="false">GitHub</string>
    <string name="signatureToggleText">Signature Toggle</string>
    <string name="replyText">Reply</string>
    <string name="processingResultText">Processing Result</string>
    <string name="signatureStatusText">Signature Status: %1$s (%2$s)</string>
    <string name="decryptionStatusText">Decryption Status: %1$s</string>
    <string name="fastReplyText">Press result field for fast reply</string>
    <string name="tryAgainText">To try again, Press result field.</string>
    <string name="NotificationTickerText">Possible PGP Data Detected</string>
    <string name="NotificationTitleText">Possible PGP Data Detected</string>
    <string name="NotificationContentText">Attempt to process it?</string>
    <string name="darkText">Dark</string>
    <string name="lightText">Light</string>
    <string name="themeStyleText">Theme Setting</string>
    <string name="errorCannotProcess">cannot process</string>
    <string name="errorCannotContinue">Error, cannot continue. Send bug report to author.</string>
    <string name="hintRecipient">To:</string>
    <string name="enableNFCAuth">Enable NFC Authentication</string>
    <string name="enableNFCAuthSummary">Check this box to allow PGPClipper perform signature with NFC token.\nNote that this application *will* store your PGP password if you enable this function.</string>
    <string name="credentialWrongText">Credential was wrong, try again</string>
    <string name="alternativeAuthenticationMethodText">%1$s to authenticate\nPress result field for password/stored credential fallback</string>
    <string name="nfcAuthenticationSetupWizardTitleText">NFC Authentication Setup Wizard</string>
    <string name="nfcWizard01Text">This Wizard will help you setup NFC token authentication.\n\nPress next to continue.\nPress close to close this wizard at anytime.</string>
    <string name="nfcWizard02Text">Generating salt value for encryption.\nPlease wait.</string>
    <string name="nfcWizard03Text">PGPClipper has successfully generated salt.</string>
    <string name="nfcWizard04fingerprintWizard02Text">Now you will provide your default key\'s password.\nThis information will be encrypted.</string>
    <string name="nfcWizard05PasswordInputText">Enter PGP password</string>
    <string name="nfcWizard05PasswordReInputText">Enter PGP password again</string>
    <string name="nfcWizard06Text">Tap NFC token to your device.</string>
    <string name="nfcWizard07Text">Tap NFC token to your device again.</string>
    <string name="nfcWizard08Text">NFC token successfully detected.</string>
    <string name="nfcWizard11Text">This NFC token cannot be used.</string>
    <string name="nfcWizard12Text">Generating hash and encrypting…\nThis might take a long time (few minutes)\ndepending on your device\'s power.\n\nScreen will stay on.</string>
    <string name="closeText">Close</string>
    <string name="nextText">Next</string>
    <string name="alternativeReplyNotificationText">%1$s to sign and encrypt message\nPress reply for password fallback</string>
    <string name="enableFingerprintAuth">Enable Fingerprint Authentication</string>
    <string name="enableFingerprintAuthSummary">Check this box to allow PGPClipper perform signature with fingerprint.\nNote that this application *will* store your PGP password if you enable this function.</string>
    <string name="fingerprintSetupWizardTitleText" >Fingerprint Setup Wizard</string>
    <string name="fingerprintWizard01Text" >This Wizard will help you setup fingerprint authentication.\n\nPress next to continue.\nPress close to close this wizard at anytime.</string>
    <string name="fingerprintWizard04Text">Locate your device\'s fingerprint sensor, and scan.</string>
    <string name="fingerprintCorrectString">Fingerprint is correct, complete!</string>
    <string name="fingerprintErrorString">Could not read fingerprint from sensor, try again.</string>
    <string name="fingerprintFatalErrorString">Fatal error! Try again later.</string>
    <string name="nfcNotAvailableString">NFC hardware not available</string>
    <string name="nfcDisabledString">Enable NFC in settings</string>
    <string name="alternativeAuthenticationMethodNFCText">Tap NFC token</string>
    <string name="alternativeAuthenticationMethodFingerprintText">Touch fingerprint scanner</string>
    <string name="channel_name">PGPClipper clipboard notification channel</string>
    <string name="channel_description">Notifies user about possible PGP data block detection</string>
    <string name="battery_optimazation_information_toast">From Android M, PGPClipper requires user to disable battery optimization in order to read clipboard data in the background. Please disable battery optimization.</string>
    <string name="aes_key_init_notice_toast">AES implementation before version 0.22 was not suitable (AES-ECB), removing encrypted PGP key password cache from device.</string>
</resources>


text: export { ArrowUpLeft20 as default } from "../../";


text:
package de.tiiunder.flatmate.rest.expense;

import android.content.Context;
import android.util.Log;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;

import de.tiiunder.flatmate.entities.expense.Expense;
import de.tiiunder.flatmate.events.expense.DeleteExpenseEvent;
import de.tiiunder.flatmate.rest.ServerConstants;
import de.tiiunder.flatmate.rest.SuperAsyncTask;
import de.tiiunder.flatmate.service.EventService;

public class DeleteExpenseTask extends SuperAsyncTask {
    private Expense expense;

    public DeleteExpenseTask(Context context, Expense expense) {
        super(context);

        this.expense = expense;
    }

    @Override
    protected Object doInBackground(Object[] params) {
        try {
            super.doInBackground(params);

            String restUrl = ServerConstants.SERVER_API_URL + "expense/" + expense.getId() + "/delete";

            ResponseEntity<Object> responseEntity = restTemplate.exchange(restUrl, HttpMethod.DELETE, new HttpEntity<Object>(requestHeaders), Object.class);

            HttpStatus status = responseEntity.getStatusCode(); // send request

            return status.value();

        } catch (HttpClientErrorException ex) {
            ex.printStackTrace();

            return ex.getStatusCode().value();
        }
    }

    @Override
    protected void onPostExecute(Object result) {
        super.onPostExecute(result);

        if((int) result == org.apache.http.HttpStatus.SC_OK) {
            EventService eventService = EventService.getInstance();

            Log.d("Event", "Delete Expense Event pushed");

            eventService.post(new DeleteExpenseEvent());
        }
    }
}


text:
package main

import (
  "io"
  "os"
)

func main() {
  // open input file
  input_file, error := os.Open("input.txt")
  if error != nil { panic(error) }

  // close file on exit and check for its returned error
  defer func() {
    if error := input_file.Close(); error != nil {
      panic(error)
    }
  }()

  // open output file
  output_file, error := os.Create("output.txt")
  if error != nil { panic(error) }
  // close output_file on exit and check for its returned error
  defer func() {
    if error := output_file.Close(); error != nil {
      panic(error)
    }
  }()

  // make a buffer to keep chunks that are read
  buffer := make([]byte, 1024)
  for {
    // read a chunk
    n, error := input_file.Read(buffer)
    if error != nil && error != io.EOF { panic(error) }
    if n == 0 { break }

    // write a chunk
    if _, error := output_file.Write(buffer[:n]); error != nil {
      panic(error)
    }
  }
}


text:
"""
To run these tests against a live database:

1. Modify the file `keystone/tests/unit/config_files/backend_sql.conf` to use
   the connection for your live database.
2. Set up a blank, live database.
3. Run the tests using::

    tox -e py27 -- keystone.tests.unit.test_sql_migrate_extensions

WARNING::

   Your database will be wiped.

   Do not do this against a Database with valuable data as
   all data will be lost.
"""

from oslo_db.sqlalchemy import utils

from keystone.contrib import endpoint_filter
from keystone.contrib import endpoint_policy
from keystone.contrib import example
from keystone.contrib import federation
from keystone.contrib import oauth1
from keystone.contrib import revoke
from keystone.tests.unit import test_sql_upgrade

class SqlUpgradeExampleExtension(test_sql_upgrade.SqlMigrateBase):
    def repo_package(self):
        return example

    def test_upgrade(self):
        self.assertTableDoesNotExist('example')
        self.upgrade(1, repository=self.repo_path)
        self.assertTableColumns('example', ['id', 'type', 'extra'])

    def test_downgrade(self):
        self.upgrade(1, repository=self.repo_path)
        self.assertTableColumns('example', ['id', 'type', 'extra'])
        self.downgrade(0, repository=self.repo_path)
        self.assertTableDoesNotExist('example')

class SqlUpgradeOAuth1Extension(test_sql_upgrade.SqlMigrateBase):
    def repo_package(self):
        return oauth1

    def upgrade(self, version):
        super(SqlUpgradeOAuth1Extension, self).upgrade(
            version, repository=self.repo_path)

    def downgrade(self, version):
        super(SqlUpgradeOAuth1Extension, self).downgrade(
            version, repository=self.repo_path)

    def _assert_v1_3_tables(self):
        self.assertTableColumns('consumer',
                                ['id',
                                 'description',
                                 'secret',
                                 'extra'])
        self.assertTableColumns('request_token',
                                ['id',
                                 'request_secret',
                                 'verifier',
                                 'authorizing_user_id',
                                 'requested_project_id',
                                 'requested_roles',
                                 'consumer_id',
                                 'expires_at'])
        self.assertTableColumns('access_token',
                                ['id',
                                 'access_secret',
                                 'authorizing_user_id',
                                 'project_id',
                                 'requested_roles',
                                 'consumer_id',
                                 'expires_at'])

    def _assert_v4_later_tables(self):
        self.assertTableColumns('consumer',
                                ['id',
                                 'description',
                                 'secret',
                                 'extra'])
        self.assertTableColumns('request_token',
                                ['id',
                                 'request_secret',
                                 'verifier',
                                 'authorizing_user_id',
                                 'requested_project_id',
                                 'role_ids',
                                 'consumer_id',
                                 'expires_at'])
        self.assertTableColumns('access_token',
                                ['id',
                                 'access_secret',
                                 'authorizing_user_id',
                                 'project_id',
                                 'role_ids',
                                 'consumer_id',
                                 'expires_at'])

    def test_upgrade(self):
        self.assertTableDoesNotExist('consumer')
        self.assertTableDoesNotExist('request_token')
        self.assertTableDoesNotExist('access_token')
        self.upgrade(1)
        self._assert_v1_3_tables()

        # NOTE(blk-u): Migrations 2-3 don't modify the tables in a way that we
        # can easily test for.

        self.upgrade(4)
        self._assert_v4_later_tables()

        self.upgrade(5)
        self._assert_v4_later_tables()

    def test_downgrade(self):
        self.upgrade(5)
        self._assert_v4_later_tables()
        self.downgrade(3)
        self._assert_v1_3_tables()
        self.downgrade(1)
        self._assert_v1_3_tables()
        self.downgrade(0)
        self.assertTableDoesNotExist('consumer')
        self.assertTableDoesNotExist('request_token')
        self.assertTableDoesNotExist('access_token')

class EndpointFilterExtension(test_sql_upgrade.SqlMigrateBase):
    def repo_package(self):
        return endpoint_filter

    def upgrade(self, version):
        super(EndpointFilterExtension, self).upgrade(
            version, repository=self.repo_path)

    def downgrade(self, version):
        super(EndpointFilterExtension, self).downgrade(
            version, repository=self.repo_path)

    def _assert_v1_tables(self):
        self.assertTableColumns('project_endpoint',
                                ['endpoint_id', 'project_id'])
        self.assertTableDoesNotExist('endpoint_group')
        self.assertTableDoesNotExist('project_endpoint_group')

    def _assert_v2_tables(self):
        self.assertTableColumns('project_endpoint',
                                ['endpoint_id', 'project_id'])
        self.assertTableColumns('endpoint_group',
                                ['id', 'name', 'description', 'filters'])
        self.assertTableColumns('project_endpoint_group',
                                ['endpoint_group_id', 'project_id'])

    def test_upgrade(self):
        self.assertTableDoesNotExist('project_endpoint')
        self.upgrade(1)
        self._assert_v1_tables()
        self.assertTableColumns('project_endpoint',
                                ['endpoint_id', 'project_id'])
        self.upgrade(2)
        self._assert_v2_tables()

    def test_downgrade(self):
        self.upgrade(2)
        self._assert_v2_tables()
        self.downgrade(1)
        self._assert_v1_tables()
        self.downgrade(0)
        self.assertTableDoesNotExist('project_endpoint')

class EndpointPolicyExtension(test_sql_upgrade.SqlMigrateBase):
    def repo_package(self):
        return endpoint_policy

    def test_upgrade(self):
        self.assertTableDoesNotExist('policy_association')
        self.upgrade(1, repository=self.repo_path)
        self.assertTableColumns('policy_association',
                                ['id', 'policy_id', 'endpoint_id',
                                 'service_id', 'region_id'])

    def test_downgrade(self):
        self.upgrade(1, repository=self.repo_path)
        self.assertTableColumns('policy_association',
                                ['id', 'policy_id', 'endpoint_id',
                                 'service_id', 'region_id'])
        self.downgrade(0, repository=self.repo_path)
        self.assertTableDoesNotExist('policy_association')

class FederationExtension(test_sql_upgrade.SqlMigrateBase):
    """Test class for ensuring the Federation SQL."""

    def setUp(self):
        super(FederationExtension, self).setUp()
        self.identity_provider = 'identity_provider'
        self.federation_protocol = 'federation_protocol'
        self.mapping = 'mapping'

    def repo_package(self):
        return federation

    def test_upgrade(self):
        self.assertTableDoesNotExist(self.identity_provider)
        self.assertTableDoesNotExist(self.federation_protocol)
        self.assertTableDoesNotExist(self.mapping)

        self.upgrade(1, repository=self.repo_path)
        self.assertTableColumns(self.identity_provider,
                                ['id',
                                 'enabled',
                                 'description'])

        self.assertTableColumns(self.federation_protocol,
                                ['id',
                                 'idp_id',
                                 'mapping_id'])

        self.upgrade(2, repository=self.repo_path)
        self.assertTableColumns(self.mapping,
                                ['id', 'rules'])

        federation_protocol = utils.get_table(
            self.engine,
            'federation_protocol')
        with self.engine.begin() as conn:
            conn.execute(federation_protocol.insert(), id=0, idp_id=1)
            self.upgrade(3, repository=self.repo_path)
            federation_protocol = utils.get_table(
                self.engine,
                'federation_protocol')
            self.assertFalse(federation_protocol.c.mapping_id.nullable)

    def test_downgrade(self):
        self.upgrade(3, repository=self.repo_path)
        self.assertTableColumns(self.identity_provider,
                                ['id', 'enabled', 'description'])
        self.assertTableColumns(self.federation_protocol,
                                ['id', 'idp_id', 'mapping_id'])
        self.assertTableColumns(self.mapping,
                                ['id', 'rules'])

        self.downgrade(2, repository=self.repo_path)
        federation_protocol = utils.get_table(
            self.engine,
            'federation_protocol')
        self.assertTrue(federation_protocol.c.mapping_id.nullable)

        self.downgrade(0, repository=self.repo_path)
        self.assertTableDoesNotExist(self.identity_provider)
        self.assertTableDoesNotExist(self.federation_protocol)
        self.assertTableDoesNotExist(self.mapping)

_REVOKE_COLUMN_NAMES = ['id', 'domain_id', 'project_id', 'user_id', 'role_id',
                        'trust_id', 'consumer_id', 'access_token_id',
                        'issued_before', 'expires_at', 'revoked_at']

class RevokeExtension(test_sql_upgrade.SqlMigrateBase):

    def repo_package(self):
        return revoke

    def test_upgrade(self):
        self.assertTableDoesNotExist('revocation_event')
        self.upgrade(1, repository=self.repo_path)
        self.assertTableColumns('revocation_event',
                                _REVOKE_COLUMN_NAMES)

    def test_downgrade(self):
        self.upgrade(1, repository=self.repo_path)
        self.assertTableColumns('revocation_event',
                                _REVOKE_COLUMN_NAMES)
        self.downgrade(0, repository=self.repo_path)
        self.assertTableDoesNotExist('revocation_event')


text:
<?php

namespace Drupal\Tests\Core\Entity;

use Drupal\Tests\UnitTestCase;

/**
 * @coversDefaultClass \Drupal\Core\Entity\EntityStorageBase
 * @group Entity
 */
class EntityStorageBaseTest extends UnitTestCase {

  /**
   * Generate a mocked entity object.
   *
   * @param string $id
   *   ID value for this entity.
   *
   * @return \Drupal\Core\Entity\EntityInterface|\PHPUnit\Framework\MockObject\MockObject
   *   The mocked entity.
   */
  public function generateEntityInterface($id) {
    $mock_entity = $this->getMockBuilder('\Drupal\Core\Entity\EntityInterface')
      ->onlyMethods(['id'])
      ->getMockForAbstractClass();
    $mock_entity->expects($this->any())
      ->method('id')
      ->willReturn((string) $id);
    return $mock_entity;
  }

  /**
   * Data provider for testLoad().
   *
   * @return array
   *   - Expected output of load().
   *   - A fixture of entities to query against. Suitable return value for
   *     loadMultiple().
   *   - The ID we'll query.
   */
  public function providerLoad() {
    $data = [];

    // Data set for a matching value.
    $entity = $this->generateEntityInterface('1');
    $data['matching-value'] = [$entity, ['1' => $entity], '1'];

    // Data set for no matching value.
    $data['no-matching-value'] = [NULL, [], '0'];

    return $data;
  }

  /**
   * @covers ::load
   *
   * @dataProvider providerLoad
   */
  public function testLoad($expected, $entity_fixture, $query) {
    $mock_base = $this->getMockBuilder('\Drupal\Core\Entity\EntityStorageBase')
      ->disableOriginalConstructor()
      ->onlyMethods(['loadMultiple'])
      ->getMockForAbstractClass();

    // load() always calls loadMultiple().
    $mock_base->expects($this->once())
      ->method('loadMultiple')
      ->with([$query])
      ->willReturn($entity_fixture);

    $this->assertEquals($expected, $mock_base->load($query));
  }

  /**
   * Data provider for testLoadMultiple.
   *
   * @return array
   *   - The expected result.
   *   - Results for doLoadMultiple(), called internally by loadMultiple().
   *   - The query, an array of IDs.
   */
  public function providerLoadMultiple() {
    // Create a fixture of entity objects.
    $fixture = [];
    foreach (range(1, 10) as $index) {
      $fixture[(string) $index] = $this->generateEntityInterface($index);
    }

    $data = [];

    // Data set for NULL ID parameter.
    $data['null-id-parameter'] = [$fixture, $fixture, NULL];

    // Data set for no results.
    $data['no-results'] = [[], [], ['11']];

    // Data set for 0 results for multiple IDs.
    $data['no-results-multiple-ids'] = [[], [], ['11', '12', '13']];

    // Data set for 1 result for 1 ID.
    $data['1-result-for-1-id'] = [
      ['1' => $fixture['1']],
      ['1' => $fixture['1']],
      ['1'],
    ];

    // Data set for results for all IDs.
    $ids = ['1', '2', '3'];
    foreach ($ids as $id) {
      $expectation[$id] = $fixture[$id];
      $load_multiple[$id] = $fixture[$id];
    }
    $data['results-for-all-ids'] = [$expectation, $load_multiple, $ids];

    // Data set for partial results for multiple IDs.
    $ids = ['1', '2', '3'];
    foreach ($ids as $id) {
      $expectation[$id] = $fixture[$id];
      $load_multiple[$id] = $fixture[$id];
    }
    $ids = array_merge($ids, ['11', '12']);
    $data['partial-results-for-multiple-ids'] = [
      $expectation,
      $load_multiple,
      $ids,
    ];

    return $data;
  }

  /**
   * Test loadMultiple().
   *
   * Does not cover statically-cached results.
   *
   * @covers ::loadMultiple
   *
   * @dataProvider providerLoadMultiple
   */
  public function testLoadMultiple($expected, $load_multiple, $query) {
    // Make our EntityStorageBase mock.
    $mock_base = $this->getMockBuilder('\Drupal\Core\Entity\EntityStorageBase')
      ->disableOriginalConstructor()
      ->onlyMethods(['doLoadMultiple', 'postLoad'])
      ->getMockForAbstractClass();

    // For all non-cached queries, we call doLoadMultiple().
    $mock_base->expects($this->once())
      ->method('doLoadMultiple')
      ->with($query)
      ->willReturn($load_multiple);

    // Make our EntityTypeInterface mock so that we can turn off static caching.
    $mock_entity_type = $this->getMockBuilder('\Drupal\Core\Entity\EntityTypeInterface')
      ->onlyMethods(['isStaticallyCacheable'])
      ->getMockForAbstractClass();
    // Disallow caching.
    $mock_entity_type->expects($this->any())
      ->method('isStaticallyCacheable')
      ->willReturn(FALSE);
    // Add the EntityTypeInterface to the storage object.
    $ref_entity_type = new \ReflectionProperty($mock_base, 'entityType');
    $ref_entity_type->setAccessible(TRUE);
    $ref_entity_type->setValue($mock_base, $mock_entity_type);

    // Set up expectations for postLoad(), which we only call if there are
    // results from loadMultiple().
    $mock_base->expects($this->exactly(empty($load_multiple) ? 0 : 1))
      ->method('postLoad');

    $this->assertEquals($expected, $mock_base->loadMultiple($query));
  }

}


text:
require 'json'

module Octopress
  module Ink
    module Utils
      extend self

      def pretty_print_yaml(yaml)
        # Use json pretty_print, but make it look like yaml
        #
        JSON.pretty_generate(yaml)
          .sub(/\A{\n/,'')          # remove leading {
          .sub(/}\z/,'')            # remove trailing }
          .gsub(/^/,' ')            # indent
          .gsub(/"(.+?)":/,'\1:')   # remove quotes around keys
          .gsub(/,$/,'')            # remove commas from end of lines
          .gsub(/{\n/,"\n")         # remove keys with empty hashes
          .gsub(/^\s+}\n/,'')       # remove keys with empty hashes
          .gsub(/\[\s+\]/,'[]')       # remove whitespace in empty arrays
      end
    end
  end
end


text:
import MyBook from './routes/MyBook'
import AllBook from './routes/AllBook'
import WorkTable from './routes/WorkTable'
import ShuireBox from './routes/ShuireBox'
import Tubefurnace from './routes/Tubefurnace'
import MyData from './routes/MyData'
import Rules from './routes/Rules'

export default (store) => ({
  path:'equipment',
  childRoutes : [
    MyBook(store),
    AllBook(store),
    WorkTable(store),
    ShuireBox(store),
    Tubefurnace(store),
    MyData(store),
    Rules(store)
  ],

   /*  Async getComponent is only invoked when route matches   */
  getComponent (nextState, cb) {
    /*  Webpack - use 'require.ensure' to create a split point
        and embed an async module loader (jsonp) when bundling   */
    require.ensure([], (require) => {
      /*  Webpack - use require callback to define
          dependencies for bundling   */
      const HeaderAndSideBar = require('./containers').default

      /*  Add the reducer to the store on key 'counter'  */

      /*  Return getComponent   */
      cb(null, HeaderAndSideBar)

    /* Webpack named bundle   */
    }, 'counter')
  }

})


text:
#ifndef __PARSEDRAW_H
#define __PARSEDRAW_H
#include <atomic>
#include <thread>
#include <map>
#include <mutex>
#include <deque>
#include <mgl2/window.h>
#include <mgl2/glut.h>
#include "ParseDrawIO.h"
#include "ParseDrawIOStdio.h"
/* -------------------------------------------------------------------------- */
class ParseDraw: public mglDraw
{
private:
  // What we're bridging together -- IO, and the window via the parser
  ParseDrawIO& io;
  mglParse parser;
  mglWnd* window;

  // IO service
  std::thread* ioThread;
  std::atomic<bool> stopIoThread;
  void ioService(void);
  void ioServiceShutdown(void);
  std::string nextCommand;

  // Parser variable store; Flat vector for variable binding which happens
  // with every push, pop, or modification
  std::map<std::string, std::vector<double> > varMap;

  // Command queue for drawing
  std::mutex commandQueueLock;
  std::deque<std::string> commandQueue;

  // Base class overrides
  int Draw(mglGraph *graph);
  void Calc();

  std::string start;

  uint32_t frameNumber;
public:
  // Public interface
  void Run(mglWnd*);
  ParseDraw(ParseDrawIO&, const std::string&);
  ~ParseDraw();
};
#endif


text:
package org.paukov.exercise.graph;

import static org.fest.assertions.Assertions.assertThat;

import org.junit.jupiter.api.Test;

public final class LC130_SurroundedRegionsTest {

  @Test
  public void test_solve() {
    LC130_SurroundedRegions solution = new LC130_SurroundedRegions();
    char[][] board = new char[][]{
        {'X','X','X','X'},{'X','O','O','X'},{'X','X','O','X'},{'X','O','X','X'}
    };

    solution.solve(board);

    assertThat(board[0]).isEqualTo(new char[]{'X','X','X','X'});
    assertThat(board[1]).isEqualTo(new char[]{'X','X','X','X'});
    assertThat(board[2]).isEqualTo(new char[]{'X','X','X','X'});
    assertThat(board[3]).isEqualTo(new char[]{'X','O','X','X'});
  }
}


text:
To run, clone this repo, and then:

```
npm install
npm start
```

If you have `budo` and `installify` installed globally, you can skip the `npm install`.

## Hack!

Hack on `index.js`.  With the server running, the `installify` transform will
automatically `npm install` any modules you require, saving them as dependencies
in `package.json`.


text:
require 'test/unit'
require 'kayako_client'

class TestUser < Test::Unit::TestCase

    def test_user_customs
        assert_raise ArgumentError do
            KayakoClient::User.all(0)
        end

        assert_raise ArgumentError do
            KayakoClient::User.all(1, 0)
        end

        assert_raise ArgumentError do
            KayakoClient::User.all(nil, 1)
        end

        assert_raise ArgumentError do
            KayakoClient::User.all(0, 1)
        end
    end

    def test_user_validate
        test = KayakoClient::User.new(
            :user_group_id => 1,
            :user_role     => :tester,
            :salutation    => 'Sir',
            :full_name     => 'Test',
            :emails        => 'test@test.com',
            :password      => 'test'
        )

        assert !test.save
        assert test.errors.has_key?(:user_role)
        assert test.errors.has_key?(:salutation)
    end

    def test_user_required
        test = KayakoClient::User.new(
            :full_name     => 'Test',
            :emails        => 'test@test.com',
            :password      => 'test'
        )
        assert_raise ArgumentError do
            test.save
        end

        test = KayakoClient::User.new(
            :user_group_id => 1,
            :emails        => 'test@test.com',
            :password      => 'test'
        )
        assert_raise ArgumentError do
            test.save
        end

        test = KayakoClient::User.new(
            :user_group_id => 1,
            :full_name     => 'Test',
            :password      => 'test'
        )
        assert_raise ArgumentError do
            test.save
        end

        test = KayakoClient::User.new(
            :user_group_id => 1,
            :full_name     => 'Test',
            :emails        => 'test@test.com'
        )
        assert_raise ArgumentError do
            test.save
        end
    end

end


text:
package com.capitalone.dashboard.service;

import java.util.List;

import com.capitalone.dashboard.model.CollectorItem;
import com.capitalone.dashboard.model.RallyFeature;
import com.capitalone.dashboard.request.RallyFeatureRequest;
import com.capitalone.dashboard.response.RallyBurnDownResponse;
public interface RallyFeatureService {

	CollectorItem getCollectorItem(RallyFeatureRequest request);
	List<RallyFeature> rallyProjectIterationType(String projectId);

	List<RallyFeature> rallyWidgetDataDetails(CollectorItem item);

	RallyBurnDownResponse rallyBurnDownData(RallyFeature request);

}


text:
package com.ap.dummyapp;

/**
 * Created by Andrew Redko on 6/5/15.
 */
public interface Car {
    public void setFuel(Fuel fuel);
    public Fuel getFuel();
}


text:
#include "physics/CCPhysicsJoint.h"
#if CC_USE_PHYSICS
#include "chipmunk/chipmunk.h"

#include "physics/CCPhysicsBody.h"
#include "physics/CCPhysicsWorld.h"
#include "physics/CCPhysicsHelper.h"
#include "2d/CCNode.h"

NS_CC_BEGIN

PhysicsJoint::PhysicsJoint()
: _bodyA(nullptr)
, _bodyB(nullptr)
, _world(nullptr)
, _enable(false)
, _collisionEnable(true)
, _destroyMark(false)
, _tag(0)
, _maxForce(PHYSICS_INFINITY)
, _initDirty(true)
{

}

PhysicsJoint::~PhysicsJoint()
{
    // reset the shapes collision group
    setCollisionEnable(true);

    for (cpConstraint* joint : _cpConstraints)
    {
        cpConstraintFree(joint);
    }
    _cpConstraints.clear();
}

bool PhysicsJoint::init(cocos2d::PhysicsBody *a, cocos2d::PhysicsBody *b)
{
    do
    {
        CCASSERT(a != nullptr && b != nullptr, "the body passed in is nil");
        CCASSERT(a != b, "the two bodies are equal");

        _bodyA = a;
        _bodyB = b;
        _bodyA->_joints.push_back(this);
        _bodyB->_joints.push_back(this);

        return true;
    } while (false);

    return false;
}

bool PhysicsJoint::initJoint()
{
    bool ret = !_initDirty;
    while (_initDirty)
    {
        ret = createConstraints();
        CC_BREAK_IF(!ret);

        for (auto subjoint : _cpConstraints)
        {
            cpConstraintSetMaxForce(subjoint, _maxForce);
            cpConstraintSetErrorBias(subjoint, cpfpow(1.0f - 0.15f, 60.0f));
            cpSpaceAddConstraint(_world->_cpSpace, subjoint);
        }
        _initDirty = false;
        ret = true;
    }

    return ret;
}

void PhysicsJoint::setEnable(bool enable)
{
    if (_enable != enable)
    {
        _enable = enable;

        if (_world)
        {
            if (enable)
            {
                _world->addJoint(this);
            }
            else
            {
                _world->removeJoint(this, false);
            }
        }
    }
}

void PhysicsJoint::setCollisionEnable(bool enable)
{
    if (_collisionEnable != enable)
    {
        _collisionEnable = enable;
    }
}

void PhysicsJoint::removeFormWorld()
{
    if (_world)
    {
        _world->removeJoint(this, false);
    }
}

void PhysicsJoint::setMaxForce(float force)
{
    _maxForce = force;
    for (auto joint : _cpConstraints)
    {
        cpConstraintSetMaxForce(joint, force);
    }
}

PhysicsJointFixed* PhysicsJointFixed::construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr)
{
    auto joint = new (std::nothrow) PhysicsJointFixed();

    if (joint && joint->init(a, b))
    {
        joint->_anchr = anchr;
        return joint;
    }

    CC_SAFE_DELETE(joint);
    return nullptr;
}

bool PhysicsJointFixed::createConstraints()
{
    do
    {
        _bodyA->getNode()->setPosition(_anchr);
        _bodyB->getNode()->setPosition(_anchr);

        // add a pivot joint to fixed two body together
        auto joint = cpPivotJointNew(_bodyA->getCPBody(), _bodyB->getCPBody(),
            PhysicsHelper::point2cpv(_anchr));
        CC_BREAK_IF(joint == nullptr);
        _cpConstraints.push_back(joint);

        // add a gear joint to make two body have the same rotation.
        joint = cpGearJointNew(_bodyA->getCPBody(), _bodyB->getCPBody(), 0, 1);
        CC_BREAK_IF(joint == nullptr);
        _cpConstraints.push_back(joint);

        _collisionEnable = false;

        return true;
    } while (false);

    return false;
}

PhysicsJointPin* PhysicsJointPin::construct(PhysicsBody* a, PhysicsBody* b, const Vec2& pivot)
{
    auto joint = new (std::nothrow) PhysicsJointPin();

    if (joint && joint->init(a, b))
    {
        joint->_anchr1 = pivot;
        joint->_useSpecificAnchr = false;
        return joint;
    }

    CC_SAFE_DELETE(joint);
    return nullptr;
}

PhysicsJointPin* PhysicsJointPin::construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr1, const Vec2& anchr2)
{
    auto joint = new (std::nothrow) PhysicsJointPin();

    if (joint && joint->init(a, b))
    {
        joint->_anchr1 = anchr1;
        joint->_anchr2 = anchr2;
        joint->_useSpecificAnchr = true;

        return joint;
    }

    CC_SAFE_DELETE(joint);
    return nullptr;
}

bool PhysicsJointPin::createConstraints()
{
    do
    {
        cpConstraint* joint = nullptr;
        if (_useSpecificAnchr)
        {
            joint = cpPivotJointNew2(_bodyA->getCPBody(), _bodyB->getCPBody(),
                PhysicsHelper::point2cpv(_anchr1), PhysicsHelper::point2cpv(_anchr2));
        }
        else
        {
            joint = cpPivotJointNew(_bodyA->getCPBody(), _bodyB->getCPBody(),
                PhysicsHelper::point2cpv(_anchr1));
        }

        CC_BREAK_IF(joint == nullptr);
        _cpConstraints.push_back(joint);

        return true;
    } while (false);

    return false;
}

PhysicsJointLimit* PhysicsJointLimit::construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr1, const Vec2& anchr2, float min, float max)
{
    auto joint = new (std::nothrow) PhysicsJointLimit();

    if (joint && joint->init(a, b))
    {
        joint->_anchr1 = anchr1;
        joint->_anchr2 = anchr2;
        joint->_min = min;
        joint->_max = max;

        return joint;
    }

    CC_SAFE_DELETE(joint);
    return nullptr;
}

PhysicsJointLimit* PhysicsJointLimit::construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr1, const Vec2& anchr2)
{
    return construct(a, b, anchr1, anchr2, 0, b->local2World(anchr1).getDistance(a->local2World(anchr2)));
}

bool PhysicsJointLimit::createConstraints()
{
    do
    {
        auto joint = cpSlideJointNew(_bodyA->getCPBody(), _bodyB->getCPBody(),
            PhysicsHelper::point2cpv(_anchr1),
            PhysicsHelper::point2cpv(_anchr2),
            _min,
            _max);

        CC_BREAK_IF(joint == nullptr);
        _cpConstraints.push_back(joint);

        return true;
    } while (false);

    return false;
}

float PhysicsJointLimit::getMin() const
{
    return PhysicsHelper::cpfloat2float(cpSlideJointGetMin(_cpConstraints.front()));
}

void PhysicsJointLimit::setMin(float min)
{
    cpSlideJointSetMin(_cpConstraints.front(), min);
}

float PhysicsJointLimit::getMax() const
{
    return PhysicsHelper::cpfloat2float(cpSlideJointGetMax(_cpConstraints.front()));
}

void PhysicsJointLimit::setMax(float max)
{
    cpSlideJointSetMax(_cpConstraints.front(), max);
}

Vec2 PhysicsJointLimit::getAnchr1() const
{
    return PhysicsHelper::cpv2point(cpSlideJointGetAnchorA(_cpConstraints.front()));
}

void PhysicsJointLimit::setAnchr1(const Vec2& anchr)
{
    cpSlideJointSetAnchorA(_cpConstraints.front(), PhysicsHelper::point2cpv(anchr));
}

Vec2 PhysicsJointLimit::getAnchr2() const
{
    return PhysicsHelper::cpv2point(cpSlideJointGetAnchorB(_cpConstraints.front()));
}

void PhysicsJointLimit::setAnchr2(const Vec2& anchr)
{
    cpSlideJointSetAnchorB(_cpConstraints.front(), PhysicsHelper::point2cpv(anchr));
}

PhysicsJointDistance* PhysicsJointDistance::construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr1, const Vec2& anchr2)
{
    auto joint = new (std::nothrow) PhysicsJointDistance();

    if (joint && joint->init(a, b))
    {
        joint->_anchr1 = anchr1;
        joint->_anchr2 = anchr2;

        return joint;
    }

    CC_SAFE_DELETE(joint);
    return nullptr;
}

bool PhysicsJointDistance::createConstraints()
{
    do
    {
        auto joint = cpPinJointNew(_bodyA->getCPBody(),
            _bodyB->getCPBody(),
            PhysicsHelper::point2cpv(_anchr1),
            PhysicsHelper::point2cpv(_anchr2));
        CC_BREAK_IF(joint == nullptr);
        _cpConstraints.push_back(joint);

        return true;
    } while (false);

    return false;
}

float PhysicsJointDistance::getDistance() const
{
    return PhysicsHelper::cpfloat2float(cpPinJointGetDist(_cpConstraints.front()));
}

void PhysicsJointDistance::setDistance(float distance)
{
    cpPinJointSetDist(_cpConstraints.front(), distance);
}

PhysicsJointSpring* PhysicsJointSpring::construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr1, const Vec2& anchr2, float stiffness, float damping)
{
    auto joint = new (std::nothrow) PhysicsJointSpring();

    if (joint && joint->init(a, b))
    {
        joint->_anchr1 = anchr1;
        joint->_anchr2 = anchr2;
        joint->_stiffness = stiffness;
        joint->_damping = damping;

        return joint;
    }

    CC_SAFE_DELETE(joint);
    return nullptr;
}

bool PhysicsJointSpring::createConstraints()
{
    do {
        auto joint = cpDampedSpringNew(_bodyA->getCPBody(),
            _bodyB->getCPBody(),
            PhysicsHelper::point2cpv(_anchr1),
            PhysicsHelper::point2cpv(_anchr2),
            _bodyB->local2World(_anchr1).getDistance(_bodyA->local2World(_anchr2)),
            _stiffness,
            _damping);

        CC_BREAK_IF(joint == nullptr);
        _cpConstraints.push_back(joint);

        return true;
    } while (false);

    return false;
}

Vec2 PhysicsJointSpring::getAnchr1() const
{
    return PhysicsHelper::cpv2point(cpDampedSpringGetAnchorA(_cpConstraints.front()));
}

void PhysicsJointSpring::setAnchr1(const Vec2& anchr)
{
    cpDampedSpringSetAnchorA(_cpConstraints.front(), PhysicsHelper::point2cpv(anchr));
}

Vec2 PhysicsJointSpring::getAnchr2() const
{
    return PhysicsHelper::cpv2point(cpDampedSpringGetAnchorB(_cpConstraints.front()));
}

void PhysicsJointSpring::setAnchr2(const Vec2& anchr)
{
    cpDampedSpringSetAnchorB(_cpConstraints.front(), PhysicsHelper::point2cpv(anchr));
}

float PhysicsJointSpring::getRestLength() const
{
    return PhysicsHelper::cpfloat2float(cpDampedSpringGetRestLength(_cpConstraints.front()));
}

void PhysicsJointSpring::setRestLength(float restLength)
{
    cpDampedSpringSetRestLength(_cpConstraints.front(), restLength);
}

float PhysicsJointSpring::getStiffness() const
{
    return PhysicsHelper::cpfloat2float(cpDampedSpringGetStiffness(_cpConstraints.front()));
}

void PhysicsJointSpring::setStiffness(float stiffness)
{
    cpDampedSpringSetStiffness(_cpConstraints.front(), stiffness);
}

float PhysicsJointSpring::getDamping() const
{
    return PhysicsHelper::cpfloat2float(cpDampedSpringGetDamping(_cpConstraints.front()));
}

void PhysicsJointSpring::setDamping(float damping)
{
    cpDampedSpringSetDamping(_cpConstraints.front(), damping);
}

PhysicsJointGroove* PhysicsJointGroove::construct(PhysicsBody* a, PhysicsBody* b, const Vec2& grooveA, const Vec2& grooveB, const Vec2& anchr2)
{
    auto joint = new (std::nothrow) PhysicsJointGroove();

    if (joint && joint->init(a, b))
    {
        joint->_grooveA = grooveA;
        joint->_grooveB = grooveB;
        joint->_anchr2 = anchr2;

        return joint;
    }

    CC_SAFE_DELETE(joint);
    return nullptr;
}

bool PhysicsJointGroove::createConstraints()
{
    do {
        auto joint = cpGrooveJointNew(_bodyA->getCPBody(),
            _bodyB->getCPBody(),
            PhysicsHelper::point2cpv(_grooveA),
            PhysicsHelper::point2cpv(_grooveB),
            PhysicsHelper::point2cpv(_anchr2));

        CC_BREAK_IF(joint == nullptr);
        _cpConstraints.push_back(joint);

        return true;
    } while (false);

    return false;
}

Vec2 PhysicsJointGroove::getGrooveA() const
{
    return PhysicsHelper::cpv2point(cpGrooveJointGetGrooveA(_cpConstraints.front()));
}

void PhysicsJointGroove::setGrooveA(const Vec2& grooveA)
{
    cpGrooveJointSetGrooveA(_cpConstraints.front(), PhysicsHelper::point2cpv(grooveA));
}

Vec2 PhysicsJointGroove::getGrooveB() const
{
    return PhysicsHelper::cpv2point(cpGrooveJointGetGrooveB(_cpConstraints.front()));
}

void PhysicsJointGroove::setGrooveB(const Vec2& grooveB)
{
    cpGrooveJointSetGrooveB(_cpConstraints.front(), PhysicsHelper::point2cpv(grooveB));
}

Vec2 PhysicsJointGroove::getAnchr2() const
{
    return PhysicsHelper::cpv2point(cpGrooveJointGetAnchorB(_cpConstraints.front()));
}

void PhysicsJointGroove::setAnchr2(const Vec2& anchr2)
{
    cpGrooveJointSetAnchorB(_cpConstraints.front(), PhysicsHelper::point2cpv(anchr2));
}

PhysicsJointRotarySpring* PhysicsJointRotarySpring::construct(PhysicsBody* a, PhysicsBody* b, float stiffness, float damping)
{
    auto joint = new (std::nothrow) PhysicsJointRotarySpring();

    if (joint && joint->init(a, b))
    {
        joint->_stiffness = stiffness;
        joint->_damping = damping;

        return joint;
    }

    CC_SAFE_DELETE(joint);
    return nullptr;
}

bool PhysicsJointRotarySpring::createConstraints()
{
    do {
        auto joint = cpDampedRotarySpringNew(_bodyA->getCPBody(),
            _bodyB->getCPBody(),
            _bodyB->getRotation() - _bodyA->getRotation(),
            _stiffness,
            _damping);

        CC_BREAK_IF(joint == nullptr);
        _cpConstraints.push_back(joint);

        return true;
    } while (false);

    return false;
}

float PhysicsJointRotarySpring::getRestAngle() const
{
    return PhysicsHelper::cpfloat2float(cpDampedRotarySpringGetRestAngle(_cpConstraints.front()));
}

void PhysicsJointRotarySpring::setRestAngle(float restAngle)
{
    cpDampedRotarySpringSetRestAngle(_cpConstraints.front(), restAngle);
}

float PhysicsJointRotarySpring::getStiffness() const
{
    return PhysicsHelper::cpfloat2float(cpDampedRotarySpringGetStiffness(_cpConstraints.front()));
}

void PhysicsJointRotarySpring::setStiffness(float stiffness)
{
    cpDampedRotarySpringSetStiffness(_cpConstraints.front(), stiffness);
}

float PhysicsJointRotarySpring::getDamping() const
{
    return PhysicsHelper::cpfloat2float(cpDampedRotarySpringGetDamping(_cpConstraints.front()));
}

void PhysicsJointRotarySpring::setDamping(float damping)
{
    cpDampedRotarySpringSetDamping(_cpConstraints.front(), damping);
}

PhysicsJointRotaryLimit* PhysicsJointRotaryLimit::construct(PhysicsBody* a, PhysicsBody* b, float min, float max)
{
    auto joint = new (std::nothrow) PhysicsJointRotaryLimit();

    if (joint && joint->init(a, b))
    {
        joint->_min = min;
        joint->_max = max;

        return joint;
    }

    CC_SAFE_DELETE(joint);
    return nullptr;
}

PhysicsJointRotaryLimit* PhysicsJointRotaryLimit::construct(PhysicsBody* a, PhysicsBody* b)
{
    return construct(a, b, 0.0f, 0.0f);
}

bool PhysicsJointRotaryLimit::createConstraints()
{
    do
    {
        auto joint = cpRotaryLimitJointNew(_bodyA->getCPBody(),
            _bodyB->getCPBody(),
            _min,
            _max);

        CC_BREAK_IF(joint == nullptr);
        _cpConstraints.push_back(joint);

        return true;
    } while (false);

    return false;
}

float PhysicsJointRotaryLimit::getMin() const
{
    return PhysicsHelper::cpfloat2float(cpRotaryLimitJointGetMin(_cpConstraints.front()));
}

void PhysicsJointRotaryLimit::setMin(float min)
{
    cpRotaryLimitJointSetMin(_cpConstraints.front(), min);
}

float PhysicsJointRotaryLimit::getMax() const
{
    return PhysicsHelper::cpfloat2float(cpRotaryLimitJointGetMax(_cpConstraints.front()));
}

void PhysicsJointRotaryLimit::setMax(float max)
{
    cpRotaryLimitJointSetMax(_cpConstraints.front(), max);
}

PhysicsJointRatchet* PhysicsJointRatchet::construct(PhysicsBody* a, PhysicsBody* b, float phase, float ratchet)
{
    auto joint = new (std::nothrow) PhysicsJointRatchet();

    if (joint && joint->init(a, b))
    {
        joint->_phase = phase;
        joint->_ratchet = ratchet;

        return joint;
    }

    CC_SAFE_DELETE(joint);
    return nullptr;
}

bool PhysicsJointRatchet::createConstraints()
{
    do
    {
        auto joint = cpRatchetJointNew(_bodyA->getCPBody(),
            _bodyB->getCPBody(),
            _phase,
            PhysicsHelper::cpfloat2float(_ratchet));

        CC_BREAK_IF(joint == nullptr);
        _cpConstraints.push_back(joint);

        return true;
    } while (false);

    return false;
}

float PhysicsJointRatchet::getAngle() const
{
    return PhysicsHelper::cpfloat2float(cpRatchetJointGetAngle(_cpConstraints.front()));
}

void PhysicsJointRatchet::setAngle(float angle)
{
    cpRatchetJointSetAngle(_cpConstraints.front(), angle);
}

float PhysicsJointRatchet::getPhase() const
{
    return PhysicsHelper::cpfloat2float(cpRatchetJointGetPhase(_cpConstraints.front()));
}

void PhysicsJointRatchet::setPhase(float phase)
{
    cpRatchetJointSetPhase(_cpConstraints.front(), phase);
}

float PhysicsJointRatchet::getRatchet() const
{
    return PhysicsHelper::cpfloat2float(cpRatchetJointGetRatchet(_cpConstraints.front()));
}

void PhysicsJointRatchet::setRatchet(float ratchet)
{
    cpRatchetJointSetRatchet(_cpConstraints.front(), ratchet);
}

PhysicsJointGear* PhysicsJointGear::construct(PhysicsBody* a, PhysicsBody* b, float phase, float ratio)
{
    auto joint = new (std::nothrow) PhysicsJointGear();

    if (joint && joint->init(a, b))
    {
        joint->_phase = phase;
        joint->_ratio = ratio;

        return joint;
    }

    CC_SAFE_DELETE(joint);
    return nullptr;
}

bool PhysicsJointGear::createConstraints()
{
    do
    {
        auto joint = cpGearJointNew(_bodyA->getCPBody(),
            _bodyB->getCPBody(),
            _phase,
            _ratio);

        CC_BREAK_IF(joint == nullptr);
        _cpConstraints.push_back(joint);

        return true;
    } while (false);

    return false;
}

float PhysicsJointGear::getPhase() const
{
    return PhysicsHelper::cpfloat2float(cpGearJointGetPhase(_cpConstraints.front()));
}

void PhysicsJointGear::setPhase(float phase)
{
    cpGearJointSetPhase(_cpConstraints.front(), phase);
}

float PhysicsJointGear::getRatio() const
{
    return PhysicsHelper::cpfloat2float(cpGearJointGetRatio(_cpConstraints.front()));
}

void PhysicsJointGear::setRatio(float ratio)
{
    cpGearJointSetRatio(_cpConstraints.front(), ratio);
}

PhysicsJointMotor* PhysicsJointMotor::construct(PhysicsBody* a, PhysicsBody* b, float rate)
{
    auto joint = new (std::nothrow) PhysicsJointMotor();

    if (joint && joint->init(a, b))
    {
        joint->_rate = rate;

        return joint;
    }

    CC_SAFE_DELETE(joint);
    return nullptr;
}

bool PhysicsJointMotor::createConstraints()
{
    do
    {
        auto joint = cpSimpleMotorNew(_bodyA->getCPBody(),
            _bodyB->getCPBody(),
            _rate);

        CC_BREAK_IF(joint == nullptr);
        _cpConstraints.push_back(joint);

        return true;
    } while (false);

    return false;
}

float PhysicsJointMotor::getRate() const
{
    return PhysicsHelper::cpfloat2float(cpSimpleMotorGetRate(_cpConstraints.front()));
}

void PhysicsJointMotor::setRate(float rate)
{
    cpSimpleMotorSetRate(_cpConstraints.front(), rate);
}

NS_CC_END
#endif // CC_USE_PHYSICS


text:
(function(GUIElement) {
  'use strict';

  /**
   * ProgressBar Element
   *
   * @param String    name        Name of GUIElement (unique)
   * @param int       percentage  Start at this value
   *
   * @api OSjs.GUI.ProgressBar
   * @see OSjs.Core.GUIElement
   *
   * @extends GUIElement
   * @class
   */
  var ProgressBar = function(name, percentage) {
    this.$container = null;
    this.$bar       = null;
    this.$label     = null;
    this.percentage = percentage || 0;

    GUIElement.apply(this, [name, {}]);
  };

  ProgressBar.prototype = Object.create(GUIElement.prototype);

  ProgressBar.prototype.init = function() {
    var el = GUIElement.prototype.init.apply(this, ['GUIProgressBar']);

    this.$container           = document.createElement('div');
    this.$container.className = 'Container';

    this.$bar           = document.createElement('div');
    this.$bar.className = 'Bar';
    this.$container.appendChild(this.$bar);

    this.$label           = document.createElement('div');
    this.$label.className = 'Label';
    this.$container.appendChild(this.$label);

    el.appendChild(this.$container);

    this.setPercentage(this.percentage);
    return el;
  };

  /**
   * Set the current value of progressbar
   *
   * @param   int     p     Progress percentage
   *
   * @return  void
   *
   * @method  ProgressBar::setPercentage()
   */
  ProgressBar.prototype.setPercentage = function(p) {
    if ( p < 0 || p > 100 ) { return; }
    this.percentage       = parseInt(p, 10);
    this.$bar.style.width = this.percentage + '%';
    this.$label.innerHTML = this.percentage + '%';
  };

  /**
   * Alias of setPercentage()
   * @see ProgressBar::setPercentage()
   * @method ProgressBar::setProgress()
   */
  ProgressBar.prototype.setProgress = function(p) {
    this.setPercentage(p);
  };

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  OSjs.GUI.ProgressBar  = ProgressBar;

})(OSjs.Core.GUIElement);


text:
#region copyright
// <copyright file="Account.cs" >
// Copyright (c) 2016 All Rights Reserved
// Licensed under MIT
// </copyright>
// <author>Raj Bandi</author>
// <date>26/6/2016</date>
// <summary></summary>
#endregion
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace RiseSharp.Core.Api.Models
{
    [DataContract]
    public class Account
    {
        [DataMember(Name = "address")]
        public string Address { get; set; }

        [DataMember(Name = "unconfirmedBalance")]
        public string UnconfirmedBalance { get; set; }

        [DataMember(Name = "balance")]
        public string Balance { get; set; }

        [DataMember(Name = "publicKey")]
        public string PublicKey { get; set; }

        [DataMember(Name = "unconfirmedSignature")]
        public int UnconfirmedSignature { get; set; }

        [DataMember(Name = "secondSignature")]
        public int SecondSignature { get; set; }

        [DataMember(Name = "secondPublicKey")]
        public object SecondPublicKey { get; set; }

        [DataMember(Name = "multisignatures")]
        public IList<object> Multisignatures { get; set; }

        [DataMember(Name = "u_multisignatures")]
        public IList<object> UMultisignatures { get; set; }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.BotService.Resources;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace Microsoft.Azure.Management.BotService
{
    /// <summary>
    /// Obtains user level tokesn with the bot service first party app audience in order
    /// to provision Msa Apps, which are crucial for bots to work
    /// </summary>
    internal class MsaAuthenticator
    {
        private const string BotFirstPartyAppId = "f3723d34-6ff5-4ceb-a148-d99dcd2511fc";
        private const string AadClientId = "1950a258-227b-4e31-a9cf-717495945fc2";
        private const string AadRedirectUri = "urn:ietf:wg:oauth:2.0:oob";

        private readonly string tenantId;

#if NET452

        /// <summary>
        /// Creates an instance of MsaAuthenticator
        /// </summary>
        public MsaAuthenticator(string tenantId)
        {
            this.tenantId = tenantId;
        }

#endif
#if NETSTANDARD1_4

        private readonly Action<DeviceCodeResult> deviceCodeAuthHandler;

        /// <summary>
        /// Creates an instance of MsaAuthenticator
        /// </summary>
        public MsaAuthenticator(string tenantId, Action<DeviceCodeResult> deviceCodeAuthHandler)
        {
            this.tenantId = tenantId;
            this.deviceCodeAuthHandler = deviceCodeAuthHandler;
        }

#endif

        /// <summary>
        /// Acquires a user token with the bot service first party app as audience
        /// </summary>
        /// <returns></returns>
        public async Task<AuthenticationResult> AcquireTokenAsync()
        {
            var authority = $"https://login.windows.net/{tenantId}";
            var context = new AuthenticationContext(
                authority: authority,
                validateAuthority: true);

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

#if NET452

            return context.AcquireToken(
                resource: BotFirstPartyAppId,
                clientId: AadClientId,
                redirectUri: new Uri(AadRedirectUri),
                promptBehavior: PromptBehavior.Always);
#endif
#if NETSTANDARD1_4

            // Request a device code
            var deviceCodeResult = await context.AcquireDeviceCodeAsync(BotFirstPartyAppId, AadClientId);

            if (deviceCodeAuthHandler == null)
            {
                throw new ArgumentException(BotServiceErrorMessages.DeviceCodeAuthNotProvided,
                    nameof(deviceCodeAuthHandler));
            }

            // Execute the user-provided handler for device code. It should prompt the user to
            // do device login
            deviceCodeAuthHandler(deviceCodeResult);

            // Now, the user should have entered the device code, acquire token
            return await context.AcquireTokenByDeviceCodeAsync(deviceCodeResult);
#endif
        }
    }
}


text:
#include <string>
#include "../public/tokenizer.h"
#include "emailSender_js.hpp"
#include "emailSender_ndk.hpp"

using namespace std;

/**
 * Default constructor.
 */
EmailSenderJS::EmailSenderJS(const std::string& id) :
		m_id(id) {
	m_pLogger = new webworks::Logger("EmailSenderJS", this);
	m_pTemplateController = new webworks::EmailSenderNDK(this);
}

/**
 * TemplateJS destructor.
 */
EmailSenderJS::~EmailSenderJS() {
	if (m_pTemplateController)
		delete m_pTemplateController;
	if (m_pLogger)
		delete m_pLogger;
}

webworks::Logger* EmailSenderJS::getLog() {
	return m_pLogger;
}

/**
 * This method returns the list of objects implemented by this native
 * extension.
 */
char* onGetObjList() {
	static char name[] = "EmailSenderJS";
	return name;
}

/**
 * This method is used by JNext to instantiate the TemplateJS object when
 * an object is created on the JavaScript server side.
 */
JSExt* onCreateObject(const string& className, const string& id) {
	if (className == "EmailSenderJS") {
		return new EmailSenderJS(id);
	}

	return NULL;
}

/**
 * Method used by JNext to determine if the object can be deleted.
 */
bool EmailSenderJS::CanDelete() {
	return true;
}

/**
 * It will be called from JNext JavaScript side with passed string.
 * This method implements the interface for the JavaScript to native binding
 * for invoking native code. This method is triggered when JNext.invoke is
 * called on the JavaScript side with this native objects id.
 */
string EmailSenderJS::InvokeMethod(const string& command) {
	// format must be: "command callbackId params"
	size_t commandIndex = command.find_first_of(" ");
	std::string strCommand = command.substr(0, commandIndex);
	size_t callbackIndex = command.find_first_of(" ", commandIndex + 1);
	std::string callbackId = command.substr(commandIndex + 1, callbackIndex - commandIndex - 1);
	std::string arg = command.substr(callbackIndex + 1, command.length());

	// based on the command given, run the appropriate method in template_ndk.cpp

	if (strCommand == "sendEmail") {
		return m_pTemplateController->sendEmail(arg);
	}else if (strCommand == "getEmailAccounts") {
		return m_pTemplateController->getEmailAccounts();
	}

	strCommand.append(";");
	strCommand.append(command);
	return strCommand;
}

// Notifies JavaScript of an event
void EmailSenderJS::NotifyEvent(const std::string& event) {
	std::string eventString = m_id + " ";
	eventString.append(event);
	SendPluginEvent(eventString.c_str(), m_pContext);
}


text:
#include "include/gpu/d3d/GrD3DTypes.h"
#include "include/private/GrD3DTypesPriv.h"

#include "src/gpu/d3d/GrD3DResourceState.h"

GrD3DBackendSurfaceInfo::GrD3DBackendSurfaceInfo(const GrD3DTextureResourceInfo& info,
                                                 GrD3DResourceState* state)
    : fTextureResourceInfo(new GrD3DTextureResourceInfo(info))
    , fResourceState(state) {}

void GrD3DBackendSurfaceInfo::cleanup() {
    SkSafeUnref(fResourceState);
    fResourceState = nullptr;
    delete fTextureResourceInfo;
    fTextureResourceInfo = nullptr;
};

void GrD3DBackendSurfaceInfo::assign(const GrD3DBackendSurfaceInfo& that, bool isThisValid) {
    GrD3DTextureResourceInfo* oldInfo = fTextureResourceInfo;
    GrD3DResourceState* oldLayout = fResourceState;
    fTextureResourceInfo = new GrD3DTextureResourceInfo(*that.fTextureResourceInfo);
    fResourceState = SkSafeRef(that.fResourceState);
    if (isThisValid) {
        delete oldInfo;
        SkSafeUnref(oldLayout);
    }
}

void GrD3DBackendSurfaceInfo::setResourceState(GrD3DResourceStateEnum resourceState) {
    SkASSERT(fResourceState);
    fResourceState->setResourceState(static_cast<D3D12_RESOURCE_STATES>(resourceState));
}

sk_sp<GrD3DResourceState> GrD3DBackendSurfaceInfo::getGrD3DResourceState() const {
    SkASSERT(fResourceState);
    return sk_ref_sp(fResourceState);
}

GrD3DTextureResourceInfo GrD3DBackendSurfaceInfo::snapTextureResourceInfo() const {
    return GrD3DTextureResourceInfo(*fTextureResourceInfo, fResourceState->getResourceState());
}

bool GrD3DBackendSurfaceInfo::isProtected() const {
    SkASSERT(fTextureResourceInfo);
    return fTextureResourceInfo->fProtected == GrProtected::kYes;
}

#if GR_TEST_UTILS
bool GrD3DBackendSurfaceInfo::operator==(const GrD3DBackendSurfaceInfo& that) const {
    GrD3DTextureResourceInfo cpyInfoThis = *fTextureResourceInfo;
    GrD3DTextureResourceInfo cpyInfoThat = *that.fTextureResourceInfo;
    // We don't care about the fResourceState here since we require they use the same
    // GrD3DResourceState.
    cpyInfoThis.fResourceState = D3D12_RESOURCE_STATE_COMMON;
    cpyInfoThat.fResourceState = D3D12_RESOURCE_STATE_COMMON;
    return cpyInfoThis == cpyInfoThat && fResourceState == that.fResourceState;
}
#endif


text:
using namespace IECoreHoudini;
using namespace boost::python;

void IECoreHoudini::bindFromHoudiniConverter()
{
	IECorePython::RunTimeTypedClass<FromHoudiniConverter>();
}


text:
{-# LANGUAGE OverloadedStrings, ExtendedDefaultRules,FlexibleInstances #-}
{-# LANGUAGE DefaultSignatures,FlexibleContexts,TypeApplications,TypeOperators #-}
{-# LANGUAGE InstanceSigs, TypeSynonymInstances,ScopedTypeVariables, DeriveGeneric #-}
{-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, DeriveGeneric, DefaultSignatures,
             PolyKinds, TypeOperators, ScopedTypeVariables, FlexibleContexts,
             FlexibleInstances, UndecidableInstances,
             OverloadedStrings, TypeApplications, StandaloneDeriving #-}

module Lucid.Tables where

import Lucid
import Data.Proxy
import qualified Data.Text as T
import GHC.Generics
import Data.Monoid

class ToHtmlTable a where
  headers:: Proxy a->[T.Text]

  default headers:: (Generic a,TableSelectors (Rep a)) => Proxy a -> [T.Text]
  headers  = map (T.pack) . tableSelectors

  toHtmlRow:: Monad m => a ->[HtmlT m ()]
  default toHtmlRow:: (Monad m, Generic a, GToTable (Rep a)) => a -> [HtmlT m ()]
  toHtmlRow a = gtoHtmlRow (from a)

class GToTable f where
  gtoHtmlRow:: Monad m => f a ->[HtmlT m ()]

instance GToTable U1 where
  gtoHtmlRow U1 = []

instance GToTable a => GToTable  (M1 C c a) where

  gtoHtmlRow =gtoHtmlRow . unM1

instance GToTable a => GToTable (M1 D c a) where

  gtoHtmlRow =gtoHtmlRow . unM1

instance (GToTable a, GToTable b) => GToTable (a :*: b) where
  gtoHtmlRow (a :*: b) =  (gtoHtmlRow a) <> (gtoHtmlRow b)

instance (Selector d, ToHtml a) => GToTable (M1 S d (K1 R a)) where

  gtoHtmlRow (M1 (K1 x)) =[toHtml x ]

-- https://hackage.haskell.org/package/hpack-0.15.0/src/src/Hpack/GenericsUtil.hs
-- Copyright (c) 2014-2016 Simon Hengel <sol@typeful.net>

tableSelectors :: (TableSelectors (Rep a)) => Proxy a -> [String]
tableSelectors = f
  where
    f :: forall a. (TableSelectors (Rep a)) => Proxy a -> [String]
    f _ = selNames (Proxy :: Proxy (Rep a))

class TableSelectors a where
  selNames :: Proxy a -> [String]

instance TableSelectors f => TableSelectors (M1 D x f) where
  selNames _ = selNames (Proxy :: Proxy f)

instance TableSelectors f => TableSelectors (M1 C x f) where
  selNames _ = selNames (Proxy :: Proxy f)

instance Selector s => TableSelectors (M1 S s (K1 R t)) where
  selNames _ = [selName (undefined :: M1 S s (K1 R t) ())]

instance (TableSelectors a, TableSelectors b) => TableSelectors (a :*: b) where
  selNames _ = selNames (Proxy :: Proxy a) ++ selNames (Proxy :: Proxy b)

instance TableSelectors U1 where
  selNames _ = []

{-
data Test = Test{
  foo :: String,
  bar ::String} deriving Generic

instance ToHtmlTable Test

h = headers $ Proxy @Test
b :: [Html ()]

b = toHtmlRow $ Test "hello" "world"
g = from $ Test "hello" "world"
-}


text:
require 'rubygems'
require 'specular'

$:.unshift ::File.expand_path '../../lib', __FILE__
require 'sonar'

class Air < ::Rack::Request
  class << self

    def use ware = nil, *args, &proc
      @middleware ||= []
      @middleware << [ware, args, proc] if ware
      @middleware
    end

    def map
      @map
    end

    def action_map
      @action_map
    end

    def app root = nil
      if root
        @root = root
      else
        return @app if @app
      end
      map!

      builder, app = ::Rack::Builder.new, self
      use.each do |w|
        ware, args, proc = w
        builder.use ware, *args, &proc
      end
      map.each_key do |route|
        builder.map route do
          run lambda { |env| app.new(env).__air__response__ route }
        end
      end
      @app = builder.to_app
    end

    alias to_app app

    def call env
      app.call env
    end

    def base_url
      @root || '/'
    end

    alias baseurl base_url

    private
    def map!
      @action_map = {}
      @map = self.instance_methods(false).reject { |m| m.to_s =~ /^__air__/ }.inject({}) do |map, meth|
        route, request_method = meth.to_s, 'GET'
        SonarConstants::REQUEST_METHODS.each do |rm|
          regex = /^#{rm}_/i
          route =~ regex && (route = route.sub(regex, '')) && (request_method = rm.upcase) && break
        end

        {'____' => '.',
         '___' => '-',
         '__' => '/'}.each_pair { |f, t| route = route.gsub(f, t) }

        arity = self.instance_method(meth).arity
        setup = [meth, arity < 0 ? -arity - 1 : arity]
        (map[rootify(route)] ||={})[request_method] = setup
        (map[rootify] ||= {})[request_method] = setup if route == 'index'
        @action_map[meth.to_sym] = rootify(route)
        map
      end
    end

    def rootify route = nil
      ('/%s/%s' % [base_url, route]).gsub /\/+/, '/'
    end
  end

  attr_reader :response

  def __air__response__ route
    rsp = catch :__air__halt__ do
      @response = ::Rack::Response.new
      rest_map = self.class.map[route] || halt(404)
      action, required_parameters = rest_map[env['REQUEST_METHOD']] || halt(404)
      arguments = env['PATH_INFO'].to_s.split('/').select { |c| c.size > 0 }
      arguments.size == required_parameters || halt(404, '%s arguments expected, %s given' % [required_parameters, arguments.size])
      response.body = [self.send(action, *arguments).to_s]
      response
    end
    rsp['Content-Type'] ||= 'text/html'
    rsp.finish
  end

  def base_url
    self.class.base_url
  end

  def halt status, message = nil
    response.status = status
    response.body = [message] if message
    throw :__air__halt__, response
  end

  def redirect action_or_path
    response['Location'] = self.class.action_map[action_or_path] || action_or_path
    response.status = 302
    throw :__air__halt__, response
  end

  def permanent_redirect action_or_path
    response['Location'] = self.class.action_map[action_or_path] || action_or_path
    response.status = 301
    throw :__air__halt__, response
  end

  def params
    @__air__params__ ||= indifferent_params(super)
  end

  def get_params
    @__air__get_params__ ||= indifferent_params(self.GET)
  end

  def post_params
    @__air__post_params__ ||= indifferent_params(self.POST)
  end

  private
  def indifferent_params(object)
    case object
      when Hash
        new_hash = indifferent_hash
        object.each { |key, value| new_hash[key] = indifferent_params(value) }
        new_hash
      when Array
        object.map { |item| indifferent_params(item) }
      else
        object
    end
  end

  def indifferent_hash
    Hash.new { |hash, key| hash[key.to_s] if Symbol === key }
  end
end


text:
name             'faims_db'
maintainer       'VeRSI'
maintainer_email 'martin.paulo@versi.edu.au'
license          'Apache 2.0'
description      'Installs/Configures faims_db'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.0.1'
depends          'postgresql'


text:
namespace pp {
class InputEvent;
}  // namespace pp

struct ColorPremul { uint32_t A, R, G, B; };  // Use premultipled Alpha.

class TestFullscreen : public TestCase {
 public:
  explicit TestFullscreen(TestingInstance* instance);

  // TestCase implementation.
  virtual bool Init();
  virtual void RunTests(const std::string& filter);
  virtual bool HandleInputEvent(const pp::InputEvent& event);
  virtual void DidChangeView(const pp::View& view);

  void CheckPluginPaint();

 private:
  std::string TestGetScreenSize();
  std::string TestNormalToFullscreenToNormal();

  void SimulateUserGesture();
  void FailFullscreenTest(const std::string& error);
  void FailNormalTest(const std::string& error);
  void PassFullscreenTest();
  void PassNormalTest();
  bool PaintPlugin(pp::Size size, ColorPremul color);

  bool GotError();
  std::string Error();

  std::string error_;

  pp::Fullscreen screen_mode_;
  pp::Size screen_size_;
  pp::Rect normal_position_;
  pp::Size painted_size_;
  uint32_t painted_color_;

  bool fullscreen_pending_;
  bool normal_pending_;
  pp::Graphics2D graphics2d_;

  NestedEvent fullscreen_event_;
  NestedEvent normal_event_;
};

#endif  // PPAPI_TESTS_TEST_FULLSCREEN_H_


text:
package types

import (
	"encoding/binary"

	sdk "github.com/cosmos/cosmos-sdk/types"
)

var _ binary.ByteOrder

const (
	// PendingAccountRevocationKeyPrefix is the prefix to retrieve all PendingAccountRevocation.
	PendingAccountRevocationKeyPrefix = "PendingAccountRevocation/value/"
)

// PendingAccountRevocationKey returns the store key to retrieve a PendingAccountRevocation from the index fields.
func PendingAccountRevocationKey(
	address sdk.AccAddress,
) []byte {
	var key []byte

	addressBytes := []byte(address)
	key = append(key, addressBytes...)
	key = append(key, []byte("/")...)

	return key
}