text:
( function ( RAIMEI ){
    "use strict";

    RAIMEI.EventDispatcher = function () {
        /**
         * @class EventDispatcher
         * @constructor
         */
        function EventDispatcher () {
            this._listeners = {};
        }

        var p = EventDispatcher.prototype;

        p.constructor = RAIMEI.EventDispatcher;

        /**
         * @method addEventListener
         * @param {String} type event type
         * @param {Function} listener Event Handler
         */
        p.addEventListener = function ( type, listener ) {

            if ( typeof this._listeners === "undefined" ) {

                this._listeners = {};
            }

            var listeners = this._listeners;

            if ( typeof listeners[ type ] === "undefined" ) {

                listeners[ type ] = [];
            }

            if ( listeners[ type ].indexOf( listener ) === -1 ) {

                listeners[ type ].push( listener );
            }
        };

        /**
         * @method hasEventListener
         * @param {String} type event type
         * @param {Function} listener Event Handler
         * @returns {boolean}
         */
        p.hasEventListener = function ( type, listener ) {

            var listeners = this._listeners;

            if ( typeof listeners === "undefined" ) {

                return false;
            } else if ( typeof listener[ type ] !== "undefined" && listeners[ type ].indexOf( listener ) !== -1 ) {

                return true;
            }

            return false;
        };

        p.removeEventListener = function ( type, listener ) {
            if ( typeof this._listeners === "undefined" ) {

                return;
            }

            var listeners = this._listeners,
                listeners_types = listeners[ type ],
                index;

            if ( typeof listeners_types !== "undefined" ) {

                index = listeners_types.indexOf( listener );

                if ( index !== -1 ) {

                    listeners_types.splice( index, 1 );
                }
            }
        };

        /**
         * @method dispatchEvent
         * @param {Object} event require event.type:String
         */
        p.dispatchEvent = function ( event ) {
            var listeners = this._listeners,
                listeners_types,
                i, limit;

            if ( typeof listeners === "undefined" || typeof event.type === "undefined" ) {

                return;
            }

            listeners_types = listeners[ event.type ];

            if ( typeof listeners_types !== "undefined" ) {

                event.target = this;

                for ( i = 0, limit = listeners_types.length; i < limit; i++ ) {

                    listeners_types[ i ].call( this, event );
                }
            }
        };

        /**
         * @method initialize
         * @param {Object} object
         * @static
         */
        EventDispatcher.initialize = function ( object ) {
            object.addEventListener = p.addEventListener;
            object.hasEventListener = p.hasEventListener;
            object.removeEventListener = p.removeEventListener;
            object.dispatchEvent = p.dispatchEvent;
        };

        return EventDispatcher;
    }();

}( window.RAIMEI ) );


text:
namespace Microsoft.Azure.Management.Batch
{
    using System.Threading.Tasks;
   using Microsoft.Rest.Azure;
   using Models;

    /// <summary>
    /// Extension methods for LocationOperations.
    /// </summary>
    public static partial class LocationOperationsExtensions
    {
            /// <summary>
            /// Gets the Batch service quotas for the specified subscription at the given
            /// location.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='locationName'>
            /// The desired region for the quotas.
            /// </param>
            public static BatchLocationQuota GetQuotas(this ILocationOperations operations, string locationName)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((ILocationOperations)s).GetQuotasAsync(locationName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Gets the Batch service quotas for the specified subscription at the given
            /// location.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='locationName'>
            /// The desired region for the quotas.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async System.Threading.Tasks.Task<BatchLocationQuota> GetQuotasAsync(this ILocationOperations operations, string locationName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.GetQuotasWithHttpMessagesAsync(locationName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

    }
}

redpajama_set_name: RedPajamaGithub


text:
import re

from flask_wtf import FlaskForm
from wtforms.fields import TextField
from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField
from purchasing.users.models import Department
from flask_security.forms import RegisterForm
from purchasing.public.models import AcceptedEmailDomains
from purchasing.users.models import Role

DOMAINS = re.compile('@[\w.]+')

class DepartmentForm(FlaskForm):
    '''Allows user to update profile information

    Attributes:
        department: sets user department based on choice of available
            departments or none value
        first_name: sets first_name value based on user input
        last_name: sets last_name value based on user input
    '''
    department = QuerySelectField(
        query_factory=Department.query_factory,
        get_pk=lambda i: i.id,
        get_label=lambda i: i.name,
        allow_blank=True, blank_text='-----'
    )
    first_name = TextField()
    last_name = TextField()

class ExtendedRegisterForm(RegisterForm):
    '''Custom registration form to enforce accepted emails

    Attributes:
        pass
    '''
    roles = QuerySelectMultipleField(
        query_factory=Role.staff_factory,
        get_pk=lambda i: i.id,
        get_label=lambda i: i.name
    )

    def __init__(self, *args, **kwargs):
        super(ExtendedRegisterForm, self).__init__(*args, **kwargs)
        if not self.roles.data:
            self.roles.data = [Role.query.filter(Role.name == 'staff').first()]

    def validate(self):
        if not super(ExtendedRegisterForm, self).validate():
            return False

        domain = re.search(DOMAINS, self.email.data)
        domain_text = domain.group().lstrip('@')
        if not all([domain, AcceptedEmailDomains.valid_domain(domain_text)]):
            self.email.errors.append(
                "That's not a valid email domain! You must be associated with the city."
            )
            return False
        return True


text:
#include "FPNode.h"
#include "FPTree.h"
#include <algorithm>
#include <stdint.h>

using namespace std;

FPNode::~FPNode() {
  if (!IsRoot()) {
    // This is a regular node, it's also appears in the linked list in
    // the header table. Remove node from the header table.
    if (!prev) {
      // This node is the first entry in header table.
      if (next) {
        // We have a next, set the first entry to that.
        HeaderTable().Set(item, next);
        next->prev = nullptr;
      } else {
        // No next, just erase the entry for this item.
        HeaderTable().Erase(item);
      }
    } else {
      if (next) {
        next->prev = prev;
      }
      prev->next = next;
    }
    if (IsLeaf()) {
      ASSERT(leafToken.IsInList());
      Leaves().Erase(leafToken);
      ASSERT(!leafToken.IsInList());
    }
    if (count) {
      Decrement(count);
    }
  }
  // Delete our child trees.
  map<Item, FPNode*>::iterator itr = children.begin();
  while (itr != children.end()) {
    delete itr->second;
    itr++;
  }
  children.clear();
}

string FPNode::ToString() const {
  string s("(");
  s.append(item.IsNull() ? "root" : item);
  s.append(":");
  s.append(std::to_string(count));

  map<Item, FPNode*>::const_iterator itr = children.begin();
  while (itr != children.end()) {
    s.append(" ");
    s.append(itr->second->ToString());
    itr++;
  }
  s.append(")");
  return s;
}

string FPNode::ToString(uint32_t stopDepth) const {
  if (depth >= stopDepth) {
    return string("");
  }
  string s("(");
  s.append(item.IsNull() ? "root" : item);
  s.append(":");
  s.append(std::to_string(count));

  map<Item, FPNode*>::const_iterator itr = children.begin();
  while (itr != children.end()) {
    s.append(" ");
    s.append(itr->second->ToString());
    itr++;
  }
  s.append(")");
  return s;
}

void FPNode::ToFile(char* fn) {
  ofstream fp(fn);
  string s = this->ToString();
  if (fp.is_open()) {
    fp << s;
  } else {
    cerr << "FPNode::ToFile File is not open.\n";
  }
}

void FPNode::ToFile(char* fn, uint32_t stopDepth) {
  ofstream fp(fn);
  string s = this->ToString(stopDepth);
  if (fp.is_open()) {
    fp << s;
  } else {
    cerr << "FPNode::ToFile File is not open.\n";
  }
}
bool FPNode::ToVector(vector<int32_t>* v) const {
  v->push_back(item.IsNull() ? 0 : item.GetId());
  map<Item, FPNode*>::const_iterator itr = children.begin();
  while (itr != children.end()) {
    itr->second->ToVector(v);
    itr++;
  }
  return true;
}

bool FPNode::ToVector(uint32_t stopDepth, vector<int32_t>* v) const {
  if (depth >= stopDepth) {
    return false;
  }
  v->push_back(item.IsNull() ? 0 : item.GetId());
  map<Item, FPNode*>::const_iterator itr = children.begin();
  while (itr != children.end()) {
    itr->second->ToVector(stopDepth, v);
    itr++;
  }
  return true;
}

bool FPNode::ToVector(vector<CmpNode>* v) const {
  CmpNode n;
  n.nId = item.IsNull() ? -1 : item.GetId();
  n.nDepth = depth;
  n.nCount = count;
  v->push_back(n);
  map<Item, FPNode*>::const_iterator itr = children.begin();
  while (itr != children.end()) {
    itr->second->ToVector(v);
    itr++;
  }
  return true;
}

bool FPNode::ToVector(uint32_t stopDepth, vector<CmpNode>* v) const {
  if (depth >= stopDepth) {
    return false;
  }
  CmpNode  p;
  p.nId = item.IsNull() ? -1 : item.GetId();
  p.nDepth = depth;
  p.nCount = count;
  v->push_back(p);
  map<Item, FPNode*>::const_iterator itr = children.begin();
  while (itr != children.end()) {
    itr->second->ToVector(stopDepth, v);
    itr++;
  }
  return true;
}

unsigned FPNode::NumNodes() const {
  unsigned n = 1; // for this node...
  map<Item, FPNode*>::const_iterator itr = children.begin();
  while (itr != children.end()) {
    FPNode* node = itr->second;
    n += node->NumNodes();
    itr++;
  }
  return n;
}

void FPNode::DumpToGraphViz(const char* filename) const {
  FILE* f = fopen(filename, "w");
  ASSERT(f);
  fprintf(f, "digraph G {\n");
  fprintf(f, "\troot;\n");
  DumpToGraphViz(f, "root");
  fprintf(f, "}\n");
  fclose(f);
}

void FPNode::DumpToGraphViz(FILE* f, string parent) const {
  map<Item, FPNode*>::const_iterator itr = children.begin();
  while (itr != children.end()) {
    FPNode* child = itr->second;
    string name = (string)child->item;
    string nodeName = parent + "_" + name;

    fprintf(f, "\t%s [label=\"%s:%d\"];\n", nodeName.c_str(), name.c_str(), child->count);

    fprintf(f, "\t%s -> %s;\n", parent.c_str(), nodeName.c_str());
    child->DumpToGraphViz(f, nodeName);
    itr++;
  }
}

bool VerifySortedByFreqAppearance(const vector<Item>& v,
                                  const ItemMap<unsigned>& freq) {
  for (unsigned i = 1; i < v.size(); i++) {
    Item prev = v[i - 1];
    Item curr = v[i];

    unsigned curCount = freq.Get(curr, 0);
    unsigned prevCount = freq.Get(prev, 0);
    if (prevCount < curCount) {
      return false;
    }
    if (prevCount == curCount &&
        v[i - 1].GetId() > v[i].GetId()) {
      return false;
    }
  }
  return true;
}

void FPNode::SortTransaction(vector<Item>& transaction) {
  if (!FrequencyTableAtLastSort().IsEmpty()) {
    ItemMapCmp<unsigned> cmp(FrequencyTableAtLastSort());
    sort(transaction.begin(), transaction.end(), cmp);
    ASSERT(VerifySortedByFreqAppearance(transaction, FrequencyTableAtLastSort()));
  } else {
    AppearanceCmp cmp;
    sort(transaction.begin(), transaction.end(), cmp);
    ASSERT(VerifySortedByAppearance(transaction));
  }
}

FPNode* FPNode::GetChild(Item aItem) const
{
  map<Item, FPNode*>::const_iterator itr = children.find(aItem);
  return (itr != children.end()) ? itr->second : nullptr;
}

FPNode* FPNode::GetOrCreateChild(Item aItem)
{
  FPNode* node = GetChild(aItem);
  if (!node) {
    // Item is not in child list, create a new node for it.
    node = new FPNode(mTree, aItem, this, 0, depth + 1);
    ASSERT(node->leafToken.IsInList());

    if (!IsRoot() && IsLeaf()) {
      // We're about to add a child node, so we'll stop being a leaf.
      // Remove us from the leaves list.
      ASSERT(leafToken.IsInList());
      Leaves().Erase(leafToken);
      ASSERT(!leafToken.IsInList());
    }
    children[aItem] = node;
    ASSERT(!IsLeaf());

    // Add new item to the headerTable.
    AddToHeaderTable(node);
  }
  return node;
}

void FPNode::Insert(std::vector<Item>::const_iterator aBegin,
                    std::vector<Item>::const_iterator aEnd,
                    unsigned aCount) {
  FPNode* parent = this;
  for (; aBegin != aEnd; aBegin++) {
    Item item = *aBegin;
    FPNode* node = parent->GetOrCreateChild(item);
    node->count += aCount;
    FrequencyTable().Increment(item, aCount);
    parent = node;
  }
}

void FPNode::Remove(const std::vector<Item>& path)
{
  Remove(path.begin(), path.end(), 1);
}

void FPNode::Decrement(uint32_t aCount)
{
  ASSERT(count >= aCount);
  count -= aCount;
  ASSERT(FrequencyTable().Get(item) >= aCount);
  ASSERT(FrequencyTable().Contains(item));
  FrequencyTable().Decrement(item, aCount);
}

void FPNode::Remove(std::vector<Item>::const_iterator aPathBegin,
                    std::vector<Item>::const_iterator aPathEnd,
                    unsigned aCount)
{
  // Traverse path, and decrement frequency. If we lower a node to count 0,
  // we can stop and delete the remainder of the subtree/path.
  FPNode* parent = this;
  for (auto pathItr = aPathBegin; pathItr != aPathEnd; pathItr++) {
    Item item = *pathItr;
    auto itr = parent->children.find(item);
    ASSERT(itr != parent->children.end());
    FPNode* node = itr->second;
    ASSERT(node);

    ASSERT(node->count >= aCount);
    node->Decrement(aCount);

    if (node->count == 0) {
      // End of the line! No more children can have non-zero path.
      ASSERT(node->parent == parent);
      parent->children.erase(itr);
      if (parent->children.size() == 0 && !parent->IsRoot()) {
        parent->leafToken = Leaves().Append(parent);
      }
      delete node;
      break;
    }
    parent = node;
  }
}

static bool NotInList(const FPNode* node, const FPNode* list) {
  const FPNode* next = list;
  while (true) {
    if (!node || !next) {
      return true;
    }
    if (node == next) {
      return false;
    }
    next = next->next;
  }
}

void FPNode::AddToHeaderTable(FPNode* node) {
  if (HeaderTable().Contains(node->item)) {
    FPNode* list = HeaderTable().Get(node->item);
    node->next = list;
    ASSERT(!list->prev);
    list->prev = node;
  } else {
    ASSERT(!node->prev);
    ASSERT(!node->next);
  }
  HeaderTable().Set(node->item, node);
}

bool FPNode::DoIsSorted() const {
  ASSERT(!IsRoot());
  map<Item, FPNode*>::const_iterator itr = children.begin();
  while (itr != children.end()) {
    Item childItem = itr->first;
    unsigned f = FrequencyTable().Get(item, 0);
    unsigned cf = FrequencyTable().Get(childItem, 0);
    if (cf == f && item.GetId() > childItem.GetId()) {
      ASSERT(false);
      return false;
    }
    if (cf > f) {
      ASSERT(false);
      return false;
    }
    FPNode* childNode = itr->second;
    if (!childNode->DoIsSorted()) {
      ASSERT(false);
      return false;
    }
    itr++;
  }
  return true;
}

bool FPNode::IsSorted() const {
  if (IsRoot()) {
    map<Item, FPNode*>::const_iterator itr = children.begin();
    while (itr != children.end()) {
      Item item = itr->first;
      FPNode* child = itr->second;
      if (!child->DoIsSorted()) {
        ASSERT(false);
        return false;
      }
      itr++;
    }
    return true;
  } else {
    return DoIsSorted();
  }
}

void FPNode::DumpFreq() const {
  ItemMap<unsigned>::Iterator itr = FrequencyTable().GetIterator();
  while (itr.HasNext()) {
    Item item = itr.GetKey();
    unsigned count = itr.GetValue();
    printf("%s %u\n", ((string)item).c_str(), count);
    itr.Next();
  }
}

TreePathIterator::TreePathIterator(FPTree* aTree)
  : root(aTree->GetRoot())
  , itr(aTree->Leaves().Begin())
{
}

bool TreePathIterator::GetNext(std::vector<Item>& path, unsigned& count) {
  path.clear();
  if (!itr->HasNext()) {
    return false;
  }
  FPNode* leaf = itr->Next();
  ASSERT(leaf);
  ASSERT(leaf->IsLeaf());
  count = leaf->count;

  // Construct the path back to the root.
  uint32_t depth = leaf->depth;
  path.resize(depth);
  FPNode* n = leaf;
  uint32_t pos = depth - 1;
  while (!n->IsRoot()) {
    path[pos] = n->item;
    pos--;
    n = n->parent;
    ASSERT(pos < path.size() || n->IsRoot());
  }

  return true;
}

void FPNode::Sort() {
  // Only call on the root!
  ASSERT(IsRoot());

  FrequencyTableAtLastSort() = FrequencyTable();
  ItemMapCmp<unsigned> cmp(FrequencyTable());
  Sort(&cmp);
}

void FPNode::Sort(ItemComparator* cmp) {
  DurationTimer timer;

  // Only call on the root!
  ASSERT(IsRoot());

  // We can't pass a virtual function pointer to std::sort. :(
  struct ConcreteItemComparator {
    ConcreteItemComparator(ItemComparator* comparator)
      : mCmp(comparator) {}
    bool operator()(const Item a, const Item b) {
      return (*mCmp)(a, b);
    }
    ItemComparator* mCmp;
  };
  ConcreteItemComparator comparator(cmp);

  TreePathIterator itr(mTree);
  vector<Item> path;
  unsigned count;
  while (itr.GetNext(path, count)) {
    // Sort path as per comparator passed in.
    vector<Item> spath(path.begin(), path.end());
    sort(spath.begin(), spath.end(), comparator);
    if (spath != path) {
      // Path after sort is different. We need to replace the now
      // unsorted path in the tree with a sorted path.
      Replace(path, spath, count);
    }
  }
  ASSERT(IsSorted());

  Log("Sort took %.3lfs\n", timer.Seconds());
}

void FPNode::Replace(const vector<Item>& from,
                     const vector<Item>& to,
                     uint32_t count)
{
  ASSERT(IsRoot());

  // Walk down the two paths to find where they differ, then we only need to
  // remove and reinsert the difference in path.
  FPNode* node = this;
  ASSERT(from.size() == to.size());
  size_t index = 0;
  while (index < from.size()) {
    if (from[index] != to[index]) {
      break;
    }
    node = node->GetChild(from[index]);
    ASSERT(node);
    index++;
  }

  node->Remove(from.begin() + index, from.end(), count);
  node->Insert(to.begin() + index, to.end(), count);
}

ItemMap<FPNode*>&
FPNode::HeaderTable() const {
  ASSERT(mTree);
  return mTree->HeaderTable();
}

ItemMap<unsigned>&
FPNode::FrequencyTable() const {
  ASSERT(mTree);
  return mTree->FrequencyTable();
}

ItemMap<unsigned>&
FPNode::FrequencyTableAtLastSort() const {
  ASSERT(mTree);
  return mTree->FrequencyTableAtLastSort();
}

List<FPNode*>&
FPNode::Leaves() const {
  ASSERT(mTree);
  return mTree->Leaves();
}


text:
package org.foo.find;

import org.apache.camel.component.connector.DefaultConnectorComponent;

/**
 * Camel twitter-find connector
 */
public class TwitterFindComponent extends DefaultConnectorComponent {

    public TwitterFindComponent() {
        super("twitter-find", "org.foo.find.TwitterFindComponent");
    }

    public TwitterFindComponent(String componentScheme) {
        super("twitter-find", componentScheme, "org.foo.find.TwitterFindComponent");
    }

}


text:
require 'new_relic/control/frameworks/rails'
require 'new_relic/rack/error_collector'
module NewRelic
  class Control
    module Frameworks
      # Control subclass instantiated when Rails is detected.  Contains
      # Rails 3.0+  specific configuration, instrumentation, environment values,
      # etc. Many methods are inherited from the
      # NewRelic::Control::Frameworks::Rails class, where the two do
      # not differ
      class Rails3 < NewRelic::Control::Frameworks::Rails

        def env
          @env ||= ::Rails.env.to_s
        end

        def rails_root
          ::Rails.root.to_s
        end

        def init_config(options={})
          super
          if Agent.config[:agent_enabled] && Agent.config[:'error_collector.enabled']
            if !rails_config.middleware.respond_to?(:include?) ||
                !rails_config.middleware.include?(NewRelic::Rack::ErrorCollector)
              add_error_collector_middleware
            end
          end
        end

        def add_error_collector_middleware
          rails_config.middleware.use NewRelic::Rack::ErrorCollector
        end

        def vendor_root
          @vendor_root ||= File.join(root,'vendor','rails')
        end

        def version
          @rails_version ||= NewRelic::VersionNumber.new(::Rails::VERSION::STRING)
        end

        protected

        def install_shim
          super
          ActiveSupport.on_load(:action_controller) do
            include NewRelic::Agent::Instrumentation::ControllerInstrumentation::Shim
          end
        end
      end
    end
  end
end


text:
//
//  Length.h
//  iPhoneApp
//
//  Created by Z.S. on 2/4/11.
//  Copyright 2011 deCarta, Inc. All rights reserved.
//

#import <Foundation/Foundation.h>

/*!
 * @ingroup Map
 * Units of Measure enumerated data type */
typedef enum {
	M, /**< Meters */
	KM, /**< Kilometers */
	MI /**< Miles */
} UOM;

/*!
 * @ingroup Map
 * @class deCartaLength
 * An object representing a real-world distance. This class contains both the
 * measurement and the corresponding units of measure.
 * @brief Real-world distance (in M, KM, or MI)
 */
@interface deCartaLength : NSObject {
        /*! Distance as a double-precision floating-point number */
	double _distance;

	/*! Units of measure (M, KM, MI) */
	UOM _uom;
}

/*! Distance as a double-precision floating-point number */
@property(nonatomic,assign) double distance;

/*! Units of measure (M, KM, MI) */
@property(nonatomic,assign) UOM uom;

/*!
 * Initialize the deCartaLength object with a distance and unit of measure.
 * @param distance Distance as a double-precision floating-point number.
 * @param uom Unit of measure: M, KM, or MI
 * @return Objective-C ID of the returned deCartaLength object
 */
-(id)initWithDistance:(double)distance andUOM:(UOM)uom;

/*!
 * Converts a deCartaLength object from it's current unit of measure (M, KM, or MI)
 * to Meters
 * @return The deCartaLength, converted to length in meters
 */
-(double)toMeters;

@end


text:
package org.apache.wink.common.model.app;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;

import junit.framework.TestCase;

import org.apache.wink.common.RestException;
import org.apache.wink.common.internal.i18n.Messages;
import org.apache.wink.common.internal.model.ModelUtils;
import org.apache.wink.common.internal.utils.JAXBUtils;
import org.apache.wink.common.model.atom.AtomCategory;
import org.apache.wink.common.model.atom.AtomText;
import org.apache.wink.test.mock.TestUtils;

public class AppTest extends TestCase {

    private static final String SERVICE_DOCUMENT =
                                                     "<service xml:lang=\"en-us\" xml:base=\"http://base/service\" anyAttirbService=\"anyAttribValueService\" xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns=\"http://www.w3.org/2007/app\">\n" + "    <workspace xml:lang=\"en-us\" xml:base=\"http://base/workspace\" anyAttirbWorkspace=\"anyAttribValueWorkspace\">\n"
                                                         + "        <atom:title type=\"text\">workspace1</atom:title>\n"
                                                         + "        <collection href=\"href1\" xml:lang=\"en-us\" xml:base=\"http://base/collection\" anyAttirbCollection=\"anyAttribValueCollection\">\n"
                                                         + "            <atom:title type=\"text\">collection1</atom:title>\n"
                                                         + "            <accept>accept1</accept>\n"
                                                         + "            <accept>accept2</accept>\n"
                                                         + "            <categories scheme=\"scheme\" fixed=\"no\">\n"
                                                         + "                <atom:category label=\"label\" scheme=\"scheme1\" term=\"term1\"/>\n"
                                                         + "                <atom:category label=\"labe2\" scheme=\"scheme2\" term=\"term2\"/>\n"
                                                         + "            </categories>\n"
                                                         + "            <categories href=\"href\"/>\n"
                                                         + "        </collection>\n"
                                                         + "        <collection href=\"href2\" xml:lang=\"en-us\" xml:base=\"http://base/collection\" anyAttirbCollection=\"anyAttribValueCollection\">\n"
                                                         + "            <atom:title type=\"text\">collection2</atom:title>\n"
                                                         + "            <accept>accept1</accept>\n"
                                                         + "            <accept>accept2</accept>\n"
                                                         + "            <categories scheme=\"scheme\" fixed=\"no\">\n"
                                                         + "                <atom:category label=\"label\" scheme=\"scheme1\" term=\"term1\"/>\n"
                                                         + "                <atom:category label=\"labe2\" scheme=\"scheme2\" term=\"term2\"/>\n"
                                                         + "            </categories>\n"
                                                         + "            <categories href=\"href\"/>\n"
                                                         + "        </collection>\n"
                                                         + "    </workspace>\n"
                                                         + "    <workspace xml:lang=\"en-us\" xml:base=\"http://base/workspace\" anyAttirbWorkspace=\"anyAttribValueWorkspace\">\n"
                                                         + "        <atom:title type=\"text\">workspace2</atom:title>\n"
                                                         + "        <collection href=\"href1\" xml:lang=\"en-us\" xml:base=\"http://base/collection\" anyAttirbCollection=\"anyAttribValueCollection\">\n"
                                                         + "            <atom:title type=\"text\">collection1</atom:title>\n"
                                                         + "            <accept>accept1</accept>\n"
                                                         + "            <accept>accept2</accept>\n"
                                                         + "            <categories scheme=\"scheme\" fixed=\"no\">\n"
                                                         + "                <atom:category label=\"label\" scheme=\"scheme1\" term=\"term1\"/>\n"
                                                         + "                <atom:category label=\"labe2\" scheme=\"scheme2\" term=\"term2\"/>\n"
                                                         + "            </categories>\n"
                                                         + "            <categories href=\"href\"/>\n"
                                                         + "        </collection>\n"
                                                         + "        <collection href=\"href2\" xml:lang=\"en-us\" xml:base=\"http://base/collection\" anyAttirbCollection=\"anyAttribValueCollection\">\n"
                                                         + "            <atom:title type=\"text\">collection2</atom:title>\n"
                                                         + "            <accept>accept1</accept>\n"
                                                         + "            <accept>accept2</accept>\n"
                                                         + "            <categories scheme=\"scheme\" fixed=\"no\">\n"
                                                         + "                <atom:category label=\"label\" scheme=\"scheme1\" term=\"term1\"/>\n"
                                                         + "                <atom:category label=\"labe2\" scheme=\"scheme2\" term=\"term2\"/>\n"
                                                         + "            </categories>\n"
                                                         + "            <categories href=\"href\"/>\n"
                                                         + "        </collection>\n"
                                                         + "    </workspace>\n"
                                                         + "</service>\n";

    private static JAXBContext  ctx;

    static {
        try {
            ctx = JAXBContext.newInstance(AppService.class.getPackage().getName());
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    public void testAppMarshal() throws Exception {
        Marshaller m = JAXBUtils.createMarshaller(ctx);

        AppService service = getService();
        JAXBElement<AppService> element = (new ObjectFactory()).createService(service);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ModelUtils.marshal(m, element, os);
        String msg = TestUtils.diffIgnoreUpdateWithAttributeQualifier(SERVICE_DOCUMENT, os.toString());
        assertNull(msg, msg);
    }

    public void testAppUnmarshal() throws IOException {
        Unmarshaller u = JAXBUtils.createUnmarshaller(ctx);
        Object element = ModelUtils.unmarshal(u, new StringReader(SERVICE_DOCUMENT));
        assertNotNull(element);
        assertTrue(element instanceof AppService);

        AppService service = (AppService)element;
        AppService expectedService = getService();

        assertService(expectedService, service);
    }

    public void testAppUnmarshalMarshal() throws Exception {
        Marshaller m = JAXBUtils.createMarshaller(ctx);
        Unmarshaller u = JAXBUtils.createUnmarshaller(ctx);

        Object service = ModelUtils.unmarshal(u, new StringReader(SERVICE_DOCUMENT));
        JAXBElement<AppService> element = (new ObjectFactory()).createService((AppService)service);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ModelUtils.marshal(m, element, os);
        String msg = TestUtils.diffIgnoreUpdateWithAttributeQualifier(SERVICE_DOCUMENT, os.toString());
        assertNull(msg, msg);
    }

    public void testCategories() {
        AppCategories cats = new AppCategories();
        cats.setHref("href");
        try {
            cats.setScheme("scheme");
        } catch (RestException e) {
            assertEquals(Messages.getMessage("cannotMixInlineAndOutOfLine"), e.getMessage());
        }

        cats = new AppCategories();
        cats.setHref("href");
        try {
            cats.setFixed(AppYesNo.YES);
        } catch (RestException e) {
            assertEquals(Messages.getMessage("cannotMixInlineAndOutOfLine"), e.getMessage());
        }

        cats = new AppCategories();
        cats.setScheme("scheme");
        cats.setFixed(AppYesNo.YES);
        try {
            cats.setHref("scheme");
        } catch (RestException e) {
            assertEquals(Messages.getMessage("cannotMixInlineAndOutOfLine"), e.getMessage());
        }

        cats = new AppCategories();
        cats.setHref("href");
        assertFalse(cats.isInline());

        cats = new AppCategories();
        assertFalse(cats.isFixedSet());
        cats.setFixed(AppYesNo.YES);
        assertTrue(cats.isFixedSet());
    }

    private void assertService(AppService expectedService, AppService service) {
        assertEquals(expectedService.getBase(), service.getBase());
        assertEquals(expectedService.getLang(), service.getLang());
        assertEquals(expectedService.getOtherAttributes().get(new QName("anyAttirbService")),
                     service.getOtherAttributes().get(new QName("anyAttirbService")));

        assertNotNull(service.getWorkspace("workspace1"));
        assertNotNull(service.getWorkspace("workspace2"));
        assertNull(service.getWorkspace("workspace3"));

        List<AppWorkspace> expectedWorkspaces = expectedService.getWorkspace();
        List<AppWorkspace> workspaces = service.getWorkspace();
        assertTrue(workspaces.size() == 2);

        assertWorkspaces(expectedWorkspaces, workspaces);
    }

    private void assertWorkspaces(List<AppWorkspace> expectedWorkspaces,
                                  List<AppWorkspace> workspaces) {
        assertEquals(expectedWorkspaces.size(), workspaces.size());
        for (int i = 0; i < expectedWorkspaces.size(); ++i) {
            AppWorkspace expectedWorkspace = expectedWorkspaces.get(i);
            AppWorkspace workspace = workspaces.get(i);

            assertEquals(expectedWorkspace.getLang(), workspace.getLang());
            assertEquals(expectedWorkspace.getBase(), workspace.getBase());
            assertEquals(expectedWorkspace.getTitle().getType(), workspace.getTitle().getType());
            assertEquals(expectedWorkspace.getTitle().getValue(), workspace.getTitle().getValue());
            assertEquals(expectedWorkspace.getOtherAttributes()
                .get(new QName("anyAttirbCollection")), workspace.getOtherAttributes()
                .get(new QName("anyAttirbCollection")));

            assertNotNull(workspace.getCollection("collection1"));
            assertNotNull(workspace.getCollection("collection2"));
            assertNull(workspace.getCollection("collection3"));

            assertCollections(expectedWorkspace.getCollection(), workspace.getCollection());
        }

    }

    private void assertCollections(List<AppCollection> expectedcollections,
                                   List<AppCollection> collections) {
        assertEquals(expectedcollections.size(), collections.size());
        for (int i = 0; i < expectedcollections.size(); ++i) {
            AppCollection expectedCollection = expectedcollections.get(i);
            AppCollection collection = collections.get(i);

            assertEquals(expectedCollection.getLang(), collection.getLang());
            assertEquals(expectedCollection.getBase(), collection.getBase());
            assertEquals(expectedCollection.getHref(), collection.getHref());
            assertEquals(expectedCollection.getTitle().getType(), collection.getTitle().getType());
            assertEquals(expectedCollection.getTitle().getValue(), collection.getTitle().getValue());
            assertEquals(expectedCollection.getOtherAttributes()
                .get(new QName("anyAttirbCollection")), collection.getOtherAttributes()
                .get(new QName("anyAttirbCollection")));

            List<AppAccept> expectedAccepts = expectedCollection.getAccept();
            List<AppAccept> accepts = collection.getAccept();
            assertEquals(expectedAccepts.size(), accepts.size());
            assertEquals(expectedAccepts.get(0).getValue(), accepts.get(0).getValue());
            assertEquals(expectedAccepts.get(1).getValue(), accepts.get(1).getValue());

            List<AppCategories> expectedCategories = expectedCollection.getCategories();
            List<AppCategories> categories = collection.getCategories();
            assertEquals(expectedCategories.size(), categories.size());

            assertNull(categories.get(0).getHref());
            assertEquals(expectedCategories.get(0).getScheme(), categories.get(0).getScheme());
            assertEquals(expectedCategories.get(0).getFixed(), categories.get(0).getFixed());
            assertEquals(expectedCategories.get(0).getCategory().get(0).getScheme(), categories
                .get(0).getCategory().get(0).getScheme());
            assertEquals(expectedCategories.get(0).getCategory().get(1).getScheme(), categories
                .get(0).getCategory().get(1).getScheme());

            assertNull(categories.get(1).getScheme());
            assertEquals(expectedCategories.get(1).getHref(), categories.get(1).getHref());
        }
    }

    private AppService getService() {
        AppService service = new AppService();
        service.setLang("en-us");
        service.setBase("http://base/service");
        service.getOtherAttributes().put(new QName("anyAttirbService"), "anyAttribValueService");

        service.getWorkspace().add(getWorkspace("1"));
        service.getWorkspace().add(getWorkspace("2"));

        service.getWorkspace();
        return service;
    }

    private AppWorkspace getWorkspace(String id) {
        AppWorkspace ws = new AppWorkspace();
        ws.setLang("en-us");
        ws.setBase("http://base/workspace");
        ws.setTitle(new AtomText("workspace" + id));
        ws.getOtherAttributes().put(new QName("anyAttirbWorkspace"), "anyAttribValueWorkspace");

        ws.getCollection().add(getCollection("1"));
        ws.getCollection().add(getCollection("2"));

        return ws;
    }

    private AppCollection getCollection(String id) {
        AppCollection col = new AppCollection();
        col.setLang("en-us");
        col.setBase("http://base/collection");
        col.setTitle(new AtomText("collection" + id));
        col.getOtherAttributes().put(new QName("anyAttirbCollection"), "anyAttribValueCollection");
        col.setHref("href" + id);

        AppAccept accept1 = new AppAccept();
        accept1.setValue("accept1");
        AppAccept accept2 = new AppAccept();
        accept2.setValue("accept2");
        col.getAccept().add(accept1);
        col.getAccept().add(accept2);

        col.getCategories().add(getInlineCategories());
        col.getCategories().add(getOutOfLineCategories());

        return col;
    }

    private AppCategories getInlineCategories() {
        AppCategories cats = new AppCategories();
        cats.setScheme("scheme");
        cats.setFixed(AppYesNo.NO);

        AtomCategory cat = new AtomCategory();
        cat.setScheme("scheme1");
        cat.setLabel("label");
        cat.setTerm("term1");
        cats.getCategory().add(cat);

        cat = new AtomCategory();
        cat.setScheme("scheme2");
        cat.setLabel("labe2");
        cat.setTerm("term2");
        cats.getCategory().add(cat);
        return cats;
    }

    private AppCategories getOutOfLineCategories() {
        AppCategories cats = new AppCategories();
        cats.setHref("href");
        return cats;
    }

}


text:
"""
vtk extract runner
"""

import enaml
from enaml.qt.qt_application import QtApplication

def run():
    with enaml.imports():
        from vtk_extract_view import Main

    app = QtApplication()

    view = Main(custom_title='VTK Geometry Extract Example')
    view.show()

    # Start the application event loop
    app.start()

run()


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width; initial-scale=1.0, maximum-scale=1">
    <link href="{{ site.url }}/public/favicon.ico" rel="shortcut icon" type="image/x-icon">
    <link href="http://gmpg.org/xfn/11" rel="profile">

    <title>
      {{ site.title }}
      {% if page.title %} · {{ page.title }}{% endif %}
    </title>

    <link rel="stylesheet" href="{{ site.url }}/public/css/hyde.css">
    <link rel="stylesheet" href="{{ site.url }}/public/css/syntax.css">
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400italic,400,600,700|Catamaran">

    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ site.url }}/public/touch-icon-144-precomposed.png">
    <link rel="shortcut icon" href="{{ site.url }}/public/favicon.png">

    <link rel="alternate" type="application/rss+xml" title="RSS" href="{{ site.url }}/atom.xml">

{{ site.title }}

{{ site.tagline }}

About

Posts

GitHub

The Grammar

Content CC-BY ·
            Code MIT

      {{ content }}


text:
.class public interface abstract Lcom/android/internal/telephony/IMms;
.super Ljava/lang/Object;
.source "IMms.java"

# interfaces
.implements Landroid/os/IInterface;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/android/internal/telephony/IMms$Stub;
    }
.end annotation

# virtual methods
.method public abstract addMultimediaMessageDraft(Ljava/lang/String;Landroid/net/Uri;)Landroid/net/Uri;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

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

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

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

.method public abstract deleteStoredMessage(Ljava/lang/String;Landroid/net/Uri;)Z
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract downloadMessage(ILjava/lang/String;Ljava/lang/String;Landroid/net/Uri;Landroid/os/Bundle;Landroid/app/PendingIntent;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

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

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

.method public abstract importMultimediaMessage(Ljava/lang/String;Landroid/net/Uri;Ljava/lang/String;JZZ)Landroid/net/Uri;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract importTextMessage(Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;JZZ)Landroid/net/Uri;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

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

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

.method public abstract sendMessage(ILjava/lang/String;Landroid/net/Uri;Ljava/lang/String;Landroid/os/Bundle;Landroid/app/PendingIntent;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract sendStoredMessage(ILjava/lang/String;Landroid/net/Uri;Landroid/os/Bundle;Landroid/app/PendingIntent;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

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

.method public abstract updateStoredMessageStatus(Ljava/lang/String;Landroid/net/Uri;Landroid/content/ContentValues;)Z
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method


text:
module FFI
  module GPhoto2Port
    class GPPortSettings < FFI::Struct
      # libgphoto2_port/libgphoto2_port/gphoto2-port.h
      layout :serial, GPPortSettingsSerial,
             :usb, GPPortSettingsUSB,
             :usbdiskdirect, GPPortSettingsUsbDiskDirect,
             :usbscsi, GPPortSettingsUsbScsi
    end
  end
end


text:
  ({                                                           \
    decltype(x) ret_;                                          \
    int try_cnt = 0;                                           \
    do {                                                       \
      ret_ = (x);                                              \
    } while (ret_ == -1 && errno == EINTR && try_cnt++ < 100); \
    ret_;                                                       \
  })

#ifndef sighandler_t
typedef void (*sighandler_t)(int sig);
#endif

const double MILE_TO_KM = 1.609344;
const double KM_TO_MILE = 1. / MILE_TO_KM;
const double MS_TO_KPH = 3.6;
const double MS_TO_MPH = MS_TO_KPH * KM_TO_MILE;
const double METER_TO_MILE = KM_TO_MILE / 1000.0;
const double METER_TO_FOOT = 3.28084;

namespace util {

void set_thread_name(const char* name);
int set_realtime_priority(int level);
int set_core_affinity(std::vector<int> cores);

// ***** Time helpers *****
struct tm get_time();
bool time_valid(struct tm sys_time);

// ***** math helpers *****

// map x from [a1, a2] to [b1, b2]
template <typename T>
T map_val(T x, T a1, T a2, T b1, T b2) {
  x = std::clamp(x, a1, a2);
  T ra = a2 - a1;
  T rb = b2 - b1;
  return (x - a1) * rb / ra + b1;
}

// ***** string helpers *****

template <typename... Args>
std::string string_format(const std::string& format, Args... args) {
  size_t size = snprintf(nullptr, 0, format.c_str(), args...) + 1;
  std::unique_ptr<char[]> buf(new char[size]);
  snprintf(buf.get(), size, format.c_str(), args...);
  return std::string(buf.get(), buf.get() + size - 1);
}

std::string getenv(const char* key, const char* default_val = "");
int getenv(const char* key, int default_val);
float getenv(const char* key, float default_val);

std::string hexdump(const uint8_t* in, const size_t size);
std::string dir_name(std::string const& path);

// **** file fhelpers *****
std::string read_file(const std::string& fn);
std::map<std::string, std::string> read_files_in_dir(const std::string& path);
void remove_files_in_dir(const std::string& path);
int write_file(const char* path, const void* data, size_t size, int flags = O_WRONLY, mode_t mode = 0664);

FILE* safe_fopen(const char* filename, const char* mode);
size_t safe_fwrite(const void * ptr, size_t size, size_t count, FILE * stream);
int safe_fflush(FILE *stream);
int safe_ioctl(int fd, unsigned long request, void *argp);

std::string readlink(const std::string& path);
bool file_exists(const std::string& fn);
bool create_directories(const std::string &dir, mode_t mode);

std::string check_output(const std::string& command);

inline void sleep_for(const int milliseconds) {
  if (milliseconds > 0) {
    std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
  }
}

}  // namespace util

class ExitHandler {
public:
  ExitHandler() {
    std::signal(SIGINT, (sighandler_t)set_do_exit);
    std::signal(SIGTERM, (sighandler_t)set_do_exit);

#ifndef __APPLE__
    std::signal(SIGPWR, (sighandler_t)set_do_exit);
#endif
  };
  inline static std::atomic<bool> power_failure = false;
  inline static std::atomic<int> signal = 0;
  inline operator bool() { return do_exit; }
  inline ExitHandler& operator=(bool v) {
    signal = 0;
    do_exit = v;
    return *this;
  }
private:
  static void set_do_exit(int sig) {
#ifndef __APPLE__
    power_failure = (sig == SIGPWR);
#endif
    signal = sig;
    do_exit = true;
  }
  inline static std::atomic<bool> do_exit = false;
};

struct unique_fd {
  unique_fd(int fd = -1) : fd_(fd) {}
  unique_fd& operator=(unique_fd&& uf) {
    fd_ = uf.fd_;
    uf.fd_ = -1;
    return *this;
  }
  ~unique_fd() {
    if (fd_ != -1) close(fd_);
  }
  operator int() const { return fd_; }
  int fd_;
};

class FirstOrderFilter {
public:
  FirstOrderFilter(float x0, float ts, float dt) {
    k_ = (dt / ts) / (1.0 + dt / ts);
    x_ = x0;
  }
  inline float update(float x) {
    x_ = (1. - k_) * x_ + k_ * x;
    return x_;
  }
  inline void reset(float x) { x_ = x; }
  inline float x(){ return x_; }

private:
  float x_, k_;
};

template<typename T>
void update_max_atomic(std::atomic<T>& max, T const& value) {
  T prev = max;
  while(prev < value && !max.compare_exchange_weak(prev, value)) {}
}

class LogState {
 public:
  bool initialized = false;
  std::mutex lock;
  void *zctx = nullptr;
  void *sock = nullptr;
  int print_level;
  const char* endpoint;

  LogState(const char* _endpoint) {
    endpoint = _endpoint;
  }

  inline void initialize() {
    zctx = zmq_ctx_new();
    sock = zmq_socket(zctx, ZMQ_PUSH);

    // Timeout on shutdown for messages to be received by the logging process
    int timeout = 100;
    zmq_setsockopt(sock, ZMQ_LINGER, &timeout, sizeof(timeout));

    zmq_connect(sock, endpoint);
    initialized = true;
  }

  ~LogState() {
    if (initialized) {
      zmq_close(sock);
      zmq_ctx_destroy(zctx);
    }
  }
};