text:
package com.mongodb.client;

import com.mongodb.AutoEncryptionSettings;
import com.mongodb.ClientEncryptionSettings;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.client.model.vault.EncryptOptions;
import com.mongodb.client.vault.ClientEncryption;
import com.mongodb.client.vault.ClientEncryptions;
import org.bson.BsonBinary;
import org.bson.BsonBinarySubType;
import org.bson.BsonDocument;
import org.bson.BsonString;
import org.bson.BsonValue;
import org.bson.UuidRepresentation;
import org.bson.codecs.UuidCodec;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Base64;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import static com.mongodb.ClusterFixture.hasEncryptionTestsEnabled;
import static com.mongodb.ClusterFixture.serverVersionAtLeast;
import static com.mongodb.client.Fixture.getMongoClientSettings;
import static com.mongodb.client.Fixture.getMongoClientSettingsBuilder;
import static java.util.Arrays.asList;
import static org.bson.codecs.configuration.CodecRegistries.fromCodecs;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assume.assumeTrue;
import static util.JsonPoweredTestHelper.getTestDocument;

// See https://github.com/mongodb/specifications/tree/master/source/client-side-encryption/corpus
@RunWith(Parameterized.class)
public class ClientSideEncryptionCorpusTest {
    private final boolean useLocalSchema;
    private MongoClient client;
    private MongoClient autoEncryptingClient;
    private ClientEncryption clientEncryption;

    public ClientSideEncryptionCorpusTest(final boolean useLocalSchema) {
        this.useLocalSchema = useLocalSchema;
    }

    @Before
    public void setUp() throws IOException, URISyntaxException {
        assumeTrue(serverVersionAtLeast(4, 2));
        assumeTrue("Corpus tests disabled", hasEncryptionTestsEnabled());

        MongoClientSettings clientSettings = getMongoClientSettingsBuilder()
                .codecRegistry(fromRegistries(fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)),
                        MongoClientSettings.getDefaultCodecRegistry())).build();

        // Step 1: create unencrypted client
        client = MongoClients.create(clientSettings);
        MongoDatabase db = client.getDatabase("db");

        // Step 2: Drop and recreate db.coll with schema
        BsonDocument schemaDocument = bsonDocumentFromPath("corpus-schema.json");

        db.getCollection("coll").drop();
        db.runCommand(new BsonDocument("create", new BsonString("coll"))
                .append("validator", new BsonDocument("$jsonSchema", schemaDocument)));

        // Step 3: Drop and create keyvault.datakeys
        MongoDatabase keyvaultDatabase = client.getDatabase("keyvault");
        MongoCollection<BsonDocument> dataKeysCollection = keyvaultDatabase.getCollection("datakeys", BsonDocument.class)
                .withWriteConcern(WriteConcern.MAJORITY);
        dataKeysCollection.drop();
        dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-aws.json"));
        dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-azure.json"));
        dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-gcp.json"));
        dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-kmip.json"));
        dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-local.json"));

        // Step 4: Configure our objects
        Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {{
            put("aws",  new HashMap<String, Object>() {{
                put("accessKeyId", System.getProperty("org.mongodb.test.awsAccessKeyId"));
                put("secretAccessKey", System.getProperty("org.mongodb.test.awsSecretAccessKey"));
            }});
            put("azure",  new HashMap<String, Object>() {{
                put("tenantId", System.getProperty("org.mongodb.test.azureTenantId"));
                put("clientId", System.getProperty("org.mongodb.test.azureClientId"));
                put("clientSecret", System.getProperty("org.mongodb.test.azureClientSecret"));
            }});
            put("gcp",  new HashMap<String, Object>() {{
                put("email", System.getProperty("org.mongodb.test.gcpEmail"));
                put("privateKey", System.getProperty("org.mongodb.test.gcpPrivateKey"));
            }});
            put("kmip",  new HashMap<String, Object>() {{
                put("endpoint", System.getProperty("org.mongodb.test.kmipEndpoint", "localhost:5698"));
            }});
            put("local", new HashMap<String, Object>() {{
                put("key", "Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBM"
                            + "UN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk");
                }});
        }};

        HashMap<String, BsonDocument> schemaMap = new HashMap<String, BsonDocument>();
        schemaMap.put("db.coll", schemaDocument);

        AutoEncryptionSettings.Builder autoEncryptionSettingsBuilder = AutoEncryptionSettings.builder()
                .keyVaultNamespace("keyvault.datakeys")
                .kmsProviders(kmsProviders);

        if (useLocalSchema) {
            autoEncryptionSettingsBuilder.schemaMap(schemaMap);
        }

        clientSettings = getMongoClientSettingsBuilder()
                .codecRegistry(fromRegistries(
                        fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)), MongoClientSettings.getDefaultCodecRegistry()))
                .autoEncryptionSettings(autoEncryptionSettingsBuilder.build())
                .build();
        autoEncryptingClient = MongoClients.create(clientSettings);

        ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().
                keyVaultMongoClientSettings(getMongoClientSettings()).
                kmsProviders(kmsProviders).
                keyVaultNamespace("keyvault.datakeys").build();
        clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    }

    @Test
    public void testCorpus() throws IOException, URISyntaxException {

        // Step 5: Iterate over corpus
        BsonDocument corpus = bsonDocumentFromPath("corpus.json");
        BsonDocument corpusCopied = new BsonDocument();
        for (String field : corpus.keySet()) {
            if (!corpus.get(field).isDocument()) {
                corpusCopied.append(field, corpus.get(field));
                continue;
            }

            BsonDocument fieldDocument = corpus.getDocument(field).clone();
            String kms = fieldDocument.getString("kms").getValue();
            String abbreviatedAlgorithName = fieldDocument.getString("algo").getValue();
            String method = fieldDocument.getString("method").getValue();
            String identifier = fieldDocument.getString("identifier").getValue();
            boolean allowed = fieldDocument.getBoolean("allowed").getValue();
            BsonValue value = fieldDocument.get("value");

            byte[] awsKeyId = Base64.getDecoder().decode("AWSAAAAAAAAAAAAAAAAAAA==");
            byte[] azureKeyId = Base64.getDecoder().decode("AZUREAAAAAAAAAAAAAAAAA==");
            byte[] gcpKeyId = Base64.getDecoder().decode("GCPAAAAAAAAAAAAAAAAAAA==");
            byte[] kmipKeyId = Base64.getDecoder().decode("KMIPAAAAAAAAAAAAAAAAAA==");
            byte[] localKeyId = Base64.getDecoder().decode("LOCALAAAAAAAAAAAAAAAAA==");

            if (method.equals("auto")) {
                corpusCopied.append(field, corpus.get(field));
                continue;
            }

            if (!method.equals("explicit")) {
                throw new UnsupportedOperationException("Unsupported method: " + method);
            }

            String fullAlgorithmName = "AEAD_AES_256_CBC_HMAC_SHA_512-";
            if (abbreviatedAlgorithName.equals("rand")) {
                fullAlgorithmName += "Random";
            } else if (abbreviatedAlgorithName.equals("det")) {
                fullAlgorithmName += "Deterministic";
            } else {
                throw new UnsupportedOperationException("Unsupported algorithm: " + abbreviatedAlgorithName);
            }

            EncryptOptions opts = new EncryptOptions(fullAlgorithmName);
            if (identifier.equals("id")) {
                switch (kms) {
                    case "aws":
                        opts.keyId(new BsonBinary(BsonBinarySubType.UUID_STANDARD, awsKeyId));
                        break;
                    case "azure":
                        opts.keyId(new BsonBinary(BsonBinarySubType.UUID_STANDARD, azureKeyId));
                        break;
                    case "gcp":
                        opts.keyId(new BsonBinary(BsonBinarySubType.UUID_STANDARD, gcpKeyId));
                        break;
                    case "kmip":
                        opts.keyId(new BsonBinary(BsonBinarySubType.UUID_STANDARD, kmipKeyId));
                        break;
                    case "local":
                        opts.keyId(new BsonBinary(BsonBinarySubType.UUID_STANDARD, localKeyId));
                        break;
                    default:
                        throw new UnsupportedOperationException("Unsupported provider: " + kms);
                }
            } else if (identifier.equals("altname")) {
                opts.keyAltName(kms);
            } else {
                throw new UnsupportedOperationException("Unsupported identifier: " + identifier);
            }

            try {
                BsonValue encryptedValue = clientEncryption.encrypt(value, opts);
                fieldDocument.put("value", encryptedValue);
                corpusCopied.append(field, fieldDocument);
            } catch (MongoException e) {
                if (allowed) {
                    throw e;
                }
                corpusCopied.append(field, fieldDocument);
            }
        }

        // Step 6: insert corpusCopied
        MongoCollection<BsonDocument> encryptedCollection = autoEncryptingClient.getDatabase("db")
                .getCollection("coll", BsonDocument.class);
        encryptedCollection.insertOne(corpusCopied);

        // Step 7: check the auto decrypted document
        BsonDocument corpusDecrypted = encryptedCollection.find(new BsonDocument()).first();
        assertEquals(corpus, corpusDecrypted);

        // Step 8: check the document with an unencrypted client
        MongoCollection<BsonDocument> coll = client.getDatabase("db").getCollection("coll", BsonDocument.class);
        BsonDocument corpusEncryptedActual = coll.find(new BsonDocument()).first();
        BsonDocument corpusEncryptedExpected = bsonDocumentFromPath("corpus-encrypted.json");

        for (String field : corpusEncryptedExpected.keySet()) {
            if (field.equals("_id") || field.equals("altname_aws") || field.equals("altname_local")) {
                continue;
            }

            boolean allowed = corpusEncryptedActual.getDocument(field).getBoolean("allowed").getValue();
            String algorithm = corpusEncryptedActual.getDocument(field).getString("algo").getValue();
            BsonValue actualValue = corpusEncryptedActual.getDocument(field).get("value");
            BsonValue expectedValue = corpusEncryptedExpected.getDocument(field).get("value");

            if (algorithm.equals("det")) {
                assertEquals(actualValue, expectedValue);
            } else if (algorithm.equals("rand")) {
                if (allowed) {
                    assertNotEquals(actualValue, expectedValue);
                }
            } else {
                throw new UnsupportedOperationException("Unsupported algorithm type: " + algorithm);
            }

            if (allowed) {
                BsonValue decrypted = clientEncryption.decrypt(actualValue.asBinary());
                assertEquals("Values should be equal for field " + field, clientEncryption.decrypt(expectedValue.asBinary()), decrypted);
            } else {
                assertEquals("Values should be equal for field " + field, expectedValue, actualValue);
            }
        }
    }

    private static BsonDocument bsonDocumentFromPath(final String path) throws IOException, URISyntaxException {
        return getTestDocument(new File(ClientSideEncryptionTest.class
                .getResource("/client-side-encryption-corpus/" + path).toURI()));
    }

    @Parameterized.Parameters(name = "useLocalSchema: {0}")
    public static Collection<Object[]> data() {
        return asList(new Object[]{true}, new Object[]{false});
    }

    @After
    public void after() {
        if (client != null) {
            try {
                client.close();
            } catch (Exception e) {
                // ignore
            }
        }

        if (autoEncryptingClient != null) {
            try {
                autoEncryptingClient.close();
            } catch (Exception e) {
                // ignore
            }
        }

        if (clientEncryption != null) {
            try {
                clientEncryption.close();
            } catch (Exception e) {
                // ignore
            }
        }
    }
}


text:
package com.bitzl.open.data.distance.heatmap.generate.model;

import com.bitzl.open.data.distance.heatmap.core.model.location.Coordinate;

import java.util.List;

public class Context {

    private Coordinate destination;

    private List<WeightedCoordinate> points;

    private String apiKey;

    public Coordinate getDestination() {
        return destination;
    }

    public void setDestination(Coordinate destination) {
        this.destination = destination;
    }

    public List<WeightedCoordinate> getPoints() {
        return points;
    }

    public void setPoints(List<WeightedCoordinate> points) {
        this.points = points;
    }

    public String getApiKey() {
        return apiKey;
    }

    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }
}

redpajama_set_name: RedPajamaGithub


text:
const test = require('tap').test
const Promise = require('bluebird')
const is = require('../src/is')
const enums = require('../src/enums')
const tError = require('./test-error')
const tOpts = require('./test-options')
const queueReanimateJob = require('../src/queue-reanimate-job')
const Queue = require('../src/queue')
const eventHandlers = require('./test-event-handlers')
const testName = 'queue-reanimate'

queueReanimateJobTests()
function queueReanimateJobTests () {
  return new Promise((resolve, reject) => {
    test(testName, (t) => {
      t.plan(49)

      // ---------- Test Setup ----------
      const q = new Queue(tOpts.cxn(), tOpts.default('queueReanimateJob'))

      // ---------- Event Handler Setup ----------
      let state = {
        testName,
        enabled: false,
        ready: 0,
        processing: 0,
        progress: 0,
        pausing: 0,
        paused: 0,
        resumed: 0,
        removed: 0,
        idle: 0,
        reset: 0,
        error: 0,
        reviewed: 0,
        detached: 0,
        stopping: 0,
        stopped: 0,
        dropped: 0,
        added: 1,
        waiting: 0,
        active: 0,
        completed: 0,
        cancelled: 1,
        failed: 0,
        terminated: 0,
        reanimated: 1,
        log: 0,
        updated: 1
      }

      // ---------- Test Setup ----------
      let job = q.createJob()
      let dateEnable
      let newDateEnable = new Date()
      newDateEnable.setDate(newDateEnable.getDate() + 5)

      return q.reset().then((resetResult) => {
        t.ok(is.integer(resetResult), 'Queue reset')
        return q.pause()
      }).then(() => {
        eventHandlers.add(t, q, state)

        // ---------- Reanimate Job Tests ----------
        t.comment('queue-reanimate-job: Reanimate Cancelled Job')
        return q.addJob(job)
      }).then((result) => {
        t.equal(result.length, 1, `Job saved successfully`)
        return q.getJob(job.id)
      }).then((result) => {
        dateEnable = result[0].dateEnable.toString()
        result[0].progress = 50
        result[0].retryCount = 2
        return result[0].update()
      }).then((result) => {
        return q.cancelJob(job.id)
      }).then((result) => {
        return q.getJob(job.id)
      }).then((result) => {
        t.equal(result[0].dateEnable.toString(), dateEnable, 'Job dateEnable is valid')
        t.equal(result[0].log.length, 3, 'Job log is valid')
        t.equal(result[0].progress, 50, 'Job progress valid')
        t.equal(result[0].queueId, q.id, 'Job queueId is valid')
        t.equal(result[0].retryCount, 2, 'Job retryCount valid')
        t.equal(result[0].status, enums.status.cancelled, 'Job is cancelled')
        return queueReanimateJob(q, job.id, newDateEnable)
      }).then((result) => {
        t.ok(is.uuid(result[0]), 'Reanimate jobs returns job ids')
        return q.getJob(job.id)
      }).then((result) => {
        t.equal(result[0].dateEnable.toString(), newDateEnable.toString(), 'Job reanimate dateEnable is valid')
        t.equal(result[0].log.length, 4, 'Job reanimate log is valid')
        t.equal(result[0].progress, 0, 'Job reanimate progress valid')
        t.equal(result[0].queueId, q.id, 'Job reanimate queueId is valid')
        t.equal(result[0].retryCount, 0, 'Job reanimate retryCount valid')
        t.equal(result[0].status, enums.status.waiting, 'Job reanimate is waiting')
        let lastLog = result[0].getLastLog()
        t.ok(is.date(lastLog.date), 'Job reanimate log date is valid')
        t.equal(lastLog.message, enums.message.jobReanimated, 'Job reanimate log message is valid')
        t.equal(lastLog.queueId, q.id, 'Job reanimate log queueId is valid')
        t.equal(lastLog.retryCount, 0, 'Job reanimate log retryCount is valid')
        t.equal(lastLog.status, enums.status.waiting, 'Job reanimate log status is valid')
        t.equal(lastLog.type, enums.log.information, 'Job reanimate log type is valid')

        // ---------- Event Summary ----------
        eventHandlers.remove(t, q, state)

        return q.reset()
      }).then((resetResult) => {
        t.ok(resetResult >= 0, 'Queue reset')
        q.stop()
        return resolve(t.end())
      }).catch(err => tError(err, module, t))
    })
  })
}


text:
package ru.job4j.xmlxsltjdbc;

import org.junit.Test;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;

/**
 * Class ru.job4j.xmlxsltjdbc.
 *
 * @author edzabarov
 * @since 16.07.2018
 */
public class StoreSQLTest {

    @Test
    public void whenStoreSQLGenerateDataThenInBDOnlyGeneratedData() {
        Properties config = new Properties();
        int n = 10;
        try {
            config.load(getClass().getResourceAsStream("/xmlxsltjdbc/properties/config.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        try (StoreSQL storeSQL = new StoreSQL(config)) {
            storeSQL.open();
            storeSQL.generate(n);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int[] expected = new int[n];
        try (Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost/java_a_from_z", "postgres",
                "password"))  {
            String sql = "SELECT Field FROM Entry ORDER BY Field";
            try (Statement st = connection.createStatement()) {
                try (ResultSet rs = st.executeQuery(sql)) {
                    for (int i = 0; i < expected.length && rs.next(); i++) {
                        expected[i] = rs.getInt("Field");
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            result[i] = i + 1;
        }
        assertThat(expected, is(result));
    }

}


text:
"use strict";

/* eslint-disable */

(function (global) {
  var apple_phone = /iPhone/i;
  var apple_ipod = /iPod/i;
  var apple_tablet = /iPad/i;
  var android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i;
  var android_tablet = /Android/i;
  var amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i;
  var amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i;
  var windows_phone = /Windows Phone/i;
  var windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i;
  var other_blackberry = /BlackBerry/i;
  var other_blackberry_10 = /BB10/i;
  var other_opera = /Opera Mini/i;
  var other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i;
  var other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i;
  var seven_inch = new RegExp("(?:" + "Nexus 7" + "|" + "BNTV250" + "|" + "Kindle Fire" + "|" + "Silk" + "|" + "GT-P1000" + ")", "i");

  var match = function match(regex, userAgent) {
    return regex.test(userAgent);
  };

  var IsMobileClass = function IsMobileClass(userAgent) {
    var ua = userAgent || navigator.userAgent;
    var tmp = ua.split("[FBAN");
    if (typeof tmp[1] !== "undefined") {
      ua = tmp[0];
    }

    tmp = ua.split("Twitter");
    if (typeof tmp[1] !== "undefined") {
      ua = tmp[0];
    }

    this.apple = {
      phone: match(apple_phone, ua),
      ipod: match(apple_ipod, ua),
      tablet: !match(apple_phone, ua) && match(apple_tablet, ua),
      device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua)
    };
    this.amazon = {
      phone: match(amazon_phone, ua),
      tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua),
      device: match(amazon_phone, ua) || match(amazon_tablet, ua)
    };
    this.android = {
      phone: match(amazon_phone, ua) || match(android_phone, ua),
      tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)),
      device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua)
    };
    this.windows = {
      phone: match(windows_phone, ua),
      tablet: match(windows_tablet, ua),
      device: match(windows_phone, ua) || match(windows_tablet, ua)
    };
    this.other = {
      blackberry: match(other_blackberry, ua),
      blackberry10: match(other_blackberry_10, ua),
      opera: match(other_opera, ua),
      firefox: match(other_firefox, ua),
      chrome: match(other_chrome, ua),
      device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua)
    };
    this.seven_inch = match(seven_inch, ua);
    this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch;

    this.phone = this.apple.phone || this.android.phone || this.windows.phone;

    this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet;

    if (typeof window === "undefined") {
      return this;
    }
  };

  var instantiate = function instantiate() {
    var IM = new IsMobileClass();
    IM.Class = IsMobileClass;
    return IM;
  };

  if (typeof module !== "undefined" && module.exports && typeof window === "undefined") {
    module.exports = IsMobileClass;
  } else if (typeof module !== "undefined" && module.exports && typeof window !== "undefined") {
    module.exports = instantiate();
  } else if (typeof define === "function" && define.amd) {
    define("isMobile", [], global.isMobile = instantiate());
  } else {
    global.isMobile = instantiate();
  }
})(undefined);


text:
NS_ASSUME_NONNULL_BEGIN

namespace autofill {
class CardUnmaskDelegate;
class CreditCard;
}  // namespace autofill

@interface CWVCreditCardVerifier ()

// Designated initializer.
// |prefs| The associated pref service. Must outlive this instance.
// |isOffTheRecord| The associated browser state's off the record state.
// |creditCard| The card that needs verification.
// |reason| Why the card needs verification.
// |delegate| Internal delegate used process verification events.
- (instancetype)initWithPrefs:(PrefService*)prefs
               isOffTheRecord:(BOOL)isOffTheRecord
                   creditCard:(const autofill::CreditCard&)creditCard
                       reason:(autofill::AutofillClient::UnmaskCardReason)reason
                     delegate:
                         (base::WeakPtr<autofill::CardUnmaskDelegate>)delegate
    NS_DESIGNATED_INITIALIZER;

// Used to pass unmask verification results to this class. Needed because
// verification results arrive from the CWVAutofillClientBridge protocol defiend
// in CWVAutofillController.
- (void)didReceiveUnmaskVerificationResult:
    (autofill::AutofillClient::PaymentsRpcResult)result;

// Use to notify CWVCreditCardVerifier that it needs to obtain risk data for
// credit card verification and to pass it back in |callback|.
- (void)loadRiskData:(base::OnceCallback<void(const std::string&)>)callback;

@end

NS_ASSUME_NONNULL_END

#endif  // IOS_WEB_VIEW_INTERNAL_AUTOFILL_CWV_CREDIT_CARD_VERIFIER_INTERNAL_H_


text:
namespace leveldb {

class FilterPolicy;

// A FilterBlockBuilder is used to construct all of the filters for a
// particular Table.  It generates a single string which is stored as
// a special block in the Table.
//
// The sequence of calls to FilterBlockBuilder must match the regexp:
//      (StartBlock AddKey*)* Finish
class FilterBlockBuilder {
 public:
  explicit FilterBlockBuilder(const FilterPolicy*);

  void StartBlock(uint64_t block_offset);
  void AddKey(const Slice& key);
  Slice Finish();

 private:
  void GenerateFilter();
  void PickFilterBase(size_t BlockOffset);

  const FilterPolicy* policy_;
  size_t filter_base_lg_;
  size_t filter_base_;
  size_t last_offset_;

  std::string keys_;              // Flattened key contents
  std::vector<size_t> start_;     // Starting index in keys_ of each key
  std::string result_;            // Filter data computed so far
  std::vector<Slice> tmp_keys_;   // policy_->CreateFilter() argument
  std::vector<uint32_t> filter_offsets_;

  // No copying allowed
  FilterBlockBuilder(const FilterBlockBuilder&);
  void operator=(const FilterBlockBuilder&);
};

class FilterBlockReader {
 public:
 // REQUIRES: "contents" and *policy must stay live while *this is live.
  FilterBlockReader(const FilterPolicy* policy, const Slice& contents);
  bool KeyMayMatch(uint64_t block_offset, const Slice& key);

 private:
  const FilterPolicy* policy_;
  const char* data_;    // Pointer to filter data (at block-start)
  const char* offset_;  // Pointer to beginning of offset array (at block-end)
  size_t num_;          // Number of entries in offset array
  size_t base_lg_;      // Encoding parameter (see kFilterBaseLg in .cc file)
};

}

#endif  // STORAGE_LEVELDB_TABLE_FILTER_BLOCK_H_


text:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';

interface Event {
  source: Subject<any>,
  observable: any
}

@Injectable()
export class EventBus {

  private eventMap: Map<string, Event> = new Map<string, Event>();
  constructor() {
  }

  emit(eventName: string, data?: any): boolean {
    if (this.eventMap.has(eventName)) {
      this.eventMap.get(eventName).source.next(data);
      return true;
    };
    return false;
  }

  on(eventName: string, handler: Function): Subscription {
    let eventObservable;
    if (!this.eventMap.has(eventName)) {
      let eventSource = new Subject<any>();
      eventObservable = eventSource.asObservable();
      this.eventMap.set(eventName, { source: eventSource, observable: eventObservable });
    } else {
      eventObservable = this.eventMap.get(eventName).observable;
    }
    return eventObservable.subscribe(handler);
  }
}


text:
package de.hpi.bpmn2_0.exceptions;

/**
 * @author Philipp Giese
 *
 */
public class MigrationHelperException extends Exception {

	/**
	 *
	 */
	private static final long serialVersionUID = -2779849528275571981L;

	public MigrationHelperException() {

	}

	public MigrationHelperException(String message) {
		super(message);
	}

	public MigrationHelperException(Throwable cause) {
		super(cause);
	}

	public MigrationHelperException(String message, Throwable cause) {
		super(message, cause);
	}

}


text:
package org.wso2.carbon.identity.mgt;

import java.util.ArrayList;
import java.util.List;

/**
 * This class represents AuthenticationContext which holds the information related to the authentication failed user.
 */
public class FailedAuthenticationContext extends AuthenticationContext {

    List<User> failedUsers = new ArrayList<>();

    public FailedAuthenticationContext() {
        super(null, false);
    }

    public FailedAuthenticationContext(List<User> failedUsers) {
        super(null, false);
        this.failedUsers = failedUsers;
    }

    public void addFailedUserToList(User failedUser) {
        failedUsers.add(failedUser);
    }

    public List<User> getFailedUsers() {
        return failedUsers;
    }
}


text:
<!DOCTYPE html>

<title>How do I enable student peer review for an assignment?</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="sakai.assignment" name="description">
<meta content="peer review, peer assessment, peer evaluation" name="search">
<link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="../css/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">

How do I download a copy of the CSV feedback file?

Go to PostEm.

Select the PostEm tool from the Tool Menu of your site.

Note: The PostEm tool is sometimes named Feedback.

Find the CSV feedback item and click the download link.

Find the CSV feedback item and click the download link to begin downloading.


text:
<?php

//src/Catalog/CatalogBundle/Entity/Catalog.php

namespace Catalog\CatalogBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Table(name="catalog_project")
 * @ORM\Entity(repositoryClass="Catalog\CatalogBundle\Entity\Repository\CatalogProjectRepository")
 * @UniqueEntity(fields="{project, catalog}", message="Sorry, this relations is already in use.", groups={"CatalogProject"})
 */
class CatalogProject {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
    * @ORM\Column(type="integer")
    */
    protected $project_id;
    /**
     * @ORM\ManyToOne(targetEntity="Catalog\ProjectBundle\Entity\Project", inversedBy="join_catalog")
     * @ORM\JoinColumn(name="project_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $project;

    /**
    * @ORM\Column(type="integer")
    */
   protected $catalog_id;
    /**
     * @ORM\ManyToOne(targetEntity="Catalog", inversedBy="join_catalog")
     * @ORM\JoinColumn(name="catalog_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $catalog;

    public function __construct($catalog, $project)
    {
        $this->catalog = $catalog;
        $this->project = $project;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set project_id
     *
     * @param integer $projectId
     * @return CatalogProject
     */
    public function setProjectId($projectId)
    {
        $this->project_id = $projectId;

        return $this;
    }

    /**
     * Get project_id
     *
     * @return integer
     */
    public function getProjectId()
    {
        return $this->project_id;
    }

    /**
     * Set catalog_id
     *
     * @param integer $catalogId
     * @return CatalogProject
     */
    public function setCatalogId($catalogId)
    {
        $this->catalog_id = $catalogId;

        return $this;
    }

    /**
     * Get catalog_id
     *
     * @return integer
     */
    public function getCatalogId()
    {
        return $this->catalog_id;
    }

    /**
     * Set project
     *
     * @param \Catalog\ProjectBundle\Entity\Project $project
     * @return CatalogProject
     */
    public function setProject(\Catalog\ProjectBundle\Entity\Project $project = null)
    {
        $this->project = $project;

        return $this;
    }

    /**
     * Get project
     *
     * @return \Catalog\ProjectBundle\Entity\Project
     */
    public function getProject()
    {
        return $this->project;
    }

    /**
     * Set catalog
     *
     * @param \Catalog\CatalogBundle\Entity\Catalog $catalog
     * @return CatalogProject
     */
    public function setCatalog(\Catalog\CatalogBundle\Entity\Catalog $catalog = null)
    {
        $this->catalog = $catalog;

        return $this;
    }

    /**
     * Get catalog
     *
     * @return \Catalog\CatalogBundle\Entity\Catalog
     */
    public function getCatalog()
    {
        return $this->catalog;
    }
}


text:
package ch.epfl.scala.index
package server

// https://github.com/btomala/akka-http-twirl

import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaTypes._
import akka.http.scaladsl.model.MediaType
import play.twirl.api.{Xml, Txt, Html}

object TwirlSupport extends TwirlSupport

trait TwirlSupport {

  /** Serialize Twirl `Html` to `text/html`. */
  implicit val twirlHtmlMarshaller = twirlMarshaller[Html](`text/html`)

  /** Serialize Twirl `Txt` to `text/plain`. */
  implicit val twirlTxtMarshaller = twirlMarshaller[Txt](`text/plain`)

  /** Serialize Twirl `Xml` to `text/xml`. */
  implicit val twirlXmlMarshaller = twirlMarshaller[Xml](`text/xml`)

  /** Serialize Twirl formats to `String`. */
  protected def twirlMarshaller[A <: AnyRef: Manifest](
      contentType: MediaType): ToEntityMarshaller[A] =
    Marshaller.StringMarshaller.wrap(contentType)(_.toString)

}


text:
import sys
import logging
import logging.config
from slackbot import settings
from slackbot.bot import Bot

def main():
    kw = {
        'format': '[%(asctime)s] %(message)s',
        'datefmt': '%m/%d/%Y %H:%M:%S',
        'level': logging.DEBUG if settings.DEBUG else logging.INFO,
        'stream': sys.stdout,
    }
    logging.basicConfig(**kw)
    logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARNING)
    bot = Bot()
    bot.run()

if __name__ == '__main__':
    main()


text:
var Dashboard = Dashboard || {};
Dashboard.StackChart = (function () {
  var pub = {};

  var plainDateFormatter = d3.time.format('%b %d');
  var timeFormatter = d3.time.format('%H:%M');
  var dateTimeFormatter = d3.time.format('%b %d %H:%M');

  function getClickRange(data) {
    var max = d3.max(data, function (site) {
      return d3.max(site.values, function (d) {
        return d.x;
      });
    });
    var min = d3.min(data, function (site) {
      return d3.min(site.values, function (d) {
        return d.x;
      });
    });

    return [min, max];
  }

  function compileLayersUsingLookback(options) {
    var layers = [];
    var sites = d3.keys(options.data[options.data.length - 1]);
    var lookback = Dashboard.Service.option(options.id, 'lookback');

    $.each(sites, function (i, siteName) {
      if (siteName === 'timestamp') {
        return;
      }

      var layer = {
        name: siteName,
        values: []
      };

      $.each(options.data, function (i, snapshot) {
        if (i < lookback) {
          return;
        }
        var cell = {
          x: snapshot.timestamp,
          y: (options.data[i][siteName] || {})[options.key] - (options.data[i - lookback][siteName] || {})[options.key] || 0
        };
        layer.values.push(cell);
      });

      layers.push(layer);
    });

    return layers;
  }

  function compileLayers(options) {
    var layers = [];
    var sites = d3.keys(options.data[options.data.length - 1]);

    $.each(sites, function (i, siteName) {
      if (siteName === 'timestamp') {
        return;
      }

      var layer = {
        name: siteName,
        values: []
      };

      $.each(options.data, function (i, snapshot) {
        var cell = {
          x: snapshot.timestamp,
          y: (snapshot[siteName] || {})[options.key] || 0
        };
        layer.values.push(cell);
      });

      layers.push(layer);
    });

    return layers;
  }

  pub.getTotals = function (data, slice) {
    var total = 0;
    $.each(data, function (i, site) {
      $.each(site, function (i, values) {
        if (i !== 'values') {
          return;
        }
        total += values[slice || values.length - 1].y;
      });
    });

    return total;
  };

  pub.onTearDown = function () {
    $(window).unbind('mousemove.stackChart');
  };

  pub.filterData = function (options, data) {
    var query = Dashboard.Service.option(options.id, 'filter');
    var filterKey = Dashboard.Service.options(options.id, 'filter').key;
    if (query && filterKey) {
      data = data.filter(function (obj) {
        var match = false;
        $.each(query.toLowerCase().split(' '), function (i, query) {
          query = Dashboard.Utils.trim(query);
          if (query && !match) {
            match = Dashboard.Utils.includes(obj[filterKey].toLowerCase(), query);
          }
        });

        return match;
      });
    }

    return data;
  };

  pub.render = function (options) {
    var data = options.lookback ? compileLayersUsingLookback(options) : compileLayers(options);
    var chartHeight = $(window).height() - 35 - $('#chart').offset().top;
    var domain = getClickRange(data);
    var range = [0, $('#chart').width() - 215];
    var x = d3.time.scale().domain(domain).range(range);
    var palette = Dashboard.Utils.getPalette();
    var lookback = Dashboard.Service.option(options.id, 'lookback') || 0;
    var offsetType = Dashboard.Service.option(options.id, 'offsetType') || 'zero';
    var stack = d3.layout.stack()
      .offset(offsetType) // zero, expand, wiggle, silhouette
      .values(function (d) { return d.values; });

    if (options.lookback) {
      data.sort(function (a, b) {
        return a.values[lookback].y - b.values[lookback].y;
      });
    } else {
      data.sort(function (a, b) {
        return a.values[a.values.length - 1].y - b.values[b.values.length - 1].y;
      });
    }

    data = pub.filterData(options, data);
    var layers = stack(data);

    var maxY = d3.max(layers, function (layer) {
      return d3.max(layer.values, function (d) {
        return d.y0 + d.y;
      });
    });

    var scaleType = Dashboard.Service.option(options.id, 'scaleType') || 'linear';
    var y = d3.scale[scaleType]()
      .domain([maxY, 0])
      .range([0, chartHeight]);

    var area = d3.svg.area()
      .interpolate('basis') // step, basis
      .x(function (d) { return x(d.x); })
      .y0(function (d) { return y(d.y0); })
      .y1(function (d) { return y(d.y0 + d.y); });

    $('#chart').html('

');
    $('#stackChart').height(chartHeight);

    var container = d3.select('#stackChart');
    var svg = container.append('svg');
    var autoColor = d3.scale.category10();

    svg.selectAll('path')
      .data(layers)
      .enter().append('path')
      .attr('d', function (d) {
        return area(d.values);
      })
      .style('fill', function (d) {
        return palette[d.name] || autoColor(d.name);
      })
      .style('stroke-width', function (d) {
        return '1px';
      })
      .style('stroke', function (d) {
        return palette[d.name] || autoColor(d.name);
      });

    var y2 = d3.scale[scaleType]()
      .domain([maxY, 0])
      .range([-6, chartHeight]);

    var mouseoverScale = d3.scale.linear()
      .domain([10, $(window).width() - 222])
      .range([0, data[0].values.length - 1]);

    $('

').appendTo('#stackChart');

    function renderYAxis(column) {
      $('#stackChart div.y_axis').remove();
      var yAxisRight = container.append('div')
        .attr('class', 'y_axis');

      var lastTop = chartHeight;
      yAxisRight.selectAll('.tick')
        .data(data)
        .enter().append('div')
        .attr('class', 'tick')
        .style('top', function (d) {
          var top = d.values[column || d.values.length - 1].y0 + (d.values[column || d.values.length - 1].y / 2);
          top = Math.min(y2(top), lastTop - 14);
          lastTop = top;
          return top + 'px';
        })
        .html(function (d) {
          var color = palette[d.name] || autoColor(d.name);
          var format = options.amountFormat || '0.0a';
          var amount = offsetType === 'expand' ?
            numeral(d.values[column || d.values.length - 1].y).format('0.0%') :
            numeral(d.values[column || d.values.length - 1].y).format(format);
          return '' + d.name.toLowerCase().replace(/_/g, ' ') +
            '' + amount + '';
        });

      if (options.showTotal) {
        $('#stackChartTotal').remove();
        $('#chart').append('

');
        var totalRevenue = '100%';
        if (offsetType === 'zero') {
          totalRevenue = Dashboard.StackChart.getTotals(data, column);
          totalRevenue = numeral(totalRevenue).format(options.totalFormat || '$0.0a');
        }
        var totalTimestamp = dateTimeFormatter(new Date(data[0].values[column || data[0].values.length - 1].x));

        var html = 'total ' + totalRevenue + '' +
          '
as of ' + totalTimestamp + '
';
        $('#stackChartTotal').html(html);
      }

      var currentYAxis = Math.round(x(data[0].values[column || data[0].values.length - 1].x));
      $('.current_y_axis').css({ left: currentYAxis });

      if (column) {
        $('#stackChart div.y_axis').css({ left: currentYAxis + 5 });
      }
    }

    renderYAxis();

    $(window).unbind('mousemove.stackChart').bind('mousemove.stackChart', function (e) {
      if (e.pageX < 10 || e.pageX > $(window).width() - 222 || e.pageY < 55) {
        return renderYAxis();
      }
      renderYAxis(Math.round(mouseoverScale(e.pageX)));
    });

    var xAxis = container.append('div')
      .attr('class', 'x_axis');

    xAxis.selectAll('.tick')
      .data(function () {
        return x.ticks(15);
      })
      .enter().append('div')
      .attr('class', 'tick')
      .style('height', chartHeight + 'px')
      .style('left', function (d) {
        return Math.round(x(d)) + 'px';
      })
      .html(function (d) {
        var t = timeFormatter(d);
        var spanClass = '';
        if (t === '00:00') {
          t = plainDateFormatter(d);
          spanClass = 'bright';
        }
        return '' + t + '';
      });

    if (options.afterRender) {
      options.afterRender(data, options);
    }
  };

  return pub;
}());


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/oval_shape_pressed" android:state_selected="true"/>
    <item android:drawable="@drawable/oval_shape_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/oval_shape"/>

</selector>


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Deleting model 'FileRevision'
        db.delete_table('projects_filerevision')

        # Deleting model 'File'
        db.delete_table('projects_file')

        # Adding field 'Project.privacy_level'
        db.add_column('projects_project', 'privacy_level',
                      self.gf('django.db.models.fields.CharField')(default='public', max_length=20),
                      keep_default=False)

    def backwards(self, orm):
        # Adding model 'FileRevision'
        db.create_table('projects_filerevision', (
            ('comment', self.gf('django.db.models.fields.TextField')(blank=True)),
            ('revision_number', self.gf('django.db.models.fields.IntegerField')()),
            ('file', self.gf('django.db.models.fields.related.ForeignKey')(related_name='revisions', to=orm['projects.File'])),
            ('created_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('diff', self.gf('django.db.models.fields.TextField')(blank=True)),
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('is_reverted', self.gf('django.db.models.fields.BooleanField')(default=False)),
        ))
        db.send_create_signal('projects', ['FileRevision'])

        # Adding model 'File'
        db.create_table('projects_file', (
            ('content', self.gf('django.db.models.fields.TextField')()),
            ('project', self.gf('django.db.models.fields.related.ForeignKey')(related_name='files', to=orm['projects.Project'])),
            ('slug', self.gf('django.db.models.fields.SlugField')(max_length=50)),
            ('status', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=1)),
            ('denormalized_path', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('parent', self.gf('django.db.models.fields.related.ForeignKey')(related_name='children', null=True, to=orm['projects.File'], blank=True)),
            ('ordering', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=1)),
            ('heading', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
        ))
        db.send_create_signal('projects', ['File'])

        # Deleting field 'Project.privacy_level'
        db.delete_column('projects_project', 'privacy_level')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 10, 13, 22, 28, 56, 789520)'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 10, 13, 22, 28, 56, 789253)'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'projects.importedfile': {
            'Meta': {'object_name': 'ImportedFile'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'md5': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'project': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'imported_files'", 'to': "orm['projects.Project']"}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'})
        },
        'projects.project': {
            'Meta': {'ordering': "('slug',)", 'object_name': 'Project'},
            'analytics_code': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
            'conf_py_file': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}),
            'copyright': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'crate_url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'default_branch': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'default_version': ('django.db.models.fields.CharField', [], {'default': "'latest'", 'max_length': '255'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'django_packages_url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'documentation_type': ('django.db.models.fields.CharField', [], {'default': "'sphinx'", 'max_length': '20'}),
            'featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'privacy_level': ('django.db.models.fields.CharField', [], {'default': "'public'", 'max_length': '20'}),
            'project_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
            'pub_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'related_projects': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['projects.Project']", 'null': 'True', 'through': "orm['projects.ProjectRelationship']", 'blank': 'True'}),
            'repo': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'repo_type': ('django.db.models.fields.CharField', [], {'default': "'git'", 'max_length': '10'}),
            'requirements_file': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'skip': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '255'}),
            'suffix': ('django.db.models.fields.CharField', [], {'default': "'.rst'", 'max_length': '10'}),
            'theme': ('django.db.models.fields.CharField', [], {'default': "'default'", 'max_length': '20'}),
            'use_system_packages': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'use_virtualenv': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'users': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'projects'", 'symmetrical': 'False', 'to': "orm['auth.User']"}),
            'version': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'})
        },
        'projects.projectrelationship': {
            'Meta': {'object_name': 'ProjectRelationship'},
            'child': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'superprojects'", 'to': "orm['projects.Project']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'subprojects'", 'to': "orm['projects.Project']"})
        },
        'taggit.tag': {
            'Meta': {'object_name': 'Tag'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'})
        },
        'taggit.taggeditem': {
            'Meta': {'object_name': 'TaggedItem'},
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
            'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"})
        }
    }

    complete_apps = ['projects']


text:
'use strict';

/* Controllers */

angular.module('icixUICCApp.controllers', []).
  controller('ListCtrl', ['$scope', '$http', function($scope, $http) {
    var headers,
      records,
      combined_data,
      map;
    var is_transposed = false;

    $http.get('data/data.json').success(function(in_data) {
      records = in_data.records;
      headers = [in_data.headers];
      combined_data = headers.concat(records);
      $scope.data = combined_data;
    });

    $scope.is_transposed = is_transposed;

    $scope.transpose = function() {
      if (is_transposed)
        is_transposed = false;
      else
        is_transposed = true;

      $scope.is_transposed = is_transposed;

      $scope.$broadcast('dotabletranspose');
    }

    $scope.get_map = function(person, index) {
      if (index != 0 ) {

        $scope.selected = index;
        jQuery(".entry").removeClass("selected");
        jQuery(".no"+index).addClass("selected");
        var address_string = jQuery.trim(person.StreetNo + ' ' + person.StreetAddress + ', ' + person.State).split(' ').join('+');
        jQuery("#map").width(jQuery("table").width());
        $scope.$broadcast('dotabletranspose');

        $http.get('http://maps.googleapis.com/maps/api/geocode/json?address='+address_string+'&sensor=false').success(function(in_data) {

          var loc = new google.maps.LatLng(in_data.results[0].geometry.location.lat, in_data.results[0].geometry.location.lng);
          var map_options = {
            center: loc,
            zoom: 12
          };

          map_options.center = loc;
          map = new google.maps.Map(jQuery("#map")[0], map_options);
          var marker = new google.maps.Marker({
              position: loc,
              map: map,
              title:jQuery.trim(person.FirstName + ' ' + person.LastName)
          });

          jQuery(window).resize(function(){
            jQuery("#map").width(jQuery("table").width());
            $scope.$broadcast('dotabletranspose');
          });

        });
      }
    }
  }]);


text:
package hu.akarnokd.rxjava2.internal.operators.nbp;

import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;

import java.util.Iterator;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

import org.junit.*;
import org.mockito.InOrder;

import hu.akarnokd.rxjava2.*;
import hu.akarnokd.rxjava2.NbpObservable.NbpSubscriber;
import hu.akarnokd.rxjava2.exceptions.TestException;
import hu.akarnokd.rxjava2.functions.*;
import hu.akarnokd.rxjava2.schedulers.*;
import hu.akarnokd.rxjava2.subscribers.nbp.NbpTestSubscriber;

public class NbpOperatorObserveOnTest {

    /**
     * This is testing a no-op path since it uses Schedulers.immediate() which will not do scheduling.
     */
    @SuppressWarnings("deprecation")
    @Test
    @Ignore("immediate scheduler not supported")
    public void testObserveOn() {
        NbpSubscriber<Integer> NbpObserver = TestHelper.mockNbpSubscriber();
        NbpObservable.just(1, 2, 3).observeOn(Schedulers.immediate()).subscribe(NbpObserver);

        verify(NbpObserver, times(1)).onNext(1);
        verify(NbpObserver, times(1)).onNext(2);
        verify(NbpObserver, times(1)).onNext(3);
        verify(NbpObserver, times(1)).onComplete();
    }

    @Test
    public void testOrdering() throws InterruptedException {
//        NbpObservable<String> obs = NbpObservable.just("one", null, "two", "three", "four");
        // FIXME null values not allowed
        NbpObservable<String> obs = NbpObservable.just("one", "null", "two", "three", "four");

        NbpSubscriber<String> NbpObserver = TestHelper.mockNbpSubscriber();

        InOrder inOrder = inOrder(NbpObserver);
        NbpTestSubscriber<String> ts = new NbpTestSubscriber<String>(NbpObserver);

        obs.observeOn(Schedulers.computation()).subscribe(ts);

        ts.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);
        if (ts.errors().size() > 0) {
            for (Throwable t : ts.errors()) {
                t.printStackTrace();
            }
            fail("failed with exception");
        }

        inOrder.verify(NbpObserver, times(1)).onNext("one");
        inOrder.verify(NbpObserver, times(1)).onNext("null");
        inOrder.verify(NbpObserver, times(1)).onNext("two");
        inOrder.verify(NbpObserver, times(1)).onNext("three");
        inOrder.verify(NbpObserver, times(1)).onNext("four");
        inOrder.verify(NbpObserver, times(1)).onComplete();
        inOrder.verifyNoMoreInteractions();
    }

    @Test
    public void testThreadName() throws InterruptedException {
        System.out.println("Main Thread: " + Thread.currentThread().getName());
        // FIXME null values not allowed
//        NbpObservable<String> obs = NbpObservable.just("one", null, "two", "three", "four");
        NbpObservable<String> obs = NbpObservable.just("one", "null", "two", "three", "four");

        NbpSubscriber<String> NbpObserver = TestHelper.mockNbpSubscriber();
        final String parentThreadName = Thread.currentThread().getName();

        final CountDownLatch completedLatch = new CountDownLatch(1);

        // assert subscribe is on main thread
        obs = obs.doOnNext(new Consumer<String>() {

            @Override
            public void accept(String s) {
                String threadName = Thread.currentThread().getName();
                System.out.println("Source ThreadName: " + threadName + "  Expected => " + parentThreadName);
                assertEquals(parentThreadName, threadName);
            }

        });

        // assert observe is on new thread
        obs.observeOn(Schedulers.newThread()).doOnNext(new Consumer<String>() {

            @Override
            public void accept(String t1) {
                String threadName = Thread.currentThread().getName();
                boolean correctThreadName = threadName.startsWith("RxNewThreadScheduler");
                System.out.println("ObserveOn ThreadName: " + threadName + "  Correct => " + correctThreadName);
                assertTrue(correctThreadName);
            }

        }).finallyDo(new Runnable() {

            @Override
            public void run() {
                completedLatch.countDown();

            }
        }).subscribe(NbpObserver);

        if (!completedLatch.await(1000, TimeUnit.MILLISECONDS)) {
            fail("timed out waiting");
        }

        verify(NbpObserver, never()).onError(any(Throwable.class));
        verify(NbpObserver, times(5)).onNext(any(String.class));
        verify(NbpObserver, times(1)).onComplete();
    }

    @SuppressWarnings("deprecation")
    @Test
    @Ignore("immediate scheduler not supported")
    public void observeOnTheSameSchedulerTwice() {
        Scheduler scheduler = Schedulers.immediate();

        NbpObservable<Integer> o = NbpObservable.just(1, 2, 3);
        NbpObservable<Integer> o2 = o.observeOn(scheduler);

        @SuppressWarnings("unchecked")
        NbpObserver<Object> observer1 = mock(NbpObserver.class);
        @SuppressWarnings("unchecked")
        NbpObserver<Object> observer2 = mock(NbpObserver.class);

        InOrder inOrder1 = inOrder(observer1);
        InOrder inOrder2 = inOrder(observer2);

        o2.subscribe(observer1);
        o2.subscribe(observer2);

        inOrder1.verify(observer1, times(1)).onNext(1);
        inOrder1.verify(observer1, times(1)).onNext(2);
        inOrder1.verify(observer1, times(1)).onNext(3);
        inOrder1.verify(observer1, times(1)).onComplete();
        verify(observer1, never()).onError(any(Throwable.class));
        inOrder1.verifyNoMoreInteractions();

        inOrder2.verify(observer2, times(1)).onNext(1);
        inOrder2.verify(observer2, times(1)).onNext(2);
        inOrder2.verify(observer2, times(1)).onNext(3);
        inOrder2.verify(observer2, times(1)).onComplete();
        verify(observer2, never()).onError(any(Throwable.class));
        inOrder2.verifyNoMoreInteractions();
    }

    @Test
    public void observeSameOnMultipleSchedulers() {
        TestScheduler scheduler1 = new TestScheduler();
        TestScheduler scheduler2 = new TestScheduler();

        NbpObservable<Integer> o = NbpObservable.just(1, 2, 3);
        NbpObservable<Integer> o1 = o.observeOn(scheduler1);
        NbpObservable<Integer> o2 = o.observeOn(scheduler2);

        NbpSubscriber<Object> observer1 = TestHelper.mockNbpSubscriber();
        NbpSubscriber<Object> observer2 = TestHelper.mockNbpSubscriber();

        InOrder inOrder1 = inOrder(observer1);
        InOrder inOrder2 = inOrder(observer2);

        o1.subscribe(observer1);
        o2.subscribe(observer2);

        scheduler1.advanceTimeBy(1, TimeUnit.SECONDS);
        scheduler2.advanceTimeBy(1, TimeUnit.SECONDS);

        inOrder1.verify(observer1, times(1)).onNext(1);
        inOrder1.verify(observer1, times(1)).onNext(2);
        inOrder1.verify(observer1, times(1)).onNext(3);
        inOrder1.verify(observer1, times(1)).onComplete();
        verify(observer1, never()).onError(any(Throwable.class));
        inOrder1.verifyNoMoreInteractions();

        inOrder2.verify(observer2, times(1)).onNext(1);
        inOrder2.verify(observer2, times(1)).onNext(2);
        inOrder2.verify(observer2, times(1)).onNext(3);
        inOrder2.verify(observer2, times(1)).onComplete();
        verify(observer2, never()).onError(any(Throwable.class));
        inOrder2.verifyNoMoreInteractions();
    }

    /**
     * Confirm that running on a NewThreadScheduler uses the same thread for the entire stream
     */
    @Test
    public void testObserveOnWithNewThreadScheduler() {
        final AtomicInteger count = new AtomicInteger();
        final int _multiple = 99;

        NbpObservable.range(1, 100000).map(new Function<Integer, Integer>() {

            @Override
            public Integer apply(Integer t1) {
                return t1 * _multiple;
            }

        }).observeOn(Schedulers.newThread())
        .toBlocking().forEach(new Consumer<Integer>() {

            @Override
            public void accept(Integer t1) {
                assertEquals(count.incrementAndGet() * _multiple, t1.intValue());
                // FIXME toBlocking methods run on the current thread
                String name = Thread.currentThread().getName();
                assertFalse("Wrong thread name: " + name, name.startsWith("Rx"));
            }

        });

    }

    /**
     * Confirm that running on a ThreadPoolScheduler allows multiple threads but is still ordered.
     */
    @Test
    public void testObserveOnWithThreadPoolScheduler() {
        final AtomicInteger count = new AtomicInteger();
        final int _multiple = 99;

        NbpObservable.range(1, 100000).map(new Function<Integer, Integer>() {

            @Override
            public Integer apply(Integer t1) {
                return t1 * _multiple;
            }

        }).observeOn(Schedulers.computation())
        .toBlocking().forEach(new Consumer<Integer>() {

            @Override
            public void accept(Integer t1) {
                assertEquals(count.incrementAndGet() * _multiple, t1.intValue());
                // FIXME toBlocking methods run on the caller's thread
                String name = Thread.currentThread().getName();
                assertFalse("Wrong thread name: " + name, name.startsWith("Rx"));
            }

        });
    }

    /**
     * Attempts to confirm that when pauses exist between events, the ScheduledObserver
     * does not lose or reorder any events since the scheduler will not block, but will
     * be re-scheduled when it receives new events after each pause.
     *
     *
     * This is non-deterministic in proving success, but if it ever fails (non-deterministically)
     * it is a sign of potential issues as thread-races and scheduling should not affect output.
     */
    @Test
    public void testObserveOnOrderingConcurrency() {
        final AtomicInteger count = new AtomicInteger();
        final int _multiple = 99;

        NbpObservable.range(1, 10000).map(new Function<Integer, Integer>() {

            @Override
            public Integer apply(Integer t1) {
                if (randomIntFrom0to100() > 98) {
                    try {
                        Thread.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return t1 * _multiple;
            }

        }).observeOn(Schedulers.computation())
        .toBlocking().forEach(new Consumer<Integer>() {

            @Override
            public void accept(Integer t1) {
                assertEquals(count.incrementAndGet() * _multiple, t1.intValue());
//                assertTrue(name.startsWith("RxComputationThreadPool"));
                // FIXME toBlocking now runs its methods on the caller thread
                String name = Thread.currentThread().getName();
                assertFalse("Wrong thread name: " + name, name.startsWith("Rx"));
            }

        });
    }

    @Test
    public void testNonBlockingOuterWhileBlockingOnNext() throws InterruptedException {

        final CountDownLatch completedLatch = new CountDownLatch(1);
        final CountDownLatch nextLatch = new CountDownLatch(1);
        final AtomicLong completeTime = new AtomicLong();
        // use subscribeOn to make async, observeOn to move
        NbpObservable.range(1, 2).subscribeOn(Schedulers.newThread()).observeOn(Schedulers.newThread()).subscribe(new NbpObserver<Integer>() {

            @Override
            public void onComplete() {
                System.out.println("onCompleted");
                completeTime.set(System.nanoTime());
                completedLatch.countDown();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Integer t) {
                // don't let this thing finish yet
                try {
                    if (!nextLatch.await(1000, TimeUnit.MILLISECONDS)) {
                        throw new RuntimeException("it shouldn't have timed out");
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException("it shouldn't have failed");
                }
            }

        });

        long afterSubscribeTime = System.nanoTime();
        System.out.println("After subscribe: " + completedLatch.getCount());
        assertEquals(1, completedLatch.getCount());
        nextLatch.countDown();
        completedLatch.await(1000, TimeUnit.MILLISECONDS);
        assertTrue(completeTime.get() > afterSubscribeTime);
        System.out.println("onComplete nanos after subscribe: " + (completeTime.get() - afterSubscribeTime));
    }

    private static int randomIntFrom0to100() {
        // XORShift instead of Math.random http://javamex.com/tutorials/random_numbers/xorshift.shtml
        long x = System.nanoTime();
        x ^= (x << 21);
        x ^= (x >>> 35);
        x ^= (x << 4);
        return Math.abs((int) x % 100);
    }

    @Test
    public void testDelayedErrorDeliveryWhenSafeSubscriberUnsubscribes() {
        TestScheduler testScheduler = new TestScheduler();

        NbpObservable<Integer> source = NbpObservable.concat(NbpObservable.<Integer> error(new TestException()), NbpObservable.just(1));

        @SuppressWarnings("unchecked")
        NbpObserver<Integer> o = mock(NbpObserver.class);
        InOrder inOrder = inOrder(o);

        source.observeOn(testScheduler).subscribe(o);

        inOrder.verify(o, never()).onError(any(TestException.class));

        testScheduler.advanceTimeBy(1, TimeUnit.SECONDS);

        inOrder.verify(o).onError(any(TestException.class));
        inOrder.verify(o, never()).onNext(anyInt());
        inOrder.verify(o, never()).onComplete();
    }

    @Test
    public void testAfterUnsubscribeCalledThenObserverOnNextNeverCalled() {
        final TestScheduler testScheduler = new TestScheduler();

        final NbpSubscriber<Integer> NbpObserver = TestHelper.mockNbpSubscriber();
        NbpTestSubscriber<Integer> ts = new NbpTestSubscriber<Integer>(NbpObserver);

        NbpObservable.just(1, 2, 3)
                .observeOn(testScheduler)
                .subscribe(ts);

        ts.dispose();
        testScheduler.advanceTimeBy(1, TimeUnit.SECONDS);

        final InOrder inOrder = inOrder(NbpObserver);

        inOrder.verify(NbpObserver, never()).onNext(anyInt());
        inOrder.verify(NbpObserver, never()).onError(any(Exception.class));
        inOrder.verify(NbpObserver, never()).onComplete();
    }

    @Test
    public void testBackpressureWithTakeBefore() {
        final AtomicInteger generated = new AtomicInteger();
        NbpObservable<Integer> o = NbpObservable.fromIterable(new Iterable<Integer>() {
            @Override
            public Iterator<Integer> iterator() {
                return new Iterator<Integer>() {

                    @Override
                    public void remove() {
                    }

                    @Override
                    public Integer next() {
                        return generated.getAndIncrement();
                    }

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

        NbpTestSubscriber<Integer> ts = new NbpTestSubscriber<Integer>();
        o
                .take(7)
                .observeOn(Schedulers.newThread())
                .subscribe(ts);

        ts.awaitTerminalEvent();
        ts.assertValues(0, 1, 2, 3, 4, 5, 6);
        assertEquals(7, generated.get());
    }

    @Test
    public void testAsyncChild() {
        NbpTestSubscriber<Integer> ts = new NbpTestSubscriber<Integer>();
        NbpObservable.range(0, 100000).observeOn(Schedulers.newThread()).observeOn(Schedulers.newThread()).subscribe(ts);
        ts.awaitTerminalEvent();
        ts.assertNoErrors();
    }
}


text:
package com.izettle.tlv;

import static java.util.Objects.requireNonNull;

import com.izettle.java.ArrayUtils;
import com.izettle.java.Hex;
import java.util.Arrays;

public class TLV {

    private final byte[] tag;
    private final byte[] length;
    private final byte[] value;

    public TLV(byte[] tag, byte[] length, byte[] value) {
        this.tag = requireNonNull(tag, "Tag cannot be null");
        this.length = requireNonNull(length, "Length cannot be null");
        this.value = requireNonNull(value, "Value cannot be null");
    }

    public byte[] getTag() {
        return Arrays.copyOf(tag, tag.length);
    }

    public byte[] getLength() {
        return Arrays.copyOf(length, length.length);
    }

    public byte[] getValue() {
        return Arrays.copyOf(value, value.length);
    }

    public byte[] toBytes() {
        return ArrayUtils.concat(tag, length, value);
    }

    @Override
    public String toString() {
        return String.format(
            "[T:%s L:%s V:%s]",
            Hex.toHexString(tag),
            Hex.toHexString(length),
            Hex.toHexString(value));
    }
}


text:
'use strict';

class SocketManager {

	onConnect(socket) {
		console.log('Socket connected');
	}

	onDisconnect(socket) {

	}

	onReceive(socket, message) {
		/*if (message.action == "CREATE_GAME") {
			let state = gameEngine.createGame(socket, message);
			socket.write(state);
		}

		if (message.action == "RUN_GAME") {
			socket.write(gameEngine.runGame(socket));
		}*/
	}
}

module.exports = SocketManager;


text:
/*global m */
(function HomeController(n) {
    'use strict';

    // declaring controller
    n.controller = function () {
        this.home = new window.listagram.home.model();
        this.showForm = function () {
            setTimeout(function () {
                listagram.xDeck.showCard(2);
            });
        };
    };

    // exporting
    window.listagram.home = n;
}(window.listagram.home || {}));


text:
/* THE GOAL OF THIS PLUGIN IS TO MAKE AN FB-STYLE TOKENIZER WITH PHOTO OPTION
accepts json data each object containing three fields, a label, a value, and an image path */

/* As much as I love the jQuery UI framework it was a goal of mine to keep this agnostic of that as much as possible. */
/* for now, it will be dependent on the jquery UI autocomplete but nothing else */

;(function($){
    var debug = true;

    var methods = {
        /* INITIAL SETTINGS / HTML INJECTION */
        init : function( options ) {
            var settings = $.extend(
                                {},
                                $.tokenize.defaults,
                                options
                            );

            return this.each(function () {
                var tokenized = new $.tokenize(this, settings);
            });
        }
    };

    /* METHOD CALLS */
    $.fn.tokenizer = function(method) {
        if ( methods[method] ) {
          return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
          return methods.init.apply( this, arguments );
        } else {
          $.error( 'Method ' +  method + ' does not exist on jQuery.tokenizer' );
        }
    };

    /* TOKENIZE - Internal core logic */
    $.tokenize = function(input,settings) {
        /*log(input);
        log(settings);*/
        var KEY = {
            BACKSPACE: 8,
            TAB: 9,
            RETURN: 13,
            ESC: 27,
            LEFT: 37,
            UP: 38,
            RIGHT: 39,
            DOWN: 40,
            COMMA: 188,
            ENTER: 13,
			DELETE: 46
        };
        // storage variables
        var $tokens = null;
        var token_items = [];

        $.template("token_template",settings.tokenTmpl);

        // ORIGINAL INPUT - hidden
        var $hiddenInput = $(input)
								.hide()
								.focus(function () { })
								.blur(function () {
										$input.blur();
									})
								.attr({
									  name:$(input).attr('name') + '_loaded'
									  });

        // NEW INPUT ELEMENT
        var $input = $("<input type=\"text\">")
                        .addClass('uiTokenField')
                        .focus(function () {

                        })
                        .blur(function () {
                            //hide_dropdown();
                        })
                        .keydown(function (event) {
                            var previous_token;
                            var next_token;

                            switch(event.keyCode) {
                                case KEY.LEFT:
                                case KEY.RIGHT:
                                case KEY.UP:
                                case KEY.DOWN:

                                    break;

                                case KEY.BACKSPACE:

                                    break;
                                case KEY.TAB:
                                case KEY.RETURN:
                                case KEY.COMMA:

                                  break;

                                case KEY.ESC:

                                  return true;
                            }
                        });

        // TOKENIZER WRAPPER - contains all elements for this instance of the tokenizer
        var $wrapper = $('<div/>').addClass('uiTokenizer mrl');

        switch(settings.type) {
            case 'token':
                settings.typeOpts = {
                    imgSize:0,
                    dragOffset:{
                        top:-10,
                        left:-30
                    }
                }
            break;
            case 'tokenImage':
                settings.typeOpts = {
                    imgSize:62,
                    dragOffset:{
                        top:23,
                        left:30
                    }
                }

                $wrapper.addClass('uiImageTokenizer');
                break;
            case 'list':
                settings.typeOpts = {
                    imgSize:0,
                    dragOffset:{
                        top:-10,
                        left:40
                    }
                }
                $wrapper.addClass('uiListTokenizer');
                break;
            case 'listImage':
                settings.typeOpts = {
                    imgSize:20,
                    dragOffset:{
                        top:-10,
                        left:40
                    }
                }
                $wrapper.addClass('uiListImageTokenizer');
                break;
        }

        // TOKEN AREA - contains all of your tokens
        var $tokenarea = $('<div/>')
                .addClass('uiTokenarea hide clearfix')
                .appendTo($wrapper)
                ;

        // AUTOCOMPLETE container element
        var $typeahead = $('<div/>').addClass('uiTypeahead').prependTo($wrapper);
        $input.appendTo($typeahead);

        // AUTOCOMPLETE (requires jQuery UI autocomplete widget
        if($.isFunction($.fn.autocomplete)) {
            $input.autocomplete({
                //define callback to format results
                selectFirst:true,
                source: function(req, add){
                    $.ajax({
                        url: settings.url,
                        type:settings.ajaxMethod,
                        dataType: "json",
                        data: $.extend({},
                                       settings.ajaxParams,
                                        {
                                        q:req.term
                                        }),
                        success: function( data ) {
                            //create array for response objects
                            var suggestions = [];

                            //process response
                            $.each(data, function(i, val){
                                var anItem = data[i];
                                anItem.label = data[i].TEXT;
                                anItem.value = data[i].OBJECT_ID;
                                suggestions.push(anItem);
                            });

                            //pass array to callback
                            add(suggestions);
                        }
                    });
                },
                delay:50,
                //define select handler
                select: function(e, ui) {
                    typeahead_select(ui.item);
                    return false;
                },

                //define select handler
                change: function() {

                    //prevent 'to' field being updated and correct position
                    $("#Degrees").val("").css("top", 2);
                }
            });

            //log("autocomplete plugin is installed.");
        }

        // INJECT ALL OF THE HTML INTO THE PAGE
        $wrapper.insertAfter($hiddenInput);

        // if you want to use watermarkText then JQUERY.WATERMARK PLUGIN NEEDED
        if(jQuery.watermark) {
            //log("watermark plugin is installed.");
            $input.watermark(settings.watermarkText);
        }

        var refreshTokens = function(clickOffset) {
            var counter = 0;

            tokens = $tokenarea.children('.uiToken').not('.droppable_placeholder');
            if(clickOffset){

            } else {
                clickOffset = { x:0,y:0 }
            }
            if(settings.type == 'tokenImage') {
                var textAll = '';
                tokens.each(function() {
                    var token = $(this);
                    var index = token.index();
                    var text = token.find('.text').text();

                    textAll = textAll + ', ' + text;
                    if(counter < 5) {
                        makeTokenShown(token);
                    } else {
                        makeTokenHidden(token);
                        //        marginOffset = parseInt($(token).height() * clickOffset.y);
                        /*if($(token).hasClass('drag')) {
                            $(token).css({
                                'margin-top':'auto'
                            });
                        } else {
                            $(token).css({
                                'margin-top':'auto'
                            });
                        }
                        console.log(marginOffset);*/
                    }

                    counter++;
                });
            }
        }

        function makeDragShown(ui) {
            ui.item.addClass('shown').removeClass('hidden').find('.tokenImg').show();
            ui.placeholder.addClass('shown shownPlaceholder').css({ height:102,width:72 }).removeClass('hidden hiddenPlaceholder').find('.tokenImg').show();
            ui.helper.addClass('shown shownPlaceholder').css({ height:102,width:72 }).removeClass('hidden hiddenPlaceholder').find('.tokenImg').show();
        }

        function makeDragHidden(ui) {
            ui.item.removeClass('shown').addClass('hidden').find('.tokenImg').hide();
            ui.placeholder.removeClass('shown shownPlaceholder').css({ height:16,width:72 }).addClass('hidden hiddenPlaceholder').find('.tokenImg').hide();
            ui.helper.removeClass('shown shownPlaceholder').css({ height:16,width:72 }).addClass('hidden hiddenPlaceholder').find('.tokenImg').hide();

        }

        function makeTokenShown(token) {
            token.addClass('shown').removeClass('hidden').find('.tokenImg').show();

            if(token.hasClass('drag')) {
                //console.log('drag');
            }
        }

        function makeTokenHidden(token) {
            token.removeClass('shown').addClass('hidden').find('.tokenImg').hide();

        }

        load_default();

        function is_printable_character(keycode) {
            if((keycode >= 48 && keycode <= 90) ||      // 0-1a-z
               (keycode >= 96 && keycode <= 111) ||     // numpad 0-9 + - / * .
               (keycode >= 186 && keycode <= 192) ||    // ; = , - . / ^
               (keycode >= 219 && keycode <= 222)       // ( \ ) '
              ) {
                  return true;
              } else {
                  return false;
              }
        }

        function load_default() {
            var list_opts = $hiddenInput.find('option:selected');

            var token = {};
            list_opts.each(function() {
                token.label = $(this).text();
                token.value = $(this).val();

                token_add(token);
            });

            refresh_binding();
        }

        function typeahead_select(token) {
            token_add(token);
            $input.val('');
            $input.blur();
        }

        function refresh_binding() {
            tokens = $tokenarea.children('.uiToken').not('.droppable_placeholder');
            tokens.drag("start",function(ev,dd) {
                            var placeholder = $("<span/>").addClass('uiToken shown shownPlaceholder droppable_placeholder');
                            var startIndex = $(this).index();
                            var startHeight = $(this).height();
                            var startWidth = $(this).width();
                            $(this).data("startIndex",startIndex);
                            $(this).data("startHeight",startHeight);
                            $(this).data("startWidth",startWidth);

                            $(this).data("placeholder",placeholder);
                            var clickOffset = {
                                x:parseInt(ev.pageX-dd.originalX)/100,
                                y:parseInt(ev.pageY-dd.originalY)/100
                            };
                            $(this).data("clickOffset",clickOffset);

                            var startOffset = $(this).height() * clickOffset.y;
                            $(this).data("startOffset",startOffset);
                            //console.log(startOffset);
                            var container = $tokenarea.offset();
                            $(this).addClass('drag');
                            $(this).css({
                                position:'absolute',
                                'z-index':'1000'
                            });
                        })
                        .drag(function(ev,dd){
                            var placeholder = $(this).data("placeholder");
                            var clickOffset = $(this).data("clickOffset");
                            var startOffset = $(this).data("startOffset");
                            var startHeight = $(this).data("startHeight");
                            var startWidth = $(this).data("startWidth");
                            var startIndex = $(this).data("startIndex");
                            var container = $tokenarea.offset();

                            var drop = dd.drop[0], method = $.data( drop || {}, "drop+reorder" );
                            var rel = {
                                y:parseInt(ev.pageY-container.top),
                                x:parseInt(ev.pageX-container.left)
                            };

                            var top = rel.y+parseInt(dd.offsetY-ev.pageY)+19;
                            var left = rel.x+parseInt(dd.offsetX-ev.pageX);

							if($(drop).parents().filter($tokenarea).length>0) {
								if ( drop && $(drop).is('.uiToken') && ( drop != dd.current || method != dd.method ) ){
									$( this )[ method ]( drop );
									dd.current = drop;
									dd.method = method;
									dd.update();
									refreshTokens(clickOffset);
									placeholder.insertAfter($(this));
								}
							}

							if(settings.type == 'tokenImage') {
								if($(this).index() > 4) {
									placeholder.addClass('hidden hiddenPlaceholder').removeClass('shown shownPlaceholder')
										.css({
											 height:$(this).height(),
											 width:$(this).width()
											 });

								} else {
									placeholder
										.addClass('shown shownPlaceholder')
										.removeClass('hidden hiddenPlaceholder')
										.css({
											 height:$(this).height()
											 });
								}
							} else {
								placeholder
									.removeClass('shown shownPlaceholder')
									.removeClass('hidden hiddenPlaceholder')
									/*.css({
										 height:$(this).height(),
										 width:$(this).width()
										 })*/;
							}

                            var currHeight = $(this).height();
                            var currWidth = $(this).width();
                            var currHeightOffset = (currHeight*clickOffset.y);
                            var testY = parseFloat(ev.pageY-dd.offsetY) - parseFloat(currHeightOffset);
                            var currWidthOffset = (currWidth*clickOffset.x);
                            var testX = parseFloat(ev.pageX-dd.offsetX) - parseFloat(currWidthOffset);

                            if(currWidth < startWidth) {
                                left = parseFloat(left) + parseFloat(testX)*clickOffset.x;
                                //console.log(testX);
                            }

                            if(currHeight < startHeight) {
                                top = parseFloat(top) + parseFloat(testY);
                                //console.log(top);
                            }

                            $(this).css({
                                position:'absolute',
                                'z-index':'1000',
                                'top':top,
                                'left':left
                            });
                        })
                        .drag("end",function(ev,dd) {
                            var placeholder = $(this).data("placeholder");
                            var container = $tokenarea.offset();
                            placeholder.remove();

                            $(this).css({
                                position:'relative',
                                'z-index':'0',
                                top: 0,
                                left: 0,
                                'margin-top':'auto'
                            });

                            $(this).removeClass('drag');
                        })
                        .drop("init",function( ev, dd ){
                            return !( this == dd.drag );
                        });

                        $.drop({
                            mode:'mouse',
                            tolerance: function( event, proxy, target ){
								var placeholder = $(this).data("placeholder");
								var testV = event.pageY > ( target.top + target.height / 2 );
								var testH = event.pageX > ( target.left + target.width / 2 );
								var container = $tokenarea.offset();

								//$('.debugger').text(parseFloat(event.pageY-container.top) + ' ' + parseFloat(event.pageX-container.left));
								$.data(target.elem, "drop+reorder", testV ? "insertAfter" : "insertBefore" );

                                return this.contains( target, [ event.pageX, event.pageY ] );
                            }
                });
        }

		function token_delete($token) {
			$token.remove();

			return false;
		}

		function token_deselect($token) {
            $token.removeClass('uiTokenSelected').removeClass('uiTokenShownSelected');

			return false;
		}

        function token_select($token) {
			var $nextToken = $token.next();
			var $prevToken = $token.prev();

			$token.addClass('uiTokenSelected');

			if($token.hasClass('shown')) {
				$token.addClass('uiTokenShownSelected');
			}

			$(document).keydown(function(e) {
				if($token.hasClass('uiTokenSelected')) {
					switch(e.keyCode) {
						case KEY.LEFT:
							if($prevToken.is('.uiToken')) {
								token_deselect($token);
								$(document).unbind("keydown");
								token_select($prevToken);
							}
							break;
						case KEY.RIGHT:
							if($nextToken.is('.uiToken')) {
								token_deselect($token);
								$(document).unbind("keydown");
								token_select($nextToken);
							}
							break;
						case KEY.TAB:
							if(e.shiftKey) {
								if($prevToken.is('.uiToken')) {
								token_deselect($token);
								$(document).unbind("keydown");
								token_select($prevToken);
							}
							} else {
								if($nextToken.is('.uiToken')) {
									token_deselect($token);
									$(document).unbind("keydown");
									token_select($nextToken);
								}
							}
							break;
						case KEY.BACKSPACE:
							token_delete($token);
							$(document).unbind("keydown");

							refreshTokens();
							token_select($nextToken);
							break;
						case KEY.DELETE:
							token_delete($token);
							$(document).unbind("keydown");

							refreshTokens();
							token_select($nextToken);
							break;

						case KEY.ESC:
							token_deselect($token);
							$(document).unbind("keydown");
						break;
					}
				}
				return false;
			});

			$("body").click();
			$("html").one("click",function() {
				token_deselect($token);

				 return false;
			 });

			return false;
        }

		function refreshHiddenInput() {
			var $tokens = $tokenarea.children('.uiToken');

			$hiddenInput.val('').html("");
		}

        function token_add(token) {
            var shownTokens = [];
            var hiddenTokens = [];

            var $token = $("<span/>")
                              .addClass('uiToken');

            if(settings.type == 'tokenImage' || settings.type == 'listImage') {
                var $tokenImg = $("<span/>").addClass('tokenImg').appendTo($token);
                var $hubPhoto = $("<div/>").css({
                                                height:settings.typeOpts.imgSize + 'px',
                                                width:settings.typeOpts.imgSize + 'px'
                                                }).addClass('hubPhoto').appendTo($tokenImg);
                $("<img/>")
                    .attr({
                        width:settings.typeOpts.imgSize,
                        height:settings.typeOpts.imgSize,
                        src:'/static/images/no-photo/none_i.png'
                     }).appendTo($hubPhoto);
            }

			$("<input/>").attr({
							   	type:'hidden',
								value:token.value,
								name:settings.fieldName,
								autocomplete:'off'
							   }).appendTo($token);
			$("<input/>").attr({
							   	type:'hidden',
								value:token.label,
								name:'text_' + settings.fieldName,
								autocomplete:'off'
							   }).appendTo($token);

            /* BINDS */
			$token.click(function() {
			 	token_select($token);

				return false;
			 });
            var $tokenText = $("<span/>")
                                .addClass('text')
                                .text(token.label).appendTo($token);

            $tokenarea.addClass('expanded').removeClass('hide');

            token_items.push(token);
            $token.prependTo($tokenarea);

            /* keeps $tokens list selector up to date */
            refreshTokens();

            return false;
        }
    }

     $.tokenize.defaults = {
         ajaxParams:null,
         shownImages: true,
         shownCount: 5,
        watermarkText: "Type in a search term",
        searchDelay: 300,
        minChars: 1,
         ajaxMethod:'get',
        type:'token',
        tokenLimit: null,
        jsonContainer: null,
        method: "GET",
        tokenTmpl: '<span title="${label}" class="uiToken ${shown}">' +
                        '        <span class="tokenImg hide">' +
                        '            <div style="height: 62px; width: 62px;" class="hubPhoto">' +
                        '                <img height="62" src="/static/images/no-photo/none_i.png" class="img">' +
                        '            </div>' +
                        '        </span>' +
                        '        <span class="text">' +
                        '            ${label}' +
                        '        </span>' +
                        '        <input type="hidden" value="${value}" name="${fieldName}" autocomplete="off">' +
                        '        <input type="hidden" value="${label}" name="text_${fieldName}" autocomplete="off">' +
                        '    </span>',
        contentType: "json",
        autocomplete:null,
        queryParam: "q",
        onResult: null,
        selectFirst: true,
        autoFill: false,
        defaultData:null
    };

    function log() {
        if(jQuery.log) {
            $.log(arguments);
        }
    };

})(jQuery);