text:
$.scrollView.height = Ti.Platform.displayCaps.platformHeight - 150;

if(Ti.Platform.osname == "android") {
	console.log("android");
	$.scrollView.height = PixelsToDPUnits(Ti.Platform.displayCaps.platformHeight) - 150;
	$.scrollView.overScrollMode = Titanium.UI.Android.OVER_SCROLL_NEVER;
}

var plan;

$.picker.setSelectedRow(0,0,false);

function plan(e)
{
	console.log("plan");
	plan = e.row.title;
	if(Ti.Platform.osname == "iphone" || Ti.Platform.osname == "ipad")
	{
		$.planLabel.text = plan;
	}
}

function showPicker()
{
	console.log("showPicker");
	console.log("$.pickerView.visible: " + $.pickerView.visible);
	if($.pickerView.visible == "false")
	{
		console.log("false");
		$.contentView.height = 300;
		$.pickerView.height = 250;
		$.pickerContentView.height  = 250;
		$.pickerView.setVisible(true);
		$.done.setVisible(true);
		$.picker.setVisible(true);
	}
	else
	{
		if($.pickerView.visible == false)
		{
			console.log("else false");
			$.contentView.height = 300;
			$.pickerView.height = 250;
			$.pickerContentView.height  = 250;
			$.pickerView.setVisible(true);
			$.done.setVisible(true);
			$.picker.setVisible(true);
		}
		else
		{
			console.log("else true");
			$.contentView.height = 100;
			$.pickerView.height = 50;
			$.pickerContentView.height  = 50;
			$.pickerView.setVisible(false);
			$.done.setVisible(false);
			$.picker.setVisible(false);
		}
	}
}

function done()
{
	console.log("done");
	$.contentView.height = 100;
	$.pickerView.height = 50;
	$.pickerContentView.height  = 50;
	$.pickerView.setVisible(false);
	$.done.setVisible(false);
	$.picker.setVisible(false);
}

function back()
{
	DRAWER.navigation("internetManagement",1);
}

function submit()
{
	console.log("submit");
}


text:
__author__ = 'zz'

# relate path
IMAGE_CACHE_PATH = 'cache'

redpajama_set_name: RedPajamaGithub


text:
module Brief::Server::Handlers
  class Action
    def self.handle(path_args, briefcase, options={})
      parts = path_args.split("/")
      action = parts.shift
      path = parts.join("/")

      document = briefcase.document_at(path)

      headers = {
        "Content-Type" => "application/json"
      }

      if !document
        return [404,headers,{error:"Could not find a document at this path"}]
      end

      model = document.to_model

      if !model.class.defined_actions.include?(action.to_sym)
        [400, headers, {error:"Invalid action: #{ action }"}]
      else
        model.send(action)
        [200, headers, model.as_json]
      end
    end
  end
end


text:
interface Processors {
  stripPrefix: any;
}

declare module 'xml2js' {
  export function parseString(string: string, callback: (err, result) => void);
  export function parseString(string: string, options: Object, callback: (err, result) => void);

  export var processors: Processors;
}


text: Adds components to enhance gameplay speed, protection, reliability, etc for Bolt.


text:
import numbers
import re

class ConfigError (Exception):
    def __init__(self, msg, note):
        super(ConfigError, self).__init__(msg)
        self.note = note

def render_path(path):
    if isinstance(path, basestring):
        return path
    def aux(p):
        if not isinstance(p, basestring):
            return '[%d]' % p
        return ('.%s' if _isidentifier(p) else '["%s"]') % p
    return '$' + ''.join([aux(p) for p in path])

# Utilities

def err(path, msg, note=None):
    raise ConfigError('%s: %s' % (render_path(path), msg), note)

_KEYWORDS = {
    'import', 'importstr', 'importbin', 'function', 'self', 'super', 'assert', 'if',
    'then', 'else', 'for', 'in', 'local', 'tailstrict', 'true', 'false', 'null', 'error',
}

def _isidentifier(name):
    return name not in _KEYWORDS and re.match("[_A-Za-z_][_a-zA-Z0-9]*$", name)

_TYPE_FROM_STR = {
    'null': type(None),
    'bool': bool,
    'number': numbers.Number,
    'object': dict,
    'array': list,
    'string': basestring,
}

def _type_err(v):
    if isinstance(v, basestring):
        return '"%s"' % v
    if isinstance(v, numbers.Number):
        return '%s' % v
    if isinstance(v, bool):
        return '%s' % v
    return _type_str(v)

def _type_str(v):
    if v is None:
        return 'null'
    if isinstance(v, basestring):
        return 'string'
    if isinstance(v, dict):
        return 'object'
    if isinstance(v, list):
        return 'array'
    if isinstance(v, numbers.Number):
        return 'number'
    if isinstance(v, bool):
        return 'bool'

class _Empty:
    pass

_NO_DEFAULT = _Empty()

# Return the value obtained by resolving the path from root.  If the value does not exist in the
# last object, create it using the default and return that instead.
def _resolve_path(root, path, default=_NO_DEFAULT):
    for i, v in enumerate(path):
        if isinstance(root, dict) and i == len(path) - 1:
            if v not in root and default != _NO_DEFAULT:
                root[v] = default
        root = root[v]
    return root

# Validators

def is_string_map(v):
    msg = is_type('object')(v)
    if msg:
        return msg
    for k, v2 in v.iteritems():
        if not isinstance(v2, basestring):
            return 'Expected field %s type to be string but got %s' % (k, _type_err(v2))

# Validator generating functions.

# Pretty-print a small set of strings.
def _set_str(s):
    return '{%s}' % ', '.join(sorted(s))

def is_any_type(types):
    def check(v):
        if _type_str(v) not in types:
            return 'Expected type to be one of %s but found %s' % (_set_str(types), _type_err(v))
    return check

def is_type(t):
    def check(v):
        if _type_str(v) != t:
            return 'Expected type %s but found %s' % (t, _type_err(v))
    return check

def is_value(expected):
    def check(v):
        if v != expected:
            return 'Expected value %s, got %s' % (expected, v)
    return check

def is_any_value(expected):
    def check(v):
        if v not in expected:
            return 'Expected value to be one of %s, got %s' % (_set_str(expected), v)
    return check

# User-friendly validation routines:

# You can just give a type name in place of a function.
def _sanitize_func(func):
    if isinstance(func, basestring):
        return is_type(func)
    return func

# Ensure path validates by func.  If not proesent, inserts default.
def path_val(root, path, func, default=None):
    func = _sanitize_func(func)
    v = _resolve_path(root, path, default)
    msg = func(v)
    if msg is not None:
        err(path, msg)
    return v

# Ensure path is an array and all elements validate by element_func.
def array(root, path, element_func, default):
    v = path_val(root, path, 'array', default)
    element_func = _sanitize_func(element_func)
    for i, el in enumerate(v):
        path_val(root, path + [i], element_func)
    return v

# Ensure path is an object and only has the given fields.  If not present, inserts
# default.
def obj_only(root, path, fields, default=None):
    v = path_val(root, path, 'object', default)
    for field in v:
        if field not in fields:
            err(path, 'Unexpected field: %s' % field)
    return v


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.infobip.cordova.demo" version="0.1.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>Infobip Cordova Demo App</name>
    <description>
        A sample Infobip Demo application that works with Infobip Push service and Centili mobile payments.
    </description>
    <author email="nikola.maric@infobip.com" href="http://www.infobip.com">
	Framework Integration Team @ Belgrade, Infobip Ltd.
    </author>
    <content src="index.html" />
    <access origin="*" />
    <preference name="fullscreen" value="true" />
    <preference name="webviewbounce" value="true" />
</widget>


text:
describe 'android/element/generic' do
  def m method
    r = method(method).call 'tent'
    r = r.first if r.kind_of? Array
    r.class.must_equal Selenium::WebDriver::Element
    r.text.must_equal 'Content'
  end

  t 'find' do
    m :find
  end

  t 'tag' do
    tag 'TextView'
  end

  t 'tags' do
    tags('TextView').length
  end

  t 'text' do
    m :text
  end

  t 'texts' do
    m :texts
  end

  t 'name' do
    m :name
  end

  t 'name_exact' do
    name_exact 'App'
  end

  t 'names' do
    names('a').length.must_be :>=, 5
  end

  t 'scroll_to' do
    text('Views').click
    e = scroll_to 'rotating button'
    e.text.must_equal 'Rotating Button'
    # back to start activity
    back
  end

  t 'scroll_to_exact' do
    text('Views').click
    e = scroll_to_exact 'Rotating Button'
    e.text.must_equal 'Rotating Button'
    # back to start activity
    back
  end

  t 'mobile find works before and after source' do
    m :text
    get_source.class.must_equal Hash
    m :text
  end
end


text:
from django.shortcuts import render

from rango.models import Category, Page
from rango.forms import CategoryForm, PageForm
from rango.forms import UserForm, UserProfileForm
from rango.bing_search import run_query

from django.shortcuts import redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from datetime import datetime

def index(request):

    category_list = Category.objects.order_by('-likes')[:5]
    page_list = Page.objects.order_by('-views')[:5]

    context_dict = {'categories': category_list, 'pages': page_list}

    visits = request.session.get('visits')
    if not visits:
        visits = 1
    reset_last_visit_time = False

    last_visit = request.session.get('last_visit')
    if last_visit:
        last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S")
        context_dict['last_visit_time'] = last_visit_time

        if (datetime.now() - last_visit_time).seconds > 0:
            # ...reassign the value of the cookie to +1 of what it was before...
            visits = visits + 1
            # ...and update the last visit cookie, too.
            reset_last_visit_time = True
    else:
        # Cookie last_visit doesn't exist, so create it to the current date/time.
        reset_last_visit_time = True

    if reset_last_visit_time:
        request.session['last_visit'] = str(datetime.now())
        request.session['visits'] = visits
    context_dict['visits'] = visits

    response = render(request,'rango/index.html', context_dict)

    return response

def category(request, category_name_slug):
    context_dict = {}
    context_dict['result_list'] = None
    context_dict['query'] = None
    if request.method == 'POST':
        query = request.POST['query'].strip()

        if query:
            # Run our Bing function to get the results list!
            result_list = run_query(query)

            context_dict['result_list'] = result_list
            context_dict['query'] = query

    try:
        category = Category.objects.get(slug=category_name_slug)
        context_dict['category_name'] = category.name
        pages = Page.objects.filter(category=category).order_by('-views')
        context_dict['pages'] = pages
        context_dict['category'] = category
    except Category.DoesNotExist:
        pass

    if not context_dict['query']:
        context_dict['query'] = category.name

    return render(request, 'rango/category.html', context_dict)

def add_category(request):
    # A HTTP POST?
    if request.method == 'POST':
        form = CategoryForm(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new category to the database.
            form.save(commit=True)

            # Now call the index() view.
            # The user will be shown the homepage.
            return index(request)
        else:
            # The supplied form contained errors - just print them to the terminal.
            print form.errors
    else:
        # If the request was not a POST, display the form to enter details.
        form = CategoryForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render(request, 'rango/add_category.html', {'form': form})

def add_page(request, category_name_slug):

    try:
        cat = Category.objects.get(slug=category_name_slug)
    except Category.DoesNotExist:
                cat = None

    if request.method == 'POST':
        form = PageForm(request.POST)
        if form.is_valid():
            if cat:
                page = form.save(commit=False)
                page.category = cat
                page.views = 0
                page.save()
                # probably better to use a redirect here.
                return category(request, category_name_slug)
        else:
            print form.errors
    else:
        form = PageForm()

    context_dict = {'form':form, 'category': cat}

    return render(request, 'rango/add_page.html', context_dict)

@login_required
def restricted(request):
    return render(request, 'rango/restricted.html', {})

def about(request):
    if request.session.get('visits'):
        count = request.session.get('visits')
    else:
        count = 0

    context_dict = {'visits': count}

    return render(request, 'rango/about.html', context_dict)

def search(request):
    result_list = []

    if request.method == 'POST':
        query = request.POST['query'].strip()

        if query:
            # Run our Bing function to get the results list!
            result_list = run_query(query)

    return render(request, 'rango/search.html', {'result_list': result_list})

def track_url(request):
    page_id = None
    url = '/rango/'
    if request.method == 'GET':
        if 'page_id' in request.GET:
            page_id = request.GET['page_id']
            try:
                page = Page.objects.get(id=page_id)
                page.views = page.views + 1
                page.save()
                url = page.url
            except:
                pass

    return redirect(url)

@login_required
def like_category(request):

    cat_id = None
    if request.method == 'GET':
        cat_id = request.GET['category_id']

    likes = 0
    if cat_id:
        cat = Category.objects.get(id=int(cat_id))
        if cat:
            likes = cat.likes + 1
            cat.likes = likes
            cat.save()

    return HttpResponse(likes)

def get_category_list(max_results=0, starts_with=''):
        cat_list = []
        if starts_with:
                cat_list = Category.objects.filter(name__istartswith=starts_with)

        if max_results > 0:
                if len(cat_list) > max_results:
                        cat_list = cat_list[:max_results]

        return cat_list

def suggest_category(request):
        cat_list = []
        starts_with = ''
        if request.method == 'GET':
                starts_with = request.GET['suggestion']

        cats = get_category_list(8, starts_with)

        return render(request, 'rango/cats.html', {'cats': cats})

@login_required
def auto_add_page(request):
    title = None
    url = None
    category_id = None
    context_dict = {}

    if request.method == 'GET':
        title = request.GET['title']
        url = request.GET['url']
        category_id = request.GET['category_id']

        if category_id:
            category = Category.objects.get(id=int(category_id))
            p = Page.objects.get_or_create(category=category, title=title, url=url)

            pages = Page.objects.filter(category=category).order_by('-views')
            context_dict['pages'] = pages

    return render(request, 'rango/page_list.html', context_dict)


text:
module Application
  VERSION = '0.0.3'
end


text:
'''
boostrap_span  django-bootstrap-span/boostrap_span.
(C) Copyright 2014 Stuart McMillan, Useful Automation
'''


text:
export const ID = 'flashMessages'
export const state2props = (state) => state[ID]


text:
package in.twizmwaz.cardinal.module.modules.filter.parsers;

import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.module.GameObjective;
import in.twizmwaz.cardinal.module.modules.filter.FilterParser;
import in.twizmwaz.cardinal.module.modules.team.TeamModule;
import in.twizmwaz.cardinal.util.Teams;
import org.jdom2.Element;

public class ObjectiveFilterParser extends FilterParser {

    private GameObjective objective;
    private TeamModule team;
    private boolean any;

    public ObjectiveFilterParser(final Element element) {
        super(element);
        String name = element.getText();
        for (GameObjective objective : GameHandler.getGameHandler().getMatch().getModules().getModules(GameObjective.class)) {
            if (objective.getId().replaceAll(" ", "").equalsIgnoreCase(name.replaceAll(" ", ""))) {
                this.objective = objective;
            }
        }
        for (GameObjective objective : GameHandler.getGameHandler().getMatch().getModules().getModules(GameObjective.class)) {
            if (objective.getId().replaceAll(" ", "").toLowerCase().startsWith(name.replaceAll(" ", "").toLowerCase())) {
                this.objective = objective;
            }
        }
        for (GameObjective objective : GameHandler.getGameHandler().getMatch().getModules().getModules(GameObjective.class)) {
            if (objective.getName().replaceAll(" ", "").equalsIgnoreCase(name.replaceAll(" ", ""))) {
                this.objective = objective;
            }
        }
        for (GameObjective objective : GameHandler.getGameHandler().getMatch().getModules().getModules(GameObjective.class)) {
            if (objective.getName().replaceAll(" ", "").toLowerCase().startsWith(name.replaceAll(" ", "").toLowerCase())) {
                this.objective = objective;
            }
        }
        try {
            String team = element.getAttributeValue("team");
            this.team = Teams.getTeamById(team).orNull();
        } catch (NullPointerException e) {
        }
        try {
            this.any = Boolean.getBoolean(element.getAttributeValue("any"));
        } catch (NullPointerException e) {
            any = false;
        }

    }

    public GameObjective getObjective() {
        return objective;
    }

    public TeamModule getTeam() {
        return team;
    }

    public boolean isAny() {
        return any;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>

    <groupId>hyrax</groupId>
    <artifactId>java-experiments</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>3.3.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.7</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.12.4</version>
        </dependency>

    </dependencies>

</project>


text:
class GridHtml
def instantiate
	@app_wrapper = '
'
	@app_wrapper_end = '
'
	@field_header_wrapper = ''
	@field_header_wrapper_end =  '	'
	@record_wrapper = '
'
	@record_wrapper_end = ''
	@field_wrapper = ''
	@field_wrapper_end = '	'
end

end


text:
require "logstash/namespace"
require "logstash/outputs/base"

class LogStash::Outputs::WebSocket < LogStash::Outputs::Base

  config_name "websocket"
  milestone 1

  config :flush_interval, :validate => :number, :default => "1000"

  config :uri, :validate => :string

  public
  def register
    jarpath = File.join(File.dirname(__FILE__), "../../../vendor/websocket-output/*.jar")
    Dir[jarpath].each do |jar|
        require jar
    end

    options = {
      :flush_interval => @flush_interval,
      :uri => @uri
    }
    options[:type] = :node

    @transmitter = com.nitorcreations.willow.messages.WebSocketTransmitter.getSingleton(@flush_interval, @uri)
    @adapter = com.nitorcreations.willow.logstash.Adapter.new()
    @transmitter.start()
  end # def register

  public
  def receive(event)
    return unless output?(event)
    event_hash = event.to_hash
    msgtype = event_hash["wsmsgtype"]
    unless msgtype then
      msgtype = "logmessage"
    end
    @transmitter.queue(@adapter.fromHash(msgtype, event_hash))
  end # def receive
end # class LogStash::Outputs::WebSocket


text:
package eu.msmit.cloud.uid;

/**
 * @author Marijn Smit (info@msmit.eu)
 * @since 30 Nov 2015
 */
public class Uids {

	private static final UidFactory FACTORY;

	static {
		FACTORY = new UidFactory("232015612951561435".getBytes());
	}

	/**
	 * @param uid
	 */
	public static <T extends Uid> T decode(String uid) {
		return FACTORY.resolve(uid);
	}

	/**
	 * @param uid
	 * @return
	 */
	public static String encode(Uid uid) {
		return FACTORY.encode(uid);
	}
}


text:
int main(int argc, char * argv[]) {
    hs_init(NULL, NULL);
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}


text:
package hawkular

import (
	"fmt"
	"net/url"
	"os"
	"strings"
	"sync"

	"github.com/GoogleCloudPlatform/heapster/extpoints"
	"github.com/golang/glog"
	"github.com/hawkular/hawkular-client-go/metrics"

	sink_api "github.com/GoogleCloudPlatform/heapster/sinks/api/v1"
	kube_api "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
)

const (
	unitsTag       string = "units"
	typeTag        string = "type"
	descriptionTag string = "_description"
	descriptorTag  string = "descriptor_name"
	groupTag       string = "group_id"
	separator      string = "/"
)

type hawkularSink struct {
	client  *metrics.Client
	models  map[string]metrics.MetricDefinition // Model definitions
	regLock sync.Mutex
	reg     map[string]*metrics.MetricDefinition // Real definitions
}

// START: ExternalSink interface implementations

func (self *hawkularSink) Register(mds []sink_api.MetricDescriptor) error {
	self.regLock.Lock()
	defer self.regLock.Unlock()

	// Create model definitions based on the MetricDescriptors
	for _, md := range mds {
		hmd := self.descriptorToDefinition(&md)
		self.models[md.Name] = hmd
	}

	// Fetch currently known metrics from Hawkular-Metrics and cache them
	prev, err := self.client.Definitions(metrics.Gauge)
	if err != nil {
		return err
	}

	for _, p := range prev {
		// If no descriptorTag is found, this metric does not belong to Heapster
		if mk, found := p.Tags[descriptorTag]; found {
			model := self.models[mk]
			if !self.recent(p, &model) {
				if err := self.client.UpdateTags(metrics.Gauge, p.Id, p.Tags); err != nil {
					return err
				}
			}
			self.reg[p.Id] = p
		}
	}

	return nil
}

// Checks that stored definition is up to date with the model
func (self *hawkularSink) recent(live *metrics.MetricDefinition, model *metrics.MetricDefinition) bool {
	recent := true
	for k, _ := range model.Tags {
		if v, found := live.Tags[k]; !found {
			// There's a label that wasn't in our stored definition
			live.Tags[k] = v
			recent = false
		}
	}

	return recent
}

// Transform the MetricDescriptor to a format used by Hawkular-Metrics
func (self *hawkularSink) descriptorToDefinition(md *sink_api.MetricDescriptor) metrics.MetricDefinition {
	tags := make(map[string]string)
	// Postfix description tags with _description
	for _, l := range md.Labels {
		if len(l.Description) > 0 {
			tags[l.Key+descriptionTag] = l.Description
		}
	}

	if len(md.Units.String()) > 0 {
		tags[unitsTag] = md.Units.String()
	}
	if len(md.Type.String()) > 0 {
		tags[typeTag] = md.Type.String()
	}

	tags[descriptorTag] = md.Name

	hmd := metrics.MetricDefinition{
		Id:   md.Name,
		Tags: tags,
	}

	return hmd
}

func (self *hawkularSink) groupName(p *sink_api.Point) string {
	n := []string{p.Labels[sink_api.LabelContainerName.Key], p.Name}
	return strings.Join(n, separator)
}

func (self *hawkularSink) idName(p *sink_api.Point) string {
	n := []string{p.Labels[sink_api.LabelContainerName.Key], p.Labels[sink_api.LabelPodId.Key], p.Name}
	return strings.Join(n, separator)
}

// Check that metrics tags are defined on the Hawkular server and if not,
// register the metric definition.
func (self *hawkularSink) registerIfNecessary(t *sink_api.Timeseries) error {
	key := self.idName(t.Point)

	self.regLock.Lock()
	defer self.regLock.Unlock()

	// If found, check it matches the current stored definition (could be old info from
	// the stored metrics cache for example)
	if _, found := self.reg[key]; !found {
		// Register the metric descriptor here..
		if md, f := self.models[t.MetricDescriptor.Name]; f {
			// Set tag values
			for k, v := range t.Point.Labels {
				md.Tags[k] = v
			}

			md.Tags[groupTag] = self.groupName(t.Point)
			md.Tags[descriptorTag] = t.MetricDescriptor.Name

			// Create metric, use updateTags instead of Create because we know it is unique
			if err := self.client.UpdateTags(metrics.Gauge, key, md.Tags); err != nil {
				// Log error and don't add this key to the lookup table
				glog.Errorf("Could not update tags: %s", err)
				return err
			}

			// Add to the lookup table
			self.reg[key] = &md
			glog.Infof("Registered new metric definition: %s", key)
		} else {
			return fmt.Errorf("Could not find definition model with name %s", t.MetricDescriptor.Name)
		}
	}
	// TODO Compare the definition tags and update if necessary? Quite expensive operation..

	return nil
}

func (self *hawkularSink) StoreTimeseries(ts []sink_api.Timeseries) error {
	if len(ts) > 0 {
		mhs := make([]metrics.MetricHeader, 0, len(ts))

		for _, t := range ts {
			self.registerIfNecessary(&t)

			if t.MetricDescriptor.ValueType == sink_api.ValueBool {
				// TODO: Model to availability type once we see some real world examples
				break
			}

			mH, err := self.pointToMetricHeader(&t)
			if err != nil {
				// One transformation error should not prevent the whole process
				glog.Errorf(err.Error())
				continue
			}

			mhs = append(mhs, *mH)
		}

		return self.client.Write(mhs)
	}
	return nil
}

// Converts Timeseries to metric structure used by the Hawkular
func (self *hawkularSink) pointToMetricHeader(t *sink_api.Timeseries) (*metrics.MetricHeader, error) {

	p := t.Point
	name := self.idName(p)

	value, err := metrics.ConvertToFloat64(p.Value)
	if err != nil {
		return nil, err
	}

	m := metrics.Datapoint{
		Value:     value,
		Timestamp: metrics.UnixMilli(p.End),
	}

	// At the moment all the values are converted to gauges.
	mh := &metrics.MetricHeader{
		Id:   name,
		Data: []metrics.Datapoint{m},
		Type: metrics.Gauge,
	}
	return mh, nil
}

func (self *hawkularSink) DebugInfo() string {
	info := fmt.Sprintf("Hawkular-Metrics Sink\n")

	self.regLock.Lock()
	defer self.regLock.Unlock()
	info += fmt.Sprintf("Known metrics: %d", len(self.reg))

	// TODO Add here statistics from the Hawkular-Metrics client instance
	return info
}

func (self *hawkularSink) StoreEvents(events []kube_api.Event) error {
	// TODO: Delegate to Fabric8 event storage (if available) until Hawkular has a solution?
	return nil
}

func (self *hawkularSink) Name() string {
	return "Hawkular-Metrics sink"
}

// END: ExternalSink

func init() {
	extpoints.SinkFactories.Register(NewHawkularSink, "hawkular")
}

func NewHawkularSink(uri string, options map[string][]string) ([]sink_api.ExternalSink, error) {

	parsedUrl, err := url.Parse(os.ExpandEnv(uri))
	if err != nil {
		return nil, err
	}

	p := metrics.Parameters{
		Tenant: "heapster",
		Host:   parsedUrl.Host,
	}

	// Connection parameters
	if len(parsedUrl.Path) > 0 {
		p.Path = parsedUrl.Path
	}

	if v, found := options["tenant"]; found {
		p.Tenant = v[0]
	}

	c, err := metrics.NewHawkularClient(p)
	if err != nil {
		return nil, err
	}
	glog.Infof("Created Hawkular Sink with parameters %v", p)

	hSink := &hawkularSink{client: c,
		reg:    make(map[string]*metrics.MetricDefinition),
		models: make(map[string]metrics.MetricDefinition),
	}

	return []sink_api.ExternalSink{hSink}, nil
}


text:
require File.expand_path('../../../spec_helper', __FILE__)

describe Instagram::Client do
  Instagram::Configuration::VALID_FORMATS.each do |format|
    context ".new(:format => '#{format}')" do
      before do
        @client = Instagram::Client.new(:format => format, :client_id => 'CID', :client_secret => 'CS', :access_token => 'AT')
      end

      describe ".user" do

        context "with user ID passed" do

          before do
            stub_get("users/4.#{format}").
              with(:query => {:access_token => @client.access_token}).
              to_return(:body => fixture("mikeyk.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
          end

          it "should get the correct resource" do
            @client.user(4)
            a_get("users/4.#{format}").
              with(:query => {:access_token => @client.access_token}).
              should have_been_made
          end

          it "should return extended information of a given user" do
            user = @client.user(4)
            user.full_name.should == "Mike Krieger"
          end

        end

        context "without user ID passed" do

          before do
            stub_get("users/self.#{format}").
              with(:query => {:access_token => @client.access_token}).
              to_return(:body => fixture("shayne.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
          end

          it "should get the correct resource" do
            @client.user()
            a_get("users/self.#{format}").
              with(:query => {:access_token => @client.access_token}).
              should have_been_made
          end
        end
      end

      describe ".user_search" do

        before do
          stub_get("users/search.#{format}").
            with(:query => {:access_token => @client.access_token}).
            with(:query => {:q => "Shayne Sweeney"}).
            to_return(:body => fixture("user_search.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
        end

        it "should get the correct resource" do
          @client.user_search("Shayne Sweeney")
          a_get("users/search.#{format}").
            with(:query => {:access_token => @client.access_token}).
            with(:query => {:q => "Shayne Sweeney"}).
            should have_been_made
        end

        it "should return an array of user search results" do
          users = @client.user_search("Shayne Sweeney")
          users.should be_a Array
          users.first.username.should == "shayne"
        end
      end

      describe ".user_follows" do

        context "with user ID passed" do

          before do
            stub_get("users/4/follows.#{format}").
              with(:query => {:access_token => @client.access_token}).
              to_return(:body => fixture("follows.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
          end

          it "should get the correct resource" do
            @client.user_follows(4)
            a_get("users/4/follows.#{format}").
              with(:query => {:access_token => @client.access_token}).
              should have_been_made
          end

          it "should return a list of users whom a given user follows" do
            follows = @client.user_follows(4)
            follows.should be_a Array
            follows.first.username.should == "heartsf"
          end
        end

        context "without user ID passed" do

          before do
            stub_get("users/self/follows.#{format}").
              with(:query => {:access_token => @client.access_token}).
              to_return(:body => fixture("follows.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
          end

          it "should get the correct resource" do
            @client.user_follows
            a_get("users/self/follows.#{format}").
              with(:query => {:access_token => @client.access_token}).
              should have_been_made
          end
        end
      end

      describe ".user_followed_by" do

        context "with user ID passed" do

          before do
            stub_get("users/4/followed-by.#{format}").
              with(:query => {:access_token => @client.access_token}).
              to_return(:body => fixture("followed_by.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
          end

          it "should get the correct resource" do
            @client.user_followed_by(4)
            a_get("users/4/followed-by.#{format}").
              with(:query => {:access_token => @client.access_token}).
              should have_been_made
          end

          it "should return a list of users whom a given user is followed by" do
            followed_by = @client.user_followed_by(4)
            followed_by.should be_a Array
            followed_by.first.username.should == "bojieyang"
          end
        end

        context "without user ID passed" do

          before do
            stub_get("users/self/followed-by.#{format}").
              with(:query => {:access_token => @client.access_token}).
              to_return(:body => fixture("followed_by.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
          end

          it "should get the correct resource" do
            @client.user_followed_by
            a_get("users/self/followed-by.#{format}").
              with(:query => {:access_token => @client.access_token}).
              should have_been_made
          end
        end
      end

      describe ".user_media_feed" do

        before do
          stub_get("users/self/feed.#{format}").
            with(:query => {:access_token => @client.access_token}).
            to_return(:body => fixture("user_media_feed.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
        end

        it "should get the correct resource" do
          @client.user_media_feed
          a_get("users/self/feed.#{format}").
            with(:query => {:access_token => @client.access_token}).
            should have_been_made
        end
      end

      describe ".user_liked_media" do

        before do
          stub_get("users/self/media/liked.#{format}").
            with(:query => {:access_token => @client.access_token}).
            to_return(:body => fixture("liked_media.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
        end

        it "should get the correct resource" do
          @client.user_liked_media
          a_get("users/self/media/liked.#{format}").
            with(:query => {:access_token => @client.access_token}).
            should have_been_made
        end
      end

      describe ".user_recent_media" do

        context "with user ID passed" do

          before do
            stub_get("users/4/media/recent.#{format}").
              with(:query => {:access_token => @client.access_token}).
              to_return(:body => fixture("recent_media.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
          end

          it "should get the correct resource" do
            @client.user_recent_media(4)
            a_get("users/4/media/recent.#{format}").
              with(:query => {:access_token => @client.access_token}).
              should have_been_made
          end

          it "should return a list of recent media items for the given user" do
            recent_media = @client.user_recent_media(4)
            recent_media.should be_a Array
            recent_media.first.user.username.should == "shayne"
          end
        end

        context "without user ID passed" do

          before do
            stub_get("users/self/media/recent.#{format}").
              with(:query => {:access_token => @client.access_token}).
              to_return(:body => fixture("recent_media.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
          end

          it "should get the correct resource" do
            @client.user_recent_media
            a_get("users/self/media/recent.#{format}").
              with(:query => {:access_token => @client.access_token}).
              should have_been_made
          end
        end
      end

      describe ".user_requested_by" do

        before do
          stub_get("users/self/requested-by.#{format}").
            with(:query => {:access_token => @client.access_token}).
            to_return(:body => fixture("requested_by.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
        end

        it "should get the correct resource" do
          @client.user_requested_by
          a_get("users/self/requested-by.#{format}").
            with(:query => {:access_token => @client.access_token}).
            should have_been_made
        end

        it "should return a list of users awaiting approval" do
          users = @client.user_requested_by
          users.should be_a Array
          users.first.username.should == "shayne"
        end
      end

      describe ".user_relationship" do

        before do
          stub_get("users/4/relationship.#{format}").
            with(:query => {:access_token => @client.access_token}).
            to_return(:body => fixture("relationship.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
        end

        it "should get the correct resource" do
          @client.user_relationship(4)
          a_get("users/4/relationship.#{format}").
            with(:query => {:access_token => @client.access_token}).
            should have_been_made
        end

        it "should return a relationship status response" do
          status = @client.user_relationship(4)
          status.incoming_status.should == "requested_by"
        end
      end

      describe ".follow_user" do

        before do
          stub_post("users/4/relationship.#{format}").
            with(:body => {:action => "follow", :access_token => @client.access_token}).
            to_return(:body => fixture("follow_user.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
        end

        it "should get the correct resource" do
          @client.follow_user(4)
          a_post("users/4/relationship.#{format}").
            with(:body => {:action => "follow", :access_token => @client.access_token}).
            should have_been_made
        end

        it "should return a relationship status response" do
          status = @client.follow_user(4)
          status.outgoing_status.should == "requested"
        end
      end

      describe ".unfollow_user" do

        before do
          stub_post("users/4/relationship.#{format}").
            with(:body => {:action => "unfollow", :access_token => @client.access_token}).
            to_return(:body => fixture("unfollow_user.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
        end

        it "should get the correct resource" do
          @client.unfollow_user(4)
          a_post("users/4/relationship.#{format}").
            with(:body => {:action => "unfollow", :access_token => @client.access_token}).
            should have_been_made
        end

        it "should return a relationship status response" do
          status = @client.unfollow_user(4)
          status.outgoing_status.should == "none"
        end
      end

      describe ".block_user" do

        before do
          stub_post("users/4/relationship.#{format}").
            with(:body => {:action => "block", :access_token => @client.access_token}).
            to_return(:body => fixture("block_user.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
        end

        it "should get the correct resource" do
          @client.block_user(4)
          a_post("users/4/relationship.#{format}").
            with(:body => {:action => "block", :access_token => @client.access_token}).
            should have_been_made
        end

        it "should return a relationship status response" do
          status = @client.block_user(4)
          status.outgoing_status.should == "none"
        end
      end

      describe ".unblock_user" do

        before do
          stub_post("users/4/relationship.#{format}").
            with(:body => {:action => "unblock", :access_token => @client.access_token}).
            to_return(:body => fixture("unblock_user.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
        end

        it "should get the correct resource" do
          @client.unblock_user(4)
          a_post("users/4/relationship.#{format}").
            with(:body => {:action => "unblock", :access_token => @client.access_token}).
            should have_been_made
        end

        it "should return a relationship status response" do
          status = @client.unblock_user(4)
          status.outgoing_status.should == "none"
        end
      end

      describe ".approve_user" do

        before do
          stub_post("users/4/relationship.#{format}").
            with(:body => {:action => "approve", :access_token => @client.access_token}).
            to_return(:body => fixture("approve_user.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
        end

        it "should get the correct resource" do
          @client.approve_user(4)
          a_post("users/4/relationship.#{format}").
            with(:body => {:action => "approve", :access_token => @client.access_token}).
            should have_been_made
        end

        it "should return a relationship status response" do
          status = @client.approve_user(4)
          status.outgoing_status.should == "follows"
        end
      end

      describe ".deny_user" do

        before do
          stub_post("users/4/relationship.#{format}").
            with(:body => {:action => "deny", :access_token => @client.access_token}).
            to_return(:body => fixture("deny_user.#{format}"), :headers => {:content_type => "application/#{format}; charset=utf-8"})
        end

        it "should get the correct resource" do
          @client.deny_user(4)
          a_post("users/4/relationship.#{format}").
            with(:body => {:action => "deny", :access_token => @client.access_token}).
            should have_been_made
        end

        it "should return a relationship status response" do
          status = @client.deny_user(4)
          status.outgoing_status.should == "none"
        end
      end
    end
  end
end


text:
""" imageProc is an application to do several simple operations in image processing"""
__author__="tahhan"
__date__ ="$Mar 16, 2012 12:56:40 AM$"

from PyQt4 import QtGui
import sys
from gui import Ui_MainWindow

def main():
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)

    MainWindow.show()

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


text:
BOOL CGStallEstablish::Read( SocketInputStream& iStream )
{
    __ENTER_FUNCTION

    return TRUE ;

    __LEAVE_FUNCTION

        return FALSE ;
}

BOOL CGStallEstablish::Write( SocketOutputStream& oStream )const
{
    __ENTER_FUNCTION

    return TRUE ;

    __LEAVE_FUNCTION

        return FALSE ;
}

UINT CGStallEstablish::Execute( Player* pPlayer )
{
    __ENTER_FUNCTION

        return CGStallEstablishHandler::Execute( this, pPlayer ) ;

    __LEAVE_FUNCTION

        return FALSE ;
}


text:
@class LWPullDownControl;
@protocol LWGridScrollViewDelegate;

@interface LWGridScrollView : UICollectionView

@property (nonatomic, assign) id<LWGridScrollViewDelegate> gridViewDelegate;

//@property (nonatomic,assign) BOOL editing;

@property(nonatomic, retain) NSMutableArray *dataArray;

@property(nonatomic, assign) BOOL editing;

@property(nonatomic, strong) NSIndexPath *movingItemIndexPath;

- (void)updateEditingState:(BOOL)editing;
@end


text:
<!doctype html>

<meta charset=utf-8>

	<input type="text" />
	<button id="postButton">Post</button>

		<button id="removePostEmbed">x</button>


text:
package com.facebook.buck.jvm.java.abi;

import static org.junit.Assert.fail;

import com.facebook.buck.jvm.java.testutil.compiler.Classes;
import com.facebook.buck.jvm.java.testutil.compiler.TestCompiler;
import com.facebook.buck.testutil.integration.TestDataHelper;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import org.junit.Rule;
import org.junit.runners.Parameterized;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;

public class DescriptorAndSignatureFactoryTestBase {
  private static final String WITH_DEPS = "With Dependencies";

  private static final String WITHOUT_DEPS = "Without Dependencies";

  @Parameterized.Parameter public String testMode;

  @Parameterized.Parameters(name = "{0}")
  public static Object[] getParameters() {
    return new Object[] {WITH_DEPS, WITHOUT_DEPS};
  }

  @Rule public TestCompiler correctClassCompiler = new TestCompiler();
  @Rule public TestCompiler testCompiler = new TestCompiler();

  private Classes correctClasses;
  protected Elements elements;
  List<String> errors = new ArrayList<>();

  protected boolean isTestingWithDependencies() {
    return testMode == WITH_DEPS;
  }

  protected void test(TestRunnable r) throws Exception {
    // Always compile with dependencies, so that we have the correct output to compare to
    generateCorrectClassFiles();

    runTest(r);
  }

  private void generateCorrectClassFiles() throws IOException {
    correctClassCompiler.addSourceFile(getSourceFile("Foo.java"));
    correctClassCompiler.addClasspathSourceFile(getSourceFile("Dependency.java"));
    correctClassCompiler.addClasspathSourceFile(getSourceFile("DependencyException.java"));
    correctClassCompiler.addClasspathSourceFile(getSourceFile("DependencyInterface.java"));
    correctClassCompiler.compile();
    correctClasses = correctClassCompiler.getClasses();
  }

  private void runTest(TestRunnable r) throws Exception {
    testCompiler.addSourceFile(getSourceFile("Foo.java"));
    if (testMode == WITH_DEPS) {
      testCompiler.addClasspathSourceFile(getSourceFile("Dependency.java"));
      testCompiler.addClasspathSourceFile(getSourceFile("DependencyException.java"));
      testCompiler.addClasspathSourceFile(getSourceFile("DependencyInterface.java"));
    } else {
      testCompiler.useFrontendOnlyJavacTask();
    }

    testCompiler.setProcessors(
        Collections.singletonList(
            new AbstractProcessor() {
              @Override
              public Set<String> getSupportedOptions() {
                return Collections.emptySet();
              }

              @Override
              public Set<String> getSupportedAnnotationTypes() {
                return Collections.singleton("*");
              }

              @Override
              public SourceVersion getSupportedSourceVersion() {
                return SourceVersion.RELEASE_8;
              }

              @Override
              public boolean process(
                  Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
                if (roundEnv.processingOver()) {
                  try {
                    r.run();
                  } catch (Exception e) {
                    throw new AssertionError(e);
                  }
                }
                return false;
              }
            }));

    elements = testCompiler.getElements();
    testCompiler.enter();
  }

  private Path getSourceFile(String filename) {
    return TestDataHelper.getTestDataScenario(this, "descriptor_and_signature_factories")
        .resolve(filename);
  }

  protected List<String> getTestErrors(
      Function<FieldNode, String> fieldNodeExpectedValueGetter,
      Function<MethodNode, String> methodNodeExpectedValueGetter,
      Function<ClassNode, String> classNodeExpectedValueGetter,
      Function<Element, String> elementActualValueGetter)
      throws IOException {
    TypeElement fooElement = elements.getTypeElement("com.facebook.foo.Foo");
    findErrors(
        fooElement,
        fieldNodeExpectedValueGetter,
        methodNodeExpectedValueGetter,
        classNodeExpectedValueGetter,
        elementActualValueGetter);
    return errors;
  }

  private void findErrors(
      TypeElement typeElement,
      Function<FieldNode, String> fieldNodeExpectedValueGetter,
      Function<MethodNode, String> methodNodeExpectedValueGetter,
      Function<ClassNode, String> classNodeExpectedValueGetter,
      Function<Element, String> elementActualValueGetter)
      throws IOException {
    ClassNode typeNode = getClassNode(elements.getBinaryName(typeElement).toString());
    for (Element enclosedElement : typeElement.getEnclosedElements()) {
      Name elementName = enclosedElement.getSimpleName();
      String actual = elementActualValueGetter.apply(enclosedElement);
      switch (enclosedElement.getKind()) {
        case FIELD:
          checkValue(
              "Field",
              elementName,
              fieldNodeExpectedValueGetter.apply(getFieldNode(typeNode, elementName)),
              actual);
          break;
        case CONSTRUCTOR:
        case METHOD:
          checkValue(
              "Method",
              elementName,
              methodNodeExpectedValueGetter.apply(getMethodNode(typeNode, elementName)),
              actual);
          break;
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
          ClassNode innerTypeNode =
              getClassNode(elements.getBinaryName((TypeElement) enclosedElement).toString());
          checkValue(
              "Class", elementName, classNodeExpectedValueGetter.apply(innerTypeNode), actual);

          findErrors(
              (TypeElement) enclosedElement,
              fieldNodeExpectedValueGetter,
              methodNodeExpectedValueGetter,
              classNodeExpectedValueGetter,
              elementActualValueGetter);
          break;
          // $CASES-OMITTED$
        default:
          fail(
              String.format(
                  "Didn't implement testing for element kind %s", enclosedElement.getKind()));
          continue;
      }
    }
  }

  private void checkValue(String type, Name elementName, String expected, String actual) {
    if (expected != actual && (expected == null || !expected.equals(actual))) {
      errors.add(
          String.format(
              "%s %s:\n\tExpected: %s\n\tActual: %s", type, elementName, expected, actual));
    }
  }

  private FieldNode getFieldNode(ClassNode classNode, Name name) {
    return classNode
        .fields
        .stream()
        .filter(field -> name.contentEquals(field.name))
        .findFirst()
        .orElse(null);
  }

  private MethodNode getMethodNode(ClassNode classNode, Name name) {
    return classNode
        .methods
        .stream()
        .filter(field -> name.contentEquals(field.name))
        .findFirst()
        .orElse(null);
  }

  private ClassNode getClassNode(String classBinaryName) throws IOException {
    ClassNode classNode = new ClassNode(Opcodes.ASM7);
    correctClasses.acceptClassVisitor(classBinaryName, 0, classNode);
    return classNode;
  }

  public interface TestRunnable {
    void run() throws Exception;
  }
}


text:
from flask_sqlalchemy import BaseQuery
from sqlalchemy.dialects.postgresql import INET, MACADDR
from sqlalchemy import distinct, desc
from sqlalchemy.sql import func

from ersa_reporting import db, id_column
from ersa_reporting import get_db_binding

DB_BINDING = get_db_binding(__name__)

class Account(db.Model):
    """OpenStack Account"""
    __bind_key__ = DB_BINDING
    id = id_column()
    openstack_id = db.Column(db.String(128), unique=True, nullable=False)
    instances = db.relationship("Instance", backref="account")

    def json(self):
        """Jsonify"""
        return {"id": self.id, "openstack_id": self.openstack_id}

class Tenant(db.Model):
    """OpenStack Tenant"""
    __bind_key__ = DB_BINDING
    id = id_column()
    openstack_id = db.Column(db.String(128), unique=True, nullable=False)
    instances = db.relationship("Instance", backref="tenant")

    def json(self):
        """Jsonify"""
        return {"id": self.id, "openstack_id": self.openstack_id}

class AvailabilityZone(db.Model):
    """OpenStack AZ/Cell"""
    __bind_key__ = DB_BINDING
    id = id_column()
    name = db.Column(db.String(64), unique=True, nullable=False)
    hypervisors = db.relationship("Hypervisor", backref="availability_zone")
    instances = db.relationship("Instance", backref="availability_zone")

    def json(self):
        """Jsonify"""
        return {"id": self.id, "name": self.name}

class Instance(db.Model):
    """OpenStack VM/Instance"""
    __bind_key__ = DB_BINDING
    id = id_column()
    openstack_id = db.Column(db.String(128), unique=True, nullable=False)
    availability_zone_id = db.Column(None,
                                     db.ForeignKey("availability_zone.id"),
                                     index=True,
                                     nullable=False)
    account_id = db.Column(None,
                           db.ForeignKey("account.id"),
                           index=True,
                           nullable=False)
    tenant_id = db.Column(None,
                          db.ForeignKey("tenant.id"),
                          index=True,
                          nullable=False)
    flavor_id = db.Column(None,
                          db.ForeignKey("flavor.id"),
                          index=True,
                          nullable=False)
    instance_states = db.relationship("InstanceState", backref="instance")
    ip_addresses = db.relationship("IPAddressMapping", backref="instance")
    mac_addresses = db.relationship("MACAddressMapping", backref="instance")

    def latest_state(self, start, end):
        """ Get full information of the latest state of an instance in the query date range

            This includes its internal instance_id, Instnace.openstack_id (server_id),
            InstanceState.name(server), Hypervisor.name (hypervisor),
            AvailabilityZone.name (az), Flavor.openstack_id (flavor),
            Image.openstack_id (image), life span (span), linked
            Account.openstack_id (account), Tenant.openstack_id (tenant).
        """
        state = InstanceState.latest(self.id, start, end)

        state["instance_id"] = self.id
        state["server_id"] = self.openstack_id

        state['account'] = Account.query.get(self.account_id).openstack_id
        state['tenant'] = Tenant.query.get(self.tenant_id).openstack_id
        state['flavor'] = Flavor.query.get(self.flavor_id).openstack_id
        state['az'] = AvailabilityZone.query.get(self.availability_zone_id).name

        return state

    def json(self):
        """Jsonify"""
        return {
            "id": self.id,
            "openstack_id": self.openstack_id,
            "account": self.account_id,
            "tenant": self.tenant_id,
            "flavor": self.flavor_id
        }

class Snapshot(db.Model):
    """A snapshot of the world."""
    __bind_key__ = DB_BINDING
    id = id_column()
    ts = db.Column(db.Integer, unique=True, nullable=False)
    instance_states = db.relationship("InstanceState", backref="snapshot")
    ip_address_mappings = db.relationship("IPAddressMapping",
                                          backref="snapshot")
    mac_address_mappings = db.relationship("MACAddressMapping",
                                           backref="snapshot")

    def json(self):
        """Jsonify"""
        return {"id": self.id, "ts": self.ts}

class IPAddress(db.Model):
    """IP Address (v4 or v6)"""
    __bind_key__ = DB_BINDING
    id = id_column()
    address = db.Column(INET, unique=True, nullable=False)
    family = db.Column(db.Integer, index=True, nullable=False)
    mappings = db.relationship("IPAddressMapping", backref="address")

    def json(self):
        """Jsonify"""
        return {"id": self.id, "address": self.address, "family": self.family}

class MACAddress(db.Model):
    """MAC Address"""
    __bind_key__ = DB_BINDING
    id = id_column()
    address = db.Column(MACADDR, unique=True, nullable=False)
    mappings = db.relationship("MACAddressMapping", backref="address")

    def json(self):
        """Jsonify"""
        return {"id": self.id, "address": self.address}

class Flavor(db.Model):
    """OpenStack Flavor"""
    __bind_key__ = DB_BINDING
    id = id_column()
    openstack_id = db.Column(db.String(128), unique=True, nullable=False)
    name = db.Column(db.String(64), nullable=False)
    vcpus = db.Column(db.Integer)
    ram = db.Column(db.Integer)
    disk = db.Column(db.Integer)
    ephemeral = db.Column(db.Integer)
    public = db.Column(db.Boolean)
    instances = db.relationship("Instance", backref="flavor")

    def json(self):
        """Jsonify"""
        return {
            "id": self.id,
            "openstack_id": self.openstack_id,
            "name": self.name,
            "vcpus": self.vcpus,
            "ram": self.ram,
            "disk": self.disk,
            "ephemeral": self.ephemeral,
            "public": self.public
        }

class Hypervisor(db.Model):
    """OpenStack Hypervisor"""
    __bind_key__ = DB_BINDING
    id = id_column()
    name = db.Column(db.String(128), nullable=False)
    availability_zone_id = db.Column(None,
                                     db.ForeignKey("availability_zone.id"),
                                     nullable=False)
    instance_states = db.relationship("InstanceState", backref="hypervisor")

    def json(self):
        """Jsonify"""
        return {
            "id": self.id,
            "name": self.name,
            "availability_zone": self.availability_zone_id
        }

class InstanceStatus(db.Model):
    """Instance States (e.g. active, error, etc.)"""
    __bind_key__ = DB_BINDING
    id = id_column()
    name = db.Column(db.String(64), unique=True, nullable=False)
    instance_state = db.relationship("InstanceState", backref="status")

    def json(self):
        """Jsonify"""
        return {"id": self.id, "name": self.name}

class Image(db.Model):
    """OpenStack Images"""
    __bind_key__ = DB_BINDING
    id = id_column()
    openstack_id = db.Column(db.String(64), unique=True, nullable=False)
    instance_state = db.relationship("InstanceState", backref="image")

    def json(self):
        """Jsonify"""
        return {"id": self.id, "openstack_id": self.openstack_id}

class InstanceState(db.Model):
    """Point-in-time OpenStack Instance State"""
    __bind_key__ = DB_BINDING
    id = id_column()
    snapshot_id = db.Column(None,
                            db.ForeignKey("snapshot.id"),
                            index=True,
                            nullable=False)
    instance_id = db.Column(None,
                            db.ForeignKey("instance.id"),
                            index=True,
                            nullable=False)
    image_id = db.Column(None, db.ForeignKey("image.id"), nullable=False)
    status_id = db.Column(None,
                          db.ForeignKey("instance_status.id"),
                          nullable=False)
    hypervisor_id = db.Column(None,
                              db.ForeignKey("hypervisor.id"),
                              nullable=False)

    name = db.Column(db.String(128), index=True, nullable=False)

    def json(self):
        """Jsonify"""
        return {
            "id": self.id,
            "name": self.name,
            "snapshot": self.snapshot_id,
            "instance": self.instance_id,
            "image": self.image_id,
            "status": self.status_id,
            "hypervisor": self.hypervisor_id
        }

    @classmethod
    def latest(cls, instance_id, start_ts=0, end_ts=0):
        """" Get the latest information of an instance in a given time range.

             During the life time of an instance, image or hypervisor can be
             changed, only report back the latest one.
        """
        # This retrieves all InstanceState.id and Snapshot.ts in order
        # to get the latest state and calculate span at once.
        # This sacrifices memory usage to avoid multiple database hit.
        query = db.session.query(InstanceState).join(Snapshot).\
                  filter(InstanceState.snapshot_id == Snapshot.id).\
                  filter(InstanceState.instance_id == instance_id).\
                  order_by(desc(Snapshot.ts))

        if start_ts > 0:
            query = query.filter(Snapshot.ts >= start_ts)
        if end_ts > 0:
            query = query.filter(Snapshot.ts < end_ts)

        timely_states = query.with_entities(InstanceState.id, Snapshot.ts)
        latest_state = InstanceState.query.get(timely_states[0][0])
        state = {"server": latest_state.name}
        # state["span"] is the difference between mapped snapshots
        # The accuracy depends on snapshot resolution
        state["span"] = timely_states[0][1] - timely_states[-1][1]
        state["image"] = latest_state.image.openstack_id
        state["hypervisor"] = Hypervisor.query.filter_by(id=latest_state.hypervisor_id).value("name")

        return state

class IPAddressMapping(db.Model):
    """Point-in-time IP-Instance Mapping"""
    __bind_key__ = DB_BINDING
    id = id_column()
    instance_id = db.Column(None,
                            db.ForeignKey("instance.id"),
                            index=True,
                            nullable=False)
    address_id = db.Column(None,
                           db.ForeignKey("ip_address.id"),
                           index=True,
                           nullable=False)
    snapshot_id = db.Column(None,
                            db.ForeignKey("snapshot.id"),
                            index=True,
                            nullable=False)

    def json(self):
        """Jsonify"""
        return {
            "id": self.id,
            "instance": self.instance_id,
            "address": self.address_id,
            "snapshot": self.snapshot_id
        }

class MACAddressMapping(db.Model):
    """Point-in-time MAC-Instance Mapping"""
    __bind_key__ = DB_BINDING
    id = id_column()
    instance_id = db.Column(None,
                            db.ForeignKey("instance.id"),
                            index=True,
                            nullable=False)
    address_id = db.Column(None,
                           db.ForeignKey("mac_address.id"),
                           index=True,
                           nullable=False)
    snapshot_id = db.Column(None,
                            db.ForeignKey("snapshot.id"),
                            index=True,
                            nullable=False)

    def json(self):
        """Jsonify"""
        return {
            "id": self.id,
            "instance": self.instance_id,
            "address": self.address_id,
            "snapshot": self.snapshot_id
        }

class Summary():
    """list distinct instance on sa node between start_ts and end_ts """
    query = None

    def __init__(self, start_ts, end_ts):
        """Build a query to get a distinct list of instance_id bewteen sart and end ts."""
        az_query = db.session.query(Hypervisor).join(AvailabilityZone).\
                     filter(Hypervisor.availability_zone_id == AvailabilityZone.id).\
                     filter(AvailabilityZone.name.like("sa%")).\
                     with_entities(Hypervisor.id).subquery()

        self.query = BaseQuery([Snapshot, InstanceState], db.session()).\
                  filter(Snapshot.ts >= start_ts, Snapshot.ts < end_ts).\
                  filter(InstanceState.snapshot_id == Snapshot.id).\
                  with_entities(InstanceState.instance_id).\
                  distinct(InstanceState.instance_id).\
                  filter(InstanceState.hypervisor_id.in_(az_query))

    def value(self):
        return [item[0] for item in self.query.all()]


text:
void print_time(const char * const head);

#endif


text:
<?php
/**
 * Created by PhpStorm.
 * User: palkin
 * Date: 6/27/14
 * Time: 2:33 AM
 */

namespace Acme\ApiBundle\Subscriber;

use Acme\ApiBundle\Event\ActionEvent;
use Acme\ApiBundle\Event\ActionInviteEvent;
use Acme\ApiBundle\Event\SubactionProgressEvent;
use Acme\EdelaBundle\Entity\Notification;
use Acme\EdelaBundle\Entity\UserActionProgress;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\EntityManager;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ActionProgressSubscriber
{

    private $em;
    private $completeEvent;

    function __construct(EntityManager $em, $completeEvent)
    {
        $this->em = $em;
        $this->completeEvent = $completeEvent;
    }

    public function subactionComplete(SubactionProgressEvent $event, $name, EventDispatcher $dispatcher)
    {
        $action = $event->getSubaction()->getAction();
        $user = $event->getUser();
        $userAction = $this->em->getRepository('AcmeEdelaBundle:UserAction')->findOneBy(array('user' => $user, 'action' => $action));
        $userTime = $user->getCurrentDateTime();
        $dayStart = clone $userTime;
        $dayFinish = clone $userTime;
        $dayStart->modify('today midnight');
        $dayFinish->modify('tomorrow midnight');
        $existingProgress = $this->em->getRepository('AcmeEdelaBundle:UserActionProgress')->matching(
            Criteria::create()
                ->where(Criteria::expr()->eq('userAction', $userAction))
                ->andWhere(Criteria::expr()->gte('createdAt', $dayStart))
                ->andWhere(Criteria::expr()->lte('createdAt', $dayFinish))
        );
        $dispatch = null;
        if (!$existingProgress->count() && $action->getSubactions()->count() == count($this->em->getRepository('AcmeEdelaBundle:Action')->getSubactions($action->getId(), $user, null, true))) {
            $progress = new UserActionProgress();
            $progress->setUserAction($userAction);
            $progress->setResult(1);
            $this->em->persist($progress);
            $dispatch = true;
        } elseif($existingProgress->count()){
            $this->em->remove($existingProgress->first());
            $dispatch = false;
        }
        $this->em->flush();
        if ($dispatch !== null){
            $event = new ActionEvent($action, $user, $dispatch);
            $dispatcher->dispatch($this->completeEvent, $event);
        }
    }

}


text:
import {Firestore} from '@google-cloud/firestore';
import {Store, SessionData} from 'express-session';

export interface StoreOptions {
  dataset: Firestore;
  kind?: string;
}

export class FirestoreStore extends Store {
  db: Firestore;
  kind: string;
  constructor(options: StoreOptions) {
    super();
    this.db = options.dataset;
    if (!this.db) {
      throw new Error('No dataset provided to Firestore Session.');
    }
    this.kind = options.kind || 'Session';
  }

  get = (
    sid: string,
    callback: (err?: Error | null, session?: SessionData) => void
  ) => {
    this.db
      .collection(this.kind)
      .doc(sid)
      .get()
      .then(doc => {
        if (!doc.exists) {
          return callback();
        }

        try {
          const result = JSON.parse(doc.data()!.data);
          return callback(null, result);
        } catch (err) {
          return callback(err as Error);
        }
      }, callback);
  };

  set = (
    sid: string,
    session: SessionData,
    callback?: (err?: Error) => void
  ) => {
    callback = callback || (() => {});
    let sessJson;

    try {
      sessJson = JSON.stringify(session);
    } catch (err) {
      return callback(err as Error);
    }

    this.db
      .collection(this.kind)
      .doc(sid)
      .set({data: sessJson})
      .then(() => {
        callback!();
      });
  };

  destroy = (sid: string, callback?: (err?: Error) => void) => {
    callback = callback || (() => {});
    this.db
      .collection(this.kind)
      .doc(sid)
      .delete()
      .then(() => callback!(), callback);
  };
}


text:
using System;

namespace Test.Core
{
    public interface IUserRepository : IRepository<User>
    {

    }
}


text:
package de.learnlib.algorithms.lstar;

import de.learnlib.algorithms.lstar.moore.ExtensibleLStarMoore;
import de.learnlib.algorithms.rivestschapire.RivestSchapireMooreBuilder;
import de.learnlib.api.oracle.MembershipOracle;
import net.automatalib.words.Alphabet;
import net.automatalib.words.Word;

/**
 * @author frohme
 */
public class RivestSchapireMooreResumableLearnerTest extends ExtensibleLStarMooreResumableLearnerTest {

    @Override
    protected ExtensibleLStarMoore<Character, Character> getLearner(final MembershipOracle<Character, Word<Character>> oracle,
                                                                    final Alphabet<Character> alphabet) {

        return new RivestSchapireMooreBuilder<Character, Character>().withAlphabet(alphabet)
                                                                     .withOracle(oracle)
                                                                     .create();
    }

    @Override
    protected int getRounds() {
        return 3;
    }

}


text:
<?php

if (!is_file($loaderFile = __DIR__.'/../vendor/autoload.php')) {
    throw new \LogicException('Could not find autoload.php in vendor/. Did you run "composer install --dev"?');
}

require $loaderFile;

define('PLUGIN_HOME', realpath(__DIR__.'/../'));


text:
Wiki::Engine.routes.draw do

  root 'application#root'
  match '_new/*path', to: 'pages#new', via: :get, as: 'new_page'
  match '_edit/*path', to: 'pages#edit', via: :get, as: 'edit_page'
  match '_update/*path', to: 'pages#update', via: [:put, :patch], as: 'update_page'
  match '_create/*path', to: 'pages#create', via: [:post], as: 'create_page'
  match '_delete/*path', to: 'pages#destroy', via: [:get, :delete], as: 'destroy_page'

  match '_list', to: 'pages#index', via: :get, as: 'pages'
  match '_log', to: 'pages#log', via: :get, as: 'log'

  match "*path", to: "application#display", via: :get, as: 'page'
  match "*path", to: "application#display", via: :get, as: 'attachment'

end


text:
module Jouba
  class Event < Hashie::Trash
    property :key,       required: true
    property :name,      required: true
    property :data,      required: true
    property :uuid, default: ->(e) { e.send(:raw_uuid).to_s }
    property :version, default: ->(e) { e.send(:raw_uuid).version }
    property :timestamp, default: ->(e) { e.send(:raw_uuid).timestamp }

    def self.serialize(event)
      event.to_h
    end

    def self.deserialize(serialized_event)
      new(serialized_event)
    end

    def self.stream(key, params)
      Jouba.Store.get(key, params).map { |event| Event.deserialize(event) }
    end

    def track
      Jouba.Store.set(key, Event.serialize(self))
    end
    alias_method :save, :track

    private

    def raw_uuid
      @raw_uuid ||= self[:uuid].nil? ? UUID.new : UUID.new(self[:uuid])
    end
  end
end


text:
"""
Miscellaneous transforms.
"""

__docformat__ = 'reStructuredText'

from docutils import nodes
from docutils.transforms import Transform, TransformError

class CallBack(Transform):

    """
    Inserts a callback into a document.  The callback is called when the
    transform is applied, which is determined by its priority.

    For use with `nodes.pending` elements.  Requires a ``details['callback']``
    entry, a bound method or function which takes one parameter: the pending
    node.  Other data can be stored in the ``details`` attribute or in the
    object hosting the callback method.
    """

    default_priority = 990

    def apply(self):
        pending = self.startnode
        pending.details['callback'](pending)
        pending.parent.remove(pending)

class ClassAttribute(Transform):

    """
    Move the "class" attribute specified in the "pending" node into the
    immediately following non-comment element.
    """

    default_priority = 210

    def apply(self):
        pending = self.startnode
        parent = pending.parent
        child = pending
        while parent:
            # Check for appropriate following siblings:
            for index in range(parent.index(child) + 1, len(parent)):
                element = parent[index]
                if (isinstance(element, nodes.Invisible) or
                    isinstance(element, nodes.system_message)):
                    continue
                element['classes'] += pending.details['class']
                pending.parent.remove(pending)
                return
            else:
                # At end of section or container; apply to sibling
                child = parent
                parent = parent.parent
        error = self.document.reporter.error(
            'No suitable element following "%s" directive'
            % pending.details['directive'],
            nodes.literal_block(pending.rawsource, pending.rawsource),
            line=pending.line)
        pending.replace_self(error)

class Transitions(Transform):

    """
    Move transitions at the end of sections up the tree.  Complain
    on transitions after a title, at the beginning or end of the
    document, and after another transition.

    For example, transform this::

            ...
            <transition>

            ...

    into this::

            ...
        <transition>

            ...
    """

    default_priority = 830

    def apply(self):
        for node in self.document.traverse(nodes.transition):
            self.visit_transition(node)

    def visit_transition(self, node):
        index = node.parent.index(node)
        error = None
        if (index == 0 or
            isinstance(node.parent[0], nodes.title) and
            (index == 1 or
             isinstance(node.parent[1], nodes.subtitle) and
             index == 2)):
            assert (isinstance(node.parent, nodes.document) or
                    isinstance(node.parent, nodes.section))
            error = self.document.reporter.error(
                'Document or section may not begin with a transition.',
                line=node.line)
        elif isinstance(node.parent[index - 1], nodes.transition):
            error = self.document.reporter.error(
                'At least one body element must separate transitions; '
                'adjacent transitions are not allowed.', line=node.line)
        if error:
            # Insert before node and update index.
            node.parent.insert(index, error)
            index += 1
        assert index < len(node.parent)
        if index != len(node.parent) - 1:
            # No need to move the node.
            return
        # Node behind which the transition is to be moved.
        sibling = node
        # While sibling is the last node of its parent.
        while index == len(sibling.parent) - 1:
            sibling = sibling.parent
            # If sibling is the whole document (i.e. it has no parent).
            if sibling.parent is None:
                # Transition at the end of document.  Do not move the
                # transition up, and place an error behind.
                error = self.document.reporter.error(
                    'Document may not end with a transition.',
                    line=node.line)
                node.parent.insert(node.parent.index(node) + 1, error)
                return
            index = sibling.parent.index(sibling)
        # Remove the original transition node.
        node.parent.remove(node)
        # Insert the transition after the sibling.
        sibling.parent.insert(index + 1, node)


text:
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <link href="http://v4.pingendo.com/assets/bootstrap/themes/default.css" rel="stylesheet" type="text/css">

          <form class="">

              Name
              <input type="text" class="form-control" placeholder="E.g. Parmigiano Reggiano">

              Description
              <input type="text" class="form-control" placeholder="e.g. A straw-yellow, crumbly, grainy texture with a superb, fruity flavour.">

              Label
              <input type="text" class="form-control" placeholder="e.g. Blue, Hard, Soft">

            <button type="submit" class="btn btn-primary" id="btn-add-cheese">Add cheese</button>
          </form>


text:
import re

import occi

from render_base import Renderer
from render_text import *

class HTTPHeadersRenderer(TextRenderer):
    """HTTP Headers OCCI Renderer

    RFC 7230 http://www.ietf.org/rfc/rfc7230.txt.

    Empty string is always returned as body during rendering.

    Beware of HTTP Headers size limitations. It is better to not use 'text/occi' mimetype for transfering OCCI Category Collection.
    """

    reHeaderChunk = re.compile(r'(?P<chunk>((?P<quoted>"([^"\\]|\\.)*")|(?P<term>[^,"\\]+))*)(?P<sep>\s*,\s*)?')

    def render_category(self, category):
        """Render OCCI Category

        :param occi.Category category: OCCI Category object
        :return: render result
        :rtype: [string, string[]]
        """
        return ['', ['Category: ' + text_category(category)]]

    def render_categories(self, categories):
        """Render OCCI Category collection

        :param occi.Category category[]: OCCI Category array
        :return: render result
        :rtype: [string, string[]]
        """
        if not categories:
            return ['', []]
        res = []
        for category in categories:
            res.append(text_category(category))
        return ['', ['Category: ' + ','.join(res)]]

    def render_links(self, links):
        """ Render OCCI Links

        :param occi.Link link[]: OCCI Link array
        :return: render result
        :rtype: string[]
        """
        if not links:
            return []
        res = []
        for link in links:
            res.append(text_link(link))
        return ['Link: ' + ','.join(res)]

    def render_attributes(self, attributes):
        """Render Attributes

        :param occi.Attribute attribute[]: OCCI Attribute object
        :return: render result
        :rtype: string[]
        """
        if not attributes:
            return []

        s = []
        for attribute in attributes:
            s.append(text_attribute_repr(attribute))
        return ['X-OCCI-Attribute: ' + ','.join(s)]

    def render_locations(self, locations):
        """ Render Locations

        :param string location: location URI
        :return: render result
        :rtype: [string, string[]]
        """
        return ['', ['X-OCCI-Location: ' + ','.join(locations)]]

    def render_resource(self, categories, links=None, attributes=None):
        """Render OCCI Resource instance

        :param occi.Category category: OCCI Category object
        :param occi.Link links[]: OCCI Link array
        :param occi.Attribute attributes[]: OCCI Attribute array
        :return: render result
        :rtype: [string, string[]]
        """
        Renderer.render_resource(self, categories, links, attributes)
        res = []
        cat_s, cat_h = self.render_categories(categories)
        res += cat_h
        if links is not None:
            res += self.render_links(links)
        if attributes is not None:
            res += self.render_attributes(attributes)
        return ['', res]

    def parse_header_values(self, body):
        """Helper generator method to split values in HTTP Header.

        :param string body: parsed text
        :return: result values
        :rtype: string
        """
        m = None
        while body:
            m = HTTPHeadersRenderer.reHeaderChunk.match(body)
            #print m
            #if m:
            #    print m.groupdict()
            #    print m.end()
            # error on empty match
            if m is None or m.group('chunk') is None or m.end() == 0:
                raise occi.ParseError('Bad quoting in HTTP Headers', body)
                m = None
                break
            chunk = m.group('chunk')
            body = body[m.end():]
            if body and not m.group('sep'):
                raise occi.ParseError('Separator expected in HTTP Headers (%s)' % chunk, body)
                m = None
                break
            yield chunk.strip(' \t')
            #print 'remains: #%s#' % body
        if m and m.group('sep'):
            yield ''

    def parse_categories(self, body, headers):
        """Parse OCCI Category Collection

        Beware of HTTP Headers size limitations. It is better to not use 'text/occi' mimetype for transfering OCCI Category Collection.

        :param string body[]: text to parse (unused in plain/occi)
        :param string headers[]: headers to parse
        :return: Array of OCCI Categories
        :rtype: occi.Category[]
        """
        categories = []
        category_ids = set()

        for line in headers:
            line = line.rstrip('\r\n')
            matched = TextRenderer.reCategory.match(line)
            if not matched:
                continue

            line = line[matched.end():]
            #print 'CATEGORY HIT:'
            #print line
            bodies = self.parse_header_values(line)
            #print 'SPLAT BODIES:'
            #print '\n\n'.join(bodies)

            for cat_s in bodies:
                # use the helper parser function inherited from text/plain renderer
                category = TextRenderer.parse_category_body(self, cat_s)

                # check uniqueness
                key = category['term'] + category['scheme']
                if key in category_ids:
                    raise occi.ParseError('Category not unique (term "%s", scheme "%s")' % (category['term'], category['scheme']), cat_s)
                category_ids.add(key)

                categories.append(category)

        return categories

    def parse_locations(self, body, headers):
        """Parse OCCI Entity collection

        :param string body[]: text to parse (unused in text/occi)
        :param string headers[]: headers to parse
        :return: Array of links
        :rtype: string[]
        """
        locations = []
        for line in headers:
            line = line.rstrip('\r\n')
            matched = TextRenderer.reLocation.match(line)
            if not matched:
                continue
            uris_str = matched.group(2)
            uris = self.parse_header_values(uris_str)
            for uri in uris:
                if not check_url(uri, scheme=True, host=True):
                    raise occi.ParseError('Invalid URI in OCCI Entity collection', line)
                locations.append(uri)

        return locations

    def parse_resource(self, body, headers):
        """Parse OCCI Resource instance

        :param string body[]: text to parse (unused in text/occi)
        :param string headers[]: headers to parse
        :return: categories, links, and attributes
        :rtype: [occi.Category categories[], occi.Link links[], occi.Attribute attributes[]]
        """
        categories = []
        links = []
        attributes = []

        for line in headers:
            line = line.rstrip('\r\n')

            matched = TextRenderer.reCategory.match(line)
            if matched is not None:
                cats_str = line[matched.end():]
                for s in self.parse_header_values(cats_str):
                    categories.append(self.parse_category_body(s))
                continue

            matched = TextRenderer.reLink.match(line)
            if matched is not None:
                links_str = line[matched.end():]
                for s in self.parse_header_values(links_str):
                    links.append(self.parse_link_body(s))
                continue

            matched = TextRenderer.reAttribute.match(line)
            if matched is not None:
                attrs_str = line[matched.end():]
                for s in self.parse_header_values(attrs_str):
                    attributes.append(self.parse_attribute_body(s))
                continue
            else:
                continue

        return [categories, links, attributes]


text:
module TableOfContents
  def render_toc
    toc_item = @items.find { |i| i.identifier == '/table-of-contents/' }
    toc_lines = toc_item.raw_content.lines
    result = '
'
    section_count = 0
    toc_lines.each do |line|
      unless line.empty? || (line == "\r\n") # SMELL Windows line feed
        section_count += 1
        result += "
#{line}
"
      end
    end
    result += '
'
    result
  end
end

include TableOfContents

require 'nanoc/filters/javascript_concatenator'
require 'compass'
require 'zurb-foundation'
#require 'faker'

# NOTE: don't need all these - copied over from nanoc-blog template project
include Nanoc::Helpers::Blogging
include Nanoc::Helpers::Tagging
include Nanoc::Helpers::Rendering
include Nanoc::Helpers::LinkTo
include Nanoc::Helpers::XMLSitemap

unless defined? LOADED_DEFAULT_CONFIG
  LOADED_DEFAULT_CONFIG = true

  Compass.add_project_configuration 'compass/config.rb'
end


text:
#include "StepperControlEncoder.h"

StepperControlEncoder::StepperControlEncoder()
{
  //lastCalcLog	= 0;

  pinChannelA = 0;
  pinChannelB = 0;

  position = 0;
  encoderType = 0; // default type
  scalingFactor = 100;

  curValChannelA = false;
  curValChannelA = false;
  prvValChannelA = false;
  prvValChannelA = false;

  readChannelA = false;
  readChannelAQ = false;
  readChannelB = false;
  readChannelBQ = false;
}

void StepperControlEncoder::test()
{
  /*
                Serial.print("R88 ");
                Serial.print("position ");
                Serial.print(position);
                Serial.print(" channel A ");
                Serial.print(prvValChannelA);
                Serial.print(" -> ");
                Serial.print(curValChannelA);
                Serial.print(" channel B ");
                Serial.print(prvValChannelB);
                Serial.print(" -> ");
                Serial.print(curValChannelB);
                Serial.print("\r\n");
*/
}

void StepperControlEncoder::loadPinNumbers(int channelA, int channelB, int channelAQ, int channelBQ)
{
  pinChannelA = channelA;
  pinChannelB = channelB;
  pinChannelAQ = channelAQ;
  pinChannelBQ = channelBQ;

  readChannels();
  shiftChannels();
}

void StepperControlEncoder::loadSettings(int encType, int scaling, int invert)
{
  encoderType = encType;
  scalingFactor = scaling;
  if (invert == 1)
  {
    encoderInvert = -1;
  }
  else
  {
    encoderInvert = 1;
  }

}

void StepperControlEncoder::setPosition(long newPosition)
{
  position = newPosition;
}

long StepperControlEncoder::currentPosition()
{

  // Apply scaling to the output of the encoder, except when scaling is zero or lower
  //return position;
  if (scalingFactor == 100 || scalingFactor <= 0)
  {
    return position * encoderInvert;
  }
  else
  {
    return position * scalingFactor / 100 * encoderInvert;
  }
}

/* Check the encoder channels for movement accoridng to thisspecification
                    ________            ________
Channel A          /        \          /        \
             _____/          \________/          \________
                         ________            ________
Channel B               /        \          /        \
             __________/          \________/          \____
                                   __
Channel I                         /  \
             ____________________/    \___________________

rotation ----------------------------------------------------->

*/

void StepperControlEncoder::readEncoder()
{

  // save the old values, read the new values
  shiftChannels();
  readChannels();

  int delta = 0;

  // and check for a position change
  // no fancy code, just a few simple compares. sorry

  //// Only detect edges on the A channel when the V channel is high
  //if (curValChannelB == true && prvValChannelA == false && curValChannelA == true)
  //{
  //  delta--;
  //}
  //if (curValChannelB == true && prvValChannelA == true && curValChannelA == false)
  //{
  //  delta++;
  //}

  if (prvValChannelA == true && curValChannelA == true && prvValChannelB == false && curValChannelB == true)
  {
    delta++;
  }
  if (prvValChannelA == true && curValChannelA == false && prvValChannelB == true && curValChannelB == true)
  {
    delta++;
  }
  if (prvValChannelA == false && curValChannelA == false && prvValChannelB == true && curValChannelB == false)
  {
    delta++;
  }
  if (prvValChannelA == false && curValChannelA == true && prvValChannelB == false && curValChannelB == false)
  {
    delta++;
  }

  if (prvValChannelA == false && curValChannelA == false && prvValChannelB == false && curValChannelB == true)
  {
    delta--;
  }
  if (prvValChannelA == false && curValChannelA == true && prvValChannelB == true && curValChannelB == true)
  {
    delta--;
  }
  if (prvValChannelA == true && curValChannelA == true && prvValChannelB == true && curValChannelB == false)
  {
    delta--;
  }
  if (prvValChannelA == true && curValChannelA == false && prvValChannelB == false && curValChannelB == false)
  {
    delta--;
  }

  position += delta;
}

void StepperControlEncoder::readChannels()
{

  // read the new values from the coder

  readChannelA = digitalRead(pinChannelA);
  readChannelB = digitalRead(pinChannelB);

  encoderType = 0; // TEVE 2017-04-20 Disabling the quadrature channels. They take too much time to read.

  if (encoderType == 1)
  {
    readChannelAQ = digitalRead(pinChannelAQ);
    readChannelBQ = digitalRead(pinChannelBQ);

    // differential encoder
    if ((readChannelA ^ readChannelAQ) && (readChannelB ^ readChannelBQ))
    {
      curValChannelA = readChannelA;
      curValChannelB = readChannelB;
    }
  }
  else
  {

    // encoderType <= 0
    // non-differential incremental encoder
    curValChannelA = readChannelA;
    curValChannelB = readChannelB;
  }

  //curValChannelA = readChannelA;
  //curValChannelB = readChannelB;

  //	curValChannelA = digitalRead(pinChannelA);
  //	curValChannelB = digitalRead(pinChannelB);
}

void StepperControlEncoder::shiftChannels()
{

  // Save the current enoder status to later on compare with new values

  prvValChannelA = curValChannelA;
  prvValChannelB = curValChannelB;
}


text:
<?php query_posts( dpa_change_picture_get_query() ) ?>
<?php if ( dpa_change_picture_has_pictures() && current_user_can( 'upload_files' ) ) : ?>

			<?php dpa_change_picture_pagination_count() ?>

			<?php dpa_change_picture_pagination() ?>

	<form class="achievement-changepicture-form standard-form" method="post" action="<?php dpa_achievement_slug_permalink(); echo DPA_SLUG_ACHIEVEMENT_CHANGE_PICTURE ?>">
	<?php if ( dpa_change_picture_has_manylots() ) : ?>

<?php printf( __( "We've noticed that you've got a lot of pictures to choose from. Set a filter to restrict which images are retrieved from your WordPress Media Library.", 'dpa' ), admin_url( 'admin.php?page=achievements' ), admin_url( 'upload.php' ) ) ?>

	<?php endif;  ?>

	<?php while ( have_posts() ) : the_post(); list( $img_src ) = image_downsize( get_the_ID(), 'thumbnail' ); ?>
		<img class="avatar-preview <?php if ( dpa_get_achievement_picture_id() == get_the_ID() ) { echo 'avatar-preview-selected'; } ?>" id="a<?php the_ID() ?>" src="<?php echo esc_attr( $img_src ) ?>" />
	<?php endwhile; ?>

	<input type="submit" name="achievement-change-picture" id="achievement-change-picture" value="<?php _e( 'Update Picture', 'dpa' ) ?>">
	<input type="hidden" name="picture_id" id="picture_id" value="<?php echo esc_attr( dpa_get_achievement_picture_id() ) ?>" />

	<?php wp_nonce_field( 'achievement-change-picture-' . dpa_get_achievement_slug() ) ?>
	</form>

			<?php dpa_change_picture_pagination_count() ?>

			<?php dpa_change_picture_pagination() ?>

<?php elseif ( current_user_can( 'upload_files' ) ) : ?>

<?php printf( __( "Before you can choose a picture, you need to upload an image to the WordPress Media Library.", 'dpa' ), admin_url( 'upload.php' ) ) ?>

<?php else : ?>

<?php _e( "Unfortunately, there aren't any pictures to choose from. You'll need to ask an Administrator to upload some to the WordPress Media Library for you.", 'dpa' ) ?>

<?php endif; ?>


text:
@interface KBAFinanceController : KBAViewController

-(IBAction)scheduleYears;

-(IBAction)scheduleInterest;

-(IBAction)scheduleCreditSum;

-(IBAction)scheduleRate;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="course.examples.networking.json">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/MaterialTheme">
        <activity
            android:name=".NetworkingJSONResponseActivity"
            android:label="@string/app_name"/>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>