text:
import os, time, webapp2, jinja2
import session, logging, json
import settings
from inspect import currentframe, getframeinfo

from google.appengine.api import users
from google.appengine.ext import ndb

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

import read_tweepy

from models import *

class MainPage(session.BaseRequestHandler):

    def get(self, command = ''):
        def lookup(dict_or_obj, member):
            try:
                # could be a dictionary or a NoneType
                member_value = dict_or_obj[member]
            except (KeyError, TypeError):
                try:
                    # could have it as an attribute
                    member_value = getattr(dict_or_obj, member)
                except AttributeError:
                    member_value = False
            return member_value

        this_app = AppOpenLSH.get_or_insert('KeyOpenLSH')
        app_is_open = this_app.is_open
        frameinfo = getframeinfo(currentframe())
        logging.info('file %s, line %s app_is_open, %s', frameinfo.filename, frameinfo.lineno+1, app_is_open)
        tw_logged_in = False
        if this_app.twitter_access_token_key:
            tw_logged_in = True
            self.session['tw_logged_in'] = True
            self.session['auth.access_token.key'] = this_app.twitter_access_token_key
            self.session['auth.access_token.secret'] = this_app.twitter_access_token_secret

        app_is_closed = False
        u = users.get_current_user()
        if u:
            demo_user = DemoUser.get_or_insert(u.user_id(), email = u.email(), nickname = u.nickname())

        ulogged = 'User not logged in' if not u else 'User is %s' % u.nickname()
        app_status = 'App is Open' if app_is_open else "App is Closed"
        if users.is_current_user_admin():
            frameinfo = getframeinfo(currentframe())
            logging.info('file %s, line %s Admin User, %s', frameinfo.filename, frameinfo.lineno+1, app_status)
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Google Logout'
        elif u and app_is_open:
            frameinfo = getframeinfo(currentframe())
            logging.info('file %s, line %s %s %s', frameinfo.filename, frameinfo.lineno+1, ulogged, app_status)
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Google Logout'
        elif not u:
            frameinfo = getframeinfo(currentframe())
            logging.info('file %s, line %s %s %s', frameinfo.filename, frameinfo.lineno+1, ulogged, app_status)
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Google Login -- use your Gmail'
        else:
            frameinfo = getframeinfo(currentframe())
            logging.info('file %s, line %s %s %s', frameinfo.filename, frameinfo.lineno+1, ulogged, app_status)
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Google Logout'
            app_is_closed = not app_is_open

        tw_banner = ''
        if tw_logged_in:
            tw_banner = 'Ready for Tweets'
        tweets = []
        tweet_display = ''
        if not app_is_closed:
            duik = lookup(self.session, 'duik')
            dui = ndb.Key(urlsafe = duik).get() if duik else None
            if not dui:
                dui = DemoUserInteraction.latest_for_user( u )
                self.session['duik'] = dui.key.urlsafe() if dui else None
            if dui:
                tweets = dui.tweets
                tw_banner = '%d Tweets as of %s' % (len(tweets), dui.asof.isoformat(' ')[:19])
                tweet_display = '
\n— '.join(tweets)
        else:
            dui = None

        similar_sets, same_sets, accounted_ids = ([], [], [])
        frameinfo = getframeinfo(currentframe())
        logging.info('file %s, line %s %s', frameinfo.filename, frameinfo.lineno+1, similar_sets)
        if lookup(dui, 'calc_done'):
            read_tweepy.LshTweets.show(self.session)
            similar_sets, same_sets, accounted_ids  = self.session['lsh_results']
        frameinfo = getframeinfo(currentframe())
        logging.info('file %s, line %s %s %s', frameinfo.filename, frameinfo.lineno+1, similar_sets, same_sets)

        try:
            if command == 'show_lsh_results':
#                 matched_tweets = [tweets[twid] for twid in range(len(tweets)) if twid     in self.session['lsh_results'][1]]
                other_tweets   = [tweets[twid] for twid in range(len(tweets)) if twid not in self.session['lsh_results'][1]]
                tweet_display = '
\n— '.join(other_tweets)
        except: pass

        template_values = {
            'app_is_closed': app_is_closed,
            'google_logged_in': u,
            'url': url,
            'url_linktext': url_linktext,
            'tw_logged_in': tw_logged_in,
            'tw_banner': tw_banner,
            'similar_sets': similar_sets,
            'same_sets': same_sets,
            'tweets': tweets,
            'fetching': lookup(dui, 'fetching'),
            'calculating': lookup(dui, 'calculating'),
            'calc_done': lookup(dui, 'calc_done'),
            'gaCode': settings.gaCode,
        }

        template = JINJA_ENVIRONMENT.get_template('tweets_index.html')
        try:
            self.response.write(template.render(template_values))
        except UnicodeDecodeError:
            template_values['tweets'] = ['unreadable content']
            self.response.write(template.render(template_values))
    def post(self):
        cmd = self.request.get('command')
        if cmd == 'calc_lsh':
            read_tweepy.LshTweets.calc(self.session)
        elif cmd == 'show_lsh_results':
            read_tweepy.LshTweets.show(self.session)
        self.get(cmd)

class WaitPage(session.BaseRequestHandler):
    def get(self):
        template_values = {
            'gaCode': settings.gaCode,
        }

        template = JINJA_ENVIRONMENT.get_template('coming_soon.html')
        try:
            self.response.write(template.render(template_values))
        except UnicodeDecodeError:
            template_values['tweets'] = 'unreadable content'
            self.response.write(template.render(template_values))
    def post(self):
        pass

urls = [
    ('/', MainPage),
    ('/coming_soon', WaitPage),
]
import read_tweepy
urls += read_tweepy.urls
import blobs
urls += blobs.urls
import mr_main
urls += mr_main.urls
import peer_belt_driver
urls += peer_belt_driver.urls
import test_db_datastore
urls += test_db_datastore.urls

sess_config = {}
sess_config['webapp2_extras.sessions'] = {
    'secret_key': 'dcd99df0-824a-4331-9a55-2d5900e27732'
}
application = webapp2.WSGIApplication(urls, debug=True, config=sess_config)


text:
using System.Collections.Generic;

namespace CSC.CSClassroom.Model.Assignments.ServiceResults
{
	/// <summary>
	/// The result for a single student's assignment.
	/// </summary>
	public class StudentAssignmentResults
	{
		/// <summary>
		/// The student's last name.
		/// </summary>
		public string LastName { get; }

		/// <summary>
		/// The student's first name.
		/// </summary>
		public string FirstName { get; }

		/// <summary>
		/// The student's section name.
		/// </summary>
		public string SectionName { get; }

		/// <summary>
		/// The results for each question.
		/// </summary>
		public IList<AssignmentGroupResult> AssignmentGroupResults { get; }

		/// <summary>
		/// Constructor.
		/// </summary>
		public StudentAssignmentResults(
			string lastName,
			string firstName,
			string sectionName,
			IList<AssignmentGroupResult> assignmentGroupResultses)
		{
			LastName = lastName;
			FirstName = firstName;
			SectionName = sectionName;
			AssignmentGroupResults = assignmentGroupResultses;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package sample.websocket;

import org.springframework.context.ApplicationListener;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import sample.data.ActiveWebSocketUser;
import sample.data.ActiveWebSocketUserRepository;

import java.security.Principal;
import java.util.Arrays;
import java.util.Calendar;

public class WebSocketConnectHandler<S> implements ApplicationListener<SessionConnectEvent> {

    private ActiveWebSocketUserRepository repository;
    private SimpMessageSendingOperations messagingTemplate;

    public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate,
                                   ActiveWebSocketUserRepository repository) {
        super();
        this.messagingTemplate = messagingTemplate;
        this.repository = repository;
    }

    public void onApplicationEvent(SessionConnectEvent event) {
        MessageHeaders headers = event.getMessage().getHeaders();
        Principal user = SimpMessageHeaderAccessor.getUser(headers);
        if(user == null) {
            return;
        }
        String id = SimpMessageHeaderAccessor.getSessionId(headers);
        repository.save(new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance()));
        messagingTemplate.convertAndSend("/topic/friends/signin",
		        Arrays.asList(user.getName()));
    }
}


text:
package org.wso2.carbon.identity.application.common.model;

import org.apache.axiom.om.OMElement;
import org.apache.commons.collections.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class FederatedAuthenticatorConfig implements Serializable {

    private static final long serialVersionUID = -2361107623257323257L;

    protected String name;
    protected String displayName;
    protected boolean enabled;
    protected Property[] properties = new Property[0];

    public static FederatedAuthenticatorConfig build(OMElement federatedAuthenticatorConfigOM) {

        if (federatedAuthenticatorConfigOM == null) {
            return null;
        }

        FederatedAuthenticatorConfig federatedAuthenticatorConfig = new FederatedAuthenticatorConfig();

        Iterator<?> iter = federatedAuthenticatorConfigOM.getChildElements();

        while (iter.hasNext()) {
            OMElement element = (OMElement) (iter.next());
            String elementName = element.getLocalName();

            if ("Name".equals(elementName)) {
                federatedAuthenticatorConfig.setName(element.getText());
            } else if ("DisplayName".equals(elementName)) {
                federatedAuthenticatorConfig.setDisplayName(element.getText());
            } else if ("IsEnabled".equals(elementName)) {
                federatedAuthenticatorConfig.setEnabled(Boolean.parseBoolean(element.getText()));
            } else if ("Properties".equals(elementName)) {
                Iterator<?> propertiesIter = element.getChildElements();
                List<Property> propertiesArrList = new ArrayList<Property>();

                if (propertiesIter != null) {
                    while (propertiesIter.hasNext()) {
                        OMElement propertiesElement = (OMElement) (propertiesIter.next());
                        propertiesArrList.add(Property.build(propertiesElement));
                    }
                }

                if (CollectionUtils.isNotEmpty(propertiesArrList)) {
                    Property[] propertiesArr = propertiesArrList.toArray(new Property[0]);
                    federatedAuthenticatorConfig.setProperties(propertiesArr);
                }
            }
        }

        return federatedAuthenticatorConfig;
    }

    /**
     * @return
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return
     */
    public boolean isEnabled() {
        return enabled;
    }

    /**
     * @param enabled
     */
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    /**
     * @return
     */
    public boolean isValid() {
        return true;
    }

    /**
     * @return
     */
    public Property[] getProperties() {
        return properties;
    }

    /**
     * @param properties
     */
    public void setProperties(Property[] properties) {
        if (properties == null) {
            return;
        }
        Set<Property> propertySet = new HashSet<Property>(Arrays.asList(properties));
        this.properties = propertySet.toArray(new Property[propertySet.size()]);
    }

    /**
     * @return
     */
    public String getDisplayName() {
        return displayName;
    }

    /*
     * <FederatedAuthenticatorConfig> <Name></Name> <DisplayName></DisplayName>
     * <IsEnabled></IsEnabled> <Properties></Properties> </FederatedAuthenticatorConfig>
     */

    /**
     * @param displayName
     */
    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof FederatedAuthenticatorConfig)) {
            return false;
        }

        FederatedAuthenticatorConfig that = (FederatedAuthenticatorConfig) o;

        if (name != null ? !name.equals(that.name) : that.name != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        return name != null ? name.hashCode() : 0;
    }
}


text:
package com.google.errorprone.refaster;

import com.sun.source.tree.Tree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.tools.javac.tree.JCTree;
import javax.annotation.Nullable;

/**
 * A serializable representation of a template syntax tree which can be unified with a target AST
 * and inlined based on a set of substitutions.
 *
 * @param <T> The type this tree inlines to.
 * @author Louis Wasserman (lowasser@google.com)
 */
public abstract class UTree<T extends JCTree> extends SimpleTreeVisitor<Choice<Unifier>, Unifier>
    implements Unifiable<Tree>, Inlineable<T>, Tree {
  @Override
  public Choice<Unifier> unify(@Nullable Tree target, Unifier unifier) {
    return (target != null) ? target.accept(this, unifier) : Choice.<Unifier>none();
  }

  @Override
  protected Choice<Unifier> defaultAction(Tree node, Unifier unifier) {
    return Choice.none();
  }
}


text:
Store = {};
// All the entered clients
Store.clients = new Rx.BehaviorSubject([]);
// Search text starts empty, any free text allowed
Store.searchText = new Rx.BehaviorSubject('');
// Sort object
// null - no search
// obj.key - search field
// obj.value - search direction
Store.sort = new Rx.BehaviorSubject(null);
// Page number
Store.pageNumber = new Rx.BehaviorSubject(Constants.PAGE);
// Page size
Store.pageSize = new Rx.BehaviorSubject(Constants.PAGE_SIZE);
// Sort field
Store.sortField = new Rx.BehaviorSubject({});
// Insert new client
// TODO this looks kinda fishy
Store.insert = new Rx.Subject();

// Whenever new client is inserted add it to store
Store.insert.subscribe(function (client) {
    Store.clients.onNext(Store.clients.value.concat(R.merge(client,{time: Date.now()})));
});
// Source of clients filtered by search text
Store.results = Store.clients.combineLatest(
    Store.searchText,
    function (clients, text) {
        return Util.search(text, clients);
    }
);
// Source of sorted resulsts (clients already filtered by search text)
Store.sorted = Store.results.combineLatest(
    Store.sort,
    function (results, sort) {
        return Util.sort(sort,results);
    }
);
// Source of shown clients (sorted clients already filtered by search text)
Store.shown = Store.sorted.combineLatest(
    Store.pageNumber,
    Store.pageSize,
    function (sorted, pageNumber, pageSize) {
        var fittedPage = Util.fitPage(sorted.length, pageNumber, pageSize);
        if (fittedPage !== pageNumber) {
            Store.pageNumber.onNext(fittedPage);
        }
        return Util.pageEntries(sorted, fittedPage, pageSize);
    }
);
// Whenever sort field changes update Store.sort
// TODO might be better to be done directly for now
Store.sortField.subscribe(function (condition) {
    Store.sort.onNext(condition);
});


text:
package org.apache.fontbox.ttf;

import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * A 'kern' table in a true type font.
 *
 * @author Glenn Adams
 */
public class KerningSubtable
{
    private static final Log LOG = LogFactory.getLog(KerningSubtable.class);

    // coverage field bit masks and values
    private static final int COVERAGE_HORIZONTAL = 0x0001;
    private static final int COVERAGE_MINIMUMS = 0x0002;
    private static final int COVERAGE_CROSS_STREAM = 0x0004;
    private static final int COVERAGE_FORMAT = 0xFF00;

    private static final int COVERAGE_HORIZONTAL_SHIFT = 0;
    private static final int COVERAGE_MINIMUMS_SHIFT = 1;
    private static final int COVERAGE_CROSS_STREAM_SHIFT = 2;
    private static final int COVERAGE_FORMAT_SHIFT = 8;

    // true if horizontal kerning
    private boolean horizontal;
    // true if minimum adjustment values (versus kerning values)
    private boolean minimums;
    // true if cross-stream (block progression) kerning
    private boolean crossStream;
    // format specific pair data
    private PairData pairs;

    KerningSubtable()
    {
    }

    /**
     * This will read the required data from the stream.
     *
     * @param data The stream to read the data from.
     * @param version The version of the table to be read
     * @throws IOException If there is an error reading the data.
     */
    void read(TTFDataStream data, int version) throws IOException
    {
        if (version == 0)
        {
            readSubtable0(data);
        }
        else if (version == 1)
        {
            readSubtable1(data);
        }
        else
        {
            throw new IllegalStateException();
        }
    }

    /**
     * Determine if subtable is designated for use in horizontal writing modes and
     * contains inline progression kerning pairs (not block progression "cross stream")
     * kerning pairs.
     *
     * @return true if subtable is for horizontal kerning
     */
    public boolean isHorizontalKerning()
    {
        return isHorizontalKerning(false);
    }

    /**
     * Determine if subtable is designated for use in horizontal writing modes, contains
     * kerning pairs (as opposed to minimum pairs), and, if CROSS is true, then return
     * cross stream designator; otherwise, if CROSS is false, return true if cross stream
     * designator is false.
     *
     * @param cross if true, then return cross stream designator in horizontal modes
     * @return true if subtable is for horizontal kerning in horizontal modes
     */
    public boolean isHorizontalKerning(boolean cross)
    {
        if (!horizontal)
        {
            return false;
        }
        else if (minimums)
        {
            return false;
        }
        else if (cross)
        {
            return crossStream;
        }
        else
        {
            return !crossStream;
        }
    }

    /**
     * Obtain kerning adjustments for GLYPHS sequence, where the
     * Nth returned adjustment is associated with the Nth glyph
     * and the succeeding non-zero glyph in the GLYPHS sequence.
     *
     * Kerning adjustments are returned in font design coordinates.
     *
     * @param glyphs a (possibly empty) array of glyph identifiers
     * @return a (possibly empty) array of kerning adjustments
     */
    public int[] getKerning(int[] glyphs)
    {
        int[] kerning = null;
        if (pairs != null)
        {
            int ng = glyphs.length;
            kerning = new int[ng];
            for (int i = 0; i < ng; ++i)
            {
                int l = glyphs[i];
                int r = -1;
                for (int k = i + 1; k < ng; ++k)
                {
                    int g = glyphs[k];
                    if (g >= 0)
                    {
                        r = g;
                        break;
                    }
                }
                kerning[i] = getKerning(l, r);
            }
        }
        else
        {
            LOG.warn("No kerning subtable data available due to an unsupported kerning subtable version");
        }
        return kerning;
    }

    /**
     * Obtain kerning adjustment for glyph pair {L,R}.
     *
     * @param l left member of glyph pair
     * @param r right member of glyph pair
     * @return a (possibly zero) kerning adjustment
     */
    public int getKerning(int l, int r)
    {
        if (pairs == null)
        {
            LOG.warn("No kerning subtable data available due to an unsupported kerning subtable version");
            return 0;
        }
        return pairs.getKerning(l, r);
    }

    private void readSubtable0(TTFDataStream data) throws IOException
    {
        int version = data.readUnsignedShort();
        if (version != 0)
        {
            LOG.info("Unsupported kerning sub-table version: " + version);
            return;
        }
        int length = data.readUnsignedShort();
        if (length < 6)
        {
            throw new IOException("Kerning sub-table too short, got " + length
                    + " bytes, expect 6 or more.");
        }
        int coverage = data.readUnsignedShort();
        if (isBitsSet(coverage, COVERAGE_HORIZONTAL, COVERAGE_HORIZONTAL_SHIFT))
        {
            this.horizontal = true;
        }
        if (isBitsSet(coverage, COVERAGE_MINIMUMS, COVERAGE_MINIMUMS_SHIFT))
        {
            this.minimums = true;
        }
        if (isBitsSet(coverage, COVERAGE_CROSS_STREAM, COVERAGE_CROSS_STREAM_SHIFT))
        {
            this.crossStream = true;
        }
        int format = getBits(coverage, COVERAGE_FORMAT, COVERAGE_FORMAT_SHIFT);
        if (format == 0)
        {
            readSubtable0Format0(data);
        }
        else if (format == 2)
        {
            readSubtable0Format2(data);
        }
        else
        {
            LOG.debug("Skipped kerning subtable due to an unsupported kerning subtable version: " + format);
        }
    }

    private void readSubtable0Format0(TTFDataStream data) throws IOException
    {
        pairs = new PairData0Format0();
        pairs.read(data);
    }

    private void readSubtable0Format2(TTFDataStream data)
    {
        LOG.info("Kerning subtable format 2 not yet supported.");
    }

    private void readSubtable1(TTFDataStream data)
    {
        LOG.info("Kerning subtable format 1 not yet supported.");
    }

    private static boolean isBitsSet(int bits, int mask, int shift)
    {
        return getBits(bits, mask, shift) != 0;
    }

    private static int getBits(int bits, int mask, int shift)
    {
        return (bits & mask) >> shift;
    }

    private interface PairData
    {
        void read(TTFDataStream data) throws IOException;

        int getKerning(int l, int r);
    }

    private static class PairData0Format0 implements Comparator<int[]>, PairData
    {
        private int searchRange;
        private int[][] pairs;

        @Override
        public void read(TTFDataStream data) throws IOException
        {
            int numPairs = data.readUnsignedShort();
            searchRange = data.readUnsignedShort()/6;
            int entrySelector = data.readUnsignedShort();
            int rangeShift = data.readUnsignedShort();
            pairs = new int[numPairs][3];
            for (int i = 0; i < numPairs; ++i)
            {
                int left = data.readUnsignedShort();
                int right = data.readUnsignedShort();
                int value = data.readSignedShort();
                pairs[i][0] = left;
                pairs[i][1] = right;
                pairs[i][2] = value;
            }
        }

        @Override
        public int getKerning(int l, int r)
        {
            int[] key = new int[] { l, r, 0 };
            int index = Arrays.binarySearch(pairs, key, this);
            if (index >= 0)
            {
                return pairs[index][2];
            }
            return 0;
        }

        @Override
        public int compare(int[] p1, int[] p2)
        {
            assert p1 != null;
            assert p1.length >= 2;
            assert p2 != null;
            assert p2.length >= 2;
            int cmp1 = Integer.compare(p1[0], p2[0]);
            if (cmp1 != 0)
            {
                return cmp1;
            }
            return Integer.compare(p1[1], p2[1]);
        }
    }
}


text:
#include "privatexml.h"
#include "clientbase.h"
#include "stanza.h"

namespace gloox
{

  // ---- PrivateXML::Query ----
  PrivateXML::Query::Query( const Tag* tag )
    : StanzaExtension( ExtPrivateXML ), m_privateXML( 0 )
  {
    if( !tag )
      return;

    if( tag->name() == "query" && tag->xmlns() == XMLNS_PRIVATE_XML )
    {
      if( tag->children().size() )
        m_privateXML = tag->children().front()->clone();
    }
    else
      m_privateXML = tag;
  }

  const std::string& PrivateXML::Query::filterString() const
  {
    static const std::string filter = "/iq/query[@xmlns='" + XMLNS_PRIVATE_XML + "']";
    return filter;
  }

  Tag* PrivateXML::Query::tag() const
  {
    Tag* t = new Tag( "query" );
    t->setXmlns( XMLNS_PRIVATE_XML );
    if( m_privateXML )
      t->addChild( m_privateXML->clone() );
    return t;
  }
  // ---- ~PrivateXML::Query ----

  // ---- PrivateXML ----
  PrivateXML::PrivateXML( ClientBase* parent )
    : m_parent( parent )
  {
    if( !m_parent )
      return;

    m_parent->registerIqHandler( this, ExtPrivateXML );
    m_parent->registerStanzaExtension( new Query() );
  }

  PrivateXML::~PrivateXML()
  {
    if( !m_parent )
      return;

    m_parent->removeIqHandler( this, ExtPrivateXML );
    m_parent->removeIDHandler( this );
    m_parent->removeStanzaExtension( ExtPrivateXML );
  }

  std::string PrivateXML::requestXML( const std::string& tag, const std::string& xmlns,
                                      PrivateXMLHandler* pxh )
  {
    const std::string& id = m_parent->getID();

    IQ iq( IQ::Get, JID(), id );
    iq.addExtension( new Query( tag, xmlns ) );

    m_track[id] = pxh;
    m_parent->send( iq, this, RequestXml );

    return id;
  }

  std::string PrivateXML::storeXML( const Tag* tag, PrivateXMLHandler* pxh )
  {
    const std::string& id = m_parent->getID();

    IQ iq( IQ::Set, JID(), id );
    iq.addExtension( new Query( tag ) );

    m_track[id] = pxh;
    m_parent->send( iq, this, StoreXml );

    return id;
  }

  void PrivateXML::handleIqID( const IQ& iq, int context )
  {
    TrackMap::iterator t = m_track.find( iq.id() );
    if( t == m_track.end() )
      return;

    if( iq.subtype() == IQ::Result )
    {
      if( context == RequestXml )
      {
        const Query* q = iq.findExtension<Query>( ExtPrivateXML );
        if( q )
          (*t).second->handlePrivateXML( q->privateXML() );
      }
      else if( context == StoreXml )
        (*t).second->handlePrivateXMLResult( iq.id(), PrivateXMLHandler::PxmlStoreOk );
    }
    else if( iq.subtype() == IQ::Error )
    {
      if( context == RequestXml )
        (*t).second->handlePrivateXMLResult( iq.id(), PrivateXMLHandler::PxmlRequestError );
      else if( context == StoreXml )
        (*t).second->handlePrivateXMLResult( iq.id(), PrivateXMLHandler::PxmlStoreError );
    }

    m_track.erase( t );
  }

}


text:
.class public interface abstract Lcom/mirrorlink/android/service/IMirrorlinkManager;
.super Ljava/lang/Object;
.source "IMirrorlinkManager.java"

# interfaces
.implements Landroid/os/IInterface;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/mirrorlink/android/service/IMirrorlinkManager$Stub;
    }
.end annotation

# virtual methods
.method public abstract getAllAppList()Ljava/util/List;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/List",
            "<",
            "Ljava/lang/String;",
            ">;"
        }
    .end annotation

    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getApplicationElements(Ljava/lang/String;)Landroid/os/Bundle;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract performRevocation()V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract performRevocationCheck(Ljava/lang/String;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract readTerminalVersion()Z
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract registerListener(Lcom/mirrorlink/android/service/IMirrorlinkListener;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract setDevMode(Z)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract unRegisterListener(Lcom/mirrorlink/android/service/IMirrorlinkListener;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract writeTerminalVersion(Z)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method


text:
// <auto-generated />
using _01._Stud.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using System;

namespace _01.Stud.Migrations
{
    [DbContext(typeof(StudentSystemDbContext))]
    [Migration("20170923084033_InitialCreate")]
    partial class InitialCreate
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "2.0.0-rtm-26452")
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("_01._Stud.Data.Course", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Description");

                    b.Property<DateTime>("EndDate");

                    b.Property<string>("Name")
                        .IsRequired();

                    b.Property<decimal>("Price");

                    b.Property<DateTime>("StartDate");

                    b.HasKey("Id");

                    b.ToTable("Courses");
                });

            modelBuilder.Entity("_01._Stud.Data.Homework", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Content")
                        .IsRequired();

                    b.Property<int>("CourseId");

                    b.Property<int>("StudentId");

                    b.Property<DateTime>("SubmissionDate");

                    b.Property<int>("Type");

                    b.HasKey("Id");

                    b.HasIndex("CourseId");

                    b.HasIndex("StudentId");

                    b.ToTable("Homeworks");
                });

            modelBuilder.Entity("_01._Stud.Data.Resource", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int>("CourseId");

                    b.Property<string>("Name")
                        .IsRequired();

                    b.Property<int>("Type");

                    b.Property<string>("Url")
                        .IsRequired();

                    b.HasKey("Id");

                    b.HasIndex("CourseId");

                    b.ToTable("Resources");
                });

            modelBuilder.Entity("_01._Stud.Data.Student", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<DateTime?>("BirthDay");

                    b.Property<string>("Name")
                        .IsRequired();

                    b.Property<string>("PhoneNumber");

                    b.Property<DateTime>("RegistrationDate");

                    b.HasKey("Id");

                    b.ToTable("Students");
                });

            modelBuilder.Entity("_01._Stud.Data.StudentCourse", b =>
                {
                    b.Property<int>("StudentId");

                    b.Property<int>("CourseId");

                    b.HasKey("StudentId", "CourseId");

                    b.HasIndex("CourseId");

                    b.ToTable("StudentCourse");
                });

            modelBuilder.Entity("_01._Stud.Data.Homework", b =>
                {
                    b.HasOne("_01._Stud.Data.Course", "Course")
                        .WithMany("Homeworks")
                        .HasForeignKey("CourseId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("_01._Stud.Data.Student", "Student")
                        .WithMany("Homeworks")
                        .HasForeignKey("StudentId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("_01._Stud.Data.Resource", b =>
                {
                    b.HasOne("_01._Stud.Data.Course", "Course")
                        .WithMany("Resources")
                        .HasForeignKey("CourseId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("_01._Stud.Data.StudentCourse", b =>
                {
                    b.HasOne("_01._Stud.Data.Course", "Course")
                        .WithMany("Students")
                        .HasForeignKey("CourseId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("_01._Stud.Data.Student", "Student")
                        .WithMany("Courses")
                        .HasForeignKey("StudentId")
                        .OnDelete(DeleteBehavior.Cascade);
                });
#pragma warning restore 612, 618
        }
    }
}


text:
import email.mime.text
from Queue import Queue, Empty
import smtplib
from threading import Thread

from pushmanager.core.settings import Settings

class MailQueue(object):

    message_queue = Queue()
    worker_thread = None
    smtp = None

    @classmethod
    def start_worker(cls):
        if cls.worker_thread is not None:
            return
        cls.worker_thread = Thread(target=cls.process_queue, name='mail-queue')
        cls.worker_thread.daemon = True
        cls.worker_thread.start()

    @classmethod
    def process_queue(cls):
        # We double-nest 'while True' blocks here so that we can
        # try to re-use the same SMTP server connection for batches
        # of emails, but not keep it open for long periods without
        # any emails to send.
        while True:
            # Blocks indefinitely
            send_email_args = cls.message_queue.get(True)
            cls.smtp = smtplib.SMTP('127.0.0.1', 25)
            while True:
                cls._send_email(*send_email_args)
                try:
                    # Only blocks for 5 seconds max, raises Empty if still nothing
                    send_email_args = cls.message_queue.get(True, 5)
                except Empty:
                    # Done with this batch, use a blocking call to wait for the next
                    break
            cls.smtp.quit()

    @classmethod
    def _send_email(cls, recipient, message, subject, from_email):
        msg = email.mime.text.MIMEText(message, 'html')
        msg['Subject'] = subject
        msg['From'] = from_email
        msg['To'] = recipient
        cls.smtp.sendmail(from_email, [recipient], msg.as_string())
        other_recipients = set(Settings['mail']['notifyall']) - set([recipient])
        if other_recipients:
            msg = email.mime.text.MIMEText(message, 'html')
            msg['Subject'] = '[all] %s' % subject
            msg['From'] = Settings['mail']['from']
            msg['To'] = ', '.join(other_recipients)
            cls.smtp.sendmail(from_email, list(other_recipients), msg.as_string())
        cls.message_queue.task_done()

    @classmethod
    def enqueue_email(cls, recipients, message, subject='', from_email=Settings['mail']['from']):
        if isinstance(recipients, (list,set,tuple)):
            # Flatten non-string iterables
            for recipient in recipients:
                cls.enqueue_email(recipient, message, subject, from_email)
        elif isinstance(recipients, (str,unicode)):
            cls.message_queue.put( (recipients, message, subject, from_email) )
        else:
            raise ValueError('Recipient(s) must be a string or iterable of strings')

    @classmethod
    def enqueue_user_email(cls, recipients, *args, **kwargs):
        """Transforms a list of 'user' to 'user@default_domain.com', then invokes enqueue_email."""
        domain = Settings['mail']['default_domain']
        recipients = ['%s@%s' % (recipient, domain) if '@' not in recipient else recipient for recipient in recipients]
        return cls.enqueue_email(recipients, *args, **kwargs)

__all__ = ['MailQueue']


text:
<?php
namespace Application\PaypalExpressCheckoutBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

use Payum\Paypal\ExpressCheckout\Nvp\Bridge\Doctrine\Entity\PaymentDetails as BasePaymentDetails;

/**
 * @ORM\Entity
 */
class PaymentDetails extends BasePaymentDetails
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;
}


text:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@null"
    android:orientation="vertical"
    tools:ignore="RtlHardcoded">

    <LinearLayout
        android:id="@+id/ll_facebook_promotion"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/secondary_background"
        android:orientation="vertical"
        android:visibility="gone">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/iv_facebook"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:contentDescription="@string/description_fb"
                android:padding="@dimen/facebook_padding"
                android:src="@drawable/fb_logo" />

            <TextView
                android:id="@+id/tv_facebook"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:alpha="0.87"
                android:text="@string/text_like_on_fb"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <ImageView
                android:id="@+id/iv_facebook_clear"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:contentDescription="@string/description_close"
                android:gravity="center_vertical"
                android:padding="@dimen/facebook_padding"
                android:src="@drawable/ic_clear_black_24dp" />

        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1px"
            android:layout_gravity="bottom"
            android:background="@color/divider" />

    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_names"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical" />

</LinearLayout>


text:
package com.huatek.unicorn.base.dbaccess.define;

public interface Const {
	public static final int EMPTY_ARRAY_LENGTH = 0;

	public static final String BLANK_STR = "";
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2015, Stratio.
  ~
  ~ Licensed to STRATIO (C) under one or more contributor license agreements.
  ~ See the NOTICE file distributed with this work for additional information
  ~ regarding copyright ownership.  The STRATIO (C) licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~   http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.stratio.cassandra</groupId>
        <artifactId>cassandra-lucene-index-parent</artifactId>
        <version>3.0.14.1-RC1-SNAPSHOT</version>
    </parent>

    <packaging>jar</packaging>
    <artifactId>cassandra-lucene-index-plugin</artifactId>
    <name>Cassandra Lucene Index plugin</name>
    <description>Cassandra Lucene Index plugin</description>

    <dependencies>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>${scala.version}</version>
        </dependency>
        <dependency>
            <groupId>com.typesafe.scala-logging</groupId>
            <artifactId>scala-logging_${scala.binary.version}</artifactId>
            <version>${scala.logging.version}</version>
        </dependency>
        <dependency>
            <groupId>org.scalatest</groupId>
            <artifactId>scalatest_${scala.binary.version}</artifactId>
            <version>${scalatest.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.cassandra</groupId>
            <artifactId>cassandra-all</artifactId>
            <version>${cassandra.version}</version>
        </dependency>
        <dependency>
            <groupId>com.github.rholder</groupId>
            <artifactId>snowball-stemmer</artifactId>
            <version>1.3.0.581.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.lucene</groupId>
            <artifactId>lucene-core</artifactId>
            <version>${lucene.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.lucene</groupId>
            <artifactId>lucene-analyzers-common</artifactId>
            <version>${lucene.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.lucene</groupId>
            <artifactId>lucene-spatial</artifactId>
            <version>${lucene.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.lucene</groupId>
            <artifactId>lucene-queryparser</artifactId>
            <version>${lucene.version}</version>
        </dependency>
        <dependency>
            <groupId>com.vividsolutions</groupId>
            <artifactId>jts-core</artifactId>
            <version>${jts.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>${mockito.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <version>3.0.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <configuration>
                    <args>
                        <arg>-nowarn</arg>
                    </args>
                </configuration>
                <executions>
                    <execution>
                        <id>scala-compile-first</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>add-source</goal>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>scala-test-compile</id>
                        <phase>process-test-resources</phase>
                        <goals>
                            <goal>add-source</goal>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <artifactSet>
                        <includes>
                            <include>org.scala-lang:*</include>
                            <include>com.typesafe.scala-logging:*</include>
                            <include>org.apache.lucene:*</include>
                            <include>com.spatial4j:*</include>
                            <include>com.github.rholder:*</include>
                            <include>com.fasterxml.jackson.core:*</include>
                        </includes>
                    </artifactSet>
                    <createDependencyReducedPom>false</createDependencyReducedPom>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <profiles>
        <profile>
            <id>patch</id>
            <properties>
                <cassandra_home>${project.build.directory}/apache-cassandra-${cassandra.version}</cassandra_home>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.7</version>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <configuration>
                                    <target>
                                        <delete verbose="true">
                                            <fileset dir="${cassandra_home}/lib" includes="${project.artifactId}*.jar"/>
                                        </delete>
                                        <copy file="${project.build.directory}/${project.build.finalName}.jar"
                                              toFile="${cassandra_home}/lib/${project.build.finalName}.jar"/>

                                    </target>
                                </configuration>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>download_and_patch</id>
            <properties>
                <cassandra_home>${project.build.directory}/apache-cassandra-${cassandra.version}</cassandra_home>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.7</version>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <configuration>
                                    <target>
                                        <echo message="Downloading Apache Cassandra"/>
                                        <get src="${archive.apache.url}"
                                             dest="${project.build.directory}/apache-cassandra-${cassandra.version}-bin.tar.gz"/>
                                        <echo message="Uncompressing Apache Cassandra"/>
                                        <gunzip src="${project.build.directory}/apache-cassandra-${cassandra.version}-bin.tar.gz"
                                                dest="${project.build.directory}/apache-cassandra-${cassandra.version}-bin.tar"/>
                                        <delete file="${project.build.directory}/apache-cassandra-${cassandra.version}-bin.tar.gz"/>
                                        <untar src="${project.build.directory}/apache-cassandra-${cassandra.version}-bin.tar"
                                               dest="${project.build.directory}"/>
                                        <delete file="${project.build.directory}/apache-cassandra-${cassandra.version}-bin.tar"/>
                                        <echo message="Patching Apache Cassandra"/>
                                        <copy file="${project.build.directory}/${project.build.finalName}.jar"
                                              toFile="${project.build.directory}/apache-cassandra-${cassandra.version}/lib/${project.build.finalName}.jar"/>
                                        <echo message="Moving Apache Cassandra to ${cassandra_home}"/>
                                        <move file="${project.build.directory}/apache-cassandra-${cassandra.version}"
                                              toFile="${cassandra_home}"/>
                                    </target>
                                </configuration>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
/**
 * Additional {@link java.util.stream.Stream} functionality.
 *
 * @author Richard Lucas
 */
package org.projectomakase.omakase.commons.streams;


text:
package org.apache.bval.jsr.xml;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import javax.validation.ValidationException;
import javax.validation.ValidatorFactory;
import javax.validation.spi.ConfigurationState;

import org.apache.bval.jsr.ApacheValidatorFactory;
import org.apache.bval.jsr.metadata.MetadataBuilder;
import org.apache.bval.jsr.metadata.MetadataBuilder.ForBean;
import org.apache.bval.jsr.metadata.MetadataSource;
import org.apache.bval.jsr.metadata.ValidatorMappingProvider;
import org.apache.bval.jsr.metadata.XmlBuilder;
import org.apache.bval.jsr.metadata.XmlValidationMappingProvider;
import org.apache.bval.util.Exceptions;
import org.apache.bval.util.Validate;
import org.apache.bval.util.reflection.Reflection;
import org.apache.commons.weaver.privilizer.Privilizing;
import org.apache.commons.weaver.privilizer.Privilizing.CallTo;
import org.xml.sax.InputSource;

/**
 * Uses JAXB to parse constraints.xml based on the validation-mapping XML schema.
 */
@Privilizing(@CallTo(Reflection.class))
public class ValidationMappingParser implements MetadataSource {
    private static final SchemaManager SCHEMA_MANAGER = new SchemaManager.Builder()
        .add(XmlBuilder.Version.v10.getId(), "http://jboss.org/xml/ns/javax/validation/mapping",
            "META-INF/validation-mapping-1.0.xsd")
        .add(XmlBuilder.Version.v11.getId(), "http://jboss.org/xml/ns/javax/validation/mapping",
            "META-INF/validation-mapping-1.1.xsd")
        .add(XmlBuilder.Version.v30.getId(), "https://jakarta.ee/xml/ns/validation/mapping",
                "META-INF/validation-mapping-3.0.xsd")
        .add(XmlBuilder.Version.v20.getId(), "http://xmlns.jcp.org/xml/ns/validation/mapping",
            "META-INF/validation-mapping-2.0.xsd")
        .build();

    private ApacheValidatorFactory validatorFactory;

    @Override
    public void initialize(ApacheValidatorFactory validatorFactory) {
        this.validatorFactory = Validate.notNull(validatorFactory);
    }

    @Override
    public void process(ConfigurationState configurationState,
        Consumer<ValidatorMappingProvider> addValidatorMappingProvider, BiConsumer<Class<?>, ForBean<?>> addBuilder) {
        Validate.validState(validatorFactory != null, "validatorFactory unknown");

        if (configurationState.isIgnoreXmlConfiguration()) {
            return;
        }
        final Set<Class<?>> beanTypes = new HashSet<>();
        for (final InputStream xmlStream : configurationState.getMappingStreams()) {
            final ConstraintMappingsType mapping = parseXmlMappings(xmlStream);

            Optional.of(mapping).map(this::toMappingProvider).ifPresent(addValidatorMappingProvider);

            final Map<Class<?>, MetadataBuilder.ForBean<?>> builders =
                new XmlBuilder(validatorFactory, mapping).forBeans();
            if (Collections.disjoint(beanTypes, builders.keySet())) {
                builders.forEach(addBuilder::accept);
                beanTypes.addAll(builders.keySet());
            } else {
                Exceptions.raise(ValidationException::new,
                    builders.keySet().stream().filter(beanTypes::contains).map(Class::getName).collect(Collectors
                        .joining("bean classes specified multiple times for XML validation mapping: [", "; ", "]")));
            }
        }
    }

    /**
     * @param in
     *            XML stream to parse using the validation-mapping-1.0.xsd
     */
    private ConstraintMappingsType parseXmlMappings(final InputStream in) {
        try {
            return SCHEMA_MANAGER.unmarshal(new InputSource(in), ConstraintMappingsType.class);
        } catch (Exception e) {
            throw new ValidationException("Failed to parse XML deployment descriptor file.", e);
        } finally {
            try {
                in.reset(); // can be read several times + we ensured it was
                            // re-readable in addMapping()
            } catch (final IOException e) {
                // no-op
            }
        }
    }

    private ValidatorMappingProvider toMappingProvider(ConstraintMappingsType mapping) {
        if (mapping.getConstraintDefinition().isEmpty()) {
            return null;
        }
        final Map<Class<? extends Annotation>, ValidatedByType> validatorMappings = new HashMap<>();

        for (ConstraintDefinitionType constraintDefinition : mapping.getConstraintDefinition()) {
            final String annotationClassName = constraintDefinition.getAnnotation();

            final Class<?> clazz = loadClass(annotationClassName, mapping.getDefaultPackage());

            Exceptions.raiseUnless(clazz.isAnnotation(), ValidationException::new, "%s is not an annotation",
                annotationClassName);

            final Class<? extends Annotation> annotationClass = clazz.asSubclass(Annotation.class);

            Exceptions.raiseIf(validatorMappings.containsKey(annotationClass), ValidationException::new,
                "XML constraint validator(s) for %s already configured.", annotationClass);

            validatorMappings.put(annotationClass, constraintDefinition.getValidatedBy());
        }
        return new XmlValidationMappingProvider(validatorMappings,
            cn -> toQualifiedClassName(cn, mapping.getDefaultPackage()));
    }

    private Class<?> loadClass(String className, String defaultPackage) {
        final String fqn = toQualifiedClassName(className, defaultPackage);
        try {
            return Reflection.toClass(fqn, Reflection.loaderFromThreadOrClass(ValidationMappingParser.class));
        } catch (ClassNotFoundException ex) {
            throw Exceptions.create(ValidationException::new, ex, "Unable to load class: %s", fqn);
        }
    }

    private String toQualifiedClassName(String className, String defaultPackage) {
        if (!isQualifiedClass(className)) {
            if (className.startsWith("[L") && className.endsWith(";")) {
                className = "[L" + defaultPackage + '.' + className.substring(2);
            } else {
                className = defaultPackage + '.' + className;
            }
        }
        return className;
    }

    private boolean isQualifiedClass(String clazz) {
        return clazz.indexOf('.') >= 0;
    }
}


text:
"""
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
"""
import os
import json
import urllib2
import sys

remote_url = 'https://storage.googleapis.com/udon-media-usa/'

script_dir = os.path.dirname(os.path.abspath(__file__))
videos_dir = os.path.join(script_dir, 'videos')

resolutions = ['1024_848', '512_424', '256_212']

if not os.path.exists(videos_dir):
    os.makedirs(videos_dir)

data_dir = os.path.join(script_dir, '..', 'data', 'sketches')

def gather_paths():
    paths = []

    for dir in os.listdir(data_dir):
        try:
            meta_file = open(os.path.join(data_dir, dir, 'meta.json'), 'r')
        except IOError:
            continue

        meta_json = json.loads(meta_file.read())
        try:
            for res in resolutions:
                for ext in ['mp4', 'webm']:
                    source = remote_url + meta_json['video']['source'] + '/%s/video.%s' % (res, ext)
                    paths.append(source)

        except KeyError:
            continue

    return paths

for remote_path in gather_paths():
    path = remote_path[remote_path.find('videos'):]
    dir_path, _, file_name = path.rpartition('/')
    local_video_path = os.path.join(videos_dir, dir_path.strip(os.sep))
    if not os.path.exists(local_video_path):
        os.makedirs(local_video_path)

    print "Downloading %s..." % remote_path
    try:
        remote_file = urllib2.urlopen(remote_path)
    except urllib2.HTTPError, e:
        print "File %s not found" % remote_path
        continue

    local_video_path_parts = local_video_path.split('/')
    local_video_path = os.path.join(*local_video_path_parts)
    local_video_path_full = os.path.join(local_video_path, file_name)

    if not sys.platform.startswith('win'):
        local_video_path_full = os.sep + local_video_path_full
    print "Download complete. Writing to %s" % local_video_path_full
    local_file = open(local_video_path_full, 'wb+')
    local_file.write(remote_file.read())
    local_file.close()


text:
import * as ts from 'typescript';
import { LinesOfCodeCalculator } from './lines-of-code-calculator';

export class NonBlankLinesOfCodeCalculator implements LinesOfCodeCalculator {
  public result(node: ts.Node, sourceFile: ts.SourceFile): number {
    let host: ts.CompilerHost = ts.createCompilerHost({});
    return sourceFile.text
      .substring(node.pos, node.end)
      .split(host.getNewLine())
      .filter(line => line.trim().length > 0)
      .length;
  }
}


text:
package twitter4j;

import twitter4j.auth.*;
import twitter4j.conf.Configuration;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

import static twitter4j.HttpResponseCode.*;

/**
 * Base class of Twitter / AsyncTwitter / TwitterStream supports OAuth.
 *
 * @author Yusuke Yamamoto - yusuke at mac.com
 */
abstract class TwitterBaseImpl implements TwitterBase, java.io.Serializable, OAuthSupport, OAuth2Support, HttpResponseListener {
    private static final String WWW_DETAILS = "See http://twitter4j.org/en/configuration.html for details";
    private static final long serialVersionUID = -7824361938865528554L;

    Configuration conf;
    private transient String screenName = null;
    private transient long id = 0;

    transient HttpClient http;
    private List<RateLimitStatusListener> rateLimitStatusListeners = new ArrayList<RateLimitStatusListener>(0);

    ObjectFactory factory;

    Authorization auth;

    /*package*/ TwitterBaseImpl(Configuration conf, Authorization auth) {
        this.conf = conf;
        this.auth = auth;
        init();
    }

    private void init() {
        if (null == auth) {
            // try to populate OAuthAuthorization if available in the configuration
            String consumerKey = conf.getOAuthConsumerKey();
            String consumerSecret = conf.getOAuthConsumerSecret();
            // try to find oauth tokens in the configuration
            if (consumerKey != null && consumerSecret != null) {
                if (conf.isApplicationOnlyAuthEnabled()) {
                    OAuth2Authorization oauth2 = new OAuth2Authorization(conf);
                    String tokenType = conf.getOAuth2TokenType();
                    String accessToken = conf.getOAuth2AccessToken();
                    if (tokenType != null && accessToken != null) {
                        oauth2.setOAuth2Token(new OAuth2Token(tokenType, accessToken));
                    }
                    this.auth = oauth2;

                } else {
                    OAuthAuthorization oauth = new OAuthAuthorization(conf);
                    String accessToken = conf.getOAuthAccessToken();
                    String accessTokenSecret = conf.getOAuthAccessTokenSecret();
                    if (accessToken != null && accessTokenSecret != null) {
                        oauth.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));
                    }
                    this.auth = oauth;
                }
            } else {
                this.auth = NullAuthorization.getInstance();
            }
        }
        http = HttpClientFactory.getInstance(conf.getHttpClientConfiguration());
        setFactory();
    }

    void setFactory() {
        factory = new JSONImplFactory(conf);
    }

    @Override
    public String getScreenName() throws TwitterException, IllegalStateException {
        if (!auth.isEnabled()) {
            throw new IllegalStateException(
                    "Neither user ID/password combination nor OAuth consumer key/secret combination supplied");
        }
        if (null == screenName) {
            if (auth instanceof BasicAuthorization) {
                screenName = ((BasicAuthorization) auth).getUserId();
                if (screenName.contains("@")) {
                    screenName = null;
                }
            }
            if (null == screenName) {
                // retrieve the screen name if this instance is authenticated with OAuth or email address
                fillInIDAndScreenName();
            }
        }
        return screenName;
    }

    @Override
    public long getId() throws TwitterException, IllegalStateException {
        if (!auth.isEnabled()) {
            throw new IllegalStateException(
                    "Neither user ID/password combination nor OAuth consumer key/secret combination supplied");
        }
        if (0 == id) {
            fillInIDAndScreenName();
        }
        // retrieve the screen name if this instance is authenticated with OAuth or email address
        return id;
    }

    User fillInIDAndScreenName() throws TwitterException {
        ensureAuthorizationEnabled();
        User user = new UserJSONImpl(http.get(conf.getRestBaseURL() + "account/verify_credentials.json", null, auth, this), conf);
        this.screenName = user.getScreenName();
        this.id = user.getId();
        return user;
    }

    @Override
    public void addRateLimitStatusListener(RateLimitStatusListener listener) {
        rateLimitStatusListeners.add(listener);
    }

    @Override
    public void httpResponseReceived(HttpResponseEvent event) {
        if (rateLimitStatusListeners.size() != 0) {
            HttpResponse res = event.getResponse();
            TwitterException te = event.getTwitterException();
            RateLimitStatus rateLimitStatus;
            int statusCode;
            if (te != null) {
                rateLimitStatus = te.getRateLimitStatus();
                statusCode = te.getStatusCode();
            } else {
                rateLimitStatus = JSONImplFactory.createRateLimitStatusFromResponseHeader(res);
                statusCode = res.getStatusCode();
            }
            if (rateLimitStatus != null) {
                RateLimitStatusEvent statusEvent
                        = new RateLimitStatusEvent(this, rateLimitStatus, event.isAuthenticated());
                if (statusCode == ENHANCE_YOUR_CLAIM
                        || statusCode == SERVICE_UNAVAILABLE
                        || statusCode == TOO_MANY_REQUESTS) {
                    // EXCEEDED_RATE_LIMIT_QUOTA is returned by Rest API
                    // SERVICE_UNAVAILABLE is returned by Search API
                    for (RateLimitStatusListener listener : rateLimitStatusListeners) {
                        listener.onRateLimitStatus(statusEvent);
                        listener.onRateLimitReached(statusEvent);
                    }
                } else {
                    for (RateLimitStatusListener listener : rateLimitStatusListeners) {
                        listener.onRateLimitStatus(statusEvent);
                    }
                }
            }
        }
    }

    @Override
    public final Authorization getAuthorization() {
        return auth;
    }

    @Override
    public Configuration getConfiguration() {
        return this.conf;
    }

    final void ensureAuthorizationEnabled() {
        if (!auth.isEnabled()) {
            throw new IllegalStateException(
                    "Authentication credentials are missing. " + WWW_DETAILS);
        }
    }

    final void ensureOAuthEnabled() {
        if (!(auth instanceof OAuthAuthorization)) {
            throw new IllegalStateException(
                    "OAuth required. Authentication credentials are missing. " + WWW_DETAILS);
        }
    }

    private void writeObject(java.io.ObjectOutputStream out) throws IOException {
        // http://docs.oracle.com/javase/6/docs/platform/serialization/spec/output.html#861
        out.putFields();
        out.writeFields();

        out.writeObject(conf);
        out.writeObject(auth);
        List<RateLimitStatusListener> serializableRateLimitStatusListeners = new ArrayList<RateLimitStatusListener>(0);
        for (RateLimitStatusListener listener : rateLimitStatusListeners) {
            if (listener instanceof java.io.Serializable) {
                serializableRateLimitStatusListeners.add(listener);
            }
        }
        out.writeObject(serializableRateLimitStatusListeners);
    }

    private void readObject(ObjectInputStream stream)
            throws IOException, ClassNotFoundException {
        // http://docs.oracle.com/javase/6/docs/platform/serialization/spec/input.html#2971
        stream.readFields();

        conf = (Configuration) stream.readObject();
        auth = (Authorization) stream.readObject();
        rateLimitStatusListeners = (List<RateLimitStatusListener>) stream.readObject();
        http = HttpClientFactory.getInstance(conf.getHttpClientConfiguration());
        setFactory();
    }

    // methods declared in OAuthSupport interface

    @Override
    public synchronized void setOAuthConsumer(String consumerKey, String consumerSecret) {
        if (null == consumerKey) {
            throw new NullPointerException("consumer key is null");
        }
        if (null == consumerSecret) {
            throw new NullPointerException("consumer secret is null");
        }
        if (auth instanceof NullAuthorization) {
            if (conf.isApplicationOnlyAuthEnabled()) {
                OAuth2Authorization oauth2 = new OAuth2Authorization(conf);
                oauth2.setOAuthConsumer(consumerKey, consumerSecret);
                auth = oauth2;
            } else {
                OAuthAuthorization oauth = new OAuthAuthorization(conf);
                oauth.setOAuthConsumer(consumerKey, consumerSecret);
                auth = oauth;
            }
        } else if (auth instanceof BasicAuthorization) {
            XAuthAuthorization xauth = new XAuthAuthorization((BasicAuthorization) auth);
            xauth.setOAuthConsumer(consumerKey, consumerSecret);
            auth = xauth;
        } else if (auth instanceof OAuthAuthorization || auth instanceof OAuth2Authorization) {
            throw new IllegalStateException("consumer key/secret pair already set.");
        }
    }

    @Override
    public RequestToken getOAuthRequestToken() throws TwitterException {
        return getOAuthRequestToken(null);
    }

    @Override
    public RequestToken getOAuthRequestToken(String callbackUrl) throws TwitterException {
        return getOAuth().getOAuthRequestToken(callbackUrl);
    }

    @Override
    public RequestToken getOAuthRequestToken(String callbackUrl, String xAuthAccessType) throws TwitterException {
        return getOAuth().getOAuthRequestToken(callbackUrl, xAuthAccessType);
    }

    /**
     * {@inheritDoc}
     * Basic authenticated instance of this class will try acquiring an AccessToken using xAuth.

     * In order to get access acquire AccessToken using xAuth, you must apply by sending an email to api@twitter.com all other applications will receive an HTTP 401 error.  Web-based applications will not be granted access, except on a temporary basis for when they are converting from basic-authentication support to full OAuth support.

     * Storage of Twitter usernames and passwords is forbidden. By using xAuth, you are required to store only access tokens and access token secrets. If the access token expires or is expunged by a user, you must ask for their login and password again before exchanging the credentials for an access token.
     *
     * @throws TwitterException When Twitter service or network is unavailable, when the user has not authorized, or when the client application is not permitted to use xAuth
     * @see xAuth | Twitter Developers
     */
    @Override
    public synchronized AccessToken getOAuthAccessToken() throws TwitterException {
        Authorization auth = getAuthorization();
        AccessToken oauthAccessToken;
        if (auth instanceof BasicAuthorization) {
            BasicAuthorization basicAuth = (BasicAuthorization) auth;
            auth = AuthorizationFactory.getInstance(conf);
            if (auth instanceof OAuthAuthorization) {
                this.auth = auth;
                OAuthAuthorization oauthAuth = (OAuthAuthorization) auth;
                oauthAccessToken = oauthAuth.getOAuthAccessToken(basicAuth.getUserId(), basicAuth.getPassword());
            } else {
                throw new IllegalStateException("consumer key / secret combination not supplied.");
            }
        } else {
            if (auth instanceof XAuthAuthorization) {
                XAuthAuthorization xauth = (XAuthAuthorization) auth;
                this.auth = xauth;
                OAuthAuthorization oauthAuth = new OAuthAuthorization(conf);
                oauthAuth.setOAuthConsumer(xauth.getConsumerKey(), xauth.getConsumerSecret());
                oauthAccessToken = oauthAuth.getOAuthAccessToken(xauth.getUserId(), xauth.getPassword());
            } else {
                oauthAccessToken = getOAuth().getOAuthAccessToken();
            }
        }
        screenName = oauthAccessToken.getScreenName();
        id = oauthAccessToken.getUserId();
        return oauthAccessToken;
    }

    @Override
    public synchronized AccessToken getOAuthAccessToken(String oauthVerifier) throws TwitterException {
        AccessToken oauthAccessToken = getOAuth().getOAuthAccessToken(oauthVerifier);
        screenName = oauthAccessToken.getScreenName();
        return oauthAccessToken;
    }

    @Override
    public synchronized AccessToken getOAuthAccessToken(RequestToken requestToken) throws TwitterException {
        OAuthSupport oauth = getOAuth();
        AccessToken oauthAccessToken = oauth.getOAuthAccessToken(requestToken);
        screenName = oauthAccessToken.getScreenName();
        return oauthAccessToken;
    }

    @Override
    public synchronized AccessToken getOAuthAccessToken(RequestToken requestToken, String oauthVerifier) throws TwitterException {
        return getOAuth().getOAuthAccessToken(requestToken, oauthVerifier);
    }

    @Override
    public synchronized void setOAuthAccessToken(AccessToken accessToken) {
        getOAuth().setOAuthAccessToken(accessToken);
    }

    @Override
    public synchronized AccessToken getOAuthAccessToken(String screenName, String password) throws TwitterException {
        return getOAuth().getOAuthAccessToken(screenName, password);
    }
    /* OAuth support methods */

    private OAuthSupport getOAuth() {
        if (!(auth instanceof OAuthSupport)) {
            throw new IllegalStateException(
                    "OAuth consumer key/secret combination not supplied");
        }
        return (OAuthSupport) auth;
    }

    @Override
    public synchronized OAuth2Token getOAuth2Token() throws TwitterException {
        return getOAuth2().getOAuth2Token();
    }

    @Override
    public void setOAuth2Token(OAuth2Token oauth2Token) {
        getOAuth2().setOAuth2Token(oauth2Token);
    }

    @Override
    public synchronized void invalidateOAuth2Token() throws TwitterException {
        getOAuth2().invalidateOAuth2Token();
    }

    private OAuth2Support getOAuth2() {
        if (!(auth instanceof OAuth2Support)) {
            throw new IllegalStateException(
                    "OAuth consumer key/secret combination not supplied");
        }
        return (OAuth2Support) auth;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof TwitterBaseImpl)) return false;

        TwitterBaseImpl that = (TwitterBaseImpl) o;

        if (auth != null ? !auth.equals(that.auth) : that.auth != null)
            return false;
        if (!conf.equals(that.conf)) return false;
        if (http != null ? !http.equals(that.http) : that.http != null)
            return false;
        if (!rateLimitStatusListeners.equals(that.rateLimitStatusListeners))
            return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = conf.hashCode();
        result = 31 * result + (http != null ? http.hashCode() : 0);
        result = 31 * result + rateLimitStatusListeners.hashCode();
        result = 31 * result + (auth != null ? auth.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "TwitterBase{" +
                "conf=" + conf +
                ", http=" + http +
                ", rateLimitStatusListeners=" + rateLimitStatusListeners +
                ", auth=" + auth +
                '}';
    }
}


text:
/*global rg2:false */
(function () {
  function Handle(x, y, time, index) {
    // current position of handles
    this.x = x;
    this.y = y;
    // positions before start of adjustment
    this.basex = x;
    this.basey = y;
    // saved positions to allow undo
    this.undox = x;
    this.undoy = y;
    this.locked = false;
    // not really a time: instead an index into the GPX data
    // this is "time" for 1s intervals, but not if in a different recording mode
    this.time = time;
    this.index = index;
  }

  function Handles() {
    // array of handles used to adjust GPS tracks
    // maintained in time order which means they are also in order along the GPS track
    this.handles = [];
  }

  Handles.prototype = {
    Constructor : Handles,

    addHandle : function (x, y, time) {
      this.handles.push(new Handle(x, y, time, this.handles.length));
      this.handles.sort(function (a, b) {
        return a.time - b.time;
      });
      this.renumberHandles();
    },

    deleteHandle : function (index) {
      if ((index === 0) || (index === this.handles.length - 1)) {
        // can't delete start or finish
        return;
      }
      this.handles.splice(index, 1);
      this.renumberHandles();
    },

    renumberHandles : function () {
      var i;
      for (i = 0; i < this.handles.length; i += 1) {
        this.handles[i].index = i;
      }
    },

    lockHandle : function (index) {
      this.handles[index].locked = true;
    },

    lockHandleByTime : function (time) {
      var i;
      for (i = 0; i < this.handles.length; i += 1) {
        if (this.handles[i].time === time) {
          this.handles[i].locked = true;
        }
      }
    },

    unlockAllHandles : function () {
      var i;
      for (i = 0; i < this.handles.length; i += 1) {
        this.handles[i].locked = false;
      }
    },

    unlockHandle : function (index) {
      this.handles[index].locked = false;
    },

    handlesLocked : function () {
      var i, count;
      count = 0;
      for (i = 0; i < this.handles.length; i += 1) {
        if (this.handles[i].locked) {
          count += 1;
        }
      }
      return count;
    },

    deleteAllHandles : function () {
      this.handles.length = 0;
    },

    rebaselineXY : function () {
      // save new locations at end of drag
      this.copyHandleFields('', 'base');
    },

    saveForUndo : function () {
      this.copyHandleFields('base', 'undo');
    },

    undo : function () {
      // undo last move: reset to saved values
      this.copyHandleFields('undo', 'base');
      this.copyHandleFields('undo', '');
    },

    copyHandleFields : function (from, to) {
      var i;
      for (i = 0; i < this.handles.length; i += 1) {
        this.handles[i][to + 'x'] = this.handles[i][from + 'x'];
        this.handles[i][to + 'y'] = this.handles[i][from + 'y'];
      }
    },

    getStartHandle : function () {
      // always the first entry
      return this.handles[0];
    },

    getFinishHandle : function () {
      // always the last entry
      return this.handles[this.handles.length - 1];
    },

    getHandleClicked : function (pt) {
      // find if the click was on an existing handle: return handle object or undefined
      // basex and basey are handle locations at the start of the drag which is what we are interested in
      var i, distance;
      for (i = 0; i < this.handles.length; i += 1) {
        distance = rg2.utils.getDistanceBetweenPoints(pt.x, pt.y, this.handles[i].basex, this.handles[i].basey);
        if (distance <= rg2.config.HANDLE_DOT_RADIUS) {
          return this.handles[i];
        }
      }
      return undefined;
    },

    getEarliestLockedHandle : function () {
      // called to find earliest locked handle: we already know at least one is locked
      var i;
      for (i = 0; i < this.handles.length; i += 1) {
        if (this.handles[i].locked) {
          return this.handles[i];
        }
      }
    },

    getLatestLockedHandle : function () {
      // called to find latest locked handle: we already know at least one is locked
      var i;
      for (i = this.handles.length - 1; i > 0; i -= 1) {
        if (this.handles[i].locked) {
          return this.handles[i];
        }
      }
    },

    getPreviousLockedHandle : function (handle) {
      // called to find previous locked handle: we already know we are between locked handles
      var i;
      for (i = handle.index - 1; i >= 0; i -= 1) {
        if (this.handles[i].locked) {
          return this.handles[i];
        }
      }
    },

    getNextLockedHandle : function (handle) {
      // called to find next locked handle: we already know we are between locked handles
      var i;
      for (i = handle.index + 1; i < this.handles.length; i += 1) {
        if (this.handles[i].locked) {
          return this.handles[i];
        }
      }
    },

    getSingleLockedHandle : function () {
    // called when we know there is only one locked handle, so we can reuse another function
      return this.getEarliestLockedHandle();
    },

    dragHandles : function (dx, dy) {
      var i;
      for (i = 0; i < this.handles.length; i += 1) {
        this.handles[i].x = this.handles[i].basex + dx;
        this.handles[i].y = this.handles[i].basey + dy;
      }
    },

    drawHandles : function () {
      var i;
      for (i = 0; i < this.handles.length; i += 1) {
        rg2.ctx.lineWidth = 1;
        if (this.handles[i].locked === true) {
          rg2.ctx.fillStyle = rg2.config.RED_30;
          rg2.ctx.strokeStyle = rg2.config.RED;
        } else {
          rg2.ctx.fillStyle = rg2.config.GREEN_30;
          rg2.ctx.strokeStyle = rg2.config.GREEN;
        }
        rg2.ctx.beginPath();
        rg2.ctx.arc(this.handles[i].x, this.handles[i].y, rg2.config.HANDLE_DOT_RADIUS, 0, 2 * Math.PI, false);
        rg2.ctx.fill();
        rg2.ctx.stroke();
      }
    },

    alignHandles : function (points) {
      var i;
      // move handles back to be on adjusted track
      for (i = 0; i < this.handles.length; i += 1) {
        this.handles[i].x = points.x[this.handles[i].time];
        this.handles[i].y = points.y[this.handles[i].time];
      }
    }
  };
  rg2.Handles = Handles;
}());


text:
class wxWindow;

namespace faint{

class Color;
class DialogContext;

const int g_sliderHeight = 40;

class ColorStopSliderImpl;

class LinearGradientSlider{
public:
  LinearGradientSlider(wxWindow* parent,
    const IntSize&,
    LinearGradient&,
    DialogContext&);
  ~LinearGradientSlider();

  wxWindow* AsWindow();
  void SetBackgroundColor(const Color&);
  void UpdateGradient();

private:
  ColorStopSliderImpl* m_impl;
};

class RadialGradientSlider{
public:
  RadialGradientSlider(wxWindow* parent,
    const IntSize&,
    RadialGradient&,
    DialogContext&);
  ~RadialGradientSlider();

  wxWindow* AsWindow();
  void SetBackgroundColor(const Color&);
  void UpdateGradient();

private:
  ColorStopSliderImpl* m_impl;
};

} // namespace

namespace faint{ namespace events{

void on_gradient_slider_change(LinearGradientSlider&,
  const std::function<void()>&);

void on_gradient_slider_change(RadialGradientSlider&,
  const std::function<void()>&);

}} // namespace

#endif


text:
java -cp ../AnyaBasic.jar net.phatcode.rel.main.AnyaBasicMain samples/sample02.abs

pause


text:
title: Cryptography
localeTitle: криптография
---
## криптография

Основная цель криптографии - дать возможность двум людям общаться по незащищенному каналу таким образом, чтобы третий человек не мог понять, что говорится. Этот канал может быть телефонной линией или компьютерной сетью.

Криптография начала использоваться римлянами, чтобы сообщения в битве были нечитаемы противником, если они дешифрованы.

Криптография до современной эпохи была фактически синонимом шифрования, превращения информации из читаемого состояния в очевидную бессмыслицу.

Современная криптография используется в данных, так что только одна сторона или только уполномоченные стороны имеют возможность доступа к информации.

Шифрование на протяжении многих лет стало более совершенным.

### пример

Информация, которую Person1 хочет отправить Person2, которую мы называем «открытым текстом», может быть текстовым, цифровым или любым типом данных. Person1 шифрует открытый текст с использованием предопределенного ключа и отправляет полученный «зашифрованный текст» по каналу. Person3, увидев зашифрованный текст в канале, не может определить, что такое открытый текст, но Person2, который знает ключ шифрования, может расшифровать зашифрованный текст и восстановить открытый текст.

### Цезарь Сифер (Shift Cypher)

Первым известным cypher был Ceasar cypher. Цезарский шифр работает, перемещая буквы «открытого текста» на определенную величину вверх или вниз в алфавите.

С точки зрения внешнего лица сообщение представляется случайными буквами с пробелами между ними.

### Современная криптография

Современное шифрование использует почти случайные числа и математически звуковые функции, чтобы обеспечить безопасную связь. Эти недавно разработанные функциональные возможности не могут быть легко взломаны из-за их структуры, требуя, чтобы даже суперкомпьютеры сотни лет трескались.

Существует два основных типа современного шифрования:

### 1) Симметричное или одно ключевое шифрование:

Симметричное шифрование ключей - это метод шифрования, в котором обе стороны используют только один ключ для шифрования и дешифрования. Эти алгоритмы, благодаря их дизайну, обычно намного быстрее, чем асимметричное или шифрование с открытым ключом.

Некоторые методы симметричного шифрования включают в себя: Стандарт шифрования данных (DES), Стандарт предварительного шифрования (AES), Blow Fish, Two Fish, RC4.

### 2) Асимметричное или публичное шифрование ключей:

Асимметричные алгоритмы шифрования предоставляют каждому пользователю пару ключей: одну общедоступную и одну приватную. Любое сообщение, зашифрованное одним ключом из пары, может быть расшифровано только с другого.

Некоторые асимметричные методы включают: RSA, Diffie-Hellman, DSS (стандарт цифровой подписи), ElGamal.

### Криптографическое Хеширование

Большинство криптографических хэш-функций предназначены для ввода строки любой длины в качестве входных данных и получения хэш-значения фиксированной длины.

Криптографическая хеш-функция должна выдерживать все известные типы криптоаналитической атаки.

### Хрипление криптографии

Криптографическая хеш-функция - это тип хеш-функции, которая также предназначена для односторонней функции (функция, которая требует слишком много времени и ресурсов для перебора). Основная цель хэшей связана с несовместимостью сообщений, поэтому одно и то же сообщение всегда приводит к одному и тому же хэшу.

#### Дополнительная информация:

*   [Криптография: теория и практика Дугласа Стинсона](https://www.crcpress.com/Cryptography-Theory-and-Practice-Third-Edition/Stinson/p/book/9781584885085)
*   [TechTarget для шифрования](http://searchsecurity.techtarget.com/definition/encryption)
*   [Руководство по криптографии](https://www.tutorialspoint.com/cryptography/index.htm)


text:
A PHP implementation of Apache's PDFBox
Requires: PHP Version 5.2 or above.


text:
// ----- this file has been automatically generated - do not edit
import { VariantOptions } from "node-opcua-variant"
import { Int32 } from "node-opcua-basic-types"
import { ExtensionObject } from "node-opcua-extension-object"
import { DTStructure } from "node-opcua-nodeset-ua/source/dt_structure"
import { DTResultId } from "./dt_result_id"
import { DTMeasId } from "./dt_meas_id"
import { DTPartId } from "./dt_part_id"
import { DTRecipeIdExternal } from "./dt_recipe_id_external"
import { DTRecipeIdInternal } from "./dt_recipe_id_internal"
import { DTProductId } from "./dt_product_id"
import { DTConfigurationId } from "./dt_configuration_id"
import { DTJobId } from "./dt_job_id"
import { DTProcessingTimes } from "./dt_processing_times"
/**
 * |           |                                                  |
 * |-----------|--------------------------------------------------|
 * | namespace |http://opcfoundation.org/UA/MachineVision         |
 * | nodeClass |DataType                                          |
 * | name      |4:ResultDataType                                  |
 * | isAbstract|false                                             |
 */
export interface DTResult extends DTStructure {
  /** System-wide unique identifier, which is assigned by the system. This ID can be used for fetching exactly this result using the pertinent result management methods and it is identical to the ResultId of the ResultReadyEventType.*/
  resultId: DTResultId; // ExtensionObject ns=4;i=3021
  /** Indicates that additional data for this result can be retrieved by temporary file transfer.*/
  hasTransferableDataOnFile?: boolean; // Boolean ns=0;i=1
  /** Indicates whether the result is the partial result of a total result.*/
  isPartial: boolean; // Boolean ns=0;i=1
  /** Indicates whether the system was in simulation mode when the result was created.*/
  isSimulated?: boolean; // Boolean ns=0;i=1
  /** ResultState provides information about the current state of a result and the ResultStateDataType is defined in Section 12.18.*/
  resultState: Int32; // Int32 ns=4;i=3009
  /** This identifier is given by the client when starting a single job or continuous execution and transmitted to the vision system. It is used to identify the respective result data generated for this job. Although the system-wide unique JobId would be sufficient to identify the job which the result belongs to, this makes for easier filtering on the part of the client without keeping track of JobIds.*/
  measId?: DTMeasId; // ExtensionObject ns=4;i=3015
  /** A PartId is given by the client when starting the job; although the system-wide unique JobId would be sufficient to identify the job which the result belongs to, this makes for easier filtering on the part of the client without keeping track of JobIds.*/
  partId?: DTPartId; // ExtensionObject ns=4;i=3004
  /** External Id of the recipe in use which produced the result. The ExternalID is only managed by the environment.*/
  externalRecipeId?: DTRecipeIdExternal; // ExtensionObject ns=4;i=3002
  /** Internal Id of the recipe in use which produced the result. This ID is system-wide unique and is assigned by the vision system.*/
  internalRecipeId: DTRecipeIdInternal; // ExtensionObject ns=4;i=3013
  /** productId which was used to trigger the job which created the result.*/
  productId?: DTProductId; // ExtensionObject ns=4;i=3003
  /** External Id of the configuration in use which produced the result. The ExternalID is only managed by the environment.*/
  externalConfigurationId?: DTConfigurationId; // ExtensionObject ns=4;i=3008
  /** Internal Id of the configuration in use which produced the result. This ID is system-wide unique and is assigned by the vision system.*/
  internalConfigurationId: DTConfigurationId; // ExtensionObject ns=4;i=3008
  /** The ID of the job, created by the transition from state Ready to state SingleExecution or to state ContinuousExecution which produced the result.*/
  jobId: DTJobId; // ExtensionObject ns=4;i=3016
  /** CreationTime indicates the time when the result was created.*/
  creationTime: Date; // DateTime ns=0;i=294
  /** Collection of different processing times that were needed to create the result.*/
  processingTimes?: DTProcessingTimes; // ExtensionObject ns=4;i=3005
  /** Abstract data type to be subtyped from to hold result data created by the selected recipe.*/
  resultContent?: VariantOptions[]; // Variant ns=0;i=0
}
export interface UDTResult extends ExtensionObject, DTResult {};


text:
/**
 * \addtogroup sys
 * @{
 */

/**
 * \defgroup ctimer Callback timer
 * @{
 *
 * The ctimer module provides a timer mechanism that calls a specified
 * C function when a ctimer expires.
 *
 */

/*
 * Copyright (c) 2006, Swedish Institute of Computer Science.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the Institute nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * This file is part of the Contiki operating system.
 *
 */

/**
 * \file
 *         Header file for the callback timer
 * \author
 *         Adam Dunkels <adam@sics.se>
 */

#ifndef __CTIMER_H__
#define __CTIMER_H__

#include "sys/etimer.h"

struct ctimer {
  struct ctimer *next;
  struct etimer etimer;
  struct process *p;
  void (*f)(void *);
  void *ptr;
};

/**
 * \brief      Reset a callback timer with the same interval as was
 *             previously set.
 * \param c    A pointer to the callback timer.
 *
 *             This function resets the callback timer with the same
 *             interval that was given to the callback timer with the
 *             ctimer_set() function. The start point of the interval
 *             is the exact time that the callback timer last
 *             expired. Therefore, this function will cause the timer
 *             to be stable over time, unlike the ctimer_restart()
 *             function.
 *
 * \sa ctimer_restart()
 */
void ctimer_reset(struct ctimer *c);

/**
 * \brief      Restart a callback timer from the current point in time
 * \param c    A pointer to the callback timer.
 *
 *             This function restarts the callback timer with the same
 *             interval that was given to the ctimer_set()
 *             function. The callback timer will start at the current
 *             time.
 *
 *             \note A periodic timer will drift if this function is
 *             used to reset it. For periodic timers, use the
 *             ctimer_reset() function instead.
 *
 * \sa ctimer_reset()
 */
void ctimer_restart(struct ctimer *c);

/**
 * \brief      Set a callback timer.
 * \param c    A pointer to the callback timer.
 * \param t    The interval before the timer expires.
 * \param f    A function to be called when the timer expires.
 * \param ptr  An opaque pointer that will be supplied as an argument to the callback function.
 *
 *             This function is used to set a callback timer for a time
 *             sometime in the future. When the callback timer expires,
 *             the callback function f will be called with ptr as argument.
 *
 */
void ctimer_set(struct ctimer *c, clock_time_t t,
		void (*f)(void *), void *ptr);

/**
 * \brief      Stop a pending callback timer.
 * \param c    A pointer to the pending callback timer.
 *
 *             This function stops a callback timer that has previously
 *             been set with ctimer_set(), ctimer_reset(), or ctimer_restart().
 *             After this function has been called, the callback timer will be
 *             expired and will not call the callback function.
 *
 */
void ctimer_stop(struct ctimer *c);

/**
 * \brief      Check if a callback timer has expired.
 * \param c    A pointer to the callback timer
 * \return     Non-zero if the timer has expired, zero otherwise.
 *
 *             This function tests if a callback timer has expired and
 *             returns true or false depending on its status.
 */
int ctimer_expired(struct ctimer *c);

/**
 * \brief      Initialize the callback timer library.
 *
 *             This function initializes the callback timer library and
 *             should be called from the system boot up code.
 */
void ctimer_init(void);

#endif /* __CTIMER_H__ */
/** @} */
/** @} */