text:
/*global mocha, describe, beforeEach, it*/

function runTests(BackboneTreeModel, expect) {

    var _ = BackboneTreeModel._, Backbone = BackboneTreeModel.Backbone, tree;

    describe('Backbone Tree', ()=> {
        beforeEach(()=> {
            tree = new Backbone.TreeModel({
                id: 'root',
                tagname: 'body',
                nodes: [
                    {
                        id: 'wrapper',
                        tagname: 'div',
                        nodes: [
                            {
                                id: 'sidebar',
                                tagname: 'div',
                                width: 300,
                                nodes: [
                                    { tagname: 'p' },
                                    {
                                        tagname: 'ul',
                                        nodes: [
                                            { tagname: 'li' },
                                            { tagname: 'li' },
                                            { tagname: 'li' }
                                        ]
                                    },
                                    { tagname: 'span' }
                                ]
                            },
                            {
                                id: 'content',
                                tagname: 'div',
                                width: 600,
                                nodes: [
                                    {
                                        id: 'title',
                                        tagname: 'h2'
                                    },
                                    {
                                        tagname: 'p',
                                        nodes: [
                                            {
                                                tagname: 'anchor',
                                                nodes: [
                                                    { tagname: 'span' }
                                                ]
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            });
        });

        describe('#find', ()=> {
            it('Should return matched node', ()=> {
                var sidebar = tree.find('sidebar');
                expect(sidebar).to.be.ok();
                expect(sidebar.get('width')).to.be(300);
                expect(sidebar.get('tagname')).to.be('div');

                expect(tree.find('title').get('tagname')).to.be('h2');
            });
            it('should return root node if id matches root', ()=> {
                expect(tree.find('root')).to.be(tree);
            });
        });

        describe('#where', ()=> {
            it('Should return all matched descendants', ()=> {
                expect(tree.where({tagname: 'body'}).length).to.be(1);

                expect(tree.where({tagname: 'div'}).length).to.be(3);
            });
            it('Should support #find/#where context chaining', ()=> {
                expect(tree.find('sidebar').where({tagname: 'div'}).length).to.be(1);
            });
        });

        describe('#isRoot', ()=> {
            it('Should return true when current node is root node', ()=> {
                expect(tree.isRoot()).to.be.ok();
                expect(tree.find('title').root().isRoot()).to.be.ok();
                expect(tree.find('title').isRoot()).to.not.be.ok();
                expect(tree.find('sidebar').isRoot()).to.not.be.ok();
            });
        });

        describe('#isRootBranch', ()=> {
            it('should check if child of root node', ()=> {
                expect(tree.find('wrapper').isRootBranch()).to.be.ok();
                expect(tree.find('sidebar').isRootBranch()).to.not.be.ok();
            });
        });

        describe('#root', ()=> {
            it('Should return the root node', ()=> {
                var sidebar = tree.find('sidebar');
                var content = tree.find('content');

                expect(sidebar.root().get('tagname')).to.be('body');
                expect(content.root().get('tagname')).to.be('body');
            });
        });

        describe('#contains', ()=> {
            it('Should return true if node is a descendant of current node', ()=> {
                expect(tree.contains(tree.find('sidebar'))).to.be.ok();
            });
            it('Should return false if node is not a descendant of current node', ()=> {
                expect(tree.find('sidebar').contains(tree)).to.not.be.ok();
            });
        });

        describe('#parent', ()=> {
            it('Should return the parent node', ()=> {
                var sidebar = tree.find('sidebar');
                var content = tree.find('content');

                expect(sidebar.parent().get('id')).to.be('wrapper');
                expect(content.parent().get('id')).to.be('wrapper');
            });
        });

        describe('#nodes', ()=> {
            it('Should return backbone collection consisting of children nodes if children exist', ()=> {
                var titleNodes = tree.find('title').nodes();
                expect(titleNodes).to.not.be.ok();

                var sidebarNodes = tree.find('sidebar').nodes();
                expect(sidebarNodes).to.be.ok();
                expect(sidebarNodes.length).to.be(3);
                expect(sidebarNodes instanceof Backbone.Collection).to.be.ok();
            });
        });

        describe('#add', ()=> {
            it('Should support adding single node', ()=> {
                var sidebar = tree.find('sidebar').add({id: 'title_1'});
                expect(sidebar.nodes().length).to.be(4);
                expect(sidebar.find('title_1')).to.be.ok();
            });

            it('Should support adding array of nodes', ()=> {
                var sidebar = tree.find('sidebar').add([
                    {
                        id: 'title_2',
                        tagname: 'h1',
                        nodes: [
                            {
                                id: 'anchor',
                                tagname: 'a',
                                nodes: [
                                    { tagname: 'span' }
                                ]
                            }
                        ]
                    },
                    {
                        id: 'title_3',
                        tagname: 'h2'
                    }
                ]);
                expect(sidebar.nodes().length).to.be(5);
                expect(sidebar.find('title_2')).to.be.ok();
                expect(sidebar.find('title_3')).to.be.ok();
                expect(sidebar.find('anchor')).to.be.ok();
                expect(sidebar.find('anchor').nodes().length).to.be(1);
            });

            it('Should support adding TreeModel nodes', ()=> {
                // place sidebar before title node
                tree.find('content').add(tree.find('sidebar'));
                expect(tree.find('content').nodes().length).to.be(3);
                expect(tree.find('wrapper').nodes().length).to.be(1);
                expect(tree.find('sidebar').parent()).to.be(tree.find('content'));
            });
        });

        describe('#insertBefore', ()=> {
            it('Should support adding objects to the left of a node', ()=> {
                var wrapper = tree.find('wrapper').insertBefore({id: 'left_wrapper'});
                expect(tree.nodes().length).to.be(2);
                expect(tree.nodes().first().id).to.be('left_wrapper');
                expect(wrapper.prev().id).to.be('left_wrapper');
            });

            it('Should support inserting TreeModel nodes', ()=> {
                // place sidebar before title node
                tree.find('title').insertBefore(tree.find('sidebar'));
                expect(tree.find('content').nodes().length).to.be(3);
                expect(tree.find('wrapper').nodes().length).to.be(1);
                expect(tree.find('sidebar').parent()).to.be(tree.find('content'));
            });
        });

        describe('#insertAfter', ()=> {
            it('Should support adding objects to the right of a node', ()=> {
                var wrapper = tree.find('wrapper').insertAfter({id: 'right_wrapper'});
                expect(tree.nodes().length).to.be(2);
                expect(tree.nodes().last().id).to.be('right_wrapper');
                expect(wrapper.next().id).to.be('right_wrapper');
            });

            it('Should support inserting TreeModel nodes', ()=> {
                // place sidebar before title node
                tree.find('title').insertAfter(tree.find('sidebar'));
                expect(tree.find('content').nodes().length).to.be(3);
                expect(tree.find('wrapper').nodes().length).to.be(1);
                expect(tree.find('sidebar').parent()).to.be(tree.find('content'));
            });
        });

        describe('#next', ()=> {
            it('Should return the node on the right', ()=> {
                expect(tree.find('sidebar').next().id).to.be('content');
            });
        });

        describe('#prev', ()=> {
            it('Should return the node on the left', ()=> {
                expect(tree.find('content').prev().id).to.be('sidebar');
            });
        });

        describe('#remove', ()=> {
            it('Should remove current node', ()=> {
                tree.find('sidebar').remove();
                expect(tree.find('wrapper').nodes().length).to.be(1);
                expect(tree.find('wrapper').nodes().first().id).to.be('content');
            });

            it('Should remove first matched descedant', ()=> {
                tree.remove({tagname: 'p'}, true);
                expect(tree.where({tagname: 'p'}).length).to.be(1);
            });

            it('Should remove all matched descedants', ()=> {
                tree.remove({tagname: 'p'});
                expect(tree.where({tagname: 'p'}).length).to.be(0);
            });
        });

        describe('#empty', ()=> {
            it('Should remove all children in current node', ()=> {
                tree.empty();
                expect(tree.find('wrapper')).to.not.be.ok();
                expect(tree.nodes()).to.not.be.ok();
            });
        });

        describe('#where for Collection/Array', ()=> {
            it('Should be supported for node children collection', ()=> {
                expect(tree.nodes().where({tagname: 'p'}, {deep: true}).length).to.be(2);
                expect(tree.find('sidebar').nodes().where({tagname: 'p'}, {deep: true}).length).to.be(1);
            });

            it('Should be supported from a chained #where call', ()=> {
                expect(tree.where({tagname: 'div'}).where({tagname: 'span'}).length).to.be(2);
                expect(tree.where({tagname: 'anchor'}).where({tagname: 'span'}).length).to.be(1);
            });
        });

        describe('#toJSON', ()=> {
            it('Should return JSON starting from node, account for node changes', ()=> {
                tree.find('sidebar').remove(); // perform a change

                var treeJSON = tree.toJSON();
                expect(treeJSON.nodes[0].nodes.length).to.be(1);
                expect(treeJSON.nodes[0].nodes[0].id).to.be('content');

                var wrapperJSON = tree.find('wrapper').toJSON();
                expect(wrapperJSON.nodes.length).to.be(1);
                expect(wrapperJSON.nodes[0].id).to.be('content');
            });
        });

        describe('#flatten', ()=> {
            it('should return a flattend array', ()=> {
                var arr = tree.flatten();
                expect(arr.length).to.be(14);
            });

            it('should support toArray alias', ()=> {
                var arr = tree.toArray();
                expect(arr.length).to.be(14);
            });
        });

        describe('should be able to specify model constructor with Model', ()=> {
            var MyCollection = Backbone.TreeCollection.extend({}),
                MyModel = Backbone.TreeModel.extend({
                collectionConstructor : MyCollection
            }),

            tree = new MyModel({
                id: 'root',
                tagname: 'body',
                nodes: [
                    {
                        id: 'wrapper',
                        tagname: 'div',
                        nodes: [
                            { tagname: 'p' }
                        ]
                    }
                ]
            });

            it('Children should be instance of MyModel', ()=> {
                expect(tree instanceof MyModel).to.be.ok();

                tree.nodes().forEach((child)=> {
                    expect(child instanceof MyModel).to.be.ok();
                });
            });

            it('Child collection should be instance of MyCollection', ()=> {
                expect(tree.nodes() instanceof MyCollection).to.be.ok();

                tree.nodes().forEach((child)=> {
                    expect(child.nodes() instanceof MyCollection).to.be.ok();
                });
            });
        });

        describe('toJSON should consider tree changes', ()=> {
            it('toJSON should return tree without Sydney', ()=> {
                tree = new Backbone.TreeCollection([
                    {
                        id:1,
                        title:'Australia',
                        nodes: [
                            {
                                id: 2,
                                title : 'Sydney'
                            }
                        ]
                    },
                ]);

                //tree without changes:
                expect(tree.toJSON()).eql([
                    {
                        id:1,
                        title:'Australia',
                        nodes: [
                            {
                                id: 2,
                                title : 'Sydney'
                            }
                        ]
                    }
                ]);

                var Sydney = tree.at(0).nodes().at(0);
                Sydney.collection.remove(Sydney);

                //tree after changes:
                expect(tree.toJSON()).eql([
                    {
                        id:1,
                        title:'Australia'
                    }
                ]);
            });
        });

        describe('#setPropDescendants', ()=> {
            it('should set descendant properties', ()=> {
                tree.setPropDescendants({newProperty: 'foo'});
                expect(tree.get('newProperty')).to.be('foo');
                expect(tree.find('content').get('newProperty')).to.be('foo');
            });
        });

        describe('#getClosestAncestorProperty', ()=> {
            it('should get closest property', ()=> {
                var title = tree.find('title');
                var closestPropWidth = title.getClosestAncestorProperty('width');
                expect(closestPropWidth).to.be(600);

                var closestPropTagname = title.getClosestAncestorProperty('tagname');
                expect(closestPropTagname).to.be('h2');
            });
        });
    });
}

if(typeof define === 'function' && define.amd) {
    define(['treemodel'], (TreeModel)=> {
        mocha.setup('bdd');
        runTests(TreeModel, window.expect);
        mocha.run();
    });
} else if(typeof exports !== 'undefined') {
    runTests(require('../src/backbone.treemodel'), require('expect.js'));
} else {
    runTests(window.BackboneTreeModel, window.expect);
}


text:
package userguide.mex.services.example3;

public class Version {
    public String getVersion() throws Exception {
        return "Hello I am Axis2 version service ," +
                " My version is " + org.apache.axis2.Version.getVersionText();
    }
}

redpajama_set_name: RedPajamaGithub


text:
@class Pinata;

@interface PullCord : NSObject<GameEntity> {
    Vector2D position;
    Vector2D velocity;
    float angle;
    float angularVelocity;
    Pinata* pinata;
    Game* game;
    Boolean alive;
    Boolean locked;
    Boolean stretched;
}

@property (nonatomic) Vector2D position;
@property (nonatomic) Vector2D velocity;
@property (nonatomic) Boolean alive;
@property (nonatomic) Boolean locked;
@property (nonatomic, readonly) float angle;

-(id)initForPinata:(Pinata*)ent forGame:(Game*)g;
-(Boolean)isInside:(CGPoint)p;
-(void)tick:(float) timeElapsed;
-(void)render:(float)timeElapsed;
-(Boolean)trigger;
-(void)addForce:(Vector2D)force;

@end


text:
namespace kaldi {

// All the lines in this file seem to be declaring template specializations.
// These tell the compiler that we'll implement the templated function
// separately for the different template arguments (float, double).

template<>
double SolveQuadraticProblem(const SpMatrix<double> &H, const VectorBase<double> &g,
                             const SolverOptions &opts, VectorBase<double> *x);

template<>
float SolveQuadraticProblem(const SpMatrix<float> &H, const VectorBase<float> &g,
                            const SolverOptions &opts, VectorBase<float> *x);

}  // namespace kaldi

#endif  // KALDI_MATRIX_SP_MATRIX_INL_H_


text:
import time
import math
from pyicloud import PyiCloudService
from pyicloud.exceptions import PyiCloudFailedLoginException

from lessons.base.plugin import JenniferResponsePlugin
from lessons.base.exceptions import JenniferUserWantsToCancelException

class JenniferFindMyIphonePlugin(JenniferResponsePlugin):

    PRIORITY = 50
    VERBOSE_NAME = "Find My Iphone"
    REQUIRES_NETWORK = True

    def can_respond(self, **kwargs):
        tags = kwargs.get('tags')
        one_verb = [
            ('find', 'VB'),
            ('finding', 'VBG'),
        ]
        one_of_these = [
            ('phone', 'NN'),
            ('iphone', 'NN')
        ]

        tags_dict = self.tags_dict_by_tag(tags)

        # There must only be one 'NN'
        can_repond = len(tags_dict.get('NN', [])) == 1
        # Need any the verbs in `one_verb` with correct context
        can_repond = can_repond and any([word in tags for word in one_verb])
        # Need at least one of the words in `one_of_these` with correct context
        can_repond = can_repond and any([word in tags for word in one_of_these])

        return can_repond

    def respond(self, **kwargs):
        client = kwargs.get('client')

        client.give_output_string(self, "Let's find that phone")

        try:
            api = PyiCloudService(self.settings['icloudEmail'], self.settings['icloudPassword'])
        except PyiCloudFailedLoginException:
            client.give_output_string(self, "Invalid iCloud Username & Password")
            return

        # All Devices
        devices = api.devices

        # Just the iPhones
        iphones = []

        # The one to ring
        phone_to_ring = None

        for device in devices:
            current = device.status()
            if "iPhone" in current['deviceDisplayName']:
                iphones.append(device)

        # No iphones
        if len(iphones) == 0:
            client.give_output_string(self, "No IPhones Found on your account")
            return

        # Many iphones
        elif len(iphones) > 1:
            client.give_output_string(self, "There are multiple iphones on your account.")
            try:
                for phone in iphones:
                    if client.confirm(self, "Did you mean the {type} named {name}?".format(type=phone.status()['deviceDisplayName'], name=phone.status()['name'])):
                        phone_to_ring = phone
                        break
            except JenniferUserWantsToCancelException():
                return

        # Just one
        elif len(iphones) == 1:
            phone_to_ring = iphones[0]

        if not phone_to_ring:
            client.give_output_string(self, "You didn't select an iPhone")
            return

        # This will attempt to update the status
        phone_to_ring.status()

        if phone_to_ring.status()['batteryLevel'] == 0:
            client.give_output_string(self, "Oh no! The phone is off!")
            location = phone_to_ring.location()
            if location and location[u'locationFinished']:
                timestamp = location['timeStamp'] / 1000
                current_timestamp = time.time()
                seconds_ago = round(abs(current_timestamp - timestamp))
                minutes = int(math.floor(seconds_ago % 60))
                hours = int(math.floor(seconds_ago / 60 / 60))

                time_ago_natural_parts = []
                if hours > 0:
                    time_ago_natural_parts.append("{} hours".format(hours))
                if minutes > 0:
                    time_ago_natural_parts.append("{} minutes".format(minutes))
                time_ago_natural = " and ".join(time_ago_natural_parts) + " ago"
                client.give_output_string(self, "It was last seen {}.".format(time_ago_natural))
            else:
                client.give_output_string(self, "I can't find a location for it.")

            return

        client.give_output_string(self, "Sending ring command to {} now".format(phone_to_ring.status()['deviceDisplayName']))
        phone_to_ring.play_sound()
        return


text:
package rsc.documentation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Indicates what kind of behaviors the operator has.
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface Operator {
    /**
     * Returns the operator behaviors
     * @return the operator behaviors
     */
    OperatorType[] traits();

    /**
     * Returns the operator known API aliases
     * @return the operator known API aliases
     */
    String[] aliases() default "";

}


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

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="homepage" pattern="/">
        <default key="_controller">WjAppBundle:Default:index</default>
    </route>
</routes>


text:
void xt_net_engine_iengine_init(xt_net_engine_iengine_t *iengine,
    xt_net_engine_iengine_create_f create,
    xt_net_engine_iengine_destroy_f destroy,
    xt_net_engine_iengine_get_handler_for_message_f get_handler_for_message,
    xt_net_engine_iengine_maintain_f maintain,
    xt_net_engine_iengine_run_f run, xt_net_engine_iengine_start_f start,
    xt_net_engine_iengine_stop_f stop)
{
  assert(iengine);

  iengine->create = create;
  iengine->destroy = destroy;
  iengine->get_handler_for_message = get_handler_for_message;
  iengine->maintain = maintain;
  iengine->run = run;
  iengine->start = start;
  iengine->stop = stop;
}


text:
using System;
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.RecoveryServicesBackup.Models
{
    public partial class AzureWorkloadSAPHanaPointInTimeRecoveryPoint : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsCollectionDefined(TimeRanges))
            {
                writer.WritePropertyName("timeRanges");
                writer.WriteStartArray();
                foreach (var item in TimeRanges)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(RecoveryPointTimeInUTC))
            {
                writer.WritePropertyName("recoveryPointTimeInUTC");
                writer.WriteStringValue(RecoveryPointTimeInUTC.Value, "O");
            }
            if (Optional.IsDefined(RestorePointType))
            {
                writer.WritePropertyName("type");
                writer.WriteStringValue(RestorePointType.Value.ToString());
            }
            if (Optional.IsCollectionDefined(RecoveryPointTierDetails))
            {
                writer.WritePropertyName("recoveryPointTierDetails");
                writer.WriteStartArray();
                foreach (var item in RecoveryPointTierDetails)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(RecoveryPointMoveReadinessInfo))
            {
                writer.WritePropertyName("recoveryPointMoveReadinessInfo");
                writer.WriteStartObject();
                foreach (var item in RecoveryPointMoveReadinessInfo)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteObjectValue(item.Value);
                }
                writer.WriteEndObject();
            }
            writer.WritePropertyName("objectType");
            writer.WriteStringValue(ObjectType);
            writer.WriteEndObject();
        }

        internal static AzureWorkloadSAPHanaPointInTimeRecoveryPoint DeserializeAzureWorkloadSAPHanaPointInTimeRecoveryPoint(JsonElement element)
        {
            Optional<IList<PointInTimeRange>> timeRanges = default;
            Optional<DateTimeOffset> recoveryPointTimeInUTC = default;
            Optional<RestorePointType> type = default;
            Optional<IList<RecoveryPointTierInformationV2>> recoveryPointTierDetails = default;
            Optional<IDictionary<string, RecoveryPointMoveReadinessInfo>> recoveryPointMoveReadinessInfo = default;
            string objectType = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("timeRanges"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<PointInTimeRange> array = new List<PointInTimeRange>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(PointInTimeRange.DeserializePointInTimeRange(item));
                    }
                    timeRanges = array;
                    continue;
                }
                if (property.NameEquals("recoveryPointTimeInUTC"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    recoveryPointTimeInUTC = property.Value.GetDateTimeOffset("O");
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    type = new RestorePointType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("recoveryPointTierDetails"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<RecoveryPointTierInformationV2> array = new List<RecoveryPointTierInformationV2>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(RecoveryPointTierInformationV2.DeserializeRecoveryPointTierInformationV2(item));
                    }
                    recoveryPointTierDetails = array;
                    continue;
                }
                if (property.NameEquals("recoveryPointMoveReadinessInfo"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    Dictionary<string, RecoveryPointMoveReadinessInfo> dictionary = new Dictionary<string, RecoveryPointMoveReadinessInfo>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, Models.RecoveryPointMoveReadinessInfo.DeserializeRecoveryPointMoveReadinessInfo(property0.Value));
                    }
                    recoveryPointMoveReadinessInfo = dictionary;
                    continue;
                }
                if (property.NameEquals("objectType"))
                {
                    objectType = property.Value.GetString();
                    continue;
                }
            }
            return new AzureWorkloadSAPHanaPointInTimeRecoveryPoint(objectType, Optional.ToNullable(recoveryPointTimeInUTC), Optional.ToNullable(type), Optional.ToList(recoveryPointTierDetails), Optional.ToDictionary(recoveryPointMoveReadinessInfo), Optional.ToList(timeRanges));
        }
    }
}


text:
package safebrowsing

import (
	"reflect"
	"testing"
	"time"

	dpb "github.com/golang/protobuf/ptypes/duration"
	pb "github.com/google/safebrowsing/internal/safebrowsing_proto"
)

func TestCacheLookup(t *testing.T) {
	now := time.Unix(1451436338, 951473000)
	mockNow := func() time.Time { return now }

	type cacheLookup struct {
		h   hashPrefix
		tds map[ThreatDescriptor]bool
		r   cacheResult
	}
	vectors := []struct {
		gotCache  *cache // The cache to apply the Purge and Lookup on
		wantCache *cache // The cache expected after Purge
		lookups   []cacheLookup
	}{{
		gotCache: &cache{
			pttls: map[hashPrefix]map[ThreatDescriptor]time.Time{
				"AAAABBBBBBBBBBBBBBBBBBBBBBBBBBBB": {
					{1, 2, 3}: now.Add(DefaultUpdatePeriod),
				},
				"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ": {
					{2, 2, 2}: now.Add(-time.Minute),
					{1, 1, 1}: now.Add(-DefaultUpdatePeriod),
				},
			},
			nttls: map[hashPrefix]time.Time{
				"AAAA": now.Add(DefaultUpdatePeriod),
				"BBBB": now.Add(-time.Minute),
			},
			now: mockNow,
		},
		wantCache: &cache{
			pttls: map[hashPrefix]map[ThreatDescriptor]time.Time{
				"AAAABBBBBBBBBBBBBBBBBBBBBBBBBBBB": {
					{1, 2, 3}: now.Add(DefaultUpdatePeriod),
				},
			},
			nttls: map[hashPrefix]time.Time{
				"AAAA": now.Add(DefaultUpdatePeriod),
			},
			now: mockNow,
		},
		lookups: []cacheLookup{{
			h:   "AAAABBBBBBBBBBBBBBBBBBBBBBBBBBBB",
			tds: map[ThreatDescriptor]bool{{1, 2, 3}: true},
			r:   positiveCacheHit,
		}, {
			h:   "AAAACDCDCDCDCDCDCDCDCDCDCDCDCDCD",
			tds: nil,
			r:   negativeCacheHit,
		}, {
			h:   "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
			tds: nil,
			r:   cacheMiss,
		}},
	}, {
		gotCache: &cache{
			pttls: map[hashPrefix]map[ThreatDescriptor]time.Time{
				"AAAABBBBBBBBBBBBBBBBBBBBBBBBBBBB": {
					{1, 2, 3}: now.Add(DefaultUpdatePeriod),
					{1, 1, 1}: now.Add(-DefaultUpdatePeriod),
				},
				"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ": {
					{2, 2, 2}: now.Add(-time.Minute),
					{1, 1, 1}: now.Add(-DefaultUpdatePeriod),
				},
			},
			nttls: map[hashPrefix]time.Time{
				"AAAA": now.Add(DefaultUpdatePeriod * 2),
				"BBBB": now.Add(-time.Minute),
			},
			now: mockNow,
		},
		wantCache: &cache{
			pttls: map[hashPrefix]map[ThreatDescriptor]time.Time{
				"AAAABBBBBBBBBBBBBBBBBBBBBBBBBBBB": {
					{1, 2, 3}: now.Add(DefaultUpdatePeriod),
					{1, 1, 1}: now.Add(-DefaultUpdatePeriod),
				},
			},
			nttls: map[hashPrefix]time.Time{
				"AAAA": now.Add(DefaultUpdatePeriod * 2),
			},
			now: mockNow,
		},
		lookups: []cacheLookup{{
			h:   "AAAABBBBBBBBBBBBBBBBBBBBBBBBBBBB",
			tds: nil,
			r:   cacheMiss,
		}, {
			h:   "AAAACDCDCDCDCDCDCDCDCDCDCDCDCDCD",
			tds: nil,
			r:   negativeCacheHit,
		}, {
			h:   "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
			tds: nil,
			r:   cacheMiss,
		}},
	}, {
		gotCache:  &cache{now: mockNow},
		wantCache: &cache{now: mockNow},
		lookups: []cacheLookup{{
			h:   "AAAABBBBBBBBBBBBBBBBBBBBBBBBBBBB",
			tds: nil,
			r:   cacheMiss,
		}, {
			h:   "AAAACDCDCDCDCDCDCDCDCDCDCDCDCDCD",
			tds: nil,
			r:   cacheMiss,
		}},
	}}

	for i, v := range vectors {
		for j, l := range v.lookups {
			gotTDs, gotR := v.gotCache.Lookup(l.h)
			if !reflect.DeepEqual(gotTDs, l.tds) {
				t.Errorf("test %d, lookup %d, threats mismatch:\ngot  %+v\nwant %+v", i, j, gotTDs, l.tds)
			}
			if gotR != l.r {
				t.Errorf("test %d, lookup %d, result mismatch: got %d, want %d", i, j, gotR, l.r)

			}
		}
		v.gotCache.Purge()
		if !reflect.DeepEqual(v.wantCache.pttls, v.gotCache.pttls) {
			t.Errorf("purge test %d, mismatching cache contents: PTTLS\ngot  %+v\nwant %+v", i, v.gotCache.pttls, v.wantCache.pttls)
		}
		if !reflect.DeepEqual(v.wantCache.nttls, v.gotCache.nttls) {
			t.Errorf("purge test %d, mismatching cache contents: NTTLS\ngot  %+v\nwant %+v", i, v.gotCache.nttls, v.wantCache.nttls)
		}
		for j, l := range v.lookups {
			gotTDs, gotR := v.gotCache.Lookup(l.h)
			if !reflect.DeepEqual(gotTDs, l.tds) {
				t.Errorf("purge test %d, lookup %d, threats mismatch:\ngot  %+v\nwant %+v", i, j, gotTDs, l.tds)
			}
			if gotR != l.r {
				t.Errorf("purge test %d, lookup %d, result mismatch: got %d, want %d", i, j, gotR, l.r)
			}
		}
	}
}

func TestCacheUpdate(t *testing.T) {
	now := time.Unix(1451436338, 951473000)
	mockNow := func() time.Time { return now }

	vectors := []struct {
		req       *pb.FindFullHashesRequest
		resp      *pb.FindFullHashesResponse
		gotCache  *cache
		wantCache *cache
	}{{
		req:  &pb.FindFullHashesRequest{},
		resp: &pb.FindFullHashesResponse{},
		gotCache: &cache{
			now: mockNow,
		},
		wantCache: &cache{pttls: map[hashPrefix]map[ThreatDescriptor]time.Time{},
			nttls: map[hashPrefix]time.Time{},
			now:   mockNow,
		},
	}, {
		req: &pb.FindFullHashesRequest{
			ThreatInfo: &pb.ThreatInfo{
				ThreatTypes:      []pb.ThreatType{0, 1, 2},
				PlatformTypes:    []pb.PlatformType{1, 2, 3},
				ThreatEntryTypes: []pb.ThreatEntryType{2, 3, 4},
				ThreatEntries:    []*pb.ThreatEntry{{Hash: []byte("aaaa")}},
			}},
		resp: &pb.FindFullHashesResponse{
			Matches: []*pb.ThreatMatch{{
				ThreatType:      0,
				PlatformType:    1,
				ThreatEntryType: 2,
				Threat:          &pb.ThreatEntry{Hash: []byte("aaaabbbbccccddddeeeeffffgggghhhh")},
				CacheDuration:   &dpb.Duration{Seconds: 1000, Nanos: 0},
			}, {
				ThreatType:      1,
				PlatformType:    2,
				ThreatEntryType: 3,
				Threat:          &pb.ThreatEntry{Hash: []byte("aaaaaaaaccccddddeeeeffffgggghhhh")},
				CacheDuration:   &dpb.Duration{Seconds: 1000, Nanos: 0},
			}, {
				ThreatType:      2,
				PlatformType:    3,
				ThreatEntryType: 4,
				Threat:          &pb.ThreatEntry{Hash: []byte("aaaaccccccccddddeeeeffffgggghhhh")},
				CacheDuration:   &dpb.Duration{Seconds: 1000, Nanos: 0},
			}},
			NegativeCacheDuration: &dpb.Duration{Seconds: 1000, Nanos: 0},
		},
		gotCache: &cache{
			now: mockNow,
		},
		wantCache: &cache{
			pttls: map[hashPrefix]map[ThreatDescriptor]time.Time{
				"aaaabbbbccccddddeeeeffffgggghhhh": {
					{0, 1, 2}: now.Add(1000 * time.Second),
				},
				"aaaaaaaaccccddddeeeeffffgggghhhh": {
					{1, 2, 3}: now.Add(1000 * time.Second),
				},
				"aaaaccccccccddddeeeeffffgggghhhh": {
					{2, 3, 4}: now.Add(1000 * time.Second),
				},
			},
			nttls: map[hashPrefix]time.Time{
				"aaaa": now.Add(1000 * time.Second),
			},
			now: mockNow,
		},
	}}

	for i, v := range vectors {
		v.gotCache.Update(v.req, v.resp)
		if !reflect.DeepEqual(v.wantCache.pttls, v.gotCache.pttls) {
			t.Errorf("test %d, mismatching cache contents: PTTLS\ngot  %+v\nwant %+v", i, v.gotCache.pttls, v.wantCache.pttls)
		}
		if !reflect.DeepEqual(v.wantCache.nttls, v.gotCache.nttls) {
			t.Errorf("test %d, mismatching cache contents: NTTLS\ngot  %+v\nwant %+v", i, v.gotCache.nttls, v.wantCache.nttls)
		}
	}
}


text:
published: true
title: VR display
tags: vr display screen
---
> What it's like to spend 40-50 hours in VR every week - [Working From Orbit](https://blog.immersed.team/working-from-orbit-39bf95a6d385) / [HN](https://news.ycombinator.com/item?id=28678041)

- [www.simulavr.com](https://www.simulavr.com/)


text:
package graph

import (
	"errors"
)

const (
	ERROR_NO_ROUTE = "NO SUCH ROUTE"
)

type (
	ExactRouteDistanceCalculator struct {
		Graph Graph
		Route []Edge
	}
)

func NewExactRouteDistanceCalculator(g Graph, edges []Edge) *ExactRouteDistanceCalculator {
	return &ExactRouteDistanceCalculator{
		Graph: g,
		Route: edges,
	}
}

func (calculator *ExactRouteDistanceCalculator) Calculate() (Distance, error) {
	distance := Distance(0)
	for _, edge := range calculator.Route {
		w, exist := calculator.Graph[edge[0]][edge[1]]
		if !exist {
			return 0, errors.New(ERROR_NO_ROUTE)
		}
		distance += w
	}
	return distance, nil
}


text:
package pl.setblack.chat;
import spray.json.DefaultJsonProtocol;
import spray.json._;

/**
 * Simple class representing message.
 */
class Message(val value: String, val author: String) extends Serializable {

}

object MessageJsonProtocol extends DefaultJsonProtocol {
  implicit object MessageJsonFormat extends RootJsonFormat[Message] {
    def write (m: Message) = {
      JsArray( JsString(m.value), JsString(m.author));
    }
    def read (value:JsValue) = value.asJsObject.getFields("value", "author") match {
      case Seq(JsString(value), JsString(author)) =>
        new Message(value, author);
      case _ => deserializationError("what is this?");
    };
  }
}

object MessageListJsonProtocol extends DefaultJsonProtocol {
  implicit object MessageListJsonFormat extends RootJsonFormat[List[Message]] {
    def write (l: List[Message]) = {

       l.map(m => JsObject( "value" -> JsString(m.value), "author" -> JsString(m.author)) ).toList.toJson;
    }

    def read (value:JsValue) = ???;
  }

}


text:
@interface IndiaUI : NSObject<AppUIProtocol>

@end


text:
var request = require('request');
var moment  = require('moment');
var keys    = require('./../keys');

// TODO: Make zipcode dynamic
// TODO: Listen for date, like `what movies TOMORROW`

function getMovies(callback) {

  var movies_url = 'http://data.tmsapi.com/v1.1/movies/showings';
      movies_url += '?startDate=2016-03-25';
      movies_url += '&zip=97123';
      movies_url += '&api_key=' + keys.gracenote.key;

  request(movies_url, function(e,r,body){
    var json = JSON.parse(body);
    var movie = {};
    movie.name = json[0].title;
    movie.theater = json[0].showtimes[0].theatre.name;
    movie.next_showing = json[0].showtimes[0].dateTime;
    return callback(movie);
  });
}

module.exports = {
  _onEnter: function() {
    this.say('Let me check...');

    getMovies(function(movie){
      var time = new moment(movie.next_showing);
      this.say(movie.name + ' is playing at ' + time.format('LT') + ' at ' + movie.theater);
      this.transition('ready');
    }.bind(this));
  }
};


text:
from django import forms

from events.models import Event, EventImage

LEVEL_CHOICES = (('beginner', 'Beginner'),
                 ('intermediate', 'Intermediate'),
                 ('expert', 'Expert'))

class EventCreateForm(forms.ModelForm):
    name = forms.CharField(label="Name", help_text="Enter name of event",
                           widget=forms.TextInput(attrs={'placeholder': "Name"}))
    start_date = forms.DateTimeField(label="Enter start date and time",
                                    widget=forms.DateTimeInput())
    end_date = forms.DateTimeField(label="Enter end date and time",
                                  widget=forms.DateTimeInput())
    description = forms.CharField(label="Description", help_text="Description",
                                 widget=forms.Textarea(attrs={'placeholder': "Description"}))
    venue = forms.CharField(label="Venue", help_text="Venue",
                            widget=forms.TextInput(attrs={'placeholder': 'Venue'}))
    trainer_bio = forms.CharField(label="Trainer bio", help_text="Enter trainer bio")
    no_of_participants = forms.IntegerField(label="No of participants", help_text="Enter no of participants")
    level = forms.ChoiceField(choices=LEVEL_CHOICES, label="Level")
    prerequisite = forms.CharField(label="Prerequisite")
    travel = forms.CharField(label="Travel info", help_text="Enter travel data")
    accommodation = forms.CharField(label="Accomodation")
    expense = forms.FloatField(label="Expenses")
    lab_requirements = forms.CharField(label='Lab Requirements')
    icts_support = forms.CharField(label="ICTS support")

    def __init__(self, *args, **kwargs):
        super(EventCreateForm, self).__init__(*args, **kwargs)
        for field in iter(self.fields):
            self.fields[field].widget.attrs.update({'class': 'form-control'})
    class Meta:
        model = Event
        fields = ['name', 'start_date', 'end_date', 'description', 'venue', 'trainer_bio', 'no_of_participants',
                  'level', 'prerequisite', 'travel', 'accommodation', 'expense', 'lab_requirements', 'icts_support']

class EventImageForm(forms.ModelForm):
    event = forms.ModelChoiceField(queryset=Event.objects.all(), label='Event', help_text='Select event')
    image = forms.ImageField(label='images',
                             widget=forms.FileInput())

    def __init__(self, *args, **kwargs):
        super(EventImageForm, self).__init__(*args, **kwargs)
        for field in iter(self.fields):
            self.fields[field].widget.attrs.update({'class': 'form-control'})

    class Meta:
        model = EventImage
        fields = ['event', 'image']


text:
//
// DataOps.cs
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Couchbase.Lite.Internal.Serialization;
using LiteCore;
using LiteCore.Interop;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Couchbase.Lite.Internal.Doc
{
    internal static class DataOps
    {
        #region Internal Methods

        internal static T ParseTo<T>(string json)
        {
            T retVal;
            try {
                var settings = new JsonSerializerSettings {
                    DateParseHandling = DateParseHandling.DateTimeOffset,
                    TypeNameHandling = TypeNameHandling.All
                };
                retVal = JsonConvert.DeserializeObject<T>(json, settings);
            } catch {
                throw new CouchbaseLiteException(C4ErrorCode.InvalidParameter, CouchbaseLiteErrorMessage.InvalidJSON);
            }

            return retVal;
        }

        internal static bool ConvertToBoolean(object value)
        {
            switch (value) {
                case null:
                    return false;
                case string s:
                    return true; // string is IConvertible, but will throw on things other than true or false
                case IConvertible c:
                    return c.ToBoolean(CultureInfo.InvariantCulture);
                default:
                    return true;
            }
        }

        internal static DateTimeOffset ConvertToDate(object value)
        {
            switch (value) {
                case null:
                    return DateTimeOffset.MinValue;
                case DateTimeOffset dto:
                    return dto;
                case DateTime dt:
                    return new DateTimeOffset(dt.ToUniversalTime());
                case string s:
                    if (DateTimeOffset.TryParseExact(s, "o", CultureInfo.InvariantCulture, DateTimeStyles.None,
                        out var retVal)) {
                        return retVal;
                    }

                    return DateTimeOffset.MinValue;
                default:
                    return DateTimeOffset.MinValue;
            }
        }

        internal static double ConvertToDouble(object value)
        {
            // NOTE: Cannot use ConvertToDecimal because double has a greater range
            switch (value) {
                case string s: // string is IConvertible, but will throw for non-numeric strings
                    return 0.0;
                case IConvertible c:
                    return c.ToDouble(CultureInfo.InvariantCulture);
                default:
                    return 0.0;
            }
        }

        internal static float ConvertToFloat(object value)
        {
            // NOTE: Cannot use ConvertToDecimal because float has a greater range
            switch (value) {
                case string s: // string is IConvertible, but will throw for non-numeric strings
                    return 0.0f;
                case IConvertible c:
                    return c.ToSingle(CultureInfo.InvariantCulture);
                default:
                    return 0.0f;
            }
        }

        internal static int ConvertToInt(object value)
        {
            return (int)Math.Truncate(ConvertToDecimal(value));
        }

        internal static long ConvertToLong(object value)
        {
            return (long)Math.Truncate(ConvertToDecimal(value));
        }

        //makes sure it is ArrayObject / DictionaryObject instead of List and Dictionary
        internal static object ToCouchbaseObject(object value)
        {
            switch (value) {
                case null:
                    return null;
                case DateTimeOffset dto:
                    return dto.ToString("o");
                case DictionaryObject rodic when !(rodic is MutableDictionaryObject):
                    return rodic.ToMutable();
                case ArrayObject roarr when !(roarr is MutableArrayObject):
                    return roarr.ToMutable();
                case JObject jobj:
                    var jobjDict = jobj.ToObject<IDictionary<string, object>>();

                    //The dictionary may contain the json dict represents Blob. Developer should be able to retrieve Blob object using the Database.GetBlob(dict).
                    return ConvertDictionary(jobjDict);
                case JArray jarr:
                    return ConvertList(jarr.ToObject<IList>());
                case JToken jToken:
                    switch (jToken.Type) {
                        case JTokenType.Date:
                            return (DateTimeOffset) jToken;
                        default:
                            return jToken.ToObject<object>();
                    }
                case IDictionary<string, object> dict:
                    return ConvertDictionary(dict);
                case IList list:
                    return ConvertList(list);
                case byte b:
                case sbyte sb:
                case ushort us:
                case short s:
                case uint ui:
                case int i:
                case long l:
                case ulong ul:
                case string str:
                case bool bl:
                case float f:
                case double d:
                case MutableArrayObject ao:
                case MutableDictionaryObject dict:
                case Blob blob:
                    return value;
                default:
                    throw new ArgumentException(String.Format(CouchbaseLiteErrorMessage.InvalidCouchbaseObjType, value.GetType().Name,
                        "byte, sbyte, short, ushort, int, uint, long, ulong, float, double, bool, DateTimeOffset, Blob," ));
            }
        }

        internal static object ToNetObject(object value)
        {
            switch (value) {
                case null:
                    return null;
                case InMemoryDictionary inMem:
                    return inMem.ToDictionary();
                case IDictionaryObject roDic:
                    return roDic.ToDictionary();
                case IArray roarr:
                    return roarr.ToList();
                default:
                    return value;
            }
        }

        internal static unsafe bool ValueWouldChange(object newValue, MValue oldValue, MCollection container)
        {
            // As a simplification we assume that array and fict values are always different, to avoid
            // a possibly expensive comparison
            var oldType = Native.FLValue_GetType(oldValue.Value);
            if (oldType == FLValueType.Undefined || oldType == FLValueType.Dict || oldType == FLValueType.Array) {
                return true;
            }

            switch (newValue) {
                case ArrayObject arr:
                case DictionaryObject dict:
                    return true;
                default:
                    var oldVal = oldValue.AsObject(container);
                    return !newValue?.Equals(oldVal) ?? oldVal != null;
            }
        }

        #endregion

        #region Private Methods

        private static MutableDictionaryObject ConvertDictionary(IDictionary<string, object> dictionary)
        {
            var subdocument = new MutableDictionaryObject();
            subdocument.SetData(dictionary);
            return subdocument;
        }

        private static MutableArrayObject ConvertList(IList list)
        {
            var array = new MutableArrayObject();
            array.SetData(list);
            return array;
        }

        private static decimal ConvertToDecimal(object value)
        {
            switch (value) {
                case string s: // string is IConvertible, but will throw for non-numeric strings
                    return 0;
                case IConvertible c:
                    return c.ToDecimal(CultureInfo.InvariantCulture);
                default:
                    return 0;
            }
        }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (C) 2014 the original author or authors.
~
~ 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>
    <parent>
        <groupId>org.apache.river</groupId>
        <artifactId>reggie</artifactId>
        <version>3.0-SNAPSHOT</version>
    </parent>

	<dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>${project.artifactId}</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

</project>


text:
<?php
namespace Phalcon\Mvc
{

    /**
     * Phalcon\Mvc\Collection
     *
     * This component implements a high level abstraction for NoSQL databases which
     * works with documents
     */
    abstract class Collection implements \Phalcon\Mvc\CollectionInterface, \Phalcon\Di\InjectionAwareInterface, \Serializable
    {

        const OP_NONE = 0;

        const OP_CREATE = 1;

        const OP_UPDATE = 2;

        const OP_DELETE = 3;

        public $_id;

        protected $_dependencyInjector;

        protected $_modelsManager;

        protected $_source;

        protected $_operationMade;

        protected $_connection;

        protected $_errorMessages;

        protected static $_reserved;

        protected static $_disableEvents;

        /**
         * \Phalcon\Mvc\Model constructor
         *
         * @param
         *            \Phalcon\DiInterface dependencyInjector
         * @param
         *            \Phalcon\Mvc\Collection\ManagerInterface modelsManager
         */
        final public function __construct(\Phalcon\DiInterface $dependencyInjector = null, \Phalcon\Mvc\Collection\ManagerInterface $modelsManager = null)
        {}

        /**
         * Sets a value for the _id property, creates a MongoId object if needed
         *
         * @param
         *            mixed id
         */
        public function setId($id)
        {}

        /**
         * Returns the value of the _id property
         *
         * @return \MongoId
         */
        public function getId()
        {}

        /**
         * Sets the dependency injection container
         *
         * @param
         *            \Phalcon\DiInterface dependencyInjector
         */
        public function setDI(\Phalcon\DiInterface $dependencyInjector)
        {}

        /**
         * Returns the dependency injection container
         *
         * @return \Phalcon\DiInterface
         */
        public function getDI()
        {}

        /**
         * Sets a custom events manager
         *
         * @param
         *            \Phalcon\Events\ManagerInterface eventsManager
         */
        protected function setEventsManager(\Phalcon\Mvc\Collection\ManagerInterface $eventsManager)
        {}

        /**
         * Returns the custom events manager
         *
         * @return \Phalcon\Events\ManagerInterface
         */
        protected function getEventsManager()
        {}

        /**
         * Returns the models manager related to the entity instance
         *
         * @return \Phalcon\Mvc\Model\ManagerInterface
         */
        public function getModelsManager()
        {}

        /**
         * Returns an array with reserved properties that cannot be part of the insert/update
         *
         * @return array
         */
        public function getReservedAttributes()
        {}

        /**
         * Sets if a model must use implicit objects ids
         *
         * @param
         *            boolean useImplicitObjectIds
         */
        protected function useImplicitObjectIds($useImplicitObjectIds)
        {}

        /**
         * Sets collection name which model should be mapped
         *
         * @param
         *            string source
         * @return \Phalcon\Mvc\Collection
         */
        protected function setSource($source)
        {}

        /**
         * Returns collection name mapped in the model
         *
         * @return string
         */
        public function getSource()
        {}

        /**
         * Sets the DependencyInjection connection service name
         *
         * @param
         *            string connectionService
         * @return \Phalcon\Mvc\Model
         */
        public function setConnectionService($connectionService)
        {}

        /**
         * Returns DependencyInjection connection service
         *
         * @return string
         */
        public function getConnectionService()
        {}

        /**
         * Retrieves a database connection
         *
         * @return \MongoDb
         */
        public function getConnection()
        {}

        /**
         * Reads an attribute value by its name
         *
         *
         * echo robot->readAttribute('name');
         *
         *
         * @param
         *            string attribute
         * @return mixed
         */
        public function readAttribute($attribute)
        {}

        /**
         * Writes an attribute value by its name
         *
         *
         * robot->writeAttribute('name', 'Rosey');
         *
         *
         * @param
         *            string attribute
         * @param
         *            mixed value
         */
        public function writeAttribute($attribute, $value)
        {}

        /**
         * Returns a cloned collection
         *
         * @param
         *            \Phalcon\Mvc\Collection collection
         * @param
         *            array document
         * @return \Phalcon\Mvc\Collection
         */
        public static function cloneResult(\Phalcon\Mvc\CollectionInterface $collection, $document)
        {}

        /**
         * Returns a collection resultset
         *
         * @param
         *            array params
         * @param
         *            \Phalcon\Mvc\Collection collection
         * @param
         *            \MongoDb connection
         * @param
         *            boolean unique
         * @return array
         */
        protected static function _getResultset($params, \Phalcon\Mvc\CollectionInterface $collection, $connection, $unique)
        {}

        /**
         * Perform a count over a resultset
         *
         * @param
         *            array params
         * @param
         *            \Phalcon\Mvc\Collection collection
         * @param
         *            \MongoDb connection
         * @return int
         */
        protected static function _getGroupResultset($params, \Phalcon\Mvc\Collection $collection, $connection)
        {}

        /**
         * Executes internal hooks before save a document
         *
         * @param
         *            \Phalcon\DiInterface dependencyInjector
         * @param
         *            boolean disableEvents
         * @param
         *            boolean exists
         * @return boolean
         */
        final protected function _preSave($dependencyInjector, $disableEvents, $exists)
        {}

        /**
         * Executes internal events after save a document
         *
         * @param
         *            boolean disableEvents
         * @param
         *            boolean success
         * @param
         *            boolean exists
         * @return boolean
         */
        final protected function _postSave($disableEvents, $success, $exists)
        {}

        /**
         * Executes validators on every validation call
         *
         *
         * use \Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn;
         *
         * class Subscriptors extends \Phalcon\Mvc\Collection
         * {
         *
         * public function validation()
         * {
         * this->validate(new ExclusionIn(array(
         * 'field' => 'status',
         * 'domain' => array('A', 'I')
         * )));
         * if (this->validationHasFailed() == true) {
         * return false;
         * }
         * }
         *
         * }
         *
         *
         * @param
         *            object validator
         */
        protected function validate($validator)
        {}

        /**
         * Check whether validation process has generated any messages
         *
         *
         * use \Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn;
         *
         * class Subscriptors extends \Phalcon\Mvc\Collection
         * {
         *
         * public function validation()
         * {
         * this->validate(new ExclusionIn(array(
         * 'field' => 'status',
         * 'domain' => array('A', 'I')
         * )));
         * if (this->validationHasFailed() == true) {
         * return false;
         * }
         * }
         *
         * }
         *
         *
         * @return boolean
         */
        public function validationHasFailed()
        {}

        /**
         * Fires an internal event
         *
         * @param
         *            string eventName
         * @return boolean
         */
        public function fireEvent($eventName)
        {}

        /**
         * Fires an internal event that cancels the operation
         *
         * @param
         *            string eventName
         * @return boolean
         */
        public function fireEventCancel($eventName)
        {}

        /**
         * Cancel the current operation
         *
         * @return boolean
         */
        protected function _cancelOperation($disableEvents)
        {}

        /**
         * Checks if the document exists in the collection
         *
         * @param
         *            \MongoCollection collection
         * @return boolean
         */
        protected function _exists($collection)
        {}

        /**
         * Returns all the validation messages
         *
         *
         * robot = new Robots();
         * robot->type = 'mechanical';
         * robot->name = 'Astro Boy';
         * robot->year = 1952;
         * if (robot->save() == false) {
         * echo "Umh, We can't store robots right now ";
         * foreach (robot->getMessages() as message) {
         * echo message;
         * }
         * } else {
         * echo "Great, a new robot was saved successfully!";
         * }
         *
         *
         * @return \Phalcon\Mvc\Model\MessageInterface[]
         */
        public function getMessages()
        {}

        /**
         * Appends a customized message on the validation process
         *
         *
         * use \Phalcon\Mvc\Model\Message as Message;
         *
         * class Robots extends \Phalcon\Mvc\Model
         * {
         *
         * public function beforeSave()
         * {
         * if (this->name == 'Peter') {
         * message = new Message("Sorry, but a robot cannot be named Peter");
         * this->appendMessage(message);
         * }
         * }
         * }
         *
         *
         * @param
         *            \Phalcon\Mvc\Model\MessageInterface message
         */
        public function appendMessage(\Phalcon\Mvc\Model\MessageInterface $message)
        {}

        /**
         * Creates/Updates a collection based on the values in the atributes
         *
         * @return boolean
         */
        public function save()
        {}

        /**
         * Find a document by its id (_id)
         *
         * @param
         *            string|\MongoId id
         * @return \Phalcon\Mvc\Collection
         */
        public static function findById($id)
        {}

        /**
         * Allows to query the first record that match the specified conditions
         *
         *
         *
         * //What's the first robot in the robots table?
         * robot = Robots::findFirst();
         * echo "The robot name is ", robot->name, "\n";
         *
         * //What's the first mechanical robot in robots table?
         * robot = Robots::findFirst(array(
         * array("type" => "mechanical")
         * ));
         * echo "The first mechanical robot name is ", robot->name, "\n";
         *
         * //Get first virtual robot ordered by name
         * robot = Robots::findFirst(array(
         * array("type" => "mechanical"),
         * "order" => array("name" => 1)
         * ));
         * echo "The first virtual robot name is ", robot->name, "\n";
         *
         *
         *
         * @param
         *            array parameters
         * @return array
         */
        public static function findFirst($parameters = null)
        {}

        /**
         * Allows to query a set of records that match the specified conditions
         *
         *
         *
         * //How many robots are there?
         * robots = Robots::find();
         * echo "There are ", count(robots), "\n";
         *
         * //How many mechanical robots are there?
         * robots = Robots::find(array(
         * array("type" => "mechanical")
         * ));
         * echo "There are ", count(robots), "\n";
         *
         * //Get and print virtual robots ordered by name
         * robots = Robots::findFirst(array(
         * array("type" => "virtual"),
         * "order" => array("name" => 1)
         * ));
         * foreach (robots as robot) {
         * echo robot->name, "\n";
         * }
         *
         * //Get first 100 virtual robots ordered by name
         * robots = Robots::find(array(
         * array("type" => "virtual"),
         * "order" => array("name" => 1),
         * "limit" => 100
         * ));
         * foreach (robots as robot) {
         * echo robot->name, "\n";
         * }
         *
         *
         * @param
         *            array parameters
         * @return array
         */
        public static function find($parameters = null)
        {}

        /**
         * Perform a count over a collection
         *
         *
         * echo 'There are ', Robots::count(), ' robots';
         *
         *
         * @param
         *            array parameters
         * @return array
         */
        public static function count($parameters = null)
        {}

        /**
         * Perform an aggregation using the Mongo aggregation framework
         *
         *
         * @param
         *            array parameters
         * @return array
         */
        public static function aggregate($parameters)
        {}

        /**
         * Allows to perform a summatory group for a column in the collection
         *
         * @param
         *            string field
         * @param
         *            array conditions
         * @param
         *            string finalize
         * @return array
         */
        public static function summatory($field, $conditions = null, $finalize = null)
        {}

        /**
         * Deletes a model instance.
         * Returning true on success or false otherwise.
         *
         *
         *
         * robot = Robots::findFirst();
         * robot->delete();
         *
         * foreach (Robots::find() as robot) {
         * robot->delete();
         * }
         *
         *
         * @return boolean
         */
        public function delete()
        {}

        /**
         * Returns the instance as an array representation
         *
         *
         * print_r(robot->to[]);
         *
         *
         * @return array
         */
        public function toArray()
        {}

        /**
         * Serializes the object ignoring connections or protected properties
         *
         * @return string
         */
        public function serialize()
        {}

        /**
         * Unserializes the object from a serialized string
         *
         * @param
         *            string data
         */
        public function unserialize($data)
        {}
    }
}


text:
module.exports.publisher = {
  //control activeness of publisher
  //its active by default
  active: true,

  // default key prefix for kue in
  // redis server
  prefix: 'q',

  //default redis configuration
  redis: {
      //default redis server port
      port: 6379,
      //default redis server host
      host: 'redis'
  },
  //number of milliseconds
  //to wait
  //before shutdown publisher
  shutdownDelay: 200,

  //job tracker ui port
  ui: {
      port: 3000,
      title: 'Job Tracker'
  }
}


text:
namespace mojo {

namespace system {
namespace internal {

bool ShutdownCheckNoLeaks(Core* core_impl) {
  // No point in taking the lock.
  const HandleTable::HandleToEntryMap& handle_to_entry_map =
      core_impl->handle_table_.handle_to_entry_map_;

  if (handle_to_entry_map.empty())
    return true;

  for (HandleTable::HandleToEntryMap::const_iterator it =
           handle_to_entry_map.begin();
       it != handle_to_entry_map.end();
       ++it) {
    LOG(ERROR) << "Mojo embedder shutdown: Leaking handle " << (*it).first;
  }
  return false;
}

}  // namespace internal
}  // namespace system

namespace embedder {
namespace test {

void InitWithSimplePlatformSupport() {
  Init(scoped_ptr<PlatformSupport>(new SimplePlatformSupport()));
}

bool Shutdown() {
  system::Core* core = system::entrypoints::GetCore();
  CHECK(core);
  system::entrypoints::SetCore(nullptr);

  bool rv = system::internal::ShutdownCheckNoLeaks(core);
  delete core;
  return rv;
}

}  // namespace test
}  // namespace embedder

}  // namespace mojo


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>Qt 4.3: List of All Members for QGLPixelBuffer</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />

  	Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

List of All Members for QGLPixelBuffer

This is the complete list of members for QGLPixelBuffer, including inherited members.

enum PaintDeviceMetric

QGLPixelBuffer ( const QSize &, const QGLFormat &, QGLWidget * )

QGLPixelBuffer ( int, int, const QGLFormat &, QGLWidget * )

~QGLPixelBuffer ()

bindTexture ( const QImage &, GLenum ) : GLuint

bindTexture ( const QPixmap &, GLenum ) : GLuint

bindTexture ( const QString & ) : GLuint

bindToDynamicTexture ( GLuint ) : bool

deleteTexture ( GLuint )

depth () const : int

doneCurrent () : bool

format () const : QGLFormat

generateDynamicTexture () const : GLuint

handle () const : Qt::HANDLE

hasOpenGLPbuffers () : bool

height () const : int

heightMM () const : int

isValid () const : bool

logicalDpiX () const : int

logicalDpiY () const : int

makeCurrent () : bool

metric ( PaintDeviceMetric ) const : int

numColors () const : int

paintEngine () const : QPaintEngine *

paintingActive () const : bool

physicalDpiX () const : int

physicalDpiY () const : int

releaseFromDynamicTexture ()

size () const : QSize

toImage () const : QImage

updateDynamicTexture ( GLuint ) const

width () const : int

widthMM () const : int

<address>

Copyright © 2008 Trolltech
Trademarks

Qt 4.3.5

</address>


text:
require 'nexmo/voice'
require 'webmock/rspec'


text:
using System;
using Result = com.google.zxing.Result;
namespace com.google.zxing.client.result
{

	/// <summary> Tries to parse results that are a URI of some kind.
	///
	/// </summary>
	/// <author>  Sean Owen
	/// </author>
	/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
	/// </author>
	sealed class URIResultParser:ResultParser
	{

		private URIResultParser()
		{
		}

		public static URIParsedResult parse(Result result)
		{
			System.String rawText = result.Text;
			// We specifically handle the odd "URL" scheme here for simplicity
			if (rawText != null && rawText.StartsWith("URL:"))
			{
				rawText = rawText.Substring(4);
			}
			if (!isBasicallyValidURI(rawText))
			{
				return null;
			}
			return new URIParsedResult(rawText, null);
		}

		/// <summary> Determines whether a string is not obviously not a URI. This implements crude checks; this class does not
		/// intend to strictly check URIs as its only function is to represent what is in a barcode, but, it does
		/// need to know when a string is obviously not a URI.
		/// </summary>
		internal static bool isBasicallyValidURI(System.String uri)
		{
			if (uri == null || uri.IndexOf(' ') >= 0 || uri.IndexOf('\n') >= 0)
			{
				return false;
			}
			// Look for period in a domain but followed by at least a two-char TLD
			// Forget strings that don't have a valid-looking protocol
			int period = uri.IndexOf('.');
			if (period >= uri.Length - 2)
			{
				return false;
			}
			int colon = uri.IndexOf(':');
			if (period < 0 && colon < 0)
			{
				return false;
			}
			if (colon >= 0)
			{
				if (period < 0 || period > colon)
				{
					// colon ends the protocol
					for (int i = 0; i < colon; i++)
					{
						char c = uri[i];
						if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z'))
						{
							return false;
						}
					}
				}
				else
				{
					// colon starts the port; crudely look for at least two numbers
					if (colon >= uri.Length - 2)
					{
						return false;
					}
					for (int i = colon + 1; i < colon + 3; i++)
					{
						char c = uri[i];
						if (c < '0' || c > '9')
						{
							return false;
						}
					}
				}
			}
			return true;
		}
	}
}


text:
angular.module('GymCompetition', ['ionic', 'ngCordova', 'GymCompetition.controllers','GymCompetition.services'])
.run(function($ionicPlatform, $rootScope, $ionicLoading, $cordovaSplashscreen, $timeout) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }

    $timeout(function(){
      $cordovaSplashscreen.hide();
    },20000);
  });

  $rootScope.$on('loading:show', function () {
    $ionicLoading.show({
      template: '<ion-spinner></ion-spinner> Loading ...'
    })
  });

  $rootScope.$on('loading:hide', function () {
    $ionicLoading.hide();
  });

  $rootScope.$on('$stateChangeStart', function () {
    console.log('Loading ...');
    $rootScope.$broadcast('loading:show');
  });

  $rootScope.$on('$stateChangeSuccess', function () {
    console.log('done');
    $rootScope.$broadcast('loading:hide');
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

  .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'templates/sidebar.html',
    controller: 'AppCtrl'
  })

  .state('app.home', {
    url: '/home',
    views: {
      'mainContent': {
        templateUrl: 'templates/home.html',
        controller: 'IndexController',
        resolve: {
          competition: ['competitionFactory', function(competitionFactory){
            return competitionFactory.getNextCompetition().get();
          }],
          club: ['clubFactory', function(clubFactory) {
            return clubFactory.getClubOfMonth().get();
          }],
          sponsor: ['sponsorFactory', function(sponsorFactory) {
            return sponsorFactory.getSponsorOfMotnh().get();
          }]
        }
      }
    }
  })

  .state('app.competitions', {
    url: '/competitions',
    views: {
      'mainContent': {
        templateUrl: 'templates/competitions.html',
        controller: 'CompetitionsController',
        resolve: {
          competitions: ['competitionFactory', function(competitionFactory){
            return competitionFactory.getCompetitions().query();
          }]
        }
      }
    }
  })

  .state('app.favorites', {
     url: '/favorites',
     views: {
       'mainContent': {
          templateUrl: 'templates/favorites.html',
          controller:'FavoritesController',
          resolve: {
            competitions: ['competitionFactory', function(competitionFactory){
              return competitionFactory.getCompetitions().query();
            }],
            favorites: ['favoriteFactory', function(favoriteFactory) {
              return favoriteFactory.getFavorites();
            }]
          }
        }
      }
    })

  .state('app.competitiondetails', {
    url: '/competitiondetails/:id',
    views: {
      'mainContent': {
        templateUrl: 'templates/competition.html',
        controller: 'CompetitionController',
        resolve: {
          competition: ['$stateParams','competitionFactory', function($stateParams, competitionFactory){
            return competitionFactory.getCompetitions().get({id: $stateParams.id});
          }]
        }
      }
    }
  })

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/home');

});


text:
layout: page
title: Malichyte Zone Music Dinner
date: 2016-05-24
author: Tiffany Yoder
tags: weekly links, java
status: published
summary: Praesent tempus sit amet ante.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 01/09/2016
  endDate: 01/10/2016
  ctyhocn: FWANOHX
  groupCode: MZMD
published: true
---
Cras laoreet urna eu orci auctor, non consectetur quam sollicitudin. Nulla non iaculis purus. Nunc tempus ligula elit, nec convallis ligula maximus ac. Vestibulum ut semper quam. Etiam cursus nunc at varius dictum. Duis neque velit, mattis sed est vitae, congue aliquet ligula. Nunc lobortis urna in facilisis pellentesque. Aliquam consectetur augue in ligula consectetur volutpat. Sed eleifend sapien vel leo lacinia accumsan. Fusce sodales urna eget dolor dignissim laoreet. Phasellus laoreet lectus dui, eu faucibus nisi mattis eu. Nullam egestas dignissim metus eget dapibus.

* Quisque at arcu pellentesque, placerat urna non, suscipit lacus
* Pellentesque finibus metus mollis lorem bibendum iaculis.

Suspendisse ac urna est. Proin lobortis, tortor nec condimentum fermentum, ligula purus porttitor arcu, quis tempor arcu elit vel leo. Curabitur fermentum, neque in consectetur venenatis, elit ante cursus neque, in varius mi est eu nunc. Donec quis urna sed libero elementum dignissim eget non magna. Integer est eros, laoreet eget quam ac, porta venenatis nisi. Quisque rhoncus, ante sit amet congue fringilla, urna leo lobortis lorem, vitae sollicitudin lacus mi et urna. Etiam non tellus vitae odio mattis consectetur. Quisque maximus sapien vitae elit imperdiet consequat. Interdum et malesuada fames ac ante ipsum primis in faucibus. Cras ut pellentesque ipsum. Pellentesque sed rutrum lorem. Quisque ac nisl a mi commodo lacinia et at justo. Pellentesque eu mauris scelerisque dolor tristique fringilla.


text:
package hudson.matrix;

import hudson.model.Item;
import hudson.util.FormValidation;

import org.jvnet.hudson.test.HudsonTestCase;
import org.jvnet.hudson.test.TestExtension;
import org.kohsuke.stapler.DataBoundConstructor;

/**
 * @author Kohsuke Kawaguchi
 */
public class MatrixConfigurationSorterTest extends HudsonTestCase {
    public void testConfigRoundtrip() throws Exception {
        MatrixProject p = createMatrixProject();
        configRoundtrip((Item)p);
        assertNull(p.getSorter());

        SorterImpl before = new SorterImpl();
        p.setSorter(before);
        p.setRunSequentially(true);
        configRoundtrip((Item)p);
        Object after = p.getSorter();
        assertNotSame(before,after);
        assertSame(before.getClass(),after.getClass());
    }

    public static class SorterImpl extends MatrixConfigurationSorter {
        @DataBoundConstructor
        public SorterImpl() {}

        @Override
        public void validate(MatrixProject p) throws FormValidation {
        }

        public int compare(MatrixConfiguration o1, MatrixConfiguration o2) {
            return o1.getDisplayName().compareTo(o2.getDisplayName());
        }

        @TestExtension
        public static class DescriptorImpl extends MatrixConfigurationSorterDescriptor {
            @Override
            public String getDisplayName() {
                return "Test Sorter";
            }
        }
    }
}


text:
#include <aws/securityhub/model/AwsIamAccessKeySessionContextAttributes.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SecurityHub
{
namespace Model
{

AwsIamAccessKeySessionContextAttributes::AwsIamAccessKeySessionContextAttributes() :
    m_mfaAuthenticated(false),
    m_mfaAuthenticatedHasBeenSet(false),
    m_creationDateHasBeenSet(false)
{
}

AwsIamAccessKeySessionContextAttributes::AwsIamAccessKeySessionContextAttributes(JsonView jsonValue) :
    m_mfaAuthenticated(false),
    m_mfaAuthenticatedHasBeenSet(false),
    m_creationDateHasBeenSet(false)
{
  *this = jsonValue;
}

AwsIamAccessKeySessionContextAttributes& AwsIamAccessKeySessionContextAttributes::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("MfaAuthenticated"))
  {
    m_mfaAuthenticated = jsonValue.GetBool("MfaAuthenticated");

    m_mfaAuthenticatedHasBeenSet = true;
  }

  if(jsonValue.ValueExists("CreationDate"))
  {
    m_creationDate = jsonValue.GetString("CreationDate");

    m_creationDateHasBeenSet = true;
  }

  return *this;
}

JsonValue AwsIamAccessKeySessionContextAttributes::Jsonize() const
{
  JsonValue payload;

  if(m_mfaAuthenticatedHasBeenSet)
  {
   payload.WithBool("MfaAuthenticated", m_mfaAuthenticated);

  }

  if(m_creationDateHasBeenSet)
  {
   payload.WithString("CreationDate", m_creationDate);

  }

  return payload;
}

} // namespace Model
} // namespace SecurityHub
} // namespace Aws


text:
<?php

namespace Gtt\Bundle\WorkflowExtensionsBundle\DependencyInjection\Compiler;

use Gtt\Bundle\WorkflowExtensionsBundle\Exception\RuntimeException;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Checks that all necessary options for scheduler are set for classes supported by corresponding workflows
 */
class CheckSubjectManipulatorConfigPass implements CompilerPassInterface
{
    /**
     * Workflow id prefix used in main workflow bundle
     */
    public const WORKFLOW_ID_PREFIX = 'workflow.';

    /**
     * Name of the method used to register workflows in registry
     */
    public const WORKFLOW_REGISTRY_ADD_WORKFLOW_METHOD_NAME = "add";

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (false === $container->hasDefinition('workflow.registry')) {
            return;
        }

        if (false === $container->hasDefinition('gtt.workflow.transition_scheduler')) {
            return;
        }

        $subjectClassesWithSubjectFromDomain = $container->getParameter('gtt.workflow.subject_classes_with_subject_from_domain');
        $workflowsWithScheduling             = $container->getParameter('gtt.workflow.workflows_with_scheduling');

        $registryDefinition = $container->getDefinition('workflow.registry');
        foreach ($registryDefinition->getMethodCalls() as [$call, $callArgs]) {
            if ($call === self::WORKFLOW_REGISTRY_ADD_WORKFLOW_METHOD_NAME) {
                if (count($callArgs) !== 2 || !$callArgs[0] instanceof Reference || !is_string($callArgs[1])) {
                    throw new RuntimeException(
                        sprintf(
                            'Workflow registry service have unsupported signature for "%s" method',
                            self::WORKFLOW_REGISTRY_ADD_WORKFLOW_METHOD_NAME
                        )
                    );
                }

                /** @var Reference $workflowReference */
                [$workflowReference, $workflowSupportedClass] = $callArgs;

                $workflowIdWithPrefix =  (string) $workflowReference;
                if (strpos($workflowIdWithPrefix, self::WORKFLOW_ID_PREFIX) !== 0) {
                    throw new RuntimeException(
                        sprintf(
                            "Workflow registry works with workflow id '%s'in unsupported format",
                            $workflowIdWithPrefix
                        )
                    );
                }

                $workflowId = substr($workflowIdWithPrefix, strlen(self::WORKFLOW_ID_PREFIX));

                if (\in_array($workflowId, $workflowsWithScheduling) &&
                    !\in_array(ltrim($workflowSupportedClass, "\\"), $subjectClassesWithSubjectFromDomain)) {
                    throw new InvalidConfigurationException(
                        sprintf(
                            'Workflow "%s" configured to use scheduler so all the supported subject classes for it'.
                            'must be configured with "subject_from_domain" option under "subject_manipulator". '.
                            'This option for "%s" class is missing.',
                            $workflowId,
                            $workflowSupportedClass
                        )
                    );
                }
            }
        }
    }
}


text:
        Card

        Level

        Media object

        Menu

        Message

        Modal

        Nav

        Pagination

        Panel

        Tabs


text:
Subject

## Synopsis

synopsis

## String conversion

string conversion

## XML conversion

XML conversion


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Travessa</tipo><logradouro>B</logradouro><bairro>Farolândia</bairro><cidade>Aracaju</cidade><uf>SE</uf><cep>49032473</cep></feed>


text:
package javasmmr.zoowsome.services.factories;

import javasmmr.zoowsome.models.animals.Animal;
import javasmmr.zoowsome.models.animals.*;

public class ReptileFactory extends SpeciesFactory {

	@Override
	public Animal getAnimal(String type) throws Exception {
		if (Constants.Animals.Reptiles.Iguana.equals(type)) {
			return new Iguana();
		} else if (Constants.Animals.Reptiles.Turtle.equals(type)) {
			return new Turtle();
		} else if (Constants.Animals.Reptiles.Viper.equals(type)) {
			return new Viper();
		} else {
			throw new Exception("Invalid animal exception!");
		}
	}

}


text:
package jade.tools.rma;

import jade.gui.AgentTree;
/**

   @author Francisco Regi, Andrea Soracchi - Universita` di Parma
   @version $Date: 2008-10-09 14:04:02 +0200 (gio, 09 ott 2008) $ $Revision: 6051 $
 */
//class SnifferAction extends FixedAction {
class SnifferAction extends ContainerAction {
  private static int progressiveNumber = 0;
  private rma myRMA;

  public SnifferAction(rma anRMA,ActionProcessor actPro) {
    super ("SnifferActionIcon","Start Sniffer",actPro);
    myRMA = anRMA;
  }

  public void doAction(AgentTree.ContainerNode node) {
  	String containerName = "";
   	if(node != null)
   	  	containerName = node.getName();

    myRMA.newAgent("sniffer"+progressiveNumber, "jade.tools.sniffer.Sniffer",new Object[0], containerName);
    progressiveNumber++;
  }

}


text:
#ifndef LIBGM_CANONICAL_GAUSSIAN_JOIN_HPP
#define LIBGM_CANONICAL_GAUSSIAN_JOIN_HPP

#include <libgm/factor/expression/canonical_gaussian_base.hpp>
#include <libgm/factor/utility/traits.hpp>
#include <libgm/functional/compose_assign.hpp>
#include <libgm/math/param/canonical_gaussian_param.hpp>
#include <libgm/range/index_range_map.hpp>

namespace libgm { namespace experimental {

  /**
   * An expression that represents a binary join of two canonical_gaussians
   * f and g. The selected dimensions of f must match the selected dimension
   * of g.
   *
   * \tparam JoinOp
   *         A binary operator that accepts two scalars or matrix expressions.
   * \tparam FDims
   *         A type that models IndexRange and denotes the left join dimensions.
   * \tparam GDims
   *         A type that models IndexRange and denotes the right join dimensions.
   * \tparam F
   *         A canonical_gaussian expression representing the left argument
   *         of the join.
   * \tparam G
   *         A canonical_gaussian expression representing the right argument
   *         of the join.
   */
  template <typename JoinOp,
            typename FDims, typename GDims, typename F, typename G>
  class canonical_gaussian_join
    : public canonical_gaussian_base<
        typename F::real_type,
        canonical_gaussian_join<JoinOp, FDims, GDims, F, G> > {

    static_assert(
      std::is_same<typename F::real_type, typename G::real_type>::value,
      "The joined expressions must have the same real type");

  public:
    // Shortcuts
    using real_type  = typename F::real_type;
    using param_type = canonical_gaussian_param<real_type>;

    //! Constructs a canonical_gaussian_join
    canonical_gaussian_join(JoinOp join_op, FDims fdims, GDims gdims,
                            const F& f, const G& g)
      : join_op_(join_op), fdims_(fdims), gdims_(gdims), f_(f), g_(g) {
      assert(fdims_.size() == gdims_.size());
      arity_ = f_.arity() + g_.arity() - fdims_.size();
    }

    std::size_t arity() const {
      return arity_;
    }

    bool alias(const param_type& param) const {
      return f_.alias(param) || g_.alias(param);
    }

    void eval_to(param_type& result) const {
      result.zero(arity());
      transform_inplace(assign<>(), result);
    }

    template <typename UpdateOp>
    void transform_inplace(UpdateOp update_op, param_type& result) const {
      f_.join_inplace(update_op, front(f_.arity()), result);
      g_.join_inplace(compose_assign(update_op, join_op_),
                      map_right(fdims_, gdims_, f_.arity(), g_.arity()),
                      result);
    }

  private:
    JoinOp join_op_;
    FDims fdims_;
    GDims gdims_;
    add_const_reference_if_factor_t<F> f_;
    add_const_reference_if_factor_t<G> g_;
    std::size_t arity_;

  }; // class canonical_gaussian_join

} } // namespace libgm::experimental

#endif


text: SET @@net_read_timeout = 1000000;


text:
package fr.openwide.core.wicket.more.markup.repeater.table.column;

import java.util.List;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;

import com.google.common.collect.Lists;

import fr.openwide.core.jpa.more.business.sort.ISort;
import fr.openwide.core.wicket.behavior.ClassAttributeAppender;
import fr.openwide.core.wicket.markup.html.basic.CoreLabel;
import fr.openwide.core.wicket.markup.html.panel.InvisiblePanel;
import fr.openwide.core.wicket.more.link.descriptor.AbstractDynamicBookmarkableLink;
import fr.openwide.core.wicket.more.link.descriptor.generator.ILinkGenerator;
import fr.openwide.core.wicket.more.link.descriptor.mapper.ILinkDescriptorMapper;
import fr.openwide.core.wicket.more.rendering.Renderer;

public abstract class CoreLabelColumn<T, S extends ISort<?>> extends AbstractCoreColumn<T, S> {

	private static final long serialVersionUID = -8588236421923900497L;

	private boolean multiline = false;

	private boolean showPlaceholder = false;

	private IModel<String> placeholderModel = null;

	private Renderer<? super T> tooltipRenderer;

	private ILinkDescriptorMapper<? extends ILinkGenerator, ? super IModel<T>> linkGeneratorMapper;

	private ILinkDescriptorMapper<? extends ILinkGenerator, ? super IModel<T>> sideLinkGeneratorMapper;

	private boolean hideIfInvalid = false;

	private List<Behavior> linkBehaviors = Lists.newArrayList();

	public CoreLabelColumn(IModel<String> displayModel) {
		super(displayModel);
	}

	@Override
	public void detach() {
		super.detach();
		if (placeholderModel != null) {
			placeholderModel.detach();
		}
		if (linkGeneratorMapper != null) {
			linkGeneratorMapper.detach();
		}
		if (sideLinkGeneratorMapper != null) {
			sideLinkGeneratorMapper.detach();
		}
	}

	@Override
	public void populateItem(Item<ICellPopulator<T>> cellItem, String componentId, IModel<T> rowModel) {
		cellItem.add(
				new CoreLabelLinkColumnPanel<T, S>(componentId, rowModel) {
					private static final long serialVersionUID = 1L;
					@Override
					public CoreLabel getLabel(String wicketId, IModel<T> rowModel) {
						return decorate(newLabel(wicketId, rowModel), rowModel);
					}
					@Override
					public MarkupContainer getLink(String wicketId, IModel<T> rowModel) {
						if (linkGeneratorMapper != null) {
							return decorate(linkGeneratorMapper.map(rowModel).link(wicketId));
						}
						return new InvisiblePanel(wicketId);
					}
					@Override
					public MarkupContainer getSideLink(String wicketId, IModel<T> rowModel) {
						if (sideLinkGeneratorMapper != null) {
							return decorate(sideLinkGeneratorMapper.map(rowModel).link(wicketId))
									.add(new WebMarkupContainer("sideLinkIcon").add(new ClassAttributeAppender("fa fa-share-square-o")));
						}
						return new InvisiblePanel(wicketId);
					}
				}.setRenderBodyOnly(true) // Delete useless <div> under <td>. If it could be usefull, give the ability to configure it
		);
	}

	protected abstract CoreLabel newLabel(String componentId, IModel<T> rowModel);

	private CoreLabel decorate(CoreLabel label, IModel<T> rowModel) {
		if (multiline) {
			label.multiline();
		}
		if (showPlaceholder) {
			if (placeholderModel != null) {
				label.showPlaceholder(placeholderModel);
			} else {
				label.showPlaceholder();
			}
		}
		if (tooltipRenderer != null) {
			label.add(new AttributeModifier("title", tooltipRenderer.asModel(rowModel)));
		}
		return label;
	}

	private AbstractDynamicBookmarkableLink decorate(AbstractDynamicBookmarkableLink link) {
		if (hideIfInvalid) {
			link.hideIfInvalid();
		}
		for (Behavior linkBehavior : linkBehaviors) {
			link.add(linkBehavior);
		}
		return link;
	}

	public CoreLabelColumn<T, S> multiline() {
		this.multiline = true;
		return this;
	}

	public CoreLabelColumn<T, S> showPlaceholder() {
		this.showPlaceholder = true;
		return this;
	}

	public IModel<String> getPlaceholderModel() {
		return placeholderModel;
	}

	public CoreLabelColumn<T, S> showPlaceholder(IModel<String> placeholderModel) {
		this.showPlaceholder = true;
		this.placeholderModel = placeholderModel;
		return this;
	}

	public Renderer<? super T> getTooltipRenderer() {
		return tooltipRenderer;
	}

	public void setTooltipRenderer(Renderer<? super T> tooltipRenderer) {
		this.tooltipRenderer = tooltipRenderer;
	}

	public ILinkDescriptorMapper<? extends ILinkGenerator, ? super IModel<T>> getLinkGeneratorMapper() {
		return linkGeneratorMapper;
	}

	public CoreLabelColumn<T, S> setLinkGeneratorMapper(ILinkDescriptorMapper<? extends ILinkGenerator, ? super IModel<T>> linkGeneratorFactory) {
		if (sideLinkGeneratorMapper != null) {
			throw new IllegalStateException("link and side link cannot be both set.");
		}
		this.linkGeneratorMapper = linkGeneratorFactory;
		return this;
	}

	public ILinkDescriptorMapper<? extends ILinkGenerator, ? super IModel<T>> getSideLinkGeneratorMapper() {
		return sideLinkGeneratorMapper;
	}

	public CoreLabelColumn<T, S> setSideLinkGeneratorMapper(ILinkDescriptorMapper<? extends ILinkGenerator, ? super IModel<T>> sideLinkGeneratorFactory) {
		if (linkGeneratorMapper != null) {
			throw new IllegalStateException("link and side link cannot be both set.");
		}
		this.sideLinkGeneratorMapper = sideLinkGeneratorFactory;
		return this;
	}

	public CoreLabelColumn<T, S> hideIfInvalid() {
		this.hideIfInvalid = true;
		return this;
	}

	public void addLinkBehavior(Behavior behavior) {
		linkBehaviors.add(behavior);
	}

}


text:
// This file was generated by Mendix Modeler.
//
// WARNING: Only the following code will be retained when actions are regenerated:
// - the import list
// - the code between BEGIN USER CODE and END USER CODE
// - the code between BEGIN EXTRA CODE and END EXTRA CODE
// Other code you write will be lost the next time you deploy the project.
// Special characters, e.g., é, ö, à, etc. are supported in comments.

package boxconnector.actions;

import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.webui.CustomJavaAction;
import com.mendix.systemwideinterfaces.core.IMendixObject;
import static boxconnector.proxies.microflows.Microflows.copyFolderImpl;

/**
 * Used to create a copy of a folder in another folder.
 * The original version of the folder will not be altered.
 *
 *
 * Required:
 * SrcBoxFolder: The source folder to copy.
 * The _id attribute is required.
 *
 * DestBoxFolder: The destination folder where to copy.
 * The _id attribute is required.
 *
 * Optional
 * NewName: The new name of the folder copy.
 */
public class CopyFolder extends CustomJavaAction<IMendixObject>
{
	private IMendixObject __accessToken;
	private boxconnector.proxies.AccessToken accessToken;
	private IMendixObject __srcBoxFolder;
	private boxconnector.proxies.BoxFolder srcBoxFolder;
	private IMendixObject __destBoxFolder;
	private boxconnector.proxies.BoxFolder destBoxFolder;
	private java.lang.String newName;
	private IMendixObject __asUser;
	private boxconnector.proxies.BoxUser asUser;

	public CopyFolder(IContext context, IMendixObject accessToken, IMendixObject srcBoxFolder, IMendixObject destBoxFolder, java.lang.String newName, IMendixObject asUser)
	{
		super(context);
		this.__accessToken = accessToken;
		this.__srcBoxFolder = srcBoxFolder;
		this.__destBoxFolder = destBoxFolder;
		this.newName = newName;
		this.__asUser = asUser;
	}

	@Override
	public IMendixObject executeAction() throws Exception
	{
		this.accessToken = __accessToken == null ? null : boxconnector.proxies.AccessToken.initialize(getContext(), __accessToken);

		this.srcBoxFolder = __srcBoxFolder == null ? null : boxconnector.proxies.BoxFolder.initialize(getContext(), __srcBoxFolder);

		this.destBoxFolder = __destBoxFolder == null ? null : boxconnector.proxies.BoxFolder.initialize(getContext(), __destBoxFolder);

		this.asUser = __asUser == null ? null : boxconnector.proxies.BoxUser.initialize(getContext(), __asUser);

		// BEGIN USER CODE
		boxconnector.proxies.BoxFolder boxFolder = copyFolderImpl(getContext(), this.srcBoxFolder, this.destBoxFolder, this.newName, this.accessToken, this.asUser);

		if(boxFolder != null) {
			return boxFolder.getMendixObject();
		} else {
			return null;
		}
		// END USER CODE
	}

	/**
	 * Returns a string representation of this action
	 */
	@Override
	public java.lang.String toString()
	{
		return "CopyFolder";
	}

	// BEGIN EXTRA CODE
	// END EXTRA CODE
}