text:
package org.apache.commons.configuration2.beanutils;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.ex.ConfigurationRuntimeException;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;

/**
 * Test class for BeanHelper.
 *
 * @since 1.3
 * @author <a
 * href="http://commons.apache.org/configuration/team-list.html">Commons
 * Configuration team</a>
 * @version $Id$
 */
public class TestBeanHelper
{
    /** Constant for the test value of the string property. */
    private static final String TEST_STRING = "testString";

    /** Constant for the test value of the numeric property. */
    private static final int TEST_INT = 42;

    /** Constant for the name of the test bean factory. */
    private static final String TEST_FACTORY = "testFactory";

    /** The test bean helper instance. */
    private BeanHelper helper;

    @Before
    public void setUp() throws Exception
    {
        helper = new BeanHelper(new TestBeanFactory());
    }

    /**
     * Tests whether the correct default bean factory is set.
     */
    @Test
    public void testDefaultBeanFactory()
    {
        helper = new BeanHelper();
        assertSame("Wrong default bean factory", DefaultBeanFactory.INSTANCE,
                helper.getDefaultBeanFactory());
    }

    /**
     * Tests whether a specific default bean factory can be set when
     * constructing an instance.
     */
    @Test
    public void testInitWithBeanFactory()
    {
        BeanFactory factory = EasyMock.createMock(BeanFactory.class);
        EasyMock.replay(factory);
        helper = new BeanHelper(factory);
        assertSame("Wrong default bean factory", factory,
                helper.getDefaultBeanFactory());
    }

    /**
     * Tests the default instance of BeanHelper.
     */
    @Test
    public void testDefaultInstance()
    {
        assertSame("Wrong factory for default instance",
                DefaultBeanFactory.INSTANCE,
                BeanHelper.INSTANCE.getDefaultBeanFactory());
    }

    /**
     * Tests that a newly created instance does not have any bean factories
     * registered.
     */
    @Test
    public void testRegisteredFactoriesEmptyForNewInstance()
    {
        assertTrue("List of registered factories is not empty", helper
                .registeredFactoryNames().isEmpty());
    }

    /**
     * Tests registering a new bean factory.
     */
    @Test
    public void testRegisterBeanFactory()
    {
        helper.registerBeanFactory(TEST_FACTORY, new TestBeanFactory());
        assertEquals("Wrong number of registered factories", 1, helper
                .registeredFactoryNames().size());
        assertTrue("Test factory is not contained", helper
                .registeredFactoryNames().contains(TEST_FACTORY));
    }

    /**
     * Tries to register a null factory. This should cause an exception.
     */
    @Test(expected = IllegalArgumentException.class)
    public void testRegisterBeanFactoryNull()
    {
        helper.registerBeanFactory(TEST_FACTORY, null);
    }

    /**
     * Tries to register a bean factory with a null name. This should cause an
     * exception.
     */
    @Test(expected = IllegalArgumentException.class)
    public void testRegisterBeanFactoryNullName()
    {
        helper.registerBeanFactory(null, new TestBeanFactory());
    }

    /**
     * Tests to deregister a bean factory.
     */
    @Test
    public void testDeregisterBeanFactory()
    {
        BeanFactory factory = new TestBeanFactory();
        helper.registerBeanFactory(TEST_FACTORY, factory);
        assertSame("Could not deregister factory", factory, helper
                .deregisterBeanFactory(TEST_FACTORY));
        assertTrue("List of factories is not empty", helper
                .registeredFactoryNames().isEmpty());
    }

    /**
     * Tests deregisterBeanFactory() for a non-existing factory name.
     */
    @Test
    public void testDeregisterBeanFactoryNonExisting()
    {
        assertNull("deregistering non existing factory",
                helper.deregisterBeanFactory(TEST_FACTORY));
    }

    /**
     * Tests deregisterBeanFactory() for a null factory name.
     */
    @Test
    public void testDeregisterBeanFactoryNull() {
        assertNull("deregistering null factory",
                helper.deregisterBeanFactory(null));
    }

    /**
     * Tests initializing a bean.
     */
    @Test
    public void testInitBean()
    {
        BeanDeclarationTestImpl data = setUpBeanDeclaration();
        BeanCreationTestBean bean = new BeanCreationTestBean();
        helper.initBean(bean, data);
        checkBean(bean);
    }

    /**
     * Tests initializing a bean when the bean declaration does not contain any
     * data.
     */
    @Test
    public void testInitBeanWithNoData()
    {
        BeanDeclarationTestImpl data = new BeanDeclarationTestImpl();
        BeanCreationTestBean bean = new BeanCreationTestBean();
        helper.initBean(bean, data);
        assertNull("Wrong string property", bean.getStringValue());
        assertEquals("Wrong int property", 0, bean.getIntValue());
        assertNull("Buddy was set", bean.getBuddy());
    }

    /**
     * Tries to initialize a bean with a bean declaration that contains an
     * invalid property value. This should cause an exception.
     */
    @Test(expected = ConfigurationRuntimeException.class)
    public void testInitBeanWithInvalidProperty()
    {
        BeanDeclarationTestImpl data = setUpBeanDeclaration();
        data.getBeanProperties().put("nonExistingProperty", Boolean.TRUE);
        helper.initBean(new BeanCreationTestBean(), data);
    }

    /**
     * Tests creating a bean. All necessary information is stored in the bean
     * declaration.
     */
    @Test
    public void testCreateBean()
    {
        TestBeanFactory factory = new TestBeanFactory();
        helper.registerBeanFactory(TEST_FACTORY, factory);
        BeanDeclarationTestImpl data = setUpBeanDeclaration();
        data.setBeanFactoryName(TEST_FACTORY);
        data.setBeanClassName(BeanCreationTestBean.class.getName());
        checkBean((BeanCreationTestBean) helper.createBean(data, null));
        assertNull("A parameter was passed", factory.parameter);
        assertEquals("Factory not called", 1, factory.getCreateBeanCount());
    }

    /**
     * Tests whether a bean with a property of type collection can be created.
     */
    @Test
    public void testCreateBeanWithListChildBean()
    {
        TestBeanFactory factory = new TestBeanFactory();
        helper.registerBeanFactory(TEST_FACTORY, factory);
        BeanDeclarationTestImpl data = setUpBeanDeclarationWithListChild();
        data.setBeanFactoryName(TEST_FACTORY);
        data.setBeanClassName(BeanCreationTestBeanWithListChild.class.getName());
        checkBean((BeanCreationTestBeanWithListChild) helper.createBean(data, null));
        assertNull("A parameter was passed", factory.parameter);
        assertEquals("Factory not called", 1, factory.getCreateBeanCount());
    }

    /**
     * Tests creating a bean when no bean declaration is provided. This should
     * cause an exception.
     */
    @Test(expected = IllegalArgumentException.class)
    public void testCreateBeanWithNullDeclaration()
    {
        helper.createBean(null);
    }

    /**
     * Tests creating a bean. The bean's class is specified as the default class
     * argument.
     */
    @Test
    public void testCreateBeanWithDefaultClass()
    {
        helper.registerBeanFactory(TEST_FACTORY, new TestBeanFactory());
        BeanDeclarationTestImpl data = setUpBeanDeclaration();
        data.setBeanFactoryName(TEST_FACTORY);
        checkBean((BeanCreationTestBean) helper.createBean(data, BeanCreationTestBean.class));
    }

    /**
     * Tests creating a bean when the bean's class is specified as the default
     * class of the bean factory.
     */
    @Test
    public void testCreateBeanWithFactoryDefaultClass()
    {
        TestBeanFactory factory = new TestBeanFactory();
        factory.supportsDefaultClass = true;
        helper.registerBeanFactory(TEST_FACTORY, factory);
        BeanDeclarationTestImpl data = setUpBeanDeclaration();
        data.setBeanFactoryName(TEST_FACTORY);
        checkBean((BeanCreationTestBean) helper.createBean(data, null));
        assertEquals("Factory not called", 1, factory.getCreateBeanCount());
    }

    /**
     * Tries to create a bean if no class is provided. This should cause an
     * exception.
     */
    @Test(expected = ConfigurationRuntimeException.class)
    public void testCreateBeanWithNoClass()
    {
        helper.registerBeanFactory(TEST_FACTORY, new TestBeanFactory());
        BeanDeclarationTestImpl data = setUpBeanDeclaration();
        data.setBeanFactoryName(TEST_FACTORY);
        helper.createBean(data, null);
    }

    /**
     * Tries to create a bean with a non existing class. This should cause an
     * exception.
     */
    @Test(expected = ConfigurationRuntimeException.class)
    public void testCreateBeanWithInvalidClass()
    {
        helper.registerBeanFactory(TEST_FACTORY, new TestBeanFactory());
        BeanDeclarationTestImpl data = setUpBeanDeclaration();
        data.setBeanFactoryName(TEST_FACTORY);
        data.setBeanClassName("non.existing.ClassName");
        helper.createBean(data, null);
    }

    /**
     * Tests creating a bean using the default bean factory.
     */
    @Test
    public void testCreateBeanWithDefaultFactory()
    {
        BeanDeclarationTestImpl data = setUpBeanDeclaration();
        data.setBeanClassName(BeanCreationTestBean.class.getName());
        checkBean((BeanCreationTestBean) helper.createBean(data, null));
        TestBeanFactory factory = (TestBeanFactory) helper.getDefaultBeanFactory();
        assertTrue("Factory not called", factory.getCreateBeanCount() > 0);
    }

    /**
     * Tests creating a bean using a non registered factory.
     */
    @Test(expected = ConfigurationRuntimeException.class)
    public void testCreateBeanWithUnknownFactory()
    {
        BeanDeclarationTestImpl data = setUpBeanDeclaration();
        data.setBeanFactoryName(TEST_FACTORY);
        data.setBeanClassName(BeanCreationTestBean.class.getName());
        helper.createBean(data, null);
    }

    /**
     * Tests creating a bean when the factory throws an exception.
     */
    @Test(expected = ConfigurationRuntimeException.class)
    public void testCreateBeanWithException()
    {
        helper.registerBeanFactory(TEST_FACTORY, new TestBeanFactory());
        BeanDeclarationTestImpl data = setUpBeanDeclaration();
        data.setBeanFactoryName(TEST_FACTORY);
        data.setBeanClassName(getClass().getName());
        helper.createBean(data, null);
    }

    /**
     * Tests if a parameter is correctly passed to the bean factory.
     */
    @Test
    public void testCreateBeanWithParameter()
    {
        Object param = new Integer(42);
        TestBeanFactory factory = new TestBeanFactory();
        helper.registerBeanFactory(TEST_FACTORY, factory);
        BeanDeclarationTestImpl data = setUpBeanDeclaration();
        data.setBeanFactoryName(TEST_FACTORY);
        data.setBeanClassName(BeanCreationTestBean.class.getName());
        checkBean((BeanCreationTestBean) helper.createBean(data, null, param));
        assertSame("Wrong parameter", param, factory.parameter);
    }

    /**
     * Tests whether a wrapper DynaBean for a Java bean can be created.
     */
    @Test
    public void testCreateWrapDynaBean()
    {
        PropertiesConfiguration config = new PropertiesConfiguration();
        DynaBean bean = BeanHelper.createWrapDynaBean(config);
        String value = "TestFooter";
        bean.set("footer", value);
        assertEquals("Property not set", value, config.getFooter());
    }

    /**
     * Tries to create a wrapper DynaBean for a null bean.
     */
    @Test(expected = IllegalArgumentException.class)
    public void testCreateWrapDynaBeanNull()
    {
        BeanHelper.createWrapDynaBean(null);
    }

    /**
     * Tests whether properties from one bean to another can be copied.
     */
    @Test
    public void testCopyProperties() throws Exception
    {
        PropertiesConfiguration src = new PropertiesConfiguration();
        src.setHeader("TestHeader");
        src.setFooter("TestFooter");
        LazyDynaBean dest = new LazyDynaBean();
        BeanHelper.copyProperties(dest, src);
        assertEquals("Wrong footer property", "TestFooter", dest.get("footer"));
        assertEquals("Wrong header property", "TestHeader", dest.get("header"));
    }

    /**
     * Returns an initialized bean declaration.
     *
     * @return the bean declaration
     */
    private BeanDeclarationTestImpl setUpBeanDeclaration()
    {
        BeanDeclarationTestImpl data = new BeanDeclarationTestImpl();
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("stringValue", TEST_STRING);
        properties.put("intValue", String.valueOf(TEST_INT));
        data.setBeanProperties(properties);
        BeanDeclarationTestImpl buddyData = new BeanDeclarationTestImpl();
        Map<String, Object> properties2 = new HashMap<String, Object>();
        properties2.put("stringValue", "Another test string");
        properties2.put("intValue", new Integer(100));
        buddyData.setBeanProperties(properties2);
        buddyData.setBeanClassName(BeanCreationTestBean.class.getName());

        Map<String, Object> nested = new HashMap<String, Object>();
        nested.put("buddy", buddyData);
        data.setNestedBeanDeclarations(nested);
        return data;
    }

    /**
     * Same as setUpBeanDeclaration, but returns a nested array of beans
     * as a single property. Tests multi-value (Collection<BeanDeclaration>)
     * children construction.
     *
     * @return The bean declaration with a list child bean proerty
     */
    private BeanDeclarationTestImpl setUpBeanDeclarationWithListChild()
    {
        BeanDeclarationTestImpl data = new BeanDeclarationTestImpl();
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("stringValue", TEST_STRING);
        properties.put("intValue", String.valueOf(TEST_INT));
        data.setBeanProperties(properties);

        List<BeanDeclaration> childData = new ArrayList<BeanDeclaration>();
        childData.add(createChildBean("child1"));
        childData.add(createChildBean("child2"));
        Map<String, Object> nested = new HashMap<String, Object>();
        nested.put("children", childData);
        data.setNestedBeanDeclarations(nested);
        return data;
    }

    /**
     * Create a simple bean declaration that has no children for testing
     * of nested children bean declarations.
     *
     * @param name A name prefix that can be used to disambiguate the children
     * @return A simple declaration
     */
    private BeanDeclarationTestImpl createChildBean(String name)
    {
        BeanDeclarationTestImpl childBean = new BeanDeclarationTestImpl();
        Map<String, Object> properties2 = new HashMap<String, Object>();
        properties2.put("stringValue", name + " Another test string");
        properties2.put("intValue", new Integer(100));
        childBean.setBeanProperties(properties2);
        childBean.setBeanClassName(BeanCreationTestBean.class.getName());

        return childBean;
    }

    /**
     * Tests if the bean was correctly initialized from the data of the test
     * bean declaration.
     *
     * @param bean the bean to be checked
     */
    private void checkBean(BeanCreationTestBean bean)
    {
        assertEquals("Wrong string property", TEST_STRING, bean
                .getStringValue());
        assertEquals("Wrong int property", TEST_INT, bean.getIntValue());
        BeanCreationTestBean buddy = bean.getBuddy();
        assertNotNull("Buddy was not set", buddy);
        assertEquals("Wrong string property in buddy", "Another test string",
                buddy.getStringValue());
        assertEquals("Wrong int property in buddy", 100, buddy.getIntValue());
    }

    /**
     * Tests if the bean was correctly initialized from the data of the test
     * bean declaration.
     *
     * @param bean the bean to be checked
     */
    private void checkBean(BeanCreationTestBeanWithListChild bean)
    {
        assertEquals("Wrong string property", TEST_STRING, bean
                .getStringValue());
        assertEquals("Wrong int property", TEST_INT, bean.getIntValue());
        List<BeanCreationTestBean> children = bean.getChildren();
        assertNotNull("Children were not set", children);
        assertEquals("Wrong number of children created", children.size(), 2);
        assertNotNull("First child was set as null", children.get(0));
        assertNotNull("Second child was set as null", children.get(1));
    }

    /**
     * An implementation of the BeanFactory interface used for testing. This
     * implementation is really simple: If the BeanCreationTestBean class is provided, a new
     * instance will be created. Otherwise an exception is thrown.
     */
    private class TestBeanFactory implements BeanFactory
    {
        Object parameter;

        boolean supportsDefaultClass;

        /** A counter for the created instances. */
        private int createBeanCount;

        @Override
        public Object createBean(BeanCreationContext bcc) throws Exception
        {
            createBeanCount++;
            parameter = bcc.getParameter();
            if (BeanCreationTestBean.class.equals(bcc.getBeanClass()))
            {
                BeanCreationTestBean bean = new BeanCreationTestBean();
                helper.initBean(bean, bcc.getBeanDeclaration());
                return bean;
            }
            else if (BeanCreationTestBeanWithListChild.class.equals(bcc
                    .getBeanClass()))
            {
                BeanCreationTestBeanWithListChild bean =
                        new BeanCreationTestBeanWithListChild();
                helper.initBean(bean, bcc.getBeanDeclaration());
                return bean;
            }
            else
            {
                throw new IllegalArgumentException("Unsupported class: "
                        + bcc.getBeanClass());
            }
        }

        /**
         * Returns the default class, but only if the supportsDefaultClass flag
         * is set.
         */
        @Override
        public Class<?> getDefaultBeanClass()
        {
            return supportsDefaultClass ? BeanCreationTestBean.class : null;
        }

        /**
         * Returns the number of beans created via this factory.
         *
         * @return the number of created beans
         */
        public int getCreateBeanCount()
        {
            return createBeanCount;
        }
    }
}


text:
package controller;

public class ExemploVetorFloat {
	public static void main(String[] args){
		float notas[] = {4, 7.5f, 10, 9};
		System.out.println("notas[1] = " +notas[1]);
	}

}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Linq;
using Orchard.ContentManagement;
using Orchard.Data;
using OrchardHarvest.Models;

namespace OrchardHarvest.Services {
    public class ConferenceService : IConferenceService {
        private readonly IRepository<SpeakerPerSessionRecord> _speakerPerSessionRepository;
        private readonly IContentManager _contentManager;

        public ConferenceService(IRepository<SpeakerPerSessionRecord> speakerPerSessionRepository, IContentManager contentManager) {
            _speakerPerSessionRepository = speakerPerSessionRepository;
            _contentManager = contentManager;
        }

        public IEnumerable<SessionPart> GetSessionsBySpeaker(int speakerId, VersionOptions versionOptions = null) {
            var ids = from record in _speakerPerSessionRepository.Table
                      where record.SpeakerId == speakerId
                      select record.SessionId;

            versionOptions = versionOptions ?? VersionOptions.Published;
            return _contentManager.GetMany<SessionPart>(ids, versionOptions, QueryHints.Empty);
        }

        public IEnumerable<SpeakerPart> GetSpeakersBySession(int sessionId, VersionOptions versionOptions = null) {
            var ids = from record in _speakerPerSessionRepository.Table
                      where record.SessionId == sessionId
                      select record.SpeakerId;

            versionOptions = versionOptions ?? VersionOptions.Published;
            return _contentManager.GetMany<SpeakerPart>(ids, versionOptions, QueryHints.Empty);
        }

        public void RemoveSessionsFromSpeaker(int speakerId, IEnumerable<int> except = null) {
            except = except ?? Enumerable.Empty<int>();

            foreach (var record in _speakerPerSessionRepository.Table.Where(x => x.SpeakerId == speakerId && !except.Contains(x.SessionId))) {
                _speakerPerSessionRepository.Delete(record);
            }
        }

        public void AddSessionsToSpeaker(int speakerId, IEnumerable<int> sessionIds) {
            var existingSessionIdsQuery = from record in _speakerPerSessionRepository.Table
                                          where record.SpeakerId == speakerId && sessionIds.Contains(record.SessionId)
                                          select record.SessionId;

            var existingSessionIds = existingSessionIdsQuery.ToArray();

            foreach (var sessionId in from sessionId in sessionIds where !existingSessionIds.Contains(sessionId) select sessionId) {

                _speakerPerSessionRepository.Create(new SpeakerPerSessionRecord {
                    SpeakerId = speakerId,
                    SessionId = sessionId
                });
            }
        }

        public void RemoveSpeakersFromSession(int sessionId, IEnumerable<int> except = null) {
            except = except ?? Enumerable.Empty<int>();

            foreach (var record in _speakerPerSessionRepository.Table.Where(x => x.SessionId == sessionId && !except.Contains(x.SpeakerId))) {
                _speakerPerSessionRepository.Delete(record);
            }
        }

        public void AddSpeakersToSession(int sessionId, IEnumerable<int> speakerIds) {
            var existingSpeakerIdsQuery = from record in _speakerPerSessionRepository.Table
                                          where record.SessionId == sessionId && speakerIds.Contains(record.SpeakerId)
                                          select record.SpeakerId;

            var existingSpeakerIds = existingSpeakerIdsQuery.ToArray();

            foreach (var speakerId in from speakerId in speakerIds where !existingSpeakerIds.Contains(speakerId) select speakerId) {

                _speakerPerSessionRepository.Create(new SpeakerPerSessionRecord {
                    SessionId = sessionId,
                    SpeakerId = speakerId
                });
            }
        }
    }
}


text:
<?php
namespace metastore;

/**
 * Autogenerated by Thrift Compiler (0.14.1)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
use Thrift\Base\TBase;
use Thrift\Type\TType;
use Thrift\Type\TMessageType;
use Thrift\Exception\TException;
use Thrift\Exception\TProtocolException;
use Thrift\Protocol\TProtocol;
use Thrift\Protocol\TBinaryProtocolAccelerated;
use Thrift\Exception\TApplicationException;

class ThriftHiveMetastore_get_delegation_token_args
{
    static public $isValidate = false;

    static public $_TSPEC = array(
        1 => array(
            'var' => 'token_owner',
            'isRequired' => false,
            'type' => TType::STRING,
        ),
        2 => array(
            'var' => 'renewer_kerberos_principal_name',
            'isRequired' => false,
            'type' => TType::STRING,
        ),
    );

    /**
     * @var string
     */
    public $token_owner = null;
    /**
     * @var string
     */
    public $renewer_kerberos_principal_name = null;

    public function __construct($vals = null)
    {
        if (is_array($vals)) {
            if (isset($vals['token_owner'])) {
                $this->token_owner = $vals['token_owner'];
            }
            if (isset($vals['renewer_kerberos_principal_name'])) {
                $this->renewer_kerberos_principal_name = $vals['renewer_kerberos_principal_name'];
            }
        }
    }

    public function getName()
    {
        return 'ThriftHiveMetastore_get_delegation_token_args';
    }

    public function read($input)
    {
        $xfer = 0;
        $fname = null;
        $ftype = 0;
        $fid = 0;
        $xfer += $input->readStructBegin($fname);
        while (true) {
            $xfer += $input->readFieldBegin($fname, $ftype, $fid);
            if ($ftype == TType::STOP) {
                break;
            }
            switch ($fid) {
                case 1:
                    if ($ftype == TType::STRING) {
                        $xfer += $input->readString($this->token_owner);
                    } else {
                        $xfer += $input->skip($ftype);
                    }
                    break;
                case 2:
                    if ($ftype == TType::STRING) {
                        $xfer += $input->readString($this->renewer_kerberos_principal_name);
                    } else {
                        $xfer += $input->skip($ftype);
                    }
                    break;
                default:
                    $xfer += $input->skip($ftype);
                    break;
            }
            $xfer += $input->readFieldEnd();
        }
        $xfer += $input->readStructEnd();
        return $xfer;
    }

    public function write($output)
    {
        $xfer = 0;
        $xfer += $output->writeStructBegin('ThriftHiveMetastore_get_delegation_token_args');
        if ($this->token_owner !== null) {
            $xfer += $output->writeFieldBegin('token_owner', TType::STRING, 1);
            $xfer += $output->writeString($this->token_owner);
            $xfer += $output->writeFieldEnd();
        }
        if ($this->renewer_kerberos_principal_name !== null) {
            $xfer += $output->writeFieldBegin('renewer_kerberos_principal_name', TType::STRING, 2);
            $xfer += $output->writeString($this->renewer_kerberos_principal_name);
            $xfer += $output->writeFieldEnd();
        }
        $xfer += $output->writeFieldStop();
        $xfer += $output->writeStructEnd();
        return $xfer;
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="Execute.cs" company="TemporalCohesion.co.uk">
//     Copyright 2012 - Present Stuart Grassie
//
//     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.
// </copyright>
//----------------------------------------------------------------------

namespace GitHubAPI
{
    using RestSharp;

    public partial class GithubRestApiClient
    {
        public IRestResponse Execute(IRestRequest request)
        {
            var response = _innerRestClient.Execute(request);
            CheckRateLimit(response.Headers);
            return response;
        }

        public IRestResponse<T> Execute<T>(IRestRequest request) where T : new()
        {
            var response = _innerRestClient.Execute<T>(request);
            CheckRateLimit(response.Headers);
            return response;
        }
    }
}


text:
package com.flybird.p004;

/**
 * Created by hongtao.
 *
 * Basically we want to remove half of one array during each step. Thus
 * reduced the size of the whole elements. Once one array reduced to 1 or 2
 * we can manually find the correct element
 */
public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        // Just consider the normal case
        // The index of the target element(s) are (length - 1) / 2  or length / 2 for length > 0
        // for example
        // length  0  1  2  3  4  5  6  7  8  9  10
        // index1  0  0  0  1  1  2  2  3  3  4  4
        // index2        1     2     3     4     5

        int length1 = nums1.length;
        int length2 = nums2.length;

        // If both arrays are empty, just return 0
        if (length1 == 0)
            return getMediumForOneArray(nums2, 0, length2 - 1);
        else if (length2 == 0) {
            return getMediumForOneArray(nums1, 0, length1 - 1);
        }

        int targetIndex = (length1 + length2 - 1) / 2;

        int startIndex1 = 0;
        int startIndex2 = 0;
        int endIndex1 = length1 - 1;
        int endIndex2 = length2 - 1;

        // now we need to cut through the elements
        while (length1 > 0 && length2 > 0) {
            int targetIndex1 = startIndex1 + (length1 - 1) / 2;
            int targetIndex2 = startIndex2 + (length2 - 1) / 2;

            if (nums1[targetIndex1] < nums2[targetIndex2]) {
                if ()
            }
        }

        return 0.0;
    }

    // Solve a general problem of find the targetIndex in the combined arrys of two given range
    private double findIndexSortedArrays(int[] nums1, int start1, int end1,
                                         int[] nums2, int start2, int end2,
                                         int targetIndex) {
        int startIndex1 = start1;
        int endIndex1 = end1;
        int startIndex2 = start2;
        int endIndex2 = end2;
        int searchIndex = targetIndex;

        return 0.0;
    }

    private double getMediumForOneArray(int[] num, int startIndex, int endIndex) {
        int length = endIndex - startIndex + 1;
        if (length <= 0)
            return 0.0;

        boolean isEven = ((length % 2) == 0);
        int lowerIndex = startIndex + (length - 1) / 2;
        if (isEven) {
            return 0.5 * (num[lowerIndex] + num[lowerIndex + 1]);
        }
        else {
            return num[lowerIndex];
        }
    }
}


text:
'use strict';

var mainController = angular.module('mainController', []);

mainController.controller('MainController', function($scope, $location) {
    $scope.$on('login', function(details) {
        $scope.authenticated = true;
        $location.path('/users');
    });

    $scope.$on('logout', function(details) {
        $scope.authenticated = false;
        $location.path('/');
    });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Agiil.Data;
using Agiil.Data.Sqlite;
using Agiil.Domain.Data;
using Autofac;
using Autofac.Core;
using CSF.DecoratorBuilder;

namespace Agiil.Bootstrap.Data
{
    public class DataModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            builder
              .RegisterType<SnapshotStore>()
              .SingleInstance();

            builder.RegisterDecoratedService<IPerformsDatabaseUpgrades>(d => d
                .UsingInitialImpl<DbUpDatabaseUpgrader>()
                .ThenWrapWith<BackupTakingUpgrader>());

            builder.RegisterType<DbUpDatabaseUpgrader>().As<ICreatesDatabaseSchema>();

            builder
              .RegisterConfiguration<DataDirectoryConfigurationSection>()
              .AsSelf()
              .As<IGetsDataDirectory>();

            builder.RegisterDecoratedService<IResetsDatabase>(d => d
                .UsingInitialImpl<DevelopmentDatabaseResetter>()
                .ThenWrapWith<SnapshottingDatabaseResetter>());

            builder.Register(GetConnectionStringAdapter);
        }

        IGetsDatabaseFilePath GetConnectionStringAdapter(IComponentContext ctx, IEnumerable<Parameter> @params)
        {
            var connectionStringParam = @params
                .OfType<TypedParameter>()
                .FirstOrDefault(x => x.Type == typeof(string));

            if(connectionStringParam != null)
                return ctx.Resolve<ConnectionStringAdapter>(connectionStringParam);

            if(@params.OfType<TypedParameter>().FirstOrDefault(x => x.Type == typeof(IConnectionStringProvider))?.Value is IConnectionStringProvider provider)
                return ctx.Resolve<ConnectionStringAdapter>(TypedParameter.From(provider.GetConnectionString()));

            throw new DependencyResolutionException($"Cannot resolve an instance of {nameof(IGetsDatabaseFilePath)}, either a {nameof(String)} or a {nameof(IConnectionStringProvider)} parameter must be provided.");
        }
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Tests.Helpers
{
    public static class EquivalentHelper
    {
        public static bool AreEquivalent(object expected, object result)
        {
            if(expected == null)
            {
                return result == null;
            }

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

            var expectedEnumerable = expected as IEnumerable;
            if(expectedEnumerable != null)
            {
                return AreEquivalent(((IEnumerable)expected).Cast<object>().ToList(), ((IEnumerable)result).Cast<object>().ToList());
            }

            var expectedType = expected.GetType();
            var resultType = result.GetType();

            if(!expectedType.IsComplexType())
            {
                return expected.Equals(result);
            }

            const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
            var expectedProperties = expectedType.GetProperties(flags).Select(p => new
            {
                Property = p,
                GetMethod = p.GetGetMethod()
            }).Where(m => m.GetMethod != null).ToList();

            var resultProperties = expectedProperties.Select(e => resultType.GetProperty(e.Property.Name, flags))
                .Where(p => p != null)
                .Select(p => new
                {
                    Property = p,
                    GetMethod = p.GetGetMethod()
                }).Where(m => m.GetMethod != null)
                .ToDictionary(m => m.Property.Name, m => m.GetMethod);

            if(expectedProperties.Count != resultProperties.Count)
            {
                return false;
            }
            if(expectedProperties.Any(e => !AreEquivalent(e.GetMethod.Invoke(expected, null), resultProperties[e.Property.Name].Invoke(result, null))))
            {
                return false;
            }

            var expectedFields = expectedType.GetFields(flags).ToList();
            var resultFields = expectedFields.Select(e => resultType.GetField(e.Name, flags)).Where(p => p != null).ToDictionary(m => m.Name, m => m);
            if(expectedFields.Count != resultFields.Count)
            {
                return false;
            }
            return expectedFields.All(e => AreEquivalent(e.GetValue(expected), resultFields[e.Name].GetValue(result)));
        }

        private static bool AreEquivalent(IReadOnlyCollection<object> expected, IReadOnlyCollection<object> result)
        {
            return expected.Count == result.Count && expected.All(e => result.Any(r => AreEquivalent(e, r)));
        }

        private static bool IsComplexType(this Type type)
        {
            if(type.IsPrimitive || type.IsEnum || type == typeof(string) || type == typeof(DateTime))
            {
                return false;
            }

            if(type.IsGenericType)
            {
                var genericDefinition = type.GetGenericTypeDefinition();
                if(genericDefinition == typeof(Nullable<>))
                {
                    return IsComplexType(type.GetGenericArguments().Single());
                }
            }

            return type.IsClass || type.IsValueType || type.IsInterface;
        }
    }
}


text:
<?php

class PasswordTest extends PHPUnit_Framework_TestCase {

	public function testMakeAndVerify() {
		$the_password = "MyLittleSecret";

		$hash = Password::make($the_password);
		$hash_2 = Password::make("Fake!");

		$this->assertNotEmpty($hash);
		$this->assertNotEmpty($hash_2);

		$this->assertTrue(Password::verify($the_password, $hash));
		$this->assertFalse(Password::verify($the_password, $hash_2));

		$this->assertTrue(Password::compare($the_password, $the_password));
		$this->assertFalse(Password::compare($the_password, "not-the-same"));

	}

}


text:
//
//  CDZQRScanningViewController.h
//
//  Created by Chris Dzombak on 10/27/13.
//  Copyright (c) 2013 Chris Dzombak. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

typedef void (^CDZQRScanResultBlock)(NSString *scanResult);
typedef void (^CDZQRScanErrorBlock)(NSError *error);
typedef void (^CDZQRScanCancelBlock)();

extern NSString * const CDZQRScanningErrorDomain;

typedef NS_ENUM(NSInteger, CDZQRScanningViewControllerErrorCode) {
    CDZQRScanningViewControllerErrorUnavailableMetadataObjectType = 1,
};

/**
 *  Easy barcode scanning view controller for iOS 7.
 */

@interface CDZQRScanningViewController : UIViewController

/**
 *  Returns a scanning view controller configured to accept the given metadata object types.
 *
 *  @param metadataObjectTypes An array of `AVMetadataMachineReadableCodeObject`s
 *
 *  @return Scanning view controller configured to accept the given metadata object types
 */
- (instancetype)initWithMetadataObjectTypes:(NSArray *)metadataObjectTypes;

/**
 *  Returns a scanning view controller configured to accept QR codes
 *
 *  @note This is equivalent to calling `initWithMetadataObjectTypes:@[ AVMetadataObjectTypeQRCode ]`
 *
 *  @return Scanning view controller configured to accept QR codes
 */
- (instancetype)init;

// Your blocks will be called on the main queue.
@property (nonatomic, copy) CDZQRScanResultBlock resultBlock;
@property (nonatomic, copy) CDZQRScanErrorBlock errorBlock;
@property (nonatomic, copy) CDZQRScanCancelBlock cancelBlock;

/**
 *  An array of `AVMetadataMachineReadableCodeObject`s
 */
@property (nonatomic, strong, readonly) NSArray *metadataObjectTypes;

@end


text:
<?php

/**#@+ @ignore */
//require_once 'Zend/Io/Reader.php';
//require_once 'Zend/Io/Writer.php';
/**#@-*/

/**
 * The base class for all ID3v2 objects.
 *
 * @category   Zend
 * @package    Zend_Media
 * @subpackage ID3
 * @author     Sven Vollbehr <sven@vollbehr.eu>
 * @author     Ryan Butterfield <buttza@gmail.com>
 * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Object.php 215 2011-04-30 10:37:09Z svollbehr $
 */
abstract class Zend_Media_Id3_Object
{
    /**
     * The reader object.
     *
     * @var Zend_Io_Reader
     */
    protected $_reader;

    /**
     * The options array.
     *
     * @var Array
     */
    private $_options;

    /**
     * Constructs the class with given parameters.
     *
     * @param Zend_Io_Reader $reader The reader object.
     * @param Array          $options The options array.
     */
    public function __construct($reader = null, &$options = array())
    {
        $this->_reader = $reader;
        $this->_options = &$options;
    }

    /**
     * Returns the options array.
     *
     * @return Array
     */
    public final function &getOptions()
    {
        return $this->_options;
    }

    /**
     * Returns the given option value, or the default value if the option is not
     * defined.
     *
     * @param string $option The name of the option.
     * @param mixed $defaultValue The default value to be returned.
     */
    public final function getOption($option, $defaultValue = null)
    {
        if (isset($this->_options[$option])) {
            return $this->_options[$option];
        }
        return $defaultValue;
    }

    /**
     * Sets the options array. See {@link Zend_Media_Id3v2} class for available
     * options.
     *
     * @param Array $options The options array.
     */
    public final function setOptions(&$options)
    {
        $this->_options = &$options;
    }

    /**
     * Sets the given option the given value.
     *
     * @param string $option The name of the option.
     * @param mixed $value The value to set for the option.
     */
    public final function setOption($option, $value)
    {
        $this->_options[$option] = $value;
    }

    /**
     * Clears the given option value.
     *
     * @param string $option The name of the option.
     */
    public final function clearOption($option)
    {
        unset($this->_options[$option]);
    }

    /**
     * Magic function so that $obj->value will work.
     *
     * @param string $name The field name.
     * @return mixed
     */
    public function __get($name)
    {
        if (method_exists($this, 'get' . ucfirst($name))) {
            return call_user_func(array($this, 'get' . ucfirst($name)));
        } else {
            //require_once 'Zend/Media/Id3/Exception.php';
            throw new Zend_Media_Id3_Exception('Unknown field: ' . $name);
        }
    }

    /**
     * Magic function so that assignments with $obj->value will work.
     *
     * @param string $name  The field name.
     * @param string $value The field value.
     * @return mixed
     */
    public function __set($name, $value)
    {
        if (method_exists($this, 'set' . ucfirst($name))) {
            call_user_func(array($this, 'set' . ucfirst($name)), $value);
        } else {
            //require_once 'Zend/Media/Id3/Exception.php';
            throw new Zend_Media_Id3_Exception('Unknown field: ' . $name);
        }
    }

    /**
     * Encodes the given 32-bit integer to 28-bit synchsafe integer, where the
     * most significant bit of each byte is zero, making seven bits out of eight
     * available.
     *
     * @param integer $val The integer to encode.
     * @return integer
     */
    protected final function _encodeSynchsafe32($val)
    {
        return ($val & 0x7f) | ($val & 0x3f80) << 1 |
            ($val & 0x1fc000) << 2 | ($val & 0xfe00000) << 3;
    }

    /**
     * Decodes the given 28-bit synchsafe integer to regular 32-bit integer.
     *
     * @param integer $val The integer to decode
     * @return integer
     */
    protected final function _decodeSynchsafe32($val)
    {
        return ($val & 0x7f) | ($val & 0x7f00) >> 1 |
            ($val & 0x7f0000) >> 2 | ($val & 0x7f000000) >> 3;
    }

    /**
     * Applies the unsynchronisation scheme to the given data string.
     *
     * Whenever a false synchronisation is found within the data, one zeroed
     * byte is inserted after the first false synchronisation byte. This has the
     * side effect that all 0xff00 combinations have to be altered, so they will
     * not be affected by the decoding process.
     *
     * Therefore all the 0xff00 combinations are replaced with the 0xff0000 combination and all the 0xff[0xe0-0xff]
     * combinations are replaced with 0xff00[0xe0-0xff] during the unsynchronisation.
     *
     * @param string $data The input data.
     * @return string
     */
    protected final function _encodeUnsynchronisation(&$data)
    {
        return preg_replace('/\xff(?=[\xe0-\xff])/', "\xff\x00", preg_replace('/\xff\x00/', "\xff\x00\x00", $data));
    }

    /**
     * Reverses the unsynchronisation scheme from the given data string.
     *
     * @see _encodeUnsynchronisation
     * @param string $data The input data.
     * @return string
     */
    protected final function _decodeUnsynchronisation(&$data)
    {
        return preg_replace('/\xff\x00\x00/', "\xff\x00", preg_replace('/\xff\x00(?=[\xe0-\xff])/', "\xff", $data));
    }

    /**
     * Splits UTF-16 formatted binary data up according to null terminators
     * residing in the string, up to a given limit.
     *
     * @param string $value The input string.
     * @return Array
     */
    protected final function _explodeString16($value, $limit = null)
    {
        $i = 0;
        $array = array();
        while (count($array) < $limit - 1 || $limit === null) {
            $start = $i;
            do {
                $i = strpos($value, "\x00\x00", $i);
                if ($i === false) {
                    $array[] = substr($value, $start);
                    return $array;
                }
            } while ($i & 0x1 != 0 && $i++); // make sure its aligned
            $array[] = substr($value, $start, $i - $start);
            $i += 2;
        }
        $array[] = substr($value, $i);
        return $array;
    }

    /**
     * Splits UTF-8 or ISO-8859-1 formatted binary data according to null
     * terminators residing in the string, up to a given limit.
     *
     * @param string $value The input string.
     * @return Array
     */
    protected final function _explodeString8($value, $limit = null)
    {
        return preg_split('/\x00/', $value, $limit);
    }

    /**
     * Converts string from the given character encoding to the target encoding
     * specified by the options as the encoding to display all the texts with,
     * and returns the converted string.
     *
     * Character encoding sets can be {@link Zend_Media_Id3_Encoding}
     * constants or already in the string form accepted by iconv.
     *
     * @param string|Array $string
     * @param string|integer $source The source encoding.
     * @param string|integer $target The target encoding. Defaults to the
     *  encoding value set in options.
     */
    protected final function _convertString($string, $source, $target = null)
    {
        if ($target === null) {
            $target = $this->getOption('encoding', 'utf-8');
        }

        $source = $this->_translateIntToEncoding($source);
        $target = $this->_translateIntToEncoding($target);

        if ($source == $target) {
            return $string;
        }

        if (is_array($string)) {
            foreach ($string as $key => $value) {
                $string[$key] = iconv($source, $target, $value);
            }
        } else {
            $string = iconv($source, $target, $string);
        }
        return $string;
    }

    /**
     * Returns given encoding in the form accepted by iconv.
     *
     * Character encoding set can be a {@link Zend_Media_Id3_Encoding}
     * constant or already in the string form accepted by iconv.
     *
     * @param string|integer $encoding The encoding.
     * @return string
     */
    protected final function _translateIntToEncoding($encoding)
    {
        if (is_string($encoding)) {
            return strtolower($encoding);
        }
        if (is_integer($encoding)) {
            switch ($encoding) {
                case Zend_Media_Id3_Encoding::UTF16:
                    return 'utf-16';
                case Zend_Media_Id3_Encoding::UTF16LE:
                    return 'utf-16le';
                case Zend_Media_Id3_Encoding::UTF16BE:
                    return 'utf-16be';
                case Zend_Media_Id3_Encoding::ISO88591:
                    return 'iso-8859-1';
                default:
                    return 'utf-8';
            }
        }
        return 'utf-8';
    }

    /**
     * Returns given encoding in the form possible to write to the tag frame.
     *
     * Character encoding set can be in the string form accepted by iconv or
     * already a {@link Zend_Media_Id3_Encoding} constant.
     *
     * @param string|integer $encoding The encoding.
     * @return integer
     */
    protected final function _translateEncodingToInt($encoding)
    {
        if (is_integer($encoding)) {
            if ($encoding >= 0 && $encoding <= 4) {
                return $encoding;
            }
        }
        if (is_string($encoding)) {
            switch ($encoding) {
                case 'utf-16':
                    return Zend_Media_Id3_Encoding::UTF16;
                case 'utf-16le':
                    return Zend_Media_Id3_Encoding::UTF16;
                case 'utf-16be':
                    return Zend_Media_Id3_Encoding::UTF16BE;
                case 'iso-8859-1':
                    return Zend_Media_Id3_Encoding::ISO88591;
                default:
                    return Zend_Media_Id3_Encoding::UTF8;
            }
        }
        return Zend_Media_Id3_Encoding::UTF8;
    }

    /**
     * Writes the object data.
     *
     * @param Zend_Io_Writer $writer The writer object.
     * @return void
     */
    abstract public function write($writer);
}


text:
.PHONY: default sync install uninstall

MODULES = fish git nvim ssh vscode

default: sync install

sync:
	mkdir -p ~/.config/nvim/autoload
	curl -fLo ~/.config/nvim/autoload/plug.vim https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

install:
	stow --no-folding $(MODULES) -t ~
	nvim -c "PlugInstall --sync" -c "qa"
	@echo
	@echo "For iTerm2, make sure to manually load the preferences .plist through the preferences GUI"
	@echo

uninstall:
	stow --no-folding -D $(MODULES) -t ~


text:
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, FlexibleContexts, FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies, MultiParamTypeClasses, NoImplicitPrelude       #-}
{-# LANGUAGE OverloadedStrings, QuasiQuotes, RecordWildCards, ScopedTypeVariables   #-}
{-# LANGUAGE StandaloneDeriving, TemplateHaskell, TypeFamilies                      #-}

module FreeAgent.Core.Server.Schedule
    ( scheduleServer
    ) where

import           FreeAgent.AgentPrelude
import           FreeAgent.Core                           hiding (lookupEvent)
import           FreeAgent.Core.Lenses
import           FreeAgent.Core.Protocol.Schedule         (serverName)
import           FreeAgent.Database.AcidState
import           FreeAgent.Server.ManagedAgent

import           Control.Monad.Reader                     (ask)
import           Control.Monad.State                      (StateT)
import qualified Data.Map.Strict                          as Map
import qualified Data.Set                                 as Set

import           Control.Distributed.Process.Extras.Time
import           Control.Distributed.Process.Extras.Timer (Tick (..), TimerRef,
                                                           cancelTimer, sendAfter)

import           Data.Default                             (Default (..))
import           Data.Time.Clock                          (addUTCTime, diffUTCTime)
import           System.Cron

-------------------------
-- Persistence
-- ----------------------
type NextScheduled = (UTCTime, Event)

data SchedulePersist
  = SchedulePersist { _persistEvents        :: Map Key Event
                    , _persistNextScheduled :: Set NextScheduled
                    } deriving (Show, Typeable)

instance Default SchedulePersist where
    def = SchedulePersist mempty Set.empty

data ScheduleState
   = ScheduleState { _stateAcid      :: !(AcidState SchedulePersist)
                   , _stateTickerRef :: Maybe TimerRef
                   , _stateTicking   :: Bool
                   } deriving (Typeable, Generic)

makeFields ''SchedulePersist

makeFields ''ScheduleState

getPersist :: Query SchedulePersist SchedulePersist
getPersist = ask

calcNextScheduled :: UTCTime -> Event -> NextScheduled
calcNextScheduled now event = scheduleFor $ schedRecur event
  where
    --TODO: need a more efficient implementation than brute force -
    --take a look a Quartz CronExpression
    scheduleFor (RecurCron sched _) = untilMatches now
      where untilMatches time'
              | scheduleMatches sched time' = (time', event)
              | otherwise = untilMatches (addMinutes 1 time')
    scheduleFor (RecurInterval ms) =
        let diff = timeIntervalToDiffTime (milliSeconds ms) in
        (addUTCTime diff now, event)
    scheduleFor (OnceAt time') = (time', event)

addMinutes :: Int -> UTCTime -> UTCTime
addMinutes additional time' =
    let minute' = timeIntervalToDiffTime (minutes additional) in
    addUTCTime minute' time'

nextMinute :: MonadIO io => io UTCTime
nextMinute = addMinutes 1 `liftM` getCurrentTime

lookupEvent :: Key -> Query SchedulePersist (Maybe Event)
lookupEvent key' = views events $ Map.lookup key'

allCronEvents :: Query SchedulePersist [(CronSchedule, Key)]
allCronEvents = Map.foldr crons [] <$> view events
  where crons Event{..} acc
          | isCron schedRecur = (cronFrom schedRecur, schedKey) : acc
          | otherwise = acc
          where isCron (RecurCron _ _) = True
                isCron _ = False
                cronFrom (RecurCron cron' _) = cron'
                cronFrom _ = $(err "illegal pattern match")

queryAllEvents :: Query SchedulePersist [Event]
queryAllEvents = views events (snd . unzip . Map.toList)

readyToRun :: UTCTime -> Update SchedulePersist [Event]
readyToRun now = do
    nextScheduled' <- use nextScheduled
    let emptyEvent = (now, Event "" (RecurInterval 0) Never zeroDate False)
        (ready, waiting) = Set.split emptyEvent nextScheduled'
        nextAfter = Set.map (\(_, ev) ->
                                case schedRecur ev of
                                    RecurCron _ _  -> -- Cron is precise to minute
                                        calcNextScheduled (addMinutes 1 now) ev
                                    _ -> calcNextScheduled now ev
                            ) ready
    nextScheduled .= Set.union nextAfter waiting
    return $ snd . unzip $ Set.toList ready

addEvent :: NextScheduled -> Update SchedulePersist ()
addEvent next@(_, event) = do
    events %= Map.insertWith newer (key event) event
    nextScheduled %= Set.insert next
  where newer new old
          | schedModified new > schedModified old = new
          | otherwise = old

removeEvent :: Key -> Update SchedulePersist ()
removeEvent key' = do
    events %= Map.delete key'
    nextScheduled %= Set.filter (\ (_, ev) -> key ev /= key')

disableEvents :: [Key] -> Update SchedulePersist ()
disableEvents keys' =
 do events %= flip ( foldr $ \k es ->
                        Map.update (\e -> Just e {schedDisabled = True}) k es
                   ) keys'
    nextScheduled %= Set.filter (\e -> schedKey (snd e) `notElem` keys')

enableEvents :: UTCTime -> [Key] -> Update SchedulePersist ()
enableEvents now keys' =
 do events' <- use events
    forM_ keys' $ \key' ->
     do let mevent = Map.lookup key' events'
        case mevent of
            Just event' ->
             do let enabled = event' {schedDisabled = False}
                events %= Map.insert key' enabled
                nextScheduled %= Set.insert (calcNextScheduled now enabled)
            Nothing -> return ()

nextScheduledTime :: Query SchedulePersist (Maybe UTCTime)
nextScheduledTime = do
    scheduled <- view nextScheduled
    return $ if Set.null scheduled
             then Nothing
             else let (time',_) = Set.findMin scheduled in Just time'

-- we have to make the splices near the top of the file
$(makeAcidic ''SchedulePersist ['getPersist, 'addEvent, 'lookupEvent
                               , 'allCronEvents, 'queryAllEvents, 'readyToRun, 'nextScheduledTime
                               , 'removeEvent, 'disableEvents, 'enableEvents ])

-- -------Implementation------
-- Implementation
-- ---------------------------

type ScheduleAgent a = StateT ScheduleState Agent a

type instance ProtoT rq ScheduleState a = StateT ScheduleState Agent a

scheduleImpl :: ScheduleImpl ScheduleState
scheduleImpl = ScheduleImpl callScheduleAddEvent' callScheduleEventControl'
                            callScheduleLookupEvent' callScheduleQueryEvents'
                            callScheduleRemoveEvent' castScheduleControl'
  where
    callScheduleAddEvent' (ScheduleAddEvent key' recur retry) =
      do now <- getCurrentTime
         callScheduleAddEvent' (ScheduleAddNewerEvent key' recur retry now)

    callScheduleAddEvent' (ScheduleAddNewerEvent key' recur retry modTime) =
      do let event = Event key' recur retry modTime False
         next <- nextMinute
         () <- update (AddEvent $ calcNextScheduled next event)
         scheduleNextTick

    callScheduleAddEvent' (ScheduleAddEvents events') =
      do next <- nextMinute
         forM_ events' $ \event -> update (AddEvent $ calcNextScheduled next event)
         scheduleNextTick

    callScheduleEventControl' (ScheduleDisableEvents keys') =
        update (DisableEvents keys')

    callScheduleEventControl' (ScheduleEnableEvents keys') =
     do now <- getCurrentTime
        void $ update (EnableEvents now keys')
        scheduleNextTick

    callScheduleLookupEvent' (ScheduleLookupEvent k) =
        query (LookupEvent k)

    callScheduleQueryEvents' _ = query QueryAllEvents

    callScheduleRemoveEvent' cmd@(ScheduleRemoveEvent k) =
        runLogExceptT cmd $ update (RemoveEvent k)

    castScheduleControl' ScheduleStart  =
     do ticking' <- use ticking
        if not ticking'
          then do ticking .= True
                  [qinfo|Starting scheduler.|]
                  tickMe
          else [qinfo|Scheduler already running.|]

    castScheduleControl' ScheduleStop  =
     do ticking' <- use ticking
        if ticking'
          then do [qinfo|Stopping scheduler.|]
                  ticking .= False
                  ticker <- use tickerRef
                  case ticker of
                      Just ref ->
                          liftP $ cancelTimer ref
                      Nothing -> return ()
          else [qinfo|Scheduler already stopped.|]

scheduleServer :: AgentServer
scheduleServer =
    defineServer
        serverName
        initSchedule
        defaultProcess {
            apiHandlers =
            [ registerCall scheduleImpl (Proxy :: Proxy ScheduleRemoveEvent)
            , registerCall scheduleImpl (Proxy :: Proxy ScheduleAddEvent)
            , registerCall scheduleImpl (Proxy :: Proxy ScheduleLookupEvent)
            , registerCall scheduleImpl (Proxy :: Proxy ScheduleQueryEvents)
            , registerCall scheduleImpl (Proxy :: Proxy ScheduleEventControl)
            , registerCast scheduleImpl (Proxy :: Proxy ScheduleControl)
            ],
            infoHandlers =
            [ agentInfoHandler $ \ Tick -> onTick
            ],
            shutdownHandler =
                \ (AgentState _ _ s) _ ->
             do case s ^. tickerRef of
                   Just ref -> cancelTimer ref
                   Nothing -> return ()
                pid <- getSelfPid
                say $ "Schedule server " ++ show pid ++ " shutting down."
        }
  where initSchedule = do
            acid' <- openOrGetDb "agent-schedule" def def
            startNow <- viewConfig initScheduler
            if startNow then
             do [qinfo|Starting scheduler.|]
                tickMe
            else [qinfo|Not starting scheduler.|]
            return $ ScheduleState acid' Nothing startNow

tickMe :: MonadProcess process => process ()
tickMe =
 do pid <- getSelfPid
    send pid Tick

onTick :: ScheduleAgent ()
onTick = do
    now <- getCurrentTime
    events' <- update (ReadyToRun now)
    Right () <- castServ $ ExecuteBatch (map key events')
    scheduleNextTick

scheduleNextTick :: ScheduleAgent ()
scheduleNextTick =
 do ticking' <- use ticking
    when ticking' $
     do mminTime <- query NextScheduledTime
        case mminTime of
            Nothing -> return ()
            Just minTime -> do
                pid <- getSelfPid
                diff <- diffUTCTime minTime <$> getCurrentTime
                tickAt pid diff
    return ()
  where tickAt pid diff
          | diff <= 0 = do
              send pid Tick
              tickerRef .= Nothing
          | otherwise = do
            let interval = diffTimeToTimeInterval diff
            ref <- liftP $ sendAfter interval pid Tick
            tickerRef .= Just ref

deriveSafeStore ''SchedulePersist


text:
published: true
title: Drivable area detection
tags: robot keyword
---

https://duckduckgo.com/?q=drivable+area+detection&t=lm&ia=software


text:
from {{project}}.apps.home import mod_home as mod
from {{project}}.apps import models
from chan.utils.decorator import templated

@mod.route('/')
@templated()
def index():
    return {}


text:
package org.kaaproject.kaa.demo.smarthousedemo.command;

public class EndpointCommandKey {

    String fqn;
    String endpontKey;

    public EndpointCommandKey(String fqn, String endpontKey) {
        this.fqn = fqn;
        this.endpontKey = endpontKey;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((endpontKey == null) ? 0 : endpontKey.hashCode());
        result = prime * result + ((fqn == null) ? 0 : fqn.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        EndpointCommandKey other = (EndpointCommandKey) obj;
        if (endpontKey == null) {
            if (other.endpontKey != null)
                return false;
        } else if (!endpontKey.equals(other.endpontKey))
            return false;
        if (fqn == null) {
            if (other.fqn != null)
                return false;
        } else if (!fqn.equals(other.fqn))
            return false;
        return true;
    }

}


text:
package org.apache.sling.resourceresolver.impl.query;

import java.util.HashSet;
import java.util.Set;

import org.apache.sling.api.resource.query.PropertyBuilder;
import org.apache.sling.api.resource.query.Query;
import org.apache.sling.api.resource.query.Query.PropertyConstraint;
import org.apache.sling.api.resource.query.Query.PropertyOperator;
import org.apache.sling.api.resource.query.QueryBuilder;

/**
 * Implementation of the query builder.
 */
public class BasicQueryBuilder implements QueryBuilder {

    private final Set<String> paths = new HashSet<String>();

    private final Set<String> resourceTypes = new HashSet<String>();

    private final Set<String> names = new HashSet<String>();

    private final Set<PropertyConstraint> propertyConstraints = new HashSet<PropertyConstraint>();

    @Override
    public Query build() {
        return new BasicQuery(paths, resourceTypes, names, propertyConstraints);
    }

    @Override
    public QueryBuilder at(final String... path) {
        for(final String p : path) {
            this.paths.add(p);
        }
        return this;
    }

    @Override
    public QueryBuilder isA(final String resourceType) {
        this.resourceTypes.add(resourceType);
        return this;
    }

    @Override
    public QueryBuilder name(final String resourceName) {
        this.names.add(resourceName);
        return this;
    }

    @Override
    public PropertyBuilder property(final String name) {
        return new PropertyBuilder() {

            @Override
            public QueryBuilder isLessOrEq(final Object value) {
                propertyConstraints.add(new BasicPropertyConstraint(PropertyOperator.LT_OR_EQ, name, value));
                return BasicQueryBuilder.this;
            }

            @Override
            public QueryBuilder isLess(final Object value) {
                propertyConstraints.add(new BasicPropertyConstraint(PropertyOperator.LT, name, value));
                return BasicQueryBuilder.this;
            }

            @Override
            public QueryBuilder isGreaterOrEq(final Object value) {
                propertyConstraints.add(new BasicPropertyConstraint(PropertyOperator.GT_OR_EQ, name, value));
                return BasicQueryBuilder.this;
            }

            @Override
            public QueryBuilder isGreater(final Object value) {
                propertyConstraints.add(new BasicPropertyConstraint(PropertyOperator.GT, name, value));
                return BasicQueryBuilder.this;
            }

            @Override
            public QueryBuilder exists() {
                propertyConstraints.add(new BasicPropertyConstraint(PropertyOperator.EXISTS, name, null));
                return BasicQueryBuilder.this;
            }

            @Override
            public QueryBuilder eq(final Object value) {
                propertyConstraints.add(new BasicPropertyConstraint(PropertyOperator.EQ, name, value));
                return BasicQueryBuilder.this;
            }

            @Override
            public QueryBuilder contains(final Object value) {
                propertyConstraints.add(new BasicPropertyConstraint(PropertyOperator.CONTAINS, name, value));
                return BasicQueryBuilder.this;
            }
        };
    }

}