text:
using System;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;

namespace Conekta.Xamarin {
	public abstract class BaseConektaTokenizer {
		internal Version CurrentVersion = new Version(0, 5, 0);
		public RuntimePlatform Platform { get; private set; }
		public abstract string GetFingerprint();
		public abstract string GetUserAgent();
		public abstract void CollectDevice();
		private string PublicKey { get; set; }

		protected BaseConektaTokenizer(string publicKey, RuntimePlatform platform) {
			if (string.IsNullOrEmpty(publicKey))
				throw new ArgumentException("publicKey");

			PublicKey = publicKey;
			Platform = platform;
		}

		public async Task<string> CreateTokenAsync(string cardNumber, string name, string cvc, int year, int month) {
			if (year <= 0)
				throw new ArgumentOutOfRangeException("year");

			if (month <= 0 || month > 12)
				throw new ArgumentOutOfRangeException("month");

			if (string.IsNullOrEmpty(cardNumber))
				throw new ArgumentNullException("cardNumber");

			if (string.IsNullOrEmpty(name))
				throw new ArgumentNullException("name");

			if (string.IsNullOrEmpty(cvc))
				throw new ArgumentNullException("cvc");

			return await CreateTokenAsync(cardNumber, name, cvc, new DateTime(year, month, 1));
		}

		public async Task<string> CreateTokenAsync(Card card) {
			try {
				if (string.IsNullOrEmpty(card.Number))
					throw new ArgumentNullException("cardNumber");

				if (string.IsNullOrEmpty(card.Name))
					throw new ArgumentNullException("name");

				if (string.IsNullOrEmpty(card.Cvc))
					throw new ArgumentNullException("cvc");

				using (var client = new HttpClient()) {
					var authHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:", PublicKey)));
					var version = string.Format("application/vnd.conekta-v{0}.{1}.{2}+json",
					                            CurrentVersion.Major,
					                            CurrentVersion.Minor,
					                            CurrentVersion.Build);

					client.DefaultRequestHeaders.Accept.Clear();
					client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(version));
					client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeader);
					client.DefaultRequestHeaders.Add("Conekta-Client-User-Agent", string.Format(@"{{""agent"": ""{0}""}}",GetUserAgent()));

					var req = new HttpRequestMessage(HttpMethod.Post, "https://api.conekta.io/tokens") {
						Content =
							new StringContent(
							string.Format(
								@"{{""card"":{{""name"":""{0}"",""number"":{1},""cvc"":{2},""exp_month"":{3},""exp_year"":{4}}}}}", card.Name,
								card.Number, card.Cvc, card.Expiration.Month, card.Expiration.Year), Encoding.UTF8, "application/json")
					};

					string str = await (await client.SendAsync(req)).Content.ReadAsStringAsync();

					return Regex.Match(str, @"""id"":""(?<Id>[^""]+)""").Groups["Id"].Value;
				}
			} catch {
				return null;
			}
		}

		public Task<string> CreateTokenAsync(string cardNumber, string name, string cvc, DateTime expiration) {
			return CreateTokenAsync(new Card {
				Number = cardNumber,
				Name = name,
				Cvc = cvc,
				Expiration = expiration
			});
		}
	}
}


text:
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//     * Neither the name of Ayende Rahien nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion

using System;
using System.Text;

using MbUnit.Framework;

namespace Rhino.Mocks.Tests
{
    [TestFixture]
    public class OrderedTests
    {
        private delegate void ConfigureMockDelegate(MockRepository mocks, I1 mockObject);

        #region TestOrderedTimesMin0
        [Test(Description="Test that a Times min of 0 works correctly inside an ordered recorder")]
        public void TestOrderedTimesMin0()
        {
            ConfigureMockDelegate deleg = new ConfigureMockDelegate(ConfigureOrderedTimesMin0);

            // Let's check all the valid possibilities
            AssertOrderValidity(deleg, true, "");
            AssertOrderValidity(deleg, true, "A");
            AssertOrderValidity(deleg, true, "C");
            AssertOrderValidity(deleg, true, "B");
            AssertOrderValidity(deleg, true, "AB");
            AssertOrderValidity(deleg, true, "AC");
            AssertOrderValidity(deleg, true, "BC");
            AssertOrderValidity(deleg, true, "ABC");

            // Let's check some invalid ones
            AssertOrderValidity(deleg, false, "CB");
            AssertOrderValidity(deleg, false, "CA");
            AssertOrderValidity(deleg, false, "BA");
            AssertOrderValidity(deleg, false, "AA");
            AssertOrderValidity(deleg, false, "ABB");
        }

        private static void ConfigureOrderedTimesMin0(MockRepository mocks, I1 mockObject)
        {
            using (mocks.Ordered())
            {
                mockObject.A();
                LastCall.Repeat.Times(0, 1);
                mockObject.B();
                LastCall.Repeat.Times(0, 1);
                mockObject.C();
                LastCall.Repeat.Times(0, 1);
            }
        }
        #endregion

        #region TestOrderedTimesMinNonZeroMaxHigherThanMin
        [Test(Description="Test that a Times non-zero min with a higher max works correctly inside an ordered recorder")]
        public void TestOrderedTimesMinNonZeroMaxHigherThanMin()
        {
            ConfigureMockDelegate deleg = new ConfigureMockDelegate(ConfigureOrderedTimesMinNonZeroMaxHigherThanMin);

            // Let's check all the valid possibilities
            AssertOrderValidity(deleg, true, "ABC");
            AssertOrderValidity(deleg, true, "ABBC");
            AssertOrderValidity(deleg, true, "ABBBC");

            // Let's check some invalid ones
            AssertOrderValidity(deleg, false, "BC"); // Missing A
            AssertOrderValidity(deleg, false, "AC"); // Too few Bs
            AssertOrderValidity(deleg, false, "ABBBBC"); // Too many Bs
        }

        private static void ConfigureOrderedTimesMinNonZeroMaxHigherThanMin(MockRepository mocks, I1 mockObject)
        {
            using (mocks.Ordered())
            {
                mockObject.A();
                mockObject.B();
                LastCall.Repeat.Times(1, 3);
                mockObject.C();
            }
        }
        #endregion

        #region TestOrderedAtLeastOnce
        [Test(Description = "Test that 'at least once' works correctly inside an ordered recorder")]
        public void TestOrderedAtLeastOnce()
        {
            ConfigureMockDelegate deleg = new ConfigureMockDelegate(ConfigureOrderedAtLeastOnce);

            // Let's check some of the valid possibilities
            AssertOrderValidity(deleg, true, "ABC");
            AssertOrderValidity(deleg, true, "ABBC");
            AssertOrderValidity(deleg, true, "ABBBBBBBBBBBBBBBBBBBBC");

            // Let's check some invalid ones
            AssertOrderValidity(deleg, false, "BC"); // Missing A
            AssertOrderValidity(deleg, false, "AC"); // Too few Bs
        }

        private static void ConfigureOrderedAtLeastOnce(MockRepository mocks, I1 mockObject)
        {
            using (mocks.Ordered())
            {
                mockObject.A();
                mockObject.B();
                LastCall.Repeat.AtLeastOnce();
                mockObject.C();
            }
        }
        #endregion

        #region TestOrderedTimesMin0WithNestedUnordered
        [Test(Description = "Test that a Times min of 0 works correctly when followed by an nested unordered section")]
        public void TestOrderedTimesMin0WithNestedUnordered()
        {
            ConfigureMockDelegate deleg = new ConfigureMockDelegate(ConfigureOrderedTimesMin0WithNestedUnordered);

            // Let's check all the valid possibilities
            AssertOrderValidity(deleg, true, "BC");
            AssertOrderValidity(deleg, true, "CB");
            AssertOrderValidity(deleg, true, "ABC");
            AssertOrderValidity(deleg, true, "ACB");
            AssertOrderValidity(deleg, true, "BCA");
            AssertOrderValidity(deleg, true, "CBA");
            AssertOrderValidity(deleg, true, "ABCA");
            AssertOrderValidity(deleg, true, "ACBA");

            // Let's check some invalid ones
            AssertOrderValidity(deleg, false, "");
            AssertOrderValidity(deleg, false, "AA");
            AssertOrderValidity(deleg, false, "AABC");
            AssertOrderValidity(deleg, false, "AACB");
            AssertOrderValidity(deleg, false, "ABCAA");
        }

        private static void ConfigureOrderedTimesMin0WithNestedUnordered(MockRepository mocks, I1 mockObject)
        {
            using (mocks.Ordered())
            {
                mockObject.A();
                LastCall.Repeat.Times(0, 1);
                using (mocks.Unordered())
                {
                    mockObject.B();
                    mockObject.C();
                }
                mockObject.A();
                LastCall.Repeat.Times(0, 1);
            }
        }
        #endregion

        #region Helper method for performing easy configuration and replay testing
        /// <summary>
        /// Sets up a mock, and runs through methods as specified by characters in <paramref name="methodOrder"/>.
        /// </summary>
        /// <param name="mockConfigurer">A delegate to use to configure the mock.</param>
        /// <param name="isValid">Whether the order should be valid or not.</param>
        /// <param name="methodOrder">The method order (e.g. "ABC", "ABBC").</param>
        private static void AssertOrderValidity( ConfigureMockDelegate mockConfigurer, bool isValid,
                                                 string methodOrder )
        {
            MockRepository mocks = new MockRepository();

            I1 i = mocks.StrictMock(typeof(I1)) as I1;

            mockConfigurer(mocks, i);

            mocks.ReplayAll();

            try
            {
                foreach (char c in methodOrder)
                {
                    switch (c)
                    {
                        case 'A':
                            i.A();
                            break;
                        case 'B':
                            i.B();
                            break;
                        case 'C':
                            i.C();
                            break;
                        default:
                            throw new NotSupportedException();
                    }
                }
                mocks.VerifyAll();
            }
            catch (Exceptions.ExpectationViolationException ex)
            {
                if (isValid)
                {
                    Assert.Fail("Order {0} was supposed to be ok, but got error: {1}", methodOrder, ex.Message);
                }
                else
                {
                    return;
                }
            }

            if (!isValid)
            {
                Assert.Fail("Order {0} was supposed to fail, but did not.", methodOrder);
            }
        }
        #endregion
    }

    public interface I1
    {
        void A();
        void B();
        void C();
    }
}

redpajama_set_name: RedPajamaGithub


text:
import os

import sh

from molecule import logger
from molecule import util
from molecule.verifier.lint import base

LOG = logger.get_logger(__name__)

class Yamllint(base.Base):
    """
    `Yamllint`_ is not the default verifier linter.

    `Yamllint`_ is a linter for yaml files.

    Additional options can be passed to `yamllint` through the options
    dict.  Any option set in this section will override the defaults.

    .. code-block:: yaml

        verifier:
          name: goss
          lint:
            name: yamllint
            options:
              config-file: foo/bar

    Test file linting can be disabled by setting `enabled` to False.

    .. code-block:: yaml

        verifier:
          name: goss
          lint:
            name: yamllint
            enabled: False

    Environment variables can be passed to lint.

    .. code-block:: yaml

        verifier:
          name: goss
          lint:
            name: yamllint
            env:
              FOO: bar

    .. _`Yamllint`: https://github.com/adrienverge/yamllint
    """

    def __init__(self, config):
        """
        Sets up the requirements to execute `yamllint` and returns None.

        :param config: An instance of a Molecule config.
        :return: None
        """
        super(Yamllint, self).__init__(config)
        self._yamllint_command = None
        if config:
            self._tests = self._get_tests()

    @property
    def default_options(self):
        return {
            's': True,
        }

    @property
    def default_env(self):
        return util.merge_dicts(os.environ.copy(), self._config.env)

    def bake(self):
        """
        Bake a `yamllint` command so it's ready to execute and returns None.

        :return: None
        """
        self._yamllint_command = sh.yamllint.bake(
            self.options,
            self._tests,
            _env=self.env,
            _out=LOG.out,
            _err=LOG.error)

    def execute(self):
        if not self.enabled:
            msg = 'Skipping, verifier_lint is disabled.'
            LOG.warn(msg)
            return

        if not len(self._tests) > 0:
            msg = 'Skipping, no tests found.'
            LOG.warn(msg)
            return

        if self._yamllint_command is None:
            self.bake()

        msg = 'Executing Yamllint on files found in {}/...'.format(
            self._config.verifier.directory)
        LOG.info(msg)

        try:
            util.run_command(self._yamllint_command, debug=self._config.debug)
            msg = 'Lint completed successfully.'
            LOG.success(msg)
        except sh.ErrorReturnCode as e:
            util.sysexit(e.exit_code)

    def _get_tests(self):
        """
        Walk the verifier's directory for tests and returns a list.

        :return: list
        """
        return [
            filename for filename in util.os_walk(
                self._config.verifier.directory, 'test_*.yml')
        ]


text:
<?php

class Singletons {
  private static $instances;

  public static function __callStatic($name, $arguments) {
    static $bindings = [
      'C' => 'Config',
      'D' => 'Database',
      'T' => 'Template',
      'U' => 'Url',
    ];
    if (!is_array(static::$instances)) {
      static::$instances = [];
    }
    if (!isset(static::$instances[$name])) {
      static::$instances[$name] = new $bindings[$name]();
    }
    return static::$instances[$name];
  }
}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"
  [<!ENTITY identifiableProperties SYSTEM "classpath://org/hisp/dhis/common/identifiableProperties.hbm">]
  >

<hibernate-mapping>
  <class name="org.hisp.dhis.trackedentity.TrackedEntity" table="trackedentity">

    <id name="id" column="trackedentityid">
      <generator class="native" />
    </id>
    &identifiableProperties;

    <property name="name" column="name" not-null="true" unique="true"
      length="230" />

    <property name="description" type="text" />

    <!-- Dynamic attribute values -->

    <set name="attributeValues" table="trackedentityattributevalues">
      <cache usage="read-write" />
      <key column="trackedentityid" />
      <many-to-many class="org.hisp.dhis.attribute.AttributeValue" column="attributevalueid" unique="true" />
    </set>

  </class>
</hibernate-mapping>


text:
import logging
import numpy as np
import xml.etree.ElementTree as ET
import xml.dom.minidom as xdm

class InputHandler(object):
    """General classs for handling XML input files.

    Attributes:
        root -- root element for tree of input file
        var_list -- list of strings of variables to be read
        input_dict -- dictionary of input values as read from XML file

    Note(s):
        --A logging instance should be created prior to instantiating
        InputHandler so that relevant log messages can be recorded.

    """

    def __init__(self,input_filename,input_vars,**kwargs):
        """Initialize InputHandler class."""

        #Create XML tree and root node
        tree = ET.parse(input_filename)
        self.root = tree.getroot()
        #Set variable list as attribute
        self.var_list = input_vars
        #Initialize dictionary to hold results of input parameters
        self.input_dict = {}
        #Start logging
        self.logger = logging.getLogger(type(self).__name__)

    def lookup_vars(self,**kwargs):
        """Loop over var_list and find XML node value."""

        for var in self.var_list:
            #Find node
            node = self.root.find(var)
            #Check if found
            if node is None:
                self.logger.warning("No value found for input %s"%var)
                self.logger.warning("Check for consistency between XML node and variable list.")
                continue

            #check node type
            node_type = node.get('type')
            #loop over children if node is a parent
            if node_type == type(np.array([])).__name__ or node_type == type([]).__name__:
                temp =[]
                for child in node:
                    temp.append(self.set_type(child))

                #set dictionary field
                self.input_dict[node.tag] = np.array(temp)
            #otherwise just get the value
            else:
                self.input_dict[node.tag] = self.set_type(node)

    def set_type(self,node,**kwargs):
        """Set node value depending on type"""

        node_type = node.get('type')
        if node_type == type(str()).__name__:
            val = node.text
        elif node_type == type(float()).__name__ or node_type == type(np.float64()).__name__:
            val = float(node.text)
        elif node_type == type(int()).__name__ or node_type == type(np.int64()).__name__:
            val = int(note.text)
        else:
            self.logger.warning("Missing or unknown type for node %s"%node.tag)
            self.logger.warning("Reading in as string.")
            val = node.text

        return val

class OutputHandler(object):
    """General class for handling printing of output files from Python dictionaries.
    Can be used to print both configuration files as well as results files. Print to
    either plain text or structured XML files.

    Attributes:
        output_filename -- string containing filename to print to
        output_dict -- dictionary to print to file

    """

    def __init__(self,output_filename,output_dict,**kwargs):
        """Initialize OutputHandler class"""

        self.output_filename = output_filename
        self.output_dict = output_dict
        #configure logger
        self.logger = logging.getLogger(type(self).__name__)

    def print_to_xml(self):
        """Print dictionary to XML file"""

        self.root = ET.Element('root')
        for key in self.output_dict:
            self._set_element_recursive(self.root,self.output_dict[key],key)

        with open(self.output_filename,'w') as f:
            f.write(self._pretty_print_xml(self.root))

        f.close()

    def display_xml(self):
        """Print configured XML to the screen"""

        if not hasattr(self,'root'):
            self.logger.error('No root element found. Run self.print_to_xml() first.')

        print(self._pretty_print_xml(self.root))

    def _set_element_recursive(self,root,node,keyname):

        #create subelement
        element = ET.SubElement(root,keyname)
        if type(node) is list:
            for item in node:
                sub_keyname = [k for k in item][0]
                self._set_element_recursive(element,item[sub_keyname],sub_keyname)
        elif type(node) is dict:
            for key in node:
                if key == '_val':
                    element.text = str(node[key])
                else:
                    element.set(key,str(node[key]))
        else:
            element.text = str(node)

    def _pretty_print_xml(self,element):
        """Formatted XML output for writing to file."""

        unformatted = ET.tostring(element)
        xdmparse = xdm.parseString(unformatted)
        return xdmparse.toprettyxml(indent="    ")


text:
from __future__ import absolute_import

from datetime import datetime

from django.test import TestCase
from django.utils import six

from .models import Article

class DefaultTests(TestCase):
    def test_field_defaults(self):
        a = Article()
        now = datetime.now()
        a.save()

        self.assertIsInstance(a.id, six.integer_types)
        self.assertEqual(a.headline, "Default headline")
        self.assertTrue((now - a.pub_date).seconds < 5)


text:
#include <stdint.h>
#include <linux/if_ether.h>

typedef enum ethmsgtype {
    ETPACKET,
    ETIOCTL,
} ethmsgtype_t;

typedef struct ethpacket {
    uint32_t size;                 /* Size of packet */
    uint8_t  data[ETH_FRAME_LEN];  /* Packet data */
} ethpacket_t;

typedef struct ethioctl {
    uint32_t cmd_ret;      /* Command or return value depending on direction */
    uint8_t  padding[22];  /* to talk to older tapd that spoke differently */
    uint8_t  hwaddr[6];
} ethioctl_t;

typedef struct ethmsg {
    enum ethmsgtype type;
    uint32_t padding;  /* for the same reason as above */
    union {
        struct ethpacket ep;
        struct ethioctl  ei;
    } payload;
} ethmsg_t;


text:
package com.compositesw.services.system.util.security;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import com.compositesw.services.system.util.common.BaseRequest;

/**
 *
Java class for getLoginModuleDefaultPropertiesRequest complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="getLoginModuleDefaultPropertiesRequest">
 *   <complexContent>
 *     <extension base="{http://www.compositesw.com/services/system/util/common}baseRequest">
 *       <sequence>
 *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getLoginModuleDefaultPropertiesRequest", propOrder = {
    "name"
})
public class GetLoginModuleDefaultPropertiesRequest
    extends BaseRequest
{

    @XmlElement(required = true)
    protected String name;

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

}


text:
NSString * const NUNextUserErrorDomain = @"com.nextuser.base";

NSInteger const NUNextUserErrorCodeGeneral = 0;

@implementation NUError

+ (NSError *)nextUserErrorWithMessage:(NSString *)message
{
    return [NSError errorWithDomain:NUNextUserErrorDomain
                               code:NUNextUserErrorCodeGeneral
                           userInfo:@{NSLocalizedDescriptionKey : message}];
}

@end


text:
#ifndef BOOST_POLY_COLLECTION_TEST_ANY_TYPES_HPP
#define BOOST_POLY_COLLECTION_TEST_ANY_TYPES_HPP

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/mpl/vector/vector10.hpp>
#include <boost/poly_collection/any_collection.hpp>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/type_erasure/builtin.hpp>
#include <boost/type_erasure/call.hpp>
#include <boost/type_erasure/operators.hpp>

namespace any_types{

struct incrementable1
{
  incrementable1(int n):n{n}{}
  incrementable1(incrementable1&&)=default;
  incrementable1(const incrementable1&)=delete;
  incrementable1& operator=(incrementable1&&)=default;
  incrementable1& operator=(const incrementable1&)=delete;
  bool operator==(const incrementable1& x)const{return n==x.n;}
  incrementable1& operator++(){++n;return *this;}
  int n;
};

struct incrementable3
{
  incrementable3():n{-1}{}
  incrementable3(int n):n{(double)n}{}
  incrementable3& operator++(){++n;return *this;}
  double n;
};

using concept_=boost::type_erasure::incrementable<>;
using collection=boost::any_collection<concept_>;

template<typename T=boost::type_erasure::_self>
struct convertible_to_int
{
  static int apply(const T& x){return x;}
};

using t1=incrementable1;
using t2=double;
using t3=incrementable3;
using t4=int;
using t5=boost::type_erasure::any<
  boost::mpl::vector4<
    boost::type_erasure::copy_constructible<>,
    boost::type_erasure::assignable<>,
    concept_,
    convertible_to_int<>
  >
>;

struct to_int
{
  template<typename Concept,typename Tag>
  int operator()(const boost::type_erasure::any<Concept,Tag>& x)const
  {
    using boost::type_erasure::any_cast;

    if(auto p=any_cast<t1*>(&x))return (*this)(*p);
    if(auto p=any_cast<t2*>(&x))return (*this)(*p);
    if(auto p=any_cast<t3*>(&x))return (*this)(*p);
    if(auto p=any_cast<t4*>(&x))return (*this)(*p);
    if(auto p=any_cast<t5*>(&x))return (*this)(*p);
    else return 0;
  }

  int operator()(const t1& x)const{return x.n;}
  int operator()(const t2& x)const{return static_cast<int>(x);};
  int operator()(const t3& x)const{return static_cast<int>(x.n);}
  int operator()(const t4& x)const{return x;}
  int operator()(const t5& x)const
  {
    return boost::type_erasure::call(convertible_to_int<>{},x);
  }
};

} /* namespace any_types*/

#endif


text:
namespace KBot {

using namespace BWAPI;

Manager::Manager(KBot &kBot) : m_kBot(kBot) {
    // Create initial base
    m_bases.emplace_back(*this, Broodwar->self()->getStartLocation());
}

void Manager::update() {
    // Display debug information
    Broodwar->drawTextScreen(2, 50, "Manager: -");

    // Display build tasks
    const std::size_t maxBuildDisplay = 10;
    Broodwar->drawTextScreen(200, 0, "Build queue:");
    for (std::size_t i = 0; i < m_buildQueue.size() && i < maxBuildDisplay; ++i)
        Broodwar->drawTextScreen(200, (i + 1) * 10, "%s", m_buildQueue[i].toString().c_str());
    if (m_buildQueue.size() > maxBuildDisplay)
        Broodwar->drawTextScreen(200, (maxBuildDisplay + 1) * 10, "and %d more...",
                                 m_buildQueue.size() - maxBuildDisplay);

    // Display available resources
    Broodwar->drawTextScreen(450, 15, "(%d)", getAvailableMinerals());
    Broodwar->drawTextScreen(518, 15, "(%d)", getAvailableGas());

    // Update bases
    for (auto &base : m_bases)
        base.update();

    // Update build tasks
    for (auto &buildTask : m_buildQueue)
        buildTask.update();

    // ----- Prevent spamming -----------------------------------------------
    // Everything below is executed only occasionally and not on every frame.
    if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)
        return;

    // Cleanup finished build tasks.
    for (auto it = m_buildQueue.begin(); it != m_buildQueue.end();) {
        if (it->getState() == BuildTask::State::finalize)
            it = m_buildQueue.erase(it);
        else
            ++it;
    }
}

void Manager::giveOwnership(const Unit &unit) {
    // Assign unit to nearest base.
    const auto it =
        std::min_element(m_bases.begin(), m_bases.end(), [&unit](const Base &a, const Base &b) {
            return distance(unit->getPosition(), a.getPosition()) <
                   distance(unit->getPosition(), b.getPosition());
        });
    assert(it != m_bases.end());
    it->giveOwnership(unit);
}

void Manager::takeOwnership(const Unit &unit) {
    // Remove unit from workers
    m_workers.erase(std::remove(m_workers.begin(), m_workers.end(), unit), m_workers.end());

    // And pass on to bases...
    for (auto &base : m_bases)
        base.takeOwnership(unit);
}

void Manager::addBuildTask(const BuildTask &buildTask) { m_buildQueue.push_back(buildTask); }

void Manager::buildTaskOnUnitCreatedOrMorphed(const Unit &unit) {
    // Return as soon as the first build task can identify the created unit.
    for (auto &buildTask : m_buildQueue) {
        if (buildTask.onUnitCreatedOrMorphed(unit))
            return;
    }
}

void Manager::buildTaskOnUnitDestroyed(const Unit &unit) {
    // Return as soon as the first build task can identify the destroyed unit.
    for (auto &buildTask : m_buildQueue) {
        if (buildTask.onUnitDestroyed(unit))
            return;
    }
}

void Manager::buildTaskOnUnitCompleted(const Unit &) {
    // Since BuildTasks are busy waiting for completion right now, this is unused.
}

int Manager::getAvailableMinerals() const {
    return BWAPI::Broodwar->self()->minerals() - m_reservedMinerals;
}

int Manager::getAvailableGas() const { return BWAPI::Broodwar->self()->gas() - m_reservedGas; }

bool Manager::acquireResources(int minerals, int gas, BuildTask::Priority priority) {
    // All higher tasks have to have their resources allocated, otherwise fail!
    for (auto it = m_buildQueue.begin(); it != m_buildQueue.end() && it->getPriority() > priority;
         ++it) {
        if (it->getState() <= BuildTask::State::acquireResources)
            return false;
    }

    // Allocate resources if available.
    if (getAvailableMinerals() >= minerals && getAvailableGas() >= gas) {
        m_reservedMinerals += minerals;
        m_reservedGas += gas;
        return true;
    }
    return false;
}

void Manager::releaseResources(int minerals, int gas) {
    m_reservedMinerals -= minerals;
    m_reservedGas -= gas;
    assert(m_reservedMinerals >= 0);
    assert(m_reservedGas >= 0);
}

Unit Manager::acquireWorker(const UnitType &workerType, const Position &nearPosition) {
    // Search for matching workers and remember their bases.
    std::vector<std::pair<Unit, Base *>> workers;
    for (auto &base : m_bases) {
        const auto worker = base.findWorker(workerType, nearPosition);
        if (worker != nullptr)
            workers.emplace_back(worker, &base);
    }

    if (workers.empty()) {
        // No worker found.
        return nullptr;
    }

    // Pick best candidate...
    const auto closestWorker = std::min_element(
        workers.begin(), workers.end(), [&nearPosition](const auto &a, const auto &b) {
            return distance(nearPosition, a.first->getPosition()) <
                   distance(nearPosition, b.first->getPosition());
        });

    // ...and take ownership explicitly!
    closestWorker->second->takeOwnership(closestWorker->first);
    m_workers.push_back(closestWorker->first);
    return closestWorker->first;
}

void Manager::releaseWorker(const Unit &worker) {
    m_workers.erase(std::remove(m_workers.begin(), m_workers.end(), worker), m_workers.end());

    // Pass ownership back to bases
    giveOwnership(worker);
}

} // namespace


text:
<?php
/**
 * Elgg garbage collector.
 *
 * @package ElggGarbageCollector
 */

elgg_register_event_handler('init', 'system', 'garbagecollector_init');

function garbagecollector_init() {
	$period = elgg_get_plugin_setting('period', 'garbagecollector');
	switch ($period) {
		case 'weekly':
		case 'monthly':
		case 'yearly':
			break;
		default:
			$period = 'monthly';
	}

	// Register cron hook
	elgg_register_plugin_hook_handler('cron', $period, 'garbagecollector_cron');

	elgg_register_plugin_hook_handler('gc', 'system', 'garbagecollector_orphaned_metastrings');
	elgg_register_plugin_hook_handler('gc', 'system', 'garbagecollector_entities');
}

/**
 * Cron job
 */
function garbagecollector_cron($hook, $entity_type, $returnvalue, $params) {

	echo elgg_echo('garbagecollector') . "\n";

	// Now, because we are nice, trigger a plugin hook to let other plugins do some GC
	$rv = true;
	$period = elgg_get_plugin_setting('period','garbagecollector');
	elgg_trigger_plugin_hook('gc', 'system', array('period' => $period));

	// Now we optimize all tables
	$tables = garbagecollector_get_tables();
	foreach ($tables as $table) {
		echo elgg_echo('garbagecollector:optimize', array($table));

		if (garbagecollector_optimize_table($table) !== false) {
			echo elgg_echo('garbagecollector:ok');
		} else {
			echo elgg_echo('garbagecollector:error');
		}

		echo "\n";
	}

	echo elgg_echo('garbagecollector:done');
}

/**
 * Get array of table names
 *
 * @return array
 */
function garbagecollector_get_tables() {
	static $tables;

	if (isset($tables)) {
		return $tables;
	}

	$table_prefix = elgg_get_config('dbprefix');
	$result = get_data("SHOW TABLES LIKE '$table_prefix%'");

	$tables = array();
	if (is_array($result) && !empty($result)) {
		foreach ($result as $row) {
			$row = (array) $row;
			if (is_array($row) && !empty($row)) {
				foreach ($row as $element) {
					$tables[] = $element;
				}
			}
		}
	}

	return $tables;
}

/**
 * Optimize a table
 *
 * @param string $table Database table name
 * @return bool
 */
function garbagecollector_optimize_table($table) {
	$table = sanitise_string($table);
	return update_data("OPTIMIZE TABLE $table");
}

/**
 * Garbage collect stub and fragments from any broken delete/create calls
 *
 * @return void
 */
function garbagecollector_entities() {
	$dbprefix = elgg_get_config('dbprefix');

	$tables = array(
		'site' => 'sites_entity',
		'object' => 'objects_entity',
		'group' => 'groups_entity',
		'user' => 'users_entity',
	);

	foreach ($tables as $type => $table) {
		delete_data("DELETE FROM {$dbprefix}{$table}
		WHERE guid NOT IN (SELECT guid FROM {$dbprefix}entities)");
		delete_data("DELETE FROM {$dbprefix}entities
		WHERE type = '$type' AND guid NOT IN (SELECT guid FROM {$dbprefix}{$table})");
	}
}

/**
 * Delete any orphaned entries in metastrings.
 *
 * @return void
 */
function garbagecollector_orphaned_metastrings() {
	$dbprefix = elgg_get_config('dbprefix');

	// Garbage collect metastrings
	echo elgg_echo('garbagecollector:gc:metastrings');

	// If memcache is enabled then we need to flush it of deleted values
	if (is_memcache_available()) {
		$select_query = "
		SELECT * FROM {$dbprefix}metastrings WHERE
		(
			(id NOT IN (SELECT name_id FROM {$dbprefix}metadata)) AND
			(id NOT IN (SELECT value_id FROM {$dbprefix}metadata)) AND
			(id NOT IN (SELECT name_id FROM {$dbprefix}annotations)) AND
			(id NOT IN (SELECT value_id FROM {$dbprefix}annotations))
		)";

		$dead = get_data($select_query);
		if ($dead) {
			static $metastrings_memcache;

			if (!$metastrings_memcache) {
				$metastrings_memcache = new \ElggMemcache('metastrings_memcache');
			}

			foreach ($dead as $d) {
				$metastrings_memcache->delete($d->string);
			}
		}
	}

	$query = "
		DELETE FROM {$dbprefix}metastrings WHERE
		(
			(id NOT IN (SELECT name_id FROM {$dbprefix}metadata)) AND
			(id NOT IN (SELECT value_id FROM {$dbprefix}metadata)) AND
			(id NOT IN (SELECT name_id FROM {$dbprefix}annotations)) AND
			(id NOT IN (SELECT value_id FROM {$dbprefix}annotations))
		)";

	$result = delete_data($query);

	if ($result !== false) {
		echo elgg_echo('garbagecollector:ok');
	} else {
		echo elgg_echo('garbagecollector:error');
	}
}


text:
require 'rubygems'
require 'test/unit'
require 'shoulda'
begin require 'redgreen'; rescue LoadError; end
require 'open3'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
Dir[File.join(File.dirname(__FILE__), "shoulda_macros", "*.rb")].each {|f| require f}
ENV['NO_COLOR'] = "true"

require 'git-style-binary'
GitStyleBinary.run = true

class Test::Unit::TestCase
  def fixtures_dir
    File.join(File.dirname(__FILE__), "fixtures")
  end
end

module RunsBinaryFixtures
  # run the specified cmd returning the string values of [stdout,stderr]
  def bin(cmd)
    stdin, stdout, stderr = Open3.popen3("#{fixtures_dir}/#{cmd}")
    [stdout.read, stderr.read]
  end
end


text:
package com.tom.storage.block;

import net.minecraft.world.World;

import com.tom.handler.GuiHandler.GuiIDs;
import com.tom.storage.tileentity.TileEntityBasicTerminal;

public class BasicTerminal extends BlockTerminalBase {
	@Override
	public TileEntityBasicTerminal createNewTileEntity(World worldIn, int meta) {
		return new TileEntityBasicTerminal();
	}

	@Override
	public int getGuiID() {
		return GuiIDs.basicTerminalBlock.ordinal();
	}

	@Override
	public String getName() {
		return "Basic Terminal";
	}

	@Override
	public boolean hasCustomFront() {
		return false;
	}

	@Override
	public int[][][] getImageIDs() {
		return new int[][][]{{{1, 0, -30}, {2, 0, -10}, {3, 0, 0}}, {{1, 0, -30}, {2, 0, -100}, {3, 0, -20}, {4, 0, -10}, {-1}, {6, 0}, {7}}};
	}

	@Override
	public String getCategory() {
		return "basic";
	}
}


text:
<?php

namespace Aedart\Model\Contracts\Strings;

/**
 *
Start Date Aware

 *
 * Component is aware of a string "start date" value, which can
 * also be specified.
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Model\Contracts\Strings
 */
interface StartDateAware
{
    /**
     * Set start date
     *
     * @param string|null $date Start date of event
     *
     * @return self
     */
    public function setStartDate(?string $date);

    /**
     * Get start date
     *
     * If no "start date" value has been set, this method will
     * set and return a default "start date" value,
     * if any such value is available
     *
     * @see getDefaultStartDate()
     *
     * @return string|null start date or null if no start date has been set
     */
    public function getStartDate() : ?string ;

    /**
     * Check if "start date" has been set
     *
     * @return bool True if "start date" has been set, false if not
     */
    public function hasStartDate() : bool;

    /**
     * Get a default "start date" value, if any is available
     *
     * @return string|null Default "start date" value or null if no default value is available
     */
    public function getDefaultStartDate() : ?string;
}


text:
#include "config.h"

#if ENABLE(WML)
#include "WMLAccessElement.h"

#include "Attribute.h"
#include "WMLDocument.h"
#include "WMLNames.h"
#include "WMLVariables.h"

namespace WebCore {

using namespace WMLNames;

WMLAccessElement::WMLAccessElement(const QualifiedName& tagName, Document* doc)
    : WMLElement(tagName, doc)
{
}

PassRefPtr<WMLAccessElement> WMLAccessElement::create(const QualifiedName& tagName, Document* document)
{
    return adoptRef(new WMLAccessElement(tagName, document));
}

void WMLAccessElement::parseMappedAttribute(Attribute* attr)
{
    if (attr->name() == domainAttr) {
        String value = parseValueForbiddingVariableReferences(attr->value());
        if (value.isEmpty())
            return;

        m_domain = value;
    } else if (attr->name() == pathAttr) {
        String value = parseValueForbiddingVariableReferences(attr->value());
        if (value.isEmpty())
            return;

        m_path = value;
    } else
        WMLElement::parseMappedAttribute(attr);
}

void WMLAccessElement::insertedIntoDocument()
{
    WMLElement::insertedIntoDocument();

    WMLPageState* pageState = wmlPageStateForDocument(document());
    if (!pageState || pageState->processAccessControlData(m_domain, m_path))
        return;

    pageState->resetAccessControlData();
    reportWMLError(document(), WMLErrorMultipleAccessElements);
}

}

#endif


text:
layout: post
comments: true
title: Macroeconomics, Introduction
---

* **Macroeconomics** is concerned with the behavior of the economy as a whole---with booms and recessions, the economy's total output of goods and services, the growth of output, the rates of inflation and development, et cetera. In brief, macroeconomics deals with major economic issues and problems of the day.
* The study of macroeconomics is organized around three models that describe the world, each model having its greatest applicability in a different time frame.
  * The **very-long run** behaviour of the economy is the domain of growth theory, which focuses on the *growth of the economy's capacity to produce goods and services*.
	* This model focuses on historical accumulation of capital and improvements in technology.
  * In a **long-run** model, we take a snapshot of very-long run model.
	* We assume that *the capital stock and the level of technology remains fixed.* Fixed capital and technology determine the production capacity of the economy and this capacity is known as **potential output**.
	* In long run, the supply of goods and services equals potential output and the prices and inflation are determined by fluctuations in demand.
  * In **short run**, fluctuations in demand determine how much of the available capacity is used and thus the level of output and unemployment.
	* In contrast to long run, in short-run, *prices are relatively fixed and output is a variable.*
* There are various opinions among Economists on what should be chosen as the time frame for each step.

### Very long run growth

* We ignore recessions and booms are related short-run fluctuations in employments of people and other resources. This is proper since over a large time span, these tend to average.

*The economy with fixed productive capacity*

* The **aggregate supply curve** depicts, for each given price level, the quantity of output firms are willing to supply. The level of aggregate supply is the amount of output the economy can produce given the resources and technology available.
  * The position of the aggregate supply curve depends on the productive capacity of the economy.
* The **aggregate demand curve** depicts, for each given price level, the level of output at which the goods market and money market are simultaneously in equilibrium. The level of aggregate demand is the total demand for goods to consume, for new investment, for goods purchased by the government, and for net goods to be exported abroad.
  * The position of the aggregate demand curve depicts on monetary and fiscal policy and also on consumer confidence.

* **In long run, the aggregate supply curve is vertical**.
* **In the long run, the output is determined by aggregate supply alone and prices are determined by both aggregate supply and aggregate demand**.
* **Very high inflation rates---episodes of rapid increases in overall price level---are always due to changes in aggregate demand**.

### Short Run

* In a short run, **the aggregate supply curve is flat**.
* Thus the prices remain fixed. Output, in contrast, can take any value. The underlying assumption is that the level of output does not affect the price level.
* We study aggregate demand because, in the short run aggregate demand determines the output and therefore unemployment.

### Medium Run

* The medium run represents the situation in which transition between long run and short run happens.

### Growth and GDP

* The **growth rate** of an economy is the rate at which the gross domestic product (GDP) is increasing.
* The GDP can grow for the following reasons
  1. The available amount of resources in the economy changes. Principal resources are capital and labour. The capital consists of things like buildings and machines.
  2. The efficiency of factors of production changes. Efficiency improvements are called *productivity increases*. Productivity increases results from changes in knowledge, people learning through experience, et cetera.

* Huge inflations have one cause: great outward sweeps of the aggregate demand curve caused by the government's printing of too much money.
* Big changes over short life spans in the level of economic activity and thus unemployment is explained by short-run aggregate supply-aggregate demand model.

### Business cycle and output graph

* The **business cycle** is more or less regular pattern of expansion (recovery) and contraction (recession) in economic activity around the path of trend growth.
* The **trend path** of the GDP is the path GDP would take if factors of production were fully employed.
* In economic terms, there is full employment of labor when everyone who wants a job can find one within reasonable amount of time.
* The **output gap** measures the gap between actual output and the output the economy would produce at full employment given the existing resources. Full employment is also called potential output. Output gap $\equiv$ Actual output $-$ Potential output.


text:
goog.provide('gmf.TreeManager');

goog.require('gmf');
goog.require('gmf.Themes');
goog.require('ngeo.Notification');
goog.require('ngeo.StateManager');
goog.require('ngeo.LayertreeController');

/**
 * Manage a tree with children. This service can be used in mode 'flush'
 * (default) or not (mode 'add'). In mode 'flush', each theme, group or group
 * by layer that you add will replace the previous children's array. In mode
 * 'add', children will be just pushed in this array. The default state can be
 * changed by setting the value `gmfTreeManagerModeFlush`, e.g.:
 *
 *     var module = angular.module('app');
 *     module.value('gmfTreeManagerModeFlush', false);
 *
 * This service's theme is a GmfTheme with only children and a name.
 * Thought to be the tree source of the gmf layertree directive.
 * @constructor
 * @struct
 * @param {angular.$timeout} $timeout Angular timeout service.
 * @param {angularGettext.Catalog} gettextCatalog Gettext catalog.
 * @param {ngeo.LayerHelper} ngeoLayerHelper Ngeo Layer Helper.
 * @param {ngeo.Notification} ngeoNotification Ngeo notification service.
 * @param {gmf.Themes} gmfThemes gmf Themes service.
 * @param {ngeo.StateManager} ngeoStateManager The ngeo StateManager service.
 * @ngInject
 * @ngdoc service
 * @ngname gmfTreeManager
 */
gmf.TreeManager = function($timeout, gettextCatalog, ngeoLayerHelper,
    ngeoNotification, gmfThemes, ngeoStateManager) {

  /**
   * @type {angular.$timeout}
   * @private
   */
  this.$timeout_ = $timeout;

  /**
   * @type {angularGettext.Catalog}
   * @private
   */
  this.gettextCatalog_ = gettextCatalog;

  /**
   * @type {ngeo.LayerHelper}
   * @private
   */
  this.layerHelper_ = ngeoLayerHelper;

  /**
   * @type {ngeo.Notification}
   * @private
   */
  this.ngeoNotification_ = ngeoNotification;

  /**
   * @type {gmf.Themes}
   * @private
   */
  this.gmfThemes_ = gmfThemes;

  this.root = /** @type {gmfThemes.GmfRootNode} */ ({
    children: []
  });

  /**
   * The controller of the (unique) root layer tree.
   * The array of top level layer trees is avaible through `rootCtrl.children`.
   * @type {ngeo.LayertreeController}
   * @export
   */
  this.rootCtrl = null;

  /**
   * Number of groups to add to the layertree during one single Angular
   * digest loop.
   * @type {number}
   * @public
   */
  this.numberOfGroupsToAddInThisDigestLoop = 0;

  /**
   * @type {Array.<gmfThemes.GmfGroup>}
   * @private
   */
  this.groupsToAddInThisDigestLoop_ = [];

  /**
   * @type {angular.$q.Promise}
   * @private
   */
  this.promiseForGroupsToAddInThisDigestLoop_ = null;

  /**
   * @type {ngeo.StateManager}
   * @private
   */
  this.ngeoStateManager_ = ngeoStateManager;

  /**
   * A reference to the OGC servers loaded by the theme service.
   * @type {gmfThemes.GmfOgcServers}
   * @private
   */
  this.ogcServers_ = null;

  ol.events.listen(
    this.gmfThemes_,
    gmf.ThemesEventType.CHANGE,
    this.handleThemesChange_,
    this
  );
};

/**
 * Called when the themes change. Get the OGC servers, then listen to the
 * tree manager Layertree controllers array changes.
 * @private
 */
gmf.TreeManager.prototype.handleThemesChange_ = function() {
  this.gmfThemes_.getOgcServersObject().then(function(ogcServers) {
    this.ogcServers_ = ogcServers;
  }.bind(this));
};

/**
 * Set some groups as tree's children. If the service use mode 'flush', the
 * previous tree's children will be removed. Add only groups that are not
 * already in the tree.
 * @param{Array.<gmfThemes.GmfGroup>} firstLevelGroups An array of gmf theme group.
 * @return{boolean} True if the group has been added. False otherwise.
 * @export
 */
gmf.TreeManager.prototype.setFirstLevelGroups = function(firstLevelGroups) {
  this.root.children.length = 0;
  this.ngeoStateManager_.deleteParam(gmf.PermalinkParam.TREE_GROUPS);
  return this.addFirstLevelGroups(firstLevelGroups);
};

/**
 * Add some groups as tree's children. If the service use mode 'flush', the
 * previous tree's children will be removed. Add only groups that are not
 * already in the tree.
 * @param {Array.<gmfThemes.GmfGroup>} firstLevelGroups An array of gmf theme
 *     group.
 * @param {boolean=} opt_add if true, force to use the 'add' mode this time.
 * @param {boolean=} opt_silent if true notifyCantAddGroups_ is not called.
 * @return{boolean} True if the group has been added. False otherwise.
 * @export
 */
gmf.TreeManager.prototype.addFirstLevelGroups = function(firstLevelGroups,
    opt_add, opt_silent) {
  var groupNotAdded = [];

  firstLevelGroups.slice().reverse().forEach(function(group) {
    if (!this.addFirstLevelGroup_(group)) {
      groupNotAdded.push(group);
    }
  }.bind(this));
  if (groupNotAdded.length > 0 && !opt_silent) {
    this.notifyCantAddGroups_(groupNotAdded);
  }

  return groupNotAdded.length === 0;
};

/**
 * Update the application state with the list of first level groups in the tree
 * @param {Array.<gmfThemes.GmfGroup>} groups firstlevel groups of the tree
 * @private
 */
gmf.TreeManager.prototype.updateTreeGroupsState_ = function(groups) {
  var treeGroupsParam = {};
  treeGroupsParam[gmf.PermalinkParam.TREE_GROUPS] = groups.map(function(node) {
    return node.name;
  }).join(',');
  this.ngeoStateManager_.updateState(treeGroupsParam);
};

/**
 * Add a group as tree's children without consideration of this service 'mode'.
 * Add it only if it's not already in the tree.
 * @param {gmfThemes.GmfGroup} group The group to add.
 * @return {boolean} true if the group has been added.
 * @private
 */
gmf.TreeManager.prototype.addFirstLevelGroup_ = function(group) {
  var alreadyAdded = false;
  var groupID = group.id;
  this.root.children.some(function(rootChild) {
    if (groupID === rootChild.id) {
      return alreadyAdded = true;
    }
  }, this);
  this.groupsToAddInThisDigestLoop_.some(function(grp) {
    if (groupID === grp.id) {
      return alreadyAdded = true;
    }
  }, this);
  if (alreadyAdded) {
    return false;
  }

  // Add groups in the list of groups to add and be sure that the counter of
  // groups to add is reset.
  this.groupsToAddInThisDigestLoop_.push(group);
  this.numberOfGroupsToAddInThisDigestLoop = 0;

  // Delete previous timeout promise if it exists to do this action only once.
  if (this.promiseForGroupsToAddInThisDigestLoop_ !== null) {
    this.$timeout_.cancel(this.promiseForGroupsToAddInThisDigestLoop_);
  }

  // Add the groups only when there is no more group to come during this digest
  // loop. The purpose of this is to preserve a consistent order between the
  // layertree (generated by a template) and the layers in the map.
  this.promiseForGroupsToAddInThisDigestLoop_ = this.$timeout_(function() {
    // Set the number of group to add.
    this.numberOfGroupsToAddInThisDigestLoop = this.groupsToAddInThisDigestLoop_.length;
    // Add each first-level-groups.
    this.groupsToAddInThisDigestLoop_.forEach(function(grp) {
      this.root.children.unshift(grp);
    }, this);
    //Update the permalink
    this.updateTreeGroupsState_(this.root.children);
    // Reset the groups and the promise state. Don't reset the
    // numberOfGroupsToAddInThisDigestLoop, it must persist because the layers
    // will be added into the map after that the layertree template is
    // generated (so in the next angular loop).
    this.groupsToAddInThisDigestLoop_.length = 0;
    this.promiseForGroupsToAddInThisDigestLoop_ = null;
  }.bind(this));

  return true;
};

/**
 * Retrieve a group (first found) by its name and add in the tree. Do nothing
 * if any corresponding group is found.
 * @param {string} groupName Name of the group to add.
 * @param {boolean=} opt_add if true, force to use the 'add' mode this time.
 * @export
 */
gmf.TreeManager.prototype.addGroupByName = function(groupName, opt_add) {
  this.gmfThemes_.getThemesObject().then(function(themes) {
    var group = gmf.Themes.findGroupByName(themes, groupName);
    if (group) {
      this.addFirstLevelGroups([group], opt_add, false);
    }
  }.bind(this));
};

/**
 * Retrieve a group by the name of a layer that is contained in this group
 * (first found). This group will be added in the tree. Do nothing if any
 * corresponding group is found.
 * @param {string} layerName Name of the layer inside the group to add.
 * @param {boolean=} opt_add if true, force to use the 'add' mode this time.
 * @param {boolean=} opt_silent if true notifyCantAddGroups_ is not called
 * @export
 */
gmf.TreeManager.prototype.addGroupByLayerName = function(layerName, opt_add, opt_silent) {
  this.gmfThemes_.getThemesObject().then(function(themes) {
    var group = gmf.Themes.findGroupByLayerNodeName(themes, layerName);
    if (group) {
      var groupAdded = this.addFirstLevelGroups([group], opt_add, opt_silent);
      this.$timeout_(function() {
        var treeCtrl = this.getTreeCtrlByNodeId(group.id);
        if (!treeCtrl) {
          console.warn('Tree controler not found, unable to add the group');
          return;
        }
        var treeCtrlToActive;
        treeCtrl.traverseDepthFirst(function(treeCtrl) {
          if (treeCtrl.node.name === layerName) {
            treeCtrlToActive = treeCtrl;
            return ngeo.LayertreeController.VisitorDecision.STOP;
          }
        });

        // Deactive all layers in the group if it's not in the tree.
        if (groupAdded)  {
          treeCtrl.setState('off');
        }

        // Active it.
        if (treeCtrlToActive) {
          treeCtrlToActive.setState('on');
        }
      }.bind(this));
    }
  }.bind(this));
};

/**
 * Remove a group from this tree's children. The first group that is found (
 * based on its name) will be removed. If any is found, nothing will append.
 * @param {gmfThemes.GmfGroup} group The group to remove.
 * @export
 */
gmf.TreeManager.prototype.removeGroup = function(group) {
  var children = this.root.children;
  var index = 0, found = false;
  children.some(function(child) {
    if (child.name === group.name) {
      return found = true;
    }
    index++;
  }.bind(this));
  if (found) {
    children.splice(index, 1);
    this.updateTreeGroupsState_(children);
  }
};

/**
 * Remove all groups.
 * @export
 */
gmf.TreeManager.prototype.removeAll = function() {
  while (this.root.children.length) {
    this.removeGroup(this.root.children[0]);
  }
};

/**
 * Clone a group node and recursively set all child node `isChecked` using
 * the given list of layer names.
 * @param {gmfThemes.GmfGroup} group The original group node.
 * @param {Array.<string>} names Array of node names to check (i.e. that
 *     should have their checkbox checked)
 * @return {gmfThemes.GmfGroup} Cloned node.
 * @private
 */
gmf.TreeManager.prototype.cloneGroupNode_ = function(group, names) {
  var clone = /** @type {gmfThemes.GmfGroup} */ (goog.object.unsafeClone(group));
  this.toggleNodeCheck_(clone, names);
  return clone;
};

/**
 * Set the child nodes metadata `isChecked` if its name is among the list of
 * given names. If a child node also has children, check those instead.
 * @param {gmfThemes.GmfGroup|gmfThemes.GmfLayer} node The original node.
 * @param {Array.<string>} names Array of node names to check (i.e. that
 *     should have their checkbox checked)
 * @private
 */
gmf.TreeManager.prototype.toggleNodeCheck_ = function(node, names) {
  if (!node.children) {
    return;
  }
  node.children.forEach(function(childNode) {
    if (childNode.children) {
      this.toggleNodeCheck_(childNode, names);
    } else if (childNode.metadata) {
      childNode.metadata.isChecked = ol.array.includes(names, childNode.name);
    }
  }, this);
};

/**
 * Display a notification that informs that the given groups are already in the
 * tree.
 * @param {Array.<gmfThemes.GmfGroup>} groups An array of groups that already in
 *   the tree.
 * @private
 */
gmf.TreeManager.prototype.notifyCantAddGroups_ = function(groups) {
  var names = [];
  var gettextCatalog = this.gettextCatalog_;
  groups.forEach(function(group) {
    names.push(group.name);
  });
  var msg = (names.length < 2) ?
      gettextCatalog.getString('group is already loaded.') :
      gettextCatalog.getString('groups are already loaded.');
  this.ngeoNotification_.notify({
    msg: names.join(', ') + ' ' + msg,
    type: ngeo.MessageType.INFORMATION
  });
};

/**
 * Get a treeCtrl based on it's node id.
 * @param {number} id the id of a GMFThemesGroup or a GMFThemesLeaf.
 * @return {ngeo.LayertreeController?} treeCtrl The associated controller or null.
 * @public
 */
gmf.TreeManager.prototype.getTreeCtrlByNodeId = function(id) {
  var correspondingTreeCtrl = null;
  if (this.rootCtrl && this.rootCtrl.traverseDepthFirst) {
    this.rootCtrl.traverseDepthFirst(function(treeCtrl) {
      if (treeCtrl.node.id === id) {
        correspondingTreeCtrl = treeCtrl;
        return ngeo.LayertreeController.VisitorDecision.STOP;
      }
    });
  }
  return correspondingTreeCtrl;
};

/**
 * Get the OGC server.
 * @param {ngeo.LayertreeController} treeCtrl ngeo layertree controller, from
 *     the current node.
 * @return {gmfThemes.GmfOgcServer} The OGC server.
 */
gmf.TreeManager.prototype.getOgcServer = function(treeCtrl) {
  if (treeCtrl.parent.node.mixed) {
    var gmfLayerWMS = /** @type {gmfThemes.GmfLayerWMS} */ (treeCtrl.node);
    goog.asserts.assert(gmfLayerWMS.ogcServer);
    return this.ogcServers_[gmfLayerWMS.ogcServer];
  } else {
    var firstLevelGroupCtrl = treeCtrl;
    while (!firstLevelGroupCtrl.parent.isRoot) {
      firstLevelGroupCtrl = firstLevelGroupCtrl.parent;
    }
    var gmfGroup = /** @type {gmfThemes.GmfGroup} */ (firstLevelGroupCtrl.node);
    goog.asserts.assert(gmfGroup.ogcServer);
    return this.ogcServers_[gmfGroup.ogcServer];
  }
};

gmf.module.service('gmfTreeManager', gmf.TreeManager);


text:
<?php

namespace ClassPreloader;

use Symfony\Component\Finder\Finder;
use Symfony\Component\Console\Application as BaseApplication;

/**
 * ClassPreloader application CLI
 */
class Application extends BaseApplication
{
    public function __construct()
    {
	parent::__construct('ClassPreloader');

	// Create a finder to find each non-abstract command in the filesystem
	$finder = new Finder();
	$finder->files()
	    ->in(__DIR__ . '/Command')
	    ->notName('Abstract*')
	    ->name('*.php');

	// Add each command to the CLI
	foreach ($finder as $file) {
	    $filename = str_replace('\\', '/', $file->getRealpath());
	    $pos = strrpos($filename, '/ClassPreloader/') + strlen('/ClassPreloader/');
	    $class = __NAMESPACE__ . '\\'
		. substr(str_replace('/', '\\', substr($filename, $pos)), 0, -4);
	    $this->add(new $class());
	}
    }
}


text:
using System;
using System.Collections.Generic;
using Zenject;
using ModestTree;
using ModestTree.Util;

namespace Zenject
{
    public class DisposablePrioritiesInstaller : Installer
    {
        List<Type> _disposables;

        public DisposablePrioritiesInstaller(List<Type> disposables)
        {
            _disposables = disposables;
        }

        public override void InstallBindings()
        {
            // All disposables without explicit priorities assigned are given priority of zero,
            // so put all of these before that (ie. negative)
            int priorityCount = -1 * _disposables.Count;

            foreach (var disposableType in _disposables)
            {
                BindPriority(Container, disposableType, priorityCount);
                priorityCount++;
            }
        }

        public static void BindPriority<T>(
            DiContainer container, int priorityCount)
            where T : IDisposable
        {
            BindPriority(container, typeof(T), priorityCount);
        }

        public static void BindPriority(
            DiContainer container, Type disposableType, int priorityCount)
        {
            Assert.That(disposableType.DerivesFrom<IDisposable>(),
                "Expected type '{0}' to derive from IDisposable", disposableType.Name());

            container.Bind<ModestTree.Util.Tuple<Type, int>>().ToInstance(
                ModestTree.Util.Tuple.New(disposableType, priorityCount)).WhenInjectedInto<DisposableManager>();
        }
    }
}


text:
@interface AsyncUIImage : UIImage

@property(weak) ComExampleAndroidDisplayingbitmapsUtilImageWorker_BitmapWorkerTask *bitmapWorkerTask;

- (instancetype)initWithCGImage:(CGImageRef)cgImage scale:(CGFloat)scale orientation:(UIImageOrientation)orientation;

@end

@implementation AsyncUIImage

- (instancetype)initWithCGImage:(CGImageRef)cgImage scale:(CGFloat)scale orientation:(UIImageOrientation)orientation
{
    if (cgImage != nil) {
        self = [super initWithCGImage:cgImage scale:scale orientation:orientation];
    } else {
        self = [super init];
    }

    return self;
}

@end

@interface J2OImageView()

@property (nonatomic, weak) UIImageView *imageView;

@end

@implementation J2OImageView

- (id) initWithImageView:(UIImageView *)imageView
{
    self = [super init];
    if (self != nil) {
        _imageView = imageView;
    }

    return self;
}

- (jboolean)hasOwner
{
    return self.imageView != nil;
}

- (void)setImageDrawableWithComExampleAndroidDisplayingbitmapsUtilAbstractBitmapDrawable:(id<ComExampleAndroidDisplayingbitmapsUtilAbstractBitmapDrawable>)d
{
    if (![d isKindOfClass:[J2OBitmapDrawable class]]) {
        return;
    }
    if (self.imageView == nil) {
        return;
    }

    J2OBitmapDrawable *bitmapDrawable = (J2OBitmapDrawable *)d;
    [self.imageView setImage:[bitmapDrawable image]];
}

- (void)setFadeInImageDrawableWithComExampleAndroidDisplayingbitmapsUtilAbstractBitmap:(id<ComExampleAndroidDisplayingbitmapsUtilAbstractBitmap>)from
                      withComExampleAndroidDisplayingbitmapsUtilAbstractBitmapDrawable:(id<ComExampleAndroidDisplayingbitmapsUtilAbstractBitmapDrawable>)to
                                                                               withInt:(jint)durationMillis
{
    if (self.imageView == nil) {
        return;
    }

    if (![from isKindOfClass:[J2OBitmap class]]) {
        return;
    }

    if (![to isKindOfClass:[J2OBitmapDrawable class]]) {
        return;
    }

    J2OBitmap *fromBitmap = (J2OBitmap *)from;
    J2OBitmapDrawable *toBitmapDrawable = (J2OBitmapDrawable *)to;

    [self.imageView setImage:fromBitmap.image];
    [UIView transitionWithView:self.imageView
                      duration:(double)durationMillis / 1000
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                        [self.imageView setImage:toBitmapDrawable.image];
                    } completion:nil];
}

- (void)setAsyncDrawableWithComExampleAndroidDisplayingbitmapsUtilAbstractBitmap:(id<ComExampleAndroidDisplayingbitmapsUtilAbstractBitmap>)loadingBitmap
          withComExampleAndroidDisplayingbitmapsUtilImageWorker_BitmapWorkerTask:(ComExampleAndroidDisplayingbitmapsUtilImageWorker_BitmapWorkerTask *)bitmapWorkerTask
{
    if (self.imageView == nil) {
        return;
    }

    UIImage *uiImage;
    if (loadingBitmap != nil) {
        if(![loadingBitmap isKindOfClass:[J2OBitmap class]]) {
            return;
        }
        uiImage = ((J2OBitmap *)loadingBitmap).image;
    } else {
        uiImage = nil;
    }

    AsyncUIImage *asyncImage = [[AsyncUIImage alloc] initWithCGImage:uiImage.CGImage
                                                              scale:1.0
                                                        orientation:uiImage.imageOrientation];
    asyncImage.bitmapWorkerTask = bitmapWorkerTask;

    self.imageView.image = asyncImage;
}

- (ComExampleAndroidDisplayingbitmapsUtilImageWorker_BitmapWorkerTask *)getBitmapWorkerTask
{
    if (self.imageView == nil) {
        return nil;
    }

    UIImage *image = self.imageView.image;
    if (image == nil  || ![image isKindOfClass:[AsyncUIImage class]]) {
        return nil;
    }

    AsyncUIImage *asyncImage = (AsyncUIImage *)image;

    return asyncImage.bitmapWorkerTask;
}

@end


text:
Faça seu Cadastro

    <form ng-submit="gravar()">

                    Nome
                    <input type="text" class="form-control" id="Name" placeholder="Seu Nome Completo" ng-model="nome" required>

                    Email
                    <input type="email" class="form-control" id="Email" placeholder="Email@exemplo.com" ng-model="email" required>

                    Senha
                    <input type="password" class="form-control" id="Passowrd" placeholder="Senha" ng-model="senha" required>

                    Confirmar Senha
                    <input type="password" class="form-control" id="ConfirmPassword" placeholder="Senha" ng-model="confirmaSenha" required>

                    Numero de Matricula
                    <input type="password" class="form-control" id="numMatricula" placeholder="Ex: 0123456" ng-model="matricula" required>

                <select id="tipo" class="form-control" required>
                    <option> </option>
                    <option>Aluno</option>
                    <option>Secretaria</option>
                    <option>Administrador</option>
                </select>

        <button type="submit" class="btn btn-default">Ok</button>

    </form>


text:
var bindings = require('./bindings');

var Element = require('./element');

/// Create a new document
/// @param {string} version xml version, default 1.0
/// @param {string} encoding the encoding, default utf8
/// @constructor
var Document = function(version, encoding) {
    version = version || '1.0';
    var doc = new bindings.Document(version);
    doc.encoding(encoding || 'utf8');
    return doc;
};

Document.prototype = bindings.Document.prototype;

/// get or set the root element
/// if called without any arguments, this will return the document root
/// @param {Element} [elem] if specified, this will become the new document root
Document.prototype.root = function(elem) {
    return this._root(elem);
};

/// add a child node to the document
/// this will set the document root
Document.prototype.node = function(name, content) {
    return this.root(Element(this, name, content));
};

/// xpath search
/// @return array of matching elements
Document.prototype.find = function(xpath, ns_uri) {
    return this.root().find(xpath, ns_uri);
};

/// xpath search
/// @return first element matching
Document.prototype.get = function(xpath, ns_uri) {
    return this.find(xpath, ns_uri)[0];
};

/// @return a given child
Document.prototype.child = function(id) {
    if (id === undefined || typeof id !== 'number') {
        throw new Error('id argument required for #child');
    }
    return this.root().child(id);
};

/// @return an Array of child nodes of the document root
Document.prototype.childNodes = function() {
    return this.root().childNodes();
};

/// @return a string representation of the document
Document.prototype.toString = function() {
    return this._toString();
}

/// @return the document version
Document.prototype.version = function() {
    return this._version();
}

/// @return the document encoding
Document.prototype.encoding = function(encoding) {
    return this._encoding(encoding);
}

module.exports = Document;

/// parse a string into a html document
/// @param string html string to parse
/// @return a Document
module.exports.fromHtmlString = function(string) {
    return bindings.fromHtmlString(string);
}

/// parse a string into a xml document
/// @param string xml string to parse
/// @return a Document
module.exports.fromXmlString = function(string) {
    return bindings.fromXmlString(string);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <title>groovy.model</title>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="keywords" CONTENT="groovy/model package">

    <link href="groovy.ico" type="image/x-icon" rel="shortcut icon">
    <link href="groovy.ico" type="image/x-icon" rel="icon">
    <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

    groovy.model

Interfaces

NestedValueModel

ValueModel

Classes

ClosureModel

DefaultTableColumn

DefaultTableModel

DefaultTableModel.MyTableColumnModel

FormModel

PropertyModel

ValueHolder


text:
"""
General exceptions that are generally useful for all/most Nommer sub-classes.
"""
class NommerException(Exception):
    """
    A generic Nommer-related exception. Try to be more specific in your code,
    just use this as a parent class.
    """
    def __init__(self, message):
        self.message = message

    def __str__(self):
        return repr(self.message)


text:
"""
homeassistant.components.light.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure a MQTT light.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.mqtt/
"""
import logging
from functools import partial

import homeassistant.components.mqtt as mqtt
from homeassistant.components.light import (
    ATTR_BRIGHTNESS, ATTR_RGB_COLOR, Light)
from homeassistant.util.template import render_with_possible_json_value

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = 'MQTT Light'
DEFAULT_QOS = 0
DEFAULT_PAYLOAD_ON = 'ON'
DEFAULT_PAYLOAD_OFF = 'OFF'
DEFAULT_OPTIMISTIC = False

DEPENDENCIES = ['mqtt']

def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """ Add MQTT Light. """

    if config.get('command_topic') is None:
        _LOGGER.error("Missing required variable: command_topic")
        return False

    add_devices_callback([MqttLight(
        hass,
        config.get('name', DEFAULT_NAME),
        {key: config.get(key) for key in
         (typ + topic
          for typ in ('', 'brightness_', 'rgb_')
          for topic in ('state_topic', 'command_topic'))},
        {key: config.get(key + '_value_template')
         for key in ('state', 'brightness', 'rgb')},
        config.get('qos', DEFAULT_QOS),
        {
            'on': config.get('payload_on', DEFAULT_PAYLOAD_ON),
            'off': config.get('payload_off', DEFAULT_PAYLOAD_OFF)
        },
        config.get('optimistic', DEFAULT_OPTIMISTIC))])

class MqttLight(Light):
    """ Provides a MQTT light. """

    # pylint: disable=too-many-arguments,too-many-instance-attributes
    def __init__(self, hass, name, topic, templates, qos, payload, optimistic):

        self._hass = hass
        self._name = name
        self._topic = topic
        self._qos = qos
        self._payload = payload
        self._optimistic = optimistic or topic["state_topic"] is None
        self._optimistic_rgb = optimistic or topic["rgb_state_topic"] is None
        self._optimistic_brightness = (optimistic or
                                       topic["brightness_state_topic"] is None)
        self._state = False

        templates = {key: ((lambda value: value) if tpl is None else
                           partial(render_with_possible_json_value, hass, tpl))
                     for key, tpl in templates.items()}

        def state_received(topic, payload, qos):
            """ A new MQTT message has been received. """
            payload = templates['state'](payload)
            if payload == self._payload["on"]:
                self._state = True
            elif payload == self._payload["off"]:
                self._state = False

            self.update_ha_state()

        if self._topic["state_topic"] is not None:
            mqtt.subscribe(self._hass, self._topic["state_topic"],
                           state_received, self._qos)

        def brightness_received(topic, payload, qos):
            """ A new MQTT message for the brightness has been received. """
            self._brightness = int(templates['brightness'](payload))
            self.update_ha_state()

        if self._topic["brightness_state_topic"] is not None:
            mqtt.subscribe(self._hass, self._topic["brightness_state_topic"],
                           brightness_received, self._qos)
            self._brightness = 255
        else:
            self._brightness = None

        def rgb_received(topic, payload, qos):
            """ A new MQTT message has been received. """
            self._rgb = [int(val) for val in
                         templates['rgb'](payload).split(',')]
            self.update_ha_state()

        if self._topic["rgb_state_topic"] is not None:
            mqtt.subscribe(self._hass, self._topic["rgb_state_topic"],
                           rgb_received, self._qos)
            self._rgb = [255, 255, 255]
        else:
            self._rgb = None

    @property
    def brightness(self):
        """ Brightness of this light between 0..255. """
        return self._brightness

    @property
    def rgb_color(self):
        """ RGB color value. """
        return self._rgb

    @property
    def should_poll(self):
        """ No polling needed for a MQTT light. """
        return False

    @property
    def name(self):
        """ Returns the name of the device if any. """
        return self._name

    @property
    def is_on(self):
        """ True if device is on. """
        return self._state

    def turn_on(self, **kwargs):
        """ Turn the device on. """
        should_update = False

        if ATTR_RGB_COLOR in kwargs and \
           self._topic["rgb_command_topic"] is not None:
            mqtt.publish(self._hass, self._topic["rgb_command_topic"],
                         "{},{},{}".format(*kwargs[ATTR_RGB_COLOR]), self._qos)

            if self._optimistic_rgb:
                self._rgb = kwargs[ATTR_RGB_COLOR]
                should_update = True

        if ATTR_BRIGHTNESS in kwargs and \
           self._topic["brightness_command_topic"] is not None:

            mqtt.publish(self._hass, self._topic["brightness_command_topic"],
                         kwargs[ATTR_BRIGHTNESS], self._qos)

            if self._optimistic_brightness:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True

        mqtt.publish(self._hass, self._topic["command_topic"],
                     self._payload["on"], self._qos)

        if self._optimistic:
            # optimistically assume that switch has changed state
            self._state = True
            should_update = True

        if should_update:
            self.update_ha_state()

    def turn_off(self, **kwargs):
        """ Turn the device off. """
        mqtt.publish(self._hass, self._topic["command_topic"],
                     self._payload["off"], self._qos)

        if self._optimistic:
            # optimistically assume that switch has changed state
            self._state = False
            self.update_ha_state()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 5: 670 (1887)

#### Original name
Agaricus psichiophorus Berk. & Broome

### Remarks
null


text:
package ds.framework.v4.widget;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import java.util.HashMap;

import ds.framework.v4.app.DSFragment;

/**
 * Created by solyom on 27/01/16.
 */
abstract public class AbsSubFragmentPagerAdapter extends AbsTemplatePagerAdapter {

    /**
     * this is where we save the fragments instance states
     * need to call (@function onSaveInstanceState(), @Function onRestoreInstanceState())
     * from parent fragment if we need these after it saves / restore it's own
     */
    private HashMap<String, Bundle> mSavedFragmentInstanceStates = new HashMap<>();

    DSFragment mParentFragment;

    public AbsSubFragmentPagerAdapter(DSFragment parentFragment) {
        super(parentFragment.getDSActivity(), 0);

        mParentFragment = parentFragment;
    }

    @Override
    public View inflatePage(ViewGroup viewParent, int position) {
        FrameLayout container = new FrameLayout(mParentFragment.getContext());
        return container;
    }

    @Override
    public void fillItem(View item, int position) {
        FrameLayout container = (FrameLayout) item;

        DSFragment fragment = (DSFragment) getItem(position);

        // attach fragment - TODO: little bit messy with position as containerViewID
        String fragmentId = fragment.getFragmentId();
        mParentFragment.attachSubFragment(position, fragment, fragmentId);
        fragment.onCreateView(((Activity) mIn).getLayoutInflater(), container, mSavedFragmentInstanceStates.get(fragmentId));

        container.addView(fragment.getRootView());
    }

    @Override
    synchronized public void destroyItem(View container, int position, Object object) {
        super.destroyItem(container, position, object);

        mParentFragment.detachSubFragment(position);
    }

    public void onSaveInstanceState(Bundle outState) {
        // TODO:
    }

    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO:
    }
}


text:
package jp.caliconography;
import java.text.SimpleDateFormat;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.databind.ObjectMapper;

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JacksonConfigurator implements ContextResolver<ObjectMapper> {

    private ObjectMapper mapper = new ObjectMapper();

    public JacksonConfigurator() {
        mapper.setDateFormat(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"));
    }

    @Override
    public ObjectMapper getContext(Class<?> arg0) {
        return mapper;
    }
}


text:
<?php
namespace ProjectRena\Model\Database\CCP;

use ProjectRena\RenaApp;

/**
 * Class invTypes
 *
 * @package ProjectRena\Model\EVE
 */
class invGroups
{
    /**
     * @var RenaApp
     */
    private $app;
    /**
     * @var \ProjectRena\Lib\Db
     */
    private $db;

    /**
     * @param RenaApp $app
     */
    function __construct(RenaApp $app)
    {
        $this->app = $app;
        $this->db = $this->app->Db;
    }

    /**
     * @param $groupID
     *
     * @return array
     */
    public function getAllByID($groupID)
    {
        return $this->db->queryRow("SELECT * FROM invGroups WHERE groupID = :id", array(":id" => $groupID), 3600);
    }

    /**
     * @param $groupName
     *
     * @return array
     */
    public function getAllByName($groupName)
    {
        return $this->db->queryRow("SELECT * FROM invGroups WHERE groupName = :name", array(":name" => $groupName), 3600);
    }
}


text:
import { EventEmitter } from 'events';

// Player Games States
export const STATES = {
  LOBBY: 0,
  IDLE: 1,
  WAITING: 2,
  THINKING: 3,
  BET_DONE: 4,
  SMALL_BLIND: 5,
  BIG_BLIND: 6,
  FOLDED: 7
};

export default class Player extends EventEmitter {
  constructor(o) {
    super();
    this.id = o.id;
    this.nickname = o.nickname;
    this.balance = o.balance;
    this.socket = o.socket;
    this.table = o.table;
    this.state = STATES.LOBBY;
    this.ready = false;
    this.cards = [];

    this.socket.emit('game:connected', {
      nickname: this.nickname,
      balance: this.balance,
      id: this.id
    });
    this._initComms();
  }

  _initComms() {
    this.socket.on('disconnect', this._handleDisconnect.bind(this));
    this.socket.on('player:ready', this._handleReady.bind(this));
    this.socket.on('player:info-update', this._handleInfoUpdate.bind(this));

    // Game actions
    this.socket.on('player:check', this._handleCheck.bind(this));
    this.socket.on('player:call', this._handleCall.bind(this));
    this.socket.on('player:raise', this._handleRaise.bind(this));
    this.socket.on('player:fold', this._handleFold.bind(this));
  }

  _changeState(state) {
    this.state = state;
    switch (state) {
    case STATES.LOBBY:
      break;
    case STATES.WAITING:
      this.socket.emit('player:wait-to-bet');
      break;
    case STATES.THINKING:
      this.socket.emit('player:my-turn');
      break;
    case STATES.SMALL_BLIND:
      this.socket.emit('player:my-turn', { state: 'small-blind' });
      break;
    case STATES.BIG_BLIND:
      this.socket.emit('player:my-turn', { state: 'big-blind' });
      break;
    case STATES.BET_DONE:
      this.socket.emit('player:ack-bet');
      break;
    case STATES.FOLDED:
      this.socket.emit('player:ack-fold');
      break;
    case STATES.IDLE:
    default:
    }
  }
  _handleDisconnect() {
    this.emit('disconnection', {
      id: this.id
    });
  }
  _handleReady() {
    this.ready = true;
    this.emit('ready', {
      id: this.id
    });
    this.socket.emit('player:ack-ready');
  }
  _handleInfoUpdate(data) {
    this.nickname = data.nickname;
    this.emit('info-update', {
      id: this.id,
      cash: this.balance,
      nickname: this.nickname
    });
    this.emit('update', this.info);
  }
  _emitUpdate() {
    this.emit('update', {
      id: this.id,
      balance: this.balance,
      nickname: this.nickname,
      status: this.status
    });
  }

  handleGameStart() {
    this.socket.emit('game:start');
    this.cards = [];
  }

  setState(state) {
    this._changeState(state);
  }
  doSmallBlind() {
    let bet = this.table.minBet / 2;
    let info = this.info;
    this.balance -= bet;
    info.bet = bet;
    this.state = STATES.SMALL_BLIND;
    this.emit('update', info);
    return bet;
  }
  doBigBlind() {
    let bet = this.table.minBet;
    let info = this.info;
    this.balance -= bet;
    info.bet = bet;
    this.state = STATES.BIG_BLIND;
    this.emit('update', info);
    return bet;
  }

  takeCard(card) {
    this.cards.push(card);
    this.socket.emit('player:new-card', card);
  }

  _handleCheck() {
    this.emit('check', this);
    this._changeState(STATES.CHECK);
  }

  _handleCall() {
    this._changeState(STATES.BET_DONE);
    this.emit('call', this);
    this.balance -= this.table.minBet;
    let info = this.info;
    info.betType = 'call';
    this.emit('update', info);
  }
  _handleRaise(amount) {
    this._changeState(STATES.BET_DONE);
    this.emit('raise', {
      id: this.id,
      amount
    });
    this.balance -= amount;
    let info = this.info;
    info.betType = 'raise';
    info.bet = amount;
    this.emit('update', info);
  }
  _handleFold() {
    this._changeState(STATES.FOLDED);
    this.emit('fold', { id: this.id });
    this.emit('update', this.info);
  }
  get info() {
    return {
      id: this.id,
      nickname: this.nickname,
      cash: this.balance,
      state: this.state
    };
  }
}


text:
class HomeController < ApplicationController
  skip_before_action :authenticate_user!
  before_action :redirect_to_dashboard, if: :user_signed_in?

  def index
    @projects =
      Rails.cache.fetch("home-index", expires_in: 24.hours) do
        [
          Project.new(repo_name: "sinatra/sinatra", ci_type: :travis),
          Project.new(repo_name: "jollygoodcode/twemoji", ci_type: :travis),
          Project.new(repo_name: "winston/google_visualr", ci_type: :travis)
        ].map! { |project| ProjectDecorator.new(project) }.each(&:process_with)
      end
  end

  private

    def redirect_to_dashboard
      redirect_to projects_path
    end
end


text:
package ed.lang.ruby;

import java.util.Set;

import org.jruby.Ruby;
import org.jruby.RubyProc;
import org.jruby.internal.runtime.GlobalVariables;
import org.jruby.runtime.IAccessor;
import org.jruby.runtime.builtin.IRubyObject;

import ed.js.engine.Scope;
import static ed.lang.ruby.RubyObjectWrapper.toJS;
import static ed.lang.ruby.RubyObjectWrapper.toRuby;

/**
 * Delegates to existing global variables, adds scope to them, and keeps scope
 * and globals synchronized. Does not synchronize variables with "special"
 * names—those that do not start with a letter.
 */
public class ScopeGlobalVariables extends GlobalVariables {

    static final boolean DEBUG = Boolean.getBoolean("DEBUG.RB.GLOBALS");

    private Scope _scope;
    private Ruby _runtime;
    private GlobalVariables _delegate;

    public ScopeGlobalVariables(Scope scope, Ruby runtime) {
        super(runtime);
        _scope = scope;
        _runtime = runtime;

        _delegate = _runtime.getGlobalVariables();
        while (_delegate instanceof ScopeGlobalVariables)
            _delegate = ((ScopeGlobalVariables)_delegate)._delegate;
    }

    /**
     * Returns true if <var>jsKey</var> is "special"—has a
     * non-letter first character.
     */
    public boolean isSpecial(String jsKey) {
        return !Character.isLetter(jsKey.charAt(0));
    }

    public void define(String name, IAccessor accessor) { _delegate.define(name, accessor); }

    public void defineReadonly(String name, IAccessor accessor) { _delegate.defineReadonly(name, accessor); }

    public boolean isDefined(String name) { return _delegate.isDefined(name) || _scope.get(name.substring(1)) != null; }

    public void alias(String name, String oldName) { _delegate.alias(name, oldName); }

    public IRubyObject get(String name) {
        String key = globalNameToJSKey(name);
        if (isSpecial(key))     // no read from scope, no debug output
            return _delegate.get(name);

        if (DEBUG)
            System.err.println("ScopeGlobalVariables.get(" + name + ")");
        Object val = _scope.get(key);
        IRubyObject ro = val == null ? _delegate.get(name) : toRuby(_scope, _runtime, val, key);
        if (DEBUG) {
            System.err.println("  value in scope = " + val);
            if (val == null)
                System.err.println("  got delegate value " + ro);
        }
        return ro;
    }

    public IRubyObject set(String name, IRubyObject value) {
        IRubyObject val = _delegate.set(name, value);

        String key = globalNameToJSKey(name);
        if (isSpecial(key))
            return val;         // no save to scope, no debug output

        if (DEBUG)
            System.err.println("ScopeGlobalVariables.set(" + name + ")");
        _scope.put(key, toJS(_scope, val));
        return val;
    }

    public void setTraceVar(String name, RubyProc proc) { _delegate.setTraceVar(name, proc); }

    public boolean untraceVar(String name, IRubyObject command) { return _delegate.untraceVar(name, command); }

    public void untraceVar(String name) { _delegate.untraceVar(name); }

    public Set<String> getNames() { return _delegate.getNames(); }

    public IRubyObject getDefaultSeparator() {
        return _delegate.getDefaultSeparator();
    }

    public void setDefaultSeparator(IRubyObject defaultSeparator) {
        _delegate.setDefaultSeparator(defaultSeparator);
    }

    private String globalNameToJSKey(String name) {
        assert name != null;
        assert name.startsWith("$");
        return name.substring(1);
    }
}


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

<!--
Copyright 2020 Google LLC
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>com.google.cloud.broker</groupId>
        <artifactId>broker-parent</artifactId>
        <version>0.10.5</version>
        <relativePath>../../../../pom.xml</relativePath>
    </parent>

    <artifactId>encryption-backend-cloud-kms</artifactId>

    <name>Cloud KMS encryption backend for the GCP Token Broker</name>

    <dependencies>
        <dependency>
            <groupId>com.google.cloud.broker</groupId>
            <artifactId>broker-core</artifactId>
            <version>${project.parent.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.crypto.tink</groupId>
            <artifactId>tink</artifactId>
            <version>${com.google.crypto.tink.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-cloudkms</artifactId>
            <version>${google-api-services-cloudkms.version}</version>
        </dependency>
        <dependency>
            <groupId>org.conscrypt</groupId>
            <artifactId>conscrypt-openjdk-uber</artifactId>
            <version>${org.conscrypt.version}</version>
        </dependency>

        <!-- Testing dependencies -->
        <dependency>
            <groupId>com.google.cloud.broker</groupId>
            <artifactId>broker-core</artifactId>
            <version>${project.parent.version}</version>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>${maven-assembly-plugin.version}</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
var signer = require('jws');
var messages = [];
var Commands = require('../profile/commands');
var Events = require('../profile/events');

setInterval(function(){
	var message = messages.shift();
}, 3000);
module.exports = function(server){
	var io = require('socket.io')(server.server);
	var nicknames = {};
	var cookieParserFunction = server.cookieParser();
	var cookieSessionFunction = server.cookieSession({ keys: [server.config.cookie.key, ':blah:'], secret: server.config.cookie.secret});
	var Persistence = server.Persistence;

	io.use(function(socket, next){
		cookieParserFunction(socket.request, socket.request.res, function(){
			cookieSessionFunction(socket.request, socket.request.res, function(){
				var decodedSignature = signer.decode(socket.request.session.passport.user);
				if(!decodedSignature){
					return next(new Error("Unauthorized"));
				}
				Persistence.member.findOne({username: socket.request._query.username}, function(err, doc){
					if(doc){
						nicknames[doc.username] = doc;
						next();
					}else{
						next(401);
					}
				});
			});
		});
	});

	io.on('connection', function (socket) {
		socket.on('message', function (msg) {
			var message = {text: msg, time: (new Date()).getTime(), from: nicknames[socket.nickname]};
			socket.broadcast.emit('message', message);
			messages.push(message);
			server.client.send(new Commands.NewMessage(message));
		});
		socket.on('send previous messages', function(msg, ack){
			return ack([]);
		});
		socket.on('nickname', function (nick, fn) {
			socket.nickname = nick;
			if (nicknames[nick]) {
				socket.broadcast.emit('joined', nicknames[nick]);
				io.sockets.emit('nicknames', nicknames);
				return fn(true);
			}
			nicknames[nick] = {username: nick};
			socket.broadcast.emit('joined', nicknames[nick]);
			io.sockets.emit('nicknames', nicknames);
			return fn(true);

		});
		socket.on('left', function(nick){
			//console.log(nick, ' has left');
		});
		socket.on('disconnect', function () {
			if (!socket.nickname) return;
			delete nicknames[socket.nickname];
			socket.broadcast.emit('left', socket.nickname);
			socket.broadcast.emit('nicknames', nicknames);
		});
		socket.emit('connected', nicknames);
	});
	return io;
};


text:
package com.toolazydogs.maiden.model;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

/**
 *
 */
public class Region implements Map<String, Object>
{
    private final static String CLASS_NAME = Region.class.getName();
    private final static Logger LOGGER = Logger.getLogger(CLASS_NAME);
    private final Map<String, Object> map = new HashMap<String, Object>();
    private volatile Region parent;
    private volatile Line begin;
    private volatile Line end;

    public Region(Region parent, Line begin)
    {
        this.parent = parent;
        this.begin = begin;
    }

    public Region getParent()
    {
        return parent;
    }

    public void setParent(Region parent)
    {
        this.parent = parent;
    }

    public Line getBegin()
    {
        return begin;
    }

    public void setBegin(Line begin)
    {
        this.begin = begin;
    }

    public Line getEnd()
    {
        return end;
    }

    public void setEnd(Line end)
    {
        this.end = end;
    }

    public int size()
    {
        int size = (parent == null ? 0 : parent.size());
        return size + map.size();
    }

    public boolean isEmpty()
    {
        boolean isEmpty = (parent == null || parent.isEmpty());
        return isEmpty || map.isEmpty();
    }

    public boolean containsKey(Object key)
    {
        boolean containsKey = (parent == null || parent.containsKey(key));
        return containsKey || map.containsKey(key);
    }

    public boolean containsValue(Object value)
    {
        boolean containsValue = (parent == null || parent.containsValue(value));
        return containsValue || map.containsValue(value);
    }

    public Object get(Object key)
    {
        return null;  //Todo change body of implemented methods use File | Settings | File Templates.
    }

    public Object put(String key, Object value)
    {
        return map.put(key, value);
    }

    public Object remove(Object key)
    {
        return null;  //Todo change body of implemented methods use File | Settings | File Templates.
    }

    public void putAll(Map<? extends String, ? extends Object> m)
    {
        //Todo change body of implemented methods use File | Settings | File Templates.
    }

    public void clear()
    {
        //Todo change body of implemented methods use File | Settings | File Templates.
    }

    public Set<String> keySet()
    {
        return null;  //Todo change body of implemented methods use File | Settings | File Templates.
    }

    public Collection<Object> values()
    {
        return null;  //Todo change body of implemented methods use File | Settings | File Templates.
    }

    public Set<Entry<String, Object>> entrySet()
    {
        return null;  //Todo change body of implemented methods use File | Settings | File Templates.
    }
}


text:
webScienceRND
=============

Multimedia content based MVC type framework, developed using TDD coding methods (PHPunit, vfsStream, Qunit ect)


text:
package org.jasig.cas.support.oauth.ticket.accesstoken;

import org.jasig.cas.authentication.Authentication;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.ticket.ExpirationPolicy;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketFactory;
import org.jasig.cas.ticket.UniqueTicketIdGenerator;
import org.jasig.cas.util.DefaultUniqueTicketIdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;

/**
 * Default OAuth access token factory.
 *
 * @author Jerome Leleu
 * @since 5.0.0
 */
@Component("defaultAccessTokenFactory")
public class DefaultAccessTokenFactory implements AccessTokenFactory {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /** Default instance for the ticket id generator. */
    @NotNull
    @Autowired(required = false)
    @Qualifier("accessTokenIdGenerator")
    protected UniqueTicketIdGenerator accessTokenIdGenerator = new DefaultUniqueTicketIdGenerator();

    /** ExpirationPolicy for access tokens. */
    @NotNull
    @Autowired
    @Qualifier("accessTokenExpirationPolicy")
    protected ExpirationPolicy expirationPolicy;

    @Override
    public AccessToken create(final Service service, final Authentication authentication) {
        final String codeId = accessTokenIdGenerator.getNewTicketId(AccessToken.PREFIX);
        return new AccessTokenImpl(codeId, service, authentication, expirationPolicy);
    }

    @Override
    public <T extends TicketFactory> T get(final Class<? extends Ticket> clazz) {
        return (T) this;
    }

    public UniqueTicketIdGenerator getAccessTokenIdGenerator() {
        return accessTokenIdGenerator;
    }

    public void setAccessTokenIdGenerator(final UniqueTicketIdGenerator accessTokenIdGenerator) {
        this.accessTokenIdGenerator = accessTokenIdGenerator;
    }

    public ExpirationPolicy getExpirationPolicy() {
        return expirationPolicy;
    }

    public void setExpirationPolicy(final ExpirationPolicy expirationPolicy) {
        this.expirationPolicy = expirationPolicy;
    }
}