text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Path Finding Project: Class Members - Variables</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Path Finding Project
    1.0

A path finding project to find shortest path.

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

All

Functions

Variables

 All Classes Files Functions Variables Macros

edges
: PathFindingAlgorithm

goal
: PathFindingAlgorithm

nodes
: PathFindingAlgorithm

path
: PathFindingAlgorithm

start
: PathFindingAlgorithm

totalCost
: PathFindingAlgorithm

<address class="footer">
Generated on Mon Mar 13 2017 23:01:59 for Path Finding Project by

 1.8.6
</address>


text:
#include "comingupviewitemmodel.h"
#include "mviewmanager.h"
#include "calendarevent.h"
#include <kdatetime.h>

ComingUpViewItemModel::ComingUpViewItemModel( MViewManager& manager, bool showOnlyNextFewEvents) :
viewManager(manager),
restrictEventCount(showOnlyNextFewEvents)
{
    modelEventList = new QList<CalendarEvent*>();
    theHeaderData.append("Title");
    theHeaderData.append("Subtitle");
    updateEvents();
}

ComingUpViewItemModel::~ComingUpViewItemModel()
{
    delete modelEventList;
}

int ComingUpViewItemModel::rowCount(const QModelIndex& /*parent*/ ) const
{
    return theData.size();
}

int ComingUpViewItemModel::columnCount(const QModelIndex& /*parent*/ ) const
{
    return theHeaderData.size();
}

QVariant ComingUpViewItemModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DisplayRole) {
        if (index.isValid() && index.row() < theData.size()) {
            QStringList rowData = theData[index.row()];
            return QVariant(rowData);
        }
    }

    return QVariant();
}

void ComingUpViewItemModel::updateEvents()
{
    modelEventList->clear();
    theData.clear();

    QList<CalendarEvent*>& eventList = viewManager.GetEvents();

    //int eventsLimitedTo = 3, comingUpEventCnt=0;
    int cntr = eventList.count();
    QDate today = QDate::currentDate();
    KDateTime daysLaterDate = KDateTime(today.addDays(7));

    for ( int i=0;i<cntr;i++ ) {
        CalendarEvent* event = eventList.at(i);
        bool addEvent = false;
        //Bug#7244 Author: sirisha.muppavarapu@intel.com
        //Fixed the issue with display of "coming up" "Later" event list
        if ( restrictEventCount == true ) {
            if ( today == event->StartDate().date() )
            {
             addEvent = true;
            }
        } else {
            if(event->StartDate().date() > daysLaterDate.date()) {
                break;
            } else if ( event->StartDate().date() > today )
            {
                addEvent = true;
            }
        }

        if ( addEvent ) {
            modelEventList->append(event);
            QString dateString;
            //Bug#7320 Author: sirisha.muppavarapu@intel.com
            //This piece of code fixes the issue with display of event
            //If today: Display time followed by event
            //Else Display Date-time followed by event
            if(today == event->StartDate().date()) {
                dateString = event->StartDate().toString ( "hh:mm AP" );
            } else {
                dateString = event->StartDate().toString ( "ddd dd hh:mm AP" );
            }
            QString alarmsString("alarmOFF");
            if ( event->Alarm() ) {
                alarmsString = "alarmON";
            }
            theData.append( QStringList() << dateString << event->Description() << alarmsString );
        }
    }
}

CalendarEvent* ComingUpViewItemModel::selectedEvent(int index)
{
    if ( index <0 || index > modelEventList->count()-1 )
    {
        return 0;
    }

    return modelEventList->at(index);
}

redpajama_set_name: RedPajamaGithub


text:
import { ALL_PRODUCTS } from "../../../shared/product";

export type ProductStyle = {
  bg: string;
  text: string;
  iconBorder: string;
};

const styles: Record<string, ProductStyle> = {
  android: {
    bg: "bg-android-bg",
    text: "text-android-text",
    iconBorder: "border-android-accent",
  },
  angular: {
    bg: "bg-angular-bg",
    text: "text-angular-text",
    iconBorder: "border-angular-accent",
  },
  cloud: {
    bg: "bg-cloud-bg",
    text: "text-cloud-text",
    iconBorder: "border-cloud-accent",
  },
  firebase: {
    bg: "bg-firebase-bg",
    text: "text-firebase-text",
    iconBorder: "border-firebase-accent",
  },
  flutter: {
    bg: "bg-flutter-bg",
    text: "text-flutter-text",
    iconBorder: "border-flutter-accent",
  },
  ml: {
    bg: "bg-ml-bg",
    text: "text-ml-text",
    iconBorder: "border-ml-accent",
  },
  assistant: {
    bg: "bg-assistant-bg",
    text: "text-assistant-text",
    iconBorder: "border-assistant-accent",
  },
};

// Listing these classes here means that PurgeCSS will not
// drop them.
const TAG_BG_COLORS = [
  "bg-blue-50",
  "bg-green-50",
  "bg-yellow-50",
  "bg-indigo-50",
  "bg-red-50",
  "bg-purple-50",
  "bg-pink-50",
];

const TAG_TEXT_COLORS = [
  "text-blue-500",
  "text-green-500",
  "text-yellow-500",
  "text-indigo-500",
  "text-red-500",
  "text-purple-500",
  "text-pink-500",
];

export function getStyle(product: string) {
  return styles[product];
}

export function getTag(product: string, value: string) {
  const p = ALL_PRODUCTS[product];
  const ind = p.tags.findIndex((t) => t.value === value);

  if (ind < 0) {
    console.warn("Warning: unknown tag", value);
    return {
      label: value.charAt(0).toUpperCase() + value.slice(1),
      color: "bg-gray-500",
    };
  }

  const t = p.tags[ind];
  return {
    label: t.label,
    textColor: TAG_TEXT_COLORS[ind % TAG_TEXT_COLORS.length],
    bgColor: TAG_BG_COLORS[ind % TAG_BG_COLORS.length],
  };
}


text:
import test from 'ava';

import compute from 'can-compute';

import canStreamX from '.';

import DefineList from 'can-define/list/list';

import Kefir from 'kefir';

const canStream = canStreamX({
  streamConstructor: Kefir.stream,
  emitMethod: 'emit',
  on: 'onValue',
  off: 'offValue'
});

/** import DefineList from 'can-define/list/list'; **/
test('Compute changes can be streamed', (t) => {
  const c = compute(0);

  const stream = canStream.toStream(c);

  let computeVal;

  stream.onValue((newVal) => {
    computeVal = newVal;
  });

  t.is(computeVal, 0);

  c(1);
  t.is(computeVal, 1);

  c(2);
  t.is(computeVal, 2);

  c(3);
  t.is(computeVal, 3);

  t.pass();
});

test('Compute streams do not bind to the compute unless activated', (t) => {
  const c = compute(0);
  const stream = canStream.toStream(c);
  t.is(c.computeInstance.__bindEvents, undefined);
  stream.onValue(() => {});
  t.is(c.computeInstance.__bindEvents._lifecycleBindings, 1);
});

test('Compute stream values can be piped into a compute', (t) => {
  let expected = 0;
  const c1 = compute(0);
  const c2 = compute(0);

  const resultCompute = canStream.toStream(c1).merge(canStream.toStream(c2));

  resultCompute.onValue((val) => {
    t.is(val, expected);
  });

  expected = 1;
  c1(1);

  expected = 2;
  c2(2);

  expected = 3;
  c1(3);
});

test('Computed streams fire change events', (t) => {
  let expected = 0;
  const c1 = compute(expected);
  const c2 = compute(expected);

  const resultCompute = canStream.toStream(c1).merge(canStream.toStream(c2));

  resultCompute.onValue((val) => {
    t.is(expected, val);
  });

  expected = 1;
  c1(expected);

  expected = 2;
  c2(expected);

  expected = 3;
  c1(expected);
});

test('Create a stream from a compute with shorthand method: toStream', (t) => {
  let expected = 0;
  const c1 = compute(0);

  const resultCompute = canStream.toStream(c1);

  resultCompute.onValue((val) => {
    t.is(val, expected);
  });

  expected = 1;
  c1(1);
});

test('toCompute(streamMaker) can-define-stream#17', (t) => {
  const c = compute('a');

  const letterStream = canStream.toStream(c);

  const streamedCompute = canStream.toCompute(setStream => setStream.merge(letterStream));

  streamedCompute.on('change', (ev, newVal) => {

  });

  t.is(streamedCompute(), 'a');

  c(1);
  t.is(streamedCompute(), 1);

  c('b');
  t.is(streamedCompute(), 'b');
});

test('setting test', (t) => {
  const c = canStream.toCompute(setStream => setStream);

  c(5);
  // listen to the compute for it to have a value
  c.on('change', () => {});

  // immediate value
  t.is(c(), 5);
});

test('Stream on DefineList', (t) => {
  let expectedLength;

  const people = new DefineList([
    { first: 'Justin', last: 'Meyer' },
    { first: 'Paula', last: 'Strozak' },
  ]);

  const stream = canStream.toStream(people, '.length');

  expectedLength = 2;

  stream.onValue((newLength) => {
    t.is(newLength, expectedLength);
  });

  expectedLength = 3;

  people.push({
    first: 'Obaid',
    last: 'Ahmed',
  });

  expectedLength = 2;

  people.pop();
});

test('Test if streams are memory safe', function(t) {
  const c = canStream.toCompute(setStream => setStream);
  const handler = (ev, newVal, oldVal) => {
    console.log('newVal', newVal); //->output: obaid
  };
  c.on('change', handler);

  t.is(c.computeInstance.__bindEvents._lifecycleBindings, 1);

  c.off('change', handler);

  t.is(c.computeInstance.__bindEvents._lifecycleBindings, 0);
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/../../../../../../DATA/work/test/conductorTest/app/app.iml" filepath="$PROJECT_DIR$/../../../../../../DATA/work/test/conductorTest/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/../../../../../../DATA/work/test/conductorTest/conductorTest.iml" filepath="$PROJECT_DIR$/../../../../../../DATA/work/test/conductorTest/conductorTest.iml" />
    </modules>
  </component>
</project>


text:
<?php
declare(strict_types=1);

namespace Fcds\IvvyTest\Model\Validator;

use Fcds\Ivvy\Model\BusinessRuleException;
use Fcds\Ivvy\Model\Address;
use Fcds\Ivvy\Model\Company;
use Fcds\Ivvy\Model\Validator\UpdateCompanyValidator;
use Fcds\Ivvy\Model\Validator\Validator;
use Fcds\IvvyTest\BaseTestCase;

/**
 * Class: UpdateCompanyValidatorTest
 *
 * @see BaseTestCase
 * @final
 * @covers Fcds\Ivvy\Model\Validator\UpdateCompanyValidator
 * @covers Fcds\Ivvy\Model\Company
 */
final class UpdateCompanyValidatorTest extends BaseTestCase
{
    /** @var Validator */
    protected $validator;

    public function setUp()
    {
        $this->validator = new UpdateCompanyValidator();
    }

    public function testSuccessfulValidation()
    {
        $company = new Company([
            'id' => 100,
            'address' => new Address([
                'countryCode' => 'AU',
                'stateCode'   => 'QLD',
                'postalCode'  => '4227',
            ]),
        ]);

        $result = $company->validate($this->validator);

        $this->assertTrue(true); // Everythign is fine
    }

    public function testValidateCompanyWithNoAddressOrCountryCodeOrStateCodeOrPostalCode()
    {
         $this->expectException(BusinessRuleException::class);

         $company = new Company([
             'id' => 100,
         ]);

        $company->validate($this->validator);
    }

    public function testValidateCompanyWithNoId()
    {
        $this->expectException(BusinessRuleException::class);

        $company = new Company;

        $result = $company->validate($this->validator);
    }
}


text:
@extends('layouts.app')

@section('content')

            	@include('videos.listing')

@endsection


text:
package org.ibase4j.mq.topic;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

@Service
public class TopicMessageListener implements MessageListener {
    private final Logger logger = LogManager.getLogger();

    public void onMessage(Message message) {
        try {
            System.out.println("TopicMessageListener接收到消息:" + ((ObjectMessage) message).getObject());
        } catch (JMSException e) {
            logger.error(e);
        }
    }
}


text:
'use strict';

/* Directives */

angular.module('directives', [])
  .directive('predicateRow', [
    function(){
        return {
            restrict: 'E',
            templateUrl: 'partials/predicateRow.html'
        }
    }
  ]);


text:
from collections import defaultdict
import functools
from multiprocessing import Array
import os
import time
import psutil
import numpy as np
import signal

from agent import Agent, TerminationEx
import util
import constants

class HeavyLearner(Agent):
    """Multiplies matrices, pointlessly."""
    def __init__(self, **kwargs):
        super(HeavyLearner, self).__init__(**kwargs)

    def first_action(self):
        self.send_to_parent(dict(sender=self.name, subject='HeavyLearner'))

    def read_messages(self):
        while True:
            try:
                message = self.inbox.pop(0)
                #print message
                self.standard_responses(message)
            except (IndexError, AttributeError):
                break

    def next_action(self):
        #self.send_to_parent(dict(sender=self.name, subject='HeavyLearner'))
        m1 = np.random.random_integers(0, 100, (1000, 1000))
        m2 = np.random.random_integers(0, 100, (1000, 1000))
        m3 = np.dot(m1, m2)

class SimpleLearner(Agent):
    """Very simple learner"""
    def __init__(self, **kwargs):
        super(SimpleLearner, self).__init__(**kwargs)
        self.actioncounter = 0

    def first_action(self):
        self.send_to_parent(dict(sender=self.name, subject='SimpleLearner'))

    def read_messages(self):
        while True:
            try:
                message = self.inbox.pop(0)
                #print message
                self.standard_responses(message)
            except (IndexError, AttributeError):
                break

    def next_action(self):
        self.read_messages()
        #if self.data is not None:
        #    print self.data.items()
        self.send_to_parent(dict(sender=self.name, subject='SimpleLearner', value=self.actioncounter))
        self.actioncounter += 1

class RecursiveLearner(Agent):
    """Makes a child of the same class, unless recursion_level is zero in which case it
    makes a sub learner. Passes all messages from children to parent, and prints a message
    about itself each second"""
    def __init__(self, recursion_level=0, sub_learner=HeavyLearner, **kwargs):
        super(RecursiveLearner, self).__init__(**kwargs)
        self.recursion_level = recursion_level
        self.sub_learner = sub_learner

    def first_action(self):
        if self.recursion_level == 0:
            learners = [self.sub_learner]
        else:
            # learners = [(RecursiveLearner, {'recursion_level': self.recursion_level - 1})]
            learners = [(RecursiveLearner, {'recursion_level': self.recursion_level - 1,
                                            'sub_learner': self.sub_learner}),
                        (RecursiveLearner, {'recursion_level': self.recursion_level - 1,
                                            'sub_learner': self.sub_learner})]
        self.create_children(classes=learners)
        self.start_children()
        self.send_to_parent(dict(sender=self.name, subject='RecursiveLearner'))

    def read_messages(self):
        while True:
            try:
                message = self.inbox.pop(0)
                #print message
                self.standard_responses(message)
            except (IndexError, AttributeError):
                break

    def next_action(self):
        self.read_messages()
        for name, inbox in self.child_inboxes.iteritems():
            while True:
                try:
                    message = inbox.pop(0)
                    # message['sender'] = self.name + '.' + message['sender']
                    self.send_to_parent(message)
                except IndexError:
                    break

class ImmortalLearner(Agent):
    """Never dies! Also checks its messages really infrequently"""
    # This tests the process killing functions
    def __init__(self, **kwargs):
        super(ImmortalLearner, self).__init__(**kwargs)

    def read_messages(self):
        while True:
            try:
                message = self.inbox.pop(0)
                #print message
                self.standard_responses(message)
            except (IndexError, AttributeError):
                break

    def next_action(self):
        self.read_messages()
        self.send_to_parent(dict(sender=self.name, subject='I am immortal'))
        time.sleep(60)

class QuickLearner(Agent):
    """Finishes immediately"""
    # Should have finished, and therefore not be pickled
    def __init__(self, **kwargs):
        super(QuickLearner, self).__init__(**kwargs)

    def read_messages(self):
        while True:
            try:
                message = self.inbox.pop(0)
                #print message
                self.standard_responses(message)
            except (IndexError, AttributeError):
                break

    def next_action(self):
        self.read_messages()
        self.send_to_parent(dict(sender=self.name, subject='I am really fast'))
        raise TerminationEx

class BigLearner(Agent):
    """Stores a large (64MiB) matrix, pointlessly."""
    def __init__(self, **kwargs):
        super(BigLearner, self).__init__(**kwargs)
        self.m1 = None
        self.extras = None
        self.extras2 = None

    def first_action(self):
        self.send_to_parent(dict(sender=self.name, subject='BigLearner'))
        self.m1 = np.random.random_sample((131072, 1024))
        # set this in first_action so that it gets counted in the memory immediately
        # sizeof(double) = 8 bytes
        # 8 * 131072 = 2^20 B = 1MB
        # 8 * 131072 * 64 = 64 MiB
        # self.extras = BigLearnerExtras()
        # self.extras2 = [BigLearnerListicles() for x in range(1024)]

    def read_messages(self):
        while True:
            try:
                message = self.inbox.pop(0)
                #print message
                self.standard_responses(message)
            except (IndexError, AttributeError):
                break

    def next_action(self):
        self.read_messages()
        print self.__dict__.keys()
        if self.extras is not None:
            print self.extras.__dict__.keys()
        if self.extras2 is not None:
            print "List length:", len(self.extras2)

class BigLearnerExtras(object):
    def __init__(self):
        self.m1 = np.random.random_sample((131072, 1024))
        # self.m2 = np.random.random_sample((131072, 64))
        # self.m3 = np.random.random_sample((131072, 64))

class BigLearnerListicles(object):
    def __init__(self):
        self.m1 = np.random.random_sample((128, 1024))  # 1MB

class SpawningLearner(Agent):
    """Makes one sub learner each second"""
    def __init__(self, maxspawn=100, sub_learner=BigLearner, **kwargs):
        super(SpawningLearner, self).__init__(**kwargs)
        self.maxspawn = maxspawn
        self.spawncount = 0
        self.sub_learner = sub_learner

    def read_messages(self):
        while True:
            try:
                message = self.inbox.pop(0)
                #print message
                self.standard_responses(message)
            except (IndexError, AttributeError):
                break

    def next_action(self):
        self.read_messages()
        if self.spawncount < self.maxspawn:
            names = self.create_children(classes=[self.sub_learner])
            self.start_children(names=names)
            self.spawncount += 1
            self.send_to_parent(dict(sender=self.name, subject='SpawningLearner', n_babies=self.spawncount))

        for name, inbox in self.child_inboxes.iteritems():
            while True:
                try:
                    message = inbox.pop(0)
                    # message['sender'] = self.name + '.' + message['sender']
                    self.send_to_parent(message)
                except IndexError:
                    break

class OrphaningLearner(Agent):
    """Makes babies and then kills itself"""
    def __init__(self, sub_learner=SimpleLearner, **kwargs):
        super(OrphaningLearner, self).__init__(**kwargs)
        self.sub_learner = sub_learner

    def first_action(self):
        self.create_children(classes=[self.sub_learner]*5)
        self.start_children()

    def next_action(self):
        time.sleep(3)
        psutil.Process().terminate()

class SimpleManager(Agent):
    """Makes sub-learners. Prints all messages received. Terminates once time budget exceeded."""
    def __init__(self, time_budget):
        super(SimpleManager, self).__init__()
        self.time_budget = time_budget
        self.actioncounter = 0
        self.data = dict(shared_value=(np.frombuffer(Array('d', [20]).get_obj())))
        self.child_cpu = defaultdict(lambda: 0)
        self.child_private_memory = defaultdict(lambda: 0)
        self.communication_sleep = 0  # next action has a sleep in it anyway
        self.learner_preference = None
        self.save_file = constants.SAVE_DIR + '/managerV1.pk'
        self.name = 'm'

    def first_action(self):
        # self.load_file('/homes/mlghomes/evs25/Development/extras/automl_datasets/christine/christine_train.data',
        #                'christine_train')
        learners = [# (SimpleLearner, {}), (SimpleLearner, {}),
                    # (RecursiveLearner, {'recursion_level': 1, 'sub_learner': OrphaningLearner}),
                    # (RecursiveLearner, {'recursion_level': 1, 'sub_learner': SimpleLearner}),
                    # (ImmortalLearner, {}),
                    # (QuickLearner, {}),
                    # (SpawningLearner, {'sub_learner': HeavyLearner}),
                    # (HeavyLearner, {}),
                    (BigLearner, {}),
                    ]
        self.create_children(classes=learners)
        self.learner_preference = range(len(learners))
        self.start_children()

    def read_messages(self, print_them=True):
        if print_them:
            print "\nSimpleManager messages:"
        for inbox in self.child_inboxes.values():
            while True:
                try:
                    if print_them:
                        print inbox.pop(0)
                    else:
                        inbox.pop(0)
                except (IndexError, AttributeError):
                    break

    def orphanfinder(self):
        me = psutil.Process()
        my_group = os.getpgid(me.pid)
        for ps in psutil.process_iter():
            if os.getpgid(ps.pid) == my_group and ps.parent().name() == 'init':
                print 'Error! Orphan:', ps

    def init_cpu(self, names=None):
        # cpu measure for a psutils.Process needs to be called once to start counting
        # child_children is a list of psutils processes for each named child and its children
        # we could store child_children as an instance variable, but it might change
        if names is None:
            names = self.child_processes.keys()

        child_children = {}
        for name in names:
            try:
                process = psutil.Process(pid=self.child_processes[name].pid)
                child_children[name] = process.children(recursive=True) + [process]
                for child in child_children[name]:
                    child.cpu_percent()
            except psutil.NoSuchProcess:
                pass
        return child_children

    def get_cpu(self, child_children):
        """Print name and total cpu usage for each named child and its offspring"""
        # Children may show up with less than the expected memory usage when first created. This is because linux only
        # copies memory to the child process when it's first used. To improve the accuracy of the memory measure,
        # large arrays etc. should be created in first_action, not in __init__

        for name in child_children:
            self.child_cpu[name] = 0
            for child in child_children[name]:
                try:
                    self.child_cpu[name] += child.cpu_percent()
                except psutil.NoSuchProcess:
                    pass

        print "\nName, CPU percentage, No. of children"
        for name in child_children:
            print name, self.child_classes[name], self.child_cpu[name], len(child_children[name])

    def monitor_memory(self):
        for name in self.child_processes.keys():
            self.child_private_memory[name] = 0
            try:
                process = psutil.Process(pid=self.child_processes[name].pid)
                for child in process.children(recursive=True) + [process]:
                    try:
                        with open('/proc/{}/smaps'.format(child.pid), 'r') as fp:
                            for line in fp.readlines():
                                if line.startswith("Private"):
                                    self.child_private_memory[name] += int(line.split()[1])
                    except IOError:  # file not found because we're not running on Linux
                        pass
            except psutil.NoSuchProcess:
                pass

        print "\nName, memory in MB"
        for name in self.child_processes.keys():
            print name, self.child_classes[name], "%.1f" % (self.child_private_memory[name]/1024.0)

    def limit_memory(self):
        available = psutil.virtual_memory().available
        print "Available memory", "%.1fMB" % (available/1048576.0)
        if self.learner_preference is None or len(self.learner_preference) == 1:
            return
        #print self.learner_preference
        i = 0
        while available < 0.5*1024*1024*1024:
            worst_child = self.learner_preference[i]
            print "Saving", worst_child
            self.save_children(names=[worst_child])
            time.sleep(1)
            available = psutil.virtual_memory().available
            print "Available memory", "%.1fMB" % (available/1048576.0)
            i += 1
            if i > len(self.learner_preference) - 2:
                print "Only one learner left!"
                break

    def tidy_up(self):
        # apparently children need to be resumed before they can be terminated
        self.resume_children()
        super(SimpleManager, self).tidy_up()

    def next_action(self):
        timenow = time.time() - self.start_time
        print "\nSimpleManager: Time {0:.1f}, actioncount {1}".format(timenow, self.actioncounter)
        if timenow > self.time_budget:
            raise TerminationEx
        self.read_messages(print_them=False)
        # self.orphanfinder()

        # initalise cpu measure
        # child_children = self.init_cpu()
        print self.child_states.items()

        if self.actioncounter == 0:
            pass
        # elif self.actioncounter == 4:
        #     self.pause_children(names=[self.child_states.keys()[0]])
        #     self.resume_children(names=[self.child_states.keys()[0]])
        # elif self.actioncounter == 15:
        #     print "Pausing child"
        #     self.pause_children()
        # elif self.actioncounter == 20:
        #     print "Resuming child"
        #     self.resume_children()
        elif self.actioncounter == 10:
            print "Starting save"
            self.start_saving_children()
        # elif self.actioncounter == 6:
        #     print "Finishing save"
        #     self.finish_saving_children()
        #     while len(self.children_told_to_save) > 0:
        #         time.sleep(1)
        #         self.finish_saving_children()
        elif self.actioncounter == 45:
            print "Unpickling child"
            self.create_children()
            self.start_children()
        # if self.actioncounter == 0:
        #     kids = self.child_processes.keys()
        #     self.paused = kids[0]
        #     self.unpaused = kids[1]
        #
        # if self.actioncounter % 5 == 0:
        #     print "Switching"
        #     self.pause_children(names=[self.unpaused])
        #     self.start_children(names=[self.paused])
        #     self.paused, self.unpaused = self.unpaused, self.paused

        self.finish_saving_children()

        time.sleep(1)
        # print self.child_states.items()
        # self.get_cpu(child_children)
        self.monitor_memory()
        #self.limit_memory(child_order=self.child_processes.keys())
        self.actioncounter += 1

if __name__ == '__main__':
    #signal.signal(signal.SIGTSTP, util.signal_handler)
    ps = psutil.Process()
    print ps.pid, os.getpgid(ps.pid)
    os.setpgid(0, 0)  # sets pgid of this process to this process's pid
    m = SimpleManager(60)
    m.communicate()
    print "All done"


text:
package org.locationtech.geomesa.process.query

import org.geotools.data.collection.ListFeatureCollection
import org.junit.runner.RunWith
import org.locationtech.geomesa.features.ScalaSimpleFeature
import org.locationtech.geomesa.utils.collection.SelfClosingIterator
import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes
import org.opengis.feature.simple.SimpleFeature
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner

import scala.util.Random

@RunWith(classOf[JUnitRunner])
class RouteSearchProcessTest extends Specification {

  import scala.collection.JavaConverters._

  sequential

  val r = new Random(-10)

  val routeSft = SimpleFeatureTypes.createType("route", "*geom:LineString:srid=4326")
  val sft = SimpleFeatureTypes.createType("tracks", "track:String,heading:Double,dtg:Date,*geom:Point:srid=4326")

  val process = new RouteSearchProcess

  val routes = new ListFeatureCollection(routeSft,
    Array[SimpleFeature](ScalaSimpleFeature.create(routeSft, "r0", "LINESTRING (40 40, 40.5 40.5, 40.5 41)")))

  // features along the lower angled part of the route, headed in the opposite direction
  val features0 = Seq.tabulate[SimpleFeature](10) { i =>
    val sf = new ScalaSimpleFeature(sft, s"0$i")
    sf.setAttribute("track", "0")
    sf.setAttribute("heading", Double.box(217.3 + (r.nextDouble * 10) - 5))
    sf.setAttribute("dtg", s"2017-02-20T00:00:0$i.000Z")
    val route = (40.0 + (10 - i) * 0.05) - (r.nextDouble / 100) - 0.005
    sf.setAttribute("geom", s"POINT($route $route)")
    sf
  }

  // features along the upper vertical part of the route
  val features1 = Seq.tabulate[SimpleFeature](10) { i =>
    val sf = new ScalaSimpleFeature(sft, s"1$i")
    sf.setAttribute("track", "1")
    sf.setAttribute("heading", Double.box((r.nextDouble * 10) - 5))
    sf.setAttribute("dtg", s"2017-02-20T00:01:0$i.000Z")
    sf.setAttribute("geom", s"POINT(${40.5 + (r.nextDouble / 100) - 0.005} ${40.5 + (i + 1) * 0.005})")
    sf
  }

  // features along the upper vertical part of the route, but with a heading off by 5-15 degrees
  val features2 = Seq.tabulate[SimpleFeature](10) { i =>
    val sf = new ScalaSimpleFeature(sft, s"2$i")
    sf.setAttribute("track", "2")
    sf.setAttribute("heading", Double.box(10 + (r.nextDouble * 10) - 5))
    sf.setAttribute("dtg", s"2017-02-20T00:02:0$i.000Z")
    sf.setAttribute("geom", s"POINT(${40.5 + (r.nextDouble / 100) - 0.005} ${40.5 + (i + 1) * 0.005})")
    sf
  }

  // features headed along the upper vertical part of the route, but not close to the route
  val features3 = Seq.tabulate[SimpleFeature](10) { i =>
    val sf = new ScalaSimpleFeature(sft, s"3$i")
    sf.setAttribute("track", "3")
    sf.setAttribute("heading", Double.box((r.nextDouble * 10) - 5))
    sf.setAttribute("dtg", s"2017-02-20T00:03:0$i.000Z")
    sf.setAttribute("geom", s"POINT(${40.7 + (r.nextDouble / 10) - 0.005} ${40.5 + (i + 1) * 0.005})")
    sf
  }

  val input = new ListFeatureCollection(sft, (features0 ++ features1 ++ features2 ++ features3).asJava)

  "RouteSearch" should {
    "return features along a route" in {
      val collection = process.execute(input, routes, 1000.0, 5.0, null, null, false, "heading")

      val results = SelfClosingIterator(collection.features).toSeq
      results must containTheSameElementsAs(features1)
    }

    "return features along a route with a wider heading tolerance" in {
      val collection = process.execute(input, routes, 1000.0, 15.0, null, null, false, "heading")

      val results = SelfClosingIterator(collection.features).toSeq
      results must containTheSameElementsAs(features1 ++ features2)
    }

    "return features along a wide buffered route" in {
      val collection = process.execute(input, routes, 100000.0, 5.0, null, null, false, "heading")

      val results = SelfClosingIterator(collection.features).toSeq
      results must containTheSameElementsAs(features1 ++ features3)
    }

    "return features along a bidirectional route" in {
      val collection = process.execute(input, routes, 1000.0, 5.0, null, null, true, "heading")

      val results = SelfClosingIterator(collection.features).toSeq
      results must containTheSameElementsAs(features0 ++ features1)
    }
  }
}


text:
package org.kavaproject.kavatouch.uikit;

import org.kavaproject.kavatouch.internal.OccInstanceMethod;

import java.util.Set;

public interface UIEventInternal {
    @OccInstanceMethod("_initWithEvent:touches:")
    void update(Set<UITouch> touches);
}


text:
<?php

class DataObjectVersionedMethodDecorator extends DataObjectDecorator {

	public function doPublish() {
		if ($this->owner->hasMethod('canPublish') &&
				!$this->owner->canPublish())
			return false;

		$original = Versioned::get_one_by_stage($this->owner->ClassName, 'Live',
			"\"{$this->owner->ClassName}\".\"ID\" = {$this->owner->ID}");
		$original = $original? $original: new $this->owner->ClassName;
		$this->owner->invokeWithExtensions('onBeforePublish', $original);
		$this->owner->publish('Stage', 'Live');
		$this->owner->invokeWithExtensions('onAfterPublish', $original);

		return true;
	}

	public function doUnpublish() {
		if ($this->owner->hasMethod('canDeleteFromLive') &&
				!$this->owner->canDeleteFromLive())
			return false;

		$this->owner->invokeWithExtensions('onBeforeUnpublish');
		$this->owner->deleteFromStage('Live');
		$this->owner->invokeWithExtensions('onAfterUnpublish');

		return true;
	}
}


text:
package com.evolveum.midpoint.model.impl.lens;

import com.evolveum.midpoint.common.crypto.CryptoUtil;
import com.evolveum.midpoint.prism.ConsistencyCheckScope;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.schema.DeltaConvertor;
import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectDeltaWaveType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectDeltaWavesType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;

import java.io.Serializable;
import java.util.*;

/**
 * @author semancik
 *
 */
public class ObjectDeltaWaves<O extends ObjectType> implements List<ObjectDelta<O>>, DebugDumpable, Serializable {

	private List<ObjectDelta<O>> waves = new ArrayList<>();

	/**
	 * Get merged deltas from all the waves.
	 */
	public ObjectDelta<O> getMergedDeltas() throws SchemaException {
		return getMergedDeltas(null, -1);
	}

	/**
	 * Get merged deltas from the waves up to maxWave (including). Optional initial delta may be supplied.
	 * Negative maxWave means to merge all available waves.
	 */
	public ObjectDelta<O> getMergedDeltas(ObjectDelta<O> initialDelta, int maxWave) throws SchemaException {
		ObjectDelta<O> merged = null;
		if (initialDelta != null) {
			merged = initialDelta.clone();
		}
		int waveNum = 0;
		for (ObjectDelta<O> delta: waves) {
			if (delta == null) {
				continue;
			}
			if (merged == null) {
				merged = delta.clone();
			} else {
				merged.merge(delta);
			}
			if (maxWave >= 0 && waveNum >= maxWave) {
				break;
			}
		}
		return merged;
	}

	public void setOid(String oid) {
		for (ObjectDelta<O> delta: waves) {
			if (delta == null) {
				continue;
			}
			delta.setOid(oid);
		}
	}

	public void checkConsistence(boolean requireOid, String shortDesc) {
		for (int wave = 0; wave < waves.size(); wave++) {
			ObjectDelta<O> delta = waves.get(wave);
			if (delta == null) {
				continue;
			}
			try {
				delta.checkConsistence(requireOid, true, true, ConsistencyCheckScope.THOROUGH);
			} catch (IllegalArgumentException e) {
				throw new IllegalArgumentException(e.getMessage()+"; in "+shortDesc+", wave "+wave, e);
			} catch (IllegalStateException e) {
				throw new IllegalStateException(e.getMessage()+"; in "+shortDesc+", wave "+wave, e);
			}
		}
	}

	public void normalize() {
		if (waves != null) {
			for (ObjectDelta<O> wave: waves) {
				if (wave != null) {
					wave.normalize();
				}
			}
		}
	}

	public ObjectDeltaWaves<O> clone() {
		ObjectDeltaWaves<O> clone = new ObjectDeltaWaves<>();
		copyValues(clone);
		return clone;
	}

	protected void copyValues(ObjectDeltaWaves<O> clone) {
		for (ObjectDelta<O> thisWave: this.waves) {
			if (thisWave != null) {
				clone.waves.add(thisWave.clone());
			} else {
				clone.waves.add(null);
			}
		}
	}

	public void adopt(PrismContext prismContext) throws SchemaException {
		for (ObjectDelta<O> thisWave: this.waves) {
			if (thisWave != null) {
				prismContext.adopt(thisWave);
			}
		}
	}

	// DELEGATED METHODS (with small tweaks)

	/* (non-Javadoc)
	 * @see java.util.List#size()
	 */
	@Override
	public int size() {
		return waves.size();
	}

	/* (non-Javadoc)
	 * @see java.util.List#isEmpty()
	 */
	@Override
	public boolean isEmpty() {
		return waves.isEmpty();
	}

	/* (non-Javadoc)
	 * @see java.util.List#contains(java.lang.Object)
	 */
	@Override
	public boolean contains(Object o) {
		return waves.contains(o);
	}

	/* (non-Javadoc)
	 * @see java.util.List#iterator()
	 */
	@Override
	public Iterator<ObjectDelta<O>> iterator() {
		return waves.iterator();
	}

	/* (non-Javadoc)
	 * @see java.util.List#toArray()
	 */
	@Override
	public Object[] toArray() {
		return waves.toArray();
	}

	/* (non-Javadoc)
	 * @see java.util.List#toArray(T[])
	 */
	@Override
	public <T> T[] toArray(T[] a) {
		return waves.toArray(a);
	}

	/* (non-Javadoc)
	 * @see java.util.List#add(java.lang.Object)
	 */
	@Override
	public boolean add(ObjectDelta<O> e) {
		return waves.add(e);
	}

	/* (non-Javadoc)
	 * @see java.util.List#remove(java.lang.Object)
	 */
	@Override
	public boolean remove(Object o) {
		return waves.remove(o);
	}

	/* (non-Javadoc)
	 * @see java.util.List#containsAll(java.util.Collection)
	 */
	@Override
	public boolean containsAll(Collection<?> c) {
		return waves.containsAll(c);
	}

	/* (non-Javadoc)
	 * @see java.util.List#addAll(java.util.Collection)
	 */
	@Override
	public boolean addAll(Collection<? extends ObjectDelta<O>> c) {
		return waves.addAll(c);
	}

	/* (non-Javadoc)
	 * @see java.util.List#addAll(int, java.util.Collection)
	 */
	@Override
	public boolean addAll(int index, Collection<? extends ObjectDelta<O>> c) {
		return waves.addAll(index, c);
	}

	/* (non-Javadoc)
	 * @see java.util.List#removeAll(java.util.Collection)
	 */
	@Override
	public boolean removeAll(Collection<?> c) {
		return waves.removeAll(c);
	}

	/* (non-Javadoc)
	 * @see java.util.List#retainAll(java.util.Collection)
	 */
	@Override
	public boolean retainAll(Collection<?> c) {
		return waves.retainAll(c);
	}

	/* (non-Javadoc)
	 * @see java.util.List#clear()
	 */
	@Override
	public void clear() {
		waves.clear();
	}

	/* (non-Javadoc)
	 * @see java.util.List#get(int)
	 */
	@Override
	public ObjectDelta<O> get(int index) {
		if (index >= waves.size()) {
			return null;
		}
		return waves.get(index);
	}

	/* (non-Javadoc)
	 * @see java.util.List#set(int, java.lang.Object)
	 */
	@Override
	public ObjectDelta<O> set(int index, ObjectDelta<O> element) {
		if (index >= waves.size()) {
			for (int i = waves.size(); i < index; i++) {
				waves.add(null);
			}
			waves.add(element);
			return element;
		}
		return waves.set(index, element);
	}

	/* (non-Javadoc)
	 * @see java.util.List#add(int, java.lang.Object)
	 */
	@Override
	public void add(int index, ObjectDelta<O> element) {
		waves.add(index, element);
	}

	/* (non-Javadoc)
	 * @see java.util.List#remove(int)
	 */
	@Override
	public ObjectDelta<O> remove(int index) {
		return waves.remove(index);
	}

	/* (non-Javadoc)
	 * @see java.util.List#indexOf(java.lang.Object)
	 */
	@Override
	public int indexOf(Object o) {
		return waves.indexOf(o);
	}

	/* (non-Javadoc)
	 * @see java.util.List#lastIndexOf(java.lang.Object)
	 */
	@Override
	public int lastIndexOf(Object o) {
		return waves.lastIndexOf(o);
	}

	/* (non-Javadoc)
	 * @see java.util.List#listIterator()
	 */
	@Override
	public ListIterator<ObjectDelta<O>> listIterator() {
		return waves.listIterator();
	}

	/* (non-Javadoc)
	 * @see java.util.List#listIterator(int)
	 */
	@Override
	public ListIterator<ObjectDelta<O>> listIterator(int index) {
		return waves.listIterator(index);
	}

	/* (non-Javadoc)
	 * @see java.util.List#subList(int, int)
	 */
	@Override
	public List<ObjectDelta<O>> subList(int fromIndex, int toIndex) {
		return waves.subList(fromIndex, toIndex);
	}

	// DUMP

	@Override
    public String debugDump() {
        return debugDump(0);
    }

    public String dump(boolean showTriples) {
        return debugDump(0, showTriples);
    }

    @Override
    public String debugDump(int indent) {
    	return debugDump(indent, true);
    }

    public String debugDump(int indent, boolean showTriples) {
        StringBuilder sb = new StringBuilder();
        DebugUtil.indentDebugDump(sb, indent);
        sb.append("ObjectDeltaWaves:");

        if (waves.isEmpty()) {
        	sb.append(" empty");
        	return sb.toString();
        }

        if (waves.size() == 1) {
        	sb.append(" single wave\n");
            if (waves.get(0) != null) {
        	    sb.append(waves.get(0).debugDump(indent + 1));
            } else {
                DebugUtil.indentDebugDump(sb, indent + 1);
                sb.append("null\n");
            }
        } else {
	        sb.append(waves.size()).append(" waves");
	        for (int wave = 0; wave < waves.size(); wave++) {
	        	sb.append("\n");
				ObjectDelta<O> delta = waves.get(wave);
				DebugUtil.indentDebugDump(sb, indent + 1);
				sb.append("wave ").append(wave).append(":");
				if (delta == null) {
					sb.append(" null");
				} else {
					sb.append("\n");
					sb.append(delta.debugDump(indent + 2));
				}
	        }
        }

        return sb.toString();
    }

	@Override
	public String toString() {
		return "ObjectDeltaWaves(" + waves + ")";
	}

    public ObjectDeltaWavesType toObjectDeltaWavesType() throws SchemaException {
        ObjectDeltaWavesType objectDeltaWavesType = new ObjectDeltaWavesType();
        for (int i = 0; i < waves.size(); i++) {
            ObjectDelta wave = waves.get(i);
            if (wave != null) {
                ObjectDeltaWaveType objectDeltaWaveType = new ObjectDeltaWaveType();
                objectDeltaWaveType.setNumber(i);
                objectDeltaWaveType.setDelta(DeltaConvertor.toObjectDeltaType(wave));
                objectDeltaWavesType.getWave().add(objectDeltaWaveType);
            }
        }
        return objectDeltaWavesType;
    }

    // don't forget to apply provisioning definitions to resulting deltas (it's the client responsibility)
    public static <O extends ObjectType> ObjectDeltaWaves<O> fromObjectDeltaWavesType(ObjectDeltaWavesType secondaryDeltas, PrismContext prismContext) throws SchemaException {
        if (secondaryDeltas == null) {
            return null;
        }

        ObjectDeltaWaves<O> retval = new ObjectDeltaWaves<>();

        int max = 0;
        for (ObjectDeltaWaveType odwt : secondaryDeltas.getWave()) {
            if (odwt.getNumber() > max) {
                max = odwt.getNumber();
            }
        }

        ObjectDelta<O>[] wavesAsArray = new ObjectDelta[max+1];
        for (ObjectDeltaWaveType odwt : secondaryDeltas.getWave()) {
            wavesAsArray[odwt.getNumber()] = DeltaConvertor.createObjectDelta(odwt.getDelta(), prismContext);
        }

        for (int i = 0; i <= max; i++) {
            retval.waves.add(wavesAsArray[i]);
        }
        return retval;
    }

	public void checkEncrypted(String shortDesc) {
		for (int wave = 0; wave < waves.size(); wave++) {
			ObjectDelta<O> delta = waves.get(wave);
			if (delta == null) {
				continue;
			}
			try {
				CryptoUtil.checkEncrypted(delta);
			} catch (IllegalArgumentException e) {
				throw new IllegalArgumentException(e.getMessage()+"; in "+shortDesc+", wave "+wave, e);
			} catch (IllegalStateException e) {
				throw new IllegalStateException(e.getMessage()+"; in "+shortDesc+", wave "+wave, e);
			}
		}
	}

	public void deleteDeltas() {
		waves.clear();
	}
}


text:
package org.redhelix.core.sensor;

/**
 *
 *
 *
 * @since RedHelix Version 0.1
 * @author Hank Bruning
 *
 */
public final class RedHxSensorNumberImpl implements RedHxSensorNumber {

  private final int sensorNumber;

  public RedHxSensorNumberImpl(final int sensorNumber) {
    this.sensorNumber = sensorNumber;
  }

  private RedHxSensorNumberImpl() {
    this.sensorNumber = 0;
  }

  /*
   * (non-Javadoc)
   *
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }

    if (obj == null) {
      return false;
    }

    if (getClass() != obj.getClass()) {
      return false;
    }

    final RedHxSensorNumberImpl other = (RedHxSensorNumberImpl) obj;

    if (sensorNumber != other.sensorNumber) {
      return false;
    }

    return true;
  }

  @Override
  public int getSensorNumber() {
    return sensorNumber;
  }

  /*
   * (non-Javadoc)
   *
   * @see java.lang.Object#hashCode()
   */
  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;

    result = prime * result + sensorNumber;

    return result;
  }

  @Override
  public String toString() {
    final StringBuilder sb = new StringBuilder();

    sb.append("[");
    sb.append("sensorNumber=, " + sensorNumber);
    sb.append(", ");
    sb.append("]");

    return sb.toString();
  }
}


text:
import { get, post } from 'axios'
import { stringify } from 'qs'

const uri = './api/ajax.php'

export default {
  get (request, params) {
    params = params || {}
    params.request = request
    return get(uri, {
      params: params
    })
  },

  post (request, data) {
    data = data || {}
    data.request = request
    let token = window.sessionStorage.getItem('login_token') || window.localStorage.getItem('login_token')
    if (token) data.login_token = token
    return post(uri, stringify(data))
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2015 Red Hat, Inc. and/or its affiliates
    and other contributors as indicated by the @author tags.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <artifactId>modules</artifactId>
  <packaging>pom</packaging>
  <name>Scepta::Modules</name>

  <parent>
    <groupId>io.scepta</groupId>
    <artifactId>scepta-parent</artifactId>
    <version>0.1.0-SNAPSHOT</version>
  </parent>

  <modules>
    <module>scepta-builder</module>
    <module>scepta-core</module>
    <module>scepta-deployment-filesystem</module>
    <module>scepta-deployment-rest</module>
    <module>scepta-design-cassandra</module>
    <module>scepta-design-rest</module>
    <module>scepta-generator</module>
    <module>scepta-runtime</module>
  </modules>
</project>


text:
<?php

// Require environment (fatal)
if (!defined('FILESENDER_BASE')) {
    die('Missing environment');
}

/**
 *  Represents collection in the database
 */
class CollectionType extends DBObject
{
    /**
     * Database map
     */
    protected static $dataMap = array(
        //collection id, as in the database
        'id' => array(
            'type' => 'uint',   //data type of 'id'
            'size' => 'medium', //size of the integer stored in 'id' (in bytes, or otherwise)
            'primary' => true,  //indicates that 'id' is the primary key in the DB
        ),
        'name' => array(
            'type' => 'string',
            'size' => 60,
        ),
        'description' => array(
            'type' => 'string',
            'size' => 512
        ),
    );

    /**
     * Properties
     */
    protected $id = null;
    protected $name = null;
    protected $description = null;

    /**
     * Predefined Enums
     */
    const UNKNOWN_ID     = 0; //"Undefined collection type";
    const TREE_ID        = 1; //"Root directory collection";
    const DIRECTORY_ID   = 2; //"Pathed directory collection";
    const LASTSTATIC_ID  = 999; //"Last static enum id";

    /**
     * Predefined Types
     */
    public static $UNKNOWN = null;
    public static $TREE = null;
    public static $DIRECTORY = null;
    public static $LASTSTATIC = null;
    public static $LATEST = null;

    /**
     * Constructor
     *
     * @param integer $id identifier of collection to load from database (null if loading not wanted)
     * @param array $data data to create the collection from (if already fetched from database)
     *
     * @throws ClassificationNotFoundException
     */
    public function __construct($id = null, $data = null)
    {
        if (!is_null($id)) {
            // Load from database if id given
            $statement = DBI::prepare('SELECT * FROM '.self::getDBTable().' WHERE id = :id');
            $statement->execute(array(':id' => $id));
            $data = $statement->fetch();
            if (!$data) {
                throw new ClassificationNotFoundException('id = '.$id);
            }
        }

        // Fill properties from provided data
        if ($data) {
            $this->fillFromDBData($data);
        }
    }

    /**
     * Initializes the CollectionType table
     *
     */
    public static function initialize()
    {
        if (!is_null(self::$UNKNOWN)) {
            return;
        }
        $types = array();

        // Load all CollectionTypes from database
        $s = DBI::prepare('SELECT * FROM '.self::getDBTable().' ORDER BY :id');
        $s->execute(array(':id' => 'id'));
        foreach ($s->fetchAll() as $data) {
            $type = self::fromData($data['id'], $data);
            $types[$data['id']] = $type;
            self::$LATEST = $type;
        }

        if (array_key_exists(self::UNKNOWN_ID, $types)) {
            self::$UNKNOWN = $types[self::UNKNOWN_ID];
        } else {
            self::$UNKNOWN = new self();
            self::$UNKNOWN->id = self::UNKNOWN_ID;
            self::$UNKNOWN->name = 'UNKNOWN';
            self::$UNKNOWN->description = 'undefined collection type';
            self::$UNKNOWN->insert();
        }

        if (array_key_exists(self::TREE_ID, $types)) {
            self::$TREE = $types[self::TREE_ID];
        } else {
            self::$TREE = new self();
            self::$TREE->id = self::TREE_ID;
            self::$TREE->name = 'TREE';
            self::$TREE->description = 'directory tree collection';
            self::$TREE->insert();
        }

        if (array_key_exists(self::DIRECTORY_ID, $types)) {
            self::$DIRECTORY = $types[self::DIRECTORY_ID];
        } else {
            self::$DIRECTORY = new self();
            self::$DIRECTORY->id = self::DIRECTORY_ID;
            self::$DIRECTORY->name = 'DIRECTORY';
            self::$DIRECTORY->description = 'directory path collection';
            self::$DIRECTORY->insert();
        }

        if (array_key_exists(self::LASTSTATIC_ID, $types)) {
            self::$LASTSTATIC = $types[self::LASTSTATIC_ID];
        } else {
            self::$LASTSTATIC = new self();
            self::$LASTSTATIC->id = self::LASTSTATIC_ID;
            self::$LASTSTATIC->name = 'LASTSTATIC';
            self::$LASTSTATIC->description = 'last static collection type';
            self::$LASTSTATIC->insert();
            self::$LATEST = self::$LASTSTATIC;
        }
    }

    /**
     * Getter
     *
     * @param string $property property to get
     *
     * @throws PropertyAccessException
     *
     * @return property value
     */
    public function __get($property)
    {
        if (in_array($property, array(
            'id', 'name', 'description'
        ))) {
            return $this->$property;
        }
        throw new PropertyAccessException($this, $property);
    }

    /**
     * Setter
     *
     * @param string $property property to get
     * @param mixed $value value to set property to
     *
     * @throws ClassificationBadHashException
     * @throws PropertyAccessException
     */
    public function __set($property, $value)
    {
        if ($property == 'name') {
            $this->name = (string)$value;
        } elseif ($property == 'description') {
            $this->description = (string)$value;
        } else {
            throw new PropertyAccessException($this, $property);
        }
    }

    /**
     * String caster
     *
     * @return string
     */
    public function __toString()
    {
        return static::getClassName().'#'.($this->id ? $this->id : 'unsaved').'('.$this->name.', '.(strlen($this->name)+strlen($this->description)+1).' bytes)';
    }
}


text:
package tabletmanager

import (
	"flag"
	"fmt"
	"sync"
	"time"

	log "github.com/golang/glog"
	"github.com/youtube/vitess/go/event"
	"github.com/youtube/vitess/go/stats"
	"github.com/youtube/vitess/go/trace"
	"github.com/youtube/vitess/go/vt/concurrency"
	"github.com/youtube/vitess/go/vt/tabletmanager/tmclient"
	"github.com/youtube/vitess/go/vt/topo"
	"github.com/youtube/vitess/go/vt/topotools"
	"github.com/youtube/vitess/go/vt/topotools/events"
	"golang.org/x/net/context"
)

var (
	_ = flag.Bool("fast_external_reparent", false, "Unused.")

	finalizeReparentTimeout = flag.Duration("finalize_external_reparent_timeout", 10*time.Second, "Timeout for the finalize stage of a fast external reparent reconciliation.")

	externalReparentStats = stats.NewTimings("ExternalReparents", "NewMasterVisible", "FullRebuild")
)

// SetReparentFlags changes flag values. It should only be used in tests.
func SetReparentFlags(timeout time.Duration) {
	*finalizeReparentTimeout = timeout
}

// TabletExternallyReparented updates all topo records so the current
// tablet is the new master for this shard.
// Should be called under RPCWrapLock.
func (agent *ActionAgent) TabletExternallyReparented(ctx context.Context, externalID string) error {
	startTime := time.Now()

	// If there is a finalize step running, wait for it to finish or time out
	// before checking the global shard record again.
	if agent.finalizeReparentCtx != nil {
		select {
		case <-agent.finalizeReparentCtx.Done():
			agent.finalizeReparentCtx = nil
		case <-ctx.Done():
			return ctx.Err()
		}
	}

	tablet := agent.Tablet()

	// Check the global shard record.
	si, err := topo.GetShard(ctx, agent.TopoServer, tablet.Keyspace, tablet.Shard)
	if err != nil {
		log.Warningf("fastTabletExternallyReparented: failed to read global shard record for %v/%v: %v", tablet.Keyspace, tablet.Shard, err)
		return err
	}
	if si.MasterAlias == tablet.Alias {
		// We may get called on the current master even when nothing has changed.
		// If the global shard record is already updated, it means we successfully
		// finished a previous reparent to this tablet.
		return nil
	}

	// Create a reusable Reparent event with available info.
	ev := &events.Reparent{
		ShardInfo:  *si,
		NewMaster:  *tablet.Tablet,
		OldMaster:  topo.Tablet{Alias: si.MasterAlias, Type: topo.TYPE_MASTER},
		ExternalID: externalID,
	}
	defer func() {
		if err != nil {
			event.DispatchUpdate(ev, "failed: "+err.Error())
		}
	}()
	event.DispatchUpdate(ev, "starting external from tablet (fast)")

	// Execute state change to master by force-updating only the local copy of the
	// tablet record. The actual record in topo will be updated later.
	log.Infof("fastTabletExternallyReparented: executing change callback for state change to MASTER")
	oldTablet := *tablet.Tablet
	newTablet := oldTablet
	newTablet.Type = topo.TYPE_MASTER
	newTablet.Health = nil
	agent.setTablet(topo.NewTabletInfo(&newTablet, -1))
	if err := agent.updateState(ctx, &oldTablet, "fastTabletExternallyReparented"); err != nil {
		return fmt.Errorf("fastTabletExternallyReparented: failed to change tablet state to MASTER: %v", err)
	}

	agent.mutex.Lock()
	agent._tabletExternallyReparentedTime = time.Now()
	agent.mutex.Unlock()

	// Directly write the new master endpoint in the serving graph.
	// We will do a true rebuild in the background soon, but in the meantime,
	// this will be enough for clients to re-resolve the new master.
	event.DispatchUpdate(ev, "writing new master endpoint")
	log.Infof("fastTabletExternallyReparented: writing new master endpoint to serving graph")
	ep, err := tablet.EndPoint()
	if err != nil {
		return fmt.Errorf("fastTabletExternallyReparented: failed to generate EndPoint for tablet %v: %v", tablet.Alias, err)
	}
	err = topo.UpdateEndPoints(ctx, agent.TopoServer, tablet.Alias.Cell,
		si.Keyspace(), si.ShardName(), topo.TYPE_MASTER,
		&topo.EndPoints{Entries: []topo.EndPoint{*ep}}, -1)
	if err != nil {
		return fmt.Errorf("fastTabletExternallyReparented: failed to update master endpoint: %v", err)
	}
	externalReparentStats.Record("NewMasterVisible", startTime)

	// Start the finalize stage with a background context, but connect the trace.
	bgCtx, cancel := context.WithTimeout(agent.batchCtx, *finalizeReparentTimeout)
	bgCtx = trace.CopySpan(bgCtx, ctx)
	agent.finalizeReparentCtx = bgCtx
	go func() {
		err := agent.finalizeTabletExternallyReparented(bgCtx, si, ev)
		cancel()

		if err != nil {
			log.Warningf("finalizeTabletExternallyReparented error: %v", err)
			event.DispatchUpdate(ev, "failed: "+err.Error())
			return
		}
		externalReparentStats.Record("FullRebuild", startTime)
	}()

	return nil
}

// finalizeTabletExternallyReparented performs slow, synchronized reconciliation
// tasks that ensure topology is self-consistent, and then marks the reparent as
// finished by updating the global shard record.
func (agent *ActionAgent) finalizeTabletExternallyReparented(ctx context.Context, si *topo.ShardInfo, ev *events.Reparent) (err error) {
	var wg sync.WaitGroup
	var errs concurrency.AllErrorRecorder
	oldMasterAlias := si.MasterAlias

	// Update the tablet records and serving graph for the old and new master concurrently.
	event.DispatchUpdate(ev, "updating old and new master tablet records")
	log.Infof("finalizeTabletExternallyReparented: updating tablet records")
	wg.Add(1)
	go func() {
		defer wg.Done()
		// Update our own record to master.
		var updatedTablet *topo.Tablet
		err := topo.UpdateTabletFields(ctx, agent.TopoServer, agent.TabletAlias,
			func(tablet *topo.Tablet) error {
				tablet.Type = topo.TYPE_MASTER
				tablet.Health = nil
				updatedTablet = tablet
				return nil
			})
		if err != nil {
			errs.RecordError(err)
			return
		}

		// Update the serving graph for the tablet.
		if updatedTablet != nil {
			errs.RecordError(
				topotools.UpdateTabletEndpoints(ctx, agent.TopoServer, updatedTablet))
		}
	}()

	if !oldMasterAlias.IsZero() {
		wg.Add(1)
		go func() {
			// Force the old master to spare.
			var oldMasterTablet *topo.Tablet
			err := topo.UpdateTabletFields(ctx, agent.TopoServer, oldMasterAlias,
				func(tablet *topo.Tablet) error {
					tablet.Type = topo.TYPE_SPARE
					oldMasterTablet = tablet
					return nil
				})
			if err != nil {
				errs.RecordError(err)
				wg.Done()
				return
			}

			if oldMasterTablet != nil {
				// Update the serving graph.
				errs.RecordError(
					topotools.UpdateTabletEndpoints(ctx, agent.TopoServer, oldMasterTablet))
				wg.Done()

				// Tell the old master to refresh its state. We don't need to wait for it.
				tmc := tmclient.NewTabletManagerClient()
				tmc.RefreshState(ctx, topo.NewTabletInfo(oldMasterTablet, -1))
			}
		}()
	}

	tablet := agent.Tablet()

	// Wait for the tablet records to be updated. At that point, any rebuild will
	// see the new master, so we're ready to mark the reparent as done in the
	// global shard record.
	wg.Wait()
	if errs.HasErrors() {
		return errs.Error()
	}

	// Update the master field in the global shard record. We don't use a lock
	// here anymore. The lock was only to ensure that the global shard record
	// didn't get modified between the time when we read it and the time when we
	// write it back. Now we use an update loop pattern to do that instead.
	event.DispatchUpdate(ev, "updating global shard record")
	log.Infof("finalizeTabletExternallyReparented: updating global shard record")
	si, err = topo.UpdateShardFields(ctx, agent.TopoServer, tablet.Keyspace, tablet.Shard, func(shard *topo.Shard) error {
		shard.MasterAlias = tablet.Alias
		return nil
	})
	if err != nil {
		return err
	}

	// We already took care of updating the serving graph for the old and new masters.
	// All that's left now is in case of a cross-cell reparent, we need to update the
	// master cell setting in the SrvShard records of all cells.
	if oldMasterAlias.Cell != tablet.Alias.Cell {
		event.DispatchUpdate(ev, "rebuilding shard serving graph")
		log.Infof("finalizeTabletExternallyReparented: updating SrvShard in all cells for cross-cell reparent")
		if err := topotools.UpdateAllSrvShards(ctx, agent.TopoServer, si); err != nil {
			return err
		}
	}

	event.DispatchUpdate(ev, "finished")
	return nil
}


text:
#include <StackEnv.h>
#include <Classes.h>
#include <Gui.local.h>

#include <List.h>

/*---------------------*/

static int  libNullGetPageId(GuiLibrary *this) {return -1;}
static void libNullReleasePageId(GuiLibrary *this,int Id) {}
static int  libNullImgLoad(GuiLibrary *this,int Id,char *filename) {return (0!=0);}
static int  libNullImgImport(GuiLibrary *this,int Id,ImgDesc *Desc) {return (0!=0);}
static GuiOutput *libNullPicture(GuiLibrary *this,int PageId,Geo2dRectangle *Dim) {return &GuiOutputNull;}
static GuiOutput *libNullSwapPalPicture(GuiLibrary *this,GuiRgbPalette *Pal,int PageId,Geo2dRectangle *Dim) {return &GuiOutputNull;}
static int  libNullRecordEngine(GuiLibrary *this,Render2dEngine *Engine){return (0!=0);}
static void libNullReleaseEngine(GuiLibrary *this,int Engine) {}

static struct GuiLibrary libNullStatic = {
    libNullGetPageId,libNullReleasePageId
	,libNullImgLoad,libNullImgImport,libNullPicture,libNullSwapPalPicture
	,libNullRecordEngine,libNullReleaseEngine
};
GuiLibrary GuiLibraryNull = {&libNullStatic};

/*-------------------------*/

typedef struct { struct lPage *Static;} lPage;
struct lPage {
	Img2dLib *(*Load)(lPage *this,Render2dEngine *Engine);
    int IsFree;
};

typedef struct {
	lPage lPage;
	union {
		dList Free;
        ImgDesc Desc;
	} Desc;
} LlPage;

#define lPageIsFree(p) ((p)->lPage.Static->IsFree)
static Img2dLib *lPageNullLoad(lPage *this,Render2dEngine *Engine) {
	return &Img2dLibNull;
}
static lPage *lPageFree(LlPage *r,dList *Before) {
    static struct lPage Static = {&lPageNullLoad,(0==0)};
	dList *p;
	r->lPage.Static = &Static;
	p = &r->Desc.Free;
	p->n = Before->n;
	p->p = Before;
	p->p->n = p->n->p = p;
	return &r->lPage;
}
static lPage *lPageReserve(LlPage *r) {
	static struct lPage Static = {&lPageNullLoad,(0!=0)};
	dList *p;
	r->lPage.Static = &Static;
	p = &r->Desc.Free;
	p->p->n = p->n;
	p->n->p = p->p;
	p->p = p->n = p;
	return &r->lPage;
}

static Img2dLib *lFilePageLoad(lPage *this,Render2dEngine *Engine) {
	ImgDesc **imgs;
	Img2dLib *r;
	ThisToThat(LlPage,lPage);
	pOpen
		pIn(imgs = GuiLoadImage(that->Desc.Desc.Data,Engine->ScreenOrgAtBottom,Engine->AlgnImagePitch));
	    if (imgs[0]) {
            r = Call(Engine,ImportImg2dLib,1(imgs[0]));
		} else {
			r = &Img2dLibNull;
		}
	pClose
	return r;
}
static lPage *lFilePageNew(LlPage *r,char *FileName) {
	static struct lPage Static = {lFilePageLoad,(0!=0)};
    r->lPage.Static = &Static;
	r->Desc.Desc.Dim.w = r->Desc.Desc.Dim.h = 0;
	r->Desc.Desc.Data = FileName;
	return &r->lPage;
}

static Img2dLib *lDescPageLoad(lPage *this,Render2dEngine *Engine) {
	ThisToThat(LlPage,lPage);
	return Call(Engine,ImportImg2dLib,1(&that->Desc.Desc));
}
static lPage *lDescPageNew(LlPage *r,ImgDesc *Desc) {
	static struct lPage Static = {lDescPageLoad,(0!=0)};
	r->lPage.Static = &Static;
	r->Desc.Desc = *Desc;
	return &r->lPage;
}

/*--------------------------*/

#define CollectPageShift 6
#define CollectPageNb 0x40
#define CollectPageMask 0x3f

typedef struct {
	List List;
	struct pageDescCollect *Collect;
} freePageId;

struct pageDescCollect {
	BinTree nPages;
	struct pageDescList {
		struct pageDescCollect *Collect;
        LlPage Page;
	} Pages[CollectPageNb];
};

typedef struct {
	Img2dLib Img2dLib;
	struct pageCollect *Collect;
	Img2dLib *Child;
} imgLibNotLoaded;

struct pageCollect {
	BinTree nPages;
	Render2dEngine *Engine;
	struct enginePages *Root;
	struct pageDescCollect *Desc;
	imgLibNotLoaded Pages[CollectPageNb];
};
static void imgLibNotLoadedInit(struct pageCollect *Collect,imgLibNotLoaded *page);

struct enginePages {
	BinTree bEngine;
	BinTree pEngine;
	Render2dEngine *Engine;
	struct Llib *Lib;
	BinTree Collects;
};

typedef struct Llib {
	GuiLibrary GuiLibrary;
	MemStack *Mem;
	struct {
		BinTree Collects;
		dList Free;
		int CollectNb;
	} PageId;
	BinTree FreeEngines,bEngines,pEngines;
	int EngineNb;
} Llib;

/*------------------------*/

static int firstEngineFound(BinTree *bt,void *clos) {return (0==0);}

static struct enginePages *libFirstFreeEngine(struct Llib *lib) {
	BinTree *bt;
	struct enginePages *r;
	bt = BinTreeForEach(&lib->FreeEngines,firstEngineFound,0);
	if (bt==BinTreeEnd) {
		mPush(lib->Mem,r);
		BinTreeInit(&r->bEngine);
		BinTreeInit(&r->pEngine);
		r->Engine = 0; // &Render2dEngineNull;
		r->Lib = lib;
		BinTreeInit(&r->Collects);
		BinTreeSeekOrInsert(&lib->FreeEngines,lib->EngineNb,&r->bEngine);
		lib->EngineNb++;
	} else {
	    r = CastBack(struct enginePages,bEngine,bt);
	}
	return r;
}

static struct enginePages *libFirstEngine(struct Llib *lib,int *Free) {
	BinTree *bt;
	struct enginePages *r;
	bt = BinTreeForEach(&lib->bEngines,firstEngineFound,0);
	*Free = (bt==BinTreeEnd);
	if (*Free) {
		r = libFirstFreeEngine(lib);
	} else {
		r = CastBack(struct enginePages,bEngine,bt);
	}
	return r;
}

static int imgLibFree(BinTree *bt,void *Clos) {
	struct pageCollect *pC;
	int i;
	pC = CastBack(struct pageCollect,nPages,bt);
	for (i=0;i<CollectPageNb;i++) {
		Call(&pC->Pages[i].Img2dLib,Close,0);
		Call(&pC->Pages[i].Img2dLib,Free,0);
	}
	pC->Engine = pC->Root->Engine;
	return (0!=0);
}
static void enginePagesClean(struct enginePages *engP) {
	BinTreeForEach(&engP->Collects,imgLibFree,0);
}

static int imgLibInit(BinTree *bt,void *Clos) {
	struct pageCollect *pC;
	pC = CastBack(struct pageCollect,nPages,bt);
	pC->Engine = pC->Root->Engine;
	return (0!=0);
}
static void enginePagesInit(struct enginePages *engP) {
	BinTreeForEach(&engP->Collects,imgLibInit,0);
}

static struct pageDescCollect *AddPageDescCollect(Llib *l,int num) {
	int i;
	BinTree *bt;
	dList *Free;
	struct pageDescCollect *n;
	mPush(l->Mem,n);
	Free = &l->PageId.Free;
	for (i=0;i<CollectPageNb;i++) {
		n->Pages[i].Collect = n;
		lPageFree(&(n->Pages[i].Page),Free->p);
	}
	if (num==l->PageId.CollectNb) l->PageId.CollectNb++;
	bt = BinTreeSeek(&l->PageId.Collects,num);
	if (bt!=BinTreeEnd) {
		num = l->PageId.CollectNb;
		do {
			bt = BinTreeSeek(&l->PageId.Collects,num);
			num++;
		} while(bt!=BinTreeEnd);
		l->PageId.CollectNb = num;
	}
	BinTreeSeekOrInsert(&l->PageId.Collects,num,&n->nPages);
	return n;
}

static struct pageDescCollect *PageDescCollectSeekOrInsert(Llib *l,int num) {
	struct pageDescCollect *r;
	BinTree *bt;
    bt = BinTreeSeek(&l->PageId.Collects,num);
	if (bt==BinTreeEnd) {
        r = AddPageDescCollect(l,num);
	} else {
		r = CastBack(struct pageDescCollect,nPages,bt);
	}
	return r;
}

static struct pageCollect *pageCollectSeekOrInsert(struct Llib *lib,struct enginePages *engP,int cPageId) {
	struct pageCollect *r;
	BinTree *bt;
	bt = BinTreeSeek(&engP->Collects,cPageId);
	if (bt==BinTreeEnd) {
		int i;
		struct pageCollect *nw;
		mPush(lib->Mem,nw);
		nw->Engine = engP->Engine;
		nw->Root = engP;
		nw->Desc = PageDescCollectSeekOrInsert(lib,cPageId);
		for (i=0;i<CollectPageNb;i++) {
             imgLibNotLoadedInit(nw,nw->Pages+i);
		}
		bt = BinTreeSeekOrInsert(&engP->Collects,cPageId,&nw->nPages);
	}
	r = CastBack(struct pageCollect,nPages,bt);
	return r;
}

/*------------------------*/

typedef struct {
	GuiOutput GuiOutput;
	imgLibNotLoaded *Last;
	Geo2dRectangle Boundary;
} LPicture;

static void LPictureDisplay(GuiOutput *this,Render2dEngine *Engine) {
	imgLibNotLoaded *Last;
	struct pageCollect *Collect;
	ThisToThat(LPicture,GuiOutput);
	Last = that->Last;
	Collect = Last->Collect;
	if (Collect->Engine!=Engine) {
		Llib *lib;
		BinTree *bt;
		lib = Collect->Root->Lib;
	    bt = BinTreeSeek(&lib->pEngines,((int)Engine));
		if (bt!=BinTreeEnd) {
		    struct pageCollect *page;
		    struct enginePages *engP;
			int Id;
			Id = Last - Collect->Pages;
			engP = CastBack(struct enginePages,pEngine,bt);
		    page = pageCollectSeekOrInsert(lib,engP,Collect->nPages.Id);
		    if (page) {
				that->Last = page->Pages+Id;
		        Call(that->Last->Child,Display,1(&that->Boundary));
			}
		}
	} else {
		Call(Last->Child,Display,1(&that->Boundary));
	}
}
static GuiOutput *LPictureNew(Llib *lib,int Id,Geo2dRectangle *Rectangle) {
	LPicture *R;
	int fr,pId,oId;
	static struct GuiOutput Static = {LPictureDisplay};
	struct enginePages *engP;
	pId = Id >> CollectPageShift;
	oId = Id & CollectPageMask;
	rPush(R);
	R->GuiOutput.Static = &Static;
	/* Not really good, that page might never be used on that engine... */ {
		struct pageCollect *page;
	    engP = libFirstEngine(lib,&fr);
		page = pageCollectSeekOrInsert(lib,engP,pId);
	    R->Last = page->Pages+oId;
	}
	R->Boundary = *Rectangle;
	return &R->GuiOutput;
}

/*------------------------*/

static struct pageDescList *reclaimPageId(Llib *l,int Id) {
	struct pageDescList *r;
	int cId,oId;
	r = 0;
	cId = Id>>CollectPageShift;
	oId = Id&CollectPageMask;
	{
	    struct pageDescCollect *col;
	    col = PageDescCollectSeekOrInsert(l,cId);
		r = col->Pages+oId;
		if (lPageIsFree(&r->Page)) { // Not allocated
			lPageReserve(&r->Page);
		} else {
			Call(&l->GuiLibrary,ReleasePageId,1(Id));
			r = reclaimPageId(l,Id);
		}
	}
	return r;
}

static int libGetPageId(GuiLibrary *this) {
	int r;
	dList *L;
	struct pageDescList *R;
	ThisToThat(Llib,GuiLibrary);
	L = that->PageId.Free.n;
	if (L==&(that->PageId.Free)) {
		struct pageDescCollect *n;
		n = AddPageDescCollect(that,that->PageId.CollectNb);
		L = that->PageId.Free.n;
	}
	R = CastBack(struct pageDescList,Page.Desc.Free,L);
	lPageReserve(&R->Page);
    r = (R->Collect->nPages.Id<<CollectPageShift)+(R-(R->Collect->Pages+0));
    return r;
}
struct engReleasePageId {
	int nCollect,oCollect;
};
static int engReleasePageId(BinTree *bt,void *Clos) {
	struct enginePages *eP;
	struct engReleasePageId *clos;
	BinTree *col;
	clos = Clos;
	eP = CastBack(struct enginePages,pEngine,bt);
	col = BinTreeSeek(&eP->Collects,clos->nCollect);
	if (col!=BinTreeEnd) {
		struct pageCollect *pC;
		Img2dLib *lb;
		pC = CastBack(struct pageCollect,nPages,col);
		lb = &pC->Pages[clos->nCollect].Img2dLib;
		Call(lb,Close,0);
		Call(lb,Free,0);
	}
	return (0!=0);
}
static void libReleasePageId(GuiLibrary *this,int Id) {
	struct engReleasePageId clos;
	BinTree *bt;
	ThisToThat(Llib,GuiLibrary);
	clos.nCollect = Id>>CollectPageShift;
	clos.oCollect = Id & CollectPageMask;
	bt = BinTreeSeek(&that->PageId.Collects,clos.nCollect);
	if (bt!=BinTreeEnd) {
		struct pageDescCollect *col;
		struct pageDescList *L;
		col = CastBack(struct pageDescCollect,nPages,bt);
		L = col->Pages+clos.oCollect;
		if (!lPageIsFree(&L->Page)) {
			lPageFree(&L->Page,&that->PageId.Free);
		    BinTreeForEach(&that->pEngines,engReleasePageId,&clos);
		}
	}
}
static int libImgLoad(GuiLibrary *this,int Id,char *filename) {
	struct pageDescList *pid;
	ThisToThat(Llib,GuiLibrary);
    pid = reclaimPageId(that,Id);
	if (pid!=0) {
		lFilePageNew(&pid->Page,filename);
	}
    return (pid!=0);
}
static int libImgImport(GuiLibrary *this,int Id,ImgDesc *Desc) {
	struct pageDescList *pid;
	ThisToThat(Llib,GuiLibrary);
	pid = reclaimPageId(that,Id);
	if (pid!=0) {
		lDescPageNew(&pid->Page,Desc);
	}
	return (pid!=0);
}
static GuiOutput *libPicture(GuiLibrary *this,int PageId,Geo2dRectangle *Dim) {
	ThisToThat(Llib,GuiLibrary);
	return LPictureNew(that,PageId,Dim);
}
static GuiOutput *libSwapPalPicture(GuiLibrary *this,GuiRgbPalette *Pal,int PageId,Geo2dRectangle *Dim) {
	ThisToThat(Llib,GuiLibrary);
	return LPictureNew(that,PageId,Dim); // For now.
}
static int libRecordEngine(GuiLibrary *this,Render2dEngine *Engine) {
	struct enginePages *pEng;
	int Id;
	BinTree *b,*p;
	ThisToThat(Llib,GuiLibrary);
	pEng = libFirstFreeEngine(that);
	pEng->Engine = Engine;
	b = &pEng->bEngine; Id = b->Id;
	p = &pEng->pEngine;
	BinTreeRemove(&that->FreeEngines,Id);
	enginePagesInit(pEng);
	BinTreeSeekOrInsert(&that->bEngines,Id,b);
    BinTreeSeekOrInsert(&that->pEngines,(int)Engine,p);
	return Id;
}
static void libReleaseEngine(GuiLibrary *this,int EngineId) {
	BinTree *bt;
	ThisToThat(Llib,GuiLibrary);
    bt = BinTreeSeek(&that->bEngines,EngineId);
	if (bt!=BinTreeEnd) {
		struct enginePages *pEng;
		pEng = CastBack(struct enginePages,bEngine,bt);
		BinTreeRemove(&that->bEngines,EngineId);
		BinTreeRemove(&that->pEngines,pEng->pEngine.Id);
		pEng->Engine = 0;
		enginePagesClean(pEng);
		BinTreeSeekOrInsert(&that->FreeEngines,pEng->bEngine.Id,&pEng->bEngine);
	}
}

GuiLibrary *GuiLibraryNew(void) {
	Llib *r;
	MemStack *Mem;
	static struct GuiLibrary Static = {
		libGetPageId,libReleasePageId,
		libImgLoad,libImgImport,libPicture,libSwapPalPicture,
		libRecordEngine,libReleaseEngine
	};
	Mem = rFork(2048);
	mPush(Mem,r);
	r->Mem = Mem;
	r->GuiLibrary.Static = &Static;
	/* Engines */{
	    r->EngineNb = 0;
		BinTreeInit(&r->bEngines);
		BinTreeInit(&r->pEngines);
		BinTreeInit(&r->FreeEngines);
	}
	/* Page Descriptors */{
		dList *d;
		BinTreeInit(&r->PageId.Collects);
		d  = &r->PageId.Free;
		d->p = d->n = d;
		r->PageId.CollectNb = 0;
	}
	return &r->GuiLibrary;
}

/*------------------------*/

static void imgLibStateUnloaded(imgLibNotLoaded *lib);
static void imgLibStateClosed(imgLibNotLoaded *lib);
static void imgLibStateOpened(imgLibNotLoaded *lib);

#define notLoadedIndex(p) ((p)-(p->Collect->Pages))

static void libNotLoadedInfo(Img2dLib *this,int *w,int *h,ImgFormat *format) {
	int idx;
	LlPage *page;
	ThisToThat(imgLibNotLoaded,Img2dLib);
	idx = (that-that->Collect->Pages);
	page = &that->Collect->Desc->Pages[idx].Page;
	*w = page->Desc.Desc.Dim.w;
	*h = page->Desc.Desc.Dim.h;
	*format = page->Desc.Desc.Format;
}
static void libNotLoadedDisplay(Img2dLib *this,Geo2dRectangle *img) {
	ThisToThat(imgLibNotLoaded,Img2dLib);
	imgLibStateClosed(that);
	if (Call(this,Open,0)) {
		Call(this,Display,1(img));
	}
}
static int libNotLoadedOpen(Img2dLib *this) {
	ThisToThat(imgLibNotLoaded,Img2dLib);
	imgLibStateClosed(that);
	return Call(this,Open,0);
}
static void libNotLoadedClose(Img2dLib *this) { }
static void libNotLoadedFree(Img2dLib *this) { }

static void imgLibStateUnloaded(imgLibNotLoaded *lib) {
	static struct Img2dLib Static = {
        libNotLoadedInfo,libNotLoadedDisplay,libNotLoadedOpen,libNotLoadedClose,libNotLoadedFree
	};
	lib->Img2dLib.Static = &Static;
}

    /*---------*/

static void libClosedInfo(Img2dLib *this,int *w,int *h,ImgFormat *format) {
	int idx;
	LlPage *page;
	ThisToThat(imgLibNotLoaded,Img2dLib);
	idx = (that-that->Collect->Pages);
	page = &that->Collect->Desc->Pages[idx].Page;
	*w = page->Desc.Desc.Dim.w;
	*h = page->Desc.Desc.Dim.h;
	*format = page->Desc.Desc.Format;
	if (page->lPage.Static->IsFree) {
		Call(this,Free,0);
	}
}
static void libClosedDisplay(Img2dLib *this,Geo2dRectangle *img) {
	ThisToThat(imgLibNotLoaded,Img2dLib);
	if (Call(this,Open,0)) {
	    Call(this,Display,1(img));
	}
}
static int libClosedOpen(Img2dLib *this) {
	int idx,r;
	LlPage *page;
	ThisToThat(imgLibNotLoaded,Img2dLib);
	idx = (that-that->Collect->Pages);
	page = &that->Collect->Desc->Pages[idx].Page;
	r = (!page->lPage.Static->IsFree)&&(that->Collect->Engine);
	if (r) {
	    that->Child = Call(&page->lPage,Load,1(that->Collect->Engine));
        imgLibStateOpened(that);
	} else {
		Call(this,Free,0);
	}
	return r;
}
static void libClosedClose(Img2dLib *this) {
	ThisToThat(imgLibNotLoaded,Img2dLib);
}
static void libClosedFree(Img2dLib *this) {
	ThisToThat(imgLibNotLoaded,Img2dLib);
	if (that->Child!=this) {
		Call(that->Child,Free,0);
	    that->Child = this;
	}
	imgLibStateUnloaded(that);
}

static void imgLibStateClosed(imgLibNotLoaded *lib) {
	static struct Img2dLib Static = {
		libClosedInfo,libClosedDisplay,libClosedOpen,libClosedClose,libClosedFree
	};
	lib->Img2dLib.Static = &Static;
}

    /*---------*/

static void libOpenedInfo(Img2dLib *this,int *w,int *h,ImgFormat *format) {
	ThisToThat(imgLibNotLoaded,Img2dLib);
	Call(that->Child,Info,3(w,h,format));
}
static void libOpenedDisplay(Img2dLib *this,Geo2dRectangle *img) {
	ThisToThat(imgLibNotLoaded,Img2dLib);
	Call(that->Child,Display,1(img));
}
static int libOpenedOpen(Img2dLib *this) {
	ThisToThat(imgLibNotLoaded,Img2dLib);
	Call(that->Child,Open,0);
}
static void libOpenedClose(Img2dLib *this) {
	ThisToThat(imgLibNotLoaded,Img2dLib);
	Call(that->Child,Close,0);
	imgLibStateClosed(that);
}
static void libOpenedFree(Img2dLib *this) {
	ThisToThat(imgLibNotLoaded,Img2dLib);
	Call(that->Child,Close,0);
	imgLibStateClosed(that);
	Call(this,Free,0);
}

static void imgLibStateOpened(imgLibNotLoaded *lib) {
	static struct Img2dLib Static = {
		libOpenedInfo,libOpenedDisplay,libOpenedOpen,libOpenedClose,libOpenedFree
	};
	lib->Img2dLib.Static = &Static;
}

    /*---------*/

static void imgLibNotLoadedInit(struct pageCollect *Collect,imgLibNotLoaded *page) {
	page->Collect = Collect;
	page->Child = &page->Img2dLib;
	imgLibStateUnloaded(page);
}


text:
#ifndef flac__vorbiscomment_h
#define flac__vorbiscomment_h

#include "FLAC/metadata.h"

FLAC__bool flac__vorbiscomment_add(FLAC__StreamMetadata *block, const char *comment, FLAC__bool value_from_file, FLAC__bool raw, const char **violation);

#endif


text:
<?php

namespace skeeks\cms\components\imaging\filters;

use Imagine\Image\Box;
use Imagine\Image\Point;
use skeeks\cms\components\imaging\Filter;
use skeeks\imagine\Image;

/**
 * @author Semenov Alexander <semenov@skeeks.com>
 */
class ThumbnailFix extends Filter
{
    public $w = 50;
    public $h = 0;

    protected function _save()
    {
        $size = Image::getImagine()->open($this->_originalRootFilePath)->getSize();

        if (!$this->h) {
            $this->h = $this->w;
        }

        $width = $this->w;
        $height = $this->h;

        $box = new Box($width, $height);
        $palette = new \Imagine\Image\Palette\RGB();
        $thumb = Image::getImagine()->create($box, $palette->color('#FFFFFF', 100));

        $startX = 0;
        $startY = 0;
        /*if ($size->getWidth() < $width) {
            $startX = ceil($width - $size->getWidth()) / 2;
        }
        if ($size->getHeight() < $height) {
            $startY = ceil($height - $size->getHeight()) / 2;
        }*/

        if ($size->getWidth() >= $size->getHeight()) {
            //Картинка горизонтальная
            /*$newWidth = $this->w;
            $newHeight = ($size->getHeight() * $this->w) / $size->getWidth();*/

            $originalImage = Image::getImagine()->open($this->_originalRootFilePath);
            $originalImage->resize($originalImage->getSize()->widen($this->w));;
            //$originalImage->save($this->_newRootFilePath);
        } else {
            /*$newHeight = $this->w;
            $newWidth = ($size->getWidth() * $this->w) / $size->getHeight();*/

            $originalImage = Image::getImagine()->open($this->_originalRootFilePath);
            $originalImage->resize($originalImage->getSize()->heighten($this->w));;
            //$originalImage->save($this->_newRootFilePath);
        }

        $size = $originalImage->getSize();
        if ($size->getWidth() < $width) {
            $startX = ceil($width - $size->getWidth()) / 2;
        }
        if ($size->getHeight() < $height) {
            $startY = ceil($height - $size->getHeight()) / 2;
        }

        $thumb->paste($originalImage, new Point($startX, $startY));
        $thumb->save($this->_newRootFilePath);
    }
}


text:
using System;
using OR_M_Data_Entities.Mapping;

namespace ORSigningPro.Common.Data.ORTSigningPro.Tables
{
    public class MobileClosingCorrection
    {
        [Key]
        public int MobileClosingCorrectionID { get; set; }

        public int VincaVendorID { get; set; }

        public string VincaOrderNumber { get; set; }

        public string VincaProductNumber { get; set; }

        public int SequenceNumber { get; set; }

        public int StatusCode { get; set; }

        public string CorrectionText { get; set; }

        public DateTimeOffset PresentedDateTime { get; set; }

        public DateTimeOffset? ConfirmedWithBorrowerDateTime { get; set; }

        public bool AppointmentRequired { get; set; }

        public DateTimeOffset? AppointmentDateTime { get; set; }

        public DateTimeOffset? DocsDownloadedPrintedDateTime { get; set; }

        public DateTimeOffset? CompletedDateTime { get; set; }

        public DateTimeOffset? DocumentsScannedDateTime { get; set; }

        public DateTimeOffset? VincaWorkAcceptedDateTime { get; set; }

        public DateTimeOffset? DroppedDateTime { get; set; }

        public DateTimeOffset? DeletedDateTime { get; set; }

        public int MobileClosingAddressID { get; set; }

        [ForeignKey("MobileClosingAddressID")]
        public MobileClosingAddress MobileClosingAddress { get; set; }

        [Unmapped]
        public object Details { get; set; }
    }
}


text:
package com.foc.shared;

public interface IFocWebModuleShared {
  public int     getOrder();
  public int     getPriorityInDeclaration();
	public boolean isAdminConsole();
	public String  getName();
	public String  getTitle();
  public void    declareXMLViewsInDictionary();
  public void    declareLeafMenuItems();
  public void    declareUnitTestingSuites();
}


text:
<?php

namespace LireinCore\YMLParser;

class Currency
{
    use TYML;
    use TError;

    const DEFAULT_PLUS = 0;

    /**
     * @var string
     */
    protected $id;

    /**
     * @var string
     */
    protected $rate;

    /**
     * @var string
     */
    protected $plus;

    /**
     * @return bool
     */
    public function isValid()
    {
        if ($this->id === null) {
            $this->addError("Currency: missing required attribute 'id'");
        } elseif (!in_array($this->id, ['RUR', 'RUB', 'UAH', 'BYN', 'BYR', 'KZT', 'USD', 'EUR'], true)) {
            $this->addError("Currency: incorrect value in attribute 'id'");
        }
        if ($this->rate === null) {
            $this->addError("Currency: missing required attribute 'rate'");
        } elseif (!(in_array($this->rate, ['CBRF', 'NBU', 'NBK', 'CB'], true) || (is_numeric($this->rate) && (float)$this->rate > 0))) {
            $this->addError("Currency: incorrect value in attribute 'rate'");
        }
        if ($this->plus !== null && (int)$this->plus < 0) {
            $this->addError("Currency: incorrect value in attribute 'plus'");
        }
        return empty($this->errors);
    }

    /**
     * @param array $attributes
     * @return $this
     */
    public function addAttributes($attributes)
    {
        foreach ($attributes as $name => $value) {
            $this->addField($name, $value);
        }

        return $this;
    }

    /**
     * @return string|null
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param string $value
     * @return $this
     */
    public function setId($value)
    {
        $this->id = $value;

        return $this;
    }

    /**
     * @return float|string|null
     */
    public function getRate()
    {
        return is_numeric($this->rate) ? (float)$this->rate : $this->rate;
    }

    /**
     * @param string $value
     * @return $this
     */
    public function setRate($value)
    {
        $this->rate = $value;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getPlus()
    {
        return $this->plus === null ? null : (int)$this->plus;
    }

    /**
     * @param string $value
     * @return $this
     */
    public function setPlus($value)
    {
        $this->plus = $value;

        return $this;
    }
}


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// So that mojo is defined.
import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js';
import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js';
import 'chrome://resources/mojo/url/mojom/url.mojom-lite.js';
import 'chrome://nearby/mojo/nearby_share_target_types.mojom-lite.js';
import 'chrome://nearby/mojo/nearby_share_share_type.mojom-lite.js';
import 'chrome://nearby/mojo/nearby_share.mojom-lite.js';

import {NearbyProgressElement} from 'chrome://nearby/shared/nearby_progress.js';

import {assertEquals} from '../../chai_assert.js';

suite('ProgressTest', function() {
  /** @type {!NearbyProgressElement} */
  let progressElement;

  setup(function() {
    progressElement = /** @type {!NearbyProgressElement} */ (
        document.createElement('nearby-progress'));
    document.body.appendChild(progressElement);
  });

  teardown(function() {
    progressElement.remove();
  });

  /** @return {!nearbyShare.mojom.ShareTarget} */
  function getDefaultShareTarget() {
    return /** @type {!nearbyShare.mojom.ShareTarget} */ ({
      id: {high: 0, low: 0},
      name: 'Default Device Name',
      type: nearbyShare.mojom.ShareTargetType.kPhone,
      imageUrl: {
        url: 'http://google.com/image',
      },
    });
  }

  test('renders component', function() {
    assertEquals('NEARBY-PROGRESS', progressElement.tagName);
  });

  test('renders device name', function() {
    const name = 'Device Name';
    const shareTarget = getDefaultShareTarget();
    shareTarget.name = name;
    progressElement.shareTarget = shareTarget;

    const renderedName =
        progressElement.shadowRoot.querySelector('#device-name').innerText;
    assertEquals(name, renderedName);
  });

  test('renders target image', function() {
    progressElement.shareTarget = getDefaultShareTarget();

    const renderedSource =
        progressElement.shadowRoot.querySelector('#share-target-image').src;
    assertEquals('chrome://image/?http://google.com/image=s68', renderedSource);
  });

  test('renders blank target image', function() {
    const shareTarget = getDefaultShareTarget();
    shareTarget.imageUrl.url = '';
    progressElement.shareTarget = shareTarget;

    const renderedSource =
        progressElement.shadowRoot.querySelector('#share-target-image').src;
    assertEquals('', renderedSource);
  });
});