text:
import sys
import os
import random
import pygame
from pygame.locals import *
import constants
#import player
import bricks
import player
pygame.init()

#Start Class Declaration
class PyBreakout:

    def __init__(self):
        self.initialize()
        self.mainLoop()

    #Declare variables and initialization classes here
    def initialize(self):
        pygame.init()
        self.sound = pygame.mixer.Sound("adam.wav")
        self.death = pygame.mixer.Sound("death.wav")

        self.width = 924
        self.height = 768
        self.screen = pygame.display.set_mode((self.width, self.height))

        self.caption = "pyBreakout"
        pygame.display.set_caption(self.caption)

        self.framerate = 60
        #self.backgroundColour = (255,255,255)
        #self.foregroundColour = (0,99,207)

        self.clock = pygame.time.Clock()

        self.fontScore = pygame.font.SysFont("Arial Black", 21, bold=False)

        self.gameScore = 0
        self.gameBatsLeft = 3
        self.gameBricksLeft = 120

        #self.brick = bricks.Brick(self.screen)

        self.ticks = 0

        #initialize the bricks that will be displayed
        self.bricksArr = []
        # xPos = 44
        # yPos = 160
        # for i in range(12):
        #     brickObj = bricks.Brick(self.screen)
        #     brickObj.setPosX(xPos)
        #     brickObj.setPosY(yPos)
        #     self.bricksArr.append(brickObj)
        #     xPos += 70

        self.initBricks()
        self.special = random.randint(2, 119)

        self.bat = player.Bat(self.screen)

        self.projectile = player.Projectile(self.screen)

        self.projectileFired = False

    def initBricks(self):
        yPos = 160
        for x in range(10):
            xPos = 44
            for i in range(12):
                brickObj = bricks.Brick(self.screen)
                brickObj.setPosX(xPos)
                brickObj.setPosY(yPos)
                self.bricksArr.append(brickObj)
                xPos += 70
            yPos += 22

    def fireProjectile(self):
        self.projectileFired = True
        self.projectile.setPosition(self.bat.getPosX() + 42, self.bat.getPosY())

    def mainLoop(self):
        while True:
            gameTime = self.clock.get_time()
            self.update(gameTime)
            self.draw(gameTime)
            self.clock.tick(self.framerate)

    #Projectile Collision Handler
    def projectileCollision(self):

        #Draw bounding box for Projectile
        rectProjectile = pygame.Rect(self.projectile.getPosX(), self.projectile.getPosY(),5,5)

        #Draw bounding box for Bricks
        for i in range(120):
            rectBrick = pygame.Rect(self.bricksArr[i].getPosX(),self.bricksArr[i].getPosY(), 66, 18)
            if rectProjectile.colliderect(rectBrick):
                if i == self.special:
                    self.gameBatsLeft += 1
                    self.gameScore += 20
                    self.bricksArr[i].setPosX(1000)
                    self.sound.play()
                else:
                    self.bricksArr[i].setPosX(1000)
                    self.gameBricksLeft = self.gameBricksLeft - 1
                    self.gameScore += 10
                    self.projectile.reflect()
                    self.projectile.reflectGrad()
                    self.sound.play()

        #Draw bounding box for bat
        rectBat = []
        rectBat.append(pygame.Rect(self.bat.getPosX(), self.bat.getPosY(), 20, 15))
        rectBat.append(pygame.Rect(self.bat.getPosX()+20, self.bat.getPosY(), 20, 15))
        rectBat.append(pygame.Rect(self.bat.getPosX()+40, self.bat.getPosY(), 5, 15))
        rectBat.append(pygame.Rect(self.bat.getPosX()+45, self.bat.getPosY(), 20, 15))
        rectBat.append(pygame.Rect(self.bat.getPosX()+65, self.bat.getPosY(), 20, 15))

        for i in range(5):
            if rectProjectile.colliderect(rectBat[0]):
                self.projectile.setGrad(-1)
                self.projectile.reflect()
                self.sound.play()
            elif rectProjectile.colliderect(rectBat[1]):
                self.projectile.setGrad(-0.3)
                self.projectile.reflect()
                self.sound.play()
            elif rectProjectile.colliderect(rectBat[2]):
                self.projectile.setGrad(0.3)
                self.projectile.reflect()
                self.sound.play()
            elif rectProjectile.colliderect(rectBat[3]):
                self.projectile.setGrad(0.3)
                self.projectile.reflect()
                self.sound.play()
            elif rectProjectile.colliderect(rectBat[4]):
                self.projectile.setGrad(1)
                self.projectile.reflect()
                self.sound.play()

        #Draw bounding box for walls
        rectWalls = []
        rectWalls.append(pygame.Rect(20,50,20,650))
        rectWalls.append(pygame.Rect(20,50,884,20))
        rectWalls.append(pygame.Rect(884,50,20,650))
        for i in range(3):
            if rectProjectile.colliderect(rectWalls[i]):
                self.projectile.reflectGrad()
                self.sound.play()

        if rectProjectile.colliderect(rectWalls[1]):
            self.projectile.reflect()

        #Draw Bounding for entire level (lost projectile)
        rectOutofBounds = pygame.Rect(0,760,1000,10) # remember to do the thing
        if rectProjectile.colliderect(rectOutofBounds):
            self.projectileFired = False
            self.gameBatsLeft = self.gameBatsLeft - 1
            self.projectile.setGrad(0.2)
            self.projectile.reflect()
            self.death.play()

    def gameLost(self):
        game = MainMenu(self.gameScore, 2)

    def gameWon(self):
        game = MainMenu(self.gameScore, 1)

    def update(self, gameTime):

        if self.gameBatsLeft == -1:
            self.gameLost()
        if self.gameBricksLeft == 0:
            self.gameWon()

        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    game = MainMenu(0, 0)

        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_a] or pressed[pygame.K_LEFT]:
            if self.bat.getPosX() >= 44:
                self.bat.setPosX(self.bat.getPosX() - 15)
        if pressed[pygame.K_d] or pressed[pygame.K_RIGHT]:
            if self.bat.getPosX() <= 799:
                self.bat.setPosX(self.bat.getPosX() + 15)
        if pressed[pygame.K_SPACE] and (self.projectileFired == False):
            self.fireProjectile() #could use some work

        self.ticks = self.ticks + gameTime

        if (self.projectileFired == True):
            self.projectile.move()
            self.projectileCollision()

    def draw(self, gameTime):
        self.screen.fill(constants.backgroundColour)

        #Display The Scoring Text
        labelBricksLeft = self.fontScore.render("Bricks Left: %d" % self.gameBricksLeft, 1, constants.foregroundColour)
        labelBatsLeft = self.fontScore.render("Bats Left: %d" % self.gameBatsLeft, 1, constants.foregroundColour)
        labelScore = self.fontScore.render("Score: %d" % self.gameScore, 1, constants.foregroundColour)

        #write text to screen
        self.screen.blit(labelBricksLeft, (20,20))
        self.screen.blit(labelBatsLeft, (370,20))
        self.screen.blit(labelScore, (710,20))

        #Draw bounding boxes
        pygame.draw.rect(self.screen, constants.foregroundColour, [20,50,20,650])
        pygame.draw.rect(self.screen, constants.foregroundColour, [20,50,884,20])
        pygame.draw.rect(self.screen, constants.foregroundColour, [884,50,20,650])

        # Colour the blocks
        c = 0
        for x in range(120):
            self.bricksArr[x].draw(c)
            if (x == 23 or x == 47 or x == 71 or x == 95):
                c = c + 1

        self.bricksArr[self.special].draw(5)

        #Draw Player
        self.bat.draw()

        if (self.projectileFired == True):
            self.projectile.draw()

        #Projectile Debug

        pygame.display.flip()

class MainMenu:

    def __init__(self, score, state):
        pygame.init()
        self.score = score
        self.width = 924
        self.height = 768
        self.screen = pygame.display.set_mode((self.width, self.height))
        self.clock = pygame.time.Clock()
        self.framerate = 60
        self.fontWelcome = pygame.font.SysFont("Arial Black", 21, bold=False)
        self.fontBig = pygame.font.SysFont("Arial Black", 40, bold=False)
        self.logo = pygame.image.load(os.path.join('resources', 'logo.jpg'))
        self.state = state

        self.mainLoop()

    def mainLoop(self):
        while True:
            gameTime = self.clock.get_time()
            self.update(gameTime)
            self.draw(gameTime)
            self.clock.tick(self.framerate)

    def update(self, gameTime):
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                if event.key == pygame.K_SPACE:
                    game = PyBreakout()

    def draw(self, gameTime):
        self.screen.fill(constants.backgroundColour)

        labelWelcome = self.fontWelcome.render("Press <Space> To Start Game", 1, constants.foregroundColour)
        labelInstruction1 = self.fontWelcome.render("You have 3 Lives", 1, constants.foregroundColour)
        labelInstruction2 = self.fontWelcome.render("Each brick is 10 points", 1, constants.foregroundColour)
        labelInstruction3 = self.fontWelcome.render("The Black brick gives you 20 points and 1 extra life", 1, constants.foregroundColour)
        labelInstruction4 = self.fontWelcome.render("Use A & D or the arrow keys to move", 1, constants.foregroundColour)
        labelInstruction5 = self.fontWelcome.render("You can press <esc> at any time to return to this screen", 1, constants.foregroundColour)

        labelWin = self.fontBig.render("Congrats you beat the game!", 1, constants.foregroundColour)

        labelLoss = self.fontBig.render("Oh no you ran out of bats", 1, constants.foregroundColour)
        labelScore = self.fontWelcome.render("Final score: %d" % self.score, 1, constants.foregroundColour)
        labelPlayAgain= self.fontWelcome.render("Press <Space> To try again", 1, constants.foregroundColour)

        if self.state == 0:
            self.screen.blit(self.logo, (40,200))
            self.screen.blit(labelWelcome, (300, 400))
            self.screen.blit(labelInstruction1, (350, 440))
            self.screen.blit(labelInstruction2, (320, 460))
            self.screen.blit(labelInstruction3, (190, 480))
            self.screen.blit(labelInstruction4, (280, 500))
            self.screen.blit(labelInstruction5, (140, 520))
        elif self.state == 1:
            self.screen.blit(labelWin, (140,200))
        elif self.state == 2:
            self.screen.blit(labelLoss, (180,300))
            self.screen.blit(labelScore, (400,400))
            self.screen.blit(labelPlayAgain, (320,440))

        pygame.display.flip()

if __name__ == "__main__":
    game = MainMenu(0,0)


text:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

using Khronos;

// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer

namespace OpenGL
{
	public partial class Glx
	{
		/// <summary>
		/// [GLX] Value of GLX_SWAP_METHOD_OML symbol.
		/// </summary>
		[RequiredByFeature("GLX_OML_swap_method")]
		public const int SWAP_METHOD_OML = 0x8060;

		/// <summary>
		/// [GLX] Value of GLX_SWAP_EXCHANGE_OML symbol.
		/// </summary>
		[RequiredByFeature("GLX_OML_swap_method")]
		public const int SWAP_EXCHANGE_OML = 0x8061;

		/// <summary>
		/// [GLX] Value of GLX_SWAP_COPY_OML symbol.
		/// </summary>
		[RequiredByFeature("GLX_OML_swap_method")]
		public const int SWAP_COPY_OML = 0x8062;

		/// <summary>
		/// [GLX] Value of GLX_SWAP_UNDEFINED_OML symbol.
		/// </summary>
		[RequiredByFeature("GLX_OML_swap_method")]
		public const int SWAP_UNDEFINED_OML = 0x8063;

	}

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sis.internal.netcdf.ucar;

/**
 * Utility methods completing UCAR library for Apache SIS needs.
 * Some methods are workarounds for UCAR library methods having a different behavior than what we would expect.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @version 1.1
 * @since   1.0
 * @module
 */
final class Utils {
    /**
     * Strings used in UCAR netCDF API for meaning that an information is not available.
     * Some {@link ucar.nc2} methods return this value instead of {@code null}.
     *
     * @see #nonEmpty(String)
     */
    private static final String NOT_AVAILABLE = "N/A";

    /**
     * Do not allow instantiation of this class.
     */
    private Utils() {
    }

    /**
     * Trims the leading and trailing spaces of the given string and excludes empty or missing texts.
     * If the given string is null, empty, contains only spaces or is {@value #NOT_AVAILABLE} (ignoring case),
     * then this method returns {@code null}.
     */
    static String nonEmpty(String text) {
        if (text != null) {
            text = text.trim();
            if (text.isEmpty() || text.equalsIgnoreCase(NOT_AVAILABLE)) {
                return null;
            }
        }
        return text;
    }

    /**
     * If {@code isUnsigned} is {@code true} but the given value is negative, makes it positive.
     *
     * @param  number  the attribute value, or {@code null}.
     * @return whether the number is unsigned.
     */
    static Number fixSign(Number number, final boolean isUnsigned) {
        if (isUnsigned) {
            if (number instanceof Byte) {
                final byte value = (byte) number;
                if (value < 0) {
                    number = (short) Byte.toUnsignedInt(value);
                }
            } else if (number instanceof Short) {
                final short value = (Short) number;
                if (value < 0) {
                    number = Short.toUnsignedInt(value);
                }
            } else if (number instanceof Integer) {
                final int value = (Integer) number;
                if (value < 0) {
                    number = Integer.toUnsignedLong(value);
                }
            }
        }
        return number;
    }
}


text:
<?php

namespace PicoFeed\Filter;

use PHPUnit_Framework_TestCase;

class HtmlFilterTest extends PHPUnit_Framework_TestCase
{
    public function testEmpty()
    {
        $filter = new Html('', 'http://www.google.ca/');
        $this->assertEquals('', $filter->execute());
    }

    public function testExecute()
    {
        $html = '<!DOCTYPE html>
                <meta name="title" content="test">

boo
foo.
';

        $filter = new Html($html, 'http://www.google.ca/');

        $this->assertEquals('
boo
foo.
', $filter->execute());
    }

    public function testFilterRules()
    {
        $html = '
'.
                '
'.
                'I always throw up in hindsight if I find out something I ate was vegan. Twogag’s super free but if you want to support the comic look no further than the Twogag patreon!';

        $filter = new Html($html, 'http://www.twogag.com/');

        $expected = '
'.
                '
'.
                'I always throw up in hindsight if I find out something I ate was vegan. Twogag's super free but if you want to support the comic look no further than the Twogag patreon!';

        $this->assertEquals($expected, $filter->execute());
    }

    public function testIframe()
    {
        $data = '';

        $f = new Html($data, 'http://blabla');
        $this->assertEmpty($f->execute());

        $data = '';
        $expected = '';

        $f = new Html($data, 'http://blabla');
        $this->assertEquals($expected, $f->execute());
    }

    public function testClearScriptAttributes()
    {
        $data = '

something

hi
';

        $f = new Html($data, 'http://blabla');
        $expected = '
something

hi
';
        $this->assertEquals($expected, $f->execute());
    }

    public function testClearStyleAttributes()
    {
        $data = '

something

hi
';

        $f = new Html($data, 'http://blabla');
        $expected = '
something

hi
';
        $this->assertEquals($expected, $f->execute());
    }

    public function testEmptyTags()
    {
        $data = <<<EOD

EOD;
        $f = new Html($data, 'http://blabla');
        $output = $f->execute();

        $this->assertEquals('', $output);
    }

    public function testBadAttributes()
    {
        $data = '';

        $f = new Html($data, 'http://blabla');
        $this->assertEquals('', $f->execute());
    }

    public function testRelativeScheme()
    {
        $f = new Html('link', 'http://blabla');
        $this->assertEquals('link', $f->execute());
    }

    public function testAttributes()
    {
        $f = new Html('', 'http://blabla');
        $this->assertEquals('', $f->execute());

        $f = new Html('', 'http://blabla');
        $this->assertEquals('', $f->execute());

        $f = new Html("<time datetime='quote\"here'>bla</time>", 'http://blabla');
        $this->assertEquals('<time datetime="quote"here">bla</time>', $f->execute());
    }

    public function testCode()
    {
        $data = '
HEAD / HTTP/1.1
Accept: text/html
Accept-Encoding: gzip, deflate, compress
Host: www.amazon.com
User-Agent: HTTPie/0.6.0

HTTP/1.1 405 MethodNotAllowed
Content-Encoding: gzip
Content-Type: text/html; charset=ISO-8859-1
Date: Mon, 15 Jul 2013 02:05:59 GMT
Server: Server
Set-Cookie: skin=noskin; path=/; domain=.amazon.com; expires=Mon, 15-Jul-2013 02:05:59 GMT
Vary: Accept-Encoding,User-Agent
allow: POST, GET
x-amz-id-1: 11WD3K15FC268R5GBJY5
x-amz-id-2: DDjqfqz2ZJufzqRAcj1mh+9XvSogrPohKHwXlo8IlkzH67G6w4wnjn9HYgbs4uI0

';

        $f = new Html($data, 'http://blabla');
        $this->assertEquals($data, $f->execute());
    }

    public function testRemoveNoBreakingSpace()
    {
        $f = new Html('
  truc
', 'http://blabla');
        $this->assertEquals('
  truc
', $f->execute());
    }

    public function testRemoveEmptyTags()
    {
        $f = new Html('
toto

', 'http://blabla');
        $this->assertEquals('
toto

', $f->execute());

        $f = new Html('

', 'http://blabla');
        $this->assertEquals('', $f->execute());

        $f = new Html('

', 'http://blabla');
        $this->assertEquals('', $f->execute());
    }

    public function testRemoveEmptyTable()
    {
        $f = new Html('

', 'http://blabla');
        $this->assertEquals('', $f->execute());

        $f = new Html('

', 'http://blabla');
        $this->assertEquals('', $f->execute());
    }

    public function testRemoveMultipleTags()
    {
        $f = new Html('

toto

momo

', 'http://blabla');
        $this->assertEquals('

toto

momo

', $f->execute());
    }
}


text:
package org.http4s
package headers

import java.time.{ZoneId, ZonedDateTime}
import scala.concurrent.duration._

class RetryAfterSpec extends HeaderLaws {
  checkAll("Retry-After", headerLaws(`Retry-After`))

  val gmtDate: ZonedDateTime = ZonedDateTime.of(1999, 12, 31, 23, 59, 59, 0, ZoneId.of("GMT"))

  "render" should {
    "format GMT date according to RFC 1123" in {
      `Retry-After`(HttpDate.unsafeFromZonedDateTime(gmtDate)).renderString must_== "Retry-After: Fri, 31 Dec 1999 23:59:59 GMT"
    }
    "duration in seconds" in {
      `Retry-After`.unsafeFromDuration(120.seconds).renderString must_== "Retry-After: 120"
    }
  }

  "build" should {
    "build correctly for positives" in {
      `Retry-After`.fromLong(0).right.map(_.value) must beLike { case Right("0") => ok }
    }
    "fail for negatives" in {
      `Retry-After`.fromLong(-10).right.map(_.value) must beLeft
    }
    "build unsafe for positives" in {
      `Retry-After`.unsafeFromDuration(0.seconds).value must_== "0"
      `Retry-After`.unsafeFromLong(10).value must_== "10"
    }
    "fail unsafe for negatives" in {
      `Retry-After`.unsafeFromDuration(-10.seconds).value must throwA[ParseFailure]
      `Retry-After`.unsafeFromLong(-10).value must throwA[ParseFailure]
    }
  }

  "parse" should {
    "accept http date" in {
      `Retry-After`.parse("Fri, 31 Dec 1999 23:59:59 GMT").right.map(_.retry) must_== (Right(
        Left(HttpDate.unsafeFromZonedDateTime(gmtDate))))
    }
    "accept duration on seconds" in {
      `Retry-After`.parse("120").right.map(_.retry) must_== (Right(Right(120L)))
    }
  }
}


text:
namespace gamelib
{
    class InputSystem : public Subsystem<InputSystem>
    {
        public:
            ASSIGN_NAMETAG("InputSystem");

            enum ButtonState
            {
                Pressed,
                Released,
                Down,
                None
            };

            struct MouseData
            {
                math::Point2i desktop;
                math::Point2i win;
                math::Point2f world;
                int wheel;
                bool moved;
            };

        public:
            InputSystem();
            InputSystem(const sf::RenderWindow& win);

            auto setWindow(const sf::RenderWindow& win) -> void;

            auto beginFrame()                 -> void;
            auto process(const sf::Event& ev) -> void;

            auto markConsumed(bool keyboard, bool mouse) -> void;
            auto isKeyboardConsumed() const -> bool;
            auto isMouseConsumed() const    -> bool;

            auto isKeyPressed(sf::Keyboard::Key key) const  -> bool;
            auto isKeyReleased(sf::Keyboard::Key key) const -> bool;
            auto isKeyDown(sf::Keyboard::Key key) const     -> bool;

            auto isMousePressed(sf::Mouse::Button btn) const  -> bool;
            auto isMouseReleased(sf::Mouse::Button btn) const -> bool;
            auto isMouseDown(sf::Mouse::Button btn) const     -> bool;

            auto isKey(sf::Keyboard::Key key, ButtonState state) const   -> bool;
            auto isMouse(sf::Mouse::Button btn, ButtonState state) const -> bool;

            auto getKeyState(sf::Keyboard::Key key) const   -> ButtonState;
            auto getMouseState(sf::Mouse::Button btn) const -> ButtonState;

            auto getMouse() const -> const MouseData&;

        private:
            auto _check(bool keyboard, bool mouse) const -> bool;

        private:
            struct StateStruct
            {
                bool keyboard;
                ButtonState state;
                union {
                    sf::Mouse::Button btn;
                    sf::Keyboard::Key key;
                };
            };

        private:
            MouseData _mouse;
            const sf::RenderWindow* _window;
            bool _consumedKeyboard;
            bool _consumedMouse;
            std::vector<StateStruct> _states;
    };
}

#endif


text:
layout: post
title: The Plan
---

I'm going to use this little static site to keep note and blog post about things I find interesting.


text:
Donacje Krwii<input class='pull-right' type="text" ng-model="searchDonation"/>

Ilość: {{blooddonation.amount}}l {{blooddonation.donnor.blood_type}},
dnia: {{blooddonation.created | date:'mediumDate'}}

{{blooddonation.donnor.name}} {{blooddonation.donnor.surname}} {{blooddonation.donnor.pesel}}


text:
sentry-mailagain
================

sentry-mailagain is a Sentry plugin to resend the mail notification on
receiving new events in an unresolved group. The mail notification will be
handled in the same manner as would a regression.

Installation
------------

> pip install sentry-mailagain

Configuration
-------------

Configuration is per-project, and has one setting: You may configure how long
the plugin should wait before treating new events for a group as needing a new
notification.

License
-------

sentry-mailagain is licensed under the BSD license.

Resources
---------

Bug tracker:
  https://github.com/simonpercivall/sentry-mailagain/issues

Source:
  https://github.com/simonpercivall/sentry-mailagain/


text:
import os
import inspect

import setuptools
from setuptools import setup

__location__ = os.path.join(os.getcwd(), os.path.dirname(inspect.getfile(inspect.currentframe())))

def read_version(package):
    data = {}
    with open(os.path.join(package, '__init__.py'), 'r') as fd:
        exec (fd.read(), data)
    return data['__version__']

NAME = 'rgbxy'
MAIN_PACKAGE = 'rgbxy'
VERSION = read_version(MAIN_PACKAGE)
DESCRIPTION = 'RGB conversion tool written in Python for Philips Hue.'
LICENSE = 'MIT'
URL = 'https://github.com/benknight/hue-python-rgb-converter'
AUTHOR = 'Ben Knight'
EMAIL = 'ben@benknight.me'

# Add here all kinds of additional classifiers as defined under
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
CLASSIFIERS = [
    'Development Status :: 4 - Beta',
    'Intended Audience :: Developers',
    'Programming Language :: Python',
]

def setup_package():
    # Some helper variables
    version = VERSION

    install_reqs=[],

    setup(
        name=NAME,
        version=version,
        url=URL,
        description=DESCRIPTION,
        author=AUTHOR,
        author_email=EMAIL,
        license=LICENSE,
        keywords='philips hue light rgb xy',
        packages=setuptools.find_packages(),
        install_requires=install_reqs
    )

if __name__ == '__main__':
    setup_package()


text:
require 'rails_helper'

RSpec.describe "regiones/edit", :type => :view do
  before(:each) do
    @region = assign(:region, Region.create!(
      :nombre => "MyString",
      :estado => nil
    ))
  end

  it "renders the edit region form" do
    render

    assert_select "form[action=?][method=?]", region_path(@region), "post" do

      assert_select "input#region_nombre[name=?]", "region[nombre]"

      assert_select "select#region_estado_id[name=?]", "region[estado_id]"
    end
  end
end


text:
const utils = require('./utils');

class Cell {
  /**
   * A representation of a cell within the table.
   * Implementations must have `init` and `draw` methods,
   * as well as `colSpan`, `rowSpan`, `desiredHeight` and `desiredWidth` properties.
   * @param options
   * @constructor
   */
  constructor(options) {
    this.setOptions(options);

    /**
     * Each cell will have it's `x` and `y` values set by the `layout-manager` prior to
     * `init` being called;
     * @type {Number}
     */
    this.x = null;
    this.y = null;
  }

  setOptions(options) {
    if (['boolean', 'number', 'string'].indexOf(typeof options) !== -1) {
      options = { content: '' + options };
    }
    options = options || {};
    this.options = options;
    let content = options.content;
    if (['boolean', 'number', 'string'].indexOf(typeof content) !== -1) {
      this.content = String(content);
    } else if (!content) {
      this.content = '';
    } else {
      throw new Error('Content needs to be a primitive, got: ' + typeof content);
    }
    this.colSpan = options.colSpan || 1;
    this.rowSpan = options.rowSpan || 1;
  }

  mergeTableOptions(tableOptions, cells) {
    this.cells = cells;

    let optionsChars = this.options.chars || {};
    let tableChars = tableOptions.chars;
    let chars = (this.chars = {});
    CHAR_NAMES.forEach(function(name) {
      setOption(optionsChars, tableChars, name, chars);
    });

    this.truncate = this.options.truncate || tableOptions.truncate;

    let style = (this.options.style = this.options.style || {});
    let tableStyle = tableOptions.style;
    setOption(style, tableStyle, 'padding-left', this);
    setOption(style, tableStyle, 'padding-right', this);
    this.head = style.head || tableStyle.head;
    this.border = style.border || tableStyle.border;

    let fixedWidth = tableOptions.colWidths[this.x];
    if (tableOptions.wordWrap && fixedWidth) {
      fixedWidth -= this.paddingLeft + this.paddingRight;
      if (this.colSpan) {
        let i = 1;
        while (i < this.colSpan) {
          fixedWidth += tableOptions.colWidths[this.x + i];
          i++;
        }
      }
      this.lines = utils.colorizeLines(utils.wordWrap(fixedWidth, this.content));
    } else {
      this.lines = utils.colorizeLines(this.content.split('\n'));
    }

    this.desiredWidth = utils.strlen(this.content) + this.paddingLeft + this.paddingRight;
    this.desiredHeight = this.lines.length;
  }

  /**
   * Initializes the Cells data structure.
   *
   * @param tableOptions - A fully populated set of tableOptions.
   * In addition to the standard default values, tableOptions must have fully populated the
   * `colWidths` and `rowWidths` arrays. Those arrays must have lengths equal to the number
   * of columns or rows (respectively) in this table, and each array item must be a Number.
   *
   */
  init(tableOptions) {
    let x = this.x;
    let y = this.y;
    this.widths = tableOptions.colWidths.slice(x, x + this.colSpan);
    this.heights = tableOptions.rowHeights.slice(y, y + this.rowSpan);
    this.width = this.widths.reduce(sumPlusOne, -1);
    this.height = this.heights.reduce(sumPlusOne, -1);

    this.hAlign = this.options.hAlign || tableOptions.colAligns[x];
    this.vAlign = this.options.vAlign || tableOptions.rowAligns[y];

    this.drawRight = x + this.colSpan == tableOptions.colWidths.length;
  }

  /**
   * Draws the given line of the cell.
   * This default implementation defers to methods `drawTop`, `drawBottom`, `drawLine` and `drawEmpty`.
   * @param lineNum - can be `top`, `bottom` or a numerical line number.
   * @param spanningCell - will be a number if being called from a RowSpanCell, and will represent how
   * many rows below it's being called from. Otherwise it's undefined.
   * @returns {String} The representation of this line.
   */
  draw(lineNum, spanningCell) {
    if (lineNum == 'top') return this.drawTop(this.drawRight);
    if (lineNum == 'bottom') return this.drawBottom(this.drawRight);
    let padLen = Math.max(this.height - this.lines.length, 0);
    let padTop;
    switch (this.vAlign) {
      case 'center':
        padTop = Math.ceil(padLen / 2);
        break;
      case 'bottom':
        padTop = padLen;
        break;
      default:
        padTop = 0;
    }
    if (lineNum < padTop || lineNum >= padTop + this.lines.length) {
      return this.drawEmpty(this.drawRight, spanningCell);
    }
    let forceTruncation = this.lines.length > this.height && lineNum + 1 >= this.height;
    return this.drawLine(lineNum - padTop, this.drawRight, forceTruncation, spanningCell);
  }

  /**
   * Renders the top line of the cell.
   * @param drawRight - true if this method should render the right edge of the cell.
   * @returns {String}
   */
  drawTop(drawRight) {
    let content = [];
    if (this.cells) {
      //TODO: cells should always exist - some tests don't fill it in though
      this.widths.forEach(function(width, index) {
        content.push(this._topLeftChar(index));
        content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], width));
      }, this);
    } else {
      content.push(this._topLeftChar(0));
      content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], this.width));
    }
    if (drawRight) {
      content.push(this.chars[this.y == 0 ? 'topRight' : 'rightMid']);
    }
    return this.wrapWithStyleColors('border', content.join(''));
  }

  _topLeftChar(offset) {
    let x = this.x + offset;
    let leftChar;
    if (this.y == 0) {
      leftChar = x == 0 ? 'topLeft' : offset == 0 ? 'topMid' : 'top';
    } else {
      if (x == 0) {
        leftChar = 'leftMid';
      } else {
        leftChar = offset == 0 ? 'midMid' : 'bottomMid';
        if (this.cells) {
          //TODO: cells should always exist - some tests don't fill it in though
          let spanAbove = this.cells[this.y - 1][x] instanceof Cell.ColSpanCell;
          if (spanAbove) {
            leftChar = offset == 0 ? 'topMid' : 'mid';
          }
          if (offset == 0) {
            let i = 1;
            while (this.cells[this.y][x - i] instanceof Cell.ColSpanCell) {
              i++;
            }
            if (this.cells[this.y][x - i] instanceof Cell.RowSpanCell) {
              leftChar = 'leftMid';
            }
          }
        }
      }
    }
    return this.chars[leftChar];
  }

  wrapWithStyleColors(styleProperty, content) {
    if (this[styleProperty] && this[styleProperty].length) {
      try {
        let colors = require('colors/safe');
        for (let i = this[styleProperty].length - 1; i >= 0; i--) {
          colors = colors[this[styleProperty][i]];
        }
        return colors(content);
      } catch (e) {
        return content;
      }
    } else {
      return content;
    }
  }

  /**
   * Renders a line of text.
   * @param lineNum - Which line of text to render. This is not necessarily the line within the cell.
   * There may be top-padding above the first line of text.
   * @param drawRight - true if this method should render the right edge of the cell.
   * @param forceTruncationSymbol - `true` if the rendered text should end with the truncation symbol even
   * if the text fits. This is used when the cell is vertically truncated. If `false` the text should
   * only include the truncation symbol if the text will not fit horizontally within the cell width.
   * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined.
   * @returns {String}
   */
  drawLine(lineNum, drawRight, forceTruncationSymbol, spanningCell) {
    let left = this.chars[this.x == 0 ? 'left' : 'middle'];
    if (this.x && spanningCell && this.cells) {
      let cellLeft = this.cells[this.y + spanningCell][this.x - 1];
      while (cellLeft instanceof ColSpanCell) {
        cellLeft = this.cells[cellLeft.y][cellLeft.x - 1];
      }
      if (!(cellLeft instanceof RowSpanCell)) {
        left = this.chars['rightMid'];
      }
    }
    let leftPadding = utils.repeat(' ', this.paddingLeft);
    let right = drawRight ? this.chars['right'] : '';
    let rightPadding = utils.repeat(' ', this.paddingRight);
    let line = this.lines[lineNum];
    let len = this.width - (this.paddingLeft + this.paddingRight);
    if (forceTruncationSymbol) line += this.truncate || '…';
    let content = utils.truncate(line, len, this.truncate);
    content = utils.pad(content, len, ' ', this.hAlign);
    content = leftPadding + content + rightPadding;
    return this.stylizeLine(left, content, right);
  }

  stylizeLine(left, content, right) {
    left = this.wrapWithStyleColors('border', left);
    right = this.wrapWithStyleColors('border', right);
    if (this.y === 0) {
      content = this.wrapWithStyleColors('head', content);
    }
    return left + content + right;
  }

  /**
   * Renders the bottom line of the cell.
   * @param drawRight - true if this method should render the right edge of the cell.
   * @returns {String}
   */
  drawBottom(drawRight) {
    let left = this.chars[this.x == 0 ? 'bottomLeft' : 'bottomMid'];
    let content = utils.repeat(this.chars.bottom, this.width);
    let right = drawRight ? this.chars['bottomRight'] : '';
    return this.wrapWithStyleColors('border', left + content + right);
  }

  /**
   * Renders a blank line of text within the cell. Used for top and/or bottom padding.
   * @param drawRight - true if this method should render the right edge of the cell.
   * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined.
   * @returns {String}
   */
  drawEmpty(drawRight, spanningCell) {
    let left = this.chars[this.x == 0 ? 'left' : 'middle'];
    if (this.x && spanningCell && this.cells) {
      let cellLeft = this.cells[this.y + spanningCell][this.x - 1];
      while (cellLeft instanceof ColSpanCell) {
        cellLeft = this.cells[cellLeft.y][cellLeft.x - 1];
      }
      if (!(cellLeft instanceof RowSpanCell)) {
        left = this.chars['rightMid'];
      }
    }
    let right = drawRight ? this.chars['right'] : '';
    let content = utils.repeat(' ', this.width);
    return this.stylizeLine(left, content, right);
  }
}

class ColSpanCell {
  /**
   * A Cell that doesn't do anything. It just draws empty lines.
   * Used as a placeholder in column spanning.
   * @constructor
   */
  constructor() {}

  draw() {
    return '';
  }

  init() {}

  mergeTableOptions() {}
}

class RowSpanCell {
  /**
   * A placeholder Cell for a Cell that spans multiple rows.
   * It delegates rendering to the original cell, but adds the appropriate offset.
   * @param originalCell
   * @constructor
   */
  constructor(originalCell) {
    this.originalCell = originalCell;
  }

  init(tableOptions) {
    let y = this.y;
    let originalY = this.originalCell.y;
    this.cellOffset = y - originalY;
    this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset);
  }

  draw(lineNum) {
    if (lineNum == 'top') {
      return this.originalCell.draw(this.offset, this.cellOffset);
    }
    if (lineNum == 'bottom') {
      return this.originalCell.draw('bottom');
    }
    return this.originalCell.draw(this.offset + 1 + lineNum);
  }

  mergeTableOptions() {}
}

// HELPER FUNCTIONS
function setOption(objA, objB, nameB, targetObj) {
  let nameA = nameB.split('-');
  if (nameA.length > 1) {
    nameA[1] = nameA[1].charAt(0).toUpperCase() + nameA[1].substr(1);
    nameA = nameA.join('');
    targetObj[nameA] = objA[nameA] || objA[nameB] || objB[nameA] || objB[nameB];
  } else {
    targetObj[nameB] = objA[nameB] || objB[nameB];
  }
}

function findDimension(dimensionTable, startingIndex, span) {
  let ret = dimensionTable[startingIndex];
  for (let i = 1; i < span; i++) {
    ret += 1 + dimensionTable[startingIndex + i];
  }
  return ret;
}

function sumPlusOne(a, b) {
  return a + b + 1;
}

let CHAR_NAMES = [
  'top',
  'top-mid',
  'top-left',
  'top-right',
  'bottom',
  'bottom-mid',
  'bottom-left',
  'bottom-right',
  'left',
  'left-mid',
  'mid',
  'mid-mid',
  'right',
  'right-mid',
  'middle',
];
module.exports = Cell;
module.exports.ColSpanCell = ColSpanCell;
module.exports.RowSpanCell = RowSpanCell;


text:
require('my-absolute-test-lib1');
require('my-absolute-test-lib2');

// Rest of the file


text:
package com.github.sandor_balazs.sentiment_analysis.jaxb.corpus;

public class Constants {

    // The trainer and evaluator files are not distributed due to license compatibility.
    public static final String LAPTOP_TRAINER_FILE = "laptop/Laptops_Train.xml";
    public static final String LAPTOP_EVALUATOR_FILE = "laptop/laptops_trial_english_sl.xml";
    public static final String LAPTOP_EVALUATOR_FILE_NS = "laptop/laptops_trial_english_sl-with_namespace.xml";

    public static final String RESTAURANT_TRAINER_FILE = "restaurant/Restaurants_Train.xml";
    public static final String RESTAURANT_EVALUATOR_FILE = "restaurant/restaurants_trial_english_sl.xml";
}


text:
name: inverse
layout: true
class: center, middle, inverse
---
# 하하호호
[ri-mahrk]
.footnote[Go to directly to [project site](https://github.com/gnab/remark)]
---
## What is it and why should I be using it?
---
layout: false
.left-column[
## What is it?
]
.right-column[
A simple, in-browser, Markdown-driven slideshow tool targeted at people who know their way around HTML and CSS, featuring:

- Markdown formatting, with smart extensions

- Presenter mode, with cloned slideshow view

- Syntax highlighting, supporting a range of languages

- Slide scaling, thus similar appearance on all devices / resolutions .red[*]

- Touch support for smart phones and pads, i.e. swipe to navigate slides

.footnote[.red[*] At least browsers try their best]
]
---
.left-column[
## What is it?
## Why use it?
]
.right-column[
If your ideal slideshow creation workflow contains any of the following steps:

- Just write what's on your mind

- Do some basic styling

- Easily collaborate with others

- Share with and show to everyone

Then remark might be perfect for your next.red[*] slideshow!

.footnote[.red[*] You probably want to convert existing slideshows as well]
]
---
.left-column[
## What is it?
## Why use it?
]
.right-column[
As the slideshow is expressed using Markdown, you may:

- Focus on the content, expressing yourself in next to plain text not worrying what flashy graphics and disturbing effects to put where

As the slideshow is actually an HTML document, you may:

- Display it in any decent browser

- Style it using regular CSS, just like any other HTML content

- Use it offline!

As the slideshow is contained in a plain file, you may:

- Store it wherever you like; on your computer, hosted from your Dropbox, hosted on Github Pages alongside the stuff you're presenting...

- Easily collaborate with others, keeping track of changes using your favourite SCM tool, like Git or Mercurial
]
---
template: inverse

## How does it work, then?
---
name: how

.left-column[
## How does it work?
### - Markdown
]
.right-column[
A Markdown-formatted chunk of text is transformed into individual slides by JavaScript running in the browser:

```remark
# Slide 1
This is slide 1

---

# Slide 2
This is slide 2
```

.slides[
.first[
### Slide 1
This is slide 1
]
.second[
### Slide 2
This is slide 2
]
]

Regular Markdown rules apply with only a single exception:

- A line containing three dashes constitutes a new slide
(not a horizontal rule, `<hr />`)

Have a look at the [Markdown website](http://daringfireball.net/projects/markdown/) if you're not familiar with Markdown formatting.
]
---
.left-column[
## How does it work?
### - Markdown
### - Inside HTML
]
.right-column[
A simple HTML document is needed for hosting the styles, Markdown and the generated slides themselves:

```xml
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
/* Slideshow styles */
</style>
</head>
<body>
*    <textarea id="source">
<!-- Slideshow Markdown -->
</textarea>
*    <script type="text/javascript" src="remark.js">
</script>
<script type="text/javascript">
*      var slideshow = remark.create();
</script>
</body>
</html>
```

You may download remark to have your slideshow not depend on any online resources, or reference the [latest version](http://remarkjs.com/downloads/remark-latest.min.js) online directly.
]
---
template: inverse

## Of course, Markdown can only go so far.
---
.left-column[
## Markdown extensions
]
.right-column[
To help out with slide layout and formatting, a few Markdown extensions have been included:

- Slide properties, for naming, styling and templating slides

- Content classes, for styling specific content

- Syntax highlighting, supporting a range of languages
]

---
.left-column[
## Markdown extensions
### - Slide properties
]
.right-column[
Initial lines containing key-value pairs are extracted as slide properties:

```remark
name: agenda
class: middle, center

# Agenda

The name of this slide is {{ name }}.
```

Slide properties serve multiple purposes:

* Naming and styling slides using properties `name` and `class`

* Using slides as templates using properties `template` and `layout`

* Expansion of `{{ property }}` expressions to property values

See the [complete list](https://github.com/gnab/remark/wiki/Markdown#slide-properties) of slide properties.
]
---
.left-column[
## Markdown extensions
### - Slide properties
### - Content classes
]
.right-column[
Any occurences of one or more dotted CSS class names followed by square brackets are replaced with the contents of the brackets with the specified classes applied:

```remark
.footnote[.red.bold[*] Important footnote]
```

Resulting HTML extract:

```xml
<span class="footnote">
<span class="red bold">*</span> Important footnote
</span>
```
]
---
.left-column[
## Markdown extensions
### - Slide properties
### - Content classes
### - Syntax Highlighting
]
.right-column[
Code blocks can be syntax highlighted by specifying a language from the set of [supported languages](https://github.com/gnab/remark/wiki/Configuration#highlighting).

Using [GFM](http://github.github.com/github-flavored-markdown/) fenced code blocks you can easily specify highlighting language:

.pull-left[

```javascript
                                                                                function add(a, b)
                                                                                return a + b
                                                                                end
                                                                                ```

]
.pull-right[

```ruby
                                                                                def add(a, b)
                                                                                a + b
                                                                                end
                                                                                ```

]

A number of highlighting [styles](https://github.com/gnab/remark/wiki/Configuration#highlighting) are available, including several well-known themes from different editors and IDEs.

]
---
.left-column[
## Presenter mode
]
.right-column[
To help out with giving presentations, a presenter mode comprising the
following features is provided:

- Display of slide notes for the current slide, to help you remember
key points

- Display of upcoming slide, to let you know what's coming

- Cloning of slideshow for viewing on extended display
]
---
.left-column[
## Presenter mode
### - Inline notes
]
.right-column[
Just like three dashes separate slides,
three question marks separate slide content from slide notes:

```
Slide 1 content

*???

Slide 1 notes

---

Slide 2 content

*???

Slide 2 notes
```

Slide notes are also treated as Markdown, and will be converted in the
same manner slide content is.

Pressing __P__ will toggle presenter mode.
]
???
Congratulations, you just toggled presenter mode!

Now press __P__ to toggle it back off.
---
.left-column[
## Presenter mode
### - Inline notes
### - Cloned view
]
.right-column[
Presenter mode of course makes no sense to the audience.

Creating a cloned view of your slideshow lets you:

- Move the cloned view to the extended display visible to the audience

- Put the original slideshow in presenter mode

- Navigate as usual, and the cloned view will automatically keep up with the original

Pressing __C__ will open a cloned view of the current slideshow in a new
browser window.
]
---
template: inverse

## It's time to get started!
---
.left-column[
## Getting started
]
.right-column[
Getting up and running is done in only a few steps:

1. Visit the [project site](http://github.com/gnab/remark)

2. Follow the steps in the Getting Started section

For more information on using remark, please check out the [wiki](https://github.com/gnab/remark/wiki) pages.
]
---
name: last-page
template: inverse

## That's all folks (for now)!

Slideshow created using [remark](http://github.com/gnab/remark).


text:
package interfaces

import "strings"

// RelatableChannel
type RelatableChannel chan Relatable

// RelatableIterator provides a method to iterate over Relatables
type RelatableIterator interface {
	Next() (Relatable, error)
	Close() error
}

// Queryable allows querying by genomic position. Anything that meets this interface
// can be used in irelate.
type Queryable interface {
	Query(region IPosition) (RelatableIterator, error)
}

// IPosition allows accessing positional interface for genomic types.
type IPosition interface {
	Chrom() string
	Start() uint32
	End() uint32
}

// Interface to get the CIPos and CIEND from a VCF. Returns start, end, ok.
type CIFace interface {
	CIPos() (uint32, uint32, bool)
	CIEnd() (uint32, uint32, bool)
}

// Relatable provides all the methods for irelate to function.
// See Interval in parsers/interval.go for a class that satisfies this interface.
// Related() likely returns and AddRelated() likely appends to a slice of
// relatables. Note that for performance reasons, Relatable should be implemented
// as a pointer to your data-structure (see Interval).
type Relatable interface {
	IPosition
	Related() []Relatable // A slice of related Relatable's filled by IRelate
	AddRelated(Relatable) // Adds to the slice of relatables
	Source() uint32
	SetSource(source uint32)
}

// Info must implement stuff to get info out of a variant info field.
type Info interface {
	Get(key string) (interface{}, error)
	Set(key string, val interface{}) error
	Delete(key string)
	Keys() []string
	String() string
	Bytes() []byte
}

// IRefAlt will force matching on the Ref and Alt fields when they are present.
type IRefAlt interface {
	IPosition
	Ref() string
	Alt() []string
}

// IVariant must implement IPosition, Ref, Alt, and Info() methods for genetic variants
type IVariant interface {
	IRefAlt
	CIFace
	Info() Info
	Id() string
	String() string
}

type SIPosition interface {
	IPosition
	String() string
}

// trun an IPosition into an IRelatalbe
type RelWrap struct {
	related []Relatable
	source  uint32
}

func (w *RelWrap) Source() uint32 {
	return w.source
}
func (w *RelWrap) SetSource(s uint32) {
	w.source = s
}
func (w *RelWrap) AddRelated(r Relatable) {
	if w.related == nil {
		w.related = make([]Relatable, 0, 2)
	}
	w.related = append(w.related, r)
}

func (w *RelWrap) Related() []Relatable {
	return w.related
}

type VarWrap struct {
	IVariant
	*RelWrap
}

type PosWrap struct {
	SIPosition
	*RelWrap
}

type RAWrap struct {
	IRefAlt
	*RelWrap
}

// turn a position thingy into a Relatable
func AsRelatable(p SIPosition) Relatable {
	if v, ok := p.(IVariant); ok {
		return VarWrap{IVariant: v, RelWrap: &RelWrap{}}
	}
	if v, ok := p.(IRefAlt); ok {
		return &RAWrap{IRefAlt: v, RelWrap: &RelWrap{}}
	}
	return &PosWrap{SIPosition: p, RelWrap: &RelWrap{}}
}

type ip struct {
	chrom string
	start uint32
	end   uint32
}

func (p ip) Chrom() string {
	return p.chrom
}
func (p ip) Start() uint32 {
	return p.start
}
func (p ip) End() uint32 {
	return p.end
}

// AsIPosition take chrom, start, end and returns an struct that meets the IPosition interface
func AsIPosition(chrom string, start int, end int) IPosition {
	return ip{chrom, uint32(start), uint32(end)}
}

// SameChrom returns true if the strings are the same chromosome. Adjust for "chr" prefix.
func SameChrom(a, b string) bool {
	if a == b {
		return true
	}
	return StripChr(a) == StripChr(b)
}

// StripChr removes the "chr" prefix if it is present
func StripChr(c string) string {
	if strings.HasPrefix(c, "chr") {
		return c[3:]
	}
	return c
}

// SamePosition tests if 2 IPositions are the same
func SamePosition(a, b IPosition) bool {
	return a.Start() == b.Start() && a.End() == b.End() && SameChrom(a.Chrom(), b.Chrom())
}

// SamePosition tests if 2 IPositions overlap
func OverlapsPosition(a, b IPosition) bool {
	return (b.Start() < a.End() && b.End() > a.Start()) && SameChrom(a.Chrom(), b.Chrom())
}

// SameVariant tests if 2 IRefAlts share the same position and ref and alt.
func SameVariant(a, b IRefAlt) bool {
	if !SamePosition(a, b) || a.Ref() != b.Ref() {
		return false
	}
	for _, aalt := range a.Alt() {
		for _, balt := range b.Alt() {
			if aalt == balt {
				return true
			}
		}
	}
	if a.Alt()[0] == "<NON_REF>" || b.Alt()[0] == "<NON_REF>" {
		return true
	}
	return false
}

// Same tests the identity of 2 IPositions and attempts to cast to IRefAlts for more stringent
// checking.
func Same(a, b IPosition, strict bool) bool {
	// strict only applies if both are IVariants, otherwise, we just check for overlap.
	if !strict {
		return OverlapsPosition(a, b)
	}
	if av, ok := a.(IRefAlt); ok {
		if bv, ok := b.(IRefAlt); ok {
			if strict {
				return SameVariant(av, bv)
			}
		}
		return OverlapsPosition(a, b)
	}
	// at most one of them is a variant, just check overlap.
	return OverlapsPosition(a, b)
}


text:
//
//  PXEllipse.m
//  Pixate
//
//  Modified by Anton Matosov on 12/30/15.
//  Created by Kevin Lindsey on 6/6/12.
//  Copyright (c) 2012 Pixate, Inc. All rights reserved.
//

#import "PXEllipse.h"

@implementation PXEllipse

#pragma mark - Static Initializers

+ (instancetype)ellipseWithCenter:(CGPoint)aCenter withRadiusX:(CGFloat)aRadiusX withRadiusY:(CGFloat)aRadiusY
{
    return [[PXEllipse alloc] initCenter:aCenter radiusX:aRadiusX radiusY:aRadiusY];
}

#pragma mark - Initializers

- (instancetype)init
{
    return [self initCenter:CGPointZero radiusX:0.0f radiusY:0.0f];
}

- (instancetype)initCenter:(CGPoint)aCenter radiusX:(CGFloat)aRadiusX radiusY:(CGFloat)aRadiusY
{
    if (self = [super init])
    {
        self.center = aCenter;
        self.radiusX = aRadiusX;
        self.radiusY = aRadiusY;
    }

    return self;
}

#pragma mark - Getters

- (CGRect)bounds
{
    return CGRectMake(_center.x - _radiusX, _center.y - _radiusY, _center.x + _radiusX, _center.y + _radiusY);
}

#pragma mark - Setters

- (void)setBounds:(CGRect)bounds
{
    // TODO: check against current value to avoid unnecessary clearing of the path cache?
    _radiusX = bounds.size.width * 0.5f;
    _radiusY = bounds.size.height * 0.5f;
    _center.x = bounds.origin.x + _radiusX;
    _center.y = bounds.origin.y + _radiusY;
    [self clearPath];
}

- (void)setCenter:(CGPoint)aCenter
{
    if (!CGPointEqualToPoint(self->_center, aCenter))
    {
        self->_center = aCenter;
        [self clearPath];
    }
}

- (void)setRadiusX:(CGFloat)radius
{
    // Use positive absolute values only
    if (radius < 0)
    {
        radius = -radius;
    }

    if (self->_radiusX != radius)
    {
        self->_radiusX = radius;
        [self clearPath];
    }
}

- (void)setRadiusY:(CGFloat)radius
{
    // Use positive absolute values only
    if (radius < 0)
    {
        radius = -radius;
    }

    if (self->_radiusY != radius)
    {
        self->_radiusY = radius;
        [self clearPath];
    }
}

#pragma mark - Overrides

- (CGPathRef)newPath
{
    CGMutablePathRef path = CGPathCreateMutable();
    CGRect rect = CGRectMake(self.center.x - self.radiusX, self.center.y - self.radiusY, self.radiusX * 2.0, self.radiusY * 2.0);

    CGPathAddEllipseInRect(path, NULL, rect);

    CGPathRef resultPath = CGPathCreateCopy(path);
    CGPathRelease(path);

    return resultPath;
}

@end


text:
/**
    File Name:          date-004.js
    Corresponds To:     15.9.5.4-2-n.js
    ECMA Section:       15.9.5.4-1 Date.prototype.getTime
    Description:

    1.  If the this value is not an object whose [[Class]] property is "Date",
        generate a runtime error.
    2.  Return this time value.
    Author:             christine@netscape.com
    Date:               12 november 1997
*/
    var SECTION = "date-004";
    var VERSION = "JS1_4";
    var TITLE   = "Date.prototype.getTime";

    startTest();
    writeHeaderToLog( SECTION + " "+ TITLE);

    var tc = 0;
    var testcases = new Array();

    var result = "Failed";
    var exception = "No exception thrown";
    var expect = "Passed";

    try {
        var MYDATE = new MyDate();
        result = MYDATE.getTime();
    } catch ( e ) {
        result = expect;
        exception = e.toString();
    }

    testcases[tc++] = new TestCase(
        SECTION,
        "MYDATE = new MyDate(); MYDATE.getTime()" +
        " (threw " + exception +")",
        expect,
        result );

    test();

function MyDate( value ) {
    this.value = value;
    this.getTime = Date.prototype.getTime;
}


text:
Install MongoDb is easier than pee lying down. LOL

![pee lying](https://cldup.com/N1L5PkCDOq-3000x3000.jpeg)

Firstly go to download page [https://www.mongodb.org/downloads#production](https://www.mongodb.org/downloads#production) and choose your Operational System.
then you just need to unpack and run.

### Linux

![Meme do Linux](https://github.com/Webschool-io/be-mean-instagram/raw/master/apostila/mongodb/images/meme-linux.jpg)
Who uses Linux like ubuntu, can install by `apt-get` following these steps, first of all ,  ensure authenticity and consitency of the MongoDb packages

```
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
```

Then you should create a files list to MongoDB, in Ubuntu 12:

```
echo "deb http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
```

Ubuntu 14:

```
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
```

Ubuntu 15:

```
echo "deb http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list"
```

If you use RedHat or CentOS follow these steps: [http://docs.mongodb.org/manual/tutorial/install-mongodb-on-red-hat/](http://docs.mongodb.org/manual/tutorial/install-mongodb-on-red-hat/)

### Mac

![Meme do Mac](https://github.com/Webschool-io/be-mean-instagram/raw/master/apostila/mongodb/images/meme-mac.jpg)

Who uses Mac can install via [brew](http://brew.sh/) . To install **brew** is easy.
simply run this command in the terminal:

```
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```

### Windows

![Meme do Mac](https://github.com/Webschool-io/be-mean-instagram/raw/master/apostila/mongodb/images/meme-windows.jpg)

It is very simple on windows, one of my pupils wrote this article that can help you [https://pablojuancruz.wordpress.com/2014/09/03/configurando-ambiente-mongodb-no-windows/](https://pablojuancruz.wordpress.com/2014/09/03/configurando-ambiente-mongodb-no-windows/).

## MongoDB Server

If you didn't have installed it by `apt-get` or `brew` you'll have to execute it directly from where it was unpacked, so preferably unpack it in a folder named `mongodb` in the root, it can be `/` or `C:\`.

If you are using Windows, please use `PowerShell`. Go to **Execute** and type  `PowerShell`, it runs  **Linux** commands on Windows and is better than `Console`.

After entering the folder you'll have just to run the binary `mongod` which is our **server**:

```
./mongod
```

or on `PowerShell`:

```
.\mongod
```

If it display an error about `dbpath` it is  **very simple** to solve. simply create a folder on the root C:\, named `data` and inside of it , create the `db` folder. If you use Linux/Mac don't forget to give the right permissions, if you want to give all permissions just run the command below :

```
sudo chmod 777 -R /data
```

**ps: *please , never do it in production !***

Probably it will have no more problem.

## MongoDB Client

After using MongoDB we need run its client to interact with it by command line. to do it just run `mongo` command on your command line:

```
mongo
```

So it will connect to a *database* called `test`. To you execute the client directly in a specific *database* , just pass its name after the command:

```
mongo be-mean-instagram
```

in this case we have already entered the *database* `be-mean-instagram` that will be the used database in our *workshop*.

## Version

To you ensure the version 3 is installed just run the command below:

```
mongod --version
db version v3.0.6
```
 On client:

```
mongo --version
MongoDB shell version: 3.0.6
```

Now we are ready to start.


text:
require 'fog/core/model'

module Fog
  module Storage
    class HP

      class File < Fog::Model

        identity  :key,             :aliases => 'name'

        attribute :content_length,  :aliases => ['bytes', 'Content-Length'], :type => :integer
        attribute :content_type,    :aliases => ['content_type', 'Content-Type']
        attribute :etag,            :aliases => ['hash', 'Etag']
        attribute :last_modified,   :aliases => ['last_modified', 'Last-Modified'], :type => :time

        def body
          attributes[:body] ||= if last_modified
            collection.get(identity).body
          else
            ''
          end
        end

        def body=(new_body)
          attributes[:body] = new_body
        end

        def directory
          @directory
        end

        def copy(target_directory_key, target_file_key)
          requires :directory, :key
          target_directory = service.directories.new(:key => target_directory_key)
          service.put_object(target_directory_key, target_file_key, nil, {'X-Copy-From' => "/#{directory.key}/#{key}" })
          target_directory.files.get(target_file_key)
        end

        def destroy
          requires :directory, :key
          service.delete_object(directory.key, key)
          true
        end

        def owner=(new_owner)
          if new_owner
            attributes[:owner] = {
              :display_name => new_owner['DisplayName'],
              :id           => new_owner['ID']
            }
          end
        end

        #def public=(new_public)
        #  new_public
        #end

        def public_url
          requires :key
          self.collection.get_url(self.key)
        end

        def cdn_public_url
          requires :key
          self.collection.get_cdn_url(self.key)
        end

        def cdn_public_ssl_url
          requires :key
          self.collection.get_cdn_ssl_url(self.key)
        end

        def temp_signed_url(expires_secs, method)
          requires :directory, :key
          service.get_object_temp_url(directory.key, key, expires_secs, method)
        end

        def save(options = {})
          requires :body, :directory, :key
          options['Content-Type'] = content_type if content_type
          data = service.put_object(directory.key, key, body, options)
          merge_attributes(data.headers)
          self.content_length = Fog::Storage.get_body_size(body)
          true
        end

        private

        def directory=(new_directory)
          @directory = new_directory
        end

      end

    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace CJia.Health.Presenters.Web
{
    public class QueryPatientPresenter : CJia.Health.Tools.PresenterPage<Models.Web.QueryPatientModel, Views.Web.IQueryPatientView>
    {
        public QueryPatientPresenter(Views.Web.IQueryPatientView view)
            : base(view)
        {
            view.OnInit += view_OnInit;
            view.OnProviceChanged += view_OnProviceChanged;
            view.OnDeptChanged += view_OnDeptChanged;
            view.OnSelect += view_OnSelect;
        }

        void view_OnSelect(object sender, Views.Web.QueryPatientArgs e)
        {
            DataTable recordData = Model.QueryPatient(e.Patient);
            DataTable applyData = Model.GetApply(e.UserData.Rows[0]["USER_ID"].ToString());
            if (recordData != null && applyData == null)
            {
                DataColumn dc = new DataColumn("FLAG", typeof(String));
                DataColumn dc1 = new DataColumn("ENABLE", typeof(Boolean));
                recordData.Columns.Add(dc);
                recordData.Columns.Add(dc1);
                foreach (DataRow dr in recordData.Rows)
                {
                    dr["ENABLE"] = true;
                    dr["FLAG"] = "";
                }
                View.ExeBindSelectRecord(recordData);
            }
            else if (recordData != null && applyData != null)
            {
                View.ExeBindSelectRecord(isApply(recordData, applyData));
            }
            else
            {
                View.ExeBindSelectRecord(null);
            }
        }

        void view_OnDeptChanged(object sender, Views.Web.QueryPatientArgs e)
        {
            DataTable data = Model.QueryDoctor(e.DeptID);
            View.ExeBIndDoctor(data, e.i);
        }

        void view_OnProviceChanged(object sender, Views.Web.QueryPatientArgs e)
        {
            DataTable data = Model.QueryCity(e.ProviceID);
            View.ExeBindCity(data);
        }

        void view_OnInit(object sender, EventArgs e)
        {
            DataTable icdData = Model.QueryICDCode();
            DataTable zlData = Model.QueryTreatResult();
            DataTable dept = Model.QueryDept();
            DataTable provice = Model.QueryProvince();
            View.ExeBind(icdData, zlData, dept, provice);
        }

        #region 内部调用方法
        /// <summary>
        /// 数据整合
        /// </summary>
        /// <param name="recordData"></param>
        /// <param name="applyData"></param>
        /// <returns></returns>
        public DataTable isApply(DataTable recordData, DataTable applyData)
        {
            DataColumn dc = new DataColumn("FLAG", typeof(String));
            DataColumn dc1 = new DataColumn("ENABLE", typeof(Boolean));
            recordData.Columns.Add(dc);
            recordData.Columns.Add(dc1);
            foreach (DataRow dr in recordData.Rows)
            {
                bool isExit = false;
                string recordNO = dr["ID"].ToString();
                foreach (DataRow dr1 in applyData.Rows)
                {
                    string recordNO1 = dr1["HEALTH_ID"].ToString();
                    if (recordNO == recordNO1)
                    {
                        isExit = true;
                    }
                }
                if (isExit)
                {
                    dr["FLAG"] = "已申请";
                    dr["ENABLE"] = false;
                }
                else
                {
                    dr["FLAG"] = " ";
                    dr["ENABLE"] = true;
                }
            }
            return recordData;
        }
        #endregion
    }
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/dom/battery/nsIDOMNavigatorBattery.idl
 */

#ifndef __gen_nsIDOMNavigatorBattery_h__
#define __gen_nsIDOMNavigatorBattery_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIDOMBatteryManager; /* forward declaration */

/* starting interface:    nsIDOMNavigatorBattery */
#define NS_IDOMNAVIGATORBATTERY_IID_STR "a19eedd7-6c26-4676-bd34-7ca74ca5f565"

#define NS_IDOMNAVIGATORBATTERY_IID \
  {0xa19eedd7, 0x6c26, 0x4676, \
    { 0xbd, 0x34, 0x7c, 0xa7, 0x4c, 0xa5, 0xf5, 0x65 }}

class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMNavigatorBattery : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMNAVIGATORBATTERY_IID)

  /* readonly attribute nsIDOMBatteryManager mozBattery; */
  NS_SCRIPTABLE NS_IMETHOD GetMozBattery(nsIDOMBatteryManager * *aMozBattery) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMNavigatorBattery, NS_IDOMNAVIGATORBATTERY_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMNAVIGATORBATTERY \
  NS_SCRIPTABLE NS_IMETHOD GetMozBattery(nsIDOMBatteryManager * *aMozBattery);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMNAVIGATORBATTERY(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetMozBattery(nsIDOMBatteryManager * *aMozBattery) { return _to GetMozBattery(aMozBattery); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMNAVIGATORBATTERY(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetMozBattery(nsIDOMBatteryManager * *aMozBattery) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetMozBattery(aMozBattery); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsDOMNavigatorBattery : public nsIDOMNavigatorBattery
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIDOMNAVIGATORBATTERY

  nsDOMNavigatorBattery();

private:
  ~nsDOMNavigatorBattery();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMNavigatorBattery, nsIDOMNavigatorBattery)

nsDOMNavigatorBattery::nsDOMNavigatorBattery()
{
  /* member initializers and constructor code */
}

nsDOMNavigatorBattery::~nsDOMNavigatorBattery()
{
  /* destructor code */
}

/* readonly attribute nsIDOMBatteryManager mozBattery; */
NS_IMETHODIMP nsDOMNavigatorBattery::GetMozBattery(nsIDOMBatteryManager * *aMozBattery)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIDOMNavigatorBattery_h__ */


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Open SCAP Library: cpe_generator Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

Open SCAP Library

Main Page

Related Pages

Modules

Data Structures

Files

Data Structures

Data Structure Index

Data Fields

Public Member Functions |
Data Fields

cpe_generator Struct Reference
CPE Dictionary

Structure with information about document.
 More...

#include <cpe_dict.h>

Public Member Functions

void 	cpe_generator_free (struct cpe_generator *generator)

struct cpe_generator * 	cpe_generator_new (void)

Getters

Return value is pointer to structure's member.

Do not free unless you null the pointer in the structure. Use remove function otherwise.

const char * 	cpe_generator_get_product_name (const struct cpe_generator *item)

 	cpe_generator functions to get product name  More...

const char * 	cpe_generator_get_product_version (const struct cpe_generator *item)

 	cpe_generator functions to get product version  More...

const char * 	cpe_generator_get_schema_version (const struct cpe_generator *item)

 	cpe_generator functions to get document schema version  More...

const char * 	cpe_generator_get_timestamp (const struct cpe_generator *item)

 	cpe_generator functions to get timestamp from generator  More...

struct cpe_generator * 	cpe_dict_model_get_generator (const struct cpe_dict_model *item)

 	cpe_dict_model functions to get generator from CPE dictionary model  More...

Setters

For lists use add functions.

Parameters of set functions are duplicated in memory and need to be freed by caller.

bool 	cpe_generator_set_product_name (struct cpe_generator *generator, const char *new_product_name)

bool 	cpe_generator_set_product_version (struct cpe_generator *generator, const char *new_product_version)

bool 	cpe_generator_set_schema_version (struct cpe_generator *generator, const char *new_schema_version)

bool 	cpe_generator_set_timestamp (struct cpe_generator *generator, const char *new_timestamp)

Data Fields

char * 	product_name

char * 	product_version

char * 	schema_version

char * 	timestamp

Detailed Description

Structure with information about document.

The documentation for this struct was generated from the following files:

cpedict_priv.c

cpe_dict.h

<address class="footer">
Generated by

 1.8.6
</address>


text:
#ifndef RHYTHMGAME_AASSETDATASOURCE_H
#define RHYTHMGAME_AASSETDATASOURCE_H

#include <android/asset_manager.h>
#include <GameConstants.h>
#include "DataSource.h"

class AAssetDataSource : public DataSource {

public:
    int64_t getSize() const override { return mBufferSize; }
    AudioProperties getProperties() const override { return mProperties; }
    const float* getData() const override { return mBuffer.get(); }

    static AAssetDataSource* newFromCompressedAsset(
            AAssetManager &assetManager,
            const char *filename,
            AudioProperties targetProperties);

private:

    AAssetDataSource(std::unique_ptr<float[]> data, size_t size,
                     const AudioProperties properties)
            : mBuffer(std::move(data))
            , mBufferSize(size)
            , mProperties(properties) {
    }

    const std::unique_ptr<float[]> mBuffer;
    const int64_t mBufferSize;
    const AudioProperties mProperties;

};
#endif //RHYTHMGAME_AASSETDATASOURCE_H


text:
<?php

namespace Symfony\Component\CssSelector\Tests\Handler;

use Symfony\Component\CssSelector\Parser\Handler\CommentHandler;
use Symfony\Component\CssSelector\Parser\Reader;
use Symfony\Component\CssSelector\Parser\Token;
use Symfony\Component\CssSelector\Parser\TokenStream;

class CommentHandlerTest extends AbstractHandlerTest
{
    /** @dataProvider getHandleValueTestData */
    public function testHandleValue($value, Token $unusedArgument, $remainingContent)
    {
        $reader = new Reader($value);
        $stream = new TokenStream();

        $this->assertTrue($this->generateHandler()->handle($reader, $stream));
        // comments are ignored (not pushed as token in stream)
        $this->assertStreamEmpty($stream);
        $this->assertRemainingContent($reader, $remainingContent);
    }

    public function getHandleValueTestData()
    {
        return array(
            // 2nd argument only exists for inherited method compatibility
            array('/* comment */', new Token(null, null, null), ''),
            array('/* comment */foo', new Token(null, null, null), 'foo'),
        );
    }

    public function getDontHandleValueTestData()
    {
        return array(
            array('>'),
            array('+'),
            array(' '),
        );
    }

    protected function generateHandler()
    {
        return new CommentHandler();
    }
}


text:
package org.jenkinsci.plugins.rabbitmqconsumer.notifiers;

import org.jenkinsci.plugins.rabbitmqconsumer.events.RMQConnectionEvent;
import org.jenkinsci.plugins.rabbitmqconsumer.listeners.RMQConnectionListener;

/**
 * Notifier interface for {@link RMQConnectionListener}.
 *
 * @author rinrinne a.k.a. rin_ne
 */
public interface RMQConnectionNotifier {
    /**
     * Add {@link RMQConnectionListener}.
     *
     * @param rmqShutdownListener
     *            the listener.
     */
    void addRMQConnectionListener(RMQConnectionListener rmqShutdownListener);

    /**
     * Notify event for {@link RMQConnection}.
     *
     * @param event
     *            the event.
     */
    void notifyRMQConnectionListeners(RMQConnectionEvent event);

    /**
     * Removes {@link RMQConnectionListener}.
     *
     * @param rmqShutdownListener
     *            the listener.
     */
    void removeRMQConnectionListener(RMQConnectionListener rmqShutdownListener);

    /**
     * Gets whether actual RabbitMQ connection is opened.
     *
     * @return true if connection is already opened.
     */
    boolean isOpenRMQConnection();

}


text:
namespace DAVA
{
DAVA_VIRTUAL_REFLECTION_IMPL(UIFlowDataService)
{
    ReflectionRegistrator<UIFlowDataService>::Begin()
    .ConstructorByPointer()
    .DestructorByPointer([](UIFlowDataService* s) { delete s; })
    .Method("SetDataDirty", &UIFlowDataService::SetDataDirty)
    .End();
}

void UIFlowDataService::SetDataDirty(const Reflection& ref)
{
    UIDataBindingSystem* dbs = Engine::Instance()->GetContext()->uiControlSystem->GetSystem<UIDataBindingSystem>();
    if (dbs)
    {
        dbs->SetDataDirty(ref.GetValueObject().GetVoidPtr());
    }
}
}


text:
attr\_inject is an small and elegant dependency injection solution for Ruby.

#Installation
`gem install attr_inject`

# Usage
attr\_inject can be used many ways scaling from the least inrtusive to more inrusive options.

## Simple Example
Dependencies are injected via a Hash through the Object's constructor.

~~~ ruby
class Application

  # initialize our dependencies
  driver = Driver.new
  passenger = Passenger.new

  # inject our dependencies into our Car object
  car = Car.new :driver => driver, :passenger => passenger

end
~~~

~~~ ruby
class Car
  attr_inject :driver
  attr_inject :passenger

  def initialize(options)
    inject_attributes options
  end

end
~~~

## Injector Example
For more inversion of control, an Injector can be used.

~~~ ruby
class Application
  include Inject

  # Map our depedencies
  injector = Injector.new
  injector.map :driver, Driver.new
  injector.map :passenger, Passenger.new

  # Inject our dependencies into our car object
  car = Car.new
  injector.apply(car)

end
~~~

~~~ ruby
class Car
  attr_inject :driver
  attr_inject :passenger
end
~~~

## Factory Example
Create an Injector to map objects and factories to.

~~~ ruby
require "attr_inject"

class Application
  include Inject

  # Map our depedencies
  injector = Injector.new
  injector.map :driver, Driver.new
  injector.map :passenger, Passenger.new

  # Factory dependencies are called
  # on each inject and are passed it's
  # target object
  injector.factory :logger do |target|
    Logger.new(target)
  end

  # Inject our dependencies into our car object
  car = Car.new
  injector.apply(car)

end
~~~

Our car object explicitly defines what dependencies it wants.

~~~ ruby
class Car

  attr_inject :driver
  attr_inject :passenger
  attr_inject :logger

end
~~~


text:
Run database migrations fast and easy.

Given project is based on [github.com/mattes/migrate](https://github.com/mattes/migrate).

## How to use it
### Migration directory
Assuming that you have directory `./migrations` with migration files like:
```
001_initial_plan_to_do_sth.up.sql     # up migration instructions
001_initial_plan_to_do_sth.down.sql   # down migration instructions
002_xxx.up.sql
002_xxx.down.sql
...
```

You are ready to use this docker image.

### Run migrations
```bash
$DB_DSN="postgres://postgres:postgres@postgres:5432/srv?sslmode=disable"
docker run -v ./migrations:/migrations \
    widmogrod/migrate -url $DB_DSN up
```

> **NOTE:** More documented options you can find here: https://github.com/mattes/migrate#usage-from-terminal

### Available drives
  - PostgreSQL
  - Cassandra
  - SQLite
  - MySQL (experimental)


text:
/**
	@class

	Benchmark provides some simple methods for benchmarking the performance of your application.
*/
rio.Benchmark = new (rio.Attr.create({
	attrAccessors: [
		["installations", []],
		["started", false]
	],
	methods: {
		install: function(obj, methodName, objString) {
			if (!objString) { objString = obj.toString(); };

			if (!this.installationFor(obj, methodName)) {
				var installation = new rio.BenchmarkInstallation({ objectString: objString, object: obj, methodName: methodName });
				this.getInstallations().push(installation);

				installation.install();
			}
		},

		start: function() {
			this.setStarted(true);
			this.getInstallations().invoke("reset");
		},

		stop: function() {
			this.setStarted(false);
		},

		begin: function(waypointName) {
			var installation = this.installationFor(waypointName);
			if (!installation) {
				installation = new rio.BenchmarkWaypoint({ objectString: "[WAYPOINT]", methodName: waypointName });
				this.getInstallations().push(installation);
			}
			installation.begin();
		},

		end: function(waypointName) {
			var installation = this.installationFor(waypointName);
			if (installation) {
				installation.end();
			}
		},

		count: function(countName) {
			var installation = this.installationFor(countName);
			if (!installation) {
				installation = new rio.BenchmarkCount({ objectString: "[COUNT]", methodName: countName });
				this.getInstallations().push(installation);
			}
			installation.increment();
		},

		metrics: function(obj, methodName) {
			var installation = this.installationFor(obj, methodName);
			return { invocations: installation.getInvocations(), time: installation.getTime() };
		},

		installationFor: function(obj, methodName) {
			if (Object.isString(obj)) {
				return this.getInstallations().detect(function(i) {
					return (i.constructor == rio.BenchmarkWaypoint || i.constructor == rio.BenchmarkCount) && i.getMethodName() == obj;
				});
			} else {
				return this.getInstallations().detect(function(i) { return i.getObject() == obj && i.getMethodName() == methodName });
			}
		},

		clear: function() {
			this.getInstallations().clear();
		},

		toString: function() {
			return "Benchmark";
		}
	}
}))();

rio.BenchmarkInstallation = rio.Attr.create({
	attrAccessors: [
		"object",
		"objectString",
		"methodName",
		["installed", false],
		["enabled", true],
		["invocations", 0],
		["time", 0]
	],

	methods: {
		incrementInvocations: function() {
			this.setInvocations(this.getInvocations() + 1);
		},

		addTime: function(time) {
			this.setTime(this.getTime() + time);
		},

		reset: function() {
			this.setInvocations(0);
			this.setTime(0);
		},

		doesApply: function() {
			return rio.Benchmark.getStarted() && this.getEnabled();
		},

		install: function() {
			if (this.getInstalled()) { return; }
			this._oldMethod = this.getObject()[this.getMethodName()];
			this.getObject()[this.getMethodName()] = this.getObject()[this.getMethodName()].wrap(function() {
				var args = $A(arguments);
				var proceed = args.shift();

				if (this.doesApply()) {
					if (!this._inLoop) {
						this._inLoop = true;
						var t = new Date().getTime();
					}
				}
				var result = proceed.apply(this, args);

				if (this.doesApply()) {
					if (t) {
						this._inLoop = false;
						this.addTime(new Date().getTime() - t);
					}
					this.incrementInvocations();
				}

				return result;
			}.bind(this));
			this.setInstalled(true);
		},

		uninstall: function() {
			this.getObject()[this.getMethodName()] = this._oldMethod;
			this.setInstalled(false);

			var index = rio.Benchmark.getInstallations().indexOf(this);
			rio.Benchmark.getInstallations().splice(index, 1);
		},

		isRemovable: function() {
			return true;
		}
	}
});

rio.BenchmarkWaypoint = rio.Attr.create({
	attrAccessors: [
		"objectString",
		"methodName",
		["installed", true],
		["enabled", true],
		["invocations", 0],
		["time", 0]
	],

	methods: {
		addTime: function(time) {
			this.setTime(this.getTime() + time);
		},

		reset: function() {
			this.setInvocations(0);
			this.setTime(0);
		},

		doesApply: function() {
			return rio.Benchmark.getStarted() && this.getEnabled();
		},

		_nesting: 0,
		begin: function() {
			if (this.doesApply()) {
				if (this._nesting == 0) {
					this._beginTime = new Date().getTime();
				}
				this._nesting++;
				this.setInvocations(this.getInvocations() + 1);
			}
		},

		end: function() {
			if (this.doesApply()) {
				this._nesting--;
				if (this._nesting == 0) {
					this.addTime(new Date().getTime() - this._beginTime);
				}
			}
		},

		isRemovable: function() {
			return false;
		}
	}
});

rio.BenchmarkCount = rio.Attr.create({
	attrAccessors: [
		"objectString",
		"methodName",
		["installed", true],
		["enabled", true],
		["invocations", 0],
		["time", 0]
	],

	methods: {
		increment: function() {
			if (this.doesApply()) {
				this.setInvocations(this.getInvocations() + 1);
			}
		},

		doesApply: function() {
			return rio.Benchmark.getStarted() && this.getEnabled();
		},

		reset: function() {
			this.setInvocations(0);
		},

		isRemovable: function() {
			return false;
		}
	}
});


text:
#if NET
using System;
using System.Threading;
using System.Threading.Tasks;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;

#nullable enable

namespace Marten.Testing.Events.Aggregation
{
    #region sample_aggregate-stream-into-state-definition

    public record AccountingMonthOpened(
        Guid FinancialAccountId,
        int Month,
        int Year,
        decimal StartingBalance
    );

    public record InflowRecorded(
        Guid FinancialAccountId,
        decimal TransactionAmount
    );

    public record CashWithdrawnFromATM(
        Guid FinancialAccountId,
        decimal CashAmount
    );

    public record AccountingMonthClosed(
        Guid FinancialAccountId,
        int Month,
        int Year,
        decimal FinalBalance
    );

    public class FinancialAccount
    {
        public Guid Id { get; private set; }
        public int CurrentMonth { get; private set; }
        public int CurrentYear { get; private set; }
        public bool IsOpened { get; private set; }
        public decimal Balance { get; private set; }
        public int Version { get; private set; }

        public void Apply(AccountingMonthOpened @event)
        {
            Id = @event.FinancialAccountId;
            CurrentMonth = @event.Month;
            CurrentYear = @event.Year;
            Balance = @event.StartingBalance;
            IsOpened = true;
            Version++;
        }

        public void Apply(InflowRecorded @event)
        {
            Balance += @event.TransactionAmount;

            Version++;
        }

        public void Apply(CashWithdrawnFromATM @event)
        {
            Balance -= @event.CashAmount;
            Version++;
        }

        public void Apply(AccountingMonthClosed @event)
        {
            IsOpened = false;
            Version++;
        }
    }

    #endregion

    #region sample_aggregate-stream-into-state-wrapper

    public class CashRegisterRepository
    {
        private IDocumentSession session;

        public CashRegisterRepository(IDocumentSession session)
        {
            this.session = session;
        }

        public Task Store(
            FinancialAccount financialAccount,
            object @event,
            CancellationToken ct = default
        )
        {
            if (@event is AccountingMonthOpened)
            {
                session.Store(financialAccount);
            }

            session.Events.Append(financialAccount.Id, @event);

            return session.SaveChangesAsync(ct);
        }

        public async Task<FinancialAccount?> Get(
            Guid cashRegisterId,
            CancellationToken ct = default
        )
        {
            var cashRegister =
                await session.LoadAsync<FinancialAccount>(cashRegisterId, ct);

            var fromVersion = cashRegister != null
                ?
                // incrementing version to not apply the same event twice
                cashRegister.Version + 1
                : 0;

            return await session.Events.AggregateStreamAsync(
                cashRegisterId,
                state: cashRegister,
                fromVersion: fromVersion,
                token: ct
            );
        }
    }

    #endregion

    public class aggregate_stream_into_samples: IntegrationContext
    {
        public async Task SampleAggregateStreamIntoState()
        {
            var streamId = Guid.NewGuid();
            var baseState = new object();
            const int baseStateVersion = 1;

            #region sample_aggregate-stream-into-state-default
            await theSession.Events.AggregateStreamAsync(
                streamId,
                state: baseState,
                fromVersion: baseStateVersion
            );
            #endregion
        }

        [Fact]
        public async Task AggregatingStreamIntoShouldUseState()
        {
            var financialAccountId = Guid.NewGuid();

            await AppendEvent(
                financialAccountId,
                new AccountingMonthOpened(financialAccountId, 10, 2021, 0),
                new InflowRecorded(financialAccountId, 100),
                new InflowRecorded(financialAccountId, 100),
                new InflowRecorded(financialAccountId, 100),
                new AccountingMonthClosed(financialAccountId, 10, 2021, 300)
            );

            #region sample_aggregate-stream-into-state-store

            (FinancialAccount, AccountingMonthOpened) OpenAccountingMonth(
                FinancialAccount cashRegister)
            {
                var @event = new AccountingMonthOpened(
                    cashRegister.Id, 11, 2021, 300);

                cashRegister.Apply(@event);
                return (cashRegister, @event);
            }

            var closedCashierShift =
                await theSession.Events.AggregateStreamAsync<FinancialAccount>(
                    financialAccountId
                );

            var (openedCashierShift, cashierShiftOpened) =
                OpenAccountingMonth(closedCashierShift!);

            var repository = new CashRegisterRepository(_session);

            await repository.Store(openedCashierShift, cashierShiftOpened);

            #endregion

            var snapshot = await theSession.LoadAsync<FinancialAccount>(financialAccountId);

            snapshot.ShouldNotBeNull();
            snapshot.Id.ShouldBe(financialAccountId);
            snapshot.CurrentMonth.ShouldBe(11);
            snapshot.CurrentYear.ShouldBe(2021);
            snapshot.Balance.ShouldBe(300);
            snapshot.IsOpened.ShouldBeTrue();
            snapshot.Version.ShouldBe(openedCashierShift.Version);

            await AppendEvent(
                financialAccountId,
                new InflowRecorded(financialAccountId, 100),
                new InflowRecorded(financialAccountId, 100),
                new InflowRecorded(financialAccountId, 100)
            );

            #region sample_aggregate-stream-into-state-get

            var currentState = await repository.Get(financialAccountId);

            #endregion

            currentState.ShouldNotBeNull();
            currentState.Id.ShouldBe(financialAccountId);
            snapshot.CurrentMonth.ShouldBe(11);
            snapshot.CurrentYear.ShouldBe(2021);
            currentState.Balance.ShouldBe(600);
            currentState.IsOpened.ShouldBeTrue();
            currentState.Version.ShouldBe(openedCashierShift.Version + 3);
        }

        public aggregate_stream_into_samples(DefaultStoreFixture fixture): base(fixture)
        {
            StoreOptions(options =>
                options.UseDefaultSerialization(nonPublicMembersStorage: NonPublicMembersStorage.NonPublicSetters)
            );
        }
    }
}
#endif